@vcp-dev/site-edit-engine 0.10.52 → 0.10.54
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +8 -8
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import*as my from"@babel/parser";import*as He from"@babel/types";import*as tn from"node:path";var js=[".tsx",".ts",".jsx",".js"],gy=js.map(e=>`/index${e}`),hy=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 lu(e){let t=e.replace(/[?#].*$/,""),n=/\.([a-z0-9]+)$/i.exec(t);return n!==null&&hy.has(n[1].toLowerCase())}function uu(e){let t=[];for(let n of e.program.body)He.isImportDeclaration(n)&&typeof n.source.value=="string"&&Pt(n.source.value)&&t.push(n.source.value),He.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&Pt(n.source.value)&&t.push(n.source.value),He.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&Pt(n.source.value)&&t.push(n.source.value);return He.traverseFast(e.program,n=>{let r=He.isImportExpression(n)?n.source:He.isCallExpression(n)&&He.isImport(n.callee)?n.arguments[0]:null;He.isStringLiteral(r)&&Pt(r.value)&&t.push(r.value)}),t}function Pt(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function bn(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=tn.dirname(e);return tn.join(n,t).replace(/\\/g,"/")}async function yy(e,t){if(js.some(n=>e.endsWith(n))&&await t(e))return e;for(let n of js){let r=`${e}${n}`;if(await t(r))return r}for(let n of gy){let r=`${e}${n}`;if(await t(r))return r}return null}async function Sn(e,t,n){let r=await Oo(e,t,n);return r.ok?r.path:null}async function Oo(e,t,n){let r=bn(e,t);try{if(!xy(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 yy(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 xy(e,t,n){if(!Pt(t)||t.includes("\0")||t.includes("\\")||tn.posix.isAbsolute(n))return!1;let r=tn.posix.normalize(n);if(r===".."||r.startsWith("../"))return!1;if(t.startsWith("@/")){let o=t.slice(2);return o.length>0&&!o.split("/").some(i=>i==="..")}return!tn.posix.isAbsolute(e)}import{createHash as Sy}from"node:crypto";import*as du from"@babel/parser";function En(e,t,n,r){return{code:e,message:t,locatorKind:n,details:r}}function J(e,t,n,r,o){return{ok:!1,source:e,diagnostic:En(t,n,r,o)}}function $s(e,t,n,r,o){return{ok:!1,source:e,diagnostic:En(t,n,r,o)}}var by={"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:du.parse(t,{sourceType:"module",plugins:by[n]})}}catch(r){return{ok:!1,source:t,diagnostic:En("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function Vs(e,t){return At({source:e,profile:fu(t.kind)})}function Ir(e,t){return At({source:e,profile:fu(t)})}function fu(e){return"next-app-entry"}function vn(e){let{filePath:t,source:n}=e,r=t.toLowerCase().split(".").pop()??"";return r==="tsx"?"tsx-module":r==="ts"?"ts-module":r==="jsx"||r==="js"||r===""&&/<\w[\s\S]*>/.test(n)?"tsx-module":"next-app-entry"}var Jt=(e,t)=>{let n=At({source:t,profile:vn({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${Sy("sha256").update(t).digest("hex")}`,ast:n.ast,imports:uu(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};function Ey(e,t){return Jt(e,t)}function vy(e,t){return bn(e,t)}import{COMPONENT_I18N_FILE_SUFFIX as ky,parseComponentI18nResourcesJson as Iy,resolveSiteTextDirection as Cy,SiteLocaleSchema as Ry}from"@vcp-dev/contracts";var wy=["i18next","react-i18next"],Ny="components/ui/site-locale-provider.tsx",Py="components/ui/component-i18n-provider.tsx",pu="app/layout.tsx";async function Lo(e){let t=e.files.filter(m=>m.path.endsWith(ky));if(t.length===0)return{ok:!0};for(let m of["package.json",pu,Ny,Py])if(!await e.exists(m))return nn(`Target snapshot is missing required i18n host file: ${m}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return nn("Target snapshot package.json is invalid.")}let r=mu(n)&&mu(n.dependencies)?n.dependencies:{},o=wy.filter(m=>typeof r[m]!="string"||r[m].trim().length===0);if(o.length>0)return nn(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile(pu),s=Ks(i,"html","lang"),a=Ks(i,"html","dir"),c=Ks(i,"SiteLocaleProvider","locale"),l=Ry.safeParse(s);if(!l.success||!a||!c||s!==c||a!==Cy(l.data))return nn("Target snapshot app/layout.tsx must keep html lang/dir and SiteLocaleProvider locale consistent.");if(!i.includes('from "@/components/ui/site-locale-provider"')||!/<SiteLocaleProvider\b/.test(i)||!/<\/SiteLocaleProvider>/.test(i))return nn("Target snapshot root layout is not wired to SiteLocaleProvider.");let d=l.data;if(e.targetLocale&&e.targetLocale!==d)return nn("Target snapshot locale does not match the authoritative site language.");let f=d.split("-")[0];for(let m of t){let u=Iy(m.content);if(!u.success)return nn(`Component i18n resource is invalid: ${m.path}.`);if(!e.deferTargetLocale&&!Object.hasOwn(u.data,d)&&!Object.hasOwn(u.data,f))return nn(`Component i18n resource ${m.path} has no locale for ${d} or ${f}.`)}return{ok:!0}}function Ks(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 mu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nn(e){return{ok:!1,message:e}}import Js from"@babel/generator";import*as Su from"@babel/parser";import Xs from"@babel/traverse";import*as Re from"@babel/types";import{computeSiteEditSourceIdentityKey as Ty}from"@vcp-dev/contracts";var gu="data-vcp-ui-component",Do="components/ui";function Xt(e){if(!e)return!1;let t=Us(e);return t===Do||t.startsWith(`${Do}/`)||t.includes(`/${Do}/`)||t.endsWith(`/${Do}`)}function kn(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?Xt(e.slice(2)):e.startsWith("./")||e.startsWith("../")?Xt(Us(`${Ay(t)}/${e}`)):Xt(e):!1}function Us(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 Ay(e){let t=Us(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}import{stripSiteEditRepeatInstanceKeys as sP}from"@vcp-dev/contracts";import{isSiteEditRuntimeContainerTag as cP,isSiteEditRuntimeTextTag as lP}from"@vcp-dev/contracts/site-edit-runtime-capability";var hu={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 Fy=typeof Js=="function"?Js:Js.default,_y=typeof Xs=="function"?Xs:Xs.default,My=new Set(["base","body","head","html","link","meta","noscript","script","style","template","title"]),Oy="suppressHydrationWarning",Ly=new Set(["SiteEditBootstrap"]);function Dy(e){let t=$y(e.file,e.projectRoot);if(!jy(e.source)||Xt(t))return{code:e.source,elements:[]};let n=e.attributes??hu,r=Su.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]}),o=[],i=Ky(r,t);return _y(r,{JSXElement(s){let a=s.node.openingElement,c=a.name;if(!Jy(c)||Eu(a,n.key))return;let l=zy(s)??"default",d=Hy(s),f=Ty(t,l,d),m=jo(c)??"unknown",u=Vy(c)?"jsx":"component-call";if(u==="component-call"&&!Wy(s.node.children)&&Ly.has(m))return;let g=u==="component-call"&&Uy(m,i);Xy(a,n.key,f),g&&yu(a,gu),By(s)&&yu(a,Oy),o.push({key:f,tag:m,componentName:l,sourceFile:t,sourceKind:u})}}),o.length===0?{code:e.source,elements:o}:{code:Fy(r,{jsescOption:{minimal:!0}}).code,elements:o}}function By(e){return!e.findParent(t=>t.isJSXElement())}function jy(e){return/(?:^|[=(:,?;\[{>&|\n\r]|return\s+)\s*<(?:[A-Za-z][\w.:-]*|>)(?:\s|>|\/)/m.test(e)}function $y(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 Vy(e){return Re.isJSXIdentifier(e)&&/^[a-z]/.test(e.name)}function jo(e){return Re.isJSXIdentifier(e)?e.name:Re.isJSXMemberExpression(e)?ku(e):null}function Ky(e,t){let n=new Set;for(let r of e.program.body)if(!(!Re.isImportDeclaration(r)||!kn(r.source.value,t)))for(let o of r.specifiers)n.add(o.local.name);return n}function Uy(e,t){let n=e.split(".")[0]??e;return t.has(n)}function Jy(e){let t=jo(e);return!t||t==="Fragment"||t.endsWith(".Fragment")?!1:!My.has(t)}function Eu(e,t){return e.attributes.some(n=>Re.isJSXAttribute(n)&&Re.isJSXIdentifier(n.name,{name:t}))}function Xy(e,t,n){vu(e,Re.jsxAttribute(Re.jsxIdentifier(t),Re.stringLiteral(n)))}function yu(e,t){Eu(e,t)||vu(e,Re.jsxAttribute(Re.jsxIdentifier(t),null))}function vu(e,t){let n=e.attributes.findIndex(r=>Re.isJSXSpreadAttribute(r));if(n>=0){e.attributes.splice(n,0,t);return}e.attributes.push(t)}function ku(e){return`${Re.isJSXIdentifier(e.object)?e.object.name:ku(e.object)}.${e.property.name}`}function zy(e){let t=e;for(;t;){if(t.isFunctionDeclaration()||t.isClassDeclaration())return t.node.id?.name??null;if(t.isVariableDeclarator()&&Re.isIdentifier(t.node.id)){let n=t.get("init");if(!Array.isArray(n)&&(n.isArrowFunctionExpression()||n.isFunctionExpression()))return t.node.id.name}t=t.parentPath}return null}function Wy(e){return e.some(t=>Re.isJSXElement(t)||Re.isJSXFragment(t))}var xu=new WeakMap,Bo=new WeakMap,zs=new WeakMap;function Hy(e){let t=xu.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=Gy(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return xu.set(e.node,o),o}function Gy(e){let t=jo(e.node.openingElement.name);return!t||t==="Fragment"||t.endsWith(".Fragment")?null:/^[A-Z]/.test(t)?`component:${t}#${bu(e,t)}`:`${t}#${bu(e,t)}`}function bu(e,t){let n=Iu(e)??e.getFunctionParent();if(!n)return 0;let r=zs.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=zs.get(n.node);o||(o=new Map,zs.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0,a=n.isJSXElement()||n.isJSXFragment()?$o(n):Yy(n);for(let c of a)if(jo(c.node.openingElement.name)===t){if(i.set(c.node,s),c.node===e.node)return s;s+=1}return i.get(e.node)??0}function Yy(e){let t=Bo.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!Iu(r)&&n.push(r)}}),Bo.set(e.node,n),n}function Iu(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement())return t;t=t.parentPath}return n}function $o(e){let t=Bo.get(e.node);if(t)return t;let n=[],r=e.get("children");for(let o of r)if(!Array.isArray(o)){if(o.isJSXElement()){n.push(o);continue}if(o.isJSXFragment()){n.push(...$o(o));continue}o.isJSXExpressionContainer()&&n.push(...In(o.get("expression")))}return Bo.set(e.node,n),n}function In(e){if(e.isJSXElement())return[e];if(e.isJSXFragment())return $o(e);if(e.isParenthesizedExpression())return In(e.get("expression"));if(e.isLogicalExpression()&&e.node.operator==="&&")return In(e.get("right"));if(e.isConditionalExpression())return[...In(e.get("consequent")),...In(e.get("alternate"))];if(e.isCallExpression()&&Qy(e.node)){let t=e.get("arguments")[0];return Zy(t)}return[]}function Zy(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return[t];if(t.isJSXFragment())return $o(t);if(t.isParenthesizedExpression())return In(t.get("expression"));if(!t.isBlockStatement())return[];for(let n of t.get("body")){if(!n.isReturnStatement())continue;let r=n.get("argument");return r.node?In(r):[]}return[]}function Qy(e){return Re.isMemberExpression(e.callee)&&Re.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.fileChanges?{fileChanges:e.fileChanges}:{},...e.output?{output:e.output}:{},...e.selectionRef?{selectionRef:e.selectionRef}:{}}}function Vo(e,t){let n=t[0]??"Site edit operation request failed contract validation.";return{ok:!1,composition:{routeId:e.composition.routeId,...e.composition.templateId!==void 0?{effectiveTemplateId:e.composition.templateId}:{}},error:{code:"INVALID_PARAMS",message:n},data:{requestId:e.id,kind:e.kind,composition:{routeId:e.composition.routeId,...e.composition.templateId!==void 0?{effectiveTemplateId:e.composition.templateId}:{}},target:e.target,resultVersion:e.documentVersion}}}function Ko(e,t){if(!e.pageComposition)throw new Error("RenderDocument is missing the required Page Composition projection.");return{siteId:t.siteId,snapshotId:t.snapshotId,composition:e.composition,version:e.version,entries:e.entries.map(n=>({key:n.key,parentKey:n.parentKey,...n.pageCompositionUnitKey?{pageCompositionUnitKey:n.pageCompositionUnitKey}:{},...n.pageCompositionActionScope?{pageCompositionActionScope:n.pageCompositionActionScope}:{},operationSummary:{canUpdateText:n.operationSummary.canUpdateText,canInsertChild:n.operationSummary.canInsertChild,canMove:n.operationSummary.canMove,canRemove:n.operationSummary.canRemove},...n.dynamicDataSummary?{dynamicDataSummary:n.dynamicDataSummary}:{}})),pageComposition:e.pageComposition.status==="unsupported"?{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics}:{status:"supported",containerKey:e.pageComposition.container.key,hasBusinessMembers:e.pageComposition.businessMembers.length>0,placementUnitKeys:e.pageComposition.placementUnits.map(n=>n.key),placements:e.pageComposition.placements.map(n=>({placementKey:n.placementKey,placementUnitKey:n.placementUnitKey,relation:n.relation}))}}}function Uo(e){return{composition:e.composition,key:e.key,tag:e.tag,...e.linkSourceKind?{linkSourceKind:e.linkSourceKind}:{},label:e.label,sourceLocator:e.sourceLocator,isOpaque:e.isOpaque,ancestors:e.ancestors,componentName:e.componentName,sourceFile:e.sourceFile,capabilities:qy(e.capabilities),provenanceChain:e.provenanceChain?{editMode:e.provenanceChain.editMode,diagnostics:e.provenanceChain.diagnostics}:void 0,dynamicData:e.dynamicData,...e.properties?{properties:e.properties}:{},textSegments:e.textSegments.map(t=>({index:t.index,editable:t.editable,sourceKind:t.source?.kind??null})),boundaryKind:e.boundaryKind}}function Jo(e,t){let n=new Date().toISOString();return e.type==="document-changed"?{type:"site-edit.document.changed",siteId:t.siteId,snapshotId:t.snapshotId,composition:e.composition,version:e.version,at:n}:e.type==="operation-completed"?{type:"site-edit.operation.completed",siteId:t.siteId,composition:e.composition,result:Cn(e.result),at:n}:e.type==="operation-failed"?{type:"site-edit.operation.failed",siteId:t.siteId,requestId:e.requestId,composition:e.composition,error:e.error,at:n}:e.type==="capability-changed"?{type:"site-edit.capability.changed",siteId:t.siteId,composition:e.composition,keys:e.keys,at:n}:e.type==="graph-invalidated"?{type:"site-edit.graph.invalidated",siteId:t.siteId,composition:e.composition,at:n}:e.type==="graph-ready"?{type:"site-edit.graph.ready",siteId:t.siteId,composition:e.composition,version:e.version,at:n}:e.type==="graph-error"?{type:"site-edit.graph.error",siteId:t.siteId,composition:e.composition,message:e.message,at:n}:null}function qy(e){return{composition:e.composition,key:e.key,canUpdateText:e.canUpdateText,canInsertChild:e.canInsertChild,canMove:e.canMove,canRemove:e.canRemove,editModes:e.editModes?{updateText:e.editModes.updateText?{mode:e.editModes.updateText.mode,reasonCode:e.editModes.updateText.reasonCode}:void 0,insertChild:e.editModes.insertChild?{mode:e.editModes.insertChild.mode,reasonCode:e.editModes.insertChild.reasonCode}:void 0,move:e.editModes.move?{mode:e.editModes.move.mode,reasonCode:e.editModes.move.reasonCode}:void 0,remove:e.editModes.remove?{mode:e.editModes.remove.mode,reasonCode:e.editModes.remove.reasonCode}:void 0}:void 0,constraints:e.constraints}}import{checkGlobalsCssEdit as zw,computeSiteEditCompositionKey as Ww,getSiteEditSourceDeleteProtectionReason as Hw,isSiteEditTextSourcePath as Gw,parseSiteEditRepeatInstanceKey as Yw,SITE_EDIT_SOURCE_DELETE_CAPABILITY as Zw,stripSiteEditRepeatInstanceKeys as ot}from"@vcp-dev/contracts";import Cs from"node:path";import{parse as Qw}from"yaml";import Zs from"node:path";import{TextDecoder as tx}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as Ru,SITE_EDIT_SOURCE_ALLOWED_DIRS as wu,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as Nu,SiteEditCompositionContextSchema as nx,SiteEditSourceFileResponseSchema as Ws,SiteEditSourceLocationSchema as rx,SiteEditSourcePathSchema as Xo,SiteEditSourceTreeResponseSchema as ox,isSiteEditTextSourcePath as ix}from"@vcp-dev/contracts";import{createHash as ex}from"node:crypto";var Cr=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 Ie(e){return`sha256:${ex("sha256").update(e).digest("hex")}`}var sx=[...Nu,...Ru,...wu];function Qs(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return nx.parse(e.composition)}var Hs=2e3,Gs=12,Ys=24*1024*1024,Cu=512*1024,ax=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),cx={".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"},lx={".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"},ux=new tx("utf-8",{fatal:!0});async function zo(e,t={}){let n=Qs(t),{files:r,truncated:o}=await yx(e,t),i=Sx(r.map(s=>s.metadata));return ox.parse({composition:n,nodes:i,defaultPath:Ex(r.map(s=>s.metadata)),totalFiles:r.length,...o?{truncated:o}:{}})}async function Wo(e,t,n={}){let r=Qs(n),o=Xo.parse(t.path),i=await fx(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(ea(o)){let a=Tu(o),c=await mx(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return Ws.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...c})}let s=await qs(e,o);return s.ok?Ws.parse({composition:r,path:o,kind:"text",language:Fu(o),sizeBytes:s.sizeBytes,contentHash:Ie(s.content),readonly:!1,content:s.content}):Ws.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function qs(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=dx(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 dx(e){if(e.includes(0))return null;try{return ux.decode(e)}catch{return null}}async function fx(e,t,n){if(!gx(t,n))return null;let r=await px(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function px(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=Pu(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(ea(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function mx(e,t){if(!ax.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>Cu)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>Cu?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function gx(e,t){return Nu.some(n=>n===e)||Ru.some(n=>n===e)||wu.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=Xo.safeParse(n);return r.success&&r.data===e})}function Ho(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return rx.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 Pu(e){return Array.isArray(e)?{files:e}:e}function hx(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function yx(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=Pu(await e.listFiles({roots:xx(t),maxFiles:Hs+1,maxDepth:Gs,maxTotalBytes:Ys+1})),r=new Map,o=new Set(n.truncated?.reasons),i=0;for(let a of[...n.files].sort((c,l)=>c.path.localeCompare(l.path))){let c=Xo.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>Gs){o.add("max-depth");continue}if(r.size>=Hs){o.add("max-files");break}if(i+a.sizeBytes>Ys){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:bx(l,a.sizeBytes,Qs(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:hx([...o]),maxFiles:Hs,maxDepth:Gs,maxTotalBytes:Ys}}:{}}}function xx(e){let t=new Set(sx);for(let n of e.routeEntryFiles??[]){let r=Xo.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function bx(e,t,n){return ea(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:Tu(e),readonly:!0}:{composition:n,path:e,kind:"text",language:Fu(e),sizeBytes:t,readonly:!1}}function Sx(e){let t=[];for(let n of e){let r=n.path.split("/"),o=t,i="";for(let[s,a]of r.entries()){i=i?`${i}/${a}`:a;let c=s===r.length-1,l=o.find(d=>d.name===a);if(l||(l=c?{kind:"file",name:a,path:i,file:n}:{kind:"directory",name:a,path:i,children:[]},o.push(l)),c){if(l.kind!=="file")throw new Error(`Source tree path collision: ${n.path}`);l.file=n}else{if(l.kind!=="directory")throw new Error(`Source tree path collision: ${n.path}`);o=l.children}}}return Au(t)}function Au(e){return e.map(t=>t.kind==="directory"?{...t,children:Au(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function Ex(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 ea(e){return!ix(e)}function Tu(e){let t=Zs.posix.extname(e).toLowerCase();return!t&&Zs.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":cx[t]??"application/octet-stream"}function Fu(e){let t=Zs.posix.extname(e).toLowerCase();return lx[t]??"plaintext"}import ta from"@babel/traverse";import*as Tt from"@babel/types";function _e(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")&&_u(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())&&_u(r.parentPath)}function _u(e){return e?.isImportDeclaration()===!0&&e.node.source.value==="react"}var rn=typeof ta=="function"?ta:ta.default,Go=new WeakMap,Yo=new WeakMap;function Ft(e,t){let n=Vs(e,t);if(!n.ok)return $s(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=ce(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}}:$s(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function ce(e,t){return t.kind==="jsx-node"?Du(e,t):t.kind==="jsx-attribute"?wx(e,t):t.kind==="value"?Nx(e,t):t.kind==="expression"?Px(e,t):t.kind==="directive"?Ax(e,t):t.kind==="export"?Tx(e,t):{ok:!1,diagnostic:En("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function Du(e,t){return t.strategy==="source-range"?vx(e,t):kx(e,t)}function vx(e,t){let n=null;if(rn(e,{JSXElement(o){if(!Rn(o.node,t.sourceRange))return;let i=De("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!Rn(o.node,t.sourceRange))return;let i=De("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!Rn(o.node,t.sourceRange))return;let i=De("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXText(o){if(!Rn(o.node,t.sourceRange))return;let i=De("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)}}),!n)return Be("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!Ux(r.path,t.expectedIdentity)?Be("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function kx(e,t){if(t.structuralPath===""){let r=Cx(e,t.component);if(r){let o=Rx(r);if(o)return o}}let n=null;return rn(e,{JSXElement(r){if(wr(r)!==t.component||ra(r)!==t.structuralPath)return;let i=De("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(wr(r)!==t.component||ra(r)!==t.structuralPath)return;let i=De("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=Ix(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:Be("jsx-node","locator-miss","JSX node not found for structural-path locator")}function Ix(e,t,n){let r=null;return rn(e,{JSXElement(o){if(wr(o)!==t||!Rn(o.node,n))return;let i=De("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(wr(o)!==t||!Rn(o.node,n))return;let i=De("jsx-node",o);i&&(r=i,o.stop())}}),r}function Cx(e,t){let n=null;return rn(e,{FunctionDeclaration(r){r.node.id?.name===t&&(n=r,r.stop())},VariableDeclarator(r){if(r.node.id.type==="Identifier"&&r.node.id.name===t){let o=r.get("init");(o.isArrowFunctionExpression()||o.isFunctionExpression())&&(n=o),r.stop()}}}),n}function Rx(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 wx(e,t){let n=Du(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>Jx(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 Nx(e,t){let n=Fx(e,t);if(!n.ok)return n;let r=_x(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!Wt(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 Px(e,t){let n=null;return rn(e,{Identifier(r){if(!jx(r))return;let o=Ou(r);if(!o||!Lu(o,t))return;let i=De("expression",r);i&&(t.expectedRange&&!Wt(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=Ou(r);if(!o||!Lu(o,t))return;let i=De("expression",r);i&&(t.expectedRange&&!Wt(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Be("expression","locator-miss","Expression not found")}function Ax(e,t){let n=null;return rn(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!Wt(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 Tx(e,t){let n=null;return rn(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let c=r.get("declaration");if(c.isFunctionDeclaration()&&c.node.id?.name==="generateMetadata"){let m=De("export",c);if(!m||t.expectedRange&&!Wt(c.node.loc,t.expectedRange))return;n=m,r.stop();return}if(!c.isVariableDeclaration())return;let l=oa(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&&!Wt(d.node.loc,t.expectedRange))return;n=f,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=oa(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!Wt(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&&!Wt(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Be("export","export-not-found",`Export '${Kx(t)}' not found`)}function Fx(e,t){let n=null;return rn(e,{Expression(r){if(n||t.root.kind!=="expression"||!Rn(r.node,t.root.sourceRange))return;let o=De("value",r);o&&(n=o,r.stop())},VariableDeclarator(r){if(n)return;if(t.root.kind==="binding"){if(r.node.id.type!=="Identifier"||r.node.id.name!==t.root.name)return;let 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=oa(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 _x(e,t){let n=na(e);for(let o of t){if(n=na(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=>Xx(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=na(n);let r=De("value",n);return r?{ok:!0,match:r}:Be("value","locator-miss","Resolved value has no source range")}function na(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 Wt(e.loc,t)}function Wt(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 ra(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!_e(n)){let o=ju(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${Mu(n,o)}`):t.unshift(`${o}#${Mu(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||Dx(n.parentPath)&&!Bx(n.parentPath))break;n=n.parentPath}return t.join("/")}function Mu(e,t){let n=Bu(e)??e.getFunctionParent();if(!n)return 0;let r=Go.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=Go.get(n.node)?.get(t);if(!i){let a=Go.get(n.node);a||(a=new Map,Go.set(n.node,a)),i=new WeakMap,a.set(t,i)}let s=n.isJSXElement()||n.isJSXFragment()?Rr(n):Mx(n);for(let a of s)if(ju(a.node.openingElement)===t){if(i.set(a.node,o),a.node===e.node)return o;o++}return i.get(e.node)??0}function Mx(e){let t=Yo.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!Bu(r)&&n.push(r)}}),Yo.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()){if(_e(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Rr(e){let t=Yo.get(e.node);if(t)return t;let n=[],r=e.get("children");for(let o of r)if(!Array.isArray(o)){if(o.isJSXElement()){if(_e(o)){n.push(...Rr(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Rr(o));continue}o.isJSXExpressionContainer()&&n.push(...zt(o.get("expression")))}return Yo.set(e.node,n),n}function zt(e){if(e.isJSXElement())return _e(e)?Rr(e):[e];if(e.isJSXFragment())return Rr(e);if(e.isParenthesizedExpression())return zt(e.get("expression"));if(e.isLogicalExpression()&&Ox(e.node.operator))return zt(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(...zt(c))}if(s.isReturnStatement()){let a=s.get("argument");a.isExpression()&&i.push(...zt(a));break}}return i}else if(o.node&&o.isExpression())return zt(o)}}}}return e.isConditionalExpression()?[...zt(e.get("consequent")),...zt(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:zt(t)):[]}function Ox(e){return e==="&&"||e==="||"||e==="??"}function ju(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?Lx(e.name):null}function Lx(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 wr(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 Dx(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function Bx(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 jx(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function Ou(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 Lu(e,t){return e.base===t.base&&$x(e.path,t.path??[])}function $x(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 Vx(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function Kx(e){return e.exportKind==="named"?e.name:e.exportKind}function Be(e,t,n,r){return{ok:!1,diagnostic:En(t,n,e,r)}}function Ux(e,t){return wr(e)!==t.component?!1:ra(e)===t.structuralPath}function Jx(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function oa(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function Xx(e,t){return e.isObjectProperty()?Vx(e.node)===t:!1}import*as Vu from"@babel/parser";import{arrayExpression as Yx,booleanLiteral as Zx,identifier as Qx,jsxAttribute as qx,jsxExpressionContainer as eb,jsxIdentifier as tb,nullLiteral as nb,numericLiteral as rb,objectExpression as ob,objectProperty as ib,stringLiteral as sa}from"@babel/types";import ia from"@babel/generator";var zx=typeof ia=="function"?ia:ia.default;function Wx(e){let t=e.split(`
|
|
2
|
-
`),n=[],r=!1;for(let s of t){let a=s.match(/^(\s+)/);if(a){let c=a[1];c.includes(" ")?r=!0:c.length>0&&n.push(c.length)}}if(r&&t.every(a=>{let c=a.match(/^(\s+)/);return!c||c[1].includes(" ")}))return"tab";if(n.length===0)return"2";function o(s,a){return a===0?s:o(a,s%a)}let i=n[0];for(let s=1;s<n.length;s++)i=o(i,n[s]);return i>=4?"4":"2"}function
|
|
3
|
-
`).map(r=>
|
|
4
|
-
`)}function Zo(e){let{ast:t,source:n}=e;try{let r=Wx(n),i=zx(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=Gx(i,r)),{ok:!0,source:i}}catch(r){return J(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 Nr(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 ye(e,t,n){let r=Zo({ast:e,source:t});return r.ok?Nr(t,r.source,n):r}function we(e,t){let n=Ir(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function Qo(e,t){return Zo({ast:e,source:t})}function sb(e,t,n){let r=ce(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=sb(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:J(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function on(e){return typeof e=="string"?sa(e):typeof e=="number"?rb(e):typeof e=="boolean"?Zx(e):e===null?nb():Array.isArray(e)?Yx(e.map(t=>on(t))):ob(Object.entries(e).map(([t,n])=>{let r=ib(aa(t),on(n));return t==="__proto__"&&(r.computed=!0),r}))}function ab(e){return typeof e=="string"?sa(e):eb(on(e))}function Pr(e,t){return qx(tb(e),ab(t))}function qo(e,t){try{let r=Vu.parse(`const __VD_NODE__ = (${t});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0];return r?.type!=="VariableDeclaration"||r.declarations[0]?.type!=="VariableDeclarator"||!r.declarations[0].init||r.declarations[0].init.type!=="JSXElement"&&r.declarations[0].init.type!=="JSXFragment"?{ok:!1,result:J(e,"unsupported-syntax","Provided JSX source does not resolve to a JSX node","jsx-node")}:{ok:!0,node:r.declarations[0].init}}catch(n){return{ok:!1,result:J(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function aa(e){return/^[$A-Z_][0-9A-Z_$]*$/i.test(e)?Qx(e):sa(e)}function ei(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=we(t,"jsx-node");if(!i.ok)return i.result;let s=ce(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let c=cb(s.match.path)[r];if(!c)return J(t,"locator-miss",`Text segment ${r} not found`,"jsx-node");switch(c.kind){case"jsx-text":c.path.node.value=lb(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 ye(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function cb(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=ub(r.get("expression"));o.length>0&&t.push(...o)}}return t}function lb(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function ub(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 ca}from"@babel/types";function Gn(e){let{source:t,locator:n}=e,r=we(t,"jsx-node");if(!r.ok)return r.result;let o=ce(r.ast,n);return o.ok?(db(o.match.path),ye(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function db(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(ca());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(ca());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(ca());return}e.remove()}import{cloneNode as fb}from"@babel/types";function ti(e){let t=we(e.source,"jsx-node");if(!t.ok)return t.result;let n=ce(t.ast,e.locator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};let r=qo(e.source,e.node.jsx);return r.ok?(n.match.path.replaceWith(fb(r.node,!0)),ye(t.ast,e.source,{kind:"replace-node",target:"jsx-node",inverse:"replace-node"})):r.result}import{cloneNode as kb}from"@babel/types";import la from"@babel/traverse";import*as q from"@babel/types";function Ar(e,t,n){return`${e}::${t}::${n}`}var V={NODE_NOT_FOUND:"NODE_NOT_FOUND",HOME_PAGE_LOCKED:"HOME_PAGE_LOCKED",ROUTE_NOT_FOUND:"ROUTE_NOT_FOUND",CAPABILITY_REJECTED:"CAPABILITY_REJECTED",CONSTRAINT_VIOLATED:"CONSTRAINT_VIOLATED",INVALID_PARAMS:"INVALID_PARAMS",PLAN_FAILED:"PLAN_FAILED",TRANSACTION_PREFLIGHT_FAILED:"TRANSACTION_PREFLIGHT_FAILED",ROUTE_REBUILD_FAILED:"ROUTE_REBUILD_FAILED",HISTORY_COMMIT_FAILED:"HISTORY_COMMIT_FAILED",MATERIALIZATION_CONFLICT:"MATERIALIZATION_CONFLICT",MATERIALIZATION_REJECTED:"MATERIALIZATION_REJECTED",MUTATION_ASSERTION_REQUIRED:"MUTATION_ASSERTION_REQUIRED",MUTATION_ASSERTION_INVALID:"MUTATION_ASSERTION_INVALID",VERSION_STALE:"VERSION_STALE",AST_PARSE_ERROR:"AST_PARSE_ERROR",UNSUPPORTED_OPERATION:"UNSUPPORTED_OPERATION",LOCATOR_FAILED:"LOCATOR_FAILED",INVALID_TARGET:"INVALID_TARGET",WRITE_IO_ERROR:"WRITE_IO_ERROR",CONCURRENT_MODIFIED:"CONCURRENT_MODIFIED",ROLLBACK_FAILED:"ROLLBACK_FAILED",RECOVERY_REQUIRED:"RECOVERY_REQUIRED",RECOVERY_PERSIST_FAILED:"RECOVERY_PERSIST_FAILED",MUTATION_SESSION_REQUIRED:"MUTATION_SESSION_REQUIRED",LEASE_ASSERTION_INVALID:"LEASE_ASSERTION_INVALID",LEASE_ASSERTION_EXPIRED:"LEASE_ASSERTION_EXPIRED",LEASE_ASSERTION_SCOPE_MISMATCH:"LEASE_ASSERTION_SCOPE_MISMATCH",CROSS_PAGE_MOVE_UNSUPPORTED:"CROSS_PAGE_MOVE_UNSUPPORTED",INTERNAL_ERROR:"INTERNAL_ERROR"};var pb=typeof la=="function"?la:la.default;function mt(e,t,n,r){if(!e.ok)return e;let o=pt(n,t);if(!o)return e;let i=mb(t,o,r);return i?{...e,selectionRef:i}:e}function mb(e,t,n){let r=gb(e,t);if(!r)return;let o=n.sourceLocator?Ku(n.sourceLocator):void 0,i=n.targetParentLocator?Ku(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??yb(r)??i?.component??o?.component;if(!(!s||!a))return{key:Ar(s,a,xb(r))}}function Ku(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function gb(e,t){let n=Hu(e,t);return!n||n.node.type!=="JSXElement"?null:n}function Hu(e,t){let n=null;return pb(e,{JSXElement(r){r.node===t&&(n=r,r.stop())},JSXFragment(r){r.node===t&&(n=r,r.stop())}}),n}function pt(e,t){if(!e)return null;if(q.isJSXElement(e))return vb(t,e)?Uu(e.children,t):e;if(q.isJSXFragment(e))return Uu(e.children,t);if(q.isJSXExpressionContainer(e)||q.isParenthesizedExpression(e)||q.isTSAsExpression(e)||q.isTSSatisfiesExpression(e)||q.isTSTypeAssertion(e)||q.isTSNonNullExpression(e))return pt(e.expression,t);if(q.isLogicalExpression(e))return pt(e.right,t);if(q.isConditionalExpression(e))return pt(e.consequent,t)??pt(e.alternate,t);if(q.isCallExpression(e)||q.isOptionalCallExpression(e))return Gu(e)?hb(e.arguments[0],t):null;if(q.isArrayExpression(e))for(let n of e.elements){if(!n)continue;let r=pt(n,t);if(r)return r}return null}function Uu(e,t){for(let n of e){let r=pt(n,t);if(r)return r}return null}function hb(e,t){return!e||!q.isArrowFunctionExpression(e)&&!q.isFunctionExpression(e)?null:q.isBlockStatement(e.body)?Tr(e.body.body,t):pt(e.body,t)}function Tr(e,t){for(let n of e){if(q.isReturnStatement(n)){let r=pt(n.argument,t);if(r)return r;continue}if(q.isBlockStatement(n)){let r=Tr(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=Tr(r.consequent,t);if(o)return o}}return null}function Ju(e,t){return q.isBlockStatement(e)?Tr(e.body,t):Tr([e],t)}function yb(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 Xu=new WeakMap,zu=new WeakMap,ua=new WeakMap;function xb(e){let t=Xu.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=bb(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return Xu.set(e.node,o),o}function bb(e){let t=Yu(e.node.openingElement.name);return!t||_e(e)?null:/^[A-Z]/.test(t)?`component:${t}#${Wu(e,t)}`:`${t}#${Wu(e,t)}`}function Wu(e,t){let n=Sb(e);if(!n)return 0;let r=ua.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=ua.get(n.node);o||(o=new Map,ua.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of wn(n))if(Yu(a.node.openingElement.name)===t){if(i.set(a.node,s),a.node===e.node)return s;s+=1}return i.get(e.node)??0}function Sb(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(_e(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function wn(e){let t=zu.get(e.node);if(t)return t;let n=[],r=e.get("children");for(let o of r)if(!Array.isArray(o)){if(o.isJSXElement()){if(_e(o)){n.push(...wn(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...wn(o));continue}o.isJSXExpressionContainer()&&n.push(..._t(o.get("expression")))}return zu.set(e.node,n),n}function _t(e){if(e.isJSXElement())return _e(e)?wn(e):[e];if(e.isJSXFragment())return wn(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())&&Gu(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?Eb(n):[]}return[]}function Eb(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return _e(t)?wn(t):[t];if(t.isJSXFragment())return wn(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 Gu(e){let t=e.callee;return(q.isMemberExpression(t)||q.isOptionalMemberExpression(t))&&q.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function vb(e,t){let n=Hu(e,t);return n?_e(n):!1}function Yu(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 sn(e,t){if(t.parentPath===e&&t.listKey==="children"&&da(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!da(n))return null;let r=n;for(;r&&r!==e;){if(!da(r)||!_e(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function da(e){return e.isJSXElement()||e.isJSXFragment()}function Yn(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=we(t,"jsx-node");if(!a.ok)return a.result;let c=ce(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return J(t,"unsupported-syntax","insert-child target must be a JSXElement or JSXFragment","jsx-node");let l=c.match.path;if(c.match.path.isJSXElement()){let k=c.match.path.node;if(!k.closingElement||k.openingElement.selfClosing)return J(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let d=qo(t,r.jsx);if(!d.ok)return d.result;let f=kb(d.node,!0),m=l.node.children,u={...s,targetParentLocator:n},g=k=>s?mt(k,a.ast,f,u):k;if(o==="append")return m.push(f),g(ye(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return m.unshift(f),g(ye(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(!i)return J(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let h=ce(a.ast,i);if(!h.ok)return{ok:!1,source:t,diagnostic:h.diagnostic};let b=sn(c.match.path,h.match.path);if(!b)return J(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,y=E.findIndex(k=>k===h.match.path.node);return y===-1?J(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(E.splice(o==="before"?y:y+1,0,f),g(ye(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as Qu from"@babel/parser";import{cloneNode as Ib}from"@babel/types";function ni(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=we(t,"jsx-node");if(!a.ok)return a.result;let c=Cb(t,r);if(!c.ok)return c.result;let l=ce(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return J(t,"unsupported-syntax","insert-jsx-expression-child target must be a JSXElement or JSXFragment","jsx-node");if(l.match.path.isJSXElement()){let E=l.match.path.node;if(!E.closingElement||E.openingElement.selfClosing)return J(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let d=l.match.path,f=null;if(i){let E=ce(a.ast,i);if(!E.ok)return{ok:!1,source:t,diagnostic:E.diagnostic};let y=sn(l.match.path,E.match.path);if(!y)return J(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");d=y,f=E.match.path.node}else if(o==="before"||o==="after")return J(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=Ib(c.node,!0),u=d.node.children,g={...s,targetParentLocator:n},h=E=>s?mt(E,a.ast,m,g):E;if(o==="append")return u.push(m),h(ye(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return u.unshift(m),h(ye(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let b=u.findIndex(E=>E===f);return b===-1?J(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(u.splice(o==="before"?b:b+1,0,m),h(ye(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function Cb(e,t){try{let r=Qu.parse(`const __VD_EXPR__ = <>{${t}}</>;`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],o=r?.type==="VariableDeclaration"?r.declarations[0]?.init:null,i=o?.type==="JSXFragment"?o.children[0]:void 0;return i?.type!=="JSXExpressionContainer"?{ok:!1,result:J(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:J(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as Rb,nullLiteral as fa}from"@babel/types";import*as an from"@babel/types";import*as qu from"@babel/types";function Fr(e,t){let n=e.parentPath;if(!n?.isConditionalExpression()||e.key!=="consequent"||!qu.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=we(t,"jsx-node");if(!a.ok)return a.result;let c=ce(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let l=ce(a.ast,r);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return J(t,"unsupported-syntax","move-node target parent must be a JSXElement or JSXFragment","jsx-node");let d=l.match.path;if(l.match.path.isJSXElement()){let k=l.match.path.node;if(!k.closingElement||k.openingElement.selfClosing)return J(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let f=null;if(i){let k=ce(a.ast,i);if(!k.ok)return{ok:!1,source:t,diagnostic:k.diagnostic};let C=k.match.path.isJSXElement()?Fr(k.match.path,l.match.path):k.match.path,N=sn(l.match.path,C);if(!N)return J(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");d=N,f=C}else if(o==="before"||o==="after")return J(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=f&&typeof f.key=="number"?f.key:-1;if(f&&m===-1)return J(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let u=c.match.path.isJSXElement()?Fr(c.match.path,l.match.path):c.match.path,g=Rb(u.node,!0);if(!an.isJSXElement(g)&&!an.isJSXExpressionContainer(g)&&!an.isJSXFragment(g)&&!an.isJSXText(g))return J(t,"unsupported-syntax","move-node source must resolve to a JSX child","jsx-node");let h=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 J(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");wb(u);let b=d.node.children,E={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return b.push(g),mt(Qo(a.ast,t),a.ast,g,E);if(o==="prepend")return b.unshift(g),mt(Qo(a.ast,t),a.ast,g,E);let y=m-(h!==-1&&h<m?1:0);return b.splice(o==="before"?y:y+1,0,g),mt(Qo(a.ast,t),a.ast,g,E)}function wb(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(fa());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(fa());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(fa());return}e.remove()}import*as ed from"@babel/parser";import{cloneNode as Nb,nullLiteral as pa}from"@babel/types";function ri(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,c=we(t,"jsx-node");if(!c.ok)return c.result;let l=Pb(t,s);if(!l.ok)return l.result;let d=ce(c.ast,n);if(!d.ok)return{ok:!1,source:t,diagnostic:d.diagnostic};let f=ce(c.ast,r);if(!f.ok)return{ok:!1,source:t,diagnostic:f.diagnostic};if(!f.match.path.isJSXElement()&&!f.match.path.isJSXFragment())return J(t,"unsupported-syntax","move-repeat-template-child target parent must be a JSXElement or JSXFragment","jsx-node");if(f.match.path.isJSXElement()){let k=f.match.path.node;if(!k.closingElement||k.openingElement.selfClosing)return J(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let m=f.match.path,u=null;if(i){let k=ce(c.ast,i);if(!k.ok)return{ok:!1,source:t,diagnostic:k.diagnostic};let C=sn(f.match.path,k.match.path);if(!C)return J(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");m=C,u=k.match.path.node}else if(o==="before"||o==="after")return J(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!d.match.path.isJSXElement())return J(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let g=m.node,h=Nb(l.node,!0);Ab(d.match.path);let b={...a,sourceLocator:n,targetParentLocator:r},E=g.children;if(o==="append")return E.push(h),mt(ye(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),mt(ye(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,b);let y=E.findIndex(k=>k===u);return y===-1?J(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(E.splice(o==="before"?y:y+1,0,h),mt(ye(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,b))}function Pb(e,t){try{let r=ed.parse(`const __VD_EXPR__ = <>{${t}}</>;`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],o=r?.type==="VariableDeclaration"?r.declarations[0]?.init:null,i=o?.type==="JSXFragment"?o.children[0]:void 0;return i?.type!=="JSXExpressionContainer"?{ok:!1,result:J(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:J(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function Ab(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(pa());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(pa());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(pa());return}e.remove()}import{SiteEditSetPropsParamsSchema as Tb,classifySiteEditPropertyName as Fb}from"@vcp-dev/contracts";import*as Qn from"@babel/types";function oi(e){let t=Tb.safeParse({kind:"set-props",scope:"selection",changes:e.changes});if(!t.success)return J(e.source,"unsupported-syntax","Invalid typed JSX property changes","jsx-node",{issues:t.error.issues});let n=we(e.source,"jsx-node");if(!n.ok)return n.result;let r=Hn(n.ast,e.locator,e.source);if(!r.ok)return r.result;for(let a of t.data.changes){let c=Fb(a.name);if(c.owner!=="generic")return J(e.source,"unsupported-syntax",c.diagnostic?.message??`Property '${a.name}' is not owned by the generic JSX primitive`,"jsx-node")}let o=r.match.path.node.openingElement,i=o.attributes.filter(Qn.isJSXAttribute),s=new Map;for(let a of i){let c=_b(a);if(!c)continue;let l=s.get(c)??[];l.push(a),s.set(c,l)}for(let a of t.data.changes)if((s.get(a.name)??[]).length>1)return J(e.source,"unsupported-syntax",`JSX attribute '${a.name}' has multiple sources`,"jsx-node");for(let a of t.data.changes){let c=s.get(a.name)?.[0];if(a.operation==="remove"){c&&(o.attributes=o.attributes.filter(d=>d!==c));continue}let l=Pr(a.name,a.value).value;c?c.value=l:o.attributes.push(Pr(a.name,a.value))}return ye(n.ast,e.source,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}function _b(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 Mb}from"@vcp-dev/contracts";import*as z from"@babel/types";var td=["prefetch","replace","scroll","locale","onNavigate"],Ob=/^on(?:Click|DoubleClick|AuxClick|MouseDown|MouseUp|PointerDown|PointerUp|TouchStart|TouchEnd|KeyDown|KeyUp|ContextMenu)(?:Capture)?$/;function Lb(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 ii(e){let t=we(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=Mb.safeParse({kind:"set-link-target",scope:"selection",link:e.link,changes:e.changes});if(!r.success||r.data.kind!=="set-link-target")return Ht(e.source,"Invalid typed link-target changes");let o=n.match.path,i=o.node,s=i.openingElement,a=Ub(s.name);if(!a)return Ht(e.source,"Unsupported JSX link tag");if(s.attributes.some(z.isJSXSpreadAttribute))return Ht(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=ga(g);if(!h)return Ht(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 Ht(e.source,"Duplicate JSX attributes cannot be transformed safely");let l=c.get("href")?.[0];if(l&&!Kb(l))return Ht(e.source,"Dynamic link href cannot be transformed safely");let d=a==="a",f=d?null:jb(o,s.name);if(!d&&!f)return Ht(e.source,"Only native anchors and imported next/link components are supported");if(e.link.kind==="none"&&Lb(o))return Ht(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=$b(t.ast,o);if(!g.ok)return Ht(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")),Vb(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"),td.forEach(g=>u.add(g))):(u.add("href"),e.link.kind==="native-link"&&td.forEach(g=>u.add(g))),s.attributes=s.attributes.filter(g=>{if(!z.isJSXAttribute(g))return!0;let h=ga(g);return!h||!u.has(h)}),e.link.kind!=="none"&&s.attributes.push(z.jsxAttribute(z.jsxIdentifier("href"),z.stringLiteral(e.link.href))),Db(s,e.changes),ye(t.ast,e.source,{kind:"set-link-target",target:"jsx-node",inverse:"set-link-target"})}function Db(e,t){for(let n of t){let r=e.attributes.find(s=>z.isJSXAttribute(s)&&ga(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(ma(n.value)),i=z.jsxAttribute(z.jsxIdentifier(n.name),o);r&&z.isJSXAttribute(r)?r.value=i.value:e.attributes.push(i)}}function ma(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=>ma(t))):typeof e=="object"?z.objectExpression(Object.entries(e).map(([t,n])=>z.objectProperty(z.isValidIdentifier(t)?z.identifier(t):z.stringLiteral(t),ma(n)))):z.nullLiteral()}function Bb(e){return z.isImportDefaultSpecifier(e)||z.isImportSpecifier(e)&&e.importKind!=="type"&&(z.isIdentifier(e.imported,{name:"default"})||z.isStringLiteral(e.imported,{value:"default"}))}function nd(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 jb(e,t){if(!z.isJSXIdentifier(t))return null;let n=e.scope.getBinding(t.name);if(!n||!nd(n.path))return null;let r=n.path.parentPath;return!r?.isImportDeclaration()||r.node.source.value!=="next/link"?null:t.name}function $b(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(Bb);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 Vb(e,t,n){let r=n.scope.getProgramParent();r.crawl();let o=r.getBinding(t);if(!o||!nd(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 Kb(e){return!e.value||z.isStringLiteral(e.value)}function Ub(e){return z.isJSXIdentifier(e)?e.name:null}function ga(e){return z.isJSXIdentifier(e.name)?e.name.name:null}function Ht(e,t){return J(e,"unsupported-syntax",t,"jsx-node")}import*as Ke from"@babel/types";import{classifySiteEditPropertyName as rd}from"@vcp-dev/contracts";function si(e){let t=rd(e.name),n=rd(e.property);if(t.owner!=="generic"||n.owner!=="generic")return J(e.source,"unsupported-syntax","Property binding is only available for generic properties","jsx-node");if(!od(e.object))return J(e.source,"unsupported-syntax","Property binding object must be a single identifier","jsx-node");if(e.property.length===0)return J(e.source,"unsupported-syntax","Property binding requires a non-empty property name","jsx-node");let r=we(e.source,"jsx-node");if(!r.ok)return r.result;let o=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)&&Xb(l)===e.name);if(s.length>1)return J(e.source,"unsupported-syntax",`JSX attribute '${e.name}' has multiple sources`,"jsx-node");let a=Jb(e.object,e.property),c=s[0];if(c)c.value=Ke.jsxExpressionContainer(a);else{let l=Pr(e.name,"");l.value=Ke.jsxExpressionContainer(a),i.attributes.push(l)}return ye(r.ast,e.source,{kind:"set-property-binding",target:"jsx-node",inverse:"restore-property-binding"})}function Jb(e,t){return od(t)?Ke.memberExpression(Ke.identifier(e),Ke.identifier(t)):Ke.memberExpression(Ke.identifier(e),Ke.stringLiteral(t),!0)}function od(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)}function Xb(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 Wb,identifier as _r,importDeclaration as Hb,importDefaultSpecifier as Gb,importNamespaceSpecifier as Yb,importSpecifier as Zb,isImportDefaultSpecifier as id,isImportNamespaceSpecifier as sd,isImportSpecifier as ad,stringLiteral as Qb}from"@babel/types";function qn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(b=>!aS(b));if(o!==-1){let b=r[o],E=b&&typeof b=="object"&&"kind"in b?b.kind:void 0;return J(t,"unsupported-syntax",`Unsupported import spec kind: ${String(E)}`)}let i=oS(r);if(!i.ok)return J(t,"unsupported-syntax",i.message);let s=we(t);if(!s.ok)return s.result;let{ast:a}=s,c=a.program,l=c.body.filter(b=>b.type==="ImportDeclaration"&&b.source.value===n),d=new Set(l.flatMap(b=>b.specifiers.flatMap(E=>{let y=cS(b,E);return y?[y]:[]}))),f=i.imports.filter(b=>!d.has(pd(b)));if(f.length===0)return Nr(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let m=iS(c.body),u=f.find(b=>m.has(ha(b)));if(u)return J(t,"unsupported-syntax",`Import local binding already exists: ${ha(u)}`);let g=rS(f);if(g.reduce((b,E)=>b+E.length,0)!==f.length)return J(t,"unsupported-syntax","Unsupported import specifier grouping");for(let b of g){if(!dd(ld(b)))return J(t,"unsupported-syntax","Unsupported import specifier combination");let E=l.find(y=>qb(y,b));if(E)eS(E,b);else{let y=Hb(cd(b),Qb(n));sS(c.body,y),l.push(y)}}return ye(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function qb(e,t){return e.importKind==="type"?!1:dd(nS(tS(e),ld(t)))}function eS(e,t){let n=!1,r=new Set(e.specifiers.map(o=>ya(o)));for(let o of cd(t)){let i=ya(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return fd(e.specifiers),{changed:n}}function cd(e){let t=e.map(n=>{switch(n.kind){case"named":return Zb(n.local?_r(n.local):_r(n.imported),_r(n.imported));case"default":return Gb(_r(n.local));case"namespace":return Yb(_r(n.local));default:return n}});return fd(t),t}function ld(e){let t=ud();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 tS(e){let t=ud();for(let n of e.specifiers)id(n)?t.defaultLocals.add(n.local.name):sd(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function ud(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function nS(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function dd(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function fd(e){let t=[...e.filter(n=>id(n)),...e.filter(n=>sd(n)),...e.filter(n=>ad(n))];e.splice(0,e.length,...t)}function rS(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 oS(e){let t=new Map,n=new Map;for(let r of e){let o=pd(r);if(t.has(o))continue;let i=ha(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 iS(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(Wb(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 sS(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 aS(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 pd(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 ha(e){return e.kind==="named"?e.local??e.imported:e.local}function cS(e,t){return e.importKind==="type"||ad(t)&&t.importKind==="type"?null:ya(t)}function ya(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=>!uS(d));if(o!==-1){let d=r[o],f=d&&typeof d=="object"&&"kind"in d?d.kind:void 0;return J(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(f)}`)}let i=we(t);if(!i.ok)return i.result;let{ast:s}=i,a=s.program,c=a.body.findIndex(d=>d.type==="ImportDeclaration"&&d.source.value===n);if(c===-1)return Nr(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let l=a.body[c];return r.length===0?(a.body.splice(c,1),ye(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(l.specifiers=l.specifiers.filter(d=>!r.some(f=>lS(d,f))),l.specifiers.length===0&&a.body.splice(c,1),ye(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function lS(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 uS(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 Mr(e){let{source:t,locator:n,next:r}=e,o=ui(t,n);return o.ok?(o.path.replaceWith(on(r)),ye(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function ai(e){let{source:t,locator:n,index:r,value:o}=e,i=ui(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(s=>s?.type==="SpreadElement")?J(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>i.path.node.elements.length?J(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,0,on(o)),ye(i.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):J(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function ci(e){let{source:t,locator:n,index:r}=e,o=ui(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(i=>i?.type==="SpreadElement")?J(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=o.path.node.elements.length?J(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(o.path.node.elements.splice(r,1),ye(o.ast,t,{kind:"remove-array-element",target:"value",inverse:"insert-array-element"})):J(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function li(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=ui(t,n);if(!i.ok)return i.result;if(!i.path.isArrayExpression())return J(t,"unsupported-syntax","Array operations require array expression target","value");if(i.path.node.elements.some(c=>c?.type==="SpreadElement"))return J(t,"unsupported-syntax","Spread array elements are not supported","value");if(r<0||r>=i.path.node.elements.length||o<0||o>i.path.node.elements.length)return J(t,"array-index-out-of-range","Array move indices are out of range","value");let[s]=i.path.node.elements.splice(r,1),a=Math.min(o,i.path.node.elements.length);return i.path.node.elements.splice(a,0,s),ye(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function ui(e,t){let n=we(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=ce(n.ast,t);return r.ok?{ok:!0,ast:n.ast,path:r.match.path}:{ok:!1,result:{ok:!1,source:e,diagnostic:r.diagnostic}}}import*as Xe from"@babel/types";function di(e){let t=we(e.source,"value");if(!t.ok)return t.result;let n=ce(t.ast,e.objectLocator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};if(!n.match.path.isObjectExpression())return J(e.source,"unsupported-syntax","Object property upsert requires an ObjectExpression parent","value");let r=n.match.path.node;if(r.properties.some(a=>Xe.isSpreadElement(a)||Xe.isObjectProperty(a)&&a.computed))return J(e.source,"unsupported-syntax","Object property upsert does not support spreads or computed keys","value");let o=r.properties.filter(a=>Xe.isObjectProperty(a)&&dS(a.key)===e.name);if(o.length>1)return J(e.source,"unsupported-syntax",`Object property '${e.name}' has multiple sources`,"value");let i=e.value.kind==="undefined"?Xe.unaryExpression("void",Xe.numericLiteral(0)):on(e.value.value),s=o[0];if(s)s.value=i,s.shorthand=!1;else{let a=Xe.objectProperty(aa(e.name),i);e.name==="__proto__"&&(a.computed=!0),r.properties.push(a)}return ye(t.ast,e.source,{kind:"upsert-object-property",target:"value",inverse:"restore-object-property"})}function dS(e){return Xe.isIdentifier(e)?e.name:Xe.isStringLiteral(e)?e.value:Xe.isNumericLiteral(e)?String(e.value):null}import{isSiteEditRuntimeContainerTag as fS,isSiteEditRuntimeVoidElementTag as pS}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 mS(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(C=>({kind:C.kind,message:C.reason})),a=i.isOpaque,l=o.parentKey===null&&i.componentName==="Page",d=i.tag.toLowerCase(),f=i.tag!==d,m=!f&&pS(d),u=f||fS(d),g=f&&i.childKeys.length>0&&!i.isPublicUiComponent,h=i.textSegments.length>0&&i.textSegments.some(C=>C.editable);m&&!s.some(C=>C.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' is void: children cannot be inserted`}),!m&&!u&&!s.some(C=>C.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' cannot contain structured children`});let 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 md(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,mS(r,e,t));return n}function xa(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:Ie(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=gS(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:Ie(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:hd(r),version:{documentVersion:e.route.graph.version,contentHash:Ie(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:gd(e.route.source,o),valueRaw:s?gd(e.route.source,s):null,attrRange:hd(o),diagnostics:[]}}function yd(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 gS(e,t){let n=At({source:e,profile:vn({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=ce(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:hS(t.sourceRange)});return!r.ok||r.match.node.type!=="JSXElement"?null:r.match.node}function xd(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 gd(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function hd(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 hS(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function bd(){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 yS}from"node:crypto";import fi from"node:fs/promises";import ba from"node:path";import{setTimeout as xS}from"node:timers/promises";var bS={async mkdir(e,t){await fi.mkdir(e,t)},async writeFile(e,t,n){await fi.writeFile(e,t,n)},async rename(e,t){await fi.rename(e,t)},async rm(e,t){await fi.rm(e,t)}},SS=new Set(["EACCES","EBUSY","EPERM"]),ES=[10,20,40,80,160];async function vS(e,t,n){for(let r of ES)try{await e.rename(t,n);return}catch(o){if(!kS(o))throw o;await xS(r)}await e.rename(t,n)}function kS(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&SS.has(e.code)}async function pi(e,t,n=bS){let r=ba.dirname(e),o=ba.basename(e),i=ba.join(r,`.${o}.${process.pid}.${yS()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await vS(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import Sa from"@babel/traverse";import*as v from"@babel/types";import*as de from"@babel/types";function Mt(e,t={}){if(de.isTSAsExpression(e)||de.isTSSatisfiesExpression(e)||de.isTSNonNullExpression(e)||de.isTypeCastExpression(e)||de.isParenthesizedExpression(e))return Mt(e.expression,t);if(de.isStringLiteral(e))return{status:"resolved",value:e.value};if(de.isNumericLiteral(e))return Number.isFinite(e.value)?{status:"resolved",value:e.value}:{status:"unresolved"};if(de.isBooleanLiteral(e))return{status:"resolved",value:e.value};if(de.isNullLiteral(e))return{status:"resolved",value:null};if(de.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(de.isIdentifier(e))return e.name==="undefined"&&!t.resolveIdentifier?{status:"undefined"}:t.resolveIdentifier?.(e.name)??{status:"unresolved"};if(de.isUnaryExpression(e)&&e.operator==="void"&&de.isNumericLiteral(e.argument)&&e.argument.value===0)return{status:"undefined"};if(de.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||de.isSpreadElement(r))return{status:"unresolved"};let o=Mt(r,t);if(o.status!=="resolved")return{status:"unresolved"};n.push(o.value)}return{status:"resolved",value:n}}if(de.isObjectExpression(e)){let n=Object.create(null);for(let r of e.properties){if(!de.isObjectProperty(r)||r.computed||!de.isExpression(r.value))return{status:"unresolved"};let o=IS(r.key);if(o===null)return{status:"unresolved"};let i=Mt(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 de.isMemberExpression(e)||de.isOptionalMemberExpression(e)?t.resolveMember?.(e)??{status:"unresolved"}:{status:"unresolved"}}function IS(e){return de.isIdentifier(e)?e.name:de.isStringLiteral(e)?e.value:de.isNumericLiteral(e)?String(e.value):null}var CS=typeof Sa=="function"?Sa:Sa.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 RS(e){return/^[A-Z]/.test(e)}function Ca(e){let t=e.openingElement;return v.isJSXIdentifier(t.name)?t.name.name==="Fragment":v.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function rr(e){return v.isJSXFragment(e)}function Ed(e){return v.isJSXIdentifier(e.name)?e.name.name:v.isJSXMemberExpression(e.name)?vd(e.name):v.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function vd(e){return v.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:v.isJSXMemberExpression(e.object)?`${vd(e.object)}.${e.property.name}`:e.property.name}function wS(e){return e.split(".")[0]??e}function NS(e){let t=e;for(;t;){let n=t.node;if(v.isFunctionDeclaration(n)&&n.id||v.isVariableDeclarator(n)&&v.isIdentifier(n.id))return n.id.name;if(v.isExportDefaultDeclaration(n)){let r=n.declaration;if(v.isFunctionDeclaration(r)&&r.id)return r.id.name;if(v.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function PS(){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 AS(e){let t=new Map;for(let n of e.program.body){if(!v.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(v.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(v.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(v.isImportSpecifier(o)){let i=v.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function Gt(e,t=[]){if(v.isIdentifier(e))return t.push(e.name),t;if(v.isObjectPattern(e)){for(let n of e.properties)v.isObjectProperty(n)?Gt(n.value,t):v.isRestElement(n)&&Gt(n.argument,t);return t}if(v.isArrayPattern(e)){for(let n of e.elements)n&&(v.isRestElement(n)?Gt(n.argument,t):Gt(n,t));return t}return v.isAssignmentPattern(e)?(Gt(e.left,t),t):(v.isRestElement(e)&&Gt(e.argument,t),t)}function Et(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Or(e,t){for(let n=t.length-1;n>=0;n-=1){let r=t[n].get(e);if(r)return r.resolved?{kind:"resolved",value:r.value}:{kind:"unresolved"}}return{kind:"unresolved"}}function TS(e,t,n){e.set(t,{resolved:!0,value:n})}function Ra(e,t){e.set(t,{resolved:!1})}function kd(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(v.isTSAsExpression(e)||v.isTSSatisfiesExpression(e)||v.isTSNonNullExpression(e)||v.isTypeCastExpression(e)||v.isParenthesizedExpression(e))return $e(e.expression,t,n);if(v.isLogicalExpression(e))return mi([$e(e.left,t,n),$e(e.right,t,n)]);if(v.isBinaryExpression(e))return mi([v.isExpression(e.left)?$e(e.left,t,n):null,v.isExpression(e.right)?$e(e.right,t,n):null]);if(v.isConditionalExpression(e))return mi([$e(e.consequent,t,n),$e(e.alternate,t,n)]);if(v.isTemplateLiteral(e))return mi(e.expressions.filter(v.isExpression).map(i=>$e(i,t,n)));if(v.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!v.isMemberExpression(e)&&!v.isOptionalMemberExpression(e))return null;let r=[],o=e;for(;v.isMemberExpression(o)||v.isOptionalMemberExpression(o);){if(o.computed)if(v.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(v.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&v.isExpression(o.property)){let i=cn(o.property,n);if(typeof i=="string")r.unshift({kind:"property",name:i});else if(Number.isInteger(i))r.unshift({kind:"index",index:i});else return null}else return null;else{if(!v.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return v.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:Et(e,t),base:o.name,path:r}:null}function mi(e){let t=e.filter(r=>r!==null);if(t.length===0)return null;let n=t[0];return t.some(r=>r.base!==n.base||JSON.stringify(r.path)!==JSON.stringify(n.path))?null:{...n}}function cn(e,t){if(v.isStringLiteral(e)||v.isNumericLiteral(e)||v.isBooleanLiteral(e))return e.value;if(v.isNullLiteral(e))return null;if(v.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(v.isIdentifier(e)){let n=Or(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(v.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||v.isSpreadElement(r))return;let o=cn(r,t);if(o===void 0)return;n.push(o)}return n}if(v.isObjectExpression(e)){let n={};for(let r of e.properties){if(!v.isObjectProperty(r)||r.computed||!v.isExpression(r.value))return;let o=null;if(v.isIdentifier(r.key)?o=r.key.name:v.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!v.isIdentifier(r.value))return;let s=Or(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=cn(r.value,t);if(i===void 0)return;n[o]=i}return n}if(v.isMemberExpression(e)){let n=$e(e,"",t);if(!n)return;let r=Or(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=kd(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(v.isCallExpression(e))return Cd(e,t)??void 0}function Id(e,t,n){let r=$e(e,n,t);if(!r)return v.isMemberExpression(e)||v.isBinaryExpression(e)||v.isLogicalExpression(e)||v.isConditionalExpression(e)||v.isCallExpression(e)?{value:Et(e,n),source:null}:null;let o=Or(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?kd(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 Ea(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:PS(),parentStack:[],valueScopes:i,importMap:o}}function ka(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of Gt(o.id))Ra(n,s);if(!v.isIdentifier(o.id)||!o.init||!v.isExpression(o.init))continue;let i=cn(o.init,t);i!==void 0&&TS(n,o.id.name,i)}}function FS(e){let t=[];for(let n of e){if(v.isVariableDeclaration(n)){t.push(n);continue}v.isExportNamedDeclaration(n)&&n.declaration&&v.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function _S(e,t,n){let r=[],o=0;for(let i of e)if(v.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:Ge(i),editable:!0,source:null})}else if(v.isJSXExpressionContainer(i)&&v.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:Ge(i),editable:!0,source:null});else if(v.isJSXExpressionContainer(i)&&v.isTemplateLiteral(i.expression)){let s=i.expression;s.expressions.length===0&&s.quasis.length===1?r.push({index:o++,value:s.quasis[0].value.cooked??s.quasis[0].value.raw,sourceRange:Ge(i),editable:!0,source:null}):r.push({index:o++,value:Et(s,n),sourceRange:Ge(i),editable:!0,source:$e(s,n,t)})}else if(v.isJSXExpressionContainer(i)&&v.isExpression(i.expression)){let s=Id(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:Ge(i),editable:!0,source:s.source})}return r}function MS(e,t,n){let r=[];for(let[o,i]of e.attributes.entries()){if(!v.isJSXAttribute(i))continue;let s=LS(i.name);if(!s)continue;let a=Et(i,n);if(v.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(v.isJSXExpressionContainer(i.value)&&v.isExpression(i.value.expression)){let c=cn(i.value.expression,t);if(s==="className"){let u=typeof c=="string"?c:c===void 0?Cd(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=Id(i.value.expression,t,n);if(c!==void 0){r.push({name:s,value:US(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=DS(i.value.expression,t),f=$e(i.value.expression,n,t),m=l?.value??Et(i.value.expression,n);r.push({name:s,value:d.status==="undefined"?"undefined":m,sourceRange:Ge(i),source:l?.source??f,syntaxKind:"expression",raw:a,order:o,resolution:d})}}return r}function OS(e,t,n){return e.attributes.flatMap((r,o)=>!v.isJSXSpreadAttribute(r)||!v.isExpression(r.argument)?[]:[{raw:Et(r.argument,n),sourceRange:Ge(r),order:o,source:$e(r.argument,n,t)}])}function LS(e){return v.isJSXIdentifier(e)?e.name:v.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function DS(e,t){return Mt(e,{resolveIdentifier(n){let r=Or(n,t.valueScopes);return r.kind==="resolved"?{status:"resolved",value:r.value}:n==="undefined"&&!t.valueScopes.some(o=>o.has(n))?{status:"undefined"}:{status:"unresolved"}},resolveMember(n){let r=cn(n,t);return r===void 0?{status:"unresolved"}:{status:"resolved",value:r}}})}function Cd(e,t){let n=nr(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function nr(e,t){if(v.isStringLiteral(e))return[e.value];if(v.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(v.isNullLiteral(e))return[];if(v.isBooleanLiteral(e))return e.value?null:[];if(v.isIdentifier(e)||v.isMemberExpression(e)){if(v.isIdentifier(e)&&e.name==="undefined")return[];let n=cn(e,t);return typeof n=="string"?[n]:null}if(v.isConditionalExpression(e)){let n=nr(e.consequent,t),r=nr(e.alternate,t);return!n||!r?null:[...n,...r]}if(v.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=cn(e.left,t);return n===!1||n===null?[]:nr(e.right,t)}if(v.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||v.isSpreadElement(r))return null;let o=nr(r,t);if(!o)return null;n.push(...o)}return n}if(v.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!v.isObjectProperty(r))return null;let o=jS(r.key);if(!o)return null;n.push(o)}return n}if(v.isCallExpression(e)){let n=BS(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!v.isExpression(o))return null;let i=nr(o,t);if(!i)return null;r.push(...i)}return r}return null}function BS(e){return v.isIdentifier(e)?e.name:v.isMemberExpression(e)&&v.isIdentifier(e.property)?e.property.name:null}function jS(e){return v.isIdentifier(e)?e.name:v.isStringLiteral(e)?e.value:null}function $S(e,t){let n=e.attributes.find(r=>v.isJSXAttribute(r)&&v.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!v.isJSXAttribute(n)||!v.isJSXExpressionContainer(n.value)?null:n.value.expression}function VS(e,t){for(let n of t){let r=$S(e,n);if(r)return r}return null}function KS(e){return v.isJSXIdentifier(e.name)?e.name.name:null}function US(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function JS(e){if(!v.isCallExpression(e)&&!v.isOptionalCallExpression(e))return null;let t=e.callee;return!v.isMemberExpression(t)&&!v.isOptionalMemberExpression(t)||!v.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!v.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function va(e){return v.isArrowFunctionExpression(e)||v.isFunctionExpression(e)}function XS(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function zS(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function Sd(e,t,n,r){if(!e||!v.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:Et(e,n),collectionSource:$e(e,n,r)};if(t){let i=t.params[0],s=t.params[1];v.isIdentifier(i)&&(o.itemParamName=i.name),v.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function Yt(e,t,n){if(!e)return[];if(v.isJSXElement(e)){if(Ca(e))return bi(e.children,t,n);let r=yi(e,t,n);return r?[r]:[]}return rr(e)?xi(e,t,n):v.isParenthesizedExpression(e)?Yt(e.expression,t,n):v.isExpression(e)?Si(e,t,n):[]}function gi(e,t,n){let r=new Map;for(let o of e.params)for(let i of Gt(o))Ra(r,i);t.valueScopes.push(r);try{if(!v.isBlockStatement(e.body))return Yt(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return Rd(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function Rd(e,t,n){let r=[];for(let o of e){if(v.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];if(i){ka([o],t,i);for(let s of o.declarations)v.isIdentifier(s.id)&&(v.isJSXElement(s.init)||v.isJSXFragment(s.init))&&r.push(...Yt(s.init,t,n))}continue}r.push(...Ia(o,t,n))}return r}function Ia(e,t,n){if(v.isReturnStatement(e))return e.argument?Yt(e.argument,t,n):[];if(v.isBlockStatement(e))return Nn(e.body,t,n);if(v.isIfStatement(e)){let r=v.isBlockStatement(e.consequent)?Nn(e.consequent.body,t,n):Ia(e.consequent,t,n),o=e.alternate?v.isBlockStatement(e.alternate)?Nn(e.alternate.body,t,n):Ia(e.alternate,t,n):[];return[...r,...o]}if(v.isSwitchStatement(e))return Nn(e.cases.flatMap(r=>r.consequent),t,n);if(v.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 Rd(e,t,n)}finally{t.valueScopes.pop()}}function hi(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:Ge(r),sourceCandidates:i&&i.length>0?i:void 0})}function WS(e,t,n,r){let o=VS(e.openingElement,["items","dataSource","data"]),i={key:t,tag:Ed(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!v.isJSXAttribute(s))continue;let a=KS(s);if(!a||!v.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!v.isJSXEmptyExpression(c)){if(XS(a)&&va(c)){let l=gi(c,n,r),d=Sd(o,c,r,n);hi(n,"repeat-region",t,s,l,d?[d]:void 0);continue}if(zS(a)){let l=va(c)?gi(c,n,r):Yt(c,n,r);hi(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!v.isJSXExpressionContainer(s)||!va(s.expression))continue;let a=gi(s.expression,n,r),c=Sd(o,s.expression,r,n);hi(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function yi(e,t,n){let r=Ed(e.openingElement);if(r==="Fragment"||Ca(e))return bi(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=RS(r),a;if(s){let C=t.ordinalTracker.getOrdinal(i,r);a=`component:${r}#${C}`}else{let C=t.ordinalTracker.getOrdinal(i,r);a=`${r}#${C}`}let c=o?t.elements.get(o.key)?.identity.structuralPath:void 0,l=c?`${c}/${a}`:a,d=Ar(t.file,t.componentName,l),f={file:t.file,component:t.componentName,structuralPath:l,key:d},m=s?"component-boundary":null,u=_S(e.children,t,n),g=MS(e.openingElement,t,n),h=OS(e.openingElement,t,n),b,E,y=!1;if(s){let C=t.importMap.get(r)??t.importMap.get(wS(r));C&&(b=C.specifier,E=C.exportName,y=kn(C.specifier,t.file))}let k={identity:f,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:Ge(e),parentKey:i,childKeys:[],textSegments:u,attributes:g.length>0?g:void 0,attributeSpreads:h.length>0?h:void 0,boundaryKind:m,isOpaque:s,...y?{isPublicUiComponent:!0}:{},importedFrom:b,exportName:E};return t.elements.set(d,k),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(d),WS(e,d,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:d,tag:r}),HS(e.children,t,n),t.parentStack.pop()),d}function xi(e,t,n){return bi(e.children,t,n)}function bi(e,t,n){let r=[];for(let o of e)if(v.isJSXElement(o))if(Ca(o))r.push(...bi(o.children,t,n));else{let i=yi(o,t,n);i&&r.push(i)}else rr(o)?r.push(...xi(o,t,n)):v.isJSXExpressionContainer(o)&&r.push(...Si(o.expression,t,n));return r}function HS(e,t,n){for(let r of e)v.isJSXElement(r)?yi(r,t,n):rr(r)?xi(r,t,n):v.isJSXExpressionContainer(r)&&Si(r.expression,t,n)}function GS(e){return e==="&&"||e==="||"||e==="??"}function Si(e,t,n){if(v.isJSXEmptyExpression(e))return[];let r=JS(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,c={kind:"repeat-template",collectionExpression:Et(r.collection,n),collectionSource:$e(r.collection,n,t)};if(v.isArrowFunctionExpression(a)||v.isFunctionExpression(a)){let d=a.params[0],f=a.params[1];v.isIdentifier(d)&&(c.itemParamName=d.name),v.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),(v.isArrowFunctionExpression(a)||v.isFunctionExpression(a))&&l.childKeys.push(...gi(a,t,n)),l.childKeys}if(v.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:Et(e.test,n),conditionSource:$e(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Ge(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Yt(e.consequent,t,n)),s.childKeys.push(...Yt(e.alternate,t,n)),s.childKeys}if(v.isLogicalExpression(e)&&GS(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:Et(e.left,n),conditionSource:$e(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Ge(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Yt(e.right,t,n)),s.childKeys}if(v.isParenthesizedExpression(e))return Si(e.expression,t,n);if(v.isJSXElement(e)){let o=yi(e,t,n);return o?[o]:[]}return rr(e)?xi(e,t,n):[]}function YS(e){let t=e.argument;return t&&(v.isExpression(t)||rr(t))?t:null}function Lr(e,t){let n=[];for(let r of e){if(v.isReturnStatement(r)){let o=YS(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(v.isIfStatement(r)){let o=v.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...Lr(o,r.test)),r.alternate){let i=v.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...Lr(i,r.test))}continue}if(v.isSwitchStatement(r))for(let o of r.cases){let i=o.test?v.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...Lr(o.consequent,i))}}return n}function Ei(e){return{routeId:e,rootKeys:[],elements:new Map,regions:[],fileIndex:new Map,version:1,diagnostics:[]}}function wd(e){let{file:t,source:n,ast:r}=e,o=e.imports.map(m=>m.specifier);if(!v.traverseFast(r,m=>{if(v.isJSXElement(m)||v.isJSXFragment(m))return v.traverseFast.stop}))return{graph:Ei(t),localImports:o};let s=new Map,a=[],c=[],l=new Map,d=AS(r);CS(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(m){let u=NS(m);if(!u)return;let g=m.node,h=[];if(v.isArrowFunctionExpression(g))v.isExpression(g.body)||rr(g.body)?h=[{argument:g.body,statement:v.returnStatement(v.isExpression(g.body)?g.body:null)}]:v.isBlockStatement(g.body)&&(h=Lr(g.body.body));else{let N=g.body;v.isBlockStatement(N)&&(h=Lr(N.body))}if(h.length===0){m.skip();return}let b=new Map;ka(FS(r.program.body),Ea(t,u,s,a,d,[b]),b);let E=new Map;for(let N of g.params)for(let T of Gt(N))Ra(E,T);let y=v.isBlockStatement(g.body)?g.body.body:[],k=h[0]?.statement??null;for(let N of y){if(k&&N===k)break;v.isVariableDeclaration(N)&&ka([N],Ea(t,u,s,a,d,[b,E]),E)}let C=Ea(t,u,s,a,d,[b,E]);for(let N of h){let T=Yt(N.argument,C,n);for(let R of T)c.includes(R)||c.push(R);if(N.condition){let R={kind:"conditional-branch",conditionExpression:Et(N.condition,n),conditionSource:$e(N.condition,n,C)};hi(C,"conditional-region","",N.statement,T,[R])}}m.skip()}});let f=[...s.keys()];return f.length>0&&l.set(t,f),{graph:{routeId:t,rootKeys:c,elements:s,regions:a,fileIndex:l,version:1,diagnostics:[]},localImports:o}}function wa(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function vi(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function ZS(e,t){if(e.length===0)return[];if(e.length===1)return[await t(e[0])];let n=new Array(e.length),r=0,o=Array.from({length:Math.min(8,e.length)},async()=>{for(;r<e.length;){let s=r++;n[s]=await t(e[s])}}),i=await Promise.allSettled(o);for(let s of i)if(s.status==="rejected")throw s.reason;return n}async function Nd(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??Jt,c=new Map,l=new Map,d=new Map,f=[],m=new Set,u=E=>{let y=`${E.path}\0${E.code}\0${E.message}\0${JSON.stringify(E.details??{})}`;m.has(y)||(m.add(y),f.push(E))},g=[{file:e,source:t,depth:0,diagnosticEntryFile:e,importStack:[]},...(o.additionalEntries??[]).map(E=>({file:E.file,source:E.source,depth:0,diagnosticEntryFile:E.file,importStack:[]}))],h=new Set;for(;g.length>0;){let E=g.shift(),{file:y,source:k,depth:C,diagnosticEntryFile:N,importStack:T}=E;if(h.has(y))continue;h.add(y),c.set(y,k);let R=o.validationOnly&&C<i?o.validatedImports?.(y,k):void 0,A,M;if(R)A=Ei(y),M=R;else{let L=a(y,k);if(!L.ok){u(vi(L.diagnostic,N,T));continue}d.set(y,L.module);let ee=o.validationOnly&&C<i?{graph:Ei(y),localImports:L.module.imports.map(ge=>ge.specifier)}:wd(L.module);A=ee.graph,M=ee.localImports}for(let L of A.elements.values())if(L.importedFrom&&Pt(L.importedFrom)){let ee=L.importedFrom,ge=await Oo(y,ee,r);ge.ok?(L.importedFrom=ge.path,Xt(ge.path)&&(L.isPublicUiComponent=!0)):kn(ee,y)||u(vi(ge.diagnostic,N,wa(T,y,ee,ge.diagnostic.path)))}if(l.set(y,A),C>=i)continue;let D=await ZS(M,async L=>{if(lu(L))return null;let ee=await Oo(y,L,r);if(!ee.ok)return kn(L,y)?null:{diagnostic:vi(ee.diagnostic,N,wa(T,y,L,ee.diagnostic.path))};let ge=ee.path;if(h.has(ge)||Xt(ge))return null;let se=wa(T,y,L,ge);try{let oe=await n(ge);return{entry:{file:ge,source:oe,depth:C+1,diagnosticEntryFile:N,importStack:se}}}catch(oe){return{diagnostic:vi({path:ge,code:"import-read-failed",message:`Failed to read imported file: ${ge}`,details:{fromFile:y,specifier:L,reason:oe instanceof Error?oe.message:String(oe)}},N,se)}}});for(let L of D)L&&"entry"in L?g.push(L.entry):L&&u(L.diagnostic)}let b=QS(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 QS(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}}function Pd(e=256){if(!Number.isSafeInteger(e)||e<1)throw new RangeError("Validated syntax capacity must be positive.");let t=new Map;return{remember(n){for(let r of n)t.get(r.file)?.source!==r.source&&(t.delete(r.file),t.size>=e&&t.delete(t.keys().next().value),t.set(r.file,{source:r.source,imports:Object.freeze(r.imports.map(o=>o.specifier))}))},getImports(n,r){let o=t.get(n);return o?.source===r?o.imports:void 0},clear(){t.clear()}}}import{SiteEditHistoryProvenanceSchema as wE}from"@vcp-dev/contracts";import{createHash as qS,randomUUID as Da}from"node:crypto";import Me from"node:fs/promises";import Le from"node:path";var jd=new WeakMap;function or(e){return jd.get(e)?.()??e.readIndex()}var gt=1,Pa=1,eE=2,tE="index.json",nE="recovery.json",rE="transaction-journal.json",oE="document-version.json",Ci={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},ne={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"},ie=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};function Zt(){return{entries:new Map,blobSizes:new Map}}function ki(e,t){let n={entries:new Map,blobs:new Map,objectBytes:0};for(let r of e)$d(n,r,t);return n}function $d(e,t,n){let r=e.entries.get(t);if(r){e.entries.set(t,{...r,references:r.references+1});return}let o=n.entries.get(t),i=new Map(o.entry.blobs.map(s=>[s.digest,n.blobSizes.get(s.digest)]));e.entries.set(t,{sizeBytes:o.sizeBytes,references:1,blobs:i}),e.objectBytes+=o.sizeBytes;for(let[s,a]of i){let c=e.blobs.get(s);e.blobs.set(s,{sizeBytes:a,references:(c?.references??0)+1}),c||(e.objectBytes+=a)}}function Vd(e,t){let n=e.entries.get(t);if(n.references>1){e.entries.set(t,{...n,references:n.references-1});return}e.entries.delete(t),e.objectBytes-=n.sizeBytes;for(let r of n.blobs.keys()){let o=e.blobs.get(r);o.references>1?e.blobs.set(r,{...o,references:o.references-1}):(e.blobs.delete(r),e.objectBytes-=o.sizeBytes)}}async function Kd(e,t={}){let n=EE(e),r=CE(t.limits),o=Na(n),i=vE(n),s=await tt(i),a=await tt(o)||s;a||(await pE(n),await mE(n)),a||await RE(n);let c=Zt(),l=await wi(n,c),d=new Set(a?(await Fi(n)).map(y=>y.stageId):[]);a||await Md(n,l.entryIds,c);let f=l.digest,m=ki(l.entryIds,c),u=async y=>{let{index:k,sizeBytes:C}=await Vr(n);if(Gd(k,y),k.digest!==f){let N=Zt();await zd(n,k.entryIds,N,C),m=ki(k.entryIds,N),f=k.digest}return{..._i(k),totalBytes:m.objectBytes+C}},g=async y=>{Ba(y),await u(),await Fd(n,m,[y.entryId],y.blobIds,y.stageId),await Ri(n,y.stageId)},h=async(y,k)=>{let C=await u(k);Jd(y,C.entryIds.length);let N=Zt();for(let T of C.entryIds.slice(Math.min(C.cursor,y)+1,Math.max(C.cursor,y)+1))await Br(n,T,N);return C},b=async()=>{if(await tt(o)||s)throw new ie(ne.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")},E={rootDir:n,recoveryRequired:a,async readDocumentVersion(){return Dd(n)},async writeDocumentVersion(y){if(await b(),!Number.isInteger(y)||y<0)throw new ie(ne.INVALID_SCHEMA,"document version must be a non-negative integer");let k=await Dd(n);y<=k||await Dr(qd(n),{schemaVersion:1,version:Math.max(k,y)})},async stageAppend(y,k={}){await b();let C=await aE(y,r),N={schemaVersion:Pa,stageId:Da(),entryId:C.entryId,blobIds:C.blobs.map(T=>T.digest)};try{await cE(n,C),await uE(n,N,k.durableManifest!==!1)}catch(T){try{await g(N)}catch(R){throw new ie(ne.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:R})}throw T}return{stageId:N.stageId,entryId:N.entryId,blobIds:N.blobIds}},async discardStage(y){await b(),Fa(y);let k=await Aa(n,y);k&&await g(k)},async previewStagedAppend(y,k){await b();let C=await u(k);return(await Ad(n,r,y,C,m)).transition},async previewCursor(y,k){await b();let C=await h(y,k);return Ud(C,C.entryIds,y)},async publishStagedAppend(y,k,C){if(await b(),Pi(y,"entryId"),C){Fa(C);let M=await Aa(n,C);if(!M||M.entryId!==y)throw new ie(ne.INVALID_SCHEMA,"history stage does not match the published entry")}let N=await u(k),T=m,R=await Ad(n,r,y,N,T),A=await Ld({rootDir:n,previousDigest:R.current.digest,entryIds:R.entryIds,cursor:R.cursor,readback:async()=>Od(n,R.usage),afterWrite:async()=>{C?await Ri(n,C):await fE(n,y),await Fd(n,R.usage,[...T.entries.keys()].filter(M=>!R.usage.entries.has(M)),[...T.blobs.keys()].filter(M=>!R.usage.blobs.has(M)))}});return m=R.usage,f=A.digest,A},async append(y){await b();let k=await u(),C=await E.stageAppend(y);try{return await E.publishStagedAppend(C.entryId,k.digest,C.stageId)}catch(N){throw await E.discardStage(C.stageId),N}},async readEntry(y){return Pi(y,"entryId"),Br(n,y)},async readBlob(y){Pi(y,"blobId");let k=await tf(n,y),C=await jr(k,ne.NOT_FOUND,"blob");return Qd(C,y,k),C},async readIndex(){let y=Zt(),k=await wi(n,y);return m=ki(k.entryIds,y),f=k.digest,k},async readStatus(){let y=await Ni(n);return{canUndo:y.undoIds.length>0,canRedo:y.redoIds.length>0,undoDepth:y.undoIds.length,redoDepth:y.redoIds.length,cursor:y.cursor,recoveryRequired:await tt(o)||await tt(i)}},async readUndoRedoIds(){let y=await Ni(n);return{undoIds:y.undoIds,redoIds:y.redoIds,currentId:y.currentId}},async setCursor(y,k){await b();let C=await h(y,k),N=await Ld({rootDir:n,previousDigest:C.digest,entryIds:C.entryIds,cursor:y,readback:async()=>Od(n,m)});return f=N.digest,N},async markRecoveryRequired(y){await tt(o)||await Dr(Na(n),{schemaVersion:gt,reason:kE(y),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await Me.rm(Na(n),{force:!0})},async readTransactionJournal(){return await tt(i)?Ii(i):null},async writeTransactionJournal(y){await b(),ef(y);try{await Dr(i,y)}catch(C){let N=await Ii(i).catch(()=>null);if(N&&Buffer.from(nt(N)).equals(Buffer.from(nt(y))))return;throw N?new ie(ne.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:C}):C}let k=await Ii(i);if(!Buffer.from(nt(k)).equals(Buffer.from(nt(y))))throw new ie(ne.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(y){let k=await tt(i)?await Ii(i):null;if(k&&k.transactionId!==y)throw new ie(ne.INVALID_SCHEMA,"transaction journal changed concurrently");try{await Me.rm(i,{force:!0})}catch(C){if(!await tt(i))return;throw C}if(await tt(i))throw new ie(ne.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await b();for(let C of d)await Ri(n,C),d.delete(C);await gE(n);let y=Zt(),k=await wi(n,y);await Md(n,k.entryIds,y),m=ki(k.entryIds,y),f=k.digest}};return jd.set(E,()=>Ni(n)),E}async function Ad(e,t,n,r,o){Pi(n,"entryId");let i=Zt(),s=await Br(e,n,i),a={entries:new Map(o.entries),blobs:new Map(o.blobs),objectBytes:o.objectBytes},c=r.entryIds.slice(0,r.cursor+1);for(let d of r.entryIds.slice(r.cursor+1))Vd(a,d);$d(a,s.id,i),c.push(s.id);let l=lE(c,t,a);return{current:r,entryIds:l.entryIds,cursor:l.cursor,usage:a,transition:Ud(r,l.entryIds,l.cursor)}}function Ud(e,t,n){return Jd(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:iE(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function iE(e,t){return ln(nt({schemaVersion:gt,entryIds:e,cursor:t}))}function Jd(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new ie(ne.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function sE(e){if(!vt(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!at(e.expectedIndexDigest)||!at(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!at(n)?!1:t===-1?n===null:at(n)}async function aE(e,t){if(!e.kind.trim())throw new ie(ne.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new ie(ne.INVALID_JSON,"history blob name must not be empty");let l=SE(c.data),d=ln(l);n.push({name:c.name,bytes:l,digest:d,sizeBytes:l.byteLength}),r.push({name:c.name,digest:d,sizeBytes:l.byteLength})}let o={schemaVersion:gt,kind:e.kind,manifest:e.manifest,blobs:r},i=nt({...o}),s=ln(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new ie(ne.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function cE(e,t){let n=Ka(e,t.entryId),r={id:t.entryId,...t.entryBody},o=[...t.blobs.map(a=>Td(Ua(e,a.digest),a.bytes,{kind:"blob",digest:a.digest},Xa(e,a.digest))),Td(n,nt(r),{kind:"entry",digest:t.entryId},Ja(e,t.entryId))],s=(await Promise.allSettled(o)).find(a=>a.status==="rejected");if(s)throw s.reason}async function Td(e,t,n,r){let o=await Oa(e)??(r?await Oa(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new ie(n.kind==="blob"?ne.BLOB_CORRUPT:ne.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await Yd(e,t)}function lE(e,t,n){let r=[...e],o=r.length-1;for(;;){if(n.objectBytes+nt(Hd(r,o)).byteLength<=t.maxSessionBytes&&r.length<=t.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new ie(ne.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");Vd(n,r.shift()),o-=1}}async function uE(e,t,n){Ba(t);let r=Va(e,t.stageId);if(n){await Dr(r,t);return}await bE(r,t)}async function Aa(e,t){let n=await Oa(Va(e,t));if(n===null)return null;let r=Kr(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=Ba(r);if(o.stageId!==t)throw new ie(ne.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function Fi(e){let t=[];for(let n of await Ti($a(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);Fa(r);let o=await Aa(e,r);o&&t.push(o)}return t}async function Fd(e,t,n,r,o){if(n.length===0&&r.length===0)return;let i=new Set(t.entries.keys()),s=new Set;for(let a of await Fi(e))if(a.stageId!==o){i.add(a.entryId);for(let c of a.blobIds)s.add(c)}for(let a of new Set(n))i.has(a)||await _d(Ka(e,a),Ja(e,a));for(let a of new Set(r))!t.blobs.has(a)&&!s.has(a)&&await _d(Ua(e,a),Xa(e,a));await La(Ur(e)),await La(Jr(e))}async function Ri(e,t){await Ta(Va(e,t)),await dE(e)}async function dE(e){try{await Me.rmdir($a(e))}catch(t){if(Xr(t)||vt(t)&&t.code==="ENOTEMPTY")return;throw t}}async function fE(e,t){for(let n of await Fi(e))n.entryId===t&&await Ri(e,n.stageId)}async function Ta(e){if(await Me.rm(e,{force:!0}),await tt(e))throw new ie(ne.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function _d(e,t){await Ta(e),await Ta(t)}function Ba(e){if(!vt(e)||e.schemaVersion!==Pa||typeof e.stageId!="string"||!Xd(e.stageId)||!at(e.entryId))throw new ie(ne.INVALID_SCHEMA,"history stage schema is invalid");let t=Zd(e.blobIds,"history stage blobIds");return{schemaVersion:Pa,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function Fa(e){if(!Xd(e))throw new ie(ne.INVALID_PATH,"history stageId must be a UUID")}function Xd(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 Md(e,t,n=Zt()){let r=new Set(t),o=new Set;for(let l of t){let d=await Br(e,l,n);for(let f of d.blobs)o.add(f.digest)}for(let l of await Fi(e)){r.add(l.entryId);for(let d of l.blobIds)o.add(d)}let i=Ur(e),s=await Ti(i);for(let l of s){if(!l.endsWith(".json"))continue;let d=Bd(l.slice(0,-5));d&&!r.has(d)&&await Ai(Le.join(i,l))}let a=Jr(e),c=await Ti(a);for(let l of c){let d=Bd(l);d&&!o.has(d)&&await Ai(Le.join(a,l))}}async function wi(e,t=Zt()){let{index:n,sizeBytes:r}=await Vr(e),{totalBytes:o}=await zd(e,n.entryIds,t,r);return{..._i(n),totalBytes:o}}async function Od(e,t){let{index:n,sizeBytes:r}=await Vr(e);return{..._i(n),totalBytes:t.objectBytes+r}}async function Vr(e){let t=ja(e),n=await jr(t,ne.NOT_FOUND,"index"),r=Kr(Buffer.from(n).toString("utf8"),"index");return{index:hE(r),sizeBytes:n.byteLength}}async function Ni(e){return _i((await Vr(e)).index)}function _i(e){let t=[...e.entryIds],n=t.slice(0,e.cursor+1).reverse(),r=t.slice(e.cursor+1);return{schemaVersion:gt,digest:e.digest,entryIds:t,cursor:e.cursor,currentId:t[e.cursor]??null,undoIds:n,redoIds:r}}async function zd(e,t,n,r){let o=0,i=new Set;o+=r??(await Vr(e)).sizeBytes;for(let s of new Set(t)){let a=await Br(e,s,n);o+=n.entries.get(s).sizeBytes;for(let c of a.blobs)i.has(c.digest)||(i.add(c.digest),o+=n.blobSizes.get(c.digest))}return{totalBytes:o}}async function Br(e,t,n=Zt()){let r=n.entries.get(t);if(r)return r.entry;let o=await IE(e,t),i=await jr(o,ne.NOT_FOUND,"entry"),s=Kr(Buffer.from(i).toString("utf8"),`entry ${t}`),a=yE(s);if(a.id!==t)throw new ie(ne.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(ln(nt({schemaVersion:a.schemaVersion,kind:a.kind,manifest:a.manifest,blobs:a.blobs}))!==t)throw new ie(ne.ENTRY_CORRUPT,`entry hash mismatch for ${t}`);for(let l of a.blobs){if(n.blobSizes.has(l.digest))continue;let d=await tf(e,l.digest),f=await jr(d,ne.NOT_FOUND,"blob");Qd(f,l.digest,d),n.blobSizes.set(l.digest,f.byteLength)}return n.entries.set(t,{entry:a,sizeBytes:i.byteLength}),a}async function Wd(e,t,n){await Dr(ja(e),Hd(t,n))}function Hd(e,t){return{schemaVersion:gt,digest:ln(nt({schemaVersion:gt,entryIds:e,cursor:t})),entryIds:e,cursor:t}}function Gd(e,t){if(t!==void 0&&e.digest!==t)throw new ie(ne.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function Ld(e){Gd(await Ni(e.rootDir),e.previousDigest);let t=ln(nt({schemaVersion:gt,entryIds:e.entryIds,cursor:e.cursor}));try{await Wd(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.();let n=await e.readback();if(n.digest!==t)throw new ie(ne.INDEX_CORRUPT,"history index readback did not match the published transition");return n}catch(n){let r=await wi(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new ie(ne.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function pE(e){await Me.mkdir(e,{recursive:!0}),await Me.mkdir(Ur(e),{recursive:!0}),await Me.mkdir(Jr(e),{recursive:!0}),await Me.mkdir($r(e),{recursive:!0})}async function mE(e){await Me.rm($r(e),{recursive:!0,force:!0}),await Me.mkdir($r(e),{recursive:!0})}async function gE(e){let t=$r(e);await Me.mkdir(t,{recursive:!0});for(let n of await Ti(t))n!=="stages"&&await Me.rm(Le.join(t,n),{recursive:!0,force:!0})}function hE(e){if(!vt(e))throw new ie(ne.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==gt)throw new ie(ne.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=Zd(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new ie(ne.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!at(o))throw new ie(ne.INDEX_CORRUPT,"index digest is invalid");let i=ln(nt({schemaVersion:gt,entryIds:t,cursor:r}));if(o!==i)throw new ie(ne.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:gt,digest:o,entryIds:t,cursor:r}}function yE(e){if(!vt(e))throw new ie(ne.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==gt)throw new ie(ne.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!at(t))throw new ie(ne.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new ie(ne.ENTRY_CORRUPT,"entry kind is invalid");let r=Ma(e.manifest,"entry.manifest"),o=xE(e.blobs);return{id:t,schemaVersion:gt,kind:n,manifest:r,blobs:o}}function xE(e){if(!Array.isArray(e))throw new ie(ne.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!vt(t))throw new ie(ne.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new ie(ne.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!at(o))throw new ie(ne.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new ie(ne.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function Dr(e,t){await Yd(e,nt(t))}async function bE(e,t){let n=Le.dirname(e),r=Le.basename(e),o=Le.join(n,`.${r}.${process.pid}.${Da()}.tmp`);await Me.mkdir(n,{recursive:!0});try{await Me.writeFile(o,nt(t),{flag:"wx"}),await Me.rename(o,e)}finally{await Ai(o)}}async function Yd(e,t){let n=Le.dirname(e),r=Le.basename(e),o=Le.join(n,`.${r}.${process.pid}.${Da()}.tmp`);await Me.mkdir(n,{recursive:!0});try{let i=await Me.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await Me.rename(o,e),await La(n)}finally{await Ai(o)}}function nt(e){return Buffer.from(JSON.stringify(_a(e)),"utf8")}function _a(e){if(Array.isArray(e))return e.map(t=>_a(t));if(vt(e)){let t={};for(let n of Object.keys(e).sort())t[n]=_a(e[n]);return t}return e}function Kr(e,t){try{return JSON.parse(e)}catch(n){throw new ie(ne.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function Ma(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=>Ma(n,t));if(vt(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=Ma(o,t);return n}break}throw new ie(ne.INVALID_JSON,`${t} must be JSON-serializable`)}function Zd(e,t){if(!Array.isArray(e))throw new ie(ne.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!at(n))throw new ie(ne.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function Pi(e,t){if(!at(e))throw new ie(ne.INVALID_PATH,`${t} must be a sha256 digest`)}function at(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function ln(e){return`sha256:${qS("sha256").update(e).digest("hex")}`}function SE(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function jr(e,t,n){try{return await Me.readFile(e)}catch(r){throw new ie(t,`${n} not found: ${e}`,{cause:r})}}async function Oa(e){try{return await Me.readFile(e)}catch(t){if(Xr(t))return null;throw t}}function Qd(e,t,n){if(ln(e)!==t)throw new ie(ne.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function tt(e){try{return await Me.access(e),!0}catch(t){if(Xr(t))return!1;throw t}}async function Ai(e){try{await Me.rm(e,{force:!0,recursive:!0})}catch{}}async function La(e){try{let t=await Me.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function Ti(e){try{return await Me.readdir(e)}catch(t){if(Xr(t))return[];throw t}}function EE(e){if(typeof e!="string"||e.trim().length===0)throw new ie(ne.INVALID_ROOT,"history store rootDir must be a non-empty string");return Le.resolve(e)}function ja(e){return Le.join(e,tE)}function Na(e){return Le.join(e,nE)}function vE(e){return Le.join(e,rE)}function qd(e){return Le.join(e,oE)}async function Dd(e){try{let t=await Me.readFile(qd(e),"utf8"),n=Kr(t,"document version");if(!vt(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new ie(ne.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(Xr(t))return 0;throw t}}async function Ii(e){let t=await jr(e,ne.RECOVERY_PENDING,"transaction journal"),n=Kr(Buffer.from(t).toString("utf8"),"transaction journal");return ef(n),n}function ef(e){if(!vt(e)||e.schemaVersion!==eE||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!sE(e.historyTransition)||!Array.isArray(e.files))throw new ie(ne.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!vt(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!at(t.preDigest)||t.postDigest!==null&&!at(t.postDigest))throw new ie(ne.INVALID_SCHEMA,"transaction journal file digest is invalid")}function kE(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function Ur(e){return Le.join(e,"entries")}function Jr(e){return Le.join(e,"blobs")}function $r(e){return Le.join(e,"tmp")}function $a(e){return Le.join($r(e),"stages")}function Va(e,t){return Le.join($a(e),`${t}.json`)}function Ka(e,t){return Le.join(Ur(e),`${rf(t)}.json`)}function Ua(e,t){return Le.join(Jr(e),rf(t))}function Ja(e,t){return Le.join(Ur(e),`${t}.json`)}function Xa(e,t){return Le.join(Jr(e),t)}async function IE(e,t){return nf(Ka(e,t),Ja(e,t))}async function tf(e,t){return nf(Ua(e,t),Xa(e,t))}async function nf(e,t){return await tt(e)?e:await tt(t)?t:e}function rf(e){return e.slice(7)}function Bd(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return at(t)?t:null}function vt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xr(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function CE(e){return{maxEntries:e?.maxEntries??Ci.maxEntries,maxSessionBytes:e?.maxSessionBytes??Ci.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??Ci.maxEntryBytes}}async function RE(e){let t=ja(e);await tt(t)||await Wd(e,[],-1)}var NE={affectedCompositions:[]};function lf(e){let t=null,n=new WeakMap;async function r(){return t??=PE(e),t}async function o(i){if(!i)return null;let s=za(i);return s?AE(e,s):i}return{async prepareAppend(i){let s=await or(e),a=await e.stageAppend(af(i),{durableManifest:!1}),c;try{c=await e.previewStagedAppend(a.entryId,s.digest)}catch(d){throw await e.discardStage(a.stageId),d}let l={kind:"append",entry:i,historyTransition:c};return n.set(l,{expectedDigest:s.digest,stageId:a.stageId,entryId:a.entryId}),l},async prepareUndo(){let i=await r(),s=await o(i.undo.at(-1));if(!s?.historyId)return null;let a=await or(e),c=a.entryIds.indexOf(s.historyId);if(c<0)throw new Error("undo entry is missing from index");if(c!==a.cursor)throw new Error("undo state changed before prepare");let l=c-1,d=await e.previewCursor(l,a.digest),f={kind:"undo",entry:s,historyTransition:d};return n.set(f,{expectedDigest:a.digest,cursor:l}),f},async prepareRedo(){let i=await r(),s=await o(i.redo.at(-1));if(!s?.historyId)return null;let a=await or(e),c=a.entryIds.indexOf(s.historyId);if(c<0)throw new Error("redo entry is missing from index");if(c!==a.cursor+1)throw new Error("redo state changed before prepare");let l=c,d=await e.previewCursor(l,a.digest),f={kind:"redo",entry:s,historyTransition:d};return n.set(f,{expectedDigest:a.digest,cursor:l}),f},async publishPrepared(i){let s=n.get(i);if(!s)throw new Error("history mutation was not prepared");let a=await r();if(i.kind==="append"){if(!s.entryId)throw new Error("staged entry id is missing");let c=await e.publishStagedAppend(s.entryId,s.expectedDigest,s.stageId);of(c,i.historyTransition),i.entry.historyId=s.entryId,Object.assign(a,ir(c))}else{if(s.cursor===void 0)throw new Error("prepared cursor is missing");let c=i.kind==="undo"?a.undo:a.redo;if(za(c.at(-1))!==za(i.entry))throw new Error("history state changed before publish");let l=await e.setCursor(s.cursor,s.expectedDigest);of(l,i.historyTransition),Object.assign(a,ir(l))}n.delete(i)},async discardPrepared(i){let s=n.get(i);if(!s)return;let a=i.historyTransition;if(a){let c=await or(e);if(c.digest===a.publishedIndexDigest&&c.cursor===a.publishedCursor&&c.currentId===a.publishedCurrentId)throw new Error("cannot discard a history mutation whose index was published")}s.stageId&&await e.discardStage(s.stageId),n.delete(i)},async peekUndo(){return o((await r()).undo.at(-1))},async pushUndo(i){let s=await r(),a=i;if(a.historyId){let d=s.entryIds.indexOf(a.historyId);if(d>=0)try{let f=await e.setCursor(d);Object.assign(s,ir(f));return}catch(f){throw s.redo.push(i),f}}let c=await e.append(af(i)),l=c.currentId;if(!l)throw new Error("history store did not publish an entry");i.historyId=l,Object.assign(s,ir(c))},async popUndo(){let i=await r(),s=await o(i.undo.at(-1));return i.undo.pop(),s},async peekRedo(){return o((await r()).redo.at(-1))},async pushRedo(i){let s=await r(),a=i;if(!a.historyId)throw s.undo.push(i),new Error("cannot move an unpersisted history entry to redo");let c=s.entryIds.indexOf(a.historyId);if(c<0)throw s.undo.push(i),new Error("history entry is missing from the durable index");try{let l=await e.setCursor(c-1);Object.assign(s,ir(l))}catch(l){throw s.undo.push(i),l}},async popRedo(){let i=await r(),s=await o(i.redo.at(-1));return i.redo.pop(),s},async clearRedo(){(await r()).redo.length=0},async getStatus(){let i=await e.readStatus();return{canUndo:i.canUndo,canRedo:i.canRedo,undoDepth:i.undoDepth,redoDepth:i.redoDepth,recoveryRequired:i.recoveryRequired}},async markRecoveryRequired(i){await e.markRecoveryRequired(i)}}}function of(e,t){if(!t)throw new Error("durable history transition is missing");if(e.digest!==t.publishedIndexDigest||e.cursor!==t.publishedCursor||e.currentId!==t.publishedCurrentId)throw new Error("durable history published an unexpected index state")}function za(e){return typeof e=="string"?e:e?.historyId}async function PE(e){let t=await or(e);return ir(t)}function ir(e){return{undo:[...e.undoIds].reverse(),redo:[...e.redoIds].reverse(),entryIds:[...e.entryIds],cursor:e.cursor}}async function AE(e,t){let n=await e.readEntry(t),r=TE(n),o=r.provenance??NE;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 sf(e,n,r.preSnapshots),postSnapshots:await sf(e,n,r.postSnapshots)}}async function sf(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(ME(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function af(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=FE(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 TE(e){if(!df(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:uf(t.provenance)}:{},preSnapshots:cf(t.preSnapshots,"preSnapshots"),postSnapshots:cf(t.postSnapshots,"postSnapshots")}}function FE(e){if(e.provenance!==void 0)return uf(e.provenance);if(e.composition)return{initiatingComposition:e.composition,affectedCompositions:[]}}function uf(e){let t=wE.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 cf(e,t){return e.map((n,r)=>{if(!df(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&&!_E(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 _E(e){return/^sha256:[0-9a-f]{64}$/.test(e)}function ME(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function df(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{randomBytes as GE}from"node:crypto";import Oi from"node:path";import{parse as Ef}from"@babel/parser";import YE from"@babel/traverse";import*as vf from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as Ha,PageResourceArtifactSchema as ZE,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as QE,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as qE,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as ev,parseComponentI18nResourcesJson as tv}from"@vcp-dev/contracts";var pf=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,mf=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,OE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,LE=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,DE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,BE=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,jE=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,$E=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,VE=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,KE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,UE=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,JE=/\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,XE=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,zE=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function zr(e,t){let n=Mi([...ht(e,OE),...ht(e,LE),...ht(e,DE),...ht(e,t.includeRgbBackgroundImage?BE:jE),...t.includeExtendedColorFunctions?[...ht(e,$E),...ht(e,VE)]:[]]),r=Mi([...ht(e,KE),...ht(e,UE)]).filter(o=>t.colorMixPolicy==="always"||pf.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...ht(e,JE).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...ht(e,zE).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:Mi(ht(e,mf)),hardCodedSurfaceOccurrences:HE(e),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?Mi(ht(e,XE)):[]}}function ht(e,t){return e.match(new RegExp(t.source,t.flags))??[]}var ff=160,WE=/((?:[a-z][a-z0-9-]*(?:\[[^\]]*\])?:)+)$/;function HE(e){let t=new RegExp(mf.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>ff?`${u.slice(0,ff-1)}\u2026`:u})}return o}function Mi(e){return[...new Set(e)]}var Ga="{{$INSTANCE}}",nv=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,rv=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,Ya="components/site/generated",ov=/\.(?:tsx?|json)$/,iv=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,sv=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],av=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Wa=YE,cv=typeof Wa=="function"?Wa:Wa.default;async function Za(e){let t=ZE.safeParse(e.artifact);if(!t.success)return Te("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>GE(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=yv(r());if(!i)return Te("Random instance suffix must be 8 lowercase hex chars.");let s=`${xv(n.resource_id)}-${i}`,a=new Map,c=new Map,l=[];for(let k of n.pages){let C=k.final_route.slice(1);a.set(k.template_page_id,k.final_route),c.set(k.template_page_id,k.title),l.push({template_page_id:k.template_page_id,title:k.title,final_route:k.final_route,route_file_path:`app/${C}/page.tsx`})}let d=[],f=new Set,m=new Set,u=new Map,g=new Map,h=[],b=new Set(n.pages.flatMap(k=>k.components.map(C=>C.component_id)));for(let k of n.components){if(!b.has(k.component_id))continue;let C=gf({materialization:k.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c});if(!C.ok)return C;for(let N of C.files){let T=yf(N,f,d);if(T)return T}m.add(C.entry),g.set(C.entry,C.entryExport),u.set(k.component_id,C.entry)}for(let[k,C]of n.pages.entries()){let N=l[k],T=gf({materialization:C.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c,pageEntryTarget:N.route_file_path,pageTitle:N.title});if(!T.ok)return T;for(let R of T.files){let A=yf(R,f,d);if(A)return A}m.add(T.entry),g.set(T.entry,T.entryExport),h.push({entry:T.entry,declaredComponentIds:new Set(C.components.map(R=>R.component_id))})}let E=uv(d,m,s,u,h,g);if(!E.ok)return E;for(let k of d)if(await e.exists(k.file))return!k.file.startsWith("app/")&&o>1?Za({...e,randomHex:r,maxAttempts:o-1}):{ok:!1,code:"MATERIALIZATION_CONFLICT",message:`Page resource create-only target already exists: ${k.file}`,path:k.file};let y=dv(d);return y||(d.sort((k,C)=>k.file.localeCompare(C.file)),{ok:!0,packageInstanceId:s,pages:l,files:d})}function gf(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:hf(o.pathTemplate,e.packageInstanceId);if(!s)return Te("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=lv(o.content,e.packageInstanceId,e.routeByPage,e.titleByPage);if(!a.ok)return a;let c=i&&e.pageTitle!==void 0?pv(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??hf(t,e.packageInstanceId);return!r||!n.some(o=>o.file===r)?Te("Materialization entry must match one controlled source file.",t):{ok:!0,files:n,entry:r,entryExport:e.materialization.entry.export}}function lv(e,t,n,r){let o,i=e.replace(nv,(c,l)=>{let d=n.get(l);return d||(o=l,c)});if(o)return Te(`Page route placeholder references unknown template page: ${o}`);let s=i.replace(rv,(c,l)=>{let d=r.get(l);return d?JSON.stringify(d):(o=l,c)});if(o)return Te(`Page title placeholder references unknown template page: ${o}`);let a=s.replaceAll(Ga,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?Te("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function hf(e,t){let n=`${Ya}/${t}`;if(e.split(Ga).length>2)return null;let o=e.replace(Ga,t),i=`${Ya}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=Oi.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!ov.test(a)||iv.test(a)?null:a}function yf(e,t,n){return t.has(e.file)?Te(`Page resource materializations resolve duplicate target: ${e.file}`,e.file):(t.add(e.file),n.push(e),null)}function uv(e,t,n,r,o,i){let s=new Set(e.map(u=>u.file)),a=`${Ya}/${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 Te("Materialization JSON file must contain valid JSON.",u.file)}if(u.file.endsWith(Ha)&&!tv(u.content).success)return Te("Materialization component i18n resources are invalid.",u.file);continue}try{let h=Ef(u.content,{sourceType:"module",plugins:["jsx","typescript"]});l.set(u.file,h);for(let E of h.program.body)if((E.type==="ImportDeclaration"||E.type==="ExportAllDeclaration"||E.type==="ExportNamedDeclaration"&&E.source)&&E.source){let y=E.source.value,k=gv(u.file,y,s,a);if(!k.allowed)return Te(`Materialization import is outside the controlled package: ${y}`,u.file);k.internalPath&&c.get(u.file).add(k.internalPath)}let b;if(cv(h,{Identifier(E){E.isReferencedIdentifier()&&av.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 Te(`Materialization source uses forbidden capability: ${b}`,u.file)}catch{return Te("Materialization source must parse as TS/TSX.",u.file)}let g=zr(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 Te("Materialization source violates the public theme token policy.",u.file)}if([...t].some(u=>!s.has(u)))return Te("Materialization entry is outside the controlled package.");for(let u of t)if(u.endsWith(".json"))return Te("Materialization JSON files cannot be package entries.");for(let[u,g]of i){let h=l.get(u);if(!h||!fv(h,g))return Te("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=Sf(u.entry,c);for(let h of u.declaredComponentIds){let b=r.get(h);if(!b||!g.has(b))return Te(`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 Te(`Page entry imports undeclared component: ${b}`,u.entry)}}let f=new Set;for(let u of t)for(let g of Sf(u,c))f.add(g);if(f.size!==e.length)return Te("Every materialization file must be reachable from a package entry.");let m=hv(e,l,c);return m||{ok:!0}}function dv(e){if(e.length>QE)return Te("Page resource exceeds the aggregate source file limit.");let t=0;for(let n of e){let r=Buffer.byteLength(n.content,"utf8");if(r>qE)return Te("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>ev?Te("Page resource exceeds the aggregate content byte limit."):null}function fv(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 pv(e,t,n){let r;try{r=Ef(e,{sourceType:"module",sourceFilename:n,plugins:["jsx","typescript"]})}catch{return Te("Page materialization PAGE_SEO must parse as TS/TSX.",n)}for(let o of r.program.body){let i=o.type==="VariableDeclaration"?o:o.type==="ExportNamedDeclaration"&&o.declaration?.type==="VariableDeclaration"?o.declaration:null;if(i)for(let s of i.declarations){if(s.id.type!=="Identifier"||s.id.name!=="PAGE_SEO")continue;let a=xf(s.init);if(a?.type!=="ObjectExpression")return{ok:!0,data:e};let c=a.properties.find(d=>d.type==="ObjectProperty"&&!d.computed&&mv(d.key));if(!c||c.type!=="ObjectProperty")return{ok:!0,data:e};let l=xf(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 xf(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&vf.isExpression(t)?t:null}function mv(e){return e.type==="Identifier"&&e.name==="title"||e.type==="StringLiteral"&&e.value==="title"}function gv(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=bf(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:sv.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=Oi.posix.normalize(Oi.posix.join(Oi.posix.dirname(e),t)),i=bf(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function bf(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 hv(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(Ha))continue;let i=o.file.slice(0,-Ha.length),s=[`${i}.tsx`,`${i}.ts`].find(d=>r.has(d));if(!s)return Te("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 Te("Component i18n resources must have exactly one same-name Client Component static importer.",s)}return null}function Sf(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 yv(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function xv(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"page-resource"}function Te(e,t){return{ok:!1,code:"MATERIALIZATION_REJECTED",message:e,...t?{path:t}:{}}}import{randomBytes as bv}from"node:crypto";import Qt from"node:path";import{parse as Sv}from"@babel/parser";import Ev from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as Li,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as kf,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as vv,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as kv,SiteEditMaterializationSchema as Iv,parseComponentI18nResourcesJson as Cv}from"@vcp-dev/contracts";var ec="components/site/generated",If="{{$INSTANCE}}",Di=5,Rv=/^[a-z][a-z0-9-]{0,48}$/,wv=/^[a-f0-9]{8}$/,Cf=/\.tsx?$/,Nv=/\.json$/,Pv=/\.(?:tsx?|json)$/,Av=/^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/,Tv=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,Fv=["react","react/","next","next/","lucide-react","react-i18next","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],Qa=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),qa=Ev,_v=typeof qa=="function"?qa:qa.default;function Mv(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>kf)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=Xv(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=Iv.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=Kv(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${ec}.`,path:e.generatedRoot}};if(!Tf(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=Nf(r.data.files),s=Nf(e.controlledFiles);if(!zv(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>kf)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>vv)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>kv?{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 Ov(e){let t=Mv(e);if(!t.ok)return t;let n=Object.keys(e.manifest.projectDependencies??{}),r=new Set(e.availableHostDependencies??[]),o=n.find(d=>!Av.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??Fv,...i],a=t.data.generatedRoot,c=Tf(e.manifest.instanceBaseName),l=Math.max(1,Math.min(Di,e.maxAttempts??Di));for(let d=0;d<l;d+=1){let f=Uv(e.instanceNameGenerator?.()??bv(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=_f(a,m),g=Lv({manifest:e.manifest,generatedRoot:a,instanceName:m,instanceRoot:u,allowedExternalImports:s});if(!g.ok)return g;if(!await Dv(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 Af(e){let t=Math.max(1,Math.min(Di,e.maxAttempts??Di));for(let n=0;n<t;n+=1){let r=await Ov({...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 Lv(e){let t=[],n=new Set;for(let i of e.manifest.files){let s=Rf({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=Rf({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=Bv(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 Dv(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function Rf(e){if(e.pathTemplate.split(If).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(If,e.instanceName),n=Jv(t);return n?_f(e.generatedRoot,e.instanceName)!==e.instanceRoot?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab instance root normalization failed.",path:e.pathTemplate}}:n!==e.instanceRoot&&!n.startsWith(`${e.instanceRoot}/`)?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab path must stay under components/site/generated/<instance>.",path:n}}:n!==t?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab path template cannot rely on path normalization semantics.",path:e.pathTemplate}}:n===e.instanceRoot||!Pv.test(n)||Tv.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 Bv(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(Nv.test(f.path)){if(f.path.endsWith(Li)){let g=Cv(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=Sv(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=zr(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(!Cf.test(f.path))continue;let m=s.get(f.path),u=null;if(_v(m,{ImportDeclaration(g){let h=wf({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(Li))){let b=jv({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=wf({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=Pf(g.node);h&&Qa.has(h)&&(u??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h}.`,file:f.path},g.stop())},OptionalMemberExpression(g){let h=Pf(g.node);h&&Qa.has(h)&&(u??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h}.`,file:f.path},g.stop())},Identifier(g){g.isReferencedIdentifier()&&Qa.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(!Cf.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(!$v(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 Vv(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:ec,instanceRoot:"",entry:{path:"",export:{kind:"default"}},files:[]}}}function wf(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=Qt.posix.normalize(Qt.posix.join(Qt.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 jv(e){let t=Qt.posix.dirname(e.importer),n=Qt.posix.dirname(e.imported),r=Qt.posix.basename(e.importer).replace(/\.tsx?$/,""),o=Qt.posix.basename(e.imported).slice(0,-Li.length),i=`./${r}${Li}`;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 $v(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 Vv(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 Kv(e){let t=Ff(e);return t===ec?t:null}function Uv(e){let t=e.trim().toLowerCase();return wv.test(t)?t:null}function Tf(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 Rv.test(t)?t:null}function Ff(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=Qt.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function Jv(e){let t=Ff(e);return!t||t!==e?null:t}function _f(...e){return Qt.posix.join(...e)}function Nf(e){return new Set(e.map(t=>t.pathTemplate))}function Xv(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 zv(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Pf(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 gc}from"node:crypto";import cc from"@babel/traverse";function tc(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 Wv}from"node:crypto";import Mf from"node:path";import*as jf from"@babel/parser";import nc from"@babel/generator";import*as Ue from"@babel/types";var Of=typeof nc=="function"?nc:nc.default;function oc(e){let t=Vf(e);if(t)return{ok:!1,error:t};let n=e.projection,r=ac(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=Yv(n,o),s={jsx:`<${e.component.localName} />`},a=Hv(e);if(i){let u=rc(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??(sc(c,n.container.sourceRange)?n.container.sourceHash:null);if(!c||!l)return Wr("Route page composition does not expose a verifiable container boundary.");let d=Gr(c),f=Df(e.source,d,l,"Route page composition container");if(!f.ok)return f.result;let m=o.anchorSourceRange?Gr(o.anchorSourceRange):void 0;if(m){if(!o.anchorSourceHash)return Wr("Route page composition placement does not expose a verifiable anchor boundary.");let u=Df(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 Hv(e){let t=ek(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 Bi(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=Ir(e.source,"value");if(!t.ok)return An(e.source,t.diagnostic.message);let n=ce(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=sr(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:Of(t.ast,{}).code};let i;try{i=jf.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(Gv(r.node,i,e.action.placement,e.action.replaceOriginal)),{ok:!0,source:Of(t.ast,{}).code})}function Gv(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 ic(e){let t=Vf(e);if(t)return{ok:!1,error:t};let n=e.projection,r=Kf(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(Zv(n,o)){let h=rc(e);return h.ok?e.operation==="remove-node"&&!Lf(n,o.placementUnitKey)?Wr("The last editable page unit cannot be deleted."):e.operation==="move-node"?Wr("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=Gr(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?[]:[Hr(a.diagnostic)]}};if(sr(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=rc(e);return h.ok?Lf(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}}}:Wr("The last editable page unit cannot be deleted."):h.result}if(e.operation==="replace-node")return{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"replace-node",locator:s}}};if(!e.targetPlacement)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Page-unit move requires a target placement.",diagnostics:[]}};if(e.targetPlacement.composition.routeId!==e.routeId||!qv(e.targetPlacement.composition,e.composition))return{ok:!1,error:{code:"CROSS_PAGE_MOVE_UNSUPPORTED",message:"Page-unit move across routes or composition templates is not supported.",diagnostics:[]}};if(e.targetPlacement.documentVersion!==e.expectedDocumentVersion)return{ok:!1,error:{code:"VERSION_STALE",message:"Page-unit target placement belongs to a different document version.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Page-unit target placement belongs to a different document version."}]}};let l=ac(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=Gr(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?[]:[Hr(u.diagnostic)]}};if(sr(e.source,u.match.node.start??null,u.match.node.end??null)!==d.containerSourceHash)return Bf("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=Gr(h),y=Ft(e.source,E);return!y.ok||!y.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:y.ok===!1?y.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:y.ok?[]:[Hr(y.diagnostic)]}}:sr(e.source,y.match.node.start??null,y.match.node.end??null)!==b?Bf("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 Lf(e,t){for(let n of e.placementUnitByKey.values())if(n.placementUnitKey!==t&&n.members.length>0)return!0;return!1}function Yv(e,t){let n=e.placementUnitByKey.get(t.placementUnitKey);return n&&e.container.kind!=="jsx-container"&&sc(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 Zv(e,t){return e.container.kind!=="jsx-container"&&sc(t.sourceRange,e.mutationTarget.sourceRange)&&t.sourceHash===e.mutationTarget.sourceHash}function rc(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?[]:[Hr(r.diagnostic)]}}}:sr(e.source,r.match.node.start??null,r.match.node.end??null)!==t.sourceHash?{ok:!1,result:$f("Route mutation target hash no longer matches the current source.")}:{ok:!0,locator:n,sourceHash:t.sourceHash}}function Df(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?[]:[Hr(o.diagnostic)]}}}:sr(e,o.match.node.start??null,o.match.node.end??null)!==n?{ok:!1,result:$f(`${r} hash no longer matches the current source.`)}:{ok:!0}}function $f(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Wr(e){return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:e,diagnostics:[]}}}function Bf(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Hr(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function Vf(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&&!Qv(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 Qv(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function qv(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function ek(e,t){let n=Mf.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Mf.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Gr(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function sr(e,t,n){return t==null||n==null?null:`sha256:${Wv("sha256").update(e.slice(t,n)).digest("hex")}`}function sc(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 tk=typeof cc=="function"?cc:cc.default;function zf(e){if(!e.ast)return kt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=lk(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=dk(t);if(!n.ok)return kt(e,[n.diagnostic]);let r=n.expression;if(r.isIdentifier()){let o=pk(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(gk(r,t))return kt(e,[Ve("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(r.isNullLiteral())return uc(e,t,"virtual-route-root",r);if(mk(r)){let o=bk({input:e,source:e.source,expression:r});return lc(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()&&!_e(r)&&!un(r)){let o=pc(r),i=Xf({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[o]});return lc(e,t,i,{kind:"virtual-route-root",sourceKind:"jsx-element"},r)}if(r.isJSXElement()||r.isJSXFragment()){let o=yk(r);if(!o.ok)return kt(e,[o.diagnostic]);let i=ar(o.path);if(i.unsupported)return kt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);if(hk(e.source,r,i.members))return uc(e,t,"starter-placeholder",r);let s=r.isJSXFragment()||_e(r);if(i.members.length===0&&s)return uc(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=Xf({input:e,containerKind:a,sourceKind:c,source:e.source,containerPath:o.path,members:i.members});return lc(e,t,l,{kind:a,sourceKind:c},r)}return kt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")])}function ac(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 Kf(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 Wf(e){return e.ok?nk(e.projection):rk(e.projection)}function nk(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)=>Hf(e,d,h,b,e.container.placementKey)),m=f.filter(({member:h})=>h.isBusinessMember).map(({sourceMember:h})=>ik(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:ok(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function rk(e){let t=e.diagnostics.map(sk);return{status:"unsupported",version:e.version,composition:e.composition,reason:ak(e.diagnostics),diagnostics:t}}function ok(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 Hf(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)=>Hf(e,t,a,c,i))]}function ik(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function sk(e){return{code:ck(e),message:e.message}}function ak(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 ck(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 lk(e){let t=null;return tk(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=uk(o.path);i&&(t=i,n.stop())}}),t}function uk(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 dk(e){let t=e.get("body");if(!t.isBlockStatement()){let s=Zr(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(!fk(s))return{ok:!1,diagnostic:Ve("UNSUPPORTED_PAGE_SHAPE","Route guard return shape is not statically safe",{reason:"guard-shape"})};continue}if(Gf(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=Zr(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 fk(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(Gf(o)||Yf(o))return null;return r}function Gf(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 pk(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=Zr(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 mk(e){return e.isConditionalExpression()?Uf(Zr(e.get("consequent")))&&Uf(Zr(e.get("alternate"))):!1}function Uf(e){return!!(e&&(e.isJSXElement()||e.isJSXFragment()||e.isNullLiteral()))}function Zr(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 gk(e,t){if(e.isIdentifier())return Jf(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return Jf(n.node.name,t)}return!1}function Jf(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 hk(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&fc(t)}function fc(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(!fc(t))return!1;continue}if(t.isJSXElement()&&!fc(t))return!1}return!0}function yk(e){let t=e;if(e.isJSXFragment()||_e(e)){let r=Yr(e),o=r[0];if(r.length===1&&o?.isJSXElement()&&un(o))t=o;else return{ok:!0,path:t}}for(;t.isJSXElement()&&un(t);){let r=Yr(t);if(r.length!==1)return{ok:!0,path:t};let o=r[0];if(!o?.isJSXElement()||!un(o))return{ok:!0,path:t};if(Yr(o).length<=1)return{ok:!0,path:t};t=o}return{ok:!0,path:t}}function Yr(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(...Yr(n));continue}n.isJSXElement()&&(_e(n)?t.push(...Yr(n)):t.push(n))}return t}function ar(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:mc(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=ar(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=un(o)?ar(o):null;n||=i?.unsupported??!1,t.push({...pc(o,i?.members),sourceRange:yt(r.node.loc),parentSourceRange:yt(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:mc(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()&&_e(r)){let o=ar(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=un(r)?ar(r):null;n||=o?.unsupported??!1,t.push({...pc(r,o?.members),parentSourceRange:yt(e.node.loc)})}}return{members:t,unsupported:n}}function pc(e,t){let n=e.isJSXElement()&&un(e)?t??ar(e).members:[],r=e.isJSXElement()&&!un(e)&&!_e(e);return{memberKey:mc(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:yt(e.node.loc),businessMemberCount:r?1:Zf(n),parentSourceRange:yt(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:xk(e)}}function un(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name[0]===t.name[0]?.toLowerCase()}function xk(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 Zf(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function ji(e){return e.length===0?0:Math.max(1,Zf(e))}function Xf(e){let t=yt(e.containerPath.node.loc),n=hc(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:ji(e.members)<=1,memberCount:ji(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function bk(e){let t=yt(e.expression.node.loc),n=hc(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 Qf(e,t){let n=yt(t.node.loc),r=hc(e.source,t.node.start,t.node.end);return!n||!r?null:{kind:"expression",documentVersion:e.version,sourceRange:n,sourceHash:r}}function lc(e,t,n,r,o){let i=Qf(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=Sk(e,n,s),c=tc(a),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:ep(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 Sk(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:ji(g)<=1,memberCount:ji(g),sourceRange:m,sourceHash:m?dc(e.source,m):null,relation:l,containerSourceRange:h,containerSourceHash:h?dc(e.source,h):null,anchorSourceRange:u,anchorSourceHash:u?dc(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 uc(e,t,n,r){let o=Qf(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=tc([a]),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:ep(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 qf([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function mc(e,t,n){return qf(["member",e,String(t??-1),String(n??-1)])}function qf(e){return`pc_${gc("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function hc(e,t,n){return t==null||n==null?null:`sha256:${gc("sha256").update(e.slice(t,n)).digest("hex")}`}function dc(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:${gc("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 ep(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 Fk}from"@vcp-dev/contracts";import u_ from"node:fs";import f_ from"node:path";var vk=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function Qr(e){let t=e.map(r=>Tk(r.path)),n=kk(t);return n?t.filter(r=>Ck(n,r)).map(r=>({routeId:Rk(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function yc(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=Ak(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function kk(e){return e.some(r=>r.startsWith("app/")&&!Ik(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function Ik(e){return/^(?:src\/)?app\/(?:_vcp|\.vcp)/.test(e)}function Ck(e,t){if(!t.startsWith(`${e}/`))return!1;let n=t.slice(t.lastIndexOf("/")+1);return vk.test(n)?t.slice(e.length+1,-n.length-1).split("/").filter(Boolean).every(r=>!r.startsWith("_")&&!r.startsWith(".")):!1}function Rk(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(Nk).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function wk(e){return e.startsWith("(")&&e.endsWith(")")}function Nk(e){return!e||e.startsWith("@")||e.startsWith("_")||wk(e)?null:Pk(e)}function Pk(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function Ak(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function Tk(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var qr=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function rt(e,t={}){throw new qr("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Invalid page-template source (${e}): ${t.path??t.routeId??t.templateId??""}`,{reason:e,...t})}function xc(e){return Fk.safeParse(e).success||rt("invalid-template-id",{templateId:e}),Buffer.from(e,"utf8").toString("base64url")}function tp(e){/^[A-Za-z0-9_-]{1,255}$/.test(e)||rt("invalid-template-key",{path:e});let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.from(e,"base64url"))}catch{return rt("invalid-template-key",{path:e})}return xc(t)!==e&&rt("noncanonical-template-key",{path:e}),t}function _k(e){let t=yc(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("(")||Mk(r)&&!np(r)))&&rt("invalid-public-route",{routeId:e}),t}function Mk(e){return e.includes("[")||e.includes("]")}function np(e){return/^\[\[\.\.\.[^\[\]]+\]\]$|^\[[^\[\]]+\]$/.test(e)}function rp(e){return e.some(np)}function op(e,t,n="app"){n!=="app"&&n!=="src/app"&&rt("invalid-app-root");let r=_k(e),o=xc(t),i=rp(r.slice(1).split("/")),s=i?`${n}/.vcp/page-templates/${o}${r}`:`${n}/.vcp/page-templates${r==="/"?"":r}`,a=i?`${s}/page.tsx`:`${s}/${o}/page.tsx`;return(Buffer.byteLength(a,"utf8")>4095||a.split("/").some(c=>Buffer.byteLength(c,"utf8")>255))&&rt("path-too-long",{path:a}),{appRoot:n,routeRoot:s,templateKey:o,templateEntryFile:a}}function ip(e){return/^(?:src\/)?app\/\.vcp\/page-templates\//.test(e)}function sp(e){let t=Array.isArray(e)?e.map(r=>[r.path,r.content]):[...e],n=new Map;for(let[r,o]of t){let i=r.replace(/\\/g,"/").replace(/^\.\//,"");i.split("/").some(s=>s===".."||s===".")&&rt("invalid-file-path",{path:i}),n.has(i)&&rt("duplicate-file-path",{path:i}),n.set(i,o)}return n}function Vi(e){let t=sp(e.files),n=Qr([...t.keys()].map(i=>({path:i}))),r=new Map;for(let i of n){if(r.has(i.routeId))throw new qr("PAGE_TEMPLATE_ROUTE_AMBIGUOUS",`Multiple canonical entries for ${i.routeId}`,{reason:"duplicate-route-id",routeId:i.routeId,candidates:n.filter(s=>s.routeId===i.routeId).map(s=>s.entryFile)});r.set(i.routeId,i.entryFile)}let o=[];for(let i of t.keys()){if(!ip(i))continue;let s=/^(app|src\/app)\/\.vcp\/page-templates\/(.+)\/page\.tsx$/.exec(i);s||rt("candidate-must-be-single-page",{path:i});let a=s[1],c=s[2].split("/"),l=rp(c),d=l?c[0]:c.pop(),f=l?c.slice(1):c,m=tp(d),u=f.length?`/${f.join("/")}`:"/";op(u,m,a).templateEntryFile!==i&&rt("candidate-path-mismatch",{path:i,routeId:u});let h=r.get(u);(!h||!h.startsWith(`${a}/`))&&rt("canonical-entry-missing",{path:i,routeId:u}),o.push({routeId:u,templateId:m,entryFile:i,canonicalEntryFile:h,appRoot:a})}return o.sort((i,s)=>$i(i.routeId,s.routeId)||$i(i.templateId,s.templateId))}function ap(e){let t=sp(e.files),n=Vi({files:t}),r=Qr([...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)=>$i(o.context.routeId,i.context.routeId)||(o.context.effectiveTemplateId===void 0?-1:i.context.effectiveTemplateId===void 0?1:$i(o.context.effectiveTemplateId,i.context.effectiveTemplateId)))}function Ok(e){let t=yc(e.selector.routeId),n=ap({files:e.files}),r=n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===void 0);(!r||r.entryFile!==e.canonicalEntryFile)&&rt("canonical-entry-mismatch",{routeId:t,path:e.canonicalEntryFile});let o=e.selector.templateId===void 0?r:n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===e.selector.templateId);return o||rt("template-selection-not-found",{routeId:t,templateId:e.selector.templateId}),{...o,mode:e.selector.templateId===void 0?"direct":"candidate",effectiveEntryFile:o.entryFile}}function $i(e,t){return e<t?-1:e>t?1:0}import{HOME_PAGE_URL_PATH as Hk}from"@vcp-dev/contracts";import{parse as pM}from"@babel/parser";import{parse as E_}from"@babel/parser";import{FormBlockIdSchema as k_,FormSpecV1Schema as I_}from"@vcp-dev/contracts";var eo="components/site/generated/forms",C_=`${eo}/vcp-form-runtime.tsx`,Ki="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",R_=new RegExp(`^${eo}/form-(${Ki})\\.spec\\.ts$`),w_=new RegExp(`^${eo}/form-(${Ki})\\.tsx$`),N_=new RegExp(`^@/${eo}/form-(${Ki})$`),P_=new RegExp(`(?:^|/)${eo}/form-(${Ki})(?:\\.tsx?)?$`);var A_=Symbol("invalid-literal");import{createHash as __}from"node:crypto";import{posix as O_}from"node:path";import{parse as D_}from"@babel/parser";import{FormSpecV1Schema as j_}from"@vcp-dev/contracts";var $_=Symbol("dynamic");import{parse as Lk}from"@babel/parser";function Ui(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.type=="string"):[]}var Dk=/^(?:src\/)?app\/(.*)page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function cp(e){let t=Dk.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 Bk(e){let t=e;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function lp(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function jk(e){let t=e;for(;t&&(t.type==="TSAsExpression"||t.type==="TSSatisfiesExpression"||t.type==="ParenthesizedExpression");)t=t.expression??null;return t}function bc(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(bc);if(t?.type==="ObjectExpression"){let n={};for(let r of Ui(t.properties)){if(r.type!=="ObjectProperty"||r.computed)throw new Error("dynamic object property");let o=lp(r.key);if(!o)throw new Error("unsupported object key");n[o]=bc(r.value)}return n}throw new Error(`unsupported static value: ${t?.type??"unknown"}`)}function Sc(e,t){let n=[],r=cp(t);if(r===null)return{found:!1,seo:null,diagnostics:n};let o;try{o=Lk(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 Ui(o.program.body)){let d=l.type==="ExportNamedDeclaration"?l.declaration:l;if(d?.type==="VariableDeclaration")for(let f of Ui(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=jk(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 Ui(s.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let d=lp(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=Bk(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=bc(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 $k}from"@babel/parser";var up=["page","anchor","external","email","phone","group","file"],Vk=["link","cta"],fp=["description","badge","iconKey"],Ec=["label","targetType","href","role","openInNewTab","nofollow","children",...fp],Kk=new Set(Ec);function no(e){return Array.isArray(e)?e:[]}function to(e){let t=e;return t?.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function Uk(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function dp(e){let t=e;return t?.type==="BooleanLiteral"&&typeof t.value=="boolean"?t.value:void 0}function vc(e){let t=[],n;try{n=$k(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 no(n.program.body)){let s=i.type==="ExportNamedDeclaration"?i.declaration:i;if(s?.type==="VariableDeclaration")for(let a of no(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 no(r.elements).forEach((i,s)=>{let a=pp(i,`NAV_ITEMS[${s}]`,t);a&&o.push(a)}),{items:o,diagnostics:t}}function pp(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 no(e.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let d=Uk(l.key);d&&(r[d]=l.value)}let o=to(r.label),i=to(r.targetType);if(!o)return n.push({severity:"fatal",path:`${t}.label`,message:"label must be a static string"}),null;if(!i||!up.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${up.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 fp){if(r[l]===void 0)continue;let d=to(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))Kk.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 ${Ec.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=[];no(r.children.elements).forEach((d,f)=>{let m=pp(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=to(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=to(r.role);if(c!==void 0&&(Vk.includes(c)?s.role=c:n.push({severity:"warning",path:`${t}.role`,message:"role ignored: not link/cta"})),r.openInNewTab!==void 0){let l=dp(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=dp(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 Jk}from"@babel/parser";function ro(e){return Array.isArray(e)?e:[]}function mp(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function Xk(e){let t;try{t=Jk(e,{sourceType:"module",plugins:["typescript","jsx"],tokens:!0})}catch{return{status:"unsupported"}}let n=[];for(let o of ro(t.program.body)){let i=o.type==="ExportNamedDeclaration"?o.declaration:o;if(i?.type==="VariableDeclaration")for(let s of ro(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=mp(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 kc(e,t){let n=gp(t);if(!n)return{status:"unsupported",source:e};let r=Xk(e);if(r.status!=="ok")return{status:r.status,source:e};let o=r.array;if(vc(e).diagnostics.some(({severity:l})=>l==="fatal"))return{status:"unsupported",source:e};let s=[],a=l=>{let d=ro(l.elements);for(let[f,m]of d.entries()){if(Wk(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 y=/^\s*,/.exec(e.slice(E));s.push({start:b,end:y?E+y[0].length:E})}continue}let u=zk(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 zk(e){if(e.type==="ObjectExpression")for(let t of ro(e.properties)){if(t.type!=="ObjectProperty")continue;let n=t.key;if((n?.name??n?.value)==="children")return mp(t.value)}}function gp(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function Wk(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of ro(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"&&gp(n??"")===t}import{estimateNavLabelWidth as Y_}from"@vcp-dev/contracts";import{parse as q_}from"@babel/parser";var Gk="components/site/generated/",oo=[".tsx",".ts",".jsx",".js"];function hp(e){if(e.expectedUrlPath===Hk)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set(Qr(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 y=Sc(b,E);return y.found&&y.seo?.path===e.expectedUrlPath});if(n.length===0)return{ok:!1,code:"ROUTE_NOT_FOUND",message:"No route uniquely matches the requested page identity."};if(n.length>1)return{ok:!1,code:"ROUTE_AMBIGUOUS",message:"Multiple routes match the requested page identity."};let[r]=n[0],o=new Set([r]);try{let h=Vi({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=Yk(e.files);if(!i.ok)return i.error;let s=i.graph,a=eI(o,s),c=tI(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=kc(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 Yk(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")||!Zk(r))continue;let s=Jt(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(Qk(c))continue;let l=bn(r,c),d=qk(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 Zk(e){let t=e.toLowerCase();return oo.some(n=>t.endsWith(n))}function Qk(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!oo.some(n=>e.endsWith(n)))}function qk(e,t){let n=e.replace(/\\/g,"/");return(oo.some(o=>n.endsWith(o))?[n]:[...oo.map(o=>`${n}${o}`),...oo.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function eI(e,t){let n=new Set,r=[...e].flatMap(o=>[...t.get(o)??[]]);for(;r.length>0;){let o=r.pop();!o.startsWith(Gk)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function tI(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 hm from"@babel/parser";import*as fe from"@babel/types";import*as ss from"node:path";import*as Ee from"@babel/types";function yp(e){if(e.path.isVariableDeclarator()){let n=e.path.get("init");return n?.isExpression()?{expressionPath:n}:null}if(!e.path.isIdentifier()||!e.path.parentPath?.isVariableDeclarator())return null;let t=e.path.parentPath.get("init");return t?.isExpression()?{expressionPath:t}:null}function Ot(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return Tn(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(Ee.isObjectPattern(n)||Ee.isArrayPattern(n))return Tn(n,e.identifier.name)}if(!e.path.isIdentifier())return!1;let t=e.path.parentPath;for(;t;){if(t.isAssignmentPattern()){let n=t.get("left");if(rI(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function Tn(e,t,n=!1){return Ee.isIdentifier(e)?e.name===t&&n:Ee.isObjectPattern(e)?e.properties.some(r=>Ee.isObjectProperty(r)?Tn(r.value,t,n):Tn(r.argument,t,n)):Ee.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=Ee.isRestElement(r)?r.argument:r;return Tn(o,t,n)}):Ee.isAssignmentPattern(e)?Tn(e.left,t,!0):Ee.isRestElement(e)?Tn(e.argument,t,n):!1}function cr(e,t){if(e.path.isObjectPattern()){if(t){let r=It(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:Ot(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:Ot(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=xp(r),i=!1,s=o?o.initBinding&&Ic(o.initBinding)?(i=Ot(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=cr(o.initBinding,{kind:"identifier",expression:o.initBinding.identifier.name,base:o.initBinding.identifier.name,path:[]});return i=c?.hasDefault??!1,c?[{kind:"property",name:c.propName},...c.remainingPath,...o.initPathPrefix]:null})():null:null,a=It(e.path.node.id,e.identifier.name);if(s&&a){let c=[...s,...a],[l,...d]=c;return!l||l.kind!=="property"?null:{propName:l.name,remainingPath:[...d,...t?.path??[]],hasDefault:i||Ot(e)}}}}let n=sI(e);if(n){let r=nI(n,e);if(r){let[s,...a]=r.path;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:r.hasDefault||Ot(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=oI(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:Ot(e)}}let i=io(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:Ot(e)}:null}if(Ic(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:Ot(e)}}return null}function nI(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=xp(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=Ic(i)?(a=Ot(i),[...s]):(()=>{let d=cr(i,{kind:"identifier",expression:i.identifier.name,base:i.identifier.name,path:[]});return a=d?.hasDefault??!1,d?[{kind:"property",name:d.propName},...d.remainingPath,...s]:null})();if(!c)return null;let l=It(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||Ot(t)}:null}function xp(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=aI(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function Ic(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function rI(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function oI(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 bp(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=Ji(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=io(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=iI(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=io(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 Ji(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=io(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=Ji(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=Ji(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=Ji(r,t);if(o)return o}}return null}function It(e,t,n=[]){if(Ee.isIdentifier(e))return e.name===t?n:null;if(Ee.isObjectPattern(e)){for(let r of e.properties)if(Ee.isObjectProperty(r)){let o=io(r);if(!o)continue;let i=It(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(Ee.isRestElement(r)){let o=It(r.argument,t,n);if(o)return o}}if(Ee.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=Ee.isRestElement(o)?o.argument:o,s=It(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return Ee.isAssignmentPattern(e)?It(e.left,t,n):null}function iI(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function sI(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 io(e){return e.computed?null:Ee.isIdentifier(e.key)?e.key.name:Ee.isStringLiteral(e.key)?e.key.value:null}function aI(e){let t=[],n=e;for(;Ee.isMemberExpression(n);){if(n.computed)if(Ee.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(Ee.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(Ee.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return Ee.isIdentifier(n)?{base:n.name,path:t}:null}import*as Ip from"@babel/parser";import wc from"@babel/traverse";import*as lr from"@babel/types";import*as le from"@babel/types";function Wi(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?Xi(n,t):null}if(e.isMemberExpression()){let n=pI(e.node),r=cI(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?Xi(o,[...r,...t]):null}return e.isAwaitExpression()||Rc(e.node)?dn(gI(e.node),t,"awaited or fetched expression"):null}function cI(e){let t=[],n=e;for(;le.isMemberExpression(n);){if(n.computed)if(le.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(le.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(le.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return le.isIdentifier(n)?t:null}function Xi(e,t=[],n){let r=lI(e,t);if(r)return r;let o=uI(e,t);if(o)return o;let i=dI(e,t,n);return i||null}function ao(e){return e?.kind==="api-source"}function lI(e,t){if(e.path.isVariableDeclarator()&&le.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&Cc(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return dn(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&le.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(c=>le.isObjectProperty(c)&&vp(c)==="data"&&so(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&Cc(a.node))return dn(e.identifier.name,t,"query hook data binding")}let n=fI(e);if(!n||vp(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()||!Cc(i.node)?null:dn(e.identifier.name,t,"query hook data binding")}function uI(e,t){if(e.path.isVariableDeclarator()&&le.isArrayPattern(e.path.node.id)){let a=e.path.get("init");if(!a?.isCallExpression()||!Ep(a.node))return null;let[c,l]=e.path.node.id.elements;return!le.isIdentifier(c)||c.name!==e.identifier.name||!le.isIdentifier(l)?null:Sp(e,l.name)?dn(e.identifier.name,t,"state setter is updated by API data"):null}if(!e.path.isIdentifier())return null;let n=e.path.parentPath;if(!n?.isArrayPattern())return null;let r=n.parentPath;if(!r?.isVariableDeclarator())return null;let o=r.get("init");if(!o?.isCallExpression()||!Ep(o.node)||n.node.elements.findIndex(a=>a===e.path.node)!==0)return null;let s=n.node.elements[1];return le.isIdentifier(s)&&Sp(e,s.name)?dn(e.identifier.name,t,"state setter is updated by API data"):null}function dI(e,t,n){let r=e.path.isVariableDeclarator()?e.path:e.path.findParent(i=>i.isVariableDeclarator());if(!r?.isVariableDeclarator())return null;let o=r.get("init");return o?.isExpression()?o.isAwaitExpression()?dn(e.identifier.name,t,"awaited binding result"):Rc(o.node,n)?dn(e.identifier.name,t,"fetch-backed binding result"):null:null}function fI(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 so(e,t){return le.isIdentifier(e)?e.name===t:le.isAssignmentPattern(e)?so(e.left,t):le.isObjectPattern(e)?e.properties.some(n=>le.isObjectProperty(n)?so(n.value,t):so(n.argument,t)):le.isArrayPattern(e)?e.elements.some(n=>!!n&&so(le.isRestElement(n)?n.argument:n,t)):!1}function Sp(e,t){let n=!1,r=!1;return e.scope.path.traverse({CallExpression(i){Rc(i.node)&&(n=!0),(mI(i.node.callee,t)||i.node.arguments.some(s=>le.isIdentifier(s)&&s.name===t))&&(r=!0)}}),n&&r}function Cc(e){let t=Hi(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function Ep(e){return Hi(e.callee)==="useState"}function Rc(e,t){let n=t?.get(e);if(n!==void 0)return n;let r=zi(e,o=>le.isCallExpression(o)&&Hi(o.callee)==="fetch");return t?.set(e,r),r}function pI(e){let t=e;for(;le.isMemberExpression(t);)t=t.object;return le.isIdentifier(t)?t.name:null}function vp(e){return e.computed?null:le.isIdentifier(e.key)?e.key.name:le.isStringLiteral(e.key)?e.key.value:null}function Hi(e){return le.isIdentifier(e)?e.name:le.isMemberExpression(e)&&le.isIdentifier(e.property)?e.property.name:null}function mI(e,t){return zi(e,n=>le.isIdentifier(n)&&n.name===t)}function zi(e,t){if(t(e))return!0;let n=le.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(le.isNode(i)&&zi(i,t))return!0;continue}if(le.isNode(o)&&zi(o,t))return!0}return!1}function gI(e){return le.isIdentifier(e)?e.name:le.isCallExpression(e)?Hi(e.callee)??"api":le.isAwaitExpression(e)?"awaited-api":"api"}function dn(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:hI(e,t),reason:n}}function hI(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var Cp=typeof wc=="function"?wc:wc.default;function Rp(e,t){let n=Np(e);if(!n)return{allowed:!0};let r=!1;return Cp(n,{CallExpression(o){if(!Pp(o.node,t.sourceRange)||!yI(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||ao(Wi(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function wp(e,t){let n=Np(e);if(!n)return{allowed:!0};let r=!1;return Cp(n,{JSXExpressionContainer(o){Pp(o.node,t.sourceRange)&&(lr.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 Np(e){try{return Ip.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function yI(e){let t=e.callee;return lr.isMemberExpression(t)&&lr.isIdentifier(t.property)&&t.property.name==="map"}function Pp(e,t){let n=e.loc;return n?kp({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&kp({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function kp(e,t){return e.line!==t.line?e.line<t.line?-1:1:e.column!==t.column?e.column<t.column?-1:1:0}import*as X from"@babel/types";import*as Ap from"@babel/parser";import Nc from"@babel/traverse";import*as Fe from"@babel/types";import*as ur from"node:path";var Ct=typeof Nc=="function"?Nc:Nc.default;function Je(e){try{return Ap.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Pc(e){return e.computed?Fe.isStringLiteral(e.key)||Fe.isNumericLiteral(e.key)?String(e.key.value):null:xI(e.key)}function xI(e){return Fe.isIdentifier(e)?e.name:Fe.isStringLiteral(e)||Fe.isNumericLiteral(e)?String(e.value):null}function Fn(e){return Fe.isParenthesizedExpression(e)||Fe.isTSAsExpression(e)||Fe.isTSSatisfiesExpression(e)||Fe.isTSNonNullExpression(e)||Fe.isTSTypeAssertion(e)?Fn(e.expression):Fe.isExpression(e)?e:null}function Ac(e){if(Fe.isIdentifier(e))return[e.name];if((Fe.isMemberExpression(e)||Fe.isOptionalMemberExpression(e))&&!e.computed&&Fe.isIdentifier(e.property)){let t=Fn(e.object),n=t?Ac(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(".")?ur.normalize(ur.join(ur.dirname(e),t)).replace(/\\/g,"/"):t}function ct(e,t){return Gi(e)===Gi(t)}function Gi(e){let t=dr(e);return t.endsWith("/index")?t.slice(0,-6):t}function dr(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function _p(e,t,n){let r=Dp(e,t);if(Bp(e,r),jp(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"}:Yi(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 Mp(e,t){let n=new Map,r=i=>{let s=fr(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 bI(i,n))o=r(s)||o}return[...n.values()]}function bI(e,t){let n=[],r=SI(e,t);for(let o of e.ast.program.body){if(X.isExportDefaultDeclaration(o)&&X.isIdentifier(o.declaration)&&(r.get(o.declaration.name)?.length??0)>0){let i=r.get(o.declaration.name)??[];for(let s of i){if(s.namespace){let a=co(s.namespace,o.declaration.name,"default");a&&n.push({file:e.file,namespace:a,exportName:s.exportName});continue}n.push({file:e.file,exportName:"default"})}continue}if(X.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=_n(e.file,o.source.value);for(let s of o.specifiers){if(X.isExportNamespaceSpecifier(s)){let l=fn(s.exported);for(let d of t.values())ct(d.file,i)&&n.push({file:e.file,namespace:Tc(l,d.namespace),exportName:d.exportName});continue}if(!X.isExportSpecifier(s))continue;let a=fn(s.local),c=[...t.values()].filter(l=>ct(l.file,i)&&Mn(l.namespace,a));if(c.length>0){let l=fn(s.exported);for(let d of c){let f=co(d.namespace,a,l);f&&n.push({file:e.file,namespace:f,exportName:d.exportName})}continue}t.has(fr({file:i,exportName:a}))&&n.push({file:e.file,exportName:fn(s.exported)})}continue}if(X.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!X.isExportSpecifier(i))continue;let s=fn(i.local),a=r.get(s)??[];if(a.length>0){let c=fn(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let d=co(l.namespace,s,c);d&&n.push({file:e.file,namespace:d,exportName:l.exportName})}}}continue}if(X.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=_n(e.file,o.source.value),s=o.exported;if(s){let a=fn(s);for(let c of t.values())ct(c.file,i)&&n.push({file:e.file,namespace:Tc(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())ct(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function Tc(e,t){return t?`${e}.${t}`:e}function Mn(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function co(e,t,n){return!Mn(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function SI(e,t){let n=new Map,r=(i,s)=>{let a=n.get(i)??[];a.push(s),n.set(i,a)};for(let i of e.ast.program.body){if(!X.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=_n(e.file,i.source.value);for(let a of i.specifiers){if(X.isImportDefaultSpecifier(a)){let c=t.get(fr({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(d=>ct(d.file,s)&&Mn(d.namespace,"default"));for(let d of l){let f=co(d.namespace,"default",a.local.name);f&&r(a.local.name,{...d,namespace:f})}continue}if(X.isImportSpecifier(a)){let c=fn(a.imported),l=[...t.values()].filter(f=>ct(f.file,s)&&Mn(f.namespace,c));for(let f of l)r(a.local.name,f);let d=t.get(fr({file:s,exportName:c}));d&&r(a.local.name,d);continue}if(X.isImportNamespaceSpecifier(a))for(let c of t.values())ct(c.file,s)&&r(a.local.name,{...c,namespace:Tc(a.local.name,c.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(X.isVariableDeclaration(i))for(let s of i.declarations){if(!X.isIdentifier(s.id)||!s.init)continue;let a=Fn(s.init);if(!a||!X.isIdentifier(a))continue;let c=n.get(a.name)??[];if(c.length===0)continue;let l=n.get(s.id.name)??[],d=new Set(l.map(fr));for(let f of c){let m=co(f.namespace,a.name,s.id.name),u=m?{...f,namespace:m}:f,g=fr(u);d.has(g)||(r(s.id.name,u),d.add(g),o=!0)}}}return n}function fr(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${Gi(e.file)}#${t}`}function fn(e){return X.isIdentifier(e)?e.name:e.value}function Op(e,t){for(let n of e.program.body){if(X.isExportDefaultDeclaration(n)){let o=n.declaration;if((X.isFunctionDeclaration(o)||X.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(X.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!X.isExportNamedDeclaration(n))continue;let r=n.declaration;if((X.isFunctionDeclaration(r)||X.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(X.isVariableDeclaration(r)){for(let o of r.declarations)if(X.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!X.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:X.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function _c(e){let t=EI(e),n=[],r=jp(e.ast,t);return Ct(e.ast,{JSXElement(o){ct(e.file,e.sourceFile)&&Yi(o)===e.sourceComponent||Up(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function Lp(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function Dp(e,t){let n=Lp();return Ct(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function EI(e){let t=Lp();return ct(e.file,e.sourceFile)&&vI(t,Dp(e.ast,e.sourceComponent)),Ct(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=_n(e.file,o),s=e.componentIdentities.filter(a=>ct(a.file,i));if(s.length!==0)for(let a of r.specifiers){let c=n.scope.getBinding(a.local.name);if(c){if(X.isImportDefaultSpecifier(a)&&s.some(l=>l.exportName==="default")&&t.localBindings.add(c),X.isImportDefaultSpecifier(a)){let l=s.filter(d=>Mn(d.namespace,"default"));if(l.length>0){let d=t.namespaceMembers.get(c)??new Set;for(let f of l){let m=Fp(f,"default");m&&d.add(m)}t.namespaceMembers.set(c,d)}continue}if(X.isImportSpecifier(a)){let l=X.isIdentifier(a.imported)?a.imported.name:a.imported.value,d=s.filter(f=>Mn(f.namespace,l));if(d.length>0){let f=t.namespaceMembers.get(c)??new Set;for(let m of d){let u=Fp(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(X.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)}}}}}),Bp(e.ast,t),t}function vI(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 Bp(e,t){Ct(e,{VariableDeclarator(n){if(!n.node.init)return;let r=Fn(n.node.init);if(r){if(X.isIdentifier(n.node.id)){let o=On(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&Fc(t,i,o);return}if(X.isObjectPattern(n.node.id)){let o=On(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&Kp(n.node.id,o.namespaceMembers,t,n)}}}})}function jp(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return Ct(e,{ReferencedIdentifier(r){if(n){r.stop();return}kI(r)||!r.isIdentifier()||!$p(r,t)||II(r,t)||CI(r)||(n=!0,r.stop())}}),n}function kI(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 $p(e,t){let n=e.scope.getBinding(e.node.name);if(!n)return null;let r=e;for(;r.parentPath?.isMemberExpression()&&r.parentPath.node.object===r.node&&!r.parentPath.node.computed;)r=r.parentPath;return t.localBindings.has(n)||t.namespaceMembers.has(n)&&On(r.node,t,r)?r:null}function II(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!Tp(e,r))return!1;let o=$p(e,t);if(!o)return!1;if(Fn(r.node)===o.node)return!!On(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&Tp(e,a)&&!!On(a.node,t,a)}function CI(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function Tp(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function On(e,t,n){let r=Fn(e);if(!r)return null;if(X.isIdentifier(r)){let a=n.scope.getBinding(r.name);if(!a)return null;let c=t.namespaceMembers.get(a);return t.localBindings.has(a)?{local:!0,namespaceMembers:new Set,unsupported:!1}:c?{local:!1,namespaceMembers:new Set(c),unsupported:!1}:null}if(X.isObjectExpression(r))return RI(r,t,n);let o=Ac(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?Vp(s,o.slice(1).join(".")):null}function RI(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!X.isObjectProperty(i))continue;let s=Pc(i);if(!s||!X.isExpression(i.value)){X.isExpression(i.value)&&(o||=On(i.value,t,n)!==null);continue}let a=On(i.value,t,n);if(a){o||=a.unsupported,a.local&&r.add(s);for(let c of a.namespaceMembers)r.add(`${s}.${c}`)}}return r.size>0||o?{local:!1,namespaceMembers:r,unsupported:o}:null}function Vp(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 Fc(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 Kp(e,t,n,r){for(let o of e.properties){if(X.isRestElement(o)){if(X.isIdentifier(o.argument)){let c=r.scope.getBinding(o.argument.name);c&&Fc(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!X.isObjectProperty(o))continue;let i=Pc(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=Vp(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=X.isAssignmentPattern(o.value)?o.value.left:o.value;if(X.isIdentifier(a)){let c=r.scope.getBinding(a.name);c&&Fc(n,c,s);continue}if(X.isObjectPattern(a)&&s.namespaceMembers.size>0){Kp(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function Fp(e,t){if(!Mn(e.namespace,t))return null;if(e.namespace===t)return e.exportName;let n=e.namespace?.slice(t.length+1);return n?`${n}.${e.exportName}`:e.exportName}function Up(e,t){let n=e.node.openingElement.name;if(X.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=Jp(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 Jp(e){if(X.isJSXIdentifier(e))return[e.name];if(X.isJSXMemberExpression(e)){let t=Jp(e.object);return t?[...t,e.property.name]:null}return null}function Yi(e){let t=e.getFunctionParent();if(!t)return null;if(t.isFunctionDeclaration())return t.node.id?.name??null;if(t.isArrowFunctionExpression()||t.isFunctionExpression()){let n=t.parentPath;if(n?.isVariableDeclarator()&&X.isIdentifier(n.node.id))return n.node.id.name}return null}function Xp(e,t){let n=Je(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=_c({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 be(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 xe(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function Lt(e,t){let n=xe(e);return!!(n&<(t,n))}function lt(e,t){return t.start>=e.start&&t.end<=e.end}function bt(e,t){let n=ce(e,be(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:Zi(e,t)}function pr(e,t){let n=xe(t);return n?e.slice(n.start,n.end):""}function zp(e,t){return e.start===t.start&&e.end===t.end}function Zi(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 Qi(e,t){return Mc(e,t).length>0}function qi(e,t){let n=xe(e.node),r=xe(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()&&!wI(o,n,r)))return!0;o=o.parentPath}return!1}function wI(e,t,n){let r=xe(e.node.consequent);if(r&<(r,t)&&!lt(r,n))return!1;let o=e.node.alternate?xe(e.node.alternate):null;return!(o&<(o,t)&&!lt(o,n))}function Mc(e,t){let n=xe(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=xe(o.node.consequent),a=xe(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()&&Oc(o.node.operator)){let s=xe(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 Oc(e){return e==="&&"||e==="||"||e==="??"}function Wp(e,t){let n=xe(e.consequent);if(n&<(n,t))return n;let r=xe(e.alternate);return r&<(r,t)?r:null}function Hp(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=>dr(a.file)));if(!t.has(dr(e.sourceFile))||!t.has(dr(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(dr(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=Op(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=Mp(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=_c({ast:a.ast,file:a.file,sourceFile:e.sourceFile,sourceComponent:e.sourceComponent,componentIdentities:o});if(c.hasUnsafeReference)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component because the component has unsupported value usages"};i.push(...c.callSites)}if(i.length!==1)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without a single project-wide component call site"};let[s]=i;return!ct(s.file,e.targetFile)||Yi(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 _I}from"@vcp-dev/contracts";function es(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 lo();let a=s.target,c=a.locator;if(a.sourceKind==="repeat-template"){let l=o?.instanceIndex;if(l===void 0)return lo();let d=NI(a,l,o?.instanceCount);if(!d)return lo();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"?lo():{ok:!0,target:{kind:"jsx-attribute"}}}function lo(){return{ok:!1,code:"unsupported-binding",reason:"Property does not have a safe typed binding write target for this scope and operation"}}function NI(e,t,n){if(!e.locator||!Number.isInteger(t)||t<0)return null;let r=e.collectionPathMap?.length??e.collectionIndexMap?.length;if(r!==void 0&&(t>=r||n!==void 0&&n!==r))return null;let o=e.collectionPathMap?.[t];if(o)return{...e.locator,path:o};let i=e.locator.path??[],s=i.findLastIndex(c=>c.kind==="index");if(s<0)return null;let a=i.map((c,l)=>l===s&&c.kind==="index"?{kind:"index",index:e.collectionIndexMap?.[t]??t}:c);return{...e.locator,path:a}}import*as Dt from"@babel/types";import{SiteEditSetPropsParamsSchema as PI}from"@vcp-dev/contracts";function Gp(e){let t=e.changes??(e.change?[e.change]:[]);if(!PI.safeParse({kind:"set-props",scope:"selection",changes:t}).success)return uo("invalid-change","Repeat property changes are invalid");if(t.length!==1||t[0].name!==e.target.propertyName)return uo("target-mismatch","A repeat property plan must contain exactly one change for its target property");let r=t[0];if(r.operation==="remove"&&e.target.propertyState==="missing")return{ok:!0,steps:[]};let o=we(e.source,"value");if(!o.ok)return uo("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=ce(o.ast,a);if(!c.ok||!c.match.path.isObjectExpression())return uo("unsupported-object",`Repeat item ${s} is not a writable object expression`);let l=s===e.target.sourceItemIndex?AI(r):TI(c.match.path.node,r.name);if(!l)return uo("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 AI(e){return e.operation==="set"?{kind:"value",value:e.value}:{kind:"undefined"}}function TI(e,t){let n=e.properties.filter(i=>Dt.isObjectProperty(i)&&FI(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=Mt(r.value);return o.status==="undefined"?{kind:"undefined"}:o.status!=="resolved"?null:{kind:"value",value:o.value}}function FI(e){return Dt.isIdentifier(e)?e.name:Dt.isStringLiteral(e)?e.value:Dt.isNumericLiteral(e)?String(e.value):null}function uo(e,t){return{ok:!1,errorCode:e,reason:t}}function Yp(e){if(e.change.name!=="className"&&e.change.name!=="class")return fo("unsupported-owner",`No specialized property owner is available for '${e.change.name}'`);let t=e.classNameSource;if(!t||t.filePath!==e.node.file)return fo("owner-source-unavailable","className source details are unavailable for the selected node");if(e.change.name==="class"&&t.sourceKind==="missing")return fo("owner-source-unavailable","The class alias requires an existing className source");if(t.sourceKind==="expression")return fo("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 fo("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 fo(e,t){return{ok:!1,errorCode:e,reason:t}}async function Qp(e){let t=_I.safeParse({kind:"set-props",scope:e.scope,changes:e.changes});if(!t.success)return pn("invalid-change","Typed property changes are invalid");if(e.node.importedFrom==="next/link"&&e.node.exportName==="default"){let r=t.data.changes.find(o=>o.name==="href");if(r&&(r.operation==="remove"||typeof r.value!="string"||r.value.trim().length===0))return pn("invalid-change","next/link requires a non-empty href; use the dedicated link-target operation to remove the link")}let n=[];for(let r of t.data.changes){let o=await MI(e,r);if(o){if(!o.ok)return pn("owner-plan-failed",o.reason);Zp(n,o.steps);continue}let i=await e.getPropertyState(e.node.key,r.name,e.selectionRef);if(!i)return pn("missing-property-state",`No authoritative property state is available for '${r.name}'`);if(i.status==="blocked")return pn("readonly-property",i.diagnostic?.message??`Property '${r.name}' is not writable`);if(DI(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=es({state:i,scope:e.scope,operation:r.operation,selectionRef:e.selectionRef,repeatTarget:s});if(!a.ok)return pn(a.code,a.reason);let c=a.target;if(c.kind==="value-binding"&&r.operation==="set"){Lc(n,{type:"update-value",order:n.length,file:c.file,locator:c.locator,value:r.value});continue}if(c.kind==="repeat-property"){let l=Gp({source:e.getFileContent(c.target.sourceFile),target:c.target,changes:[r]});if(!l.ok)return pn("repeat-target-failed",l.reason);Zp(n,l.steps);continue}Lc(n,{type:"set-property-changes",order:n.length,file:e.node.file,locator:OI(e.node),scope:e.scope,changes:[r]})}return n.forEach((r,o)=>{r.order=o}),LI(n)?pn("step-conflict","Property changes resolve to conflicting write steps"):{ok:!0,steps:n}}async function MI(e,t){return t.name!=="className"&&t.name!=="class"?null:Yp({node:e.node,change:t,classNameSource:e.classNameSource})}function OI(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 LI(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 Zp(e,t){for(let n of t)Lc(e,{...n,order:e.length})}function Lc(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 DI(e,t){if(t.operation!=="set"||e.status!=="direct")return!1;let n=e.attribute?.resolution;return n?.status==="resolved"?Dc(n.value,t.value):e.attribute?.source===null&&e.attribute.value===t.value}function Dc(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)=>Dc(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=>Dc(n[i],r[i]))}return!1}function pn(e,t){return{ok:!1,errorCode:e,reason:t}}import*as gr from"@babel/types";import*as G from"@babel/types";function Bc(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=pr(e,d.node),m=r.node.params.map(h=>pr(e,h)),u=xe(i.node),g=xe(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:ts(d.node),callbackPath:r,collectionPath:d}}function po(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function BI(e,t){let n=xe(e.node);return n?jI(t).some(r=>{let o=xe(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function jI(e){let t=e.callbackPath.node.body;return G.isBlockStatement(t)?mn(t.body):gn(t)}function mn(e){let t=[];for(let n of e){if(G.isReturnStatement(n)){n.argument&&t.push(...gn(n.argument));continue}if(G.isBlockStatement(n)){t.push(...mn(n.body));continue}if(G.isIfStatement(n)){let r=G.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...mn(r)),n.alternate){let o=G.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...mn(o))}continue}if(G.isSwitchStatement(n)){for(let r of n.cases)t.push(...mn(r.consequent));continue}G.isTryStatement(n)&&(t.push(...mn(n.block.body)),n.handler&&t.push(...mn(n.handler.body.body)),n.finalizer&&t.push(...mn(n.finalizer.body)))}return t}function gn(e){return G.isJSXElement(e)?$I(e)?qp(e.children):[e]:G.isJSXFragment(e)?qp(e.children):G.isParenthesizedExpression(e)||G.isTSAsExpression(e)||G.isTSSatisfiesExpression(e)||G.isTSNonNullExpression(e)||G.isTSTypeAssertion(e)?gn(e.expression):G.isConditionalExpression(e)?[...gn(e.consequent),...gn(e.alternate)]:G.isLogicalExpression(e)&&Oc(e.operator)?gn(e.right):[]}function qp(e){return e.flatMap(t=>G.isJSXElement(t)||G.isJSXFragment(t)?gn(t):G.isJSXExpressionContainer(t)&&(G.isJSXElement(t.expression)||G.isJSXFragment(t.expression)||G.isConditionalExpression(t.expression)||G.isLogicalExpression(t.expression))?gn(t.expression):[])}function $I(e){let t=e.openingElement.name;return G.isJSXIdentifier(t)?t.name==="Fragment":G.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function em(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function ts(e){return!(G.isIdentifier(e)||G.isThisExpression(e)||G.isMemberExpression(e)||G.isOptionalMemberExpression(e)||G.isCallExpression(e)||G.isOptionalCallExpression(e))}function tm(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 mr(e,t){let n=Je(e);if(!n)return t.isRepeatItemRoot===!0;let r=ce(n,be(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:Zi(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=Bt(e,o);return i?BI(o,i):t.isRepeatItemRoot===!0}function nm(e,t){let n=Je(e);if(!n)return!1;let r=ce(n,be(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:Zi(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 Ce from"@babel/types";function jc(e){if(Ce.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(Ce.isJSXMemberExpression(e)){let t=e;for(;Ce.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function VI(e,t){let n=xe(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);!a||Lt(a.path.node,n)||hn(a,i,t)||r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=jc(i.node.name);s&&o(s,i)}}),[...r].sort()}function $c(e,t,n){let r=Je(e);if(!r)return{ok:!0};let o=ce(r,be(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=ce(r,be(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};let s=Fr(o.match.path,i.match.path);if(Qi(s,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let a=VI(s,i.match.path);return a.length>0?{ok:!1,bindingNames:a}:{ok:!0}}function om(e){let t=e;for(;Ce.isTSQualifiedName(t);)t=t.left;return Ce.isIdentifier(t)?t.name:null}function mo(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function ns(e){let t=[],n=r=>{if(r){if(Ce.isIdentifier(r)){t.push(r.name);return}if(Ce.isObjectPattern(r)){for(let o of r.properties){if(Ce.isRestElement(o)){n(o.argument);continue}Ce.isObjectProperty(o)&&n(o.value)}return}if(Ce.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(Ce.isAssignmentPattern(r)){n(r.left);return}if(Ce.isRestElement(r)){n(r.argument);return}Ce.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function Vc(e,t){let n=xe(e.node),r=xe(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=rm(e),i=rm(t);if(!o||!i||!zp(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=Wp(s.node,n);if(a&&!lt(a,r))return{ok:!1,reason:"Cannot move repeat-backed child out of a component because the component call site is conditionally rendered outside the target scope"}}else if(s.isLogicalExpression()){let a=xe(s.node.right);if(a&<(a,n)&&!lt(a,r))return{ok:!1,reason:"Cannot move repeat-backed child out of a component because the component call site is conditionally rendered outside the target scope"}}else if((s.isArrowFunctionExpression()||s.isFunctionExpression())&&tm(s)){let a=xe(s.node.body)??xe(s.node);if(a&&!lt(a,r))return{ok:!1,reason:"Cannot move repeat-backed child out of a component because the component call site is repeated outside the target scope"}}s=s.parentPath}return{ok:!0}}function rm(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?xe(t.node.argument):null;if(t.isArrowFunctionExpression()&&(Ce.isJSXElement(t.node.body)||Ce.isJSXFragment(t.node.body)||Ce.isConditionalExpression(t.node.body)||Ce.isLogicalExpression(t.node.body)))return xe(t.node.body);t=t.parentPath}return null}function hn(e,t,n){return n.scope.getBinding(t)===e}function Kc(e,t,n,r={}){if(!r.preserveConditionalBoundary&&Qi(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=xe(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(c=>ns(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)||hn(d,c,t)||s.add(c)};return e.traverse({ReferencedIdentifier(c){a(c.node.name,c)},JSXOpeningElement(c){let l=jc(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function Uc(e,t,n){let r=xe(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>ns(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return mo(e,s=>{let a=s.scope.getBinding(s.node.name);!a||Lt(a.path.node,r)||o.has(a.path.node)||hn(a,s.node.name,t)||i.add(s.node.name)}),i.size>0?{ok:!1,bindingNames:[...i].sort()}:{ok:!0}}function im(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>ns(a)).map(a=>e.callbackPath.scope.getBinding(a)?.path.node).filter(Boolean)),r=new Set,o=(a,c)=>{let l=c.scope.getBinding(a);!l||n.has(l.path.node)||hn(l,a,t)||r.add(a)},i=e.callbackPath.get("params"),s=Array.isArray(i)?i:[i];for(let a of s)a.traverse({ReferencedIdentifier(c){o(c.node.name,c)},TSTypeReference(c){let l=c.node.typeName;if(gr.isIdentifier(l))o(l.name,c);else{let d=om(l);d&&o(d,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function Jc(e,t){let n=xe(e.node),r=new Set;return mo(e,o=>{let i=o.scope.getBinding(o.node.name);i&&(n&&Lt(i.path.node,n)||hn(i,o.node.name,t)||r.add(o.node.name))}),r.size>0?{ok:!1,bindingNames:[...r].sort(),reason:"Cannot move repeat-backed child because the repeat collection is not visible at the target"}:{ok:!0}}function sm(e){let t=[];for(let n of e.callbackPath.node.params){if(gr.isIdentifier(n)){t.push(n.name);continue}if(gr.isRestElement(n)&&gr.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 am(e,t){return{...e,callbackParams:t}}function Xc(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function go(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 cm(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 KI(e){return e.target.kind==="node"?e.target.key:null}function UI(e){return"kind"in e}function rs(e){return!UI(e)}function Yc(e,t){let n=ss.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=ss.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function zc(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=Ft(n,be(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function Qc(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 JI(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function XI(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 Wc(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function zI(e){let t=_p(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=Vc(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=WI({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=ym(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?ts(o):!0}}}function WI(e){let t=xe(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=YI(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=QI(e.callSitePath,c.propName,e.source);if(!l.ok){o=l.reason;return}let d=HI(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=Jc(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}hn(a,s.node.name,e.targetParentPath)||r.add(s.node.name)};return e.sourceContext.collectionPath.isIdentifier()&&e.sourceContext.collectionPath.isReferencedIdentifier()&&i(e.sourceContext.collectionPath),e.sourceContext.collectionPath.traverse({ReferencedIdentifier(s){s.isIdentifier()&&i(s)}}),o?{ok:!1,reason:o}:r.size>0?{ok:!1,reason:`Cannot move prop-backed repeat child because the collection depends on bindings outside the target scope: ${[...r].sort().join(", ")}`}:n.size===0?{ok:!1,reason:"Cannot move repeat-backed child out of its component without an explicit prop mapping"}:{ok:!0,collectionExpression:qI(e.source,t,[...n.values()])}}function HI(e,t){if(t.length===0)return e;let n=ym(e);if(!n)return null;let r=ts(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=GI(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function GI(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function YI(e,t,n){let r=ZI(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=cr(t,o);if(!i)return null;let s=r?.range??xe(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function ZI(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!Lt(n.node,t)||n.node.computed||!fe.isIdentifier(n.node.property))return null;let r=xe(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function QI(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()&&fe.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=pr(n,s.node);return a?{ok:!0,expression:a,expressionPath:s}:{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' cannot be read`}}function qI(e,t,n){let r=e.slice(t.start,t.end),o=[...n].sort((i,s)=>s.start-i.start);for(let i of o)r=r.slice(0,i.start-t.start)+i.text+r.slice(i.end-t.start);return r}function ym(e){try{let n=hm.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=fe.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&fe.isExpression(r)?r:null}catch{return null}}function eC(e){let t=xe(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=lm(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let d=lm(c,e.targetFile,e.targetFile);(!d||d.moduleFile!==a.moduleFile||!tC(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 mo(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 tC(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 lm(e,t,n){let r=nC(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(".")?Yc(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=fe.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 nC(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function um(e,t,n,r){let o=Mc(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=pr(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=rC(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${iC(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function rC(e,t){return oC(e.node)?t:`(${t})`}function oC(e){return fe.isIdentifier(e)||fe.isThisExpression(e)||fe.isSuper(e)||fe.isMemberExpression(e)||fe.isOptionalMemberExpression(e)||fe.isCallExpression(e)||fe.isOptionalCallExpression(e)||fe.isBooleanLiteral(e)||fe.isNumericLiteral(e)||fe.isStringLiteral(e)||fe.isNullLiteral(e)||fe.isUnaryExpression(e)}function iC(e){return e.trim().startsWith("<")?e:`(${e})`}var sC={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 os(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=sC[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 aC(e,t){for(let n of e.program.body){if(!fe.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>fe.isImportDefaultSpecifier(o));if(r&&fe.isImportDefaultSpecifier(r))return r.local.name}return null}function cC(e,t,n){for(let r of e.program.body){if(!fe.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>fe.isImportSpecifier(i)&&(fe.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&fe.isImportSpecifier(o))return o.local.name}return null}function dm(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 fm(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function lC(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=Qc(e),o=Je(t);if(n.exportName!=="default"){let a=o?cC(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?fm(r,dm(o)):r;return{localName:c,importStep:Hc(e,c)}}if(!o)return{localName:r,importStep:Hc(e,r)};let i=aC(o,n.source);if(i)return{localName:i};let s=fm(r,dm(o));return{localName:s,importStep:Hc(e,s)}}function uC(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??Qc(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 dC(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?fC(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function fC(e){return Object.fromEntries(Object.entries(e).filter(t=>Zc(t[1])))}function Zc(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(Zc):typeof e=="object"?Object.values(e).every(Zc):!1}function Hc(e,t=Qc(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 pm(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 pC(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function hr(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function qc(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function ho(e){let t=e.path??[];for(let n=t.length-1;n>=0;n-=1){let r=t[n];if(r.kind==="index")return{locator:qc(e,t.slice(0,n)),index:r.index}}return null}function Gc(e,t){return e.locator?e.collectionPathMap?.[t]?qc(e.locator,e.collectionPathMap[t]):ho(e.locator)?gC(e.locator,hC(t,e.collectionIndexMap)):null:null}function mC(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:xm(o,t)}function xm(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=xm(r,t);return o===void 0?void 0:{[n.name]:o}}function gC(e,t){let n=e.path??[];for(let r=n.length-1;r>=0;r-=1)if(n[r].kind==="index"){let i=[...n];return i[r]={kind:"index",index:t},qc(e,i)}return null}function hC(e,t){return t?.[e]??e}function mm(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 yC(e,t){return xC(e.root,t.root)&&SC(e.path??[],t.path??[])}function xC(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&&bC(e.sourceRange,t.sourceRange)}}function bC(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function SC(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 is=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:hr(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:hr(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:hr(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:hr(t.kind,t.params.kind)};let r=t;if(!rs(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=pm(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:hr(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:hr(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=KI(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):gm(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 gm(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:be(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?Qp({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=Gc(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:be(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=Gc(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:be(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=ce(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!JI(a.match.path))return{ok:!0,value:r};let c=XI(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=Gc(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=ce(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=ho(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=go(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:be(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||Xp(n,t)>1)return null;let r=Yc(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(!rs(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=go(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=Rp(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=os(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"?lC(n.params.node,this.graph.getFileContent(r.file)):void 0,y=E?.importStep;return y&&h.push({order:b++,file:r.file,type:"add-import",moduleSpecifier:y.moduleSpecifier,imports:y.imports}),h.push({order:b++,file:r.file,type:"insert-child",parentLocator:be(r),node:{jsx:uC(n.params.node,E?.localName)},placement:n.params.position.relation,anchorLocator:i?be(i):void 0}),this.buildPlan(t,n,h,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!rs(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:dC(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(!rs(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=ho(a.locator);if(!c)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let l=mC(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"?mm(0,a.collectionIndexMap):mm(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=go(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 mr(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:")||nm(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&&mr(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(!po(m,u))return null;if(a&&(s==="before"||s==="after")){let h=bt(l,a),b=h?Bt(c,h):null;if(!po(m,b))return null}if(qi(d,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let g=$c(c,r,o);return g.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:be(r),targetParentLocator:be(o),placement:s,anchorLocator:a?be(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&&mr(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(po(m,u))return null;if(u&&!em(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 k=Bc(c,l,a);if(u&&!po(u,k)||!u&&k)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 k=os(o,{kind:"native-tag",tag:r.tag});if(k)return{ok:!1,errorCode:"unsupported-operation",reason:k}}let g=zc(this.graph,r);if(!g)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(qi(d,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let h=um(c,d,f,g);for(let k of h.conditionPaths){let C=Uc(k,f,m);if(!C.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${C.bindingNames.join(", ")}`}}let b=Kc(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=im(m,f);if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its callback parameters depend on bindings outside the target scope: ${E.bindingNames.join(", ")}`};let y=m;if(r.component!==o.component){let k=zI({source:c,ast:l,sourceContext:m,sourceNode:r,targetParent:o,targetParentPath:f});if(!k.ok)return{ok:!1,errorCode:"unsupported-operation",reason:k.reason};y=k.context}else{let k=Jc(m.collectionPath,f);if(!k.ok)return{ok:!1,errorCode:"unsupported-operation",reason:k.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${k.bindingNames.join(", ")}`}}return this.buildPlan(t,n,[{order:0,file:r.file,type:"move-repeat-template-child",locator:be(r),targetParentLocator:be(o),placement:s,anchorLocator:a?be(a):void 0,repeatExpression:Xc(y,h.sourceJsx),selectionContext:Ln(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&mr(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=Hp({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=Vc(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")&&Bc(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 M=os(o,{kind:"native-tag",tag:r.tag});if(M)return{ok:!1,errorCode:"unsupported-operation",reason:M}}let y=zc(this.graph,r);if(!y)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(qi(u,g))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let k=um(c,u,g,y);for(let M of k.conditionPaths){let D=Uc(M,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 C=Kc(u,g,b,{preserveConditionalBoundary:k.conditionPaths.length>0});if(!C.ok)return{ok:!1,errorCode:"unsupported-operation",reason:C.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${C.bindingNames.join(", ")}`};let N=eC({sourceFile:r.file,targetFile:o.file,sourceContext:b,targetParentPath:g});if(!N.ok)return{ok:!1,errorCode:"unsupported-operation",reason:N.reason};let T=sm(b);if(!T.ok)return{ok:!1,errorCode:"unsupported-operation",reason:T.reason};let R=am(b,T.callbackParams),A=[{order:0,file:r.file,type:"remove-node",locator:be(r),removeWhitespace:!0}];for(let M of N.imports)A.push({order:A.length,file:o.file,type:"add-import",moduleSpecifier:M.moduleSpecifier,imports:M.imports});return A.push({order:A.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:be(o),expression:Xc(R,k.sourceJsx),placement:s,anchorLocator:a?be(a):void 0,selectionContext:Ln(o)}),this.buildPlan(t,n,A,i)}async planMoveNode(t,n,r,o){if(!o.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};if("kind"in n.params.target&&n.params.target.kind==="source-sibling"){let k=n.params.target,C=this.graph.getNode(k.anchorKey);if(!C||r.file!==C.file||r.component!==C.component)return{ok:!1,errorCode:"locator-miss",reason:"Source sibling move requires a sibling in the same component file"};let N=this.graph.getFileVersion(r.file);if(n.documentVersion!==N)return{ok:!1,errorCode:"stale-version",reason:`Document version ${n.documentVersion} is stale or otherwise does not match source sibling file version (current: ${N})`};let T=this.graph.getFileContent(r.file),R=Je(T),A=R?bt(R,r):null,M=R?bt(R,C):null,D=A?.parentPath,L=M?.parentPath;if(!A||!M||!D||!L||D.node!==L.node||!D.isJSXFragment()&&!(D.isJSXElement()&&_e(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:be(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:k.relation,anchorLocator:be(C),selectionContext:Ln(r)}],o):{ok:!1,errorCode:"locator-miss",reason:"Source Fragment has no stable source range"}}let i=pm(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(pC(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 k=n.params.target.relation,C=i.anchorNode&&(k==="before"||k==="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:k,anchorSourceId:C?.kind==="external-entry"?C.sourceId:null,parentKey:"parentKey"in n.params.target?n.params.target.parentKey:null}}],o)}let l=r.file!==s.file,d=n.params.target.relation,f=i.anchorNode,m=this.graph.getTextProvenance?.(r.key,0)??null,u=go(r,c,m);if(u&&!Wc(u)&&!cm(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 k=c,C=await this.graph.getTextWriteTarget(f.key,0);if(k?.kind==="value-binding"&&C?.kind==="value-binding"&&k.locator&&C.locator){let N=ho(k.locator),T=ho(C.locator);if(N&&T&&k.file===C.file&&yC(N.locator,T.locator)){let R=N.index,A=T.index,M=d==="before"?A-(R<A?1:0):A+(R<A?0:1);return this.buildPlan(t,n,[{order:0,file:k.file,type:"move-array-item",locator:N.locator,fromIndex:R,toIndex:M}],o)}}}if(r.isRepeatItemRoot&&mr(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=Wc(u)?u:g;if(h&&Wc(h)){let k=this.planRepeatTemplateInternalMove(t,n,r,s,o,d,f);if(k)return k;let C=this.planRepeatTemplateHoistMove(t,n,r,s,o,d,f);if(C)return C;let N=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,d,f);return N||{ok:!1,errorCode:"unsupported-operation",reason:h}}if(g)return{ok:!1,errorCode:"unsupported-operation",reason:g};let b=await this.getUpstreamBackedDescendantReason(r);if(b)return{ok:!1,errorCode:"unsupported-operation",reason:b};if(r.tag&&r.tag.toLowerCase()===r.tag){let k=os(s,{kind:"native-tag",tag:r.tag});if(k)return{ok:!1,errorCode:"unsupported-operation",reason:k}}if(l)return this.planCrossFileMove(t,n,r,s,o,d,f);let E=$c(this.graph.getFileContent(r.file),r,s);if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:E.reason??`Cannot move node because it depends on bindings outside the target scope: ${E.bindingNames.join(", ")}`};let y=[{order:0,file:r.file,type:"move-node",locator:be(r),targetParentLocator:be(s),placement:d,anchorLocator:f?be(f):void 0,selectionContext:Ln(s)}];return this.buildPlan(t,n,y,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,d=this.graph.getFileContent(r.file),f=zc(this.graph,r)??`<${r.component} />`,m=wp(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:be(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let g=r.tag??r.component,b={moduleSpecifier:Yc(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:be(o),node:{jsx:f},placement:s,anchorLocator:a?be(a):void 0,selectionContext:Ln(o)})}else c.push({order:l++,file:o.file,type:"insert-child",parentLocator:be(o),node:{jsx:f},placement:s,anchorLocator:a?be(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:Ie(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 gm(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 ol from"@babel/generator";import{parse as OC}from"@babel/parser";import*as w from"@babel/types";import*as $t from"@babel/types";import el from"@babel/generator";import*as ve from"@babel/types";var EC=typeof el=="function"?el:el.default,vC=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,kC=/^((?:https?:)?\/\/)[^/@\s]+@/i,IC=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function Sm(e,t){let n=jt(e.callee);if(!n)return null;if(n==="fetch")return tl(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(bm(r))return tl(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(bm(r))return tl(e.arguments[0],r,t,["ky client contract"])}return null}function tl(e,t,n,r){if(!e||ve.isSpreadElement(e)||ve.isJSXNamespacedName(e))return NC(t,n,r,"missing url argument");let o=yo(e);return{sourceKind:wC(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 yo(e){if(ve.isStringLiteral(e))return as(e.value);if(ve.isTemplateLiteral(e))return as(CC(e));if(ve.isBinaryExpression(e)&&e.operator==="+"){let t=yo(e.left),n=yo(e.right);return!t&&!n?void 0:as(`${t??nl(e.left)}${n??nl(e.right)}`)}if(ve.isMemberExpression(e)){let t=Em(e);if(t)return`env:${t}`}if(!(ve.isCallExpression(e)&&jt(e.callee)==="new URL")){if(ve.isNewExpression(e)&&ve.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!ve.isSpreadElement(t)?yo(t):void 0,o=n&&!ve.isSpreadElement(n)?yo(n):void 0;return o&&r?as(`${o} + ${r}`):r??o}if(ve.isIdentifier(e))return`:${e.name}`}}function CC(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+=nl(r))}return t}function nl(e){if(ve.isIdentifier(e))return`:${e.name}`;if(ve.isMemberExpression(e)){let t=Em(e);if(t)return`env:${t}`}return`:${RC(e)}`}function RC(e){return EC(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function as(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(kC,"$1<redacted>@").replace(IC,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?vC.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function wC(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 NC(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function bm(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function Em(e){return!ve.isMemberExpression(e.object)||!ve.isIdentifier(e.object.object,{name:"process"})||!PC(e.object.property,"env")?null:ve.isIdentifier(e.property)?e.property.name:ve.isStringLiteral(e.property)?e.property.value:null}function PC(e,t){return ve.isIdentifier(e)&&e.name===t}function jt(e){if(ve.isIdentifier(e))return e.name;if(ve.isMemberExpression(e)){let t=jt(e.object),n=ve.isIdentifier(e.property)?e.property.name:ve.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var AC=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),TC=new Set(["getConfig","submit"]);function vm(e,t){let n=FC(jt(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!AC.has(i))return null;let s=rl(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(!TC.has(i))return null;let s=rl(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=rl(e,0)??_C(e,0,"path")??"/cms/:path",s=MC(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 FC(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 km(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 Im(e){let t=jt(e.callee);return typeof t=="string"&&t.startsWith("cms.field.")}function rl(e,t){let n=e.arguments[t];return $t.isStringLiteral(n)?n.value:null}function _C(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 MC(e){return/^\/collections\/([^/]+)(?:\/|$)/.exec(e)?.[1]??null}function Cm(e=4096){if(!Number.isSafeInteger(e)||e<1)throw new RangeError("Re-export relation capacity must be positive.");let t=new Map,n=new Set,r=o=>{let i=t.get(o.fromFile),s=i?.get(o.exportName),a=s?.get(o.targetFile);a?.get(o.maxImportDepth)===o&&(a.delete(o.maxImportDepth),a.size===0&&s.delete(o.targetFile),s.size===0&&i.delete(o.exportName),i.size===0&&t.delete(o.fromFile),n.delete(o))};return{resolve(o,i){let{fromFile:s,exportName:a,targetFile:c,maxImportDepth:l}=o,d=t.get(s)?.get(a)?.get(c)?.get(l);if(d)return d.pending;let f=i();n.size>=e&&r(n.values().next().value);let m={fromFile:s,exportName:a,targetFile:c,maxImportDepth:l,pending:f},u=t.get(s)??new Map,g=u.get(a)??new Map,h=g.get(c)??new Map;return h.set(l,m),g.set(c,h),u.set(a,g),t.set(s,u),n.add(m),f.catch(()=>{r(m)}),f}}}var QO=typeof ol=="function"?ol:ol.default,Mm=new WeakMap;function Om(e){let t=new Map;return Mm.set(t,new Map([...e].map(n=>[n.file,n]))),t}var LC={maxFunctionDepth:8,maxImportDepth:6},DC=new Set(["src","href","alt","poster","content","title","aria-label"]),Rm=new WeakMap;function BC(e,t,n){let r=Rm.get(t.fileCache);r||(r=new WeakMap,Rm.set(t.fileCache,r));let o=r.get(e);if(!o){o={imported:[],local:new Map};let d=0;for(let f of e.elements.values()){let m={element:f,order:d++};f.importedFrom&&f.exportName&&o.imported.push(m);let u=o.local.get(f.sourceFile);u||(u=new Map,o.local.set(f.sourceFile,u));let g=u.get(f.tag)??[];g.push(m),u.set(f.tag,g)}r.set(e,o)}let i=o.local.get(t.file)?.get(n)??[],s=o.imported,a=[],c=0,l=0;for(;c<s.length||l<i.length;){let d=s[c],f=i[l];d&&(!f||d.order<f.order)?(a.push(d.element),c++):f&&(!d||f.order<d.order)?(a.push(f.element),l++):(a.push(d.element),c++,l++)}return a}async function Lm(e){if(!e.element.textSegments.some(s=>s.source)&&!(e.element.attributes??[]).some(s=>s.source&&Nm(s,e.element))&&!e.graph.regions.some(s=>s.ownerKey===e.element.identity.key&&(s.kind==="repeat-region"||s.kind==="conditional-region")))return{hasDynamicData:!1,bindings:[]};let t=e.fileCache??new Map,n=cl(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...LC,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:Zm(n,e.element.componentName)};await Dm(e.element.componentName,e.graph,r);let o=[];o.push(...await KC(e.element,e.graph,r),...await UC(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await JC(s,e.element,e.graph,r);a&&o.push(us(a,"text","children"))}for(let s of e.element.attributes??[]){let a=Nm(s,e.element);if(!a)continue;let c=await Vm(s.source,e.element,e.graph,r);c&&o.push(us(c,a,s.name))}let i=iR(o).sort(Gm);return{hasDynamicData:i.length>0,bindings:i}}async function Dm(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 BC(t,n,e)){if(l.sourceFile===n.file&&l.tag===e){s.push(l);continue}!l.importedFrom||!l.exportName||l.importedFrom===n.file&&l.exportName!==i||(l.importedFrom===n.file||await jC(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 $m(l.sourceFile,n);if(!f)continue;let m=fs(f,n,{importDepth:n.importDepth+1});m.paramSources.clear(),m.scopeVariables=Zm(f,l.componentName),await Dm(l.componentName,t,m);let u=await $C(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=Wm(d);f.length===1&&c.set(l,f[0])}VC(o,c,n)}var wm=new WeakMap;function jC(e,t,n,r){let o=wm.get(r.fileCache);return o||(o=Cm(),wm.set(r.fileCache,o)),o.resolve({fromFile:e,exportName:t,targetFile:n,maxImportDepth:r.options.maxImportDepth},()=>Bm(e,t,n,r))}async function Bm(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 $m(e,r))?.imports.get(t);if(!s||!Pt(s.source))return!1;let a=await eg(e,s.source,r.exists);return a?a===n?!0:Bm(a,s.importedName,n,r,o):!1}async function $C(e,t){let n=new Map,r=t.analysis.jsxElementsByRange.get(jm(e.sourceRange));if(r)for(let i of r.openingElement.attributes)!w.isJSXAttribute(i)||!w.isJSXIdentifier(i.name)||!w.isJSXExpressionContainer(i.value)||!w.isExpression(i.value.expression)||n.set(i.name.name,i.value.expression);let o=new Map;for(let[i,s]of n){let a=await je(s,t);a&&o.set(i,a)}return o}function jm(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}async function $m(e,t){let n=t.fileCache.get(e);if(n)return n;if(!await t.exists(e))return null;let r=await t.readFile(e);return cl(e,r,t.fileCache)}function VC(e,t,n){if(w.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,al(Object.fromEntries(t),n.file));return}if(w.isObjectPattern(e))for(let r of e.properties){if(!w.isObjectProperty(r)||r.computed||!w.isIdentifier(r.key))continue;let o=t.get(r.key.name);if(!o)continue;let i=w.isAssignmentPattern(r.value)?r.value.left:r.value;w.isIdentifier(i)&&n.paramSources.set(i.name,ze(o))}}function Nm(e,t){return e.name==="dangerouslySetInnerHTML"?"richtext":DC.has(e.name)?"attribute":t.importedFrom||/^[A-Z]/.test(t.tag)?"component-prop":null}async function KC(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 ds(i.collectionSource,n);s&&r.push(us(Dn(s),"repeat-region",i.collectionExpression))}return r}async function UC(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 ds(i.conditionSource,n);s&&r.push(us(Dn(s),"conditional-region",i.conditionExpression))}return r}async function JC(e,t,n,r){return Vm(e.source,t,n,r)}async function Vm(e,t,n,r){let o=await XC(e,t,n,r);return o||ds(e,r)}async function XC(e,t,n,r){if(!e)return null;let o=zC(e.base,t,n);if(!o)return null;let i=await ds(o.collectionSource,r);return i?Eo(i,e.path,!0):null}function zC(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 ds(e,t){if(!e)return null;let n=await Km(e.base,t);return n?Eo(n,e.path,!1):null}async function Km(e,t){let n=t.paramSources.get(e);if(n)return ze(n);if(t.variableCache.has(e))return sR(t.variableCache.get(e)??null);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let r=await WC(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 Qm(i,t);if(s){let a=fs(s,t,{importDepth:t.importDepth+1}),c=qm(i,s);if(c){let f=(await Bn(c,[],a)).returnSource;return t.variableCache.set(e,f?ze(f):null),t.resolvingVariables.delete(e),f}let l=s.variables.get(i.importedName);if(l){let 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 WC(e,t){let n=t.analysis.stateSetters.get(e);if(!n)return null;let r=t.analysis.stateSetterCandidates.get(n)??[];for(let o of r){let i=await je(o,t);if(i)return i}return null}async function je(e,t){if(w.isIdentifier(e))return Km(e.name,t);if(w.isMemberExpression(e)||w.isOptionalMemberExpression(e)){let n=w.isMemberExpression(e)?km(e,{file:t.file}):null;if(n)return zm(n);let r=await HC(e,t);if(!r)return null;let o=rR(e);return Eo(r,o,!1)}if(w.isAwaitExpression(e))return w.isExpression(e.argument)?je(e.argument,t):null;if(w.isCallExpression(e))return Um(e,t);if(w.isObjectExpression(e)){let n=await Jm(e,t);return Object.keys(n).length>0?al(n,t.file):null}if(w.isConditionalExpression(e)){let n=await je(e.consequent,t),r=await je(e.alternate,t);return So(Am(n,r))}if(w.isLogicalExpression(e)){let n=await je(e.left,t),r=await je(e.right,t);return So(Am(n,r))}return w.isTSAsExpression(e)||w.isTSSatisfiesExpression(e)||w.isTSNonNullExpression(e)||w.isTypeCastExpression(e)||w.isParenthesizedExpression(e)?je(e.expression,t):null}async function HC(e,t){let n=e;for(;w.isMemberExpression(n)||w.isOptionalMemberExpression(n);)n=n.object;return w.isExpression(n)?je(n,t):null}async function Um(e,t){let n=vm(e,{file:t.file,imports:t.analysis.imports});if(n)return zm(n);if(Im(e)){let f=e.arguments[0];if(f&&w.isExpression(f))return So(await je(f,t))}let r=await GC(e,t);if(r)return r;let o=Sm(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 QC(e,t);if(i)return i;let s=await qC(e,t);if(s)return s;let a=await eR(e,t);if(a)return a;let c=await tR(e,t);if(c)return c;let l=[];for(let f of e.arguments)if(w.isExpression(f)){let m=await je(f,t);m&&l.push(m)}let d=Wm(l);return d.length===1?So(d[0]):null}async function GC(e,t){let n=jt(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=ZC(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(w.isIdentifier(s)){let a=await bo(s.name,t);if(a)return(await Bn(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!w.isObjectExpression(r))return cs(t.file,`${n} without static options`);let o=YC(r,"queryFn");if(!o)return cs(t.file,`${n} without queryFn`);if(w.isIdentifier(o)){let i=await bo(o.name,t);return i?(await Bn(i.node,[],i.context)).returnSource:cs(t.file,`${n} queryFn unresolved`)}return w.isArrowFunctionExpression(o)||w.isFunctionExpression(o)?(await Bn(o,[],t)).returnSource:w.isCallExpression(o)?Um(o,t):null}function YC(e,t){for(let n of e.properties){if(!w.isObjectProperty(n)||!w.isExpression(n.value))continue;if(Xm(n)===t)return n.value}return null}function ZC(e,t,n){return w.isStringLiteral(e)?{sourceKind:e.value.startsWith("/api/")?"site-api-route":"external-api",sourceType:"api-field",endpointPattern:e.value,confidence:"exact",readonly:!0,evidence:[{file:t,reason:n}]}:null}async function QC(e,t){if(!w.isMemberExpression(e.callee)||!w.isIdentifier(e.callee.property))return null;let n=e.callee.property.name;if(!["map","filter","slice","sort","toSorted"].includes(n))return null;let r=w.isExpression(e.callee.object)?await je(e.callee.object,t):null;if(!r)return null;if(n!=="map")return Dn(r);let o=e.arguments[0];if(w.isIdentifier(o)){let i=await bo(o.name,t);if(!i)return Dn(r);let s=await Bn(i.node,[r],i.context);return{...Dn(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(w.isArrowFunctionExpression(o)||w.isFunctionExpression(o)){let i=await Bn(o,[r],t);return{...Dn(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return Dn(r)}async function qC(e,t){return!w.isMemberExpression(e.callee)||!w.isIdentifier(e.callee.property,{name:"json"})||!w.isExpression(e.callee.object)?null:je(e.callee.object,t)}async function eR(e,t){return!w.isMemberExpression(e.callee)||!w.isIdentifier(e.callee.property,{name:"then"})||!w.isExpression(e.callee.object)?null:So(await je(e.callee.object,t))}async function tR(e,t){if(!w.isIdentifier(e.callee))return null;let n=await bo(e.callee.name,t);if(!n)return null;let r=[];for(let i of e.arguments){if(!w.isExpression(i)){r.push(cs(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 bo(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 Qm(r,t);if(!o)return null;let i=fs(o,t,{importDepth:t.importDepth+1}),s=qm(r,o);return s?{node:s,context:i}:bo(r.importedName,i)}async function Bn(e,t,n){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let r=fs(n.analysis,n,{functionDepth:n.functionDepth+1});r.scopeVariables=n.analysis.functionVariables.get(e),e.params.forEach((c,l)=>{let d=t[l];d&&il(c,oR(d),r)});let o=nR(e),i=null,s,a=!1;for(let c of o){if(w.isObjectExpression(c)){s={...s??{},...await Jm(c,r)},i=i??al(s,n.file);continue}let l=await je(c,r);if(l){if(!i){i=l;continue}let d=sl(i,l);if(!d){a=!0,i=null;continue}i=d}}return{returnSource:a?null:i,...s?{objectReturnMap:s}:{}}}function il(e,t,n){if(w.isIdentifier(e)){n.paramSources.set(e.name,ze(t));return}if(w.isAssignmentPattern(e)){il(e.left,t,n);return}if(w.isObjectPattern(e))for(let r of e.properties){if(!w.isObjectProperty(r)||r.computed||!w.isIdentifier(r.key))continue;let o=Eo(t,[{kind:"property",name:r.key.name}],!0),i=w.isAssignmentPattern(r.value)?r.value.left:r.value;il(i,o,n)}}function nR(e){if(w.isArrowFunctionExpression(e)&&w.isExpression(e.body))return[e.body];let t=[],n=e.body;if(!w.isBlockStatement(n))return t;let r=o=>{if(w.isFunction(o)&&o!==e)return;if(w.isReturnStatement(o)){o.argument&&w.isExpression(o.argument)&&t.push(o.argument);return}let i=w.VISITOR_KEYS[o.type];for(let s of i??[]){let a=o[s];if(Array.isArray(a))for(let c of a)w.isNode(c)&&r(c);else w.isNode(a)&&r(a)}};return r(n),t}async function Jm(e,t){let n={};for(let r of e.properties){if(!w.isObjectProperty(r))continue;let o=Xm(r);if(!o||!w.isExpression(r.value))continue;let i=await je(r.value,t);i&&(n[o]=i)}return n}function Xm(e){return w.isIdentifier(e.key)&&!e.computed?e.key.name:w.isStringLiteral(e.key)?e.key.value:null}function rR(e){let t=[],n=e;for(;w.isMemberExpression(n)||w.isOptionalMemberExpression(n);){let r=n.property;n.computed?w.isStringLiteral(r)?t.unshift({kind:"property",name:r.value}):w.isNumericLiteral(r)&&t.unshift({kind:"index",index:r.value}):w.isIdentifier(r)&&t.unshift({kind:"property",name:r.name}),n=n.object}return w.isIdentifier(n),t}function Eo(e,t,n){if(t.length===0)return ze(e);let r=t[0];if(r?.kind==="property"&&e.fieldMap?.[r.name])return Eo(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=xo(o.valuePath,"data.items[]"),o.cmsFieldRoot=!1,o):i[0]==="fields"?(o.fieldPath=xo(o.fieldPath,i.slice(1).join(".")),o.cmsFieldRoot=!0,o):o.cmsFieldRoot||n||o.fieldMap?(o.fieldPath=xo(o.fieldPath,i.join(".")),o):(o.valuePath=xo(o.valuePath,Pm(t)),o)}return o.valuePath=xo(o.valuePath,Pm(t)),o}function Pm(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function xo(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function zm(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 oR(e){let t=ze(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&(t.cmsFieldRoot=!1),t}function So(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 Am(e,t){return e?t?sl(e,t):ze(e):t?ze(t):null}function sl(e,t){if(ls(e)!==ls(t))return null;let n=Ym(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function Wm(e){let t=new Map;for(let n of e){let r=ls(n),o=t.get(r);t.set(r,o?sl(o,n):ze(n))}return[...t.values()]}function ls(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,ls(r)])):void 0;return JSON.stringify({sourceKind:e.sourceKind,sourceType:e.sourceType,endpointPattern:e.endpointPattern,operation:e.operation,collection:e.collection,fieldPath:e.fieldPath,valuePath:e.valuePath,cmsFieldRoot:e.cmsFieldRoot,fieldMap:t})}function al(e,t){let n=Object.values(e)[0];return{sourceKind:n?.sourceKind??"unknown-api",sourceType:n?.sourceType??"api-field",endpointPattern:n?.endpointPattern,operation:n?.operation,collection:n?.collection,confidence:n?.confidence??"partial",readonly:!0,evidence:n?.evidence??[{file:t,reason:"object return map"}],fieldMap:e}}function cs(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function us(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 Hm(e){let t=[...e].sort(Gm),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 iR(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 Gm(e,t){return Tm(e.targetKind)-Tm(t.targetKind)||Ym(e.confidence,t.confidence)||Fm(e.sourceKind)-Fm(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function Tm(e){return{"repeat-region":0,"conditional-region":1,text:2,richtext:3,attribute:4,"component-prop":5}[e]}function Fm(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function Ym(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function cl(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=Mm.get(n)?.get(e),i=o?.source===t?o.ast:OC(t,{sourceType:"module",plugins:["jsx","typescript"]}),s={file:e,source:t,ast:i,variables:new Map,functions:new Map,imports:new Map,stateSetters:new Map,stateSetterCandidates:new Map,jsxElementsByRange:new Map,functionVariables:new WeakMap},a=[],c=[];w.traverse(i,{enter(f){switch(w.isFunction(f)&&a.push(f),f.type){case"CallExpression":c.push(f);break;case"JSXElement":{let m=f.loc;if(!m)return;let u=jm({startLine:m.start.line,startColumn:m.start.column,endLine:m.end.line,endColumn:m.end.column});s.jsxElementsByRange.has(u)||s.jsxElementsByRange.set(u,f);break}case"ImportDeclaration":{let m=f.source.value;for(let u of f.specifiers)w.isImportSpecifier(u)&&w.isIdentifier(u.local)?s.imports.set(u.local.name,{source:m,importedName:w.isIdentifier(u.imported)?u.imported.name:u.imported.value,localName:u.local.name,isDefault:!1}):w.isImportDefaultSpecifier(u)&&s.imports.set(u.local.name,{source:m,importedName:"default",localName:u.local.name,isDefault:!0});break}case"FunctionDeclaration":{f.id?.name&&s.functions.set(f.id.name,f);break}case"VariableDeclarator":{let m=a.at(-1),u=m&&(w.isFunctionDeclaration(m)||w.isFunctionExpression(m)||w.isArrowFunctionExpression(m))?m:null,g=u?s.functionVariables.get(u)??new Map:s.variables;u&&!s.functionVariables.has(u)&&s.functionVariables.set(u,g);for(let h of yr(f.id))g.set(h,w.isExpression(f.init)?f.init:null);if(w.isArrayPattern(f.id)&&w.isCallExpression(f.init)&&jt(f.init.callee)==="useState"){let[h,b]=f.id.elements;w.isIdentifier(h)&&w.isIdentifier(b)&&s.stateSetters.set(h.name,b.name)}w.isIdentifier(f.id)&&_m(f.init)&&s.functions.set(f.id.name,f.init);break}case"ExportNamedDeclaration":{let m=f.declaration,u=f.source?.value;if(u)for(let g of f.specifiers){if(!w.isExportSpecifier(g))continue;let h=w.isIdentifier(g.exported)?g.exported.name:g.exported.value,b=g.local.name;s.imports.set(h,{source:u,importedName:b,localName:h,isDefault:b==="default"})}if(w.isFunctionDeclaration(m)&&m.id?.name&&s.functions.set(m.id.name,m),w.isVariableDeclaration(m))for(let g of m.declarations)w.isIdentifier(g.id)&&_m(g.init)&&s.functions.set(g.id.name,g.init);break}case"ExportDefaultDeclaration":{let m=f.declaration;if((w.isFunctionDeclaration(m)||w.isFunctionExpression(m)||w.isArrowFunctionExpression(m))&&s.functions.set("default",m),w.isIdentifier(m)){let u=s.functions.get(m.name);u&&s.functions.set("default",u)}break}}},exit(f){w.isFunction(f)&&a.pop()}});let l=new Set(s.stateSetters.values()),d=(f,m)=>{let u=s.stateSetterCandidates.get(f)??[];u.push(m),s.stateSetterCandidates.set(f,u)};if(l.size>0)for(let f of c){let m=w.isIdentifier(f.callee)?f.callee.name:null;m&&l.has(m)&&w.isExpression(f.arguments[0])&&d(m,f.arguments[0]);let u=new Set;for(let g of f.arguments)w.isIdentifier(g)&&g.name!==m&&l.has(g.name)&&u.add(g.name);for(let g of u)d(g,f)}return n.set(e,s),s}function yr(e){return!e||w.isVoidPattern(e)?[]:w.isIdentifier(e)?[e.name]:w.isObjectPattern(e)?e.properties.flatMap(t=>w.isObjectProperty(t)?yr(t.value):yr(t.argument)):w.isArrayPattern(e)?e.elements.flatMap(t=>t?yr(w.isRestElement(t)?t.argument:t):[]):w.isAssignmentPattern(e)?yr(e.left):w.isRestElement(e)?yr(e.argument):[]}function _m(e){return w.isFunctionExpression(e)||w.isArrowFunctionExpression(e)}function Zm(e,t){let n=e.functions.get(t)??e.functions.get("default");return n?e.functionVariables.get(n):void 0}async function Qm(e,t){let n=await eg(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return cl(n,r,t.fileCache)}function qm(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function eg(e,t,n){return Pt(t)?Sn(e,t,n):null}function fs(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 sR(e){return e?ze(e):null}function ze(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,ze(n)]))}:{}}}import*as ul from"@babel/parser";import ll from"@babel/traverse";import*as Y from"@babel/types";import{classifySiteEditPropertyName as aR}from"@vcp-dev/contracts";var dl=typeof ll=="function"?ll:ll.default;function fl(e){let t=aR(e.propertyName);if(t.owner!=="generic")return ut("invalid-property",t.diagnostic?.message??`Property '${e.propertyName}' is not a generic property`);let n=e.selectionRef;if(!n)return ut("missing-selection-ref","A repeat property target requires a complete selection reference");if(n.key!==e.element.identity.key)return ut("selection-mismatch","Selection reference does not identify the requested element");if(n.instanceIndex===void 0)return ut("missing-instance-index","A repeat property target requires an instance index");let r;try{r=ul.parse(e.source,{sourceType:"module",plugins:["typescript","jsx"]})}catch(b){return ut("repeat-not-found",`Unable to parse repeat source: ${b instanceof Error?b.message:String(b)}`)}let o=cR(r,e.element.sourceRange);if(!o)return ut("repeat-not-found","The selected element is not inside a supported map repeat");if(!Y.isIdentifier(o.callback.params[0]))return ut("unsupported-callback","Repeat property materialization requires an identifier callback item");let i=lR(r,o.collection,e.file,e.sources);if(!i)return ut("collection-not-found","The repeat collection is not a visible local static array");let{array:s,locator:a,sourceFile:c}=i,l=[],d=[];for(let[b,E]of s.elements.entries()){if(!E||!Y.isObjectExpression(E)||!sg(E))return ut("unsafe-collection","Repeat materialization requires an array of local static objects without spreads");let y=[{kind:"index",index:b}];l.push(y),d.push({kind:"value",root:a.root,path:y})}let f=d.length;if(n.instanceCount!==void 0&&n.instanceCount!==f)return ut("count-mismatch",`Selection reports ${n.instanceCount} instances but the source collection has ${f}`);let m=n.instanceIndex;if(m>=f)return ut("index-out-of-range",`Selected repeat instance ${m} is outside the source collection`);let u=s.elements[m];if(!u||!Y.isObjectExpression(u))return ut("unsafe-collection","Selected repeat item is not an object");let g=gR(e.element,e.propertyName),h=pR(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:mR(u,e.propertyName),...g?{property:g}:{},selectionRef:n}:ut("unsafe-property-source",`Property '${e.propertyName}' has a dynamic or unsupported source in the repeat item`)}function cR(e,t){let n=[];return dl(e,{CallExpression(r){let o=tg(r.node);o&&rg(o.callback,t)&&n.push({...o,span:ng(r.node)})},OptionalCallExpression(r){let o=tg(r.node);o&&rg(o.callback,t)&&n.push({...o,span:ng(r.node)})}}),n.sort((r,o)=>r.span-o.span),n[0]??null}function tg(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 lR(e,t,n,r){let o=vo(t);if(o&&Y.isArrayExpression(o))return{array:o,locator:{kind:"value",root:{kind:"expression",sourceRange:cg(o)}},sourceFile:n};if(!Y.isIdentifier(t))return null;let i=[];if(dl(e,{VariableDeclarator(s){Y.isIdentifier(s.node.id)&&s.node.id.name===t.name&&s.node.init&&i.push(s.node)}}),i.length===1){let s=vo(i[0].init);return!s||!Y.isArrayExpression(s)?null:{array:s,locator:{kind:"value",root:{kind:"binding",name:t.name}},sourceFile:n}}return uR(e,t.name,n,r)}function uR(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=fR(n,o.source.value,r);if(!s)return null;let a=Y.isIdentifier(i.imported)?i.imported.name:i.imported.value,c=r.get(s);if(c===void 0)return null;let l;try{l=ul.parse(c,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}let d=dR(l,a),f=d?vo(d):null;return!f||!Y.isArrayExpression(f)?null:{array:f,locator:{kind:"value",root:{kind:"binding",name:a}},sourceFile:s}}return null}function dR(e,t){let n=null;return dl(e,{VariableDeclarator(r){n||!Y.isIdentifier(r.node.id)||r.node.id.name!==t||!r.node.init||!Y.isExpression(r.node.init)||(n=r.node.init)}}),n}function fR(e,t,n){let r=bn(e,t);return[r,r+".tsx",r+".ts",r+".jsx",r+".js",r+"/index.tsx",r+"/index.ts",r+"/index.jsx",r+"/index.js"].find(i=>n.has(i))??null}function vo(e){return Y.isParenthesizedExpression(e)?vo(e.expression):Y.isTSAsExpression(e)?ig(e.typeAnnotation)?vo(e.expression):null:Y.isTSSatisfiesExpression(e)?null:e}function ig(e){return Y.isTSTypeReference(e)&&Y.isIdentifier(e.typeName)&&e.typeName.name==="const"}function sg(e){return e.properties.every(t=>!Y.isObjectProperty(t)||t.computed||!Y.isExpression(t.value)?!1:ps(t.value))}function ps(e){if(Y.isTSAsExpression(e)&&ig(e.typeAnnotation))return ps(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:ps(n));if(Y.isObjectExpression(e))return sg(e);let t=Mt(e);return t.status==="resolved"||t.status==="undefined"}function pR(e,t){let n=e.properties.filter(o=>Y.isObjectProperty(o)&&ag(o.key)===t);if(n.length>1)return null;let r=n[0];return r?Y.isExpression(r.value)?ps(r.value)?"static":Y.isIdentifier(r.value)||Y.isMemberExpression(r.value)?"binding":null:null:"missing"}function mR(e,t){let n=e.properties.filter(o=>Y.isObjectProperty(o)&&ag(o.key)===t);if(n.length>1)return{status:"unresolved"};let r=n[0];return!r||!Y.isExpression(r.value)?{status:"undefined"}:Mt(r.value)}function gR(e,t){let n=e.attributes?.filter(r=>r.name===t)??[];return n.length===1?n[0]:void 0}function ag(e){return Y.isIdentifier(e)?e.name:Y.isStringLiteral(e)?e.value:Y.isNumericLiteral(e)?String(e.value):null}function cg(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 ng(e){return e.start==null||e.end==null?Number.MAX_SAFE_INTEGER:e.end-e.start}function rg(e,t){let n=cg(e);return og(n.startLine,n.startColumn,t.startLine,t.startColumn)<=0&&og(n.endLine,n.endColumn,t.endLine,t.endColumn)>=0}function og(e,t,n,r){return e===n?t-r:e-n}function ut(e,t){return{ok:!1,errorCode:e,reason:t}}import{classifySiteEditPropertyName as tw}from"@vcp-dev/contracts";import*as Q from"@babel/types";import wo from"node:path";import*as $ from"@babel/types";import*as mg from"@babel/parser";import pl from"@babel/traverse";import*as re from"@babel/types";function gs(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 lg(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 Qe(e,t){let n=e;for(let r of t){if(r.kind==="property"){if(n===null||Array.isArray(n)||typeof n!="object"||!(r.name in n))return;n=n[r.name];continue}if(!Array.isArray(n)||r.index<0||r.index>=n.length)return;n=n[r.index]}return n}var Vt=Symbol("not-closed-literal");function ms(e){switch(e.type){case"StringLiteral":case"NumericLiteral":case"BooleanLiteral":return e.value;case"NullLiteral":return null;case"TemplateLiteral":return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:Vt;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":return ms(e.expression);case"ArrayExpression":{let t=[];for(let n of e.elements){if(!n||re.isSpreadElement(n))return Vt;let r=ms(n);if(r===Vt)return Vt;t.push(r)}return t}case"ObjectExpression":{let t={};for(let n of e.properties){if(!re.isObjectProperty(n)||n.computed||n.shorthand||!re.isExpression(n.value))return Vt;let r=re.isIdentifier(n.key)?n.key.name:re.isStringLiteral(n.key)?n.key.value:null;if(!r)return Vt;let o=ms(n.value);if(o===Vt)return Vt;t[r]=o}return t}default:return Vt}}function ug(e){let{resolveBindingTarget:t}=e;async function n(i,s,a,c,l,d,f){let m=ms(i);if(m!==Vt)return m;if(!re.isTemplateLiteral(i)){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 u=s.getBinding(i.name);if(!u)return;let g=await t({currentFile:a,binding:u,readFile:c,exists:l,fileCache:d,visited:f});return g?.kind==="static"?g.value:void 0}if(re.isArrayExpression(i)){let u=[];for(let g of i.elements){if(!g||re.isSpreadElement(g))return;let h=await r(g,s,a,c,l,d,f);if(h===void 0)return;u.push(h)}return u}if(re.isObjectExpression(i)){let u={};for(let g of i.properties){if(!re.isObjectProperty(g)||g.computed)return;let h=null;if(re.isIdentifier(g.key)?h=g.key.name:re.isStringLiteral(g.key)&&(h=g.key.value),!h)return;if(g.shorthand){if(!re.isIdentifier(g.value))return;let E=await r(g.value,s,a,c,l,d,f);if(E===void 0)return;u[h]=E;continue}if(!re.isExpression(g.value))return;let b=await r(g.value,s,a,c,l,d,f);b!==void 0&&(u[h]=b)}return u}if(re.isMemberExpression(i)){let u=await o(i,s,a,c,l,d,f);if(!u)return;let g=s.getBinding(u.base);if(!g)return;let h=await t({currentFile:a,binding:g,readFile:c,exists:l,fileCache:d,visited:f});return!h||h.kind!=="static"?void 0:Qe(h.value,u.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 gg=typeof pl=="function"?pl:pl.default,dg=new WeakMap;function hg(e){try{return mg.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function hs(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=hg(n);return e.set(t,{source:n,ast:o}),o}function ys(e,t){return gl(ko(e).expressionRanges,t,!1)}function yg(e,t){return ko(e).exactExpressions.get(xg(t))??null}function ml(e,t){return gl(ko(e).jsxRanges,t,!0)}function ko(e){let t=dg.get(e);if(t)return t;let n={expressions:[],expressionRanges:[],jsxRanges:[],exactExpressions:new Map};return gg(e,{Expression(r){let o=r;n.expressions.push(o);let i=fg(o,n.expressions.length-1);if(!i)return;n.expressionRanges.push(i);let s=xg(i.range),a=n.exactExpressions.get(s);(!a||i.span<=(a.node.end??0)-(a.node.start??0))&&n.exactExpressions.set(s,o)},JSXElement(r){let o=fg(r,n.jsxRanges.length);o&&n.jsxRanges.push(o)}}),n.expressionRanges.sort(pg),n.jsxRanges.sort(pg),dg.set(e,n),n}function fg(e,t){let n=Io(e.node);return n?{path:e,range:n,traversalIndex:t,span:(e.node.end??0)-(e.node.start??0)}:null}function xg(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}function pg(e,t){return e.range.startLine-t.range.startLine||e.range.startColumn-t.range.startColumn||e.traversalIndex-t.traversalIndex}function gl(e,t,n,r){let o=0,i=e.length;for(;o<i;){let c=o+Math.floor((i-o)/2),l=e[c].range;l.startLine<t.startLine||l.startLine===t.startLine&&l.startColumn<t.startColumn?o=c+1:i=c}let s=null,a=n?1/0:-1;for(let c=o;c<e.length;c++){let l=e[c],d=l.range;if(d.startLine>t.endLine||d.startLine===t.endLine&&d.startColumn>t.endColumn)break;if(d.endLine>t.endLine||d.endLine===t.endLine&&d.endColumn>t.endColumn||r&&!r(l.path))continue;((n?l.span<a:l.span>a)||l.span===a&&(!s||l.traversalIndex>s.traversalIndex))&&(s=l,a=l.span)}return s?.path??null}function Io(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 xr(e,t){if(t)return hl(e,t);let n=lg(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function hl(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Co(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of ko(e).expressions){if(hl(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function bg(e,t,n,r){return gl(ko(e).expressionRanges,r,!0,o=>hl(o.node,t)===n)}function br(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function Ro(e){let t=null;if(gg(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}async function Kt(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=hg(o),s={source:o,ast:i};return n.set(e,s),s}function hR(e){return $.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:$.isMemberExpression(e.callee)&&$.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function yR(e){if(!$.isNewExpression(e)||!$.isIdentifier(e.callee,{name:"Proxy"})||e.arguments.length!==2||!$.isIdentifier(e.arguments[0])||!$.isObjectExpression(e.arguments[1])||e.arguments[1].properties.length!==1)return null;let[t]=e.arguments[1].properties;if(!$.isObjectMethod(t)||t.kind!=="method"||t.computed||t.async||t.generator||!$.isIdentifier(t.key,{name:"get"})||t.params.length!==3||!t.params.every($.isIdentifier)||t.body.body.length!==2)return null;let[n,r,o]=t.params,[i,s]=t.body.body;if($.isIfStatement(i)&&$.isBlockStatement(i.consequent)&&i.consequent.body.length!==1)return null;let a=$.isIfStatement(i)?i.test:null,c=a&&$.isLogicalExpression(a,{operator:"&&"})?a.right:null,l=$.isIfStatement(i)?$.isBlockStatement(i.consequent)?i.consequent.body[0]:i.consequent:null,d=$.isReturnStatement(s)?s.argument:null;return!a||!$.isLogicalExpression(a,{operator:"&&"})||!$.isBinaryExpression(a.left,{operator:"==="})||!$.isUnaryExpression(a.left.left,{operator:"typeof"})||!$.isIdentifier(a.left.left.argument,{name:r.name})||!$.isStringLiteral(a.left.right,{value:"string"})||!$.isUnaryExpression(c,{operator:"!"})||!$.isBinaryExpression(c.argument,{operator:"in"})||!$.isIdentifier(c.argument.left,{name:r.name})||!$.isIdentifier(c.argument.right,{name:n.name})||!$.isReturnStatement(l)||!$.isIfStatement(i)||i.alternate||!$.isCallExpression(d)||!$.isMemberExpression(d.callee)||!$.isIdentifier(d.callee.object,{name:"Reflect"})||!$.isIdentifier(d.callee.property,{name:"get"})||d.arguments.length!==3||!$.isIdentifier(d.arguments[0],{name:n.name})||!$.isIdentifier(d.arguments[1],{name:r.name})||!$.isIdentifier(d.arguments[2],{name:o.name})?null:e.arguments[0].name}function xR(e){let t=e.getFunctionParent();if(!t)return null;if(t.isFunctionDeclaration()){let s=t.node.id?.name;if(!s)return null;let a=t.parentPath?.isExportDefaultDeclaration()?"default":(t.parentPath?.isExportNamedDeclaration(),s);return{componentName:s,exportName:a}}if(!t.isArrowFunctionExpression()&&!t.isFunctionExpression())return null;let n=t.parentPath;if(!n?.isVariableDeclarator()||!$.isIdentifier(n.node.id))return null;let r=n.node.id.name,o=n.parentPath,i=o?.parentPath?.isExportDefaultDeclaration()?"default":(o?.parentPath?.isExportNamedDeclaration(),r);return{componentName:r,exportName:i}}function bR(e,t){let n=xR(e.path);if(!n)return null;let r=cr(e,t);return r?{...n,...r}:null}function SR(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}function yl(e,t){let n=[{kind:"component-prop",file:t.file,displayName:`${t.componentName}.${t.propName}`,canEditHere:!0}];return e.kind==="external"?{...e,chainPrefix:[...n,...e.chainPrefix??[]],editMode:e.editMode==="readonly"?"readonly":"upstream"}:{...e,chainPrefix:[...n,...e.chainPrefix??[]],editMode:"upstream"}}function xl(e,t){for(let n of e.program.body){if(t==="default"&&$.isExportDefaultDeclaration(n))return $.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:($.isFunctionDeclaration(n.declaration)||$.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if($.isExportNamedDeclaration(n)){if(n.declaration){if($.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if($.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if(($.isFunctionDeclaration(n.declaration)||$.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if(($.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&$.isExportSpecifier(r))return n.source?{kind:"re-export",name:r.local.name,source:n.source.value}:{kind:"local-binding",name:r.local.name}}}return null}function Sg(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:y,visited:k}=u,C=`${g}::${h.kind}::${h.identifier.name}`;if(k.has(C))return null;k.add(C);try{let N=await a({currentFile:g,binding:h,readFile:b,exists:E,fileCache:y,visited:k});if(N)return N;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:y,visited:k});if(h.kind==="param")return null;if(h.path.isVariableDeclarator()){let T=h.path.node.init;if(!T||!$.isExpression(T))return null;let R=yR(T);if(R&&!h.path.scope.getBinding("Proxy")&&!h.path.scope.getBinding("Reflect")){let D=h.path.scope.getBinding(R),L=D?await s({...u,binding:D}):null;if(L?.kind==="static"&&L.value!==null&&!Array.isArray(L.value)&&typeof L.value=="object")return L}let A=h.path.get("init");if(A&&!Array.isArray(A)&&A.isExpression()){let D=await t({currentFile:g,expressionPath:A,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:k});if(D)return D;if(A.isCallExpression()){let L=await n({currentFile:g,callPath:A,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:k});if(L)return L}}let M=await r(T,h.path.scope,g,b,E,y,k);return M===void 0?null:{kind:"static",file:g,root:{kind:"binding",name:h.identifier.name},value:M,sourceKind:"binding"}}if(h.path.isIdentifier()&&h.path.parentPath?.isExportDefaultDeclaration()){let T=h.path.parentPath.node.declaration;if(!$.isExpression(T))return null;let R=await r(T,h.path.scope,g,b,E,y,k);return R===void 0?null:{kind:"static",file:g,root:{kind:"binding",name:h.identifier.name},value:R,sourceKind:"binding"}}return null}finally{k.delete(C)}}async function a(u){let{currentFile:g,binding:h,readFile:b,exists:E,fileCache:y,visited:k}=u;if(!h.path.isVariableDeclarator()||!h.path.get("id").isArrayPattern())return null;let C=h.path,N=C.node.init;if(!N||!$.isCallExpression(N))return null;let T=hR(N);if(!T||!$.isArrayPattern(C.node.id)||C.node.id.elements.findIndex(L=>$.isIdentifier(L)&&L.name===h.identifier.name)!==0)return null;let A=T==="useReducer"?1:0,M=N.arguments[A];if(!M||!$.isExpression(M))return null;let D=await r(M,C.scope,g,b,E,y,k);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=bR(u.binding,u.sourceInfo);if(!g||!u.graph)return null;let h=[...u.graph.elements.values()].filter(T=>SR(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 yl(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 yl(T,{componentName:g.componentName,propName:g.propName,file:b.sourceFile});let R=bp(u.binding,g.componentName,g.propName);if(!R||R.propName!==g.propName)return null;let A=await r(R.expressionPath.node,R.expressionPath.scope,u.currentFile,u.readFile,u.exists,u.fileCache,u.visited);if(A===void 0)return null;let M=g.remainingPath;return M.length>0&&Qe(A,M)===void 0?null:{kind:"value",file:u.currentFile,root:{kind:"binding",name:g.propName},path:M,sourceKind:"binding",semanticKind:"component-prop",displayExpression:R.displayPath,chainPrefix:[{kind:"component-prop",file:u.currentFile,displayName:R.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let y=await Kt(b.sourceFile,u.readFile,u.fileCache);if(!y.ast)return null;let k=bg(y.ast,y.source,E.source.expression,E.sourceRange)??Co(y.ast,y.source,E.source.expression);if(!k)return null;let C={...E.source,expression:br(E.source.expression,g.remainingPath),path:[...E.source.path,...g.remainingPath]},N=await o({currentFile:b.sourceFile,expressionPath:k,sourceInfo:C,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});return N?yl(N.kind==="external"?N:{...N,displayExpression:C.expression},{componentName:g.componentName,propName:g.propName,file:b.sourceFile}):null}async function l(u){let g=await Kt(u.caller.sourceFile,u.readFile,u.fileCache);if(!g.ast)return null;let h=ml(g.ast,u.caller.sourceRange);if(!h)return null;let b=h.get("openingElement").get("attributes").find(C=>C.isJSXAttribute()&&C.node.name.type==="JSXIdentifier"&&C.node.name.name===u.propName);if(!b?.isJSXAttribute())return null;let E=b.get("value"),y=E.isStringLiteral()?E:E.isJSXExpressionContainer()?E.get("expression"):null;if(!y?.isExpression())return null;let k=Io(y.node);return k?{kind:"value",file:u.caller.sourceFile,root:{kind:"expression",sourceRange:k},path:u.remainingPath,sourceKind:"binding",semanticKind:"component-prop",displayExpression:u.propName,editMode:"upstream",diagnostics:[]}:null}async function d(u){let g=await Kt(u.caller.sourceFile,u.readFile,u.fileCache);if(!g.ast)return null;let h=ml(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 y=E.get("argument");if(!y.isExpression())continue;let k=await i({expression:y.node,scope:y.scope,source:g.source,currentFile:u.caller.sourceFile,readFile:u.readFile,exists:u.exists,fileCache:u.fileCache,visited:u.visited});if(!k)continue;let C=[{kind:"property",name:u.propName},...u.remainingPath],N={...k,expression:br(k.expression,C),path:[...k.path,...C]},T=await o({currentFile:u.caller.sourceFile,expressionPath:y,sourceInfo:N,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});if(T)return T.kind==="external"?T:{...T,displayExpression:N.expression}}return null}async function f(u){let{currentFile:g,binding:h,readFile:b,exists:E,fileCache:y,visited:k}=u,C=h.path.parentPath;if(!C||!C.isImportDeclaration())return null;let N=C.node.source.value;if(typeof N!="string")return null;let T=await Sn(g,N,E);if(!T)return null;if(h.path.isImportDefaultSpecifier()){let ee=await Kt(T,b,y),ge=ee.ast?xl(ee.ast,"default"):null,se=await m({file:T,exportName:"default",readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:k});return!se||se.kind!=="static"?null:{kind:"static",file:ge?.kind==="default-expression"?se.file:T,root:ge?.kind==="default-expression"?se.root:{kind:"default-export"},value:se.value,sourceKind:"imported-binding"}}if(!h.path.isImportSpecifier())return null;let R=h.path.node.imported,A=$.isIdentifier(R)?R.name:R.value,M=await Kt(T,b,y),D=M.ast?xl(M.ast,A):null,L=await m({file:T,exportName:A,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:k});return L?L.kind==="external"?L:{kind:"static",file:D?.kind==="re-export"?L.file:T,root:D?.kind==="re-export"||L.root.kind==="binding"&&L.root.name!==D?.name?L.root:{kind:"named-export",name:A},value:L.value,sourceKind:"imported-binding"}:null}async function m(u){let{file:g,exportName:h,readFile:b,exists:E,fileCache:y,visited:k}=u,C=`export::${g}::${h}`;if(!k.has(C)){k.add(C);try{let N=await Kt(g,b,y);if(!N.ast)return;let T=xl(N.ast,h);if(!T)return;if(T.kind==="default-expression"){let D=T.expression;if(!D||!$.isIdentifier(D))return;let L=Ro(N.ast).getBinding(D.name);return L?await s({currentFile:g,binding:L,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:k})??void 0:void 0}if(T.kind==="re-export"){if(!T.source||!T.name)return;let D=await Sn(g,T.source,E);return D?m({...u,file:D,exportName:T.name}):void 0}let R=T.name;if(!R)return;let A=Ro(N.ast).getBinding(R);return A?await s({currentFile:g,binding:A,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:k})??void 0:void 0}finally{k.delete(C)}}}return{resolveExportValue:m,resolveComponentPropBinding:c,resolveBindingTarget:s}}import*as H from"@babel/types";function Sl(e,t){let n=e.scope.getBinding(t);if(!n)return null;let r=n.path.getFunctionParent();if(!r||!r.isArrowFunctionExpression()&&!r.isFunctionExpression())return null;let o=r.node.params[0],i=It(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!ER(s,r)?null:{callPath:s,basePath:i}}function ER(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 kg(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:Wi(r,t)}function Eg(e,t){return e?H.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}function vg(e,t,n,r,o){let i=H.isExpression(e.body)?e.body:e.body.body.find(a=>H.isReturnStatement(a))?.argument;if(!i||!H.isExpression(i))return;let s=bl(i,t,n,r,o);return typeof s=="number"?s:void 0}function bl(e,t,n,r,o){if(H.isNumericLiteral(e)||H.isStringLiteral(e)||H.isBooleanLiteral(e))return e.value;if(H.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(H.isMemberExpression(e)){let i=gs(e,t);if(i)return Qe(r,i);let s=gs(e,n);return s?Qe(o,s):void 0}if(H.isBinaryExpression(e)&&e.operator==="-"){let i=H.isExpression(e.left)?bl(e.left,t,n,r,o):void 0,s=H.isExpression(e.right)?bl(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function vR(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 kR(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=gs(e,t);return r?Qe(n,r):void 0}if(H.isUnaryExpression(e)&&e.operator==="!"){let r=jn(e.argument,t,n);return r===void 0?void 0:!r}if(H.isLogicalExpression(e)){let r=jn(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&jn(e.right,t,n);if(e.operator==="||")return r||jn(e.right,t,n)}if(H.isBinaryExpression(e)){let r=H.isExpression(e.left)?jn(e.left,t,n):void 0,o=H.isExpression(e.right)?jn(e.right,t,n):void 0;if(r===void 0||o===void 0)return;switch(e.operator){case"===":return r===o;case"!==":return r!==o;case"==":return r==o;case"!=":return r!=o;default:return}}}function Ig(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 Cg(e){return e.some(t=>t.kind==="dynamic")}function IR(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}function Rg(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 CR(e,t){let n=[],r=[];for(let o of t){let i=Qe(e,o);if(!Array.isArray(i))return null;for(let[s,a]of i.entries())n.push(a),r.push([...o,{kind:"index",index:s}])}return{value:n,collectionPathMap:r}}function wg(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:y,visited:k}=u,C=h.node.callee;if(!H.isMemberExpression(C)||!H.isIdentifier(C.property)||C.property.name!=="map")return null;let N=h.get("callee");if(!N.isMemberExpression())return null;let T=N.get("object");if(Array.isArray(T)||!T.isExpression())return null;let R=await s({currentFile:g,expressionPath:T,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:k});return!R||!Array.isArray(R.value)||R.value.length===0?null:R}async function s(u){let{currentFile:g,expressionPath:h,readFile:b,exists:E,fileCache:y,visited:k}=u;if(h.isIdentifier()){let C=h.scope.getBinding(h.node.name);if(!C)return null;let N=await t({currentFile:g,binding:C,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:k});return N?.kind==="static"?N: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:y,visited:k});if(h.isTSAsExpression()||h.isTSSatisfiesExpression()||h.isTSNonNullExpression()){let C=h.get("expression");if(!Array.isArray(C)&&C.isExpression())return s({...u,expressionPath:C})}if(h.isArrayExpression()){let C=Io(h.node);if(!C)return null;let N=await n(h.node,h.scope,g,b,E,y,k);return Array.isArray(N)?{kind:"static",file:g,root:{kind:"expression",sourceRange:C},value:N,sourceKind:"binding"}:null}if(h.isMemberExpression()){let C=await r({expression:h.node,scope:h.scope,currentFile:g,readFile:b,exists:E,fileCache:y,visited:k});if(!C)return null;let N=await o({currentFile:g,expressionPath:h,sourceInfo:C,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:k});if(!N||N.kind==="external")return null;let T=await a({currentFile:g,expressionPath:h,provenance:N,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:k});if(!T||T.kind!=="static")return null;if(N.collectionPathMap?.length){let A=CR(T.value,N.collectionPathMap);if(A)return{kind:"static",file:N.file,root:N.root,value:A.value,sourceKind:N.sourceKind,collectionPathMap:A.collectionPathMap}}let R=Qe(T.value,N.path);return Array.isArray(R)?{kind:"static",file:N.file,root:N.root,value:R,sourceKind:N.sourceKind,pathPrefix:N.path,collectionIndexMap:N.collectionIndexMap,collectionPathMap:N.collectionPathMap}:null}return null}async function a(u){let{provenance:g}=u;if(g.root.kind==="binding"){let y=u.expressionPath.scope.getBinding(g.root.name);if(!y&&g.file!==u.currentFile){let k=await Kt(g.file,u.readFile,u.fileCache);y=k.ast?Ro(k.ast).getBinding(g.root.name):void 0}return y?await t({currentFile:g.file,binding:y,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited}):null}if(g.root.kind!=="expression")return null;let h=await Kt(g.file,u.readFile,u.fileCache);if(!h.ast)return null;let b=yg(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 y=await s({currentFile:u.currentFile,expressionPath:E,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});if(!y||!Array.isArray(y.value))return null;let[k]=g.node.arguments;if(!H.isArrowFunctionExpression(k)&&!H.isFunctionExpression(k))return null;let C=k.params[0];if(!H.isIdentifier(C))return null;let N=vR(k);if(!N)return null;let T=[],R=[],A=[];for(let[M,D]of y.value.entries()){let L=kR(N,C.name,D);if(typeof L!="boolean")return null;if(L){T.push(D),R.push(y.collectionIndexMap?.[M]??M);let ee=y.collectionPathMap?.[M];ee&&A.push(ee)}}return{...y,value:T,pathPrefix:y.pathPrefix,collectionIndexMap:R,...A.length>0?{collectionPathMap:A}:{}}}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 y=await s({currentFile:u.currentFile,expressionPath:E,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});if(!y||!Array.isArray(y.value))return null;let[k,C]=g.node.arguments,N=Eg(k,0),T=Eg(C,y.value.length);if(N===null||T===null)return null;let R=Math.max(0,N<0?y.value.length+N:N),A=Math.max(0,T<0?y.value.length+T:T),M=y.value.map((L,ee)=>y.collectionIndexMap?.[ee]??ee).slice(R,A),D=y.collectionPathMap?.slice(R,A);return{...y,value:y.value.slice(R,A),pathPrefix:y.pathPrefix,collectionIndexMap:M,...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 y=await s({currentFile:u.currentFile,expressionPath:E,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});if(!y||!Array.isArray(y.value))return null;let[k]=g.node.arguments;if(!H.isArrowFunctionExpression(k)&&!H.isFunctionExpression(k))return null;let[C,N]=k.params;if(!H.isIdentifier(C)||!H.isIdentifier(N))return null;let T=y.value.map((A,M)=>({value:A,sourceIndex:y.collectionIndexMap?.[M]??M,originalIndex:M})),R=[...T];for(let A of T)for(let M of T)if(vg(k,C.name,N.name,A.value,M.value)===void 0)return null;return R.sort((A,M)=>{let D=vg(k,C.name,N.name,A.value,M.value)??0;return D===0?A.originalIndex-M.originalIndex:D}),{...y,value:R.map(A=>A.value),pathPrefix:y.pathPrefix,collectionIndexMap:R.map(A=>A.sourceIndex),...y.collectionPathMap?{collectionPathMap:R.map(A=>y.collectionPathMap?.[A.originalIndex]).filter(A=>!!A)}:{}}}async function m(u){let g=null,h,b=[];for(let y of u.segments){if(y.kind!=="dynamic")continue;let k=await r({expression:y.expression,scope:u.expressionPath.scope,source:u.fileCache.get(u.currentFile)?.source,currentFile:u.currentFile,readFile:u.readFile,exists:u.exists,fileCache:u.fileCache,visited:u.visited});if(!k)return null;let C=Sl(u.expressionPath,k.base);if(!C)return null;let N=await i({currentFile:u.currentFile,callPath:C.callPath,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});if(!N||!Array.isArray(N.value))return null;let T=N.value.map((R,A)=>{let M=Qe(N.value,[{kind:"index",index:A},...C.basePath,...k.path]);return IR(M)});if(T.some(R=>R===null)||g!==null&&g!==T.length)return null;g=T.length,h??=N.collectionIndexMap,b.push(T)}if(g===null||g===0)return null;let E=[];for(let y=0;y<g;y+=1){let k=[...u.rootPath],C=0;for(let N of u.segments){if(N.kind==="dynamic"){let T=b[C]?.[y];if(!T)return null;k.push(T),C+=1;continue}k.push({...N})}E.push(k)}return{...h?{collectionIndexMap:h}:{},collectionPathMap:E}}return{resolveRepeatCollectionTarget:i,resolveCollectionCallTarget:c,resolveDynamicMemberPathMap:m}}var{normalizeExpressionWithScope:RR,evaluateStaticExpression:xs}=ug({resolveBindingTarget:e=>bs(e)}),{resolveRepeatCollectionTarget:wR,resolveCollectionCallTarget:NR,resolveDynamicMemberPathMap:PR}=wg({resolveBindingTarget:e=>bs(e),evaluateStaticExpression:xs,buildExpressionSourceInfo:Ut,resolveSourceInfoProvenance:St}),{resolveExportValue:AR,resolveComponentPropBinding:TR,resolveBindingTarget:bs}=Sg({resolveExternalExpression:wl,resolveCollectionCallTarget:NR,evaluateStaticExpression:xs,resolveSourceInfoProvenance:St,buildExpressionSourceInfo:Ut});function Lg(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}var Ng=new WeakMap;function FR(e){let t=Ng.get(e);return t||(t=new WeakMap,Ng.set(e,t)),t}function Pg(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 Dg(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=hs(s,t,n);if(!a)return null;let c=ys(a,r.sourceRange);if(!c)return null;let l=await Ut({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!l){let m=await Tl({currentFile:t,expressionPath:c,readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:new Set});return m?kl(m,xr(c.node,n)):null}let d=new Set,f=await ew({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?kl(f,l.expression):null}async function Sr(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=hs(i,t,n);if(!s)return null;let a=e.sourceRange?ys(s,e.sourceRange):e.expression!==void 0?Co(s,n,e.expression):null;if(!a)return null;let c=Ss(a);if(!c.isIdentifier()&&!c.isMemberExpression())return null;let l=new Set,d=await Ut({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 Xg({currentFile:t,expressionPath:c,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:l});return kl(f,e.expression??xr(c.node,n))}async function Rl(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=hs(i,t,n);if(!s)return dt("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?_R({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}):MR({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}async function Ut(e){if(Q.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!Q.isMemberExpression(e.expression))return null;let t=await RR(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:xr(e.expression,e.source),base:t.base,path:t.path}:null}function kl(e,t){if(!e||e.kind==="value"&&e.editMode==="readonly")return null;if(e.kind==="external")return{kind:"external-entry",file:e.file,sourceType:e.sourceType,sourceId:e.sourceId,adapterId:e.adapterId,displayExpression:e.displayPath};let n={kind:"value",root:e.root,path:e.path.length>0?e.path:[]};return{kind:"value-binding",file:e.file,locator:n,root:e.root,path:e.path,displayExpression:e.displayExpression??t,sourceKind:e.sourceKind,...e.collectionIndexMap?{collectionIndexMap:e.collectionIndexMap}:{},...e.collectionPathMap?{collectionPathMap:e.collectionPathMap}:{}}}async function _R(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=ys(r,o.sourceRange),d=l?await Ut({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 Ag(t,o.value);let m=await Tl({currentFile:t,expressionPath:l,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});return m?m.kind==="external"?Og(t,m):Cl(t,xr(l.node,n),m):OR({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return dt("unsupported-expression","Unable to locate text expression for provenance resolution");let f=await St({currentFile:t,expressionPath:l,sourceInfo:d,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});if(!f){let m=Il(l.node);if(m)return dt(m.code,m.message);let u=l.scope.getBinding(d.base);if(u?.path.isVariableDeclarator()){let g=Il(u.path.node.init);if(g)return dt(g.code,g.message)}return u?.path.isVariableDeclarator()&&Q.isCallExpression(u.path.node.init)?LR("unsupported-expression",Kg(u.path.node.init,e.functionCallContracts)):dt("unsupported-expression",`Unable to resolve provenance for expression "${d.expression}"`)}return f.kind==="external"?Og(t,f):Cl(t,d.expression,f)}async function MR(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return dt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=Co(r,n,o.conditionExpression);if(!l)return dt("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let d=await St({currentFile:t,expressionPath:l,sourceInfo:o.conditionSource,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});if(!d)return dt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(d.kind==="external")return dt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let f=Cl(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 Ag(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 OR(e){let t=await jg(e);if(t.length===0)return dt("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(DR(e.expression))return Bg(t);if(Vg(e.expression))return dt("unsupported-expression","i18n helpers require a static message id string");if(Q.isMemberExpression(e.expression)&&e.expression.computed&&!Q.isNumericLiteral(e.expression.property)&&!Q.isStringLiteral(e.expression.property))return dt("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return dt(n.code,n.message)}function dt(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function LR(e,t){return Bg([{code:e,message:t}])}function Bg(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function DR(e){return Q.isCallExpression(e)||Q.isConditionalExpression(e)||Q.isLogicalExpression(e)||Q.isBinaryExpression(e)}function No(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 jg(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=Il(t);if(l)return[l];if(Q.isCallExpression(t))return[{code:"unsupported-expression",message:Kg(t,c)}];if(Q.isMemberExpression(t)&&t.computed){let d=t.property;if(!Q.isNumericLiteral(d)&&!Q.isStringLiteral(d)){if(!Q.isExpression(d))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let m=await xs(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 Q.isBinaryExpression(t)?No([...await El(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):Q.isLogicalExpression(t)?No([...await El(t.left,t.right,e),{code:"unsupported-expression",message:t.operator==="??"||t.operator==="||"?"Fallback expressions are recognized but remain readonly until a safer composition editing strategy is available":"Complex conditional expressions are recognized but remain readonly until a safer editing strategy is available"}]):Q.isConditionalExpression(t)?No([...await El(t.test,t.consequent,t.alternate,e),{code:"unsupported-expression",message:"Complex conditional expressions are recognized but remain readonly until a safer editing strategy is available"}]):[]}function Il(e){return Vg(e)?Tg("i18n helpers require a static message id string"):KR(e)?Tg("CMS helpers require static entry id and field path string arguments"):null}async function El(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await jg({...t,expression:o}));return r}function BR(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:[jR(e.sourceType)]}}async function wl(e){for(let n of zR){if(!Fg(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return Mg(_g(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(!Fg(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return Mg(_g(r),e.externalAdapters)}return null}function jR(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function $R(e){return{code:"external-source-readonly",message:e}}function Tg(e){return{code:"unsupported-expression",message:e}}function Nl(e){return!e||!Q.isCallExpression(e)?null:Q.isIdentifier(e.callee)?e.callee.name:Q.isMemberExpression(e.callee)&&!e.callee.computed&&Q.isIdentifier(e.callee.object)&&Q.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function Fg(e,t){if(!t||t.length===0)return!0;let n=Nl(e.node);return n?t.includes(n):!1}function _g(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:No(e.diagnostics??[])}:{match:e,diagnostics:[]}}function Mg(e,t){let n=BR(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:No([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function VR(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!Q.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!Q.isStringLiteral(n)||!Q.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 KR(e){return!!e&&Q.isCallExpression(e)&&Q.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!Q.isStringLiteral(e.arguments[0])||!Q.isStringLiteral(e.arguments[1]))}function $g(e){if(!(!e||!Q.isCallExpression(e))){if(Q.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&Q.isStringLiteral(t)?t.value:null}if(Q.isMemberExpression(e.callee)&&!e.callee.computed&&Q.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&Q.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!Q.isObjectExpression(t))return null;for(let n of t.properties)if(Q.isObjectProperty(n)&&!n.computed&&(Q.isIdentifier(n.key)&&n.key.name==="id"||Q.isStringLiteral(n.key)&&n.key.value==="id")&&Q.isStringLiteral(n.value))return n.value.value;return null}}}function Vg(e){return $g(e)===null}async function UR(e,t,n){let r=new Set,o=wo.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=wo.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"]:[wo.posix.join(i,"locales"),wo.posix.join(i,"messages")];for(let a of s){let c=wo.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function JR(e){let t=$g(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await UR(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function XR(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!Q.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!Q.isExpression(n))return null;let o=await xs(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:[$R("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var zR=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>VR(e)},{helperNames:["apiField"],resolve:e=>XR(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>JR({currentFile:e,expressionPath:t,exists:n})}];function Pl(e){return{...e,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Derived display values are readonly because no identity-preserving write target exists"}]}}function Og(e,t){return{finalSource:{kind:t.sourceType,file:t.file,locator:null,displayPath:t.displayPath,externalSource:{sourceType:t.sourceType,sourceId:t.sourceId,adapterId:t.adapterId}},chain:[...t.chainPrefix??[],{kind:t.sourceType,file:t.file,displayName:t.displayPath,canEditHere:t.editMode!=="readonly"}],confidence:"exact",editMode:t.editMode==="direct"?t.file===e?"direct":"proxy":t.editMode,diagnostics:t.diagnostics}}function Cl(e,t,n){let r={kind:"value",root:n.root,path:n.path.length>0?n.path:[]},o=n.path.some(l=>l.kind==="index"),i=qR(n),s;n.semanticKind?s=n.semanticKind:i?s="config-entry":n.sourceKind==="repeat-template"?s="repeat-template":n.path.length===0?s=n.sourceKind==="imported-binding"?"imported-binding":"binding":s=o?"array-item":"object-field";let a=n.displayExpression??t,c=[...n.chainPrefix??[]];return n.sourceKind==="binding"?c.push({kind:"binding",file:n.file,displayName:n.root.kind==="binding"?n.root.name:a,canEditHere:n.editMode!=="readonly"}):n.sourceKind==="imported-binding"?c.push({kind:"imported-binding",file:n.file,displayName:n.root.kind==="named-export"?n.root.name:"default",canEditHere:n.editMode!=="readonly"}):n.sourceKind==="repeat-template"&&c.push({kind:"repeat-template",file:n.file,displayName:t,canEditHere:n.editMode!=="readonly"}),n.path.length>0&&n.sourceKind!=="repeat-template"&&c.push({kind:o?"array-item":"object-field",file:n.file,displayName:a,canEditHere:n.editMode!=="readonly"}),i&&c.push({kind:"config-entry",file:n.file,displayName:i.displayPath,canEditHere:n.editMode!=="readonly"}),{finalSource:{kind:s,file:n.file,locator:r,root:n.root,path:n.path,displayPath:a,externalSource:i?{sourceType:"config-entry",sourceId:i.sourceId}:void 0},chain:n.editMode==="readonly"?c.map(l=>({...l,canEditHere:!1})):c,confidence:n.sourceKind==="repeat-template"?"safe-derived":"exact",editMode:n.editMode??(n.file===e?"direct":"proxy"),diagnostics:n.diagnostics??[]}}var WR=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function Al(e,t){let n=[...WR,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function Kg(e,t){let n=e.callee;return Q.isIdentifier(n)&&Al(n.name,t)?.purity==="side-effect"?`Helper "${n.name}" is registered as side-effectful and remains readonly`:"Function calls remain readonly because purity does not establish an identity-preserving write target"}async function Tl(e){let t=await wl(e);if(t)return t;let n=await Ug({...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 Ut({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 ZR(e)}async function Ug(e){let t=await Rt({...e,allowComposed:!1});if(t?.kind!=="source")return null;let n=Ss(e.expressionPath);return n.isIdentifier()||n.isMemberExpression()?t.provenance:Pl(t.provenance)}async function Rt(e){let t=Ss(e.expressionPath),n=YR(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 Ut({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 Ut({expression:t.node,scope:t.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(!r)return null;let o=await St({currentFile:e.currentFile,expressionPath:t,sourceInfo:r,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return!o||o.kind==="external"?null:{kind:"source",provenance:o}}if(t.isConditionalExpression()){let r=t.get("test"),o=t.get("consequent"),i=t.get("alternate");if(Array.isArray(r)||Array.isArray(o)||Array.isArray(i)||!r.isExpression()||!o.isExpression()||!i.isExpression())return null;let s=await Rt({...e,expressionPath:r,allowComposed:!0}),a=await Rt({...e,expressionPath:o,allowComposed:!1}),c=await Rt({...e,expressionPath:i,allowComposed:!1});return vl(s,a,c)}if(t.isCallExpression())return HR({...e,expressionPath:t});if(!e.allowComposed)return null;if(t.isBinaryExpression()){let r=t.get("left"),o=t.get("right");if(Array.isArray(r)||Array.isArray(o)||!r.isExpression()||!o.isExpression())return null;let i=await Rt({...e,expressionPath:r,allowComposed:!0}),s=await Rt({...e,expressionPath:o,allowComposed:!0});return vl(i,s)}if(t.isLogicalExpression()){let r=t.get("left"),o=t.get("right");if(Array.isArray(r)||Array.isArray(o)||!r.isExpression()||!o.isExpression())return null;let i=await Rt({...e,expressionPath:r,allowComposed:!0}),s=await Rt({...e,expressionPath:o,allowComposed:!0});return vl(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:Rt({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function Ss(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 HR(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(Q.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:Rt({...e,expressionPath:o,allowComposed:!1})}}return null}function vl(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!GR(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function GR(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 YR(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function ZR(e){if(!e.expressionPath.isCallExpression())return null;let t=Nl(e.expressionPath.node);if(!t)return null;let n=Al(t,e.functionCallContracts);if(!n||n.purity!=="pure")return null;let r=n.sourceArgIndex??0,o=e.expressionPath.get(`arguments.${r}`);if(!o||Array.isArray(o)||!o.isExpression())return null;let i=await Jg({currentFile:e.currentFile,argumentPath:o,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return i?Pl(i):null}async function Jg(e){let t=await wl({currentFile:e.currentFile,expressionPath:e.argumentPath,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(t)return t;let n=await Ut({expression:e.argumentPath.node,scope:e.argumentPath.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(n){let r=await St({currentFile:e.currentFile,expressionPath:e.argumentPath,sourceInfo:n,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return!r||r.kind==="external"?r:{...r,displayExpression:n.expression}}return await Tl({currentFile:e.currentFile,expressionPath:e.argumentPath,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited})}async function QR(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!Q.isCallExpression(t))return null;let n=t.callee;if(!Q.isIdentifier(n))return null;let r=Al(n.name,e.functionCallContracts);if(!r||r.purity!=="pure")return null;let o=r.sourceArgIndex??0,i=e.binding.path.get("init");if(!i||Array.isArray(i)||!i.isCallExpression())return null;let s=i.get(`arguments.${o}`);if(!s||Array.isArray(s)||!s.isExpression())return null;let a=await Jg({currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited,argumentPath:s});return a?Pl(a):null}function qR(e){if(e.sourceKind!=="imported-binding")return null;let t=e.root.kind==="binding"||e.root.kind==="named-export"?e.root.name:e.root.kind==="default-export"?"default":null;if(!t)return null;let n=/(^|[\/.-])(config|settings)([\/.-]|$)/i.test(e.file),r=/config|settings/i.test(t);if(!n&&!r)return null;let o=br(t,e.path);return{sourceId:o,displayPath:o}}async function ew(e){let t=e.segment.source;return t?St({currentFile:e.currentFile,expressionPath:e.expressionPath,sourceInfo:t,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited}):null}async function St(e){let t=e.sourceInfo,n=Sl(e.expressionPath,t.base);if(n){let l=await wR({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=kg(n.callPath,[...n.basePath,...t.path]);return ao(h)?Pg(e.currentFile,h.sourceId,h.displayPath):null}let d=Rg(l,[...n.basePath,...t.path]),f=l.collectionIndexMap?.[0]??0,m=[...l.pathPrefix??[],{kind:"index",index:f},...n.basePath,...t.path],u=[{kind:"index",index:0},...n.basePath,...t.path];return Qe(l.value,u)===void 0?null:{kind:"value",file:l.file,root:l.root,path:d?.[0]??m,sourceKind:"repeat-template",collectionIndexMap:l.collectionIndexMap,...d?{collectionPathMap:d}:{}}}let r=e.expressionPath.scope.getBinding(t.base);if(!r)return null;if(r.path.isImportNamespaceSpecifier()){let l=t.path[0],d=r.path.parentPath;if(!l||l.kind!=="property"||!d?.isImportDeclaration())return null;let f=await Sn(e.currentFile,d.node.source.value,e.exists);if(!f)return null;let m=await AR({file:f,exportName:l.name,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(!m||m.kind==="external")return null;let u=t.path.slice(1);return Qe(m.value,u)===void 0?null:{kind:"value",file:m.file,root:m.root,path:u,sourceKind:"imported-binding",collectionIndexMap:m.collectionIndexMap}}let o=yp(r);if(o){let l=o.expressionPath,d=await Ut({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:br(d.expression,t.path),path:[...d.path,...t.path]}});if(f)return f}else if(r.constant){let f=`dynamic-alias:${e.currentFile}:${l.node.start}`;if(e.visited.has(f))return null;e.visited.add(f);try{let m=await Xg({...e,expressionPath:Ss(l),memberSuffix:t.path});if(m?.kind==="value")return m}finally{e.visited.delete(f)}}if(t.path.length===0){let f=await Ug({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 TR({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 QR({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=Xi(r,t.path,FR(e.fileCache));if(ao(s))return Pg(e.currentFile,s.sourceId,s.displayPath);let a=await bs({currentFile:e.currentFile,binding:r,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return a?a.kind==="external"?t.path.length===0?a:null:Qe(a.value,t.path)===void 0?null:{kind:"value",file:a.file,root:a.root,path:t.path,sourceKind:a.sourceKind,collectionIndexMap:a.collectionIndexMap}:null}async function Xg(e){let t=Ig(e.expressionPath.node);if(!t||!Cg(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 PR({...e,rootPath:n.path,segments:t.segments});if(!r)return null;let o=r.collectionPathMap.map(i=>[...i,...e.memberSuffix??[]]);if(e.memberSuffix){let i=e.expressionPath.scope.getBinding(t.base),s=i?await bs({...e,binding:i}):null;if(s?.kind!=="static"||o.some(a=>Qe(s.value,a.slice(n.path.length))===void 0))return null}return{...n,path:o[0]??n.path,sourceKind:"repeat-template",displayExpression:xr(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:o}}async function zg(e){let t=tw(e.propertyName);if(t.owner==="blocked")return yn(t.owner,t.diagnostic);if(t.owner==="class-name-source"||t.owner==="style")return yn(t.owner,{code:"owner-delegated",message:`Property '${e.propertyName}' is owned by ${t.owner}`});let n=e.element.attributes?.filter(l=>l.name===e.propertyName)??[];if(n.length>1)return yn("generic",{code:"duplicate-property-source",message:`Property '${e.propertyName}' has multiple explicit sources`});let r=n[0],o=[];r&&o.push({kind:"attribute",order:r.order??e.element.attributes.indexOf(r),attribute:r});let i=e.element.attributeSpreads??[];for(let l of i)o.push({kind:"spread",order:l.order,spread:l,target:await rw(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 yn("generic",{code:"ambiguous-property-source",message:`A spread may provide or override property '${e.propertyName}'`});if(s.kind==="spread")return s.target?{status:"binding",owner:"generic",target:s.target}:yn("generic",{code:"ambiguous-property-source",message:`The final spread source for '${e.propertyName}' is not provably writable`});let c=o.filter(l=>l.kind==="spread"&&l.order<s.order);return e.operation==="remove"&&c.length>0?yn("generic",{code:"remove-exposes-spread",message:`Removing '${e.propertyName}' would expose an earlier spread source`}):nw(e,s.attribute)}async function nw(e,t){if(t.resolution&&t.resolution.status!=="resolved"&&!t.source){let r=await Sr({file:e.file,source:e.source,sourceRange:t.sourceRange,expression:t.value,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache});return r&&r.kind!=="external-entry"?{status:"binding",owner:"generic",attribute:t,target:{kind:"value-binding",target:r}}:yn("generic",{code:"unsupported-property-source",message:`Property '${e.propertyName}' has an unresolved value source`})}if(!t.source?.expression)return{status:"direct",owner:"generic",attribute:t,target:{kind:"jsx-attribute",file:e.file,sourceRange:t.sourceRange}};let n=await Sr({file:e.file,source:e.source,sourceRange:t.sourceRange,expression:t.source.expression,sourceInfo:t.source,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache});return!n||n.kind==="external-entry"?yn("generic",{code:"unsupported-property-source",message:`Property '${e.propertyName}' does not have a local writable source`}):{status:"binding",owner:"generic",attribute:t,target:{kind:"value-binding",target:n}}}async function rw(e,t){let n=t.source?.expression;if(!n)return;let r=await Sr({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:ow(r,e.propertyName)}}function ow(e,t){let n=[...e.path??[],{kind:"property",name:t}];return{...e,path:n,locator:e.locator?{...e.locator,path:n}:{kind:"value",root:e.root??{kind:"binding",name:t},path:n}}}function yn(e,t){return{status:"blocked",owner:e,...t?{diagnostic:t}:{}}}function Wg(e){let t=new Map;for(let r of e.elements.values()){if(r.importedFrom===void 0)continue;let o=t.get(r.importedFrom);o||(o={candidates:[],keys:new Map},t.set(r.importedFrom,o)),o.candidates.push(r)}let n=r=>{if($n(r.tag))return r.identity.key;let o=t.get(r.sourceFile);if(!o)return null;if(o.keys.has(r.componentName))return o.keys.get(r.componentName);let i=o.candidates.filter(a=>cw(a,r.componentName)),s=i.length===1?i[0].identity.key:null;return o.keys.set(r.componentName,s),s};return r=>iw({...r,graph:e},n)}function iw(e,t){let{key:n,element:r,graph:o,provenances:i}=e,s=aw(n,r,o,t),a=s?.tag??($n(r.tag)?r.tag:r.componentName),c=s?.identity.key??t(r,o)??n,l=uw(s),d=dw(n,r,o,i,s),f=sw(n,r,o,i,c);return{componentName:a,instanceKey:c,templateOwner:lw(s??r,a),...l.length>0?{variantKeys:l}:{},...d.length>0?{slotKeys:d}:{},editableStrategy:f,impactScope:fw(f),alternativeStrategies:pw(f)}}function sw(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return Fl(e,n)?"instance":!$n(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function aw(e,t,n,r){if($n(t.tag))return t;let o=Fl(e,n);if(o)return o;let i=r(t,n);return i?n.elements.get(i)??null:null}function cw(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function lw(e,t){return $n(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function uw(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 dw(e,t,n,r,o){let i=new Set,s=Fl(e,n);s&&o?.identity.key===s.identity.key&&i.add("children");for(let a of r.values()){let c=a?.chain.find(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 Fl(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if($n(r.tag))return r;n=r.parentKey}return null}function $n(e){return/^[A-Z]/.test(e)}function fw(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function pw(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}function Yg(e){let t=e.isRepeat??(e.graph?vw(e.element,e.graph):!1),n=e.propertyProvenance??new Map,r=e.repeatTargets??new Map,o=Ew(e.element.attributes??[]),i=[...r.values()].some(d=>d.ok),s=o.map(d=>mw({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:kw(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 mw(e){let{attribute:t,provenance:n,repeatTarget:r}=e,o=e.selectionRef?.instanceIndex!==void 0&&r?.ok===!0?r:null,i=gw(t,n,e.isRepeat),s=["selection","template"].map(b=>({scope:b,result:es({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=hw(t,n,l,e.isRepeat),f=c?bw(c,e.element,t.name):void 0,m=s.filter(({result:b})=>b.ok).map(({scope:b})=>b),u=m.length>0?xw(n,o,e.element):"unsupported",g=o?"repeat-item":e.isRepeat?"repeat-template":"node",h=Sw(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 gw(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 hw(e,t,n,r){return n?Hg(n.selectedResolution):t?.status==="blocked"?{status:"unresolved"}:r&&t?.status==="binding"?{status:"unresolved"}:Hg(yw(e))}function yw(e){return e.resolution?e.resolution:e.syntaxKind==="boolean-shorthand"?{status:"resolved",value:!0}:e.resolvedValue!==void 0?{status:"resolved",value:e.resolvedValue}:e.source?{status:"unresolved"}:{status:"resolved",value:e.value}}function Hg(e){return!e||e.status==="unresolved"?{status:"unresolved"}:e.status==="undefined"?{status:"undefined"}:{status:"resolved",value:e.value}}function xw(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 bw(e,t,n){return e.kind==="repeat-property"?{kind:"value-path",file:e.target.sourceFile,isProxy:e.target.sourceFile!==t.sourceFile,displayPath:Gg({...e.target.selectedParentObjectLocator,path:[...e.target.selectedParentObjectLocator.path??[],{kind:"property",name:n}]})}:e.kind==="value-binding"?{kind:"value-path",file:e.file,isProxy:e.file!==t.sourceFile,displayPath:Gg(e.locator)}:{kind:"jsx-node",file:t.sourceFile,isProxy:!1,displayPath:t.componentName+" > "+n}}function Sw(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 Ew(e){let t=new Set;return e.filter(n=>t.has(n.name)?!1:(t.add(n.name),!0))}function vw(e,t){let n=t.regions.filter(r=>r.kind==="repeat-region");for(let r of n){let o=e;for(;o;){if(r.childKeys.includes(o.identity.key))return!0;o=o.parentKey?t.elements.get(o.parentKey):void 0}}return!1}function Gg(e){return`${e.root.kind==="binding"?e.root.name:e.root.kind==="expression"?e.root.sourceRange?"expression":"value":e.root.kind}${(e.path??[]).map(n=>n.kind==="index"?`[${n.index}]`:`.${n.name}`).join("")}`}function kw(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 Iw(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var Cw=160;function Zg(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 Qg(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=rh(m.textSegments,s),b=oh(e,t,m,g,h),E=h?Pw(h):void 0,y=Aw(i,h),k=m.textSegments.map(R=>({index:R.index,value:R.value,editable:ih(R,g,s?.get(R.index)??null),source:o.get(R.index)??null})),C=th(m,t),N=m.childKeys.map(R=>{let A=t.elements.get(R);return A?{key:R,tag:A.tag,label:A.tag}:null}).filter(R=>R!==null),T=[];if(m.parentKey){let R=t.elements.get(m.parentKey);if(R)for(let A of R.childKeys){if(A===e)continue;let M=t.elements.get(A);M&&T.push({key:A,tag:M.tag,label:M.tag})}}return{composition:f,key:e,tag:m.tag,componentName:m.componentName,sourceFile:m.sourceFile,sourceLocator:eh(m),label:m.tag,capabilities:b,writeTarget:i,effectiveWriteTarget:y,provenanceChain:E,componentSemantic:c,styleSource:l,conditional:a,...d?{dynamicData:d}:{},textSegments:k,boundaryKind:m.boundaryKind,isOpaque:m.isOpaque,ancestors:C,children:N,siblings:T}}function qg(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=rh(l.textSegments,i),u=Rw(l);return{composition:c,key:e,tag:l.tag,...u?{linkSourceKind:u}:{},componentName:l.componentName,sourceFile:l.sourceFile,sourceLocator:eh(l),label:l.tag,capabilities:oh(e,t,l,f,m),provenanceChain:m?{editMode:m.editMode,diagnostics:m.diagnostics.map(g=>({code:g.code,message:g.message}))}:void 0,...s?{dynamicData:s}:{},...a?{properties:a}:{},textSegments:l.textSegments.map(g=>{let h=o.get(g.index);return{index:g.index,editable:ih(g,f,i?.get(g.index)??null),source:h?{kind:h.kind}:null}}),boundaryKind:l.boundaryKind,isOpaque:l.isOpaque,ancestors:th(l,t)}}function Rw(e){if(e.tag==="a")return"native-anchor";if(e.importedFrom==="next/link"&&e.exportName==="default")return"next-link";if(e.tag==="Link")return"unsupported"}function eh(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:ww(e.sourceRange),structuralPath:e.identity.structuralPath,...Nw(e.textSegments)}}function th(e,t){let n=[],r=e.parentKey;for(;r;){let o=t.elements.get(r);if(!o)break;n.push({key:r,tag:o.tag,label:o.tag}),r=o.parentKey}return n.reverse(),n}function ww(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function Nw(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,Cw)}:{}}function nh(e,t){let n=t.find(r=>r.editable&&r.source&&r.source.kind!=="literal");return n?.source?{kind:"value-binding",file:n.source.file,componentName:e.componentName,isProxy:n.source.file!==e.file}:{kind:"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function rh(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function oh(e,t,n,r,o){let i=n.identity.structuralPath.includes("#repeat:"),s=t.regions.some(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&&sh(c.mode);return{...r,canUpdateText:l,editModes:{updateText:c,insertChild:r.canInsertChild?{mode:"direct",reasonCode:i||s?"repeat-template":void 0}:{mode:"unsupported",reasonCode:"capability-denied"},move:r.canMove?{mode:s?"proxy":"direct",reasonCode:s?"repeat-collection":void 0}:{mode:"unsupported",reasonCode:"capability-denied"},remove:r.canRemove?{mode:s?"proxy":"direct",reasonCode:s?"repeat-collection":void 0}:{mode:"unsupported",reasonCode:"capability-denied"}}}}function ih(e,t,n){return!e.editable||!t.canUpdateText?!1:n?sh(n.editMode):!0}function sh(e){return e==="direct"||e==="proxy"||e==="upstream"}function Pw(e){return{finalSource:e.finalSource?{kind:e.finalSource.kind,file:e.finalSource.file,displayPath:e.finalSource.displayPath,externalSource:e.finalSource.externalSource}:null,chain:e.chain.map(t=>({kind:t.kind,file:t.file,displayName:t.displayName,canEditHere:t.canEditHere})),confidence:e.confidence,editMode:e.editMode,diagnostics:e.diagnostics.map(t=>({code:t.code,message:t.message}))}}function Aw(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}:Iw(t.finalSource.kind)?{kind:"external-entry",file:t.finalSource.file,isProxy:!1,displayPath:t.finalSource.displayPath,sourceType:t.finalSource.externalSource?.sourceType,sourceId:t.finalSource.externalSource?.sourceId}:{kind:"value-path",file:t.finalSource.file,isProxy:t.finalSource.file!==e.file,displayPath:t.finalSource.displayPath}:{kind:e.kind==="route-export"?"route-export":"jsx-node",file:e.file,isProxy:e.isProxy}}var _l=["set-class-name-source","apply-style-draft"];function ah(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:_l,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element"}]};if(t.resolution&&t.resolution.status!=="resolved")return{kind:"class-name-source",className:"",sourceKind:"dynamic-expression",editable:!1,operationBoundary:[],sourcePath:t.source?.expression,diagnostics:[{code:"dynamic-binding",message:"Style binding is unresolved and cannot be edited"}]};if(t.source?.expression){let n=t.source.expression,r=typeof t.resolvedValue=="string"?t.resolvedValue:t.value!==n?t.value:void 0;return typeof r!="string"?{kind:"class-name-source",className:"",sourceKind:"dynamic-expression",editable:!1,operationBoundary:[],sourcePath:n,diagnostics:[{code:t.resolvedValue===void 0?"dynamic-binding":"non-string-binding",message:t.resolvedValue===void 0?"Style binding is dynamic and cannot be edited":"Style binding must resolve to a static string before it can be edited"}]}:{kind:"class-name-source",className:r,sourceKind:"static-expression",editable:!0,operationBoundary:_l,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:_l}}function ch(e){let t=new Map;for(let[n,r]of e.elements){let o=/^[A-Z]/.test(r.tag),i={file:r.sourceFile,componentName:r.componentName,isProxy:o},s=r.boundaryKind,a=[];r.isOpaque&&a.push({kind:"opaque-region",reason:`Component '${r.tag}' is opaque: internal structure not editable`}),o&&!r.isOpaque&&a.push({kind:"component-boundary",reason:`Component '${r.tag}' boundary: editing requires source file access`});let c={key:n,writeTarget:i,boundaryKind:s,parentKey:r.parentKey,childKeys:[...r.childKeys],constraints:a};t.set(n,c)}for(let n of e.regions){let r=n.kind==="repeat-region"?"repeat-region":n.kind==="conditional-region"?"conditional-region":n.kind==="opaque-region"?"opaque-region":"component-boundary",o=n.kind==="repeat-region"?"Node is inside a repeat region: operations affect the template, not individual instances":n.kind==="conditional-region"?"Node is inside a conditional region: visibility depends on runtime condition":`Node is inside a ${n.kind}`;for(let i of n.childKeys){let s=t.get(i);s&&s.constraints.push({kind:r,reason:o}),lh(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function lh(e,t,n,r,o){let i=o.elements.get(e);if(i)for(let s of i.childKeys){let a=r.get(s);a&&!a.constraints.some(c=>c.kind===t)&&(a.constraints.push({kind:t,reason:n}),lh(s,t,n,r,o))}}import uh from"node:path";function Ol(){let e=Promise.resolve();return{async runExclusive(t){let n,r=new Promise(i=>{n=i}),o=e;e=o.then(()=>r,()=>r),await o;try{return await t()}finally{n()}}}}async function fh(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=Mw(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 Es(e){let t=()=>Tw(e);return e.mutex?e.mutex.runExclusive(t):t()}async function Tw(e){let t=await fh(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=Fw(e.overlay,t.plan),r;try{r=await e.buildCandidate({overlay:n,plan:t.plan})}catch(l){return{ok:!1,stage:"build",reason:"Candidate build failed.",error:l,recoveryRequired:!1}}let o,i;try{o=await e.prepareHistory?.({candidate:r,plan:t.plan}),await e.reverify?.({candidate:r,plan:t.plan,history:o}),i=await e.writeCandidate({candidate:r,plan:t.plan}),await e.markCandidateWritten?.({candidate:r,plan:t.plan,history:o,receipt:i})}catch(l){return Ml({candidate:r,plan:t.plan,failedStage:"commit",error:l,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let s=r;try{let l=await e.validateCandidate({candidate:r,plan:t.plan,receipt:i});l!==void 0&&(s=l)}catch(l){return Ml({candidate:r,plan:t.plan,failedStage:"validate",error:l,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let a;try{a=await e.publishCandidate({candidate:s,plan:t.plan,history:o,receipt:i})}catch(l){return Ml({candidate:s,plan:t.plan,failedStage:"publish",error:l,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let c={candidate:s,plan:t.plan,history:o,receipt:i,published:a};try{await e.swapCandidate?.(c)}catch(l){return dh("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return dh("finalize",l,"Transaction finalization failed after live state swap.")}try{e.emitCommitted?.({candidate:s,plan:t.plan,published:a})}catch{}return{ok:!0,stage:"publish",published:a,plan:t.plan}}function Fw(e,t){let n=new Map(e);for(let r of t.intents)r.kind==="delete"?n.delete(r.path):n.set(r.path,r.content);return n}function Ml(e){return e.rollbackCandidate({candidate:e.candidate,plan:e.plan,failedStage:e.failedStage,error:e.error,...e.history===void 0?{}:{history:e.history},...e.receipt===void 0?{}:{receipt:e.receipt}}).then(()=>({ok:!1,stage:e.failedStage,reason:_w(e.failedStage),error:e.error,recoveryRequired:!1})).catch(t=>({ok:!1,stage:"rollback",reason:"Rollback failed after candidate commit/validation/publish failure.",error:t,recoveryRequired:!0,cause:e.error}))}function dh(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function _w(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 Mw(e){if(e.length===0)return{ok:!1,code:"unsafe-path",path:e,reason:"File path must not be empty."};if(e.includes("\0")||e.includes("\\"))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};if(/^[a-zA-Z]:/.test(e)||uh.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=uh.posix.normalize(e);return t==="."||t===".."||t.startsWith("../")||t.includes("/../")?{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`}:t.startsWith("./")||t.includes("/./")?{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`}:{ok:!0,path:t}}var Ow=50,Lw=8*1024*1024;function hh(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??Ow),s=Math.max(0,t.maxUndoBytes??Lw);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:d,redo:f};async function a(R){let A=[...R.steps].sort((se,oe)=>se.order-oe.order),M=A.filter(se=>se.type!=="invoke-external-adapter");if(M.length!==A.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let D=new Set(M.map(se=>se.file)),L=await y(D),ee=new Map(L.map(se=>[se.file,se.exists===!1?"":se.content])),ge;for(let se of M){let oe=gh(se,ee.get(se.file)??"");if(!oe.ok)return{ok:!1,errorCode:oe.errorCode,reason:oe.reason};ee.set(se.file,oe.source),ge=oe.selectionRef??ge}return{ok:!0,filePlan:{operationId:R.operationId,kind:"source-edit",target:R.target,documentVersion:R.documentVersion,conflictPolicy:"compare-and-swap",edits:[...ee].map(([se,oe])=>({operation:"upsert",file:se,content:oe,baseContentHash:L.find(Oe=>Oe.file===se)?.sha256??null}))},...ge?{selectionRef:ge}:{}}}async function c(R){let A=[...R.steps].sort((Oe,Nt)=>Oe.order-Nt.order),M=A.filter(Oe=>Oe.type!=="invoke-external-adapter"),D=A.filter(Oe=>Oe.type==="invoke-external-adapter"),L=new Set(M.map(Oe=>Oe.file));if(M.length>0&&D.length>0)return{ok:!1,operationId:R.operationId,errorCode:"unsupported-operation",reason:"Mixed local file rewrites and external adapter writes require an explicit compensation contract.",rolledBack:!1};if(M.length===0)return b(R,D);let ee=await y(L),ge=new Map;for(let Oe of ee)ge.set(Oe.file,Oe.exists===!1?"":Oe.content);let se;for(let Oe of M){let Nt=ge.get(Oe.file)??"",qt=gh(Oe,Nt);if(!qt.ok)return{ok:!1,operationId:R.operationId,errorCode:qt.errorCode,reason:qt.reason,rolledBack:!1};ge.set(Oe.file,qt.source),qt.selectionRef&&(se=qt.selectionRef)}let oe=await C([...ge].map(([Oe,Nt])=>({file:Oe,content:Nt,exists:!0,version:0,sha256:Ie(Nt)})),ee);return oe.ok===!1?{ok:!1,operationId:R.operationId,errorCode:oe.rolledBack?"writeback-failed":"rollback-failed",reason:oe.reason,rolledBack:oe.rolledBack}:(n.push({operationId:R.operationId,preSnapshots:ee,postSnapshots:oe.snapshots,plan:R}),m(),r.length=0,{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:Math.max(...oe.snapshots.map(Oe=>Oe.version)),affectedFiles:[...L],...se?{selectionRef:se}:{}})}async function l(R){let A=new Set(R.edits.map(oe=>oe.file)),M=await y(A),D=E(R,M);if(D)return{ok:!1,operationId:R.operationId,errorCode:"stale-version",reason:D.reason,affectedFiles:[D.file],rolledBack:!1};let L=new Map(M.map(oe=>[oe.file,oe])),ee=R.edits.find(oe=>oe.operation==="create-only"&&L.get(oe.file)?.exists!==!1);if(ee)return{ok:!1,operationId:R.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${ee.file}`,affectedFiles:[ee.file],rolledBack:!1};let ge=R.edits.map(oe=>oe.operation==="delete"?{file:oe.file,content:"",exists:!1,version:0}:{file:oe.file,content:oe.content,exists:!0,version:0,sha256:Ie(oe.content)}),se=await C(ge,M,new Set(R.edits.filter(oe=>oe.operation==="create-only").map(oe=>oe.file)));return se.ok===!1?{ok:!1,operationId:R.operationId,errorCode:se.rolledBack?"writeback-failed":"rollback-failed",reason:se.reason,rolledBack:se.rolledBack}:(n.push({operationId:R.operationId,preSnapshots:M,postSnapshots:se.snapshots,plan:{operationId:R.operationId,kind:R.kind,target:R.target,documentVersion:R.documentVersion,steps:[],preSnapshots:M}}),m(),r.length=0,{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:Math.max(...se.snapshots.map(oe=>oe.version)),affectedFiles:[...A]})}async function d(){let R=n.at(-1);if(!R)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let A=await C(R.preSnapshots,R.postSnapshots);return A.ok===!1?{ok:!1,operationId:R.operationId,errorCode:A.rolledBack?"writeback-failed":"rollback-failed",reason:A.reason,rolledBack:A.rolledBack}:(n.pop(),r.push(R),{ok:!0,operationId:R.operationId,kind:R.plan.kind,target:R.plan.target,resultVersion:Math.max(...A.snapshots.map(M=>M.version)),affectedFiles:R.preSnapshots.map(M=>M.file)})}async function f(){let R=r.at(-1);if(!R)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let A=await C(R.postSnapshots,R.preSnapshots);return A.ok===!1?{ok:!1,operationId:R.operationId,errorCode:A.rolledBack?"writeback-failed":"rollback-failed",reason:A.reason,rolledBack:A.rolledBack}:(r.pop(),n.push(R),m(),{ok:!0,operationId:R.operationId,kind:R.plan.kind,target:R.plan.target,resultVersion:Math.max(...A.snapshots.map(M=>M.version)),affectedFiles:R.postSnapshots.map(M=>M.file)})}function m(){for(;n.length>i;)n.shift();for(;n.length>0&&u()>s;)n.shift()}function u(){return n.reduce((R,A)=>R+g(A),0)}function g(R){return h(R.preSnapshots)+h(R.postSnapshots)}function h(R){return R.reduce((A,M)=>A+M.file.length+M.content.length,0)}async function b(R,A){let M=[];for(let D of A){let L=D.capability??"write-text",ee=o.find(se=>se.sourceType===D.sourceType&&(D.adapterId===void 0||se.adapterId===D.adapterId)&&(se.capabilities===void 0||se.capabilities.includes(L)));if(!ee)return{ok:!1,operationId:R.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${D.sourceType}`,rolledBack:!1};let ge=await ee.execute(D);if(!ge.ok)return{ok:!1,operationId:R.operationId,errorCode:"writeback-failed",reason:ge.reason??`External adapter failed for ${D.sourceType}`,rolledBack:!1};M.push(D.file)}return{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:0,affectedFiles:M}}function E(R,A){if(R.conflictPolicy!=="compare-and-swap")return null;let M=new Map(A.map(D=>[D.file,D]));for(let D of R.edits){if(D.operation==="create-only")continue;if(D.baseContentHash===void 0)return{file:D.file,reason:`Source file ${D.file} is missing baseContentHash. Reopen the file before saving.`};let L=M.get(D.file),ee=D.baseContentHash;if(ee===null){if(L?.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(L?.exists===!1||L?.sha256!==ee)return{file:D.file,reason:`Source file ${D.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function y(R){let A=[];for(let M of R)A.push(await k(M));return A}async function k(R){if(!await e.exists(R))return{file:R,content:"",version:0,exists:!1};let M=Math.max(1,e.getVersion(R)),D=await e.readFile(R);return{file:R,content:D,version:M,exists:!0,sha256:Ie(D)}}async function C(R,A,M=new Set){let D=[];try{for(let L of R){if(M.has(L.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive(L.file,L.content)}else await N(L);let ee=e.bumpVersion(L.file);D.push(L.file),L.version=ee}}catch(L){let ee=await T(A.filter(se=>D.includes(se.file)));if(ee.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${ee.failedFiles.join(", ")}: ${mh(L)}`,rolledBack:!1,instanceConflict:ph(L)};let ge=ph(L);return{ok:!1,reason:`${ge?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${mh(L)}`,rolledBack:!0,instanceConflict:ge}}return{ok:!0,snapshots:R.map(Dw)}}async function N(R){if(R.exists===!1){await e.deleteFile(R.file);return}await e.writeFile(R.file,R.content)}async function T(R){let A=[];for(let M of R)try{await N(M),e.bumpVersion(M.file)}catch{A.push(M.file)}return A.length===0?{ok:!0}:{ok:!1,failedFiles:A}}}function ph(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function Dw(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:Ie(e.content)}:{}}}function mh(e){return e instanceof Error?e.message:String(e)}function gh(e,t){switch(e.type){case"invoke-external-adapter":return{ok:!1,reason:"External adapter steps must be executed asynchronously",errorCode:"unsupported-operation"};case"add-import":return We(qn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return We(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(ei({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return We(Mr({source:t,locator:e.locator,next:e.value}));case"update-array-item":return We(Mr({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return We(ai({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return We(ni({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return We(ci({source:t,locator:e.locator,index:e.index}));case"move-array-item":return We(li({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return We(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(ri({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,repeatExpression:e.repeatExpression,selectionContext:e.selectionContext}));case"set-class-name-source":return Bw(e,t);case"set-property-changes":return We(oi({source:t,locator:e.locator,changes:e.changes}));case"set-link-target":return We(ii({source:t,locator:e.locator,link:e.link,changes:e.changes}));case"set-property-binding":return We(si({source:t,locator:e.locator,name:e.name,object:e.object,property:e.property}));case"upsert-object-property":return We(di({source:t,objectLocator:e.locator,name:e.name,value:e.value}));default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function Bw(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!xd(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!==Ie(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:yd({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 vs,SiteEditCompositionContextSchema as jw,SiteEditCompositionSelectorSchema as $w}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 yh(e,t){throw new Ye("INVALID_COMPOSITION",e,{value:t})}function ks(e){let t=jw.safeParse(e);return t.success?t.data:yh("Invalid SiteEditCompositionContext.",e)}function xh(e){let t=[],n=new Map,r=new Map;for(let l of e.compositions){let d=ks(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=vs(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=ks(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=vs(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=$w.safeParse(l);if(!d.success)return yh("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=ks(l),f=vs(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=ks(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=vs(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))]}}function Ll(e){let t=new Map,n=new Map;return{readFile(r){let o=t.get(r);return o||(o=e.readFile(r),t.set(r,o)),o},exists(r){let o=n.get(r);return o||(o=e.exists(r),n.set(r,o)),o}}}async function bh(e,t){if(e.length===0)return[];if(e.length===1)return[await t(e[0])];let n=new Array(e.length),r=[],o=0,i=Array.from({length:Math.min(4,e.length)},async()=>{for(;o<e.length&&r.length===0;){let c=o++;try{n[c]=await t(e[c])}catch(l){r.push({index:c,error:l})}}}),s=await Promise.allSettled(i),a=r.sort((c,l)=>c.index-l.index)[0];if(a)throw a.error;for(let c of s)if(c.status==="rejected")throw c.reason;return n}import{composeSiteEditRepeatInstanceKey as Vw,stripSiteEditRepeatInstanceKeys as Sh}from"@vcp-dev/contracts";function Eh(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=Sh(o.key)??o.key;if(i===o.key)continue;let s=n.get(i)??0;r.set(o.key,s),n.set(i,s+1)}return{entriesByKey:t,repeatOccurrenceIndexByKey:r}}function Kw(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 Is(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=Is(e.collectionPathMap?.[t])??Is(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:Is(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>Is(o)??[])}}function vh(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)=>Vw(u,g),c=(u,g,h)=>{let b=o.get(u);if(!b)return a(u,h);let E=a(u,h),y={...b,key:E,parentKey:g,childKeys:[]};return i.push(y),y.childKeys=b.childKeys.flatMap(k=>l(k,h,E)),E},l=(u,g,h)=>{if(!r.has(u))return[c(u,h,g)];let b=f(u,g),E=[];for(let y=0;y<b;y+=1)E.push(c(u,h,[...g,y]));return E},d=Array.from(new Set([...e.rootKeys,...e.entries.filter(u=>u.parentKey===null).map(u=>u.key)]));for(let u of d){if(!r.has(u)){c(u,null,[]);continue}let g=f(u,[]);for(let h=0;h<g;h+=1)c(u,null,[h])}return{...e,rootKeys:[...e.rootKeys],entries:i};function f(u,g){let h=new Set;for(let b of m(u)){let E=n.get(b);if(E){for(let y of[...E.textTargets.values(),...E.elementPropertyTargets.values()])if(!(y?.kind!=="value-binding"||y.sourceKind!=="repeat-template"))for(let k of Uw(y))k.length<=g.length||Jw(k,g)&&h.add(k[g.length])}}return h.size>0?h.size:Kw(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 kh(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function Ih(e,t,n,r){let o=r?.repeatOccurrenceIndexByKey.get(t);if(o!==void 0)return o;if(!e)return null;let i=0;for(let s of e.entries)if((Sh(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function Uw(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 Jw(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 Ch(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 Rh(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 wh(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function Xw(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var Po=class extends Error{constructor(t){let n=t.map(wh);super(Xw(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function Nh(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof Po?{routeId:e,message:n,diagnostics:t.diagnostics.map(wh)}:{routeId:e,message:n}}function Bl(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function jl(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function Er(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function Ph(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function $l(e,t,n,r){if(!e.has(t)&&e.size>=r){let o=e.keys().next().value;o&&e.delete(o)}e.set(t,n)}function Ah(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 qw=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,eN=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],Th=32,Vl=256;function tN(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var Fh={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 pi(t,n)},async deleteFile(t){await(await import("node:fs/promises")).rm(t,{force:!0})},async exists(t){let n=await import("node:fs/promises");try{return await n.access(t),!0}catch{return!1}},getVersion(t){return e.get(t)??1},bumpVersion(t){let n=(e.get(t)??1)+1;return e.set(t,n),n}}}async function 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>Fh.maxEntries||iN(e)>Fh.maxBytes;)e.shift()}}function iN(e){return e.reduce((t,n)=>t+sN(n),0)}function sN(e){return _h(e.preSnapshots)+_h(e.postSnapshots)+aN(e.provenance)}function aN(e){return e?new TextEncoder().encode(JSON.stringify(e)).byteLength:0}function _h(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function Mh(e,t){return{key:Ww(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 Rs=class extends Error{constructor(t){super(t.reason),this.result=t}},Vn=class extends Error{constructor(t){super(Bl(t)),this.failedRoutes=t}};function Oh(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=ot(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(ot(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}function cN(e,t,n){if(!n)return;let r=ot(n.key)??n.key;if(n.key!==e&&n.key!==t&&r!==t)throw new Error(`Selection reference '${n.key}' does not match selected key '${e}'`);if(n.instanceIndex!==void 0&&(!Number.isInteger(n.instanceIndex)||n.instanceIndex<0))throw new Error("Selection reference instanceIndex must be non-negative");if(n.instanceCount!==void 0&&(!Number.isInteger(n.instanceCount)||n.instanceCount<=0))throw new Error("Selection reference instanceCount must be positive");if(n.instanceIndex!==void 0&&n.instanceCount!==void 0&&n.instanceIndex>=n.instanceCount)throw new Error("Selection reference instanceIndex must be smaller than instanceCount");return{...n,key:t}}var 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 i of t)n.set(i.path,i.operation==="delete"?{exists:!1}:{exists:!0,content:i.content});let r=new Map,o=new Map;return{async readFile(i){let s=n.get(i);if(s){if(!s.exists)throw new Error(`Source file not found: ${i}`);return s.content}let a=r.get(i);return a||(a=e.readFile(i),r.set(i,a)),a},async writeFile(){throw new Error("Source edit preflight overlay is read-only.")},async deleteFile(){throw new Error("Source edit preflight overlay is read-only.")},async exists(i){let s=n.get(i);if(s)return s.exists;let a=o.get(i);return a||(a=e.exists(i),o.set(i,a)),a},async getFileInfo(i){let s=n.get(i);return s?s.exists?{path:i,sizeBytes:Buffer.byteLength(s.content,"utf8")}:null:e.getFileInfo?.(i)??null},async listFiles(i={}){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let s=Vh(await e.listFiles(i)),a=new Map(s.files.map(l=>[l.path,l]));for(let[l,d]of n)if(yN(l,i.roots??[])){if(!d.exists){a.delete(l);continue}a.set(l,{path:l,sizeBytes:Buffer.byteLength(d.content,"utf8")})}let c=[...a.values()].sort((l,d)=>l.path.localeCompare(d.path));return s.truncated?{files:c,truncated:s.truncated}:c},getVersion(i){return e.getVersion(i)},bumpVersion(i){return e.getVersion(i)}}}function yN(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function Vh(e){return Array.isArray(e)?{files:e}:e}function xN(e){if(!Gw(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!==Zw||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=Hw(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:vn({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(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=Lh({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(fN.test(e.path)){let t=Lh({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(pN.test(e.path))try{Qw(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${qe(t)}`,details:{path:e.path}}}return{ok:!0}}function Lh({content:e,path:t,profile:n}){let r=[],o=null,i=!1,s=!1,a=!1,c=!1,l=!0;for(let f=0;f<e.length;f+=1){let m=e[f]??"",u=e[f+1]??"";if(n==="mdx"&&l&&e.startsWith("```",f)){c=!c;let g=e.indexOf(`
|
|
1
|
+
import*as gy from"@babel/parser";import*as He from"@babel/types";import*as tn from"node:path";var js=[".tsx",".ts",".jsx",".js"],hy=js.map(e=>`/index${e}`),yy=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 lu(e){let t=e.replace(/[?#].*$/,""),n=/\.([a-z0-9]+)$/i.exec(t);return n!==null&&yy.has(n[1].toLowerCase())}function uu(e){let t=[];for(let n of e.program.body)He.isImportDeclaration(n)&&typeof n.source.value=="string"&&Pt(n.source.value)&&t.push(n.source.value),He.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&Pt(n.source.value)&&t.push(n.source.value),He.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&Pt(n.source.value)&&t.push(n.source.value);return He.traverseFast(e.program,n=>{let r=He.isImportExpression(n)?n.source:He.isCallExpression(n)&&He.isImport(n.callee)?n.arguments[0]:null;He.isStringLiteral(r)&&Pt(r.value)&&t.push(r.value)}),t}function Pt(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function bn(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=tn.dirname(e);return tn.join(n,t).replace(/\\/g,"/")}async function xy(e,t){if(js.some(n=>e.endsWith(n))&&await t(e))return e;for(let n of js){let r=`${e}${n}`;if(await t(r))return r}for(let n of hy){let r=`${e}${n}`;if(await t(r))return r}return null}async function Sn(e,t,n){let r=await Oo(e,t,n);return r.ok?r.path:null}async function Oo(e,t,n){let r=bn(e,t);try{if(!by(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 xy(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 by(e,t,n){if(!Pt(t)||t.includes("\0")||t.includes("\\")||tn.posix.isAbsolute(n))return!1;let r=tn.posix.normalize(n);if(r===".."||r.startsWith("../"))return!1;if(t.startsWith("@/")){let o=t.slice(2);return o.length>0&&!o.split("/").some(i=>i==="..")}return!tn.posix.isAbsolute(e)}import{createHash as Ey}from"node:crypto";import*as du from"@babel/parser";function En(e,t,n,r){return{code:e,message:t,locatorKind:n,details:r}}function J(e,t,n,r,o){return{ok:!1,source:e,diagnostic:En(t,n,r,o)}}function $s(e,t,n,r,o){return{ok:!1,source:e,diagnostic:En(t,n,r,o)}}var Sy={"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:du.parse(t,{sourceType:"module",plugins:Sy[n]})}}catch(r){return{ok:!1,source:t,diagnostic:En("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function Vs(e,t){return At({source:e,profile:fu(t.kind)})}function Ir(e,t){return At({source:e,profile:fu(t)})}function fu(e){return"next-app-entry"}function vn(e){let{filePath:t,source:n}=e,r=t.toLowerCase().split(".").pop()??"";return r==="tsx"?"tsx-module":r==="ts"?"ts-module":r==="jsx"||r==="js"||r===""&&/<\w[\s\S]*>/.test(n)?"tsx-module":"next-app-entry"}var Jt=(e,t)=>{let n=At({source:t,profile:vn({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${Ey("sha256").update(t).digest("hex")}`,ast:n.ast,imports:uu(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};function vy(e,t){return Jt(e,t)}function ky(e,t){return bn(e,t)}import{COMPONENT_I18N_FILE_SUFFIX as Iy,parseComponentI18nResourcesJson as Cy,resolveSiteTextDirection as Ry,SiteLocaleSchema as wy}from"@vcp-dev/contracts";var Ny=["i18next","react-i18next"],Py="components/ui/site-locale-provider.tsx",Ay="components/ui/component-i18n-provider.tsx",pu="app/layout.tsx";async function Lo(e){let t=e.files.filter(m=>m.path.endsWith(Iy));if(t.length===0)return{ok:!0};for(let m of["package.json",pu,Py,Ay])if(!await e.exists(m))return nn(`Target snapshot is missing required i18n host file: ${m}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return nn("Target snapshot package.json is invalid.")}let r=mu(n)&&mu(n.dependencies)?n.dependencies:{},o=Ny.filter(m=>typeof r[m]!="string"||r[m].trim().length===0);if(o.length>0)return nn(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile(pu),s=Ks(i,"html","lang"),a=Ks(i,"html","dir"),c=Ks(i,"SiteLocaleProvider","locale"),l=wy.safeParse(s);if(!l.success||!a||!c||s!==c||a!==Ry(l.data))return nn("Target snapshot app/layout.tsx must keep html lang/dir and SiteLocaleProvider locale consistent.");if(!i.includes('from "@/components/ui/site-locale-provider"')||!/<SiteLocaleProvider\b/.test(i)||!/<\/SiteLocaleProvider>/.test(i))return nn("Target snapshot root layout is not wired to SiteLocaleProvider.");let d=l.data;if(e.targetLocale&&e.targetLocale!==d)return nn("Target snapshot locale does not match the authoritative site language.");let f=d.split("-")[0];for(let m of t){let u=Cy(m.content);if(!u.success)return nn(`Component i18n resource is invalid: ${m.path}.`);if(!e.deferTargetLocale&&!Object.hasOwn(u.data,d)&&!Object.hasOwn(u.data,f))return nn(`Component i18n resource ${m.path} has no locale for ${d} or ${f}.`)}return{ok:!0}}function Ks(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 mu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nn(e){return{ok:!1,message:e}}import Js from"@babel/generator";import*as Su from"@babel/parser";import Xs from"@babel/traverse";import*as Re from"@babel/types";import{computeSiteEditSourceIdentityKey as Fy}from"@vcp-dev/contracts";var gu="data-vcp-ui-component",Do="components/ui";function Xt(e){if(!e)return!1;let t=Us(e);return t===Do||t.startsWith(`${Do}/`)||t.includes(`/${Do}/`)||t.endsWith(`/${Do}`)}function kn(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?Xt(e.slice(2)):e.startsWith("./")||e.startsWith("../")?Xt(Us(`${Ty(t)}/${e}`)):Xt(e):!1}function Us(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 Ty(e){let t=Us(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}import{stripSiteEditRepeatInstanceKeys as aP}from"@vcp-dev/contracts";import{isSiteEditRuntimeContainerTag as lP,isSiteEditRuntimeTextTag as uP}from"@vcp-dev/contracts/site-edit-runtime-capability";var hu={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 _y=typeof Js=="function"?Js:Js.default,My=typeof Xs=="function"?Xs:Xs.default,Oy=new Set(["base","body","head","html","link","meta","noscript","script","style","template","title"]),Ly="suppressHydrationWarning",Dy=new Set(["SiteEditBootstrap"]);function By(e){let t=Vy(e.file,e.projectRoot);if(!$y(e.source)||Xt(t))return{code:e.source,elements:[]};let n=e.attributes??hu,r=Su.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]}),o=[],i=Uy(r,t);return My(r,{JSXElement(s){let a=s.node.openingElement,c=a.name;if(!Xy(c)||Eu(a,n.key))return;let l=Wy(s)??"default",d=Gy(s),f=Fy(t,l,d),m=jo(c)??"unknown",u=Ky(c)?"jsx":"component-call";if(u==="component-call"&&!Hy(s.node.children)&&Dy.has(m))return;let g=u==="component-call"&&Jy(m,i);zy(a,n.key,f),g&&yu(a,gu),jy(s)&&yu(a,Ly),o.push({key:f,tag:m,componentName:l,sourceFile:t,sourceKind:u})}}),o.length===0?{code:e.source,elements:o}:{code:_y(r,{jsescOption:{minimal:!0}}).code,elements:o}}function jy(e){return!e.findParent(t=>t.isJSXElement())}function $y(e){return/(?:^|[=(:,?;\[{>&|\n\r]|return\s+)\s*<(?:[A-Za-z][\w.:-]*|>)(?:\s|>|\/)/m.test(e)}function Vy(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 Ky(e){return Re.isJSXIdentifier(e)&&/^[a-z]/.test(e.name)}function jo(e){return Re.isJSXIdentifier(e)?e.name:Re.isJSXMemberExpression(e)?ku(e):null}function Uy(e,t){let n=new Set;for(let r of e.program.body)if(!(!Re.isImportDeclaration(r)||!kn(r.source.value,t)))for(let o of r.specifiers)n.add(o.local.name);return n}function Jy(e,t){let n=e.split(".")[0]??e;return t.has(n)}function Xy(e){let t=jo(e);return!t||t==="Fragment"||t.endsWith(".Fragment")?!1:!Oy.has(t)}function Eu(e,t){return e.attributes.some(n=>Re.isJSXAttribute(n)&&Re.isJSXIdentifier(n.name,{name:t}))}function zy(e,t,n){vu(e,Re.jsxAttribute(Re.jsxIdentifier(t),Re.stringLiteral(n)))}function yu(e,t){Eu(e,t)||vu(e,Re.jsxAttribute(Re.jsxIdentifier(t),null))}function vu(e,t){let n=e.attributes.findIndex(r=>Re.isJSXSpreadAttribute(r));if(n>=0){e.attributes.splice(n,0,t);return}e.attributes.push(t)}function ku(e){return`${Re.isJSXIdentifier(e.object)?e.object.name:ku(e.object)}.${e.property.name}`}function Wy(e){let t=e;for(;t;){if(t.isFunctionDeclaration()||t.isClassDeclaration())return t.node.id?.name??null;if(t.isVariableDeclarator()&&Re.isIdentifier(t.node.id)){let n=t.get("init");if(!Array.isArray(n)&&(n.isArrowFunctionExpression()||n.isFunctionExpression()))return t.node.id.name}t=t.parentPath}return null}function Hy(e){return e.some(t=>Re.isJSXElement(t)||Re.isJSXFragment(t))}var xu=new WeakMap,Bo=new WeakMap,zs=new WeakMap;function Gy(e){let t=xu.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=Yy(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return xu.set(e.node,o),o}function Yy(e){let t=jo(e.node.openingElement.name);return!t||t==="Fragment"||t.endsWith(".Fragment")?null:/^[A-Z]/.test(t)?`component:${t}#${bu(e,t)}`:`${t}#${bu(e,t)}`}function bu(e,t){let n=Iu(e)??e.getFunctionParent();if(!n)return 0;let r=zs.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=zs.get(n.node);o||(o=new Map,zs.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0,a=n.isJSXElement()||n.isJSXFragment()?$o(n):Zy(n);for(let c of a)if(jo(c.node.openingElement.name)===t){if(i.set(c.node,s),c.node===e.node)return s;s+=1}return i.get(e.node)??0}function Zy(e){let t=Bo.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!Iu(r)&&n.push(r)}}),Bo.set(e.node,n),n}function Iu(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement())return t;t=t.parentPath}return n}function $o(e){let t=Bo.get(e.node);if(t)return t;let n=[],r=e.get("children");for(let o of r)if(!Array.isArray(o)){if(o.isJSXElement()){n.push(o);continue}if(o.isJSXFragment()){n.push(...$o(o));continue}o.isJSXExpressionContainer()&&n.push(...In(o.get("expression")))}return Bo.set(e.node,n),n}function In(e){if(e.isJSXElement())return[e];if(e.isJSXFragment())return $o(e);if(e.isParenthesizedExpression())return In(e.get("expression"));if(e.isLogicalExpression()&&e.node.operator==="&&")return In(e.get("right"));if(e.isConditionalExpression())return[...In(e.get("consequent")),...In(e.get("alternate"))];if(e.isCallExpression()&&qy(e.node)){let t=e.get("arguments")[0];return Qy(t)}return[]}function Qy(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return[t];if(t.isJSXFragment())return $o(t);if(t.isParenthesizedExpression())return In(t.get("expression"));if(!t.isBlockStatement())return[];for(let n of t.get("body")){if(!n.isReturnStatement())continue;let r=n.get("argument");return r.node?In(r):[]}return[]}function qy(e){return Re.isMemberExpression(e.callee)&&Re.isIdentifier(e.callee.property)&&e.callee.property.name==="map"}import{SiteEditOperationRequestSchema as DN,SiteEditPatchPlanSchema as BN}from"@vcp-dev/contracts";function Cn(e){return{requestId:e.requestId,kind:e.kind,composition:e.composition,target:e.target,resultVersion:e.resultVersion,affectedFiles:e.affectedFiles,...e.fileChanges?{fileChanges:e.fileChanges}:{},...e.output?{output:e.output}:{},...e.selectionRef?{selectionRef:e.selectionRef}:{}}}function Vo(e,t){let n=t[0]??"Site edit operation request failed contract validation.";return{ok:!1,composition:{routeId:e.composition.routeId,...e.composition.templateId!==void 0?{effectiveTemplateId:e.composition.templateId}:{}},error:{code:"INVALID_PARAMS",message:n},data:{requestId:e.id,kind:e.kind,composition:{routeId:e.composition.routeId,...e.composition.templateId!==void 0?{effectiveTemplateId:e.composition.templateId}:{}},target:e.target,resultVersion:e.documentVersion}}}function Ko(e,t){if(!e.pageComposition)throw new Error("RenderDocument is missing the required Page Composition projection.");return{siteId:t.siteId,snapshotId:t.snapshotId,composition:e.composition,version:e.version,entries:e.entries.map(n=>({key:n.key,parentKey:n.parentKey,...n.pageCompositionUnitKey?{pageCompositionUnitKey:n.pageCompositionUnitKey}:{},...n.pageCompositionActionScope?{pageCompositionActionScope:n.pageCompositionActionScope}:{},operationSummary:{canUpdateText:n.operationSummary.canUpdateText,canInsertChild:n.operationSummary.canInsertChild,canMove:n.operationSummary.canMove,canRemove:n.operationSummary.canRemove},...n.dynamicDataSummary?{dynamicDataSummary:n.dynamicDataSummary}:{}})),pageComposition:e.pageComposition.status==="unsupported"?{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics}:{status:"supported",containerKey:e.pageComposition.container.key,hasBusinessMembers:e.pageComposition.businessMembers.length>0,placementUnitKeys:e.pageComposition.placementUnits.map(n=>n.key),placements:e.pageComposition.placements.map(n=>({placementKey:n.placementKey,placementUnitKey:n.placementUnitKey,relation:n.relation}))}}}function Uo(e){return{composition:e.composition,key:e.key,tag:e.tag,...e.linkSourceKind?{linkSourceKind:e.linkSourceKind}:{},label:e.label,sourceLocator:e.sourceLocator,isOpaque:e.isOpaque,ancestors:e.ancestors,componentName:e.componentName,sourceFile:e.sourceFile,capabilities:ex(e.capabilities),provenanceChain:e.provenanceChain?{editMode:e.provenanceChain.editMode,diagnostics:e.provenanceChain.diagnostics}:void 0,dynamicData:e.dynamicData,...e.properties?{properties:e.properties}:{},textSegments:e.textSegments.map(t=>({index:t.index,editable:t.editable,sourceKind:t.source?.kind??null})),boundaryKind:e.boundaryKind}}function Jo(e,t){let n=new Date().toISOString();return e.type==="document-changed"?{type:"site-edit.document.changed",siteId:t.siteId,snapshotId:t.snapshotId,composition:e.composition,version:e.version,at:n}:e.type==="operation-completed"?{type:"site-edit.operation.completed",siteId:t.siteId,composition:e.composition,result:Cn(e.result),at:n}:e.type==="operation-failed"?{type:"site-edit.operation.failed",siteId:t.siteId,requestId:e.requestId,composition:e.composition,error:e.error,at:n}:e.type==="capability-changed"?{type:"site-edit.capability.changed",siteId:t.siteId,composition:e.composition,keys:e.keys,at:n}:e.type==="graph-invalidated"?{type:"site-edit.graph.invalidated",siteId:t.siteId,composition:e.composition,at:n}:e.type==="graph-ready"?{type:"site-edit.graph.ready",siteId:t.siteId,composition:e.composition,version:e.version,at:n}:e.type==="graph-error"?{type:"site-edit.graph.error",siteId:t.siteId,composition:e.composition,message:e.message,at:n}:null}function ex(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 Ww,computeSiteEditCompositionKey as Hw,getSiteEditSourceDeleteProtectionReason as Gw,isSiteEditTextSourcePath as Yw,parseSiteEditRepeatInstanceKey as Zw,SITE_EDIT_SOURCE_DELETE_CAPABILITY as Qw,stripSiteEditRepeatInstanceKeys as ot}from"@vcp-dev/contracts";import Cs from"node:path";import{parse as qw}from"yaml";import Zs from"node:path";import{TextDecoder as nx}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as Ru,SITE_EDIT_SOURCE_ALLOWED_DIRS as wu,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as Nu,SiteEditCompositionContextSchema as rx,SiteEditSourceFileResponseSchema as Ws,SiteEditSourceLocationSchema as ox,SiteEditSourcePathSchema as Xo,SiteEditSourceTreeResponseSchema as ix,isSiteEditTextSourcePath as sx}from"@vcp-dev/contracts";import{createHash as tx}from"node:crypto";var Cr=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 Ie(e){return`sha256:${tx("sha256").update(e).digest("hex")}`}var ax=[...Nu,...Ru,...wu];function Qs(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return rx.parse(e.composition)}var Hs=2e3,Gs=12,Ys=24*1024*1024,Cu=512*1024,cx=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),lx={".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"},ux={".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"},dx=new nx("utf-8",{fatal:!0});async function zo(e,t={}){let n=Qs(t),{files:r,truncated:o}=await xx(e,t),i=Ex(r.map(s=>s.metadata));return ix.parse({composition:n,nodes:i,defaultPath:vx(r.map(s=>s.metadata)),totalFiles:r.length,...o?{truncated:o}:{}})}async function Wo(e,t,n={}){let r=Qs(n),o=Xo.parse(t.path),i=await px(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(ea(o)){let a=Tu(o),c=await gx(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return Ws.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...c})}let s=await qs(e,o);return s.ok?Ws.parse({composition:r,path:o,kind:"text",language:Fu(o),sizeBytes:s.sizeBytes,contentHash:Ie(s.content),readonly:!1,content:s.content}):Ws.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function qs(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=fx(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 fx(e){if(e.includes(0))return null;try{return dx.decode(e)}catch{return null}}async function px(e,t,n){if(!hx(t,n))return null;let r=await mx(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function mx(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=Pu(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(ea(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function gx(e,t){if(!cx.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>Cu)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>Cu?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function hx(e,t){return Nu.some(n=>n===e)||Ru.some(n=>n===e)||wu.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=Xo.safeParse(n);return r.success&&r.data===e})}function Ho(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return ox.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 Pu(e){return Array.isArray(e)?{files:e}:e}function yx(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function xx(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=Pu(await e.listFiles({roots:bx(t),maxFiles:Hs+1,maxDepth:Gs,maxTotalBytes:Ys+1})),r=new Map,o=new Set(n.truncated?.reasons),i=0;for(let a of[...n.files].sort((c,l)=>c.path.localeCompare(l.path))){let c=Xo.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>Gs){o.add("max-depth");continue}if(r.size>=Hs){o.add("max-files");break}if(i+a.sizeBytes>Ys){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:Sx(l,a.sizeBytes,Qs(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:yx([...o]),maxFiles:Hs,maxDepth:Gs,maxTotalBytes:Ys}}:{}}}function bx(e){let t=new Set(ax);for(let n of e.routeEntryFiles??[]){let r=Xo.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function Sx(e,t,n){return ea(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:Tu(e),readonly:!0}:{composition:n,path:e,kind:"text",language:Fu(e),sizeBytes:t,readonly:!1}}function Ex(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 Au(t)}function Au(e){return e.map(t=>t.kind==="directory"?{...t,children:Au(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function vx(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 ea(e){return!sx(e)}function Tu(e){let t=Zs.posix.extname(e).toLowerCase();return!t&&Zs.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":lx[t]??"application/octet-stream"}function Fu(e){let t=Zs.posix.extname(e).toLowerCase();return ux[t]??"plaintext"}import ta from"@babel/traverse";import*as Tt from"@babel/types";function _e(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")&&_u(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())&&_u(r.parentPath)}function _u(e){return e?.isImportDeclaration()===!0&&e.node.source.value==="react"}var rn=typeof ta=="function"?ta:ta.default,Go=new WeakMap,Yo=new WeakMap;function Ft(e,t){let n=Vs(e,t);if(!n.ok)return $s(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=ce(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}}:$s(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function ce(e,t){return t.kind==="jsx-node"?Du(e,t):t.kind==="jsx-attribute"?Nx(e,t):t.kind==="value"?Px(e,t):t.kind==="expression"?Ax(e,t):t.kind==="directive"?Tx(e,t):t.kind==="export"?Fx(e,t):{ok:!1,diagnostic:En("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function Du(e,t){return t.strategy==="source-range"?kx(e,t):Ix(e,t)}function kx(e,t){let n=null;if(rn(e,{JSXElement(o){if(!Rn(o.node,t.sourceRange))return;let i=De("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!Rn(o.node,t.sourceRange))return;let i=De("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!Rn(o.node,t.sourceRange))return;let i=De("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXText(o){if(!Rn(o.node,t.sourceRange))return;let i=De("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)}}),!n)return Be("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!Jx(r.path,t.expectedIdentity)?Be("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function Ix(e,t){if(t.structuralPath===""){let r=Rx(e,t.component);if(r){let o=wx(r);if(o)return o}}let n=null;return rn(e,{JSXElement(r){if(wr(r)!==t.component||ra(r)!==t.structuralPath)return;let i=De("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(wr(r)!==t.component||ra(r)!==t.structuralPath)return;let i=De("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=Cx(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:Be("jsx-node","locator-miss","JSX node not found for structural-path locator")}function Cx(e,t,n){let r=null;return rn(e,{JSXElement(o){if(wr(o)!==t||!Rn(o.node,n))return;let i=De("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(wr(o)!==t||!Rn(o.node,n))return;let i=De("jsx-node",o);i&&(r=i,o.stop())}}),r}function Rx(e,t){let n=null;return rn(e,{FunctionDeclaration(r){r.node.id?.name===t&&(n=r,r.stop())},VariableDeclarator(r){if(r.node.id.type==="Identifier"&&r.node.id.name===t){let o=r.get("init");(o.isArrowFunctionExpression()||o.isFunctionExpression())&&(n=o),r.stop()}}}),n}function wx(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 Nx(e,t){let n=Du(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>Xx(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 Px(e,t){let n=_x(e,t);if(!n.ok)return n;let r=Mx(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!Wt(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 Ax(e,t){let n=null;return rn(e,{Identifier(r){if(!$x(r))return;let o=Ou(r);if(!o||!Lu(o,t))return;let i=De("expression",r);i&&(t.expectedRange&&!Wt(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=Ou(r);if(!o||!Lu(o,t))return;let i=De("expression",r);i&&(t.expectedRange&&!Wt(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Be("expression","locator-miss","Expression not found")}function Tx(e,t){let n=null;return rn(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!Wt(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 Fx(e,t){let n=null;return rn(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let c=r.get("declaration");if(c.isFunctionDeclaration()&&c.node.id?.name==="generateMetadata"){let m=De("export",c);if(!m||t.expectedRange&&!Wt(c.node.loc,t.expectedRange))return;n=m,r.stop();return}if(!c.isVariableDeclaration())return;let l=oa(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&&!Wt(d.node.loc,t.expectedRange))return;n=f,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=oa(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!Wt(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&&!Wt(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Be("export","export-not-found",`Export '${Ux(t)}' not found`)}function _x(e,t){let n=null;return rn(e,{Expression(r){if(n||t.root.kind!=="expression"||!Rn(r.node,t.root.sourceRange))return;let o=De("value",r);o&&(n=o,r.stop())},VariableDeclarator(r){if(n)return;if(t.root.kind==="binding"){if(r.node.id.type!=="Identifier"||r.node.id.name!==t.root.name)return;let 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=oa(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 Mx(e,t){let n=na(e);for(let o of t){if(n=na(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=>zx(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=na(n);let r=De("value",n);return r?{ok:!0,match:r}:Be("value","locator-miss","Resolved value has no source range")}function na(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 Wt(e.loc,t)}function Wt(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 ra(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!_e(n)){let o=ju(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${Mu(n,o)}`):t.unshift(`${o}#${Mu(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||Bx(n.parentPath)&&!jx(n.parentPath))break;n=n.parentPath}return t.join("/")}function Mu(e,t){let n=Bu(e)??e.getFunctionParent();if(!n)return 0;let r=Go.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=Go.get(n.node)?.get(t);if(!i){let a=Go.get(n.node);a||(a=new Map,Go.set(n.node,a)),i=new WeakMap,a.set(t,i)}let s=n.isJSXElement()||n.isJSXFragment()?Rr(n):Ox(n);for(let a of s)if(ju(a.node.openingElement)===t){if(i.set(a.node,o),a.node===e.node)return o;o++}return i.get(e.node)??0}function Ox(e){let t=Yo.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!Bu(r)&&n.push(r)}}),Yo.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()){if(_e(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Rr(e){let t=Yo.get(e.node);if(t)return t;let n=[],r=e.get("children");for(let o of r)if(!Array.isArray(o)){if(o.isJSXElement()){if(_e(o)){n.push(...Rr(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Rr(o));continue}o.isJSXExpressionContainer()&&n.push(...zt(o.get("expression")))}return Yo.set(e.node,n),n}function zt(e){if(e.isJSXElement())return _e(e)?Rr(e):[e];if(e.isJSXFragment())return Rr(e);if(e.isParenthesizedExpression())return zt(e.get("expression"));if(e.isLogicalExpression()&&Lx(e.node.operator))return zt(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(...zt(c))}if(s.isReturnStatement()){let a=s.get("argument");a.isExpression()&&i.push(...zt(a));break}}return i}else if(o.node&&o.isExpression())return zt(o)}}}}return e.isConditionalExpression()?[...zt(e.get("consequent")),...zt(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:zt(t)):[]}function Lx(e){return e==="&&"||e==="||"||e==="??"}function ju(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?Dx(e.name):null}function Dx(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 wr(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 Bx(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function jx(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 $x(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function Ou(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 Lu(e,t){return e.base===t.base&&Vx(e.path,t.path??[])}function Vx(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 Kx(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function Ux(e){return e.exportKind==="named"?e.name:e.exportKind}function Be(e,t,n,r){return{ok:!1,diagnostic:En(t,n,e,r)}}function Jx(e,t){return wr(e)!==t.component?!1:ra(e)===t.structuralPath}function Xx(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function oa(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function zx(e,t){return e.isObjectProperty()?Kx(e.node)===t:!1}import*as Vu from"@babel/parser";import{arrayExpression as Zx,booleanLiteral as Qx,identifier as qx,jsxAttribute as eb,jsxExpressionContainer as tb,jsxIdentifier as nb,nullLiteral as rb,numericLiteral as ob,objectExpression as ib,objectProperty as sb,stringLiteral as sa}from"@babel/types";import ia from"@babel/generator";var Wx=typeof ia=="function"?ia:ia.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 Gx(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 Yx(e,t){return e.split(`
|
|
3
|
+
`).map(r=>Gx(r,t)).join(`
|
|
4
|
+
`)}function Zo(e){let{ast:t,source:n}=e;try{let r=Hx(n),i=Wx(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=Yx(i,r)),{ok:!0,source:i}}catch(r){return J(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 Nr(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 ye(e,t,n){let r=Zo({ast:e,source:t});return r.ok?Nr(t,r.source,n):r}function we(e,t){let n=Ir(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function Qo(e,t){return Zo({ast:e,source:t})}function ab(e,t,n){let r=ce(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=ab(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:J(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function on(e){return typeof e=="string"?sa(e):typeof e=="number"?ob(e):typeof e=="boolean"?Qx(e):e===null?rb():Array.isArray(e)?Zx(e.map(t=>on(t))):ib(Object.entries(e).map(([t,n])=>{let r=sb(aa(t),on(n));return t==="__proto__"&&(r.computed=!0),r}))}function cb(e){return typeof e=="string"?sa(e):tb(on(e))}function Pr(e,t){return eb(nb(e),cb(t))}function qo(e,t){try{let r=Vu.parse(`const __VD_NODE__ = (${t});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0];return r?.type!=="VariableDeclaration"||r.declarations[0]?.type!=="VariableDeclarator"||!r.declarations[0].init||r.declarations[0].init.type!=="JSXElement"&&r.declarations[0].init.type!=="JSXFragment"?{ok:!1,result:J(e,"unsupported-syntax","Provided JSX source does not resolve to a JSX node","jsx-node")}:{ok:!0,node:r.declarations[0].init}}catch(n){return{ok:!1,result:J(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function aa(e){return/^[$A-Z_][0-9A-Z_$]*$/i.test(e)?qx(e):sa(e)}function ei(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=we(t,"jsx-node");if(!i.ok)return i.result;let s=ce(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let c=lb(s.match.path)[r];if(!c)return J(t,"locator-miss",`Text segment ${r} not found`,"jsx-node");switch(c.kind){case"jsx-text":c.path.node.value=ub(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 ye(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function lb(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=db(r.get("expression"));o.length>0&&t.push(...o)}}return t}function ub(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function db(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 ca}from"@babel/types";function Gn(e){let{source:t,locator:n}=e,r=we(t,"jsx-node");if(!r.ok)return r.result;let o=ce(r.ast,n);return o.ok?(fb(o.match.path),ye(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function fb(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(ca());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(ca());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(ca());return}e.remove()}import{cloneNode as pb}from"@babel/types";function ti(e){let t=we(e.source,"jsx-node");if(!t.ok)return t.result;let n=ce(t.ast,e.locator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};let r=qo(e.source,e.node.jsx);return r.ok?(n.match.path.replaceWith(pb(r.node,!0)),ye(t.ast,e.source,{kind:"replace-node",target:"jsx-node",inverse:"replace-node"})):r.result}import{cloneNode as Ib}from"@babel/types";import la from"@babel/traverse";import*as q from"@babel/types";function Ar(e,t,n){return`${e}::${t}::${n}`}var V={NODE_NOT_FOUND:"NODE_NOT_FOUND",HOME_PAGE_LOCKED:"HOME_PAGE_LOCKED",ROUTE_NOT_FOUND:"ROUTE_NOT_FOUND",CAPABILITY_REJECTED:"CAPABILITY_REJECTED",CONSTRAINT_VIOLATED:"CONSTRAINT_VIOLATED",INVALID_PARAMS:"INVALID_PARAMS",PLAN_FAILED:"PLAN_FAILED",TRANSACTION_PREFLIGHT_FAILED:"TRANSACTION_PREFLIGHT_FAILED",ROUTE_REBUILD_FAILED:"ROUTE_REBUILD_FAILED",HISTORY_COMMIT_FAILED:"HISTORY_COMMIT_FAILED",MATERIALIZATION_CONFLICT:"MATERIALIZATION_CONFLICT",MATERIALIZATION_REJECTED:"MATERIALIZATION_REJECTED",MUTATION_ASSERTION_REQUIRED:"MUTATION_ASSERTION_REQUIRED",MUTATION_ASSERTION_INVALID:"MUTATION_ASSERTION_INVALID",VERSION_STALE:"VERSION_STALE",AST_PARSE_ERROR:"AST_PARSE_ERROR",UNSUPPORTED_OPERATION:"UNSUPPORTED_OPERATION",LOCATOR_FAILED:"LOCATOR_FAILED",INVALID_TARGET:"INVALID_TARGET",WRITE_IO_ERROR:"WRITE_IO_ERROR",CONCURRENT_MODIFIED:"CONCURRENT_MODIFIED",ROLLBACK_FAILED:"ROLLBACK_FAILED",RECOVERY_REQUIRED:"RECOVERY_REQUIRED",RECOVERY_PERSIST_FAILED:"RECOVERY_PERSIST_FAILED",MUTATION_SESSION_REQUIRED:"MUTATION_SESSION_REQUIRED",LEASE_ASSERTION_INVALID:"LEASE_ASSERTION_INVALID",LEASE_ASSERTION_EXPIRED:"LEASE_ASSERTION_EXPIRED",LEASE_ASSERTION_SCOPE_MISMATCH:"LEASE_ASSERTION_SCOPE_MISMATCH",CROSS_PAGE_MOVE_UNSUPPORTED:"CROSS_PAGE_MOVE_UNSUPPORTED",INTERNAL_ERROR:"INTERNAL_ERROR"};var mb=typeof la=="function"?la:la.default;function mt(e,t,n,r){if(!e.ok)return e;let o=pt(n,t);if(!o)return e;let i=gb(t,o,r);return i?{...e,selectionRef:i}:e}function gb(e,t,n){let r=hb(e,t);if(!r)return;let o=n.sourceLocator?Ku(n.sourceLocator):void 0,i=n.targetParentLocator?Ku(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??xb(r)??i?.component??o?.component;if(!(!s||!a))return{key:Ar(s,a,bb(r))}}function Ku(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function hb(e,t){let n=Hu(e,t);return!n||n.node.type!=="JSXElement"?null:n}function Hu(e,t){let n=null;return mb(e,{JSXElement(r){r.node===t&&(n=r,r.stop())},JSXFragment(r){r.node===t&&(n=r,r.stop())}}),n}function pt(e,t){if(!e)return null;if(q.isJSXElement(e))return kb(t,e)?Uu(e.children,t):e;if(q.isJSXFragment(e))return Uu(e.children,t);if(q.isJSXExpressionContainer(e)||q.isParenthesizedExpression(e)||q.isTSAsExpression(e)||q.isTSSatisfiesExpression(e)||q.isTSTypeAssertion(e)||q.isTSNonNullExpression(e))return pt(e.expression,t);if(q.isLogicalExpression(e))return pt(e.right,t);if(q.isConditionalExpression(e))return pt(e.consequent,t)??pt(e.alternate,t);if(q.isCallExpression(e)||q.isOptionalCallExpression(e))return Gu(e)?yb(e.arguments[0],t):null;if(q.isArrayExpression(e))for(let n of e.elements){if(!n)continue;let r=pt(n,t);if(r)return r}return null}function Uu(e,t){for(let n of e){let r=pt(n,t);if(r)return r}return null}function yb(e,t){return!e||!q.isArrowFunctionExpression(e)&&!q.isFunctionExpression(e)?null:q.isBlockStatement(e.body)?Tr(e.body.body,t):pt(e.body,t)}function Tr(e,t){for(let n of e){if(q.isReturnStatement(n)){let r=pt(n.argument,t);if(r)return r;continue}if(q.isBlockStatement(n)){let r=Tr(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=Tr(r.consequent,t);if(o)return o}}return null}function Ju(e,t){return q.isBlockStatement(e)?Tr(e.body,t):Tr([e],t)}function xb(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 Xu=new WeakMap,zu=new WeakMap,ua=new WeakMap;function bb(e){let t=Xu.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=Sb(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return Xu.set(e.node,o),o}function Sb(e){let t=Yu(e.node.openingElement.name);return!t||_e(e)?null:/^[A-Z]/.test(t)?`component:${t}#${Wu(e,t)}`:`${t}#${Wu(e,t)}`}function Wu(e,t){let n=Eb(e);if(!n)return 0;let r=ua.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=ua.get(n.node);o||(o=new Map,ua.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of wn(n))if(Yu(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 Eb(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(_e(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function wn(e){let t=zu.get(e.node);if(t)return t;let n=[],r=e.get("children");for(let o of r)if(!Array.isArray(o)){if(o.isJSXElement()){if(_e(o)){n.push(...wn(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...wn(o));continue}o.isJSXExpressionContainer()&&n.push(..._t(o.get("expression")))}return zu.set(e.node,n),n}function _t(e){if(e.isJSXElement())return _e(e)?wn(e):[e];if(e.isJSXFragment())return wn(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())&&Gu(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?vb(n):[]}return[]}function vb(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return _e(t)?wn(t):[t];if(t.isJSXFragment())return wn(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 Gu(e){let t=e.callee;return(q.isMemberExpression(t)||q.isOptionalMemberExpression(t))&&q.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function kb(e,t){let n=Hu(e,t);return n?_e(n):!1}function Yu(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 sn(e,t){if(t.parentPath===e&&t.listKey==="children"&&da(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!da(n))return null;let r=n;for(;r&&r!==e;){if(!da(r)||!_e(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function da(e){return e.isJSXElement()||e.isJSXFragment()}function Yn(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=we(t,"jsx-node");if(!a.ok)return a.result;let c=ce(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return J(t,"unsupported-syntax","insert-child target must be a JSXElement or JSXFragment","jsx-node");let l=c.match.path;if(c.match.path.isJSXElement()){let k=c.match.path.node;if(!k.closingElement||k.openingElement.selfClosing)return J(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let d=qo(t,r.jsx);if(!d.ok)return d.result;let f=Ib(d.node,!0),m=l.node.children,u={...s,targetParentLocator:n},g=k=>s?mt(k,a.ast,f,u):k;if(o==="append")return m.push(f),g(ye(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return m.unshift(f),g(ye(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(!i)return J(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let h=ce(a.ast,i);if(!h.ok)return{ok:!1,source:t,diagnostic:h.diagnostic};let b=sn(c.match.path,h.match.path);if(!b)return J(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,y=E.findIndex(k=>k===h.match.path.node);return y===-1?J(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(E.splice(o==="before"?y:y+1,0,f),g(ye(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as Qu from"@babel/parser";import{cloneNode as Cb}from"@babel/types";function ni(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=we(t,"jsx-node");if(!a.ok)return a.result;let c=Rb(t,r);if(!c.ok)return c.result;let l=ce(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return J(t,"unsupported-syntax","insert-jsx-expression-child target must be a JSXElement or JSXFragment","jsx-node");if(l.match.path.isJSXElement()){let E=l.match.path.node;if(!E.closingElement||E.openingElement.selfClosing)return J(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let d=l.match.path,f=null;if(i){let E=ce(a.ast,i);if(!E.ok)return{ok:!1,source:t,diagnostic:E.diagnostic};let y=sn(l.match.path,E.match.path);if(!y)return J(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");d=y,f=E.match.path.node}else if(o==="before"||o==="after")return J(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=Cb(c.node,!0),u=d.node.children,g={...s,targetParentLocator:n},h=E=>s?mt(E,a.ast,m,g):E;if(o==="append")return u.push(m),h(ye(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return u.unshift(m),h(ye(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let b=u.findIndex(E=>E===f);return b===-1?J(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(u.splice(o==="before"?b:b+1,0,m),h(ye(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function Rb(e,t){try{let r=Qu.parse(`const __VD_EXPR__ = <>{${t}}</>;`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],o=r?.type==="VariableDeclaration"?r.declarations[0]?.init:null,i=o?.type==="JSXFragment"?o.children[0]:void 0;return i?.type!=="JSXExpressionContainer"?{ok:!1,result:J(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:J(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as wb,nullLiteral as fa}from"@babel/types";import*as an from"@babel/types";import*as qu from"@babel/types";function Fr(e,t){let n=e.parentPath;if(!n?.isConditionalExpression()||e.key!=="consequent"||!qu.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=we(t,"jsx-node");if(!a.ok)return a.result;let c=ce(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let l=ce(a.ast,r);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return J(t,"unsupported-syntax","move-node target parent must be a JSXElement or JSXFragment","jsx-node");let d=l.match.path;if(l.match.path.isJSXElement()){let k=l.match.path.node;if(!k.closingElement||k.openingElement.selfClosing)return J(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let f=null;if(i){let k=ce(a.ast,i);if(!k.ok)return{ok:!1,source:t,diagnostic:k.diagnostic};let C=k.match.path.isJSXElement()?Fr(k.match.path,l.match.path):k.match.path,N=sn(l.match.path,C);if(!N)return J(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");d=N,f=C}else if(o==="before"||o==="after")return J(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=f&&typeof f.key=="number"?f.key:-1;if(f&&m===-1)return J(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let u=c.match.path.isJSXElement()?Fr(c.match.path,l.match.path):c.match.path,g=wb(u.node,!0);if(!an.isJSXElement(g)&&!an.isJSXExpressionContainer(g)&&!an.isJSXFragment(g)&&!an.isJSXText(g))return J(t,"unsupported-syntax","move-node source must resolve to a JSX child","jsx-node");let h=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 J(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");Nb(u);let b=d.node.children,E={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return b.push(g),mt(Qo(a.ast,t),a.ast,g,E);if(o==="prepend")return b.unshift(g),mt(Qo(a.ast,t),a.ast,g,E);let y=m-(h!==-1&&h<m?1:0);return b.splice(o==="before"?y:y+1,0,g),mt(Qo(a.ast,t),a.ast,g,E)}function Nb(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(fa());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(fa());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(fa());return}e.remove()}import*as ed from"@babel/parser";import{cloneNode as Pb,nullLiteral as pa}from"@babel/types";function ri(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,c=we(t,"jsx-node");if(!c.ok)return c.result;let l=Ab(t,s);if(!l.ok)return l.result;let d=ce(c.ast,n);if(!d.ok)return{ok:!1,source:t,diagnostic:d.diagnostic};let f=ce(c.ast,r);if(!f.ok)return{ok:!1,source:t,diagnostic:f.diagnostic};if(!f.match.path.isJSXElement()&&!f.match.path.isJSXFragment())return J(t,"unsupported-syntax","move-repeat-template-child target parent must be a JSXElement or JSXFragment","jsx-node");if(f.match.path.isJSXElement()){let k=f.match.path.node;if(!k.closingElement||k.openingElement.selfClosing)return J(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let m=f.match.path,u=null;if(i){let k=ce(c.ast,i);if(!k.ok)return{ok:!1,source:t,diagnostic:k.diagnostic};let C=sn(f.match.path,k.match.path);if(!C)return J(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");m=C,u=k.match.path.node}else if(o==="before"||o==="after")return J(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!d.match.path.isJSXElement())return J(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let g=m.node,h=Pb(l.node,!0);Tb(d.match.path);let b={...a,sourceLocator:n,targetParentLocator:r},E=g.children;if(o==="append")return E.push(h),mt(ye(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),mt(ye(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,b);let y=E.findIndex(k=>k===u);return y===-1?J(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(E.splice(o==="before"?y:y+1,0,h),mt(ye(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,b))}function Ab(e,t){try{let r=ed.parse(`const __VD_EXPR__ = <>{${t}}</>;`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],o=r?.type==="VariableDeclaration"?r.declarations[0]?.init:null,i=o?.type==="JSXFragment"?o.children[0]:void 0;return i?.type!=="JSXExpressionContainer"?{ok:!1,result:J(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:J(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function Tb(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(pa());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(pa());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(pa());return}e.remove()}import{SiteEditSetPropsParamsSchema as Fb,classifySiteEditPropertyName as _b}from"@vcp-dev/contracts";import*as Qn from"@babel/types";function oi(e){let t=Fb.safeParse({kind:"set-props",scope:"selection",changes:e.changes});if(!t.success)return J(e.source,"unsupported-syntax","Invalid typed JSX property changes","jsx-node",{issues:t.error.issues});let n=we(e.source,"jsx-node");if(!n.ok)return n.result;let r=Hn(n.ast,e.locator,e.source);if(!r.ok)return r.result;for(let a of t.data.changes){let c=_b(a.name);if(c.owner!=="generic")return J(e.source,"unsupported-syntax",c.diagnostic?.message??`Property '${a.name}' is not owned by the generic JSX primitive`,"jsx-node")}let o=r.match.path.node.openingElement,i=o.attributes.filter(Qn.isJSXAttribute),s=new Map;for(let a of i){let c=Mb(a);if(!c)continue;let l=s.get(c)??[];l.push(a),s.set(c,l)}for(let a of t.data.changes)if((s.get(a.name)??[]).length>1)return J(e.source,"unsupported-syntax",`JSX attribute '${a.name}' has multiple sources`,"jsx-node");for(let a of t.data.changes){let c=s.get(a.name)?.[0];if(a.operation==="remove"){c&&(o.attributes=o.attributes.filter(d=>d!==c));continue}let l=Pr(a.name,a.value).value;c?c.value=l:o.attributes.push(Pr(a.name,a.value))}return ye(n.ast,e.source,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}function Mb(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 Ob}from"@vcp-dev/contracts";import*as z from"@babel/types";var td=["prefetch","replace","scroll","locale","onNavigate"],Lb=/^on(?:Click|DoubleClick|AuxClick|MouseDown|MouseUp|PointerDown|PointerUp|TouchStart|TouchEnd|KeyDown|KeyUp|ContextMenu)(?:Capture)?$/;function Db(e){let t=e;for(;t;){if(t.isJSXElement()&&t.node.openingElement.attributes.some(n=>z.isJSXAttribute(n)&&z.isJSXIdentifier(n.name)&&Lb.test(n.name.name)))return!0;t=t.parentPath}return!1}function ii(e){let t=we(e.source,"jsx-node");if(!t.ok)return t.result;let n=Hn(t.ast,e.locator,e.source);if(!n.ok)return n.result;let r=Ob.safeParse({kind:"set-link-target",scope:"selection",link:e.link,changes:e.changes});if(!r.success||r.data.kind!=="set-link-target")return Ht(e.source,"Invalid typed link-target changes");let o=n.match.path,i=o.node,s=i.openingElement,a=Jb(s.name);if(!a)return Ht(e.source,"Unsupported JSX link tag");if(s.attributes.some(z.isJSXSpreadAttribute))return Ht(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=ga(g);if(!h)return Ht(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 Ht(e.source,"Duplicate JSX attributes cannot be transformed safely");let l=c.get("href")?.[0];if(l&&!Ub(l))return Ht(e.source,"Dynamic link href cannot be transformed safely");let d=a==="a",f=d?null:$b(o,s.name);if(!d&&!f)return Ht(e.source,"Only native anchors and imported next/link components are supported");if(e.link.kind==="none"&&Db(o))return Ht(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=Vb(t.ast,o);if(!g.ok)return Ht(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")),Kb(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"),td.forEach(g=>u.add(g))):(u.add("href"),e.link.kind==="native-link"&&td.forEach(g=>u.add(g))),s.attributes=s.attributes.filter(g=>{if(!z.isJSXAttribute(g))return!0;let h=ga(g);return!h||!u.has(h)}),e.link.kind!=="none"&&s.attributes.push(z.jsxAttribute(z.jsxIdentifier("href"),z.stringLiteral(e.link.href))),Bb(s,e.changes),ye(t.ast,e.source,{kind:"set-link-target",target:"jsx-node",inverse:"set-link-target"})}function Bb(e,t){for(let n of t){let r=e.attributes.find(s=>z.isJSXAttribute(s)&&ga(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(ma(n.value)),i=z.jsxAttribute(z.jsxIdentifier(n.name),o);r&&z.isJSXAttribute(r)?r.value=i.value:e.attributes.push(i)}}function ma(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=>ma(t))):typeof e=="object"?z.objectExpression(Object.entries(e).map(([t,n])=>z.objectProperty(z.isValidIdentifier(t)?z.identifier(t):z.stringLiteral(t),ma(n)))):z.nullLiteral()}function jb(e){return z.isImportDefaultSpecifier(e)||z.isImportSpecifier(e)&&e.importKind!=="type"&&(z.isIdentifier(e.imported,{name:"default"})||z.isStringLiteral(e.imported,{value:"default"}))}function nd(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 $b(e,t){if(!z.isJSXIdentifier(t))return null;let n=e.scope.getBinding(t.name);if(!n||!nd(n.path))return null;let r=n.path.parentPath;return!r?.isImportDeclaration()||r.node.source.value!=="next/link"?null:t.name}function Vb(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(jb);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 Kb(e,t,n){let r=n.scope.getProgramParent();r.crawl();let o=r.getBinding(t);if(!o||!nd(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 Ub(e){return!e.value||z.isStringLiteral(e.value)}function Jb(e){return z.isJSXIdentifier(e)?e.name:null}function ga(e){return z.isJSXIdentifier(e.name)?e.name.name:null}function Ht(e,t){return J(e,"unsupported-syntax",t,"jsx-node")}import*as Ke from"@babel/types";import{classifySiteEditPropertyName as rd}from"@vcp-dev/contracts";function si(e){let t=rd(e.name),n=rd(e.property);if(t.owner!=="generic"||n.owner!=="generic")return J(e.source,"unsupported-syntax","Property binding is only available for generic properties","jsx-node");if(!od(e.object))return J(e.source,"unsupported-syntax","Property binding object must be a single identifier","jsx-node");if(e.property.length===0)return J(e.source,"unsupported-syntax","Property binding requires a non-empty property name","jsx-node");let r=we(e.source,"jsx-node");if(!r.ok)return r.result;let o=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)&&zb(l)===e.name);if(s.length>1)return J(e.source,"unsupported-syntax",`JSX attribute '${e.name}' has multiple sources`,"jsx-node");let a=Xb(e.object,e.property),c=s[0];if(c)c.value=Ke.jsxExpressionContainer(a);else{let l=Pr(e.name,"");l.value=Ke.jsxExpressionContainer(a),i.attributes.push(l)}return ye(r.ast,e.source,{kind:"set-property-binding",target:"jsx-node",inverse:"restore-property-binding"})}function Xb(e,t){return od(t)?Ke.memberExpression(Ke.identifier(e),Ke.identifier(t)):Ke.memberExpression(Ke.identifier(e),Ke.stringLiteral(t),!0)}function od(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)}function zb(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 _r,importDeclaration as Gb,importDefaultSpecifier as Yb,importNamespaceSpecifier as Zb,importSpecifier as Qb,isImportDefaultSpecifier as id,isImportNamespaceSpecifier as sd,isImportSpecifier as ad,stringLiteral as qb}from"@babel/types";function qn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(b=>!cS(b));if(o!==-1){let b=r[o],E=b&&typeof b=="object"&&"kind"in b?b.kind:void 0;return J(t,"unsupported-syntax",`Unsupported import spec kind: ${String(E)}`)}let i=iS(r);if(!i.ok)return J(t,"unsupported-syntax",i.message);let s=we(t);if(!s.ok)return s.result;let{ast:a}=s,c=a.program,l=c.body.filter(b=>b.type==="ImportDeclaration"&&b.source.value===n),d=new Set(l.flatMap(b=>b.specifiers.flatMap(E=>{let y=lS(b,E);return y?[y]:[]}))),f=i.imports.filter(b=>!d.has(pd(b)));if(f.length===0)return Nr(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let m=sS(c.body),u=f.find(b=>m.has(ha(b)));if(u)return J(t,"unsupported-syntax",`Import local binding already exists: ${ha(u)}`);let g=oS(f);if(g.reduce((b,E)=>b+E.length,0)!==f.length)return J(t,"unsupported-syntax","Unsupported import specifier grouping");for(let b of g){if(!dd(ld(b)))return J(t,"unsupported-syntax","Unsupported import specifier combination");let E=l.find(y=>eS(y,b));if(E)tS(E,b);else{let y=Gb(cd(b),qb(n));aS(c.body,y),l.push(y)}}return ye(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function eS(e,t){return e.importKind==="type"?!1:dd(rS(nS(e),ld(t)))}function tS(e,t){let n=!1,r=new Set(e.specifiers.map(o=>ya(o)));for(let o of cd(t)){let i=ya(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return fd(e.specifiers),{changed:n}}function cd(e){let t=e.map(n=>{switch(n.kind){case"named":return Qb(n.local?_r(n.local):_r(n.imported),_r(n.imported));case"default":return Yb(_r(n.local));case"namespace":return Zb(_r(n.local));default:return n}});return fd(t),t}function ld(e){let t=ud();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 nS(e){let t=ud();for(let n of e.specifiers)id(n)?t.defaultLocals.add(n.local.name):sd(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function ud(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function rS(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function dd(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function fd(e){let t=[...e.filter(n=>id(n)),...e.filter(n=>sd(n)),...e.filter(n=>ad(n))];e.splice(0,e.length,...t)}function oS(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 iS(e){let t=new Map,n=new Map;for(let r of e){let o=pd(r);if(t.has(o))continue;let i=ha(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 sS(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 aS(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 cS(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 pd(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 ha(e){return e.kind==="named"?e.local??e.imported:e.local}function lS(e,t){return e.importKind==="type"||ad(t)&&t.importKind==="type"?null:ya(t)}function ya(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=>!dS(d));if(o!==-1){let d=r[o],f=d&&typeof d=="object"&&"kind"in d?d.kind:void 0;return J(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(f)}`)}let i=we(t);if(!i.ok)return i.result;let{ast:s}=i,a=s.program,c=a.body.findIndex(d=>d.type==="ImportDeclaration"&&d.source.value===n);if(c===-1)return Nr(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let l=a.body[c];return r.length===0?(a.body.splice(c,1),ye(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(l.specifiers=l.specifiers.filter(d=>!r.some(f=>uS(d,f))),l.specifiers.length===0&&a.body.splice(c,1),ye(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function uS(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 dS(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 Mr(e){let{source:t,locator:n,next:r}=e,o=ui(t,n);return o.ok?(o.path.replaceWith(on(r)),ye(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function ai(e){let{source:t,locator:n,index:r,value:o}=e,i=ui(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(s=>s?.type==="SpreadElement")?J(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>i.path.node.elements.length?J(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,0,on(o)),ye(i.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):J(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function ci(e){let{source:t,locator:n,index:r}=e,o=ui(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(i=>i?.type==="SpreadElement")?J(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=o.path.node.elements.length?J(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(o.path.node.elements.splice(r,1),ye(o.ast,t,{kind:"remove-array-element",target:"value",inverse:"insert-array-element"})):J(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function li(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=ui(t,n);if(!i.ok)return i.result;if(!i.path.isArrayExpression())return J(t,"unsupported-syntax","Array operations require array expression target","value");if(i.path.node.elements.some(c=>c?.type==="SpreadElement"))return J(t,"unsupported-syntax","Spread array elements are not supported","value");if(r<0||r>=i.path.node.elements.length||o<0||o>i.path.node.elements.length)return J(t,"array-index-out-of-range","Array move indices are out of range","value");let[s]=i.path.node.elements.splice(r,1),a=Math.min(o,i.path.node.elements.length);return i.path.node.elements.splice(a,0,s),ye(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function ui(e,t){let n=we(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=ce(n.ast,t);return r.ok?{ok:!0,ast:n.ast,path:r.match.path}:{ok:!1,result:{ok:!1,source:e,diagnostic:r.diagnostic}}}import*as Xe from"@babel/types";function di(e){let t=we(e.source,"value");if(!t.ok)return t.result;let n=ce(t.ast,e.objectLocator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};if(!n.match.path.isObjectExpression())return J(e.source,"unsupported-syntax","Object property upsert requires an ObjectExpression parent","value");let r=n.match.path.node;if(r.properties.some(a=>Xe.isSpreadElement(a)||Xe.isObjectProperty(a)&&a.computed))return J(e.source,"unsupported-syntax","Object property upsert does not support spreads or computed keys","value");let o=r.properties.filter(a=>Xe.isObjectProperty(a)&&fS(a.key)===e.name);if(o.length>1)return J(e.source,"unsupported-syntax",`Object property '${e.name}' has multiple sources`,"value");let i=e.value.kind==="undefined"?Xe.unaryExpression("void",Xe.numericLiteral(0)):on(e.value.value),s=o[0];if(s)s.value=i,s.shorthand=!1;else{let a=Xe.objectProperty(aa(e.name),i);e.name==="__proto__"&&(a.computed=!0),r.properties.push(a)}return ye(t.ast,e.source,{kind:"upsert-object-property",target:"value",inverse:"restore-object-property"})}function fS(e){return Xe.isIdentifier(e)?e.name:Xe.isStringLiteral(e)?e.value:Xe.isNumericLiteral(e)?String(e.value):null}import{isSiteEditRuntimeContainerTag as pS,isSiteEditRuntimeVoidElementTag as mS}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 gS(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(C=>({kind:C.kind,message:C.reason})),a=i.isOpaque,l=o.parentKey===null&&i.componentName==="Page",d=i.tag.toLowerCase(),f=i.tag!==d,m=!f&&mS(d),u=f||pS(d),g=f&&i.childKeys.length>0&&!i.isPublicUiComponent,h=i.textSegments.length>0&&i.textSegments.some(C=>C.editable);m&&!s.some(C=>C.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' is void: children cannot be inserted`}),!m&&!u&&!s.some(C=>C.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' cannot contain structured children`});let 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 md(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,gS(r,e,t));return n}function xa(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:Ie(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=hS(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:Ie(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:hd(r),version:{documentVersion:e.route.graph.version,contentHash:Ie(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:gd(e.route.source,o),valueRaw:s?gd(e.route.source,s):null,attrRange:hd(o),diagnostics:[]}}function yd(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 hS(e,t){let n=At({source:e,profile:vn({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=ce(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:yS(t.sourceRange)});return!r.ok||r.match.node.type!=="JSXElement"?null:r.match.node}function xd(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 gd(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function hd(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 yS(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function bd(){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 xS}from"node:crypto";import fi from"node:fs/promises";import ba from"node:path";import{setTimeout as bS}from"node:timers/promises";var SS={async mkdir(e,t){await fi.mkdir(e,t)},async writeFile(e,t,n){await fi.writeFile(e,t,n)},async rename(e,t){await fi.rename(e,t)},async rm(e,t){await fi.rm(e,t)}},ES=new Set(["EACCES","EBUSY","EPERM"]),vS=[10,20,40,80,160];async function kS(e,t,n){for(let r of vS)try{await e.rename(t,n);return}catch(o){if(!IS(o))throw o;await bS(r)}await e.rename(t,n)}function IS(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&ES.has(e.code)}async function pi(e,t,n=SS){let r=ba.dirname(e),o=ba.basename(e),i=ba.join(r,`.${o}.${process.pid}.${xS()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await kS(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import Sa from"@babel/traverse";import*as v from"@babel/types";import*as de from"@babel/types";function Mt(e,t={}){if(de.isTSAsExpression(e)||de.isTSSatisfiesExpression(e)||de.isTSNonNullExpression(e)||de.isTypeCastExpression(e)||de.isParenthesizedExpression(e))return Mt(e.expression,t);if(de.isStringLiteral(e))return{status:"resolved",value:e.value};if(de.isNumericLiteral(e))return Number.isFinite(e.value)?{status:"resolved",value:e.value}:{status:"unresolved"};if(de.isBooleanLiteral(e))return{status:"resolved",value:e.value};if(de.isNullLiteral(e))return{status:"resolved",value:null};if(de.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(de.isIdentifier(e))return e.name==="undefined"&&!t.resolveIdentifier?{status:"undefined"}:t.resolveIdentifier?.(e.name)??{status:"unresolved"};if(de.isUnaryExpression(e)&&e.operator==="void"&&de.isNumericLiteral(e.argument)&&e.argument.value===0)return{status:"undefined"};if(de.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||de.isSpreadElement(r))return{status:"unresolved"};let o=Mt(r,t);if(o.status!=="resolved")return{status:"unresolved"};n.push(o.value)}return{status:"resolved",value:n}}if(de.isObjectExpression(e)){let n=Object.create(null);for(let r of e.properties){if(!de.isObjectProperty(r)||r.computed||!de.isExpression(r.value))return{status:"unresolved"};let o=CS(r.key);if(o===null)return{status:"unresolved"};let i=Mt(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 de.isMemberExpression(e)||de.isOptionalMemberExpression(e)?t.resolveMember?.(e)??{status:"unresolved"}:{status:"unresolved"}}function CS(e){return de.isIdentifier(e)?e.name:de.isStringLiteral(e)?e.value:de.isNumericLiteral(e)?String(e.value):null}var RS=typeof Sa=="function"?Sa:Sa.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 wS(e){return/^[A-Z]/.test(e)}function Ca(e){let t=e.openingElement;return v.isJSXIdentifier(t.name)?t.name.name==="Fragment":v.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function rr(e){return v.isJSXFragment(e)}function Ed(e){return v.isJSXIdentifier(e.name)?e.name.name:v.isJSXMemberExpression(e.name)?vd(e.name):v.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function vd(e){return v.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:v.isJSXMemberExpression(e.object)?`${vd(e.object)}.${e.property.name}`:e.property.name}function NS(e){return e.split(".")[0]??e}function PS(e){let t=e;for(;t;){let n=t.node;if(v.isFunctionDeclaration(n)&&n.id||v.isVariableDeclarator(n)&&v.isIdentifier(n.id))return n.id.name;if(v.isExportDefaultDeclaration(n)){let r=n.declaration;if(v.isFunctionDeclaration(r)&&r.id)return r.id.name;if(v.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function AS(){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 TS(e){let t=new Map;for(let n of e.program.body){if(!v.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(v.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(v.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(v.isImportSpecifier(o)){let i=v.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function Gt(e,t=[]){if(v.isIdentifier(e))return t.push(e.name),t;if(v.isObjectPattern(e)){for(let n of e.properties)v.isObjectProperty(n)?Gt(n.value,t):v.isRestElement(n)&&Gt(n.argument,t);return t}if(v.isArrayPattern(e)){for(let n of e.elements)n&&(v.isRestElement(n)?Gt(n.argument,t):Gt(n,t));return t}return v.isAssignmentPattern(e)?(Gt(e.left,t),t):(v.isRestElement(e)&&Gt(e.argument,t),t)}function Et(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Or(e,t){for(let n=t.length-1;n>=0;n-=1){let r=t[n].get(e);if(r)return r.resolved?{kind:"resolved",value:r.value}:{kind:"unresolved"}}return{kind:"unresolved"}}function FS(e,t,n){e.set(t,{resolved:!0,value:n})}function Ra(e,t){e.set(t,{resolved:!1})}function kd(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(v.isTSAsExpression(e)||v.isTSSatisfiesExpression(e)||v.isTSNonNullExpression(e)||v.isTypeCastExpression(e)||v.isParenthesizedExpression(e))return $e(e.expression,t,n);if(v.isLogicalExpression(e))return mi([$e(e.left,t,n),$e(e.right,t,n)]);if(v.isBinaryExpression(e))return mi([v.isExpression(e.left)?$e(e.left,t,n):null,v.isExpression(e.right)?$e(e.right,t,n):null]);if(v.isConditionalExpression(e))return mi([$e(e.consequent,t,n),$e(e.alternate,t,n)]);if(v.isTemplateLiteral(e))return mi(e.expressions.filter(v.isExpression).map(i=>$e(i,t,n)));if(v.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!v.isMemberExpression(e)&&!v.isOptionalMemberExpression(e))return null;let r=[],o=e;for(;v.isMemberExpression(o)||v.isOptionalMemberExpression(o);){if(o.computed)if(v.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(v.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&v.isExpression(o.property)){let i=cn(o.property,n);if(typeof i=="string")r.unshift({kind:"property",name:i});else if(Number.isInteger(i))r.unshift({kind:"index",index:i});else return null}else return null;else{if(!v.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return v.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:Et(e,t),base:o.name,path:r}:null}function mi(e){let t=e.filter(r=>r!==null);if(t.length===0)return null;let n=t[0];return t.some(r=>r.base!==n.base||JSON.stringify(r.path)!==JSON.stringify(n.path))?null:{...n}}function cn(e,t){if(v.isStringLiteral(e)||v.isNumericLiteral(e)||v.isBooleanLiteral(e))return e.value;if(v.isNullLiteral(e))return null;if(v.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(v.isIdentifier(e)){let n=Or(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(v.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||v.isSpreadElement(r))return;let o=cn(r,t);if(o===void 0)return;n.push(o)}return n}if(v.isObjectExpression(e)){let n={};for(let r of e.properties){if(!v.isObjectProperty(r)||r.computed||!v.isExpression(r.value))return;let o=null;if(v.isIdentifier(r.key)?o=r.key.name:v.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!v.isIdentifier(r.value))return;let s=Or(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=cn(r.value,t);if(i===void 0)return;n[o]=i}return n}if(v.isMemberExpression(e)){let n=$e(e,"",t);if(!n)return;let r=Or(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=kd(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(v.isCallExpression(e))return Cd(e,t)??void 0}function Id(e,t,n){let r=$e(e,n,t);if(!r)return v.isMemberExpression(e)||v.isBinaryExpression(e)||v.isLogicalExpression(e)||v.isConditionalExpression(e)||v.isCallExpression(e)?{value:Et(e,n),source:null}:null;let o=Or(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?kd(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 Ea(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:AS(),parentStack:[],valueScopes:i,importMap:o}}function ka(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of Gt(o.id))Ra(n,s);if(!v.isIdentifier(o.id)||!o.init||!v.isExpression(o.init))continue;let i=cn(o.init,t);i!==void 0&&FS(n,o.id.name,i)}}function _S(e){let t=[];for(let n of e){if(v.isVariableDeclaration(n)){t.push(n);continue}v.isExportNamedDeclaration(n)&&n.declaration&&v.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function MS(e,t,n){let r=[],o=0;for(let i of e)if(v.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:Ge(i),editable:!0,source:null})}else if(v.isJSXExpressionContainer(i)&&v.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:Ge(i),editable:!0,source:null});else if(v.isJSXExpressionContainer(i)&&v.isTemplateLiteral(i.expression)){let s=i.expression;s.expressions.length===0&&s.quasis.length===1?r.push({index:o++,value:s.quasis[0].value.cooked??s.quasis[0].value.raw,sourceRange:Ge(i),editable:!0,source:null}):r.push({index:o++,value:Et(s,n),sourceRange:Ge(i),editable:!0,source:$e(s,n,t)})}else if(v.isJSXExpressionContainer(i)&&v.isExpression(i.expression)){let s=Id(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:Ge(i),editable:!0,source:s.source})}return r}function OS(e,t,n){let r=[];for(let[o,i]of e.attributes.entries()){if(!v.isJSXAttribute(i))continue;let s=DS(i.name);if(!s)continue;let a=Et(i,n);if(v.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(v.isJSXExpressionContainer(i.value)&&v.isExpression(i.value.expression)){let c=cn(i.value.expression,t);if(s==="className"){let u=typeof c=="string"?c:c===void 0?Cd(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=Id(i.value.expression,t,n);if(c!==void 0){r.push({name:s,value:JS(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=BS(i.value.expression,t),f=$e(i.value.expression,n,t),m=l?.value??Et(i.value.expression,n);r.push({name:s,value:d.status==="undefined"?"undefined":m,sourceRange:Ge(i),source:l?.source??f,syntaxKind:"expression",raw:a,order:o,resolution:d})}}return r}function LS(e,t,n){return e.attributes.flatMap((r,o)=>!v.isJSXSpreadAttribute(r)||!v.isExpression(r.argument)?[]:[{raw:Et(r.argument,n),sourceRange:Ge(r),order:o,source:$e(r.argument,n,t)}])}function DS(e){return v.isJSXIdentifier(e)?e.name:v.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function BS(e,t){return Mt(e,{resolveIdentifier(n){let r=Or(n,t.valueScopes);return r.kind==="resolved"?{status:"resolved",value:r.value}:n==="undefined"&&!t.valueScopes.some(o=>o.has(n))?{status:"undefined"}:{status:"unresolved"}},resolveMember(n){let r=cn(n,t);return r===void 0?{status:"unresolved"}:{status:"resolved",value:r}}})}function Cd(e,t){let n=nr(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function nr(e,t){if(v.isStringLiteral(e))return[e.value];if(v.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(v.isNullLiteral(e))return[];if(v.isBooleanLiteral(e))return e.value?null:[];if(v.isIdentifier(e)||v.isMemberExpression(e)){if(v.isIdentifier(e)&&e.name==="undefined")return[];let n=cn(e,t);return typeof n=="string"?[n]:null}if(v.isConditionalExpression(e)){let n=nr(e.consequent,t),r=nr(e.alternate,t);return!n||!r?null:[...n,...r]}if(v.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=cn(e.left,t);return n===!1||n===null?[]:nr(e.right,t)}if(v.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||v.isSpreadElement(r))return null;let o=nr(r,t);if(!o)return null;n.push(...o)}return n}if(v.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!v.isObjectProperty(r))return null;let o=$S(r.key);if(!o)return null;n.push(o)}return n}if(v.isCallExpression(e)){let n=jS(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!v.isExpression(o))return null;let i=nr(o,t);if(!i)return null;r.push(...i)}return r}return null}function jS(e){return v.isIdentifier(e)?e.name:v.isMemberExpression(e)&&v.isIdentifier(e.property)?e.property.name:null}function $S(e){return v.isIdentifier(e)?e.name:v.isStringLiteral(e)?e.value:null}function VS(e,t){let n=e.attributes.find(r=>v.isJSXAttribute(r)&&v.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!v.isJSXAttribute(n)||!v.isJSXExpressionContainer(n.value)?null:n.value.expression}function KS(e,t){for(let n of t){let r=VS(e,n);if(r)return r}return null}function US(e){return v.isJSXIdentifier(e.name)?e.name.name:null}function JS(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function XS(e){if(!v.isCallExpression(e)&&!v.isOptionalCallExpression(e))return null;let t=e.callee;return!v.isMemberExpression(t)&&!v.isOptionalMemberExpression(t)||!v.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!v.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function va(e){return v.isArrowFunctionExpression(e)||v.isFunctionExpression(e)}function zS(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function WS(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function Sd(e,t,n,r){if(!e||!v.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:Et(e,n),collectionSource:$e(e,n,r)};if(t){let i=t.params[0],s=t.params[1];v.isIdentifier(i)&&(o.itemParamName=i.name),v.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function Yt(e,t,n){if(!e)return[];if(v.isJSXElement(e)){if(Ca(e))return bi(e.children,t,n);let r=yi(e,t,n);return r?[r]:[]}return rr(e)?xi(e,t,n):v.isParenthesizedExpression(e)?Yt(e.expression,t,n):v.isExpression(e)?Si(e,t,n):[]}function gi(e,t,n){let r=new Map;for(let o of e.params)for(let i of Gt(o))Ra(r,i);t.valueScopes.push(r);try{if(!v.isBlockStatement(e.body))return Yt(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return Rd(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function Rd(e,t,n){let r=[];for(let o of e){if(v.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];if(i){ka([o],t,i);for(let s of o.declarations)v.isIdentifier(s.id)&&(v.isJSXElement(s.init)||v.isJSXFragment(s.init))&&r.push(...Yt(s.init,t,n))}continue}r.push(...Ia(o,t,n))}return r}function Ia(e,t,n){if(v.isReturnStatement(e))return e.argument?Yt(e.argument,t,n):[];if(v.isBlockStatement(e))return Nn(e.body,t,n);if(v.isIfStatement(e)){let r=v.isBlockStatement(e.consequent)?Nn(e.consequent.body,t,n):Ia(e.consequent,t,n),o=e.alternate?v.isBlockStatement(e.alternate)?Nn(e.alternate.body,t,n):Ia(e.alternate,t,n):[];return[...r,...o]}if(v.isSwitchStatement(e))return Nn(e.cases.flatMap(r=>r.consequent),t,n);if(v.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 Rd(e,t,n)}finally{t.valueScopes.pop()}}function hi(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:Ge(r),sourceCandidates:i&&i.length>0?i:void 0})}function HS(e,t,n,r){let o=KS(e.openingElement,["items","dataSource","data"]),i={key:t,tag:Ed(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!v.isJSXAttribute(s))continue;let a=US(s);if(!a||!v.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!v.isJSXEmptyExpression(c)){if(zS(a)&&va(c)){let l=gi(c,n,r),d=Sd(o,c,r,n);hi(n,"repeat-region",t,s,l,d?[d]:void 0);continue}if(WS(a)){let l=va(c)?gi(c,n,r):Yt(c,n,r);hi(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!v.isJSXExpressionContainer(s)||!va(s.expression))continue;let a=gi(s.expression,n,r),c=Sd(o,s.expression,r,n);hi(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function yi(e,t,n){let r=Ed(e.openingElement);if(r==="Fragment"||Ca(e))return bi(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=wS(r),a;if(s){let C=t.ordinalTracker.getOrdinal(i,r);a=`component:${r}#${C}`}else{let C=t.ordinalTracker.getOrdinal(i,r);a=`${r}#${C}`}let c=o?t.elements.get(o.key)?.identity.structuralPath:void 0,l=c?`${c}/${a}`:a,d=Ar(t.file,t.componentName,l),f={file:t.file,component:t.componentName,structuralPath:l,key:d},m=s?"component-boundary":null,u=MS(e.children,t,n),g=OS(e.openingElement,t,n),h=LS(e.openingElement,t,n),b,E,y=!1;if(s){let C=t.importMap.get(r)??t.importMap.get(NS(r));C&&(b=C.specifier,E=C.exportName,y=kn(C.specifier,t.file))}let k={identity:f,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:Ge(e),parentKey:i,childKeys:[],textSegments:u,attributes:g.length>0?g:void 0,attributeSpreads:h.length>0?h:void 0,boundaryKind:m,isOpaque:s,...y?{isPublicUiComponent:!0}:{},importedFrom:b,exportName:E};return t.elements.set(d,k),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}),GS(e.children,t,n),t.parentStack.pop()),d}function xi(e,t,n){return bi(e.children,t,n)}function bi(e,t,n){let r=[];for(let o of e)if(v.isJSXElement(o))if(Ca(o))r.push(...bi(o.children,t,n));else{let i=yi(o,t,n);i&&r.push(i)}else rr(o)?r.push(...xi(o,t,n)):v.isJSXExpressionContainer(o)&&r.push(...Si(o.expression,t,n));return r}function GS(e,t,n){for(let r of e)v.isJSXElement(r)?yi(r,t,n):rr(r)?xi(r,t,n):v.isJSXExpressionContainer(r)&&Si(r.expression,t,n)}function YS(e){return e==="&&"||e==="||"||e==="??"}function Si(e,t,n){if(v.isJSXEmptyExpression(e))return[];let r=XS(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,c={kind:"repeat-template",collectionExpression:Et(r.collection,n),collectionSource:$e(r.collection,n,t)};if(v.isArrowFunctionExpression(a)||v.isFunctionExpression(a)){let d=a.params[0],f=a.params[1];v.isIdentifier(d)&&(c.itemParamName=d.name),v.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),(v.isArrowFunctionExpression(a)||v.isFunctionExpression(a))&&l.childKeys.push(...gi(a,t,n)),l.childKeys}if(v.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:Et(e.test,n),conditionSource:$e(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Ge(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Yt(e.consequent,t,n)),s.childKeys.push(...Yt(e.alternate,t,n)),s.childKeys}if(v.isLogicalExpression(e)&&YS(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:Et(e.left,n),conditionSource:$e(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Ge(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Yt(e.right,t,n)),s.childKeys}if(v.isParenthesizedExpression(e))return Si(e.expression,t,n);if(v.isJSXElement(e)){let o=yi(e,t,n);return o?[o]:[]}return rr(e)?xi(e,t,n):[]}function ZS(e){let t=e.argument;return t&&(v.isExpression(t)||rr(t))?t:null}function Lr(e,t){let n=[];for(let r of e){if(v.isReturnStatement(r)){let o=ZS(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(v.isIfStatement(r)){let o=v.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...Lr(o,r.test)),r.alternate){let i=v.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...Lr(i,r.test))}continue}if(v.isSwitchStatement(r))for(let o of r.cases){let i=o.test?v.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...Lr(o.consequent,i))}}return n}function Ei(e){return{routeId:e,rootKeys:[],elements:new Map,regions:[],fileIndex:new Map,version:1,diagnostics:[]}}function wd(e){let{file:t,source:n,ast:r}=e,o=e.imports.map(m=>m.specifier);if(!v.traverseFast(r,m=>{if(v.isJSXElement(m)||v.isJSXFragment(m))return v.traverseFast.stop}))return{graph:Ei(t),localImports:o};let s=new Map,a=[],c=[],l=new Map,d=TS(r);RS(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(m){let u=PS(m);if(!u)return;let g=m.node,h=[];if(v.isArrowFunctionExpression(g))v.isExpression(g.body)||rr(g.body)?h=[{argument:g.body,statement:v.returnStatement(v.isExpression(g.body)?g.body:null)}]:v.isBlockStatement(g.body)&&(h=Lr(g.body.body));else{let N=g.body;v.isBlockStatement(N)&&(h=Lr(N.body))}if(h.length===0){m.skip();return}let b=new Map;ka(_S(r.program.body),Ea(t,u,s,a,d,[b]),b);let E=new Map;for(let N of g.params)for(let T of Gt(N))Ra(E,T);let y=v.isBlockStatement(g.body)?g.body.body:[],k=h[0]?.statement??null;for(let N of y){if(k&&N===k)break;v.isVariableDeclaration(N)&&ka([N],Ea(t,u,s,a,d,[b,E]),E)}let C=Ea(t,u,s,a,d,[b,E]);for(let N of h){let T=Yt(N.argument,C,n);for(let R of T)c.includes(R)||c.push(R);if(N.condition){let R={kind:"conditional-branch",conditionExpression:Et(N.condition,n),conditionSource:$e(N.condition,n,C)};hi(C,"conditional-region","",N.statement,T,[R])}}m.skip()}});let f=[...s.keys()];return f.length>0&&l.set(t,f),{graph:{routeId:t,rootKeys:c,elements:s,regions:a,fileIndex:l,version:1,diagnostics:[]},localImports:o}}function wa(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function vi(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function QS(e,t){if(e.length===0)return[];if(e.length===1)return[await t(e[0])];let n=new Array(e.length),r=0,o=Array.from({length:Math.min(8,e.length)},async()=>{for(;r<e.length;){let s=r++;n[s]=await t(e[s])}}),i=await Promise.allSettled(o);for(let s of i)if(s.status==="rejected")throw s.reason;return n}async function Nd(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??Jt,c=new Map,l=new Map,d=new Map,f=[],m=new Set,u=E=>{let y=`${E.path}\0${E.code}\0${E.message}\0${JSON.stringify(E.details??{})}`;m.has(y)||(m.add(y),f.push(E))},g=[{file:e,source:t,depth:0,diagnosticEntryFile:e,importStack:[]},...(o.additionalEntries??[]).map(E=>({file:E.file,source:E.source,depth:0,diagnosticEntryFile:E.file,importStack:[]}))],h=new Set;for(;g.length>0;){let E=g.shift(),{file:y,source:k,depth:C,diagnosticEntryFile:N,importStack:T}=E;if(h.has(y))continue;h.add(y),c.set(y,k);let R=o.validationOnly&&C<i?o.validatedImports?.(y,k):void 0,A,M;if(R)A=Ei(y),M=R;else{let L=a(y,k);if(!L.ok){u(vi(L.diagnostic,N,T));continue}d.set(y,L.module);let ee=o.validationOnly&&C<i?{graph:Ei(y),localImports:L.module.imports.map(ge=>ge.specifier)}:wd(L.module);A=ee.graph,M=ee.localImports}for(let L of A.elements.values())if(L.importedFrom&&Pt(L.importedFrom)){let ee=L.importedFrom,ge=await Oo(y,ee,r);ge.ok?(L.importedFrom=ge.path,Xt(ge.path)&&(L.isPublicUiComponent=!0)):kn(ee,y)||u(vi(ge.diagnostic,N,wa(T,y,ee,ge.diagnostic.path)))}if(l.set(y,A),C>=i)continue;let D=await QS(M,async L=>{if(lu(L))return null;let ee=await Oo(y,L,r);if(!ee.ok)return kn(L,y)?null:{diagnostic:vi(ee.diagnostic,N,wa(T,y,L,ee.diagnostic.path))};let ge=ee.path;if(h.has(ge)||Xt(ge))return null;let se=wa(T,y,L,ge);try{let oe=await n(ge);return{entry:{file:ge,source:oe,depth:C+1,diagnosticEntryFile:N,importStack:se}}}catch(oe){return{diagnostic:vi({path:ge,code:"import-read-failed",message:`Failed to read imported file: ${ge}`,details:{fromFile:y,specifier:L,reason:oe instanceof Error?oe.message:String(oe)}},N,se)}}});for(let L of D)L&&"entry"in L?g.push(L.entry):L&&u(L.diagnostic)}let b=qS(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 qS(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}}function Pd(e=256){if(!Number.isSafeInteger(e)||e<1)throw new RangeError("Validated syntax capacity must be positive.");let t=new Map;return{remember(n){for(let r of n)t.get(r.file)?.source!==r.source&&(t.delete(r.file),t.size>=e&&t.delete(t.keys().next().value),t.set(r.file,{source:r.source,imports:Object.freeze(r.imports.map(o=>o.specifier))}))},getImports(n,r){let o=t.get(n);return o?.source===r?o.imports:void 0},clear(){t.clear()}}}import{SiteEditHistoryProvenanceSchema as NE}from"@vcp-dev/contracts";import{createHash as eE,randomUUID as Da}from"node:crypto";import Me from"node:fs/promises";import Le from"node:path";var jd=new WeakMap;function or(e){return jd.get(e)?.()??e.readIndex()}var gt=1,Pa=1,tE=2,nE="index.json",rE="recovery.json",oE="transaction-journal.json",iE="document-version.json",Ci={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},ne={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"},ie=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};function Zt(){return{entries:new Map,blobSizes:new Map}}function ki(e,t){let n={entries:new Map,blobs:new Map,objectBytes:0};for(let r of e)$d(n,r,t);return n}function $d(e,t,n){let r=e.entries.get(t);if(r){e.entries.set(t,{...r,references:r.references+1});return}let o=n.entries.get(t),i=new Map(o.entry.blobs.map(s=>[s.digest,n.blobSizes.get(s.digest)]));e.entries.set(t,{sizeBytes:o.sizeBytes,references:1,blobs:i}),e.objectBytes+=o.sizeBytes;for(let[s,a]of i){let c=e.blobs.get(s);e.blobs.set(s,{sizeBytes:a,references:(c?.references??0)+1}),c||(e.objectBytes+=a)}}function Vd(e,t){let n=e.entries.get(t);if(n.references>1){e.entries.set(t,{...n,references:n.references-1});return}e.entries.delete(t),e.objectBytes-=n.sizeBytes;for(let r of n.blobs.keys()){let o=e.blobs.get(r);o.references>1?e.blobs.set(r,{...o,references:o.references-1}):(e.blobs.delete(r),e.objectBytes-=o.sizeBytes)}}async function Kd(e,t={}){let n=vE(e),r=RE(t.limits),o=Na(n),i=kE(n),s=await tt(i),a=await tt(o)||s;a||(await mE(n),await gE(n)),a||await wE(n);let c=Zt(),l=await wi(n,c),d=new Set(a?(await Fi(n)).map(y=>y.stageId):[]);a||await Md(n,l.entryIds,c);let f=l.digest,m=ki(l.entryIds,c),u=async y=>{let{index:k,sizeBytes:C}=await Vr(n);if(Gd(k,y),k.digest!==f){let N=Zt();await zd(n,k.entryIds,N,C),m=ki(k.entryIds,N),f=k.digest}return{..._i(k),totalBytes:m.objectBytes+C}},g=async y=>{Ba(y),await u(),await Fd(n,m,[y.entryId],y.blobIds,y.stageId),await Ri(n,y.stageId)},h=async(y,k)=>{let C=await u(k);Jd(y,C.entryIds.length);let N=Zt();for(let T of C.entryIds.slice(Math.min(C.cursor,y)+1,Math.max(C.cursor,y)+1))await Br(n,T,N);return C},b=async()=>{if(await tt(o)||s)throw new ie(ne.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")},E={rootDir:n,recoveryRequired:a,async readDocumentVersion(){return Dd(n)},async writeDocumentVersion(y){if(await b(),!Number.isInteger(y)||y<0)throw new ie(ne.INVALID_SCHEMA,"document version must be a non-negative integer");let k=await Dd(n);y<=k||await Dr(qd(n),{schemaVersion:1,version:Math.max(k,y)})},async stageAppend(y,k={}){await b();let C=await cE(y,r),N={schemaVersion:Pa,stageId:Da(),entryId:C.entryId,blobIds:C.blobs.map(T=>T.digest)};try{await lE(n,C),await dE(n,N,k.durableManifest!==!1)}catch(T){try{await g(N)}catch(R){throw new ie(ne.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:R})}throw T}return{stageId:N.stageId,entryId:N.entryId,blobIds:N.blobIds}},async discardStage(y){await b(),Fa(y);let k=await Aa(n,y);k&&await g(k)},async previewStagedAppend(y,k){await b();let C=await u(k);return(await Ad(n,r,y,C,m)).transition},async previewCursor(y,k){await b();let C=await h(y,k);return Ud(C,C.entryIds,y)},async publishStagedAppend(y,k,C){if(await b(),Pi(y,"entryId"),C){Fa(C);let M=await Aa(n,C);if(!M||M.entryId!==y)throw new ie(ne.INVALID_SCHEMA,"history stage does not match the published entry")}let N=await u(k),T=m,R=await Ad(n,r,y,N,T),A=await Ld({rootDir:n,previousDigest:R.current.digest,entryIds:R.entryIds,cursor:R.cursor,readback:async()=>Od(n,R.usage),afterWrite:async()=>{C?await Ri(n,C):await pE(n,y),await Fd(n,R.usage,[...T.entries.keys()].filter(M=>!R.usage.entries.has(M)),[...T.blobs.keys()].filter(M=>!R.usage.blobs.has(M)))}});return m=R.usage,f=A.digest,A},async append(y){await b();let k=await u(),C=await E.stageAppend(y);try{return await E.publishStagedAppend(C.entryId,k.digest,C.stageId)}catch(N){throw await E.discardStage(C.stageId),N}},async readEntry(y){return Pi(y,"entryId"),Br(n,y)},async readBlob(y){Pi(y,"blobId");let k=await tf(n,y),C=await jr(k,ne.NOT_FOUND,"blob");return Qd(C,y,k),C},async readIndex(){let y=Zt(),k=await wi(n,y);return m=ki(k.entryIds,y),f=k.digest,k},async readStatus(){let y=await Ni(n);return{canUndo:y.undoIds.length>0,canRedo:y.redoIds.length>0,undoDepth:y.undoIds.length,redoDepth:y.redoIds.length,cursor:y.cursor,recoveryRequired:await tt(o)||await tt(i)}},async readUndoRedoIds(){let y=await Ni(n);return{undoIds:y.undoIds,redoIds:y.redoIds,currentId:y.currentId}},async setCursor(y,k){await b();let C=await h(y,k),N=await Ld({rootDir:n,previousDigest:C.digest,entryIds:C.entryIds,cursor:y,readback:async()=>Od(n,m)});return f=N.digest,N},async markRecoveryRequired(y){await tt(o)||await Dr(Na(n),{schemaVersion:gt,reason:IE(y),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await Me.rm(Na(n),{force:!0})},async readTransactionJournal(){return await tt(i)?Ii(i):null},async writeTransactionJournal(y){await b(),ef(y);try{await Dr(i,y)}catch(C){let N=await Ii(i).catch(()=>null);if(N&&Buffer.from(nt(N)).equals(Buffer.from(nt(y))))return;throw N?new ie(ne.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:C}):C}let k=await Ii(i);if(!Buffer.from(nt(k)).equals(Buffer.from(nt(y))))throw new ie(ne.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(y){let k=await tt(i)?await Ii(i):null;if(k&&k.transactionId!==y)throw new ie(ne.INVALID_SCHEMA,"transaction journal changed concurrently");try{await Me.rm(i,{force:!0})}catch(C){if(!await tt(i))return;throw C}if(await tt(i))throw new ie(ne.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await b();for(let C of d)await Ri(n,C),d.delete(C);await hE(n);let y=Zt(),k=await wi(n,y);await Md(n,k.entryIds,y),m=ki(k.entryIds,y),f=k.digest}};return jd.set(E,()=>Ni(n)),E}async function Ad(e,t,n,r,o){Pi(n,"entryId");let i=Zt(),s=await Br(e,n,i),a={entries:new Map(o.entries),blobs:new Map(o.blobs),objectBytes:o.objectBytes},c=r.entryIds.slice(0,r.cursor+1);for(let d of r.entryIds.slice(r.cursor+1))Vd(a,d);$d(a,s.id,i),c.push(s.id);let l=uE(c,t,a);return{current:r,entryIds:l.entryIds,cursor:l.cursor,usage:a,transition:Ud(r,l.entryIds,l.cursor)}}function Ud(e,t,n){return Jd(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:sE(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function sE(e,t){return ln(nt({schemaVersion:gt,entryIds:e,cursor:t}))}function Jd(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new ie(ne.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function aE(e){if(!vt(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!at(e.expectedIndexDigest)||!at(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!at(n)?!1:t===-1?n===null:at(n)}async function cE(e,t){if(!e.kind.trim())throw new ie(ne.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new ie(ne.INVALID_JSON,"history blob name must not be empty");let l=EE(c.data),d=ln(l);n.push({name:c.name,bytes:l,digest:d,sizeBytes:l.byteLength}),r.push({name:c.name,digest:d,sizeBytes:l.byteLength})}let o={schemaVersion:gt,kind:e.kind,manifest:e.manifest,blobs:r},i=nt({...o}),s=ln(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new ie(ne.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function lE(e,t){let n=Ka(e,t.entryId),r={id:t.entryId,...t.entryBody},o=[...t.blobs.map(a=>Td(Ua(e,a.digest),a.bytes,{kind:"blob",digest:a.digest},Xa(e,a.digest))),Td(n,nt(r),{kind:"entry",digest:t.entryId},Ja(e,t.entryId))],s=(await Promise.allSettled(o)).find(a=>a.status==="rejected");if(s)throw s.reason}async function Td(e,t,n,r){let o=await Oa(e)??(r?await Oa(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new ie(n.kind==="blob"?ne.BLOB_CORRUPT:ne.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await Yd(e,t)}function uE(e,t,n){let r=[...e],o=r.length-1;for(;;){if(n.objectBytes+nt(Hd(r,o)).byteLength<=t.maxSessionBytes&&r.length<=t.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new ie(ne.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");Vd(n,r.shift()),o-=1}}async function dE(e,t,n){Ba(t);let r=Va(e,t.stageId);if(n){await Dr(r,t);return}await SE(r,t)}async function Aa(e,t){let n=await Oa(Va(e,t));if(n===null)return null;let r=Kr(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=Ba(r);if(o.stageId!==t)throw new ie(ne.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function Fi(e){let t=[];for(let n of await Ti($a(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);Fa(r);let o=await Aa(e,r);o&&t.push(o)}return t}async function Fd(e,t,n,r,o){if(n.length===0&&r.length===0)return;let i=new Set(t.entries.keys()),s=new Set;for(let a of await Fi(e))if(a.stageId!==o){i.add(a.entryId);for(let c of a.blobIds)s.add(c)}for(let a of new Set(n))i.has(a)||await _d(Ka(e,a),Ja(e,a));for(let a of new Set(r))!t.blobs.has(a)&&!s.has(a)&&await _d(Ua(e,a),Xa(e,a));await La(Ur(e)),await La(Jr(e))}async function Ri(e,t){await Ta(Va(e,t)),await fE(e)}async function fE(e){try{await Me.rmdir($a(e))}catch(t){if(Xr(t)||vt(t)&&t.code==="ENOTEMPTY")return;throw t}}async function pE(e,t){for(let n of await Fi(e))n.entryId===t&&await Ri(e,n.stageId)}async function Ta(e){if(await Me.rm(e,{force:!0}),await tt(e))throw new ie(ne.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function _d(e,t){await Ta(e),await Ta(t)}function Ba(e){if(!vt(e)||e.schemaVersion!==Pa||typeof e.stageId!="string"||!Xd(e.stageId)||!at(e.entryId))throw new ie(ne.INVALID_SCHEMA,"history stage schema is invalid");let t=Zd(e.blobIds,"history stage blobIds");return{schemaVersion:Pa,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function Fa(e){if(!Xd(e))throw new ie(ne.INVALID_PATH,"history stageId must be a UUID")}function Xd(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 Md(e,t,n=Zt()){let r=new Set(t),o=new Set;for(let l of t){let d=await Br(e,l,n);for(let f of d.blobs)o.add(f.digest)}for(let l of await Fi(e)){r.add(l.entryId);for(let d of l.blobIds)o.add(d)}let i=Ur(e),s=await Ti(i);for(let l of s){if(!l.endsWith(".json"))continue;let d=Bd(l.slice(0,-5));d&&!r.has(d)&&await Ai(Le.join(i,l))}let a=Jr(e),c=await Ti(a);for(let l of c){let d=Bd(l);d&&!o.has(d)&&await Ai(Le.join(a,l))}}async function wi(e,t=Zt()){let{index:n,sizeBytes:r}=await Vr(e),{totalBytes:o}=await zd(e,n.entryIds,t,r);return{..._i(n),totalBytes:o}}async function Od(e,t){let{index:n,sizeBytes:r}=await Vr(e);return{..._i(n),totalBytes:t.objectBytes+r}}async function Vr(e){let t=ja(e),n=await jr(t,ne.NOT_FOUND,"index"),r=Kr(Buffer.from(n).toString("utf8"),"index");return{index:yE(r),sizeBytes:n.byteLength}}async function Ni(e){return _i((await Vr(e)).index)}function _i(e){let t=[...e.entryIds],n=t.slice(0,e.cursor+1).reverse(),r=t.slice(e.cursor+1);return{schemaVersion:gt,digest:e.digest,entryIds:t,cursor:e.cursor,currentId:t[e.cursor]??null,undoIds:n,redoIds:r}}async function zd(e,t,n,r){let o=0,i=new Set;o+=r??(await Vr(e)).sizeBytes;for(let s of new Set(t)){let a=await Br(e,s,n);o+=n.entries.get(s).sizeBytes;for(let c of a.blobs)i.has(c.digest)||(i.add(c.digest),o+=n.blobSizes.get(c.digest))}return{totalBytes:o}}async function Br(e,t,n=Zt()){let r=n.entries.get(t);if(r)return r.entry;let o=await CE(e,t),i=await jr(o,ne.NOT_FOUND,"entry"),s=Kr(Buffer.from(i).toString("utf8"),`entry ${t}`),a=xE(s);if(a.id!==t)throw new ie(ne.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(ln(nt({schemaVersion:a.schemaVersion,kind:a.kind,manifest:a.manifest,blobs:a.blobs}))!==t)throw new ie(ne.ENTRY_CORRUPT,`entry hash mismatch for ${t}`);for(let l of a.blobs){if(n.blobSizes.has(l.digest))continue;let d=await tf(e,l.digest),f=await jr(d,ne.NOT_FOUND,"blob");Qd(f,l.digest,d),n.blobSizes.set(l.digest,f.byteLength)}return n.entries.set(t,{entry:a,sizeBytes:i.byteLength}),a}async function Wd(e,t,n){await Dr(ja(e),Hd(t,n))}function Hd(e,t){return{schemaVersion:gt,digest:ln(nt({schemaVersion:gt,entryIds:e,cursor:t})),entryIds:e,cursor:t}}function Gd(e,t){if(t!==void 0&&e.digest!==t)throw new ie(ne.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function Ld(e){Gd(await Ni(e.rootDir),e.previousDigest);let t=ln(nt({schemaVersion:gt,entryIds:e.entryIds,cursor:e.cursor}));try{await Wd(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.();let n=await e.readback();if(n.digest!==t)throw new ie(ne.INDEX_CORRUPT,"history index readback did not match the published transition");return n}catch(n){let r=await wi(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new ie(ne.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function mE(e){await Me.mkdir(e,{recursive:!0}),await Me.mkdir(Ur(e),{recursive:!0}),await Me.mkdir(Jr(e),{recursive:!0}),await Me.mkdir($r(e),{recursive:!0})}async function gE(e){await Me.rm($r(e),{recursive:!0,force:!0}),await Me.mkdir($r(e),{recursive:!0})}async function hE(e){let t=$r(e);await Me.mkdir(t,{recursive:!0});for(let n of await Ti(t))n!=="stages"&&await Me.rm(Le.join(t,n),{recursive:!0,force:!0})}function yE(e){if(!vt(e))throw new ie(ne.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==gt)throw new ie(ne.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=Zd(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new ie(ne.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!at(o))throw new ie(ne.INDEX_CORRUPT,"index digest is invalid");let i=ln(nt({schemaVersion:gt,entryIds:t,cursor:r}));if(o!==i)throw new ie(ne.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:gt,digest:o,entryIds:t,cursor:r}}function xE(e){if(!vt(e))throw new ie(ne.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==gt)throw new ie(ne.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!at(t))throw new ie(ne.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new ie(ne.ENTRY_CORRUPT,"entry kind is invalid");let r=Ma(e.manifest,"entry.manifest"),o=bE(e.blobs);return{id:t,schemaVersion:gt,kind:n,manifest:r,blobs:o}}function bE(e){if(!Array.isArray(e))throw new ie(ne.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!vt(t))throw new ie(ne.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new ie(ne.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!at(o))throw new ie(ne.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new ie(ne.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function Dr(e,t){await Yd(e,nt(t))}async function SE(e,t){let n=Le.dirname(e),r=Le.basename(e),o=Le.join(n,`.${r}.${process.pid}.${Da()}.tmp`);await Me.mkdir(n,{recursive:!0});try{await Me.writeFile(o,nt(t),{flag:"wx"}),await Me.rename(o,e)}finally{await Ai(o)}}async function Yd(e,t){let n=Le.dirname(e),r=Le.basename(e),o=Le.join(n,`.${r}.${process.pid}.${Da()}.tmp`);await Me.mkdir(n,{recursive:!0});try{let i=await Me.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await Me.rename(o,e),await La(n)}finally{await Ai(o)}}function nt(e){return Buffer.from(JSON.stringify(_a(e)),"utf8")}function _a(e){if(Array.isArray(e))return e.map(t=>_a(t));if(vt(e)){let t={};for(let n of Object.keys(e).sort())t[n]=_a(e[n]);return t}return e}function Kr(e,t){try{return JSON.parse(e)}catch(n){throw new ie(ne.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function Ma(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=>Ma(n,t));if(vt(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=Ma(o,t);return n}break}throw new ie(ne.INVALID_JSON,`${t} must be JSON-serializable`)}function Zd(e,t){if(!Array.isArray(e))throw new ie(ne.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!at(n))throw new ie(ne.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function Pi(e,t){if(!at(e))throw new ie(ne.INVALID_PATH,`${t} must be a sha256 digest`)}function at(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function ln(e){return`sha256:${eE("sha256").update(e).digest("hex")}`}function EE(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function jr(e,t,n){try{return await Me.readFile(e)}catch(r){throw new ie(t,`${n} not found: ${e}`,{cause:r})}}async function Oa(e){try{return await Me.readFile(e)}catch(t){if(Xr(t))return null;throw t}}function Qd(e,t,n){if(ln(e)!==t)throw new ie(ne.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function tt(e){try{return await Me.access(e),!0}catch(t){if(Xr(t))return!1;throw t}}async function Ai(e){try{await Me.rm(e,{force:!0,recursive:!0})}catch{}}async function La(e){try{let t=await Me.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function Ti(e){try{return await Me.readdir(e)}catch(t){if(Xr(t))return[];throw t}}function vE(e){if(typeof e!="string"||e.trim().length===0)throw new ie(ne.INVALID_ROOT,"history store rootDir must be a non-empty string");return Le.resolve(e)}function ja(e){return Le.join(e,nE)}function Na(e){return Le.join(e,rE)}function kE(e){return Le.join(e,oE)}function qd(e){return Le.join(e,iE)}async function Dd(e){try{let t=await Me.readFile(qd(e),"utf8"),n=Kr(t,"document version");if(!vt(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new ie(ne.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(Xr(t))return 0;throw t}}async function Ii(e){let t=await jr(e,ne.RECOVERY_PENDING,"transaction journal"),n=Kr(Buffer.from(t).toString("utf8"),"transaction journal");return ef(n),n}function ef(e){if(!vt(e)||e.schemaVersion!==tE||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!aE(e.historyTransition)||!Array.isArray(e.files))throw new ie(ne.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!vt(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!at(t.preDigest)||t.postDigest!==null&&!at(t.postDigest))throw new ie(ne.INVALID_SCHEMA,"transaction journal file digest is invalid")}function IE(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function Ur(e){return Le.join(e,"entries")}function Jr(e){return Le.join(e,"blobs")}function $r(e){return Le.join(e,"tmp")}function $a(e){return Le.join($r(e),"stages")}function Va(e,t){return Le.join($a(e),`${t}.json`)}function Ka(e,t){return Le.join(Ur(e),`${rf(t)}.json`)}function Ua(e,t){return Le.join(Jr(e),rf(t))}function Ja(e,t){return Le.join(Ur(e),`${t}.json`)}function Xa(e,t){return Le.join(Jr(e),t)}async function CE(e,t){return nf(Ka(e,t),Ja(e,t))}async function tf(e,t){return nf(Ua(e,t),Xa(e,t))}async function nf(e,t){return await tt(e)?e:await tt(t)?t:e}function rf(e){return e.slice(7)}function Bd(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return at(t)?t:null}function vt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xr(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function RE(e){return{maxEntries:e?.maxEntries??Ci.maxEntries,maxSessionBytes:e?.maxSessionBytes??Ci.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??Ci.maxEntryBytes}}async function wE(e){let t=ja(e);await tt(t)||await Wd(e,[],-1)}var PE={affectedCompositions:[]};function lf(e){let t=null,n=new WeakMap;async function r(){return t??=AE(e),t}async function o(i){if(!i)return null;let s=za(i);return s?TE(e,s):i}return{async prepareAppend(i){let s=await or(e),a=await e.stageAppend(af(i),{durableManifest:!1}),c;try{c=await e.previewStagedAppend(a.entryId,s.digest)}catch(d){throw await e.discardStage(a.stageId),d}let l={kind:"append",entry:i,historyTransition:c};return n.set(l,{expectedDigest:s.digest,stageId:a.stageId,entryId:a.entryId}),l},async prepareUndo(){let i=await r(),s=await o(i.undo.at(-1));if(!s?.historyId)return null;let a=await or(e),c=a.entryIds.indexOf(s.historyId);if(c<0)throw new Error("undo entry is missing from index");if(c!==a.cursor)throw new Error("undo state changed before prepare");let l=c-1,d=await e.previewCursor(l,a.digest),f={kind:"undo",entry:s,historyTransition:d};return n.set(f,{expectedDigest:a.digest,cursor:l}),f},async prepareRedo(){let i=await r(),s=await o(i.redo.at(-1));if(!s?.historyId)return null;let a=await or(e),c=a.entryIds.indexOf(s.historyId);if(c<0)throw new Error("redo entry is missing from index");if(c!==a.cursor+1)throw new Error("redo state changed before prepare");let l=c,d=await e.previewCursor(l,a.digest),f={kind:"redo",entry:s,historyTransition:d};return n.set(f,{expectedDigest:a.digest,cursor:l}),f},async publishPrepared(i){let s=n.get(i);if(!s)throw new Error("history mutation was not prepared");let a=await r();if(i.kind==="append"){if(!s.entryId)throw new Error("staged entry id is missing");let c=await e.publishStagedAppend(s.entryId,s.expectedDigest,s.stageId);of(c,i.historyTransition),i.entry.historyId=s.entryId,Object.assign(a,ir(c))}else{if(s.cursor===void 0)throw new Error("prepared cursor is missing");let c=i.kind==="undo"?a.undo:a.redo;if(za(c.at(-1))!==za(i.entry))throw new Error("history state changed before publish");let l=await e.setCursor(s.cursor,s.expectedDigest);of(l,i.historyTransition),Object.assign(a,ir(l))}n.delete(i)},async discardPrepared(i){let s=n.get(i);if(!s)return;let a=i.historyTransition;if(a){let c=await or(e);if(c.digest===a.publishedIndexDigest&&c.cursor===a.publishedCursor&&c.currentId===a.publishedCurrentId)throw new Error("cannot discard a history mutation whose index was published")}s.stageId&&await e.discardStage(s.stageId),n.delete(i)},async peekUndo(){return o((await r()).undo.at(-1))},async pushUndo(i){let s=await r(),a=i;if(a.historyId){let d=s.entryIds.indexOf(a.historyId);if(d>=0)try{let f=await e.setCursor(d);Object.assign(s,ir(f));return}catch(f){throw s.redo.push(i),f}}let c=await e.append(af(i)),l=c.currentId;if(!l)throw new Error("history store did not publish an entry");i.historyId=l,Object.assign(s,ir(c))},async popUndo(){let i=await r(),s=await o(i.undo.at(-1));return i.undo.pop(),s},async peekRedo(){return o((await r()).redo.at(-1))},async pushRedo(i){let s=await r(),a=i;if(!a.historyId)throw s.undo.push(i),new Error("cannot move an unpersisted history entry to redo");let c=s.entryIds.indexOf(a.historyId);if(c<0)throw s.undo.push(i),new Error("history entry is missing from the durable index");try{let l=await e.setCursor(c-1);Object.assign(s,ir(l))}catch(l){throw s.undo.push(i),l}},async popRedo(){let i=await r(),s=await o(i.redo.at(-1));return i.redo.pop(),s},async clearRedo(){(await r()).redo.length=0},async getStatus(){let i=await e.readStatus();return{canUndo:i.canUndo,canRedo:i.canRedo,undoDepth:i.undoDepth,redoDepth:i.redoDepth,recoveryRequired:i.recoveryRequired}},async markRecoveryRequired(i){await e.markRecoveryRequired(i)}}}function of(e,t){if(!t)throw new Error("durable history transition is missing");if(e.digest!==t.publishedIndexDigest||e.cursor!==t.publishedCursor||e.currentId!==t.publishedCurrentId)throw new Error("durable history published an unexpected index state")}function za(e){return typeof e=="string"?e:e?.historyId}async function AE(e){let t=await or(e);return ir(t)}function ir(e){return{undo:[...e.undoIds].reverse(),redo:[...e.redoIds].reverse(),entryIds:[...e.entryIds],cursor:e.cursor}}async function TE(e,t){let n=await e.readEntry(t),r=FE(n),o=r.provenance??PE;return{historyId:t,...o.initiatingComposition?{composition:o.initiatingComposition}:{},operationId:r.operationId,kind:r.kind,target:r.target,provenance:o,...r.selectionRef?{selectionRef:r.selectionRef}:{},...r.output?{output:r.output}:{},preSnapshots:await sf(e,n,r.preSnapshots),postSnapshots:await sf(e,n,r.postSnapshots)}}async function sf(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(OE(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function af(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=_E(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 FE(e){if(!df(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:uf(t.provenance)}:{},preSnapshots:cf(t.preSnapshots,"preSnapshots"),postSnapshots:cf(t.postSnapshots,"postSnapshots")}}function _E(e){if(e.provenance!==void 0)return uf(e.provenance);if(e.composition)return{initiatingComposition:e.composition,affectedCompositions:[]}}function uf(e){let t=NE.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 cf(e,t){return e.map((n,r)=>{if(!df(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&&!ME(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 ME(e){return/^sha256:[0-9a-f]{64}$/.test(e)}function OE(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function df(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{randomBytes as YE}from"node:crypto";import Oi from"node:path";import{parse as Ef}from"@babel/parser";import ZE from"@babel/traverse";import*as vf from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as Ha,PageResourceArtifactSchema as QE,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as qE,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as ev,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as tv,parseComponentI18nResourcesJson as nv}from"@vcp-dev/contracts";var pf=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,mf=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,LE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,DE=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,BE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,jE=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,$E=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,VE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,KE=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,UE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,JE=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,XE=/\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,zE=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,WE=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function zr(e,t){let n=Mi([...ht(e,LE),...ht(e,DE),...ht(e,BE),...ht(e,t.includeRgbBackgroundImage?jE:$E),...t.includeExtendedColorFunctions?[...ht(e,VE),...ht(e,KE)]:[]]),r=Mi([...ht(e,UE),...ht(e,JE)]).filter(o=>t.colorMixPolicy==="always"||pf.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...ht(e,XE).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...ht(e,WE).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:Mi(ht(e,mf)),hardCodedSurfaceOccurrences:GE(e),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?Mi(ht(e,zE)):[]}}function ht(e,t){return e.match(new RegExp(t.source,t.flags))??[]}var ff=160,HE=/((?:[a-z][a-z0-9-]*(?:\[[^\]]*\])?:)+)$/;function GE(e){let t=new RegExp(mf.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=HE.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>ff?`${u.slice(0,ff-1)}\u2026`:u})}return o}function Mi(e){return[...new Set(e)]}var Ga="{{$INSTANCE}}",rv=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,ov=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,Ya="components/site/generated",iv=/\.(?:tsx?|json)$/,sv=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,av=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],cv=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Wa=ZE,lv=typeof Wa=="function"?Wa:Wa.default;async function Za(e){let t=QE.safeParse(e.artifact);if(!t.success)return Te("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>YE(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=xv(r());if(!i)return Te("Random instance suffix must be 8 lowercase hex chars.");let s=`${bv(n.resource_id)}-${i}`,a=new Map,c=new Map,l=[];for(let k of n.pages){let C=k.final_route.slice(1);a.set(k.template_page_id,k.final_route),c.set(k.template_page_id,k.title),l.push({template_page_id:k.template_page_id,title:k.title,final_route:k.final_route,route_file_path:`app/${C}/page.tsx`})}let d=[],f=new Set,m=new Set,u=new Map,g=new Map,h=[],b=new Set(n.pages.flatMap(k=>k.components.map(C=>C.component_id)));for(let k of n.components){if(!b.has(k.component_id))continue;let C=gf({materialization:k.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c});if(!C.ok)return C;for(let N of C.files){let T=yf(N,f,d);if(T)return T}m.add(C.entry),g.set(C.entry,C.entryExport),u.set(k.component_id,C.entry)}for(let[k,C]of n.pages.entries()){let N=l[k],T=gf({materialization:C.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c,pageEntryTarget:N.route_file_path,pageTitle:N.title});if(!T.ok)return T;for(let R of T.files){let A=yf(R,f,d);if(A)return A}m.add(T.entry),g.set(T.entry,T.entryExport),h.push({entry:T.entry,declaredComponentIds:new Set(C.components.map(R=>R.component_id))})}let E=dv(d,m,s,u,h,g);if(!E.ok)return E;for(let k of d)if(await e.exists(k.file))return!k.file.startsWith("app/")&&o>1?Za({...e,randomHex:r,maxAttempts:o-1}):{ok:!1,code:"MATERIALIZATION_CONFLICT",message:`Page resource create-only target already exists: ${k.file}`,path:k.file};let y=fv(d);return y||(d.sort((k,C)=>k.file.localeCompare(C.file)),{ok:!0,packageInstanceId:s,pages:l,files:d})}function gf(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:hf(o.pathTemplate,e.packageInstanceId);if(!s)return Te("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=uv(o.content,e.packageInstanceId,e.routeByPage,e.titleByPage);if(!a.ok)return a;let c=i&&e.pageTitle!==void 0?mv(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??hf(t,e.packageInstanceId);return!r||!n.some(o=>o.file===r)?Te("Materialization entry must match one controlled source file.",t):{ok:!0,files:n,entry:r,entryExport:e.materialization.entry.export}}function uv(e,t,n,r){let o,i=e.replace(rv,(c,l)=>{let d=n.get(l);return d||(o=l,c)});if(o)return Te(`Page route placeholder references unknown template page: ${o}`);let s=i.replace(ov,(c,l)=>{let d=r.get(l);return d?JSON.stringify(d):(o=l,c)});if(o)return Te(`Page title placeholder references unknown template page: ${o}`);let a=s.replaceAll(Ga,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?Te("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function hf(e,t){let n=`${Ya}/${t}`;if(e.split(Ga).length>2)return null;let o=e.replace(Ga,t),i=`${Ya}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=Oi.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!iv.test(a)||sv.test(a)?null:a}function yf(e,t,n){return t.has(e.file)?Te(`Page resource materializations resolve duplicate target: ${e.file}`,e.file):(t.add(e.file),n.push(e),null)}function dv(e,t,n,r,o,i){let s=new Set(e.map(u=>u.file)),a=`${Ya}/${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 Te("Materialization JSON file must contain valid JSON.",u.file)}if(u.file.endsWith(Ha)&&!nv(u.content).success)return Te("Materialization component i18n resources are invalid.",u.file);continue}try{let h=Ef(u.content,{sourceType:"module",plugins:["jsx","typescript"]});l.set(u.file,h);for(let E of h.program.body)if((E.type==="ImportDeclaration"||E.type==="ExportAllDeclaration"||E.type==="ExportNamedDeclaration"&&E.source)&&E.source){let y=E.source.value,k=hv(u.file,y,s,a);if(!k.allowed)return Te(`Materialization import is outside the controlled package: ${y}`,u.file);k.internalPath&&c.get(u.file).add(k.internalPath)}let b;if(lv(h,{Identifier(E){E.isReferencedIdentifier()&&cv.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 Te(`Materialization source uses forbidden capability: ${b}`,u.file)}catch{return Te("Materialization source must parse as TS/TSX.",u.file)}let g=zr(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 Te("Materialization source violates the public theme token policy.",u.file)}if([...t].some(u=>!s.has(u)))return Te("Materialization entry is outside the controlled package.");for(let u of t)if(u.endsWith(".json"))return Te("Materialization JSON files cannot be package entries.");for(let[u,g]of i){let h=l.get(u);if(!h||!pv(h,g))return Te("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=Sf(u.entry,c);for(let h of u.declaredComponentIds){let b=r.get(h);if(!b||!g.has(b))return Te(`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 Te(`Page entry imports undeclared component: ${b}`,u.entry)}}let f=new Set;for(let u of t)for(let g of Sf(u,c))f.add(g);if(f.size!==e.length)return Te("Every materialization file must be reachable from a package entry.");let m=yv(e,l,c);return m||{ok:!0}}function fv(e){if(e.length>qE)return Te("Page resource exceeds the aggregate source file limit.");let t=0;for(let n of e){let r=Buffer.byteLength(n.content,"utf8");if(r>ev)return Te("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>tv?Te("Page resource exceeds the aggregate content byte limit."):null}function pv(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 mv(e,t,n){let r;try{r=Ef(e,{sourceType:"module",sourceFilename:n,plugins:["jsx","typescript"]})}catch{return Te("Page materialization PAGE_SEO must parse as TS/TSX.",n)}for(let o of r.program.body){let i=o.type==="VariableDeclaration"?o:o.type==="ExportNamedDeclaration"&&o.declaration?.type==="VariableDeclaration"?o.declaration:null;if(i)for(let s of i.declarations){if(s.id.type!=="Identifier"||s.id.name!=="PAGE_SEO")continue;let a=xf(s.init);if(a?.type!=="ObjectExpression")return{ok:!0,data:e};let c=a.properties.find(d=>d.type==="ObjectProperty"&&!d.computed&&gv(d.key));if(!c||c.type!=="ObjectProperty")return{ok:!0,data:e};let l=xf(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 xf(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&vf.isExpression(t)?t:null}function gv(e){return e.type==="Identifier"&&e.name==="title"||e.type==="StringLiteral"&&e.value==="title"}function hv(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=bf(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:av.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=Oi.posix.normalize(Oi.posix.join(Oi.posix.dirname(e),t)),i=bf(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function bf(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 yv(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(Ha))continue;let i=o.file.slice(0,-Ha.length),s=[`${i}.tsx`,`${i}.ts`].find(d=>r.has(d));if(!s)return Te("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 Te("Component i18n resources must have exactly one same-name Client Component static importer.",s)}return null}function Sf(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 xv(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function bv(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"page-resource"}function Te(e,t){return{ok:!1,code:"MATERIALIZATION_REJECTED",message:e,...t?{path:t}:{}}}import{randomBytes as Sv}from"node:crypto";import Qt from"node:path";import{parse as Ev}from"@babel/parser";import vv from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as Li,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as kf,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as kv,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as Iv,SiteEditMaterializationSchema as Cv,parseComponentI18nResourcesJson as Rv}from"@vcp-dev/contracts";var ec="components/site/generated",If="{{$INSTANCE}}",Di=5,wv=/^[a-z][a-z0-9-]{0,48}$/,Nv=/^[a-f0-9]{8}$/,Cf=/\.tsx?$/,Pv=/\.json$/,Av=/\.(?:tsx?|json)$/,Tv=/^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/,Fv=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,_v=["react","react/","next","next/","lucide-react","react-i18next","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],Qa=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),qa=vv,Mv=typeof qa=="function"?qa:qa.default;function Ov(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>kf)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=zv(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=Cv.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=Uv(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${ec}.`,path:e.generatedRoot}};if(!Tf(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=Nf(r.data.files),s=Nf(e.controlledFiles);if(!Wv(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>kf)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>kv)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>Iv?{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 Lv(e){let t=Ov(e);if(!t.ok)return t;let n=Object.keys(e.manifest.projectDependencies??{}),r=new Set(e.availableHostDependencies??[]),o=n.find(d=>!Tv.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??_v,...i],a=t.data.generatedRoot,c=Tf(e.manifest.instanceBaseName),l=Math.max(1,Math.min(Di,e.maxAttempts??Di));for(let d=0;d<l;d+=1){let f=Jv(e.instanceNameGenerator?.()??Sv(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=_f(a,m),g=Dv({manifest:e.manifest,generatedRoot:a,instanceName:m,instanceRoot:u,allowedExternalImports:s});if(!g.ok)return g;if(!await Bv(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 Af(e){let t=Math.max(1,Math.min(Di,e.maxAttempts??Di));for(let n=0;n<t;n+=1){let r=await Lv({...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 Dv(e){let t=[],n=new Set;for(let i of e.manifest.files){let s=Rf({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=Rf({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=jv(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 Bv(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function Rf(e){if(e.pathTemplate.split(If).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(If,e.instanceName),n=Xv(t);return n?_f(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||!Av.test(n)||Fv.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 jv(e,t,n,r,o){let i=new Set(e.map(f=>f.path)),s=new Map,a=new Map(e.map(f=>[f.path,new Set])),c=new Map;for(let f of e){if(Pv.test(f.path)){if(f.path.endsWith(Li)){let g=Rv(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=Ev(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=zr(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(!Cf.test(f.path))continue;let m=s.get(f.path),u=null;if(Mv(m,{ImportDeclaration(g){let h=wf({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(Li))){let b=$v({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=wf({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=Pf(g.node);h&&Qa.has(h)&&(u??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h}.`,file:f.path},g.stop())},OptionalMemberExpression(g){let h=Pf(g.node);h&&Qa.has(h)&&(u??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h}.`,file:f.path},g.stop())},Identifier(g){g.isReferencedIdentifier()&&Qa.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(!Cf.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(!Vv(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 Kv(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:ec,instanceRoot:"",entry:{path:"",export:{kind:"default"}},files:[]}}}function wf(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=Qt.posix.normalize(Qt.posix.join(Qt.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 $v(e){let t=Qt.posix.dirname(e.importer),n=Qt.posix.dirname(e.imported),r=Qt.posix.basename(e.importer).replace(/\.tsx?$/,""),o=Qt.posix.basename(e.imported).slice(0,-Li.length),i=`./${r}${Li}`;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 Vv(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 Kv(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 Uv(e){let t=Ff(e);return t===ec?t:null}function Jv(e){let t=e.trim().toLowerCase();return Nv.test(t)?t:null}function Tf(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 wv.test(t)?t:null}function Ff(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=Qt.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function Xv(e){let t=Ff(e);return!t||t!==e?null:t}function _f(...e){return Qt.posix.join(...e)}function Nf(e){return new Set(e.map(t=>t.pathTemplate))}function zv(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 Wv(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Pf(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 gc}from"node:crypto";import cc from"@babel/traverse";function tc(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 Hv}from"node:crypto";import Mf from"node:path";import*as jf from"@babel/parser";import nc from"@babel/generator";import*as Ue from"@babel/types";var Of=typeof nc=="function"?nc:nc.default;function oc(e){let t=Vf(e);if(t)return{ok:!1,error:t};let n=e.projection,r=ac(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=Zv(n,o),s={jsx:`<${e.component.localName} />`},a=Gv(e);if(i){let u=rc(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??(sc(c,n.container.sourceRange)?n.container.sourceHash:null);if(!c||!l)return Wr("Route page composition does not expose a verifiable container boundary.");let d=Gr(c),f=Df(e.source,d,l,"Route page composition container");if(!f.ok)return f.result;let m=o.anchorSourceRange?Gr(o.anchorSourceRange):void 0;if(m){if(!o.anchorSourceHash)return Wr("Route page composition placement does not expose a verifiable anchor boundary.");let u=Df(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 Gv(e){let t=tk(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 Bi(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=Ir(e.source,"value");if(!t.ok)return An(e.source,t.diagnostic.message);let n=ce(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=sr(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:Of(t.ast,{}).code};let i;try{i=jf.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(Yv(r.node,i,e.action.placement,e.action.replaceOriginal)),{ok:!0,source:Of(t.ast,{}).code})}function Yv(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 ic(e){let t=Vf(e);if(t)return{ok:!1,error:t};let n=e.projection,r=Kf(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(Qv(n,o)){let h=rc(e);return h.ok?e.operation==="remove-node"&&!Lf(n,o.placementUnitKey)?Wr("The last editable page unit cannot be deleted."):e.operation==="move-node"?Wr("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=Gr(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?[]:[Hr(a.diagnostic)]}};if(sr(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=rc(e);return h.ok?Lf(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}}}:Wr("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||!ek(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=ac(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=Gr(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?[]:[Hr(u.diagnostic)]}};if(sr(e.source,u.match.node.start??null,u.match.node.end??null)!==d.containerSourceHash)return Bf("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=Gr(h),y=Ft(e.source,E);return!y.ok||!y.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:y.ok===!1?y.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:y.ok?[]:[Hr(y.diagnostic)]}}:sr(e.source,y.match.node.start??null,y.match.node.end??null)!==b?Bf("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 Lf(e,t){for(let n of e.placementUnitByKey.values())if(n.placementUnitKey!==t&&n.members.length>0)return!0;return!1}function Zv(e,t){let n=e.placementUnitByKey.get(t.placementUnitKey);return n&&e.container.kind!=="jsx-container"&&sc(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 Qv(e,t){return e.container.kind!=="jsx-container"&&sc(t.sourceRange,e.mutationTarget.sourceRange)&&t.sourceHash===e.mutationTarget.sourceHash}function rc(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?[]:[Hr(r.diagnostic)]}}}:sr(e.source,r.match.node.start??null,r.match.node.end??null)!==t.sourceHash?{ok:!1,result:$f("Route mutation target hash no longer matches the current source.")}:{ok:!0,locator:n,sourceHash:t.sourceHash}}function Df(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?[]:[Hr(o.diagnostic)]}}}:sr(e,o.match.node.start??null,o.match.node.end??null)!==n?{ok:!1,result:$f(`${r} hash no longer matches the current source.`)}:{ok:!0}}function $f(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Wr(e){return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:e,diagnostics:[]}}}function Bf(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Hr(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function Vf(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&&!qv(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 qv(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function ek(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function tk(e,t){let n=Mf.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Mf.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Gr(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function sr(e,t,n){return t==null||n==null?null:`sha256:${Hv("sha256").update(e.slice(t,n)).digest("hex")}`}function sc(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 nk=typeof cc=="function"?cc:cc.default;function zf(e){if(!e.ast)return kt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=uk(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=fk(t);if(!n.ok)return kt(e,[n.diagnostic]);let r=n.expression;if(r.isIdentifier()){let o=mk(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(hk(r,t))return kt(e,[Ve("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(r.isNullLiteral())return uc(e,t,"virtual-route-root",r);if(gk(r)){let o=Sk({input:e,source:e.source,expression:r});return lc(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()&&!_e(r)&&!un(r)){let o=pc(r),i=Xf({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[o]});return lc(e,t,i,{kind:"virtual-route-root",sourceKind:"jsx-element"},r)}if(r.isJSXElement()||r.isJSXFragment()){let o=xk(r);if(!o.ok)return kt(e,[o.diagnostic]);let i=ar(o.path);if(i.unsupported)return kt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);if(yk(e.source,r,i.members))return uc(e,t,"starter-placeholder",r);let s=r.isJSXFragment()||_e(r);if(i.members.length===0&&s)return uc(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=Xf({input:e,containerKind:a,sourceKind:c,source:e.source,containerPath:o.path,members:i.members});return lc(e,t,l,{kind:a,sourceKind:c},r)}return kt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")])}function ac(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 Kf(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 Wf(e){return e.ok?rk(e.projection):ok(e.projection)}function rk(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)=>Hf(e,d,h,b,e.container.placementKey)),m=f.filter(({member:h})=>h.isBusinessMember).map(({sourceMember:h})=>sk(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:ik(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function ok(e){let t=e.diagnostics.map(ak);return{status:"unsupported",version:e.version,composition:e.composition,reason:ck(e.diagnostics),diagnostics:t}}function ik(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 Hf(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)=>Hf(e,t,a,c,i))]}function sk(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function ak(e){return{code:lk(e),message:e.message}}function ck(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 lk(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 uk(e){let t=null;return nk(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=dk(o.path);i&&(t=i,n.stop())}}),t}function dk(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 fk(e){let t=e.get("body");if(!t.isBlockStatement()){let s=Zr(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(!pk(s))return{ok:!1,diagnostic:Ve("UNSUPPORTED_PAGE_SHAPE","Route guard return shape is not statically safe",{reason:"guard-shape"})};continue}if(Gf(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=Zr(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 pk(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(Gf(o)||Yf(o))return null;return r}function Gf(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 mk(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=Zr(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 gk(e){return e.isConditionalExpression()?Uf(Zr(e.get("consequent")))&&Uf(Zr(e.get("alternate"))):!1}function Uf(e){return!!(e&&(e.isJSXElement()||e.isJSXFragment()||e.isNullLiteral()))}function Zr(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 hk(e,t){if(e.isIdentifier())return Jf(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return Jf(n.node.name,t)}return!1}function Jf(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 yk(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&fc(t)}function fc(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(!fc(t))return!1;continue}if(t.isJSXElement()&&!fc(t))return!1}return!0}function xk(e){let t=e;if(e.isJSXFragment()||_e(e)){let r=Yr(e),o=r[0];if(r.length===1&&o?.isJSXElement()&&un(o))t=o;else return{ok:!0,path:t}}for(;t.isJSXElement()&&un(t);){let r=Yr(t);if(r.length!==1)return{ok:!0,path:t};let o=r[0];if(!o?.isJSXElement()||!un(o))return{ok:!0,path:t};if(Yr(o).length<=1)return{ok:!0,path:t};t=o}return{ok:!0,path:t}}function Yr(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(...Yr(n));continue}n.isJSXElement()&&(_e(n)?t.push(...Yr(n)):t.push(n))}return t}function ar(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:mc(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=ar(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=un(o)?ar(o):null;n||=i?.unsupported??!1,t.push({...pc(o,i?.members),sourceRange:yt(r.node.loc),parentSourceRange:yt(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:mc(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()&&_e(r)){let o=ar(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=un(r)?ar(r):null;n||=o?.unsupported??!1,t.push({...pc(r,o?.members),parentSourceRange:yt(e.node.loc)})}}return{members:t,unsupported:n}}function pc(e,t){let n=e.isJSXElement()&&un(e)?t??ar(e).members:[],r=e.isJSXElement()&&!un(e)&&!_e(e);return{memberKey:mc(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:yt(e.node.loc),businessMemberCount:r?1:Zf(n),parentSourceRange:yt(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:bk(e)}}function un(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name[0]===t.name[0]?.toLowerCase()}function bk(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 Zf(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function ji(e){return e.length===0?0:Math.max(1,Zf(e))}function Xf(e){let t=yt(e.containerPath.node.loc),n=hc(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:ji(e.members)<=1,memberCount:ji(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function Sk(e){let t=yt(e.expression.node.loc),n=hc(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 Qf(e,t){let n=yt(t.node.loc),r=hc(e.source,t.node.start,t.node.end);return!n||!r?null:{kind:"expression",documentVersion:e.version,sourceRange:n,sourceHash:r}}function lc(e,t,n,r,o){let i=Qf(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=Ek(e,n,s),c=tc(a),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:ep(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 Ek(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:ji(g)<=1,memberCount:ji(g),sourceRange:m,sourceHash:m?dc(e.source,m):null,relation:l,containerSourceRange:h,containerSourceHash:h?dc(e.source,h):null,anchorSourceRange:u,anchorSourceHash:u?dc(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 uc(e,t,n,r){let o=Qf(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=tc([a]),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:ep(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 qf([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function mc(e,t,n){return qf(["member",e,String(t??-1),String(n??-1)])}function qf(e){return`pc_${gc("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function hc(e,t,n){return t==null||n==null?null:`sha256:${gc("sha256").update(e.slice(t,n)).digest("hex")}`}function dc(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:${gc("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 ep(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 _k}from"@vcp-dev/contracts";import d_ from"node:fs";import p_ from"node:path";var kk=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function Qr(e){let t=e.map(r=>Fk(r.path)),n=Ik(t);return n?t.filter(r=>Rk(n,r)).map(r=>({routeId:wk(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function yc(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=Tk(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function Ik(e){return e.some(r=>r.startsWith("app/")&&!Ck(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function Ck(e){return/^(?:src\/)?app\/(?:_vcp|\.vcp)/.test(e)}function Rk(e,t){if(!t.startsWith(`${e}/`))return!1;let n=t.slice(t.lastIndexOf("/")+1);return kk.test(n)?t.slice(e.length+1,-n.length-1).split("/").filter(Boolean).every(r=>!r.startsWith("_")&&!r.startsWith(".")):!1}function wk(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(Pk).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function Nk(e){return e.startsWith("(")&&e.endsWith(")")}function Pk(e){return!e||e.startsWith("@")||e.startsWith("_")||Nk(e)?null:Ak(e)}function Ak(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function Tk(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function Fk(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var qr=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function rt(e,t={}){throw new qr("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Invalid page-template source (${e}): ${t.path??t.routeId??t.templateId??""}`,{reason:e,...t})}function xc(e){return _k.safeParse(e).success||rt("invalid-template-id",{templateId:e}),Buffer.from(e,"utf8").toString("base64url")}function tp(e){/^[A-Za-z0-9_-]{1,255}$/.test(e)||rt("invalid-template-key",{path:e});let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.from(e,"base64url"))}catch{return rt("invalid-template-key",{path:e})}return xc(t)!==e&&rt("noncanonical-template-key",{path:e}),t}function Mk(e){let t=yc(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("(")||Ok(r)&&!np(r)))&&rt("invalid-public-route",{routeId:e}),t}function Ok(e){return e.includes("[")||e.includes("]")}function np(e){return/^\[\[\.\.\.[^\[\]]+\]\]$|^\[[^\[\]]+\]$/.test(e)}function rp(e){return e.some(np)}function op(e,t,n="app"){n!=="app"&&n!=="src/app"&&rt("invalid-app-root");let r=Mk(e),o=xc(t),i=rp(r.slice(1).split("/")),s=i?`${n}/.vcp/page-templates/${o}${r}`:`${n}/.vcp/page-templates${r==="/"?"":r}`,a=i?`${s}/page.tsx`:`${s}/${o}/page.tsx`;return(Buffer.byteLength(a,"utf8")>4095||a.split("/").some(c=>Buffer.byteLength(c,"utf8")>255))&&rt("path-too-long",{path:a}),{appRoot:n,routeRoot:s,templateKey:o,templateEntryFile:a}}function ip(e){return/^(?:src\/)?app\/\.vcp\/page-templates\//.test(e)}function sp(e){let t=Array.isArray(e)?e.map(r=>[r.path,r.content]):[...e],n=new Map;for(let[r,o]of t){let i=r.replace(/\\/g,"/").replace(/^\.\//,"");i.split("/").some(s=>s===".."||s===".")&&rt("invalid-file-path",{path:i}),n.has(i)&&rt("duplicate-file-path",{path:i}),n.set(i,o)}return n}function Vi(e){let t=sp(e.files),n=Qr([...t.keys()].map(i=>({path:i}))),r=new Map;for(let i of n){if(r.has(i.routeId))throw new qr("PAGE_TEMPLATE_ROUTE_AMBIGUOUS",`Multiple canonical entries for ${i.routeId}`,{reason:"duplicate-route-id",routeId:i.routeId,candidates:n.filter(s=>s.routeId===i.routeId).map(s=>s.entryFile)});r.set(i.routeId,i.entryFile)}let o=[];for(let i of t.keys()){if(!ip(i))continue;let s=/^(app|src\/app)\/\.vcp\/page-templates\/(.+)\/page\.tsx$/.exec(i);s||rt("candidate-must-be-single-page",{path:i});let a=s[1],c=s[2].split("/"),l=rp(c),d=l?c[0]:c.pop(),f=l?c.slice(1):c,m=tp(d),u=f.length?`/${f.join("/")}`:"/";op(u,m,a).templateEntryFile!==i&&rt("candidate-path-mismatch",{path:i,routeId:u});let h=r.get(u);(!h||!h.startsWith(`${a}/`))&&rt("canonical-entry-missing",{path:i,routeId:u}),o.push({routeId:u,templateId:m,entryFile:i,canonicalEntryFile:h,appRoot:a})}return o.sort((i,s)=>$i(i.routeId,s.routeId)||$i(i.templateId,s.templateId))}function ap(e){let t=sp(e.files),n=Vi({files:t}),r=Qr([...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)=>$i(o.context.routeId,i.context.routeId)||(o.context.effectiveTemplateId===void 0?-1:i.context.effectiveTemplateId===void 0?1:$i(o.context.effectiveTemplateId,i.context.effectiveTemplateId)))}function Lk(e){let t=yc(e.selector.routeId),n=ap({files:e.files}),r=n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===void 0);(!r||r.entryFile!==e.canonicalEntryFile)&&rt("canonical-entry-mismatch",{routeId:t,path:e.canonicalEntryFile});let o=e.selector.templateId===void 0?r:n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===e.selector.templateId);return o||rt("template-selection-not-found",{routeId:t,templateId:e.selector.templateId}),{...o,mode:e.selector.templateId===void 0?"direct":"candidate",effectiveEntryFile:o.entryFile}}function $i(e,t){return e<t?-1:e>t?1:0}import{HOME_PAGE_URL_PATH as Gk}from"@vcp-dev/contracts";import{parse as mM}from"@babel/parser";import{parse as v_}from"@babel/parser";import{FormBlockIdSchema as I_,FormSpecV1Schema as C_}from"@vcp-dev/contracts";var eo="components/site/generated/forms",R_=`${eo}/vcp-form-runtime.tsx`,Ki="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",w_=new RegExp(`^${eo}/form-(${Ki})\\.spec\\.ts$`),N_=new RegExp(`^${eo}/form-(${Ki})\\.tsx$`),P_=new RegExp(`^@/${eo}/form-(${Ki})$`),A_=new RegExp(`(?:^|/)${eo}/form-(${Ki})(?:\\.tsx?)?$`);var T_=Symbol("invalid-literal");import{createHash as M_}from"node:crypto";import{posix as L_}from"node:path";import{parse as B_}from"@babel/parser";import{FormSpecV1Schema as $_}from"@vcp-dev/contracts";var V_=Symbol("dynamic");import{parse as Dk}from"@babel/parser";function Ui(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.type=="string"):[]}var Bk=/^(?:src\/)?app\/(.*)page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function cp(e){let t=Bk.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 jk(e){let t=e;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function lp(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function $k(e){let t=e;for(;t&&(t.type==="TSAsExpression"||t.type==="TSSatisfiesExpression"||t.type==="ParenthesizedExpression");)t=t.expression??null;return t}function bc(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(bc);if(t?.type==="ObjectExpression"){let n={};for(let r of Ui(t.properties)){if(r.type!=="ObjectProperty"||r.computed)throw new Error("dynamic object property");let o=lp(r.key);if(!o)throw new Error("unsupported object key");n[o]=bc(r.value)}return n}throw new Error(`unsupported static value: ${t?.type??"unknown"}`)}function Sc(e,t){let n=[],r=cp(t);if(r===null)return{found:!1,seo:null,diagnostics:n};let o;try{o=Dk(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 Ui(o.program.body)){let d=l.type==="ExportNamedDeclaration"?l.declaration:l;if(d?.type==="VariableDeclaration")for(let f of Ui(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=$k(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 Ui(s.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let d=lp(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=jk(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=bc(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 Vk}from"@babel/parser";var up=["page","anchor","external","email","phone","group","file"],Kk=["link","cta"],fp=["description","badge","iconKey"],Ec=["label","targetType","href","role","openInNewTab","nofollow","children",...fp],Uk=new Set(Ec);function no(e){return Array.isArray(e)?e:[]}function to(e){let t=e;return t?.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function Jk(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function dp(e){let t=e;return t?.type==="BooleanLiteral"&&typeof t.value=="boolean"?t.value:void 0}function vc(e){let t=[],n;try{n=Vk(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 no(n.program.body)){let s=i.type==="ExportNamedDeclaration"?i.declaration:i;if(s?.type==="VariableDeclaration")for(let a of no(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 no(r.elements).forEach((i,s)=>{let a=pp(i,`NAV_ITEMS[${s}]`,t);a&&o.push(a)}),{items:o,diagnostics:t}}function pp(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 no(e.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let d=Jk(l.key);d&&(r[d]=l.value)}let o=to(r.label),i=to(r.targetType);if(!o)return n.push({severity:"fatal",path:`${t}.label`,message:"label must be a static string"}),null;if(!i||!up.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${up.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 fp){if(r[l]===void 0)continue;let d=to(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))Uk.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 ${Ec.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=[];no(r.children.elements).forEach((d,f)=>{let m=pp(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=to(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=to(r.role);if(c!==void 0&&(Kk.includes(c)?s.role=c:n.push({severity:"warning",path:`${t}.role`,message:"role ignored: not link/cta"})),r.openInNewTab!==void 0){let l=dp(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=dp(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 Xk}from"@babel/parser";function ro(e){return Array.isArray(e)?e:[]}function mp(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function zk(e){let t;try{t=Xk(e,{sourceType:"module",plugins:["typescript","jsx"],tokens:!0})}catch{return{status:"unsupported"}}let n=[];for(let o of ro(t.program.body)){let i=o.type==="ExportNamedDeclaration"?o.declaration:o;if(i?.type==="VariableDeclaration")for(let s of ro(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=mp(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 kc(e,t){let n=gp(t);if(!n)return{status:"unsupported",source:e};let r=zk(e);if(r.status!=="ok")return{status:r.status,source:e};let o=r.array;if(vc(e).diagnostics.some(({severity:l})=>l==="fatal"))return{status:"unsupported",source:e};let s=[],a=l=>{let d=ro(l.elements);for(let[f,m]of d.entries()){if(Hk(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 y=/^\s*,/.exec(e.slice(E));s.push({start:b,end:y?E+y[0].length:E})}continue}let u=Wk(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 Wk(e){if(e.type==="ObjectExpression")for(let t of ro(e.properties)){if(t.type!=="ObjectProperty")continue;let n=t.key;if((n?.name??n?.value)==="children")return mp(t.value)}}function gp(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function Hk(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of ro(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"&&gp(n??"")===t}import{estimateNavLabelWidth as Z_}from"@vcp-dev/contracts";import{parse as eM}from"@babel/parser";var Yk="components/site/generated/",oo=[".tsx",".ts",".jsx",".js"];function hp(e){if(e.expectedUrlPath===Gk)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set(Qr(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 y=Sc(b,E);return y.found&&y.seo?.path===e.expectedUrlPath});if(n.length===0)return{ok:!1,code:"ROUTE_NOT_FOUND",message:"No route uniquely matches the requested page identity."};if(n.length>1)return{ok:!1,code:"ROUTE_AMBIGUOUS",message:"Multiple routes match the requested page identity."};let[r]=n[0],o=new Set([r]);try{let h=Vi({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=Zk(e.files);if(!i.ok)return i.error;let s=i.graph,a=tI(o,s),c=nI(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=kc(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 Zk(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")||!Qk(r))continue;let s=Jt(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(qk(c))continue;let l=bn(r,c),d=eI(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 Qk(e){let t=e.toLowerCase();return oo.some(n=>t.endsWith(n))}function qk(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!oo.some(n=>e.endsWith(n)))}function eI(e,t){let n=e.replace(/\\/g,"/");return(oo.some(o=>n.endsWith(o))?[n]:[...oo.map(o=>`${n}${o}`),...oo.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function tI(e,t){let n=new Set,r=[...e].flatMap(o=>[...t.get(o)??[]]);for(;r.length>0;){let o=r.pop();!o.startsWith(Yk)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function nI(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 ym from"@babel/parser";import*as fe from"@babel/types";import*as ss from"node:path";import*as Ee from"@babel/types";function yp(e){if(e.path.isVariableDeclarator()){let n=e.path.get("init");return n?.isExpression()?{expressionPath:n}:null}if(!e.path.isIdentifier()||!e.path.parentPath?.isVariableDeclarator())return null;let t=e.path.parentPath.get("init");return t?.isExpression()?{expressionPath:t}:null}function Ot(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return Tn(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(Ee.isObjectPattern(n)||Ee.isArrayPattern(n))return Tn(n,e.identifier.name)}if(!e.path.isIdentifier())return!1;let t=e.path.parentPath;for(;t;){if(t.isAssignmentPattern()){let n=t.get("left");if(oI(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function Tn(e,t,n=!1){return Ee.isIdentifier(e)?e.name===t&&n:Ee.isObjectPattern(e)?e.properties.some(r=>Ee.isObjectProperty(r)?Tn(r.value,t,n):Tn(r.argument,t,n)):Ee.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=Ee.isRestElement(r)?r.argument:r;return Tn(o,t,n)}):Ee.isAssignmentPattern(e)?Tn(e.left,t,!0):Ee.isRestElement(e)?Tn(e.argument,t,n):!1}function cr(e,t){if(e.path.isObjectPattern()){if(t){let r=It(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:Ot(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:Ot(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=xp(r),i=!1,s=o?o.initBinding&&Ic(o.initBinding)?(i=Ot(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=cr(o.initBinding,{kind:"identifier",expression:o.initBinding.identifier.name,base:o.initBinding.identifier.name,path:[]});return i=c?.hasDefault??!1,c?[{kind:"property",name:c.propName},...c.remainingPath,...o.initPathPrefix]:null})():null:null,a=It(e.path.node.id,e.identifier.name);if(s&&a){let c=[...s,...a],[l,...d]=c;return!l||l.kind!=="property"?null:{propName:l.name,remainingPath:[...d,...t?.path??[]],hasDefault:i||Ot(e)}}}}let n=aI(e);if(n){let r=rI(n,e);if(r){let[s,...a]=r.path;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:r.hasDefault||Ot(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=iI(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:Ot(e)}}let i=io(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:Ot(e)}:null}if(Ic(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:Ot(e)}}return null}function rI(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=xp(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=Ic(i)?(a=Ot(i),[...s]):(()=>{let d=cr(i,{kind:"identifier",expression:i.identifier.name,base:i.identifier.name,path:[]});return a=d?.hasDefault??!1,d?[{kind:"property",name:d.propName},...d.remainingPath,...s]:null})();if(!c)return null;let l=It(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||Ot(t)}:null}function xp(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=cI(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function Ic(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function oI(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function iI(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 bp(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=Ji(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=io(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=sI(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=io(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 Ji(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=io(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=Ji(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=Ji(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=Ji(r,t);if(o)return o}}return null}function It(e,t,n=[]){if(Ee.isIdentifier(e))return e.name===t?n:null;if(Ee.isObjectPattern(e)){for(let r of e.properties)if(Ee.isObjectProperty(r)){let o=io(r);if(!o)continue;let i=It(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(Ee.isRestElement(r)){let o=It(r.argument,t,n);if(o)return o}}if(Ee.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=Ee.isRestElement(o)?o.argument:o,s=It(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return Ee.isAssignmentPattern(e)?It(e.left,t,n):null}function sI(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function aI(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 io(e){return e.computed?null:Ee.isIdentifier(e.key)?e.key.name:Ee.isStringLiteral(e.key)?e.key.value:null}function cI(e){let t=[],n=e;for(;Ee.isMemberExpression(n);){if(n.computed)if(Ee.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(Ee.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(Ee.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return Ee.isIdentifier(n)?{base:n.name,path:t}:null}import*as Cp from"@babel/parser";import wc from"@babel/traverse";import*as lr from"@babel/types";import*as le from"@babel/types";var Sp=new WeakMap;function Wi(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?Xi(n,t):null}if(e.isMemberExpression()){let n=mI(e.node),r=lI(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?Xi(o,[...r,...t]):null}return e.isAwaitExpression()||Rc(e.node)?dn(hI(e.node),t,"awaited or fetched expression"):null}function lI(e){let t=[],n=e;for(;le.isMemberExpression(n);){if(n.computed)if(le.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(le.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(le.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return le.isIdentifier(n)?t:null}function Xi(e,t=[],n){let r=uI(e,t);if(r)return r;let o=dI(e,t,n);if(o)return o;let i=fI(e,t,n);return i||null}function ao(e){return e?.kind==="api-source"}function uI(e,t){if(e.path.isVariableDeclarator()&&le.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&Cc(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return dn(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&le.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(c=>le.isObjectProperty(c)&&kp(c)==="data"&&so(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&Cc(a.node))return dn(e.identifier.name,t,"query hook data binding")}let n=pI(e);if(!n||kp(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()||!Cc(i.node)?null:dn(e.identifier.name,t,"query hook data binding")}function dI(e,t,n){if(e.path.isVariableDeclarator()&&le.isArrayPattern(e.path.node.id)){let c=e.path.get("init");if(!c?.isCallExpression()||!vp(c.node))return null;let[l,d]=e.path.node.id.elements;return!le.isIdentifier(l)||l.name!==e.identifier.name||!le.isIdentifier(d)?null:Ep(e,d.name,n)?dn(e.identifier.name,t,"state setter is updated by API data"):null}if(!e.path.isIdentifier())return null;let r=e.path.parentPath;if(!r?.isArrayPattern())return null;let o=r.parentPath;if(!o?.isVariableDeclarator())return null;let i=o.get("init");if(!i?.isCallExpression()||!vp(i.node)||r.node.elements.findIndex(c=>c===e.path.node)!==0)return null;let a=r.node.elements[1];return le.isIdentifier(a)&&Ep(e,a.name,n)?dn(e.identifier.name,t,"state setter is updated by API data"):null}function fI(e,t,n){let r=e.path.isVariableDeclarator()?e.path:e.path.findParent(i=>i.isVariableDeclarator());if(!r?.isVariableDeclarator())return null;let o=r.get("init");return o?.isExpression()?o.isAwaitExpression()?dn(e.identifier.name,t,"awaited binding result"):Rc(o.node,n)?dn(e.identifier.name,t,"fetch-backed binding result"):null:null}function pI(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 so(e,t){return le.isIdentifier(e)?e.name===t:le.isAssignmentPattern(e)?so(e.left,t):le.isObjectPattern(e)?e.properties.some(n=>le.isObjectProperty(n)?so(n.value,t):so(n.argument,t)):le.isArrayPattern(e)?e.elements.some(n=>!!n&&so(le.isRestElement(n)?n.argument:n,t)):!1}function Ep(e,t,n){let r=!1,o=!1,i=e.scope.path,s;if(n){let c=Sp.get(n);c||(c=new WeakMap,Sp.set(n,c)),s=c.get(i.node),s||(s=new Map,c.set(i.node,s));let l=s.get(t);if(l!==void 0)return l}i.traverse({CallExpression(c){Rc(c.node)&&(r=!0),(gI(c.node.callee,t)||c.node.arguments.some(l=>le.isIdentifier(l)&&l.name===t))&&(o=!0)}});let a=r&&o;return s?.set(t,a),a}function Cc(e){let t=Hi(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function vp(e){return Hi(e.callee)==="useState"}function Rc(e,t){let n=t?.get(e);if(n!==void 0)return n;let r=zi(e,o=>le.isCallExpression(o)&&Hi(o.callee)==="fetch");return t?.set(e,r),r}function mI(e){let t=e;for(;le.isMemberExpression(t);)t=t.object;return le.isIdentifier(t)?t.name:null}function kp(e){return e.computed?null:le.isIdentifier(e.key)?e.key.name:le.isStringLiteral(e.key)?e.key.value:null}function Hi(e){return le.isIdentifier(e)?e.name:le.isMemberExpression(e)&&le.isIdentifier(e.property)?e.property.name:null}function gI(e,t){return zi(e,n=>le.isIdentifier(n)&&n.name===t)}function zi(e,t){if(t(e))return!0;let n=le.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(le.isNode(i)&&zi(i,t))return!0;continue}if(le.isNode(o)&&zi(o,t))return!0}return!1}function hI(e){return le.isIdentifier(e)?e.name:le.isCallExpression(e)?Hi(e.callee)??"api":le.isAwaitExpression(e)?"awaited-api":"api"}function dn(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:yI(e,t),reason:n}}function yI(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var Rp=typeof wc=="function"?wc:wc.default;function wp(e,t){let n=Pp(e);if(!n)return{allowed:!0};let r=!1;return Rp(n,{CallExpression(o){if(!Ap(o.node,t.sourceRange)||!xI(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||ao(Wi(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function Np(e,t){let n=Pp(e);if(!n)return{allowed:!0};let r=!1;return Rp(n,{JSXExpressionContainer(o){Ap(o.node,t.sourceRange)&&(lr.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 Pp(e){try{return Cp.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function xI(e){let t=e.callee;return lr.isMemberExpression(t)&&lr.isIdentifier(t.property)&&t.property.name==="map"}function Ap(e,t){let n=e.loc;return n?Ip({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&Ip({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function Ip(e,t){return e.line!==t.line?e.line<t.line?-1:1:e.column!==t.column?e.column<t.column?-1:1:0}import*as X from"@babel/types";import*as Tp from"@babel/parser";import Nc from"@babel/traverse";import*as Fe from"@babel/types";import*as ur from"node:path";var Ct=typeof Nc=="function"?Nc:Nc.default;function Je(e){try{return Tp.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Pc(e){return e.computed?Fe.isStringLiteral(e.key)||Fe.isNumericLiteral(e.key)?String(e.key.value):null:bI(e.key)}function bI(e){return Fe.isIdentifier(e)?e.name:Fe.isStringLiteral(e)||Fe.isNumericLiteral(e)?String(e.value):null}function Fn(e){return Fe.isParenthesizedExpression(e)||Fe.isTSAsExpression(e)||Fe.isTSSatisfiesExpression(e)||Fe.isTSNonNullExpression(e)||Fe.isTSTypeAssertion(e)?Fn(e.expression):Fe.isExpression(e)?e:null}function Ac(e){if(Fe.isIdentifier(e))return[e.name];if((Fe.isMemberExpression(e)||Fe.isOptionalMemberExpression(e))&&!e.computed&&Fe.isIdentifier(e.property)){let t=Fn(e.object),n=t?Ac(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(".")?ur.normalize(ur.join(ur.dirname(e),t)).replace(/\\/g,"/"):t}function ct(e,t){return Gi(e)===Gi(t)}function Gi(e){let t=dr(e);return t.endsWith("/index")?t.slice(0,-6):t}function dr(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function Mp(e,t,n){let r=Bp(e,t);if(jp(e,r),$p(e,r))return{ok:!1,reason:"Cannot move prop-backed repeat child because the component is referenced through an unsupported value usage"};let o=[];return Ct(e,{JSXElement(s){Jp(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:Yi(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 Op(e,t){let n=new Map,r=i=>{let s=fr(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 SI(i,n))o=r(s)||o}return[...n.values()]}function SI(e,t){let n=[],r=EI(e,t);for(let o of e.ast.program.body){if(X.isExportDefaultDeclaration(o)&&X.isIdentifier(o.declaration)&&(r.get(o.declaration.name)?.length??0)>0){let i=r.get(o.declaration.name)??[];for(let s of i){if(s.namespace){let a=co(s.namespace,o.declaration.name,"default");a&&n.push({file:e.file,namespace:a,exportName:s.exportName});continue}n.push({file:e.file,exportName:"default"})}continue}if(X.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=_n(e.file,o.source.value);for(let s of o.specifiers){if(X.isExportNamespaceSpecifier(s)){let l=fn(s.exported);for(let d of t.values())ct(d.file,i)&&n.push({file:e.file,namespace:Tc(l,d.namespace),exportName:d.exportName});continue}if(!X.isExportSpecifier(s))continue;let a=fn(s.local),c=[...t.values()].filter(l=>ct(l.file,i)&&Mn(l.namespace,a));if(c.length>0){let l=fn(s.exported);for(let d of c){let f=co(d.namespace,a,l);f&&n.push({file:e.file,namespace:f,exportName:d.exportName})}continue}t.has(fr({file:i,exportName:a}))&&n.push({file:e.file,exportName:fn(s.exported)})}continue}if(X.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!X.isExportSpecifier(i))continue;let s=fn(i.local),a=r.get(s)??[];if(a.length>0){let c=fn(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let d=co(l.namespace,s,c);d&&n.push({file:e.file,namespace:d,exportName:l.exportName})}}}continue}if(X.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=_n(e.file,o.source.value),s=o.exported;if(s){let a=fn(s);for(let c of t.values())ct(c.file,i)&&n.push({file:e.file,namespace:Tc(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())ct(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function Tc(e,t){return t?`${e}.${t}`:e}function Mn(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function co(e,t,n){return!Mn(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function EI(e,t){let n=new Map,r=(i,s)=>{let a=n.get(i)??[];a.push(s),n.set(i,a)};for(let i of e.ast.program.body){if(!X.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=_n(e.file,i.source.value);for(let a of i.specifiers){if(X.isImportDefaultSpecifier(a)){let c=t.get(fr({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(d=>ct(d.file,s)&&Mn(d.namespace,"default"));for(let d of l){let f=co(d.namespace,"default",a.local.name);f&&r(a.local.name,{...d,namespace:f})}continue}if(X.isImportSpecifier(a)){let c=fn(a.imported),l=[...t.values()].filter(f=>ct(f.file,s)&&Mn(f.namespace,c));for(let f of l)r(a.local.name,f);let d=t.get(fr({file:s,exportName:c}));d&&r(a.local.name,d);continue}if(X.isImportNamespaceSpecifier(a))for(let c of t.values())ct(c.file,s)&&r(a.local.name,{...c,namespace:Tc(a.local.name,c.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(X.isVariableDeclaration(i))for(let s of i.declarations){if(!X.isIdentifier(s.id)||!s.init)continue;let a=Fn(s.init);if(!a||!X.isIdentifier(a))continue;let c=n.get(a.name)??[];if(c.length===0)continue;let l=n.get(s.id.name)??[],d=new Set(l.map(fr));for(let f of c){let m=co(f.namespace,a.name,s.id.name),u=m?{...f,namespace:m}:f,g=fr(u);d.has(g)||(r(s.id.name,u),d.add(g),o=!0)}}}return n}function fr(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${Gi(e.file)}#${t}`}function fn(e){return X.isIdentifier(e)?e.name:e.value}function Lp(e,t){for(let n of e.program.body){if(X.isExportDefaultDeclaration(n)){let o=n.declaration;if((X.isFunctionDeclaration(o)||X.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(X.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!X.isExportNamedDeclaration(n))continue;let r=n.declaration;if((X.isFunctionDeclaration(r)||X.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(X.isVariableDeclaration(r)){for(let o of r.declarations)if(X.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!X.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:X.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function _c(e){let t=vI(e),n=[],r=$p(e.ast,t);return Ct(e.ast,{JSXElement(o){ct(e.file,e.sourceFile)&&Yi(o)===e.sourceComponent||Jp(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function Dp(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function Bp(e,t){let n=Dp();return Ct(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function vI(e){let t=Dp();return ct(e.file,e.sourceFile)&&kI(t,Bp(e.ast,e.sourceComponent)),Ct(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=_n(e.file,o),s=e.componentIdentities.filter(a=>ct(a.file,i));if(s.length!==0)for(let a of r.specifiers){let c=n.scope.getBinding(a.local.name);if(c){if(X.isImportDefaultSpecifier(a)&&s.some(l=>l.exportName==="default")&&t.localBindings.add(c),X.isImportDefaultSpecifier(a)){let l=s.filter(d=>Mn(d.namespace,"default"));if(l.length>0){let d=t.namespaceMembers.get(c)??new Set;for(let f of l){let m=_p(f,"default");m&&d.add(m)}t.namespaceMembers.set(c,d)}continue}if(X.isImportSpecifier(a)){let l=X.isIdentifier(a.imported)?a.imported.name:a.imported.value,d=s.filter(f=>Mn(f.namespace,l));if(d.length>0){let f=t.namespaceMembers.get(c)??new Set;for(let m of d){let u=_p(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(X.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)}}}}}),jp(e.ast,t),t}function kI(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 jp(e,t){Ct(e,{VariableDeclarator(n){if(!n.node.init)return;let r=Fn(n.node.init);if(r){if(X.isIdentifier(n.node.id)){let o=On(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&Fc(t,i,o);return}if(X.isObjectPattern(n.node.id)){let o=On(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&Up(n.node.id,o.namespaceMembers,t,n)}}}})}function $p(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return Ct(e,{ReferencedIdentifier(r){if(n){r.stop();return}II(r)||!r.isIdentifier()||!Vp(r,t)||CI(r,t)||RI(r)||(n=!0,r.stop())}}),n}function II(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 Vp(e,t){let n=e.scope.getBinding(e.node.name);if(!n)return null;let r=e;for(;r.parentPath?.isMemberExpression()&&r.parentPath.node.object===r.node&&!r.parentPath.node.computed;)r=r.parentPath;return t.localBindings.has(n)||t.namespaceMembers.has(n)&&On(r.node,t,r)?r:null}function CI(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!Fp(e,r))return!1;let o=Vp(e,t);if(!o)return!1;if(Fn(r.node)===o.node)return!!On(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&Fp(e,a)&&!!On(a.node,t,a)}function RI(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function Fp(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function On(e,t,n){let r=Fn(e);if(!r)return null;if(X.isIdentifier(r)){let a=n.scope.getBinding(r.name);if(!a)return null;let c=t.namespaceMembers.get(a);return t.localBindings.has(a)?{local:!0,namespaceMembers:new Set,unsupported:!1}:c?{local:!1,namespaceMembers:new Set(c),unsupported:!1}:null}if(X.isObjectExpression(r))return wI(r,t,n);let o=Ac(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?Kp(s,o.slice(1).join(".")):null}function wI(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!X.isObjectProperty(i))continue;let s=Pc(i);if(!s||!X.isExpression(i.value)){X.isExpression(i.value)&&(o||=On(i.value,t,n)!==null);continue}let a=On(i.value,t,n);if(a){o||=a.unsupported,a.local&&r.add(s);for(let c of a.namespaceMembers)r.add(`${s}.${c}`)}}return r.size>0||o?{local:!1,namespaceMembers:r,unsupported:o}:null}function Kp(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 Fc(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 Up(e,t,n,r){for(let o of e.properties){if(X.isRestElement(o)){if(X.isIdentifier(o.argument)){let c=r.scope.getBinding(o.argument.name);c&&Fc(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!X.isObjectProperty(o))continue;let i=Pc(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=Kp(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=X.isAssignmentPattern(o.value)?o.value.left:o.value;if(X.isIdentifier(a)){let c=r.scope.getBinding(a.name);c&&Fc(n,c,s);continue}if(X.isObjectPattern(a)&&s.namespaceMembers.size>0){Up(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function _p(e,t){if(!Mn(e.namespace,t))return null;if(e.namespace===t)return e.exportName;let n=e.namespace?.slice(t.length+1);return n?`${n}.${e.exportName}`:e.exportName}function Jp(e,t){let n=e.node.openingElement.name;if(X.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=Xp(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 Xp(e){if(X.isJSXIdentifier(e))return[e.name];if(X.isJSXMemberExpression(e)){let t=Xp(e.object);return t?[...t,e.property.name]:null}return null}function Yi(e){let t=e.getFunctionParent();if(!t)return null;if(t.isFunctionDeclaration())return t.node.id?.name??null;if(t.isArrowFunctionExpression()||t.isFunctionExpression()){let n=t.parentPath;if(n?.isVariableDeclarator()&&X.isIdentifier(n.node.id))return n.node.id.name}return null}function zp(e,t){let n=Je(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=_c({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 be(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 xe(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function Lt(e,t){let n=xe(e);return!!(n&<(t,n))}function lt(e,t){return t.start>=e.start&&t.end<=e.end}function bt(e,t){let n=ce(e,be(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:Zi(e,t)}function pr(e,t){let n=xe(t);return n?e.slice(n.start,n.end):""}function Wp(e,t){return e.start===t.start&&e.end===t.end}function Zi(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 Qi(e,t){return Mc(e,t).length>0}function qi(e,t){let n=xe(e.node),r=xe(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()&&!NI(o,n,r)))return!0;o=o.parentPath}return!1}function NI(e,t,n){let r=xe(e.node.consequent);if(r&<(r,t)&&!lt(r,n))return!1;let o=e.node.alternate?xe(e.node.alternate):null;return!(o&<(o,t)&&!lt(o,n))}function Mc(e,t){let n=xe(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=xe(o.node.consequent),a=xe(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()&&Oc(o.node.operator)){let s=xe(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 Oc(e){return e==="&&"||e==="||"||e==="??"}function Hp(e,t){let n=xe(e.consequent);if(n&<(n,t))return n;let r=xe(e.alternate);return r&<(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=>dr(a.file)));if(!t.has(dr(e.sourceFile))||!t.has(dr(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(dr(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=Lp(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=Op(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=_c({ast:a.ast,file:a.file,sourceFile:e.sourceFile,sourceComponent:e.sourceComponent,componentIdentities:o});if(c.hasUnsafeReference)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component because the component has unsupported value usages"};i.push(...c.callSites)}if(i.length!==1)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without a single project-wide component call site"};let[s]=i;return!ct(s.file,e.targetFile)||Yi(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 MI}from"@vcp-dev/contracts";function es(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 lo();let a=s.target,c=a.locator;if(a.sourceKind==="repeat-template"){let l=o?.instanceIndex;if(l===void 0)return lo();let d=PI(a,l,o?.instanceCount);if(!d)return lo();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"?lo():{ok:!0,target:{kind:"jsx-attribute"}}}function lo(){return{ok:!1,code:"unsupported-binding",reason:"Property does not have a safe typed binding write target for this scope and operation"}}function PI(e,t,n){if(!e.locator||!Number.isInteger(t)||t<0)return null;let r=e.collectionPathMap?.length??e.collectionIndexMap?.length;if(r!==void 0&&(t>=r||n!==void 0&&n!==r))return null;let o=e.collectionPathMap?.[t];if(o)return{...e.locator,path:o};let i=e.locator.path??[],s=i.findLastIndex(c=>c.kind==="index");if(s<0)return null;let a=i.map((c,l)=>l===s&&c.kind==="index"?{kind:"index",index:e.collectionIndexMap?.[t]??t}:c);return{...e.locator,path:a}}import*as Dt from"@babel/types";import{SiteEditSetPropsParamsSchema as AI}from"@vcp-dev/contracts";function Yp(e){let t=e.changes??(e.change?[e.change]:[]);if(!AI.safeParse({kind:"set-props",scope:"selection",changes:t}).success)return uo("invalid-change","Repeat property changes are invalid");if(t.length!==1||t[0].name!==e.target.propertyName)return uo("target-mismatch","A repeat property plan must contain exactly one change for its target property");let r=t[0];if(r.operation==="remove"&&e.target.propertyState==="missing")return{ok:!0,steps:[]};let o=we(e.source,"value");if(!o.ok)return uo("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=ce(o.ast,a);if(!c.ok||!c.match.path.isObjectExpression())return uo("unsupported-object",`Repeat item ${s} is not a writable object expression`);let l=s===e.target.sourceItemIndex?TI(r):FI(c.match.path.node,r.name);if(!l)return uo("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 TI(e){return e.operation==="set"?{kind:"value",value:e.value}:{kind:"undefined"}}function FI(e,t){let n=e.properties.filter(i=>Dt.isObjectProperty(i)&&_I(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=Mt(r.value);return o.status==="undefined"?{kind:"undefined"}:o.status!=="resolved"?null:{kind:"value",value:o.value}}function _I(e){return Dt.isIdentifier(e)?e.name:Dt.isStringLiteral(e)?e.value:Dt.isNumericLiteral(e)?String(e.value):null}function uo(e,t){return{ok:!1,errorCode:e,reason:t}}function Zp(e){if(e.change.name!=="className"&&e.change.name!=="class")return fo("unsupported-owner",`No specialized property owner is available for '${e.change.name}'`);let t=e.classNameSource;if(!t||t.filePath!==e.node.file)return fo("owner-source-unavailable","className source details are unavailable for the selected node");if(e.change.name==="class"&&t.sourceKind==="missing")return fo("owner-source-unavailable","The class alias requires an existing className source");if(t.sourceKind==="expression")return fo("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 fo("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 fo(e,t){return{ok:!1,errorCode:e,reason:t}}async function qp(e){let t=MI.safeParse({kind:"set-props",scope:e.scope,changes:e.changes});if(!t.success)return pn("invalid-change","Typed property changes are invalid");if(e.node.importedFrom==="next/link"&&e.node.exportName==="default"){let r=t.data.changes.find(o=>o.name==="href");if(r&&(r.operation==="remove"||typeof r.value!="string"||r.value.trim().length===0))return pn("invalid-change","next/link requires a non-empty href; use the dedicated link-target operation to remove the link")}let n=[];for(let r of t.data.changes){let o=await OI(e,r);if(o){if(!o.ok)return pn("owner-plan-failed",o.reason);Qp(n,o.steps);continue}let i=await e.getPropertyState(e.node.key,r.name,e.selectionRef);if(!i)return pn("missing-property-state",`No authoritative property state is available for '${r.name}'`);if(i.status==="blocked")return pn("readonly-property",i.diagnostic?.message??`Property '${r.name}' is not writable`);if(BI(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=es({state:i,scope:e.scope,operation:r.operation,selectionRef:e.selectionRef,repeatTarget:s});if(!a.ok)return pn(a.code,a.reason);let c=a.target;if(c.kind==="value-binding"&&r.operation==="set"){Lc(n,{type:"update-value",order:n.length,file:c.file,locator:c.locator,value:r.value});continue}if(c.kind==="repeat-property"){let l=Yp({source:e.getFileContent(c.target.sourceFile),target:c.target,changes:[r]});if(!l.ok)return pn("repeat-target-failed",l.reason);Qp(n,l.steps);continue}Lc(n,{type:"set-property-changes",order:n.length,file:e.node.file,locator:LI(e.node),scope:e.scope,changes:[r]})}return n.forEach((r,o)=>{r.order=o}),DI(n)?pn("step-conflict","Property changes resolve to conflicting write steps"):{ok:!0,steps:n}}async function OI(e,t){return t.name!=="className"&&t.name!=="class"?null:Zp({node:e.node,change:t,classNameSource:e.classNameSource})}function LI(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 DI(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 Qp(e,t){for(let n of t)Lc(e,{...n,order:e.length})}function Lc(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 BI(e,t){if(t.operation!=="set"||e.status!=="direct")return!1;let n=e.attribute?.resolution;return n?.status==="resolved"?Dc(n.value,t.value):e.attribute?.source===null&&e.attribute.value===t.value}function Dc(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)=>Dc(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=>Dc(n[i],r[i]))}return!1}function pn(e,t){return{ok:!1,errorCode:e,reason:t}}import*as gr from"@babel/types";import*as G from"@babel/types";function Bc(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=pr(e,d.node),m=r.node.params.map(h=>pr(e,h)),u=xe(i.node),g=xe(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:ts(d.node),callbackPath:r,collectionPath:d}}function po(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function jI(e,t){let n=xe(e.node);return n?$I(t).some(r=>{let o=xe(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function $I(e){let t=e.callbackPath.node.body;return G.isBlockStatement(t)?mn(t.body):gn(t)}function mn(e){let t=[];for(let n of e){if(G.isReturnStatement(n)){n.argument&&t.push(...gn(n.argument));continue}if(G.isBlockStatement(n)){t.push(...mn(n.body));continue}if(G.isIfStatement(n)){let r=G.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...mn(r)),n.alternate){let o=G.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...mn(o))}continue}if(G.isSwitchStatement(n)){for(let r of n.cases)t.push(...mn(r.consequent));continue}G.isTryStatement(n)&&(t.push(...mn(n.block.body)),n.handler&&t.push(...mn(n.handler.body.body)),n.finalizer&&t.push(...mn(n.finalizer.body)))}return t}function gn(e){return G.isJSXElement(e)?VI(e)?em(e.children):[e]:G.isJSXFragment(e)?em(e.children):G.isParenthesizedExpression(e)||G.isTSAsExpression(e)||G.isTSSatisfiesExpression(e)||G.isTSNonNullExpression(e)||G.isTSTypeAssertion(e)?gn(e.expression):G.isConditionalExpression(e)?[...gn(e.consequent),...gn(e.alternate)]:G.isLogicalExpression(e)&&Oc(e.operator)?gn(e.right):[]}function em(e){return e.flatMap(t=>G.isJSXElement(t)||G.isJSXFragment(t)?gn(t):G.isJSXExpressionContainer(t)&&(G.isJSXElement(t.expression)||G.isJSXFragment(t.expression)||G.isConditionalExpression(t.expression)||G.isLogicalExpression(t.expression))?gn(t.expression):[])}function VI(e){let t=e.openingElement.name;return G.isJSXIdentifier(t)?t.name==="Fragment":G.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function tm(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function ts(e){return!(G.isIdentifier(e)||G.isThisExpression(e)||G.isMemberExpression(e)||G.isOptionalMemberExpression(e)||G.isCallExpression(e)||G.isOptionalCallExpression(e))}function nm(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 mr(e,t){let n=Je(e);if(!n)return t.isRepeatItemRoot===!0;let r=ce(n,be(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:Zi(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=Bt(e,o);return i?jI(o,i):t.isRepeatItemRoot===!0}function rm(e,t){let n=Je(e);if(!n)return!1;let r=ce(n,be(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:Zi(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 Ce from"@babel/types";function jc(e){if(Ce.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(Ce.isJSXMemberExpression(e)){let t=e;for(;Ce.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function KI(e,t){let n=xe(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);!a||Lt(a.path.node,n)||hn(a,i,t)||r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=jc(i.node.name);s&&o(s,i)}}),[...r].sort()}function $c(e,t,n){let r=Je(e);if(!r)return{ok:!0};let o=ce(r,be(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=ce(r,be(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};let s=Fr(o.match.path,i.match.path);if(Qi(s,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let a=KI(s,i.match.path);return a.length>0?{ok:!1,bindingNames:a}:{ok:!0}}function im(e){let t=e;for(;Ce.isTSQualifiedName(t);)t=t.left;return Ce.isIdentifier(t)?t.name:null}function mo(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function ns(e){let t=[],n=r=>{if(r){if(Ce.isIdentifier(r)){t.push(r.name);return}if(Ce.isObjectPattern(r)){for(let o of r.properties){if(Ce.isRestElement(o)){n(o.argument);continue}Ce.isObjectProperty(o)&&n(o.value)}return}if(Ce.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(Ce.isAssignmentPattern(r)){n(r.left);return}if(Ce.isRestElement(r)){n(r.argument);return}Ce.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function Vc(e,t){let n=xe(e.node),r=xe(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=om(e),i=om(t);if(!o||!i||!Wp(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=Hp(s.node,n);if(a&&!lt(a,r))return{ok:!1,reason:"Cannot move repeat-backed child out of a component because the component call site is conditionally rendered outside the target scope"}}else if(s.isLogicalExpression()){let a=xe(s.node.right);if(a&<(a,n)&&!lt(a,r))return{ok:!1,reason:"Cannot move repeat-backed child out of a component because the component call site is conditionally rendered outside the target scope"}}else if((s.isArrowFunctionExpression()||s.isFunctionExpression())&&nm(s)){let a=xe(s.node.body)??xe(s.node);if(a&&!lt(a,r))return{ok:!1,reason:"Cannot move repeat-backed child out of a component because the component call site is repeated outside the target scope"}}s=s.parentPath}return{ok:!0}}function om(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?xe(t.node.argument):null;if(t.isArrowFunctionExpression()&&(Ce.isJSXElement(t.node.body)||Ce.isJSXFragment(t.node.body)||Ce.isConditionalExpression(t.node.body)||Ce.isLogicalExpression(t.node.body)))return xe(t.node.body);t=t.parentPath}return null}function hn(e,t,n){return n.scope.getBinding(t)===e}function Kc(e,t,n,r={}){if(!r.preserveConditionalBoundary&&Qi(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=xe(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(c=>ns(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)||hn(d,c,t)||s.add(c)};return e.traverse({ReferencedIdentifier(c){a(c.node.name,c)},JSXOpeningElement(c){let l=jc(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function Uc(e,t,n){let r=xe(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>ns(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return mo(e,s=>{let a=s.scope.getBinding(s.node.name);!a||Lt(a.path.node,r)||o.has(a.path.node)||hn(a,s.node.name,t)||i.add(s.node.name)}),i.size>0?{ok:!1,bindingNames:[...i].sort()}:{ok:!0}}function sm(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>ns(a)).map(a=>e.callbackPath.scope.getBinding(a)?.path.node).filter(Boolean)),r=new Set,o=(a,c)=>{let l=c.scope.getBinding(a);!l||n.has(l.path.node)||hn(l,a,t)||r.add(a)},i=e.callbackPath.get("params"),s=Array.isArray(i)?i:[i];for(let a of s)a.traverse({ReferencedIdentifier(c){o(c.node.name,c)},TSTypeReference(c){let l=c.node.typeName;if(gr.isIdentifier(l))o(l.name,c);else{let d=im(l);d&&o(d,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function Jc(e,t){let n=xe(e.node),r=new Set;return mo(e,o=>{let i=o.scope.getBinding(o.node.name);i&&(n&&Lt(i.path.node,n)||hn(i,o.node.name,t)||r.add(o.node.name))}),r.size>0?{ok:!1,bindingNames:[...r].sort(),reason:"Cannot move repeat-backed child because the repeat collection is not visible at the target"}:{ok:!0}}function am(e){let t=[];for(let n of e.callbackPath.node.params){if(gr.isIdentifier(n)){t.push(n.name);continue}if(gr.isRestElement(n)&&gr.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 cm(e,t){return{...e,callbackParams:t}}function Xc(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function go(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 lm(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 UI(e){return e.target.kind==="node"?e.target.key:null}function JI(e){return"kind"in e}function rs(e){return!JI(e)}function Yc(e,t){let n=ss.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=ss.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function zc(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=Ft(n,be(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function Qc(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 XI(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function zI(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 Wc(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function WI(e){let t=Mp(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=Vc(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=HI({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=xm(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?ts(o):!0}}}function HI(e){let t=xe(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=ZI(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=qI(e.callSitePath,c.propName,e.source);if(!l.ok){o=l.reason;return}let d=GI(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=Jc(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}hn(a,s.node.name,e.targetParentPath)||r.add(s.node.name)};return e.sourceContext.collectionPath.isIdentifier()&&e.sourceContext.collectionPath.isReferencedIdentifier()&&i(e.sourceContext.collectionPath),e.sourceContext.collectionPath.traverse({ReferencedIdentifier(s){s.isIdentifier()&&i(s)}}),o?{ok:!1,reason:o}:r.size>0?{ok:!1,reason:`Cannot move prop-backed repeat child because the collection depends on bindings outside the target scope: ${[...r].sort().join(", ")}`}:n.size===0?{ok:!1,reason:"Cannot move repeat-backed child out of its component without an explicit prop mapping"}:{ok:!0,collectionExpression:eC(e.source,t,[...n.values()])}}function GI(e,t){if(t.length===0)return e;let n=xm(e);if(!n)return null;let r=ts(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=YI(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function YI(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function ZI(e,t,n){let r=QI(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=cr(t,o);if(!i)return null;let s=r?.range??xe(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function QI(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!Lt(n.node,t)||n.node.computed||!fe.isIdentifier(n.node.property))return null;let r=xe(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function qI(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()&&fe.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=pr(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 eC(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 xm(e){try{let n=ym.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=fe.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&fe.isExpression(r)?r:null}catch{return null}}function tC(e){let t=xe(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=um(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let d=um(c,e.targetFile,e.targetFile);(!d||d.moduleFile!==a.moduleFile||!nC(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 mo(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 nC(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 um(e,t,n){let r=rC(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(".")?Yc(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=fe.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 rC(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function dm(e,t,n,r){let o=Mc(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=pr(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=oC(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${sC(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function oC(e,t){return iC(e.node)?t:`(${t})`}function iC(e){return fe.isIdentifier(e)||fe.isThisExpression(e)||fe.isSuper(e)||fe.isMemberExpression(e)||fe.isOptionalMemberExpression(e)||fe.isCallExpression(e)||fe.isOptionalCallExpression(e)||fe.isBooleanLiteral(e)||fe.isNumericLiteral(e)||fe.isStringLiteral(e)||fe.isNullLiteral(e)||fe.isUnaryExpression(e)}function sC(e){return e.trim().startsWith("<")?e:`(${e})`}var aC={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 os(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=aC[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 cC(e,t){for(let n of e.program.body){if(!fe.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>fe.isImportDefaultSpecifier(o));if(r&&fe.isImportDefaultSpecifier(r))return r.local.name}return null}function lC(e,t,n){for(let r of e.program.body){if(!fe.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>fe.isImportSpecifier(i)&&(fe.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&fe.isImportSpecifier(o))return o.local.name}return null}function fm(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 pm(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function uC(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=Qc(e),o=Je(t);if(n.exportName!=="default"){let a=o?lC(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?pm(r,fm(o)):r;return{localName:c,importStep:Hc(e,c)}}if(!o)return{localName:r,importStep:Hc(e,r)};let i=cC(o,n.source);if(i)return{localName:i};let s=pm(r,fm(o));return{localName:s,importStep:Hc(e,s)}}function dC(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??Qc(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 fC(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?pC(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function pC(e){return Object.fromEntries(Object.entries(e).filter(t=>Zc(t[1])))}function Zc(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(Zc):typeof e=="object"?Object.values(e).every(Zc):!1}function Hc(e,t=Qc(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 mm(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 mC(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function hr(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function qc(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function ho(e){let t=e.path??[];for(let n=t.length-1;n>=0;n-=1){let r=t[n];if(r.kind==="index")return{locator:qc(e,t.slice(0,n)),index:r.index}}return null}function Gc(e,t){return e.locator?e.collectionPathMap?.[t]?qc(e.locator,e.collectionPathMap[t]):ho(e.locator)?hC(e.locator,yC(t,e.collectionIndexMap)):null:null}function gC(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:bm(o,t)}function bm(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=bm(r,t);return o===void 0?void 0:{[n.name]:o}}function hC(e,t){let n=e.path??[];for(let r=n.length-1;r>=0;r-=1)if(n[r].kind==="index"){let i=[...n];return i[r]={kind:"index",index:t},qc(e,i)}return null}function yC(e,t){return t?.[e]??e}function gm(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 xC(e,t){return bC(e.root,t.root)&&EC(e.path??[],t.path??[])}function bC(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&&SC(e.sourceRange,t.sourceRange)}}function SC(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function EC(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 is=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:hr(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:hr(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:hr(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:hr(t.kind,t.params.kind)};let r=t;if(!rs(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=mm(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:hr(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:hr(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=UI(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):hm(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 hm(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:be(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?qp({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=Gc(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:be(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=Gc(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:be(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=ce(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!XI(a.match.path))return{ok:!0,value:r};let c=zI(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=Gc(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=ce(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=ho(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=go(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:be(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||zp(n,t)>1)return null;let r=Yc(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(!rs(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=go(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=wp(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=os(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"?uC(n.params.node,this.graph.getFileContent(r.file)):void 0,y=E?.importStep;return y&&h.push({order:b++,file:r.file,type:"add-import",moduleSpecifier:y.moduleSpecifier,imports:y.imports}),h.push({order:b++,file:r.file,type:"insert-child",parentLocator:be(r),node:{jsx:dC(n.params.node,E?.localName)},placement:n.params.position.relation,anchorLocator:i?be(i):void 0}),this.buildPlan(t,n,h,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!rs(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:fC(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(!rs(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=ho(a.locator);if(!c)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let l=gC(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"?gm(0,a.collectionIndexMap):gm(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=go(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 mr(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:")||rm(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&&mr(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(!po(m,u))return null;if(a&&(s==="before"||s==="after")){let h=bt(l,a),b=h?Bt(c,h):null;if(!po(m,b))return null}if(qi(d,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let g=$c(c,r,o);return g.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:be(r),targetParentLocator:be(o),placement:s,anchorLocator:a?be(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&&mr(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(po(m,u))return null;if(u&&!tm(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 k=Bc(c,l,a);if(u&&!po(u,k)||!u&&k)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 k=os(o,{kind:"native-tag",tag:r.tag});if(k)return{ok:!1,errorCode:"unsupported-operation",reason:k}}let g=zc(this.graph,r);if(!g)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(qi(d,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let h=dm(c,d,f,g);for(let k of h.conditionPaths){let C=Uc(k,f,m);if(!C.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${C.bindingNames.join(", ")}`}}let b=Kc(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=sm(m,f);if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its callback parameters depend on bindings outside the target scope: ${E.bindingNames.join(", ")}`};let y=m;if(r.component!==o.component){let k=WI({source:c,ast:l,sourceContext:m,sourceNode:r,targetParent:o,targetParentPath:f});if(!k.ok)return{ok:!1,errorCode:"unsupported-operation",reason:k.reason};y=k.context}else{let k=Jc(m.collectionPath,f);if(!k.ok)return{ok:!1,errorCode:"unsupported-operation",reason:k.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${k.bindingNames.join(", ")}`}}return this.buildPlan(t,n,[{order:0,file:r.file,type:"move-repeat-template-child",locator:be(r),targetParentLocator:be(o),placement:s,anchorLocator:a?be(a):void 0,repeatExpression:Xc(y,h.sourceJsx),selectionContext:Ln(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&mr(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=Vc(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")&&Bc(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 M=os(o,{kind:"native-tag",tag:r.tag});if(M)return{ok:!1,errorCode:"unsupported-operation",reason:M}}let y=zc(this.graph,r);if(!y)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(qi(u,g))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let k=dm(c,u,g,y);for(let M of k.conditionPaths){let D=Uc(M,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 C=Kc(u,g,b,{preserveConditionalBoundary:k.conditionPaths.length>0});if(!C.ok)return{ok:!1,errorCode:"unsupported-operation",reason:C.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${C.bindingNames.join(", ")}`};let N=tC({sourceFile:r.file,targetFile:o.file,sourceContext:b,targetParentPath:g});if(!N.ok)return{ok:!1,errorCode:"unsupported-operation",reason:N.reason};let T=am(b);if(!T.ok)return{ok:!1,errorCode:"unsupported-operation",reason:T.reason};let R=cm(b,T.callbackParams),A=[{order:0,file:r.file,type:"remove-node",locator:be(r),removeWhitespace:!0}];for(let M of N.imports)A.push({order:A.length,file:o.file,type:"add-import",moduleSpecifier:M.moduleSpecifier,imports:M.imports});return A.push({order:A.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:be(o),expression:Xc(R,k.sourceJsx),placement:s,anchorLocator:a?be(a):void 0,selectionContext:Ln(o)}),this.buildPlan(t,n,A,i)}async planMoveNode(t,n,r,o){if(!o.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};if("kind"in n.params.target&&n.params.target.kind==="source-sibling"){let k=n.params.target,C=this.graph.getNode(k.anchorKey);if(!C||r.file!==C.file||r.component!==C.component)return{ok:!1,errorCode:"locator-miss",reason:"Source sibling move requires a sibling in the same component file"};let N=this.graph.getFileVersion(r.file);if(n.documentVersion!==N)return{ok:!1,errorCode:"stale-version",reason:`Document version ${n.documentVersion} is stale or otherwise does not match source sibling file version (current: ${N})`};let T=this.graph.getFileContent(r.file),R=Je(T),A=R?bt(R,r):null,M=R?bt(R,C):null,D=A?.parentPath,L=M?.parentPath;if(!A||!M||!D||!L||D.node!==L.node||!D.isJSXFragment()&&!(D.isJSXElement()&&_e(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:be(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:k.relation,anchorLocator:be(C),selectionContext:Ln(r)}],o):{ok:!1,errorCode:"locator-miss",reason:"Source Fragment has no stable source range"}}let i=mm(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(mC(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 k=n.params.target.relation,C=i.anchorNode&&(k==="before"||k==="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:k,anchorSourceId:C?.kind==="external-entry"?C.sourceId:null,parentKey:"parentKey"in n.params.target?n.params.target.parentKey:null}}],o)}let l=r.file!==s.file,d=n.params.target.relation,f=i.anchorNode,m=this.graph.getTextProvenance?.(r.key,0)??null,u=go(r,c,m);if(u&&!Wc(u)&&!lm(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 k=c,C=await this.graph.getTextWriteTarget(f.key,0);if(k?.kind==="value-binding"&&C?.kind==="value-binding"&&k.locator&&C.locator){let N=ho(k.locator),T=ho(C.locator);if(N&&T&&k.file===C.file&&xC(N.locator,T.locator)){let R=N.index,A=T.index,M=d==="before"?A-(R<A?1:0):A+(R<A?0:1);return this.buildPlan(t,n,[{order:0,file:k.file,type:"move-array-item",locator:N.locator,fromIndex:R,toIndex:M}],o)}}}if(r.isRepeatItemRoot&&mr(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=Wc(u)?u:g;if(h&&Wc(h)){let k=this.planRepeatTemplateInternalMove(t,n,r,s,o,d,f);if(k)return k;let C=this.planRepeatTemplateHoistMove(t,n,r,s,o,d,f);if(C)return C;let N=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,d,f);return N||{ok:!1,errorCode:"unsupported-operation",reason:h}}if(g)return{ok:!1,errorCode:"unsupported-operation",reason:g};let b=await this.getUpstreamBackedDescendantReason(r);if(b)return{ok:!1,errorCode:"unsupported-operation",reason:b};if(r.tag&&r.tag.toLowerCase()===r.tag){let k=os(s,{kind:"native-tag",tag:r.tag});if(k)return{ok:!1,errorCode:"unsupported-operation",reason:k}}if(l)return this.planCrossFileMove(t,n,r,s,o,d,f);let E=$c(this.graph.getFileContent(r.file),r,s);if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:E.reason??`Cannot move node because it depends on bindings outside the target scope: ${E.bindingNames.join(", ")}`};let y=[{order:0,file:r.file,type:"move-node",locator:be(r),targetParentLocator:be(s),placement:d,anchorLocator:f?be(f):void 0,selectionContext:Ln(s)}];return this.buildPlan(t,n,y,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,d=this.graph.getFileContent(r.file),f=zc(this.graph,r)??`<${r.component} />`,m=Np(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:be(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let g=r.tag??r.component,b={moduleSpecifier:Yc(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:be(o),node:{jsx:f},placement:s,anchorLocator:a?be(a):void 0,selectionContext:Ln(o)})}else c.push({order:l++,file:o.file,type:"insert-child",parentLocator:be(o),node:{jsx:f},placement:s,anchorLocator:a?be(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:Ie(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 hm(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 ol from"@babel/generator";import{parse as LC}from"@babel/parser";import*as w from"@babel/types";import*as $t from"@babel/types";import el from"@babel/generator";import*as ve from"@babel/types";var vC=typeof el=="function"?el:el.default,kC=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,IC=/^((?:https?:)?\/\/)[^/@\s]+@/i,CC=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function Em(e,t){let n=jt(e.callee);if(!n)return null;if(n==="fetch")return tl(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(Sm(r))return tl(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(Sm(r))return tl(e.arguments[0],r,t,["ky client contract"])}return null}function tl(e,t,n,r){if(!e||ve.isSpreadElement(e)||ve.isJSXNamespacedName(e))return PC(t,n,r,"missing url argument");let o=yo(e);return{sourceKind:NC(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 yo(e){if(ve.isStringLiteral(e))return as(e.value);if(ve.isTemplateLiteral(e))return as(RC(e));if(ve.isBinaryExpression(e)&&e.operator==="+"){let t=yo(e.left),n=yo(e.right);return!t&&!n?void 0:as(`${t??nl(e.left)}${n??nl(e.right)}`)}if(ve.isMemberExpression(e)){let t=vm(e);if(t)return`env:${t}`}if(!(ve.isCallExpression(e)&&jt(e.callee)==="new URL")){if(ve.isNewExpression(e)&&ve.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!ve.isSpreadElement(t)?yo(t):void 0,o=n&&!ve.isSpreadElement(n)?yo(n):void 0;return o&&r?as(`${o} + ${r}`):r??o}if(ve.isIdentifier(e))return`:${e.name}`}}function RC(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+=nl(r))}return t}function nl(e){if(ve.isIdentifier(e))return`:${e.name}`;if(ve.isMemberExpression(e)){let t=vm(e);if(t)return`env:${t}`}return`:${wC(e)}`}function wC(e){return vC(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function as(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(IC,"$1<redacted>@").replace(CC,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?kC.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function NC(e){return e?e.startsWith("/api/")?"site-api-route":/^(?:https?:)?\/\//.test(e)||e.startsWith("env:")?"external-api":e.startsWith("/")?"site-api-route":"unknown-api":"unknown-api"}function PC(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function Sm(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function vm(e){return!ve.isMemberExpression(e.object)||!ve.isIdentifier(e.object.object,{name:"process"})||!AC(e.object.property,"env")?null:ve.isIdentifier(e.property)?e.property.name:ve.isStringLiteral(e.property)?e.property.value:null}function AC(e,t){return ve.isIdentifier(e)&&e.name===t}function jt(e){if(ve.isIdentifier(e))return e.name;if(ve.isMemberExpression(e)){let t=jt(e.object),n=ve.isIdentifier(e.property)?e.property.name:ve.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var TC=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),FC=new Set(["getConfig","submit"]);function km(e,t){let n=_C(jt(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!TC.has(i))return null;let s=rl(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(!FC.has(i))return null;let s=rl(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=rl(e,0)??MC(e,0,"path")??"/cms/:path",s=OC(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 _C(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 Im(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 Cm(e){let t=jt(e.callee);return typeof t=="string"&&t.startsWith("cms.field.")}function rl(e,t){let n=e.arguments[t];return $t.isStringLiteral(n)?n.value:null}function MC(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 OC(e){return/^\/collections\/([^/]+)(?:\/|$)/.exec(e)?.[1]??null}function Rm(e=4096){if(!Number.isSafeInteger(e)||e<1)throw new RangeError("Re-export relation capacity must be positive.");let t=new Map,n=new Set,r=o=>{let i=t.get(o.fromFile),s=i?.get(o.exportName),a=s?.get(o.targetFile);a?.get(o.maxImportDepth)===o&&(a.delete(o.maxImportDepth),a.size===0&&s.delete(o.targetFile),s.size===0&&i.delete(o.exportName),i.size===0&&t.delete(o.fromFile),n.delete(o))};return{resolve(o,i){let{fromFile:s,exportName:a,targetFile:c,maxImportDepth:l}=o,d=t.get(s)?.get(a)?.get(c)?.get(l);if(d)return d.pending;let f=i();n.size>=e&&r(n.values().next().value);let m={fromFile:s,exportName:a,targetFile:c,maxImportDepth:l,pending:f},u=t.get(s)??new Map,g=u.get(a)??new Map,h=g.get(c)??new Map;return h.set(l,m),g.set(c,h),u.set(a,g),t.set(s,u),n.add(m),f.catch(()=>{r(m)}),f}}}var qO=typeof ol=="function"?ol:ol.default,Om=new WeakMap;function Lm(e){let t=new Map;return Om.set(t,new Map([...e].map(n=>[n.file,n]))),t}var DC={maxFunctionDepth:8,maxImportDepth:6},BC=new Set(["src","href","alt","poster","content","title","aria-label"]),wm=new WeakMap;function jC(e,t,n){let r=wm.get(t.fileCache);r||(r=new WeakMap,wm.set(t.fileCache,r));let o=r.get(e);if(!o){o={imported:[],local:new Map};let d=0;for(let f of e.elements.values()){let m={element:f,order:d++};f.importedFrom&&f.exportName&&o.imported.push(m);let u=o.local.get(f.sourceFile);u||(u=new Map,o.local.set(f.sourceFile,u));let g=u.get(f.tag)??[];g.push(m),u.set(f.tag,g)}r.set(e,o)}let i=o.local.get(t.file)?.get(n)??[],s=o.imported,a=[],c=0,l=0;for(;c<s.length||l<i.length;){let d=s[c],f=i[l];d&&(!f||d.order<f.order)?(a.push(d.element),c++):f&&(!d||f.order<d.order)?(a.push(f.element),l++):(a.push(d.element),c++,l++)}return a}async function Dm(e){if(!e.element.textSegments.some(s=>s.source)&&!(e.element.attributes??[]).some(s=>s.source&&Pm(s,e.element))&&!e.graph.regions.some(s=>s.ownerKey===e.element.identity.key&&(s.kind==="repeat-region"||s.kind==="conditional-region")))return{hasDynamicData:!1,bindings:[]};let t=e.fileCache??new Map,n=cl(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...DC,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:Qm(n,e.element.componentName)};await Bm(e.element.componentName,e.graph,r);let o=[];o.push(...await UC(e.element,e.graph,r),...await JC(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await XC(s,e.element,e.graph,r);a&&o.push(us(a,"text","children"))}for(let s of e.element.attributes??[]){let a=Pm(s,e.element);if(!a)continue;let c=await Km(s.source,e.element,e.graph,r);c&&o.push(us(c,a,s.name))}let i=sR(o).sort(Ym);return{hasDynamicData:i.length>0,bindings:i}}async function Bm(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 jC(t,n,e)){if(l.sourceFile===n.file&&l.tag===e){s.push(l);continue}!l.importedFrom||!l.exportName||l.importedFrom===n.file&&l.exportName!==i||(l.importedFrom===n.file||await $C(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 Vm(l.sourceFile,n);if(!f)continue;let m=fs(f,n,{importDepth:n.importDepth+1});m.paramSources.clear(),m.scopeVariables=Qm(f,l.componentName),await Bm(l.componentName,t,m);let u=await VC(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=Hm(d);f.length===1&&c.set(l,f[0])}KC(o,c,n)}var Nm=new WeakMap;function $C(e,t,n,r){let o=Nm.get(r.fileCache);return o||(o=Rm(),Nm.set(r.fileCache,o)),o.resolve({fromFile:e,exportName:t,targetFile:n,maxImportDepth:r.options.maxImportDepth},()=>jm(e,t,n,r))}async function jm(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 Vm(e,r))?.imports.get(t);if(!s||!Pt(s.source))return!1;let a=await tg(e,s.source,r.exists);return a?a===n?!0:jm(a,s.importedName,n,r,o):!1}async function VC(e,t){let n=new Map,r=t.analysis.jsxElementsByRange.get($m(e.sourceRange));if(r)for(let i of r.openingElement.attributes)!w.isJSXAttribute(i)||!w.isJSXIdentifier(i.name)||!w.isJSXExpressionContainer(i.value)||!w.isExpression(i.value.expression)||n.set(i.name.name,i.value.expression);let o=new Map;for(let[i,s]of n){let a=await je(s,t);a&&o.set(i,a)}return o}function $m(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}async function Vm(e,t){let n=t.fileCache.get(e);if(n)return n;if(!await t.exists(e))return null;let r=await t.readFile(e);return cl(e,r,t.fileCache)}function KC(e,t,n){if(w.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,al(Object.fromEntries(t),n.file));return}if(w.isObjectPattern(e))for(let r of e.properties){if(!w.isObjectProperty(r)||r.computed||!w.isIdentifier(r.key))continue;let o=t.get(r.key.name);if(!o)continue;let i=w.isAssignmentPattern(r.value)?r.value.left:r.value;w.isIdentifier(i)&&n.paramSources.set(i.name,ze(o))}}function Pm(e,t){return e.name==="dangerouslySetInnerHTML"?"richtext":BC.has(e.name)?"attribute":t.importedFrom||/^[A-Z]/.test(t.tag)?"component-prop":null}async function UC(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 ds(i.collectionSource,n);s&&r.push(us(Dn(s),"repeat-region",i.collectionExpression))}return r}async function JC(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 ds(i.conditionSource,n);s&&r.push(us(Dn(s),"conditional-region",i.conditionExpression))}return r}async function XC(e,t,n,r){return Km(e.source,t,n,r)}async function Km(e,t,n,r){let o=await zC(e,t,n,r);return o||ds(e,r)}async function zC(e,t,n,r){if(!e)return null;let o=WC(e.base,t,n);if(!o)return null;let i=await ds(o.collectionSource,r);return i?Eo(i,e.path,!0):null}function WC(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 ds(e,t){if(!e)return null;let n=await Um(e.base,t);return n?Eo(n,e.path,!1):null}async function Um(e,t){let n=t.paramSources.get(e);if(n)return ze(n);if(t.variableCache.has(e))return aR(t.variableCache.get(e)??null);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let r=await HC(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 qm(i,t);if(s){let a=fs(s,t,{importDepth:t.importDepth+1}),c=eg(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 HC(e,t){let n=t.analysis.stateSetters.get(e);if(!n)return null;let r=t.analysis.stateSetterCandidates.get(n)??[];for(let o of r){let i=await je(o,t);if(i)return i}return null}async function je(e,t){if(w.isIdentifier(e))return Um(e.name,t);if(w.isMemberExpression(e)||w.isOptionalMemberExpression(e)){let n=w.isMemberExpression(e)?Im(e,{file:t.file}):null;if(n)return Wm(n);let r=await GC(e,t);if(!r)return null;let o=oR(e);return Eo(r,o,!1)}if(w.isAwaitExpression(e))return w.isExpression(e.argument)?je(e.argument,t):null;if(w.isCallExpression(e))return Jm(e,t);if(w.isObjectExpression(e)){let n=await Xm(e,t);return Object.keys(n).length>0?al(n,t.file):null}if(w.isConditionalExpression(e)){let n=await je(e.consequent,t),r=await je(e.alternate,t);return So(Tm(n,r))}if(w.isLogicalExpression(e)){let n=await je(e.left,t),r=await je(e.right,t);return So(Tm(n,r))}return w.isTSAsExpression(e)||w.isTSSatisfiesExpression(e)||w.isTSNonNullExpression(e)||w.isTypeCastExpression(e)||w.isParenthesizedExpression(e)?je(e.expression,t):null}async function GC(e,t){let n=e;for(;w.isMemberExpression(n)||w.isOptionalMemberExpression(n);)n=n.object;return w.isExpression(n)?je(n,t):null}async function Jm(e,t){let n=km(e,{file:t.file,imports:t.analysis.imports});if(n)return Wm(n);if(Cm(e)){let f=e.arguments[0];if(f&&w.isExpression(f))return So(await je(f,t))}let r=await YC(e,t);if(r)return r;let o=Em(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 qC(e,t);if(i)return i;let s=await eR(e,t);if(s)return s;let a=await tR(e,t);if(a)return a;let c=await nR(e,t);if(c)return c;let l=[];for(let f of e.arguments)if(w.isExpression(f)){let m=await je(f,t);m&&l.push(m)}let d=Hm(l);return d.length===1?So(d[0]):null}async function YC(e,t){let n=jt(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=QC(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(w.isIdentifier(s)){let a=await bo(s.name,t);if(a)return(await Bn(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!w.isObjectExpression(r))return cs(t.file,`${n} without static options`);let o=ZC(r,"queryFn");if(!o)return cs(t.file,`${n} without queryFn`);if(w.isIdentifier(o)){let i=await bo(o.name,t);return i?(await Bn(i.node,[],i.context)).returnSource:cs(t.file,`${n} queryFn unresolved`)}return w.isArrowFunctionExpression(o)||w.isFunctionExpression(o)?(await Bn(o,[],t)).returnSource:w.isCallExpression(o)?Jm(o,t):null}function ZC(e,t){for(let n of e.properties){if(!w.isObjectProperty(n)||!w.isExpression(n.value))continue;if(zm(n)===t)return n.value}return null}function QC(e,t,n){return w.isStringLiteral(e)?{sourceKind:e.value.startsWith("/api/")?"site-api-route":"external-api",sourceType:"api-field",endpointPattern:e.value,confidence:"exact",readonly:!0,evidence:[{file:t,reason:n}]}:null}async function qC(e,t){if(!w.isMemberExpression(e.callee)||!w.isIdentifier(e.callee.property))return null;let n=e.callee.property.name;if(!["map","filter","slice","sort","toSorted"].includes(n))return null;let r=w.isExpression(e.callee.object)?await je(e.callee.object,t):null;if(!r)return null;if(n!=="map")return Dn(r);let o=e.arguments[0];if(w.isIdentifier(o)){let i=await bo(o.name,t);if(!i)return Dn(r);let s=await Bn(i.node,[r],i.context);return{...Dn(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(w.isArrowFunctionExpression(o)||w.isFunctionExpression(o)){let i=await Bn(o,[r],t);return{...Dn(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return Dn(r)}async function eR(e,t){return!w.isMemberExpression(e.callee)||!w.isIdentifier(e.callee.property,{name:"json"})||!w.isExpression(e.callee.object)?null:je(e.callee.object,t)}async function tR(e,t){return!w.isMemberExpression(e.callee)||!w.isIdentifier(e.callee.property,{name:"then"})||!w.isExpression(e.callee.object)?null:So(await je(e.callee.object,t))}async function nR(e,t){if(!w.isIdentifier(e.callee))return null;let n=await bo(e.callee.name,t);if(!n)return null;let r=[];for(let i of e.arguments){if(!w.isExpression(i)){r.push(cs(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 bo(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 qm(r,t);if(!o)return null;let i=fs(o,t,{importDepth:t.importDepth+1}),s=eg(r,o);return s?{node:s,context:i}:bo(r.importedName,i)}async function Bn(e,t,n){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let r=fs(n.analysis,n,{functionDepth:n.functionDepth+1});r.scopeVariables=n.analysis.functionVariables.get(e),e.params.forEach((c,l)=>{let d=t[l];d&&il(c,iR(d),r)});let o=rR(e),i=null,s,a=!1;for(let c of o){if(w.isObjectExpression(c)){s={...s??{},...await Xm(c,r)},i=i??al(s,n.file);continue}let l=await je(c,r);if(l){if(!i){i=l;continue}let d=sl(i,l);if(!d){a=!0,i=null;continue}i=d}}return{returnSource:a?null:i,...s?{objectReturnMap:s}:{}}}function il(e,t,n){if(w.isIdentifier(e)){n.paramSources.set(e.name,ze(t));return}if(w.isAssignmentPattern(e)){il(e.left,t,n);return}if(w.isObjectPattern(e))for(let r of e.properties){if(!w.isObjectProperty(r)||r.computed||!w.isIdentifier(r.key))continue;let o=Eo(t,[{kind:"property",name:r.key.name}],!0),i=w.isAssignmentPattern(r.value)?r.value.left:r.value;il(i,o,n)}}function rR(e){if(w.isArrowFunctionExpression(e)&&w.isExpression(e.body))return[e.body];let t=[],n=e.body;if(!w.isBlockStatement(n))return t;let r=o=>{if(w.isFunction(o)&&o!==e)return;if(w.isReturnStatement(o)){o.argument&&w.isExpression(o.argument)&&t.push(o.argument);return}let i=w.VISITOR_KEYS[o.type];for(let s of i??[]){let a=o[s];if(Array.isArray(a))for(let c of a)w.isNode(c)&&r(c);else w.isNode(a)&&r(a)}};return r(n),t}async function Xm(e,t){let n={};for(let r of e.properties){if(!w.isObjectProperty(r))continue;let o=zm(r);if(!o||!w.isExpression(r.value))continue;let i=await je(r.value,t);i&&(n[o]=i)}return n}function zm(e){return w.isIdentifier(e.key)&&!e.computed?e.key.name:w.isStringLiteral(e.key)?e.key.value:null}function oR(e){let t=[],n=e;for(;w.isMemberExpression(n)||w.isOptionalMemberExpression(n);){let r=n.property;n.computed?w.isStringLiteral(r)?t.unshift({kind:"property",name:r.value}):w.isNumericLiteral(r)&&t.unshift({kind:"index",index:r.value}):w.isIdentifier(r)&&t.unshift({kind:"property",name:r.name}),n=n.object}return w.isIdentifier(n),t}function Eo(e,t,n){if(t.length===0)return ze(e);let r=t[0];if(r?.kind==="property"&&e.fieldMap?.[r.name])return Eo(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=xo(o.valuePath,"data.items[]"),o.cmsFieldRoot=!1,o):i[0]==="fields"?(o.fieldPath=xo(o.fieldPath,i.slice(1).join(".")),o.cmsFieldRoot=!0,o):o.cmsFieldRoot||n||o.fieldMap?(o.fieldPath=xo(o.fieldPath,i.join(".")),o):(o.valuePath=xo(o.valuePath,Am(t)),o)}return o.valuePath=xo(o.valuePath,Am(t)),o}function Am(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function xo(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function Wm(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 iR(e){let t=ze(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&(t.cmsFieldRoot=!1),t}function So(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 Tm(e,t){return e?t?sl(e,t):ze(e):t?ze(t):null}function sl(e,t){if(ls(e)!==ls(t))return null;let n=Zm(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function Hm(e){let t=new Map;for(let n of e){let r=ls(n),o=t.get(r);t.set(r,o?sl(o,n):ze(n))}return[...t.values()]}function ls(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,ls(r)])):void 0;return JSON.stringify({sourceKind:e.sourceKind,sourceType:e.sourceType,endpointPattern:e.endpointPattern,operation:e.operation,collection:e.collection,fieldPath:e.fieldPath,valuePath:e.valuePath,cmsFieldRoot:e.cmsFieldRoot,fieldMap:t})}function al(e,t){let n=Object.values(e)[0];return{sourceKind:n?.sourceKind??"unknown-api",sourceType:n?.sourceType??"api-field",endpointPattern:n?.endpointPattern,operation:n?.operation,collection:n?.collection,confidence:n?.confidence??"partial",readonly:!0,evidence:n?.evidence??[{file:t,reason:"object return map"}],fieldMap:e}}function cs(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function us(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 Gm(e){let t=[...e].sort(Ym),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 sR(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 Ym(e,t){return Fm(e.targetKind)-Fm(t.targetKind)||Zm(e.confidence,t.confidence)||_m(e.sourceKind)-_m(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function Fm(e){return{"repeat-region":0,"conditional-region":1,text:2,richtext:3,attribute:4,"component-prop":5}[e]}function _m(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function Zm(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function cl(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=Om.get(n)?.get(e),i=o?.source===t?o.ast:LC(t,{sourceType:"module",plugins:["jsx","typescript"]}),s={file:e,source:t,ast:i,variables:new Map,functions:new Map,imports:new Map,stateSetters:new Map,stateSetterCandidates:new Map,jsxElementsByRange:new Map,functionVariables:new WeakMap},a=[],c=[];w.traverse(i,{enter(f){switch(w.isFunction(f)&&a.push(f),f.type){case"CallExpression":c.push(f);break;case"JSXElement":{let m=f.loc;if(!m)return;let u=$m({startLine:m.start.line,startColumn:m.start.column,endLine:m.end.line,endColumn:m.end.column});s.jsxElementsByRange.has(u)||s.jsxElementsByRange.set(u,f);break}case"ImportDeclaration":{let m=f.source.value;for(let u of f.specifiers)w.isImportSpecifier(u)&&w.isIdentifier(u.local)?s.imports.set(u.local.name,{source:m,importedName:w.isIdentifier(u.imported)?u.imported.name:u.imported.value,localName:u.local.name,isDefault:!1}):w.isImportDefaultSpecifier(u)&&s.imports.set(u.local.name,{source:m,importedName:"default",localName:u.local.name,isDefault:!0});break}case"FunctionDeclaration":{f.id?.name&&s.functions.set(f.id.name,f);break}case"VariableDeclarator":{let m=a.at(-1),u=m&&(w.isFunctionDeclaration(m)||w.isFunctionExpression(m)||w.isArrowFunctionExpression(m))?m:null,g=u?s.functionVariables.get(u)??new Map:s.variables;u&&!s.functionVariables.has(u)&&s.functionVariables.set(u,g);for(let h of yr(f.id))g.set(h,w.isExpression(f.init)?f.init:null);if(w.isArrayPattern(f.id)&&w.isCallExpression(f.init)&&jt(f.init.callee)==="useState"){let[h,b]=f.id.elements;w.isIdentifier(h)&&w.isIdentifier(b)&&s.stateSetters.set(h.name,b.name)}w.isIdentifier(f.id)&&Mm(f.init)&&s.functions.set(f.id.name,f.init);break}case"ExportNamedDeclaration":{let m=f.declaration,u=f.source?.value;if(u)for(let g of f.specifiers){if(!w.isExportSpecifier(g))continue;let h=w.isIdentifier(g.exported)?g.exported.name:g.exported.value,b=g.local.name;s.imports.set(h,{source:u,importedName:b,localName:h,isDefault:b==="default"})}if(w.isFunctionDeclaration(m)&&m.id?.name&&s.functions.set(m.id.name,m),w.isVariableDeclaration(m))for(let g of m.declarations)w.isIdentifier(g.id)&&Mm(g.init)&&s.functions.set(g.id.name,g.init);break}case"ExportDefaultDeclaration":{let m=f.declaration;if((w.isFunctionDeclaration(m)||w.isFunctionExpression(m)||w.isArrowFunctionExpression(m))&&s.functions.set("default",m),w.isIdentifier(m)){let u=s.functions.get(m.name);u&&s.functions.set("default",u)}break}}},exit(f){w.isFunction(f)&&a.pop()}});let l=new Set(s.stateSetters.values()),d=(f,m)=>{let u=s.stateSetterCandidates.get(f)??[];u.push(m),s.stateSetterCandidates.set(f,u)};if(l.size>0)for(let f of c){let m=w.isIdentifier(f.callee)?f.callee.name:null;m&&l.has(m)&&w.isExpression(f.arguments[0])&&d(m,f.arguments[0]);let u=new Set;for(let g of f.arguments)w.isIdentifier(g)&&g.name!==m&&l.has(g.name)&&u.add(g.name);for(let g of u)d(g,f)}return n.set(e,s),s}function yr(e){return!e||w.isVoidPattern(e)?[]:w.isIdentifier(e)?[e.name]:w.isObjectPattern(e)?e.properties.flatMap(t=>w.isObjectProperty(t)?yr(t.value):yr(t.argument)):w.isArrayPattern(e)?e.elements.flatMap(t=>t?yr(w.isRestElement(t)?t.argument:t):[]):w.isAssignmentPattern(e)?yr(e.left):w.isRestElement(e)?yr(e.argument):[]}function Mm(e){return w.isFunctionExpression(e)||w.isArrowFunctionExpression(e)}function Qm(e,t){let n=e.functions.get(t)??e.functions.get("default");return n?e.functionVariables.get(n):void 0}async function qm(e,t){let n=await tg(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return cl(n,r,t.fileCache)}function eg(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function tg(e,t,n){return Pt(t)?Sn(e,t,n):null}function fs(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 aR(e){return e?ze(e):null}function ze(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,ze(n)]))}:{}}}import*as ul from"@babel/parser";import ll from"@babel/traverse";import*as Y from"@babel/types";import{classifySiteEditPropertyName as cR}from"@vcp-dev/contracts";var dl=typeof ll=="function"?ll:ll.default;function fl(e){let t=cR(e.propertyName);if(t.owner!=="generic")return ut("invalid-property",t.diagnostic?.message??`Property '${e.propertyName}' is not a generic property`);let n=e.selectionRef;if(!n)return ut("missing-selection-ref","A repeat property target requires a complete selection reference");if(n.key!==e.element.identity.key)return ut("selection-mismatch","Selection reference does not identify the requested element");if(n.instanceIndex===void 0)return ut("missing-instance-index","A repeat property target requires an instance index");let r;try{r=ul.parse(e.source,{sourceType:"module",plugins:["typescript","jsx"]})}catch(b){return ut("repeat-not-found",`Unable to parse repeat source: ${b instanceof Error?b.message:String(b)}`)}let o=lR(r,e.element.sourceRange);if(!o)return ut("repeat-not-found","The selected element is not inside a supported map repeat");if(!Y.isIdentifier(o.callback.params[0]))return ut("unsupported-callback","Repeat property materialization requires an identifier callback item");let i=uR(r,o.collection,e.file,e.sources);if(!i)return ut("collection-not-found","The repeat collection is not a visible local static array");let{array:s,locator:a,sourceFile:c}=i,l=[],d=[];for(let[b,E]of s.elements.entries()){if(!E||!Y.isObjectExpression(E)||!ag(E))return ut("unsafe-collection","Repeat materialization requires an array of local static objects without spreads");let y=[{kind:"index",index:b}];l.push(y),d.push({kind:"value",root:a.root,path:y})}let f=d.length;if(n.instanceCount!==void 0&&n.instanceCount!==f)return ut("count-mismatch",`Selection reports ${n.instanceCount} instances but the source collection has ${f}`);let m=n.instanceIndex;if(m>=f)return ut("index-out-of-range",`Selected repeat instance ${m} is outside the source collection`);let u=s.elements[m];if(!u||!Y.isObjectExpression(u))return ut("unsafe-collection","Selected repeat item is not an object");let g=hR(e.element,e.propertyName),h=mR(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:gR(u,e.propertyName),...g?{property:g}:{},selectionRef:n}:ut("unsafe-property-source",`Property '${e.propertyName}' has a dynamic or unsupported source in the repeat item`)}function lR(e,t){let n=[];return dl(e,{CallExpression(r){let o=ng(r.node);o&&og(o.callback,t)&&n.push({...o,span:rg(r.node)})},OptionalCallExpression(r){let o=ng(r.node);o&&og(o.callback,t)&&n.push({...o,span:rg(r.node)})}}),n.sort((r,o)=>r.span-o.span),n[0]??null}function ng(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 uR(e,t,n,r){let o=vo(t);if(o&&Y.isArrayExpression(o))return{array:o,locator:{kind:"value",root:{kind:"expression",sourceRange:lg(o)}},sourceFile:n};if(!Y.isIdentifier(t))return null;let i=[];if(dl(e,{VariableDeclarator(s){Y.isIdentifier(s.node.id)&&s.node.id.name===t.name&&s.node.init&&i.push(s.node)}}),i.length===1){let s=vo(i[0].init);return!s||!Y.isArrayExpression(s)?null:{array:s,locator:{kind:"value",root:{kind:"binding",name:t.name}},sourceFile:n}}return dR(e,t.name,n,r)}function dR(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=pR(n,o.source.value,r);if(!s)return null;let a=Y.isIdentifier(i.imported)?i.imported.name:i.imported.value,c=r.get(s);if(c===void 0)return null;let l;try{l=ul.parse(c,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}let d=fR(l,a),f=d?vo(d):null;return!f||!Y.isArrayExpression(f)?null:{array:f,locator:{kind:"value",root:{kind:"binding",name:a}},sourceFile:s}}return null}function fR(e,t){let n=null;return dl(e,{VariableDeclarator(r){n||!Y.isIdentifier(r.node.id)||r.node.id.name!==t||!r.node.init||!Y.isExpression(r.node.init)||(n=r.node.init)}}),n}function pR(e,t,n){let r=bn(e,t);return[r,r+".tsx",r+".ts",r+".jsx",r+".js",r+"/index.tsx",r+"/index.ts",r+"/index.jsx",r+"/index.js"].find(i=>n.has(i))??null}function vo(e){return Y.isParenthesizedExpression(e)?vo(e.expression):Y.isTSAsExpression(e)?sg(e.typeAnnotation)?vo(e.expression):null:Y.isTSSatisfiesExpression(e)?null:e}function sg(e){return Y.isTSTypeReference(e)&&Y.isIdentifier(e.typeName)&&e.typeName.name==="const"}function ag(e){return e.properties.every(t=>!Y.isObjectProperty(t)||t.computed||!Y.isExpression(t.value)?!1:ps(t.value))}function ps(e){if(Y.isTSAsExpression(e)&&sg(e.typeAnnotation))return ps(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:ps(n));if(Y.isObjectExpression(e))return ag(e);let t=Mt(e);return t.status==="resolved"||t.status==="undefined"}function mR(e,t){let n=e.properties.filter(o=>Y.isObjectProperty(o)&&cg(o.key)===t);if(n.length>1)return null;let r=n[0];return r?Y.isExpression(r.value)?ps(r.value)?"static":Y.isIdentifier(r.value)||Y.isMemberExpression(r.value)?"binding":null:null:"missing"}function gR(e,t){let n=e.properties.filter(o=>Y.isObjectProperty(o)&&cg(o.key)===t);if(n.length>1)return{status:"unresolved"};let r=n[0];return!r||!Y.isExpression(r.value)?{status:"undefined"}:Mt(r.value)}function hR(e,t){let n=e.attributes?.filter(r=>r.name===t)??[];return n.length===1?n[0]:void 0}function cg(e){return Y.isIdentifier(e)?e.name:Y.isStringLiteral(e)?e.value:Y.isNumericLiteral(e)?String(e.value):null}function lg(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 rg(e){return e.start==null||e.end==null?Number.MAX_SAFE_INTEGER:e.end-e.start}function og(e,t){let n=lg(e);return ig(n.startLine,n.startColumn,t.startLine,t.startColumn)<=0&&ig(n.endLine,n.endColumn,t.endLine,t.endColumn)>=0}function ig(e,t,n,r){return e===n?t-r:e-n}function ut(e,t){return{ok:!1,errorCode:e,reason:t}}import{classifySiteEditPropertyName as nw}from"@vcp-dev/contracts";import*as Q from"@babel/types";import wo from"node:path";import*as $ from"@babel/types";import*as gg from"@babel/parser";import pl from"@babel/traverse";import*as re from"@babel/types";function gs(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 ug(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 Qe(e,t){let n=e;for(let r of t){if(r.kind==="property"){if(n===null||Array.isArray(n)||typeof n!="object"||!(r.name in n))return;n=n[r.name];continue}if(!Array.isArray(n)||r.index<0||r.index>=n.length)return;n=n[r.index]}return n}var Vt=Symbol("not-closed-literal");function ms(e){switch(e.type){case"StringLiteral":case"NumericLiteral":case"BooleanLiteral":return e.value;case"NullLiteral":return null;case"TemplateLiteral":return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:Vt;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":return ms(e.expression);case"ArrayExpression":{let t=[];for(let n of e.elements){if(!n||re.isSpreadElement(n))return Vt;let r=ms(n);if(r===Vt)return Vt;t.push(r)}return t}case"ObjectExpression":{let t={};for(let n of e.properties){if(!re.isObjectProperty(n)||n.computed||n.shorthand||!re.isExpression(n.value))return Vt;let r=re.isIdentifier(n.key)?n.key.name:re.isStringLiteral(n.key)?n.key.value:null;if(!r)return Vt;let o=ms(n.value);if(o===Vt)return Vt;t[r]=o}return t}default:return Vt}}function dg(e){let{resolveBindingTarget:t}=e;async function n(i,s,a,c,l,d,f){let m=ms(i);if(m!==Vt)return m;if(!re.isTemplateLiteral(i)){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 u=s.getBinding(i.name);if(!u)return;let g=await t({currentFile:a,binding:u,readFile:c,exists:l,fileCache:d,visited:f});return g?.kind==="static"?g.value:void 0}if(re.isArrayExpression(i)){let u=[];for(let g of i.elements){if(!g||re.isSpreadElement(g))return;let h=await r(g,s,a,c,l,d,f);if(h===void 0)return;u.push(h)}return u}if(re.isObjectExpression(i)){let u={};for(let g of i.properties){if(!re.isObjectProperty(g)||g.computed)return;let h=null;if(re.isIdentifier(g.key)?h=g.key.name:re.isStringLiteral(g.key)&&(h=g.key.value),!h)return;if(g.shorthand){if(!re.isIdentifier(g.value))return;let E=await r(g.value,s,a,c,l,d,f);if(E===void 0)return;u[h]=E;continue}if(!re.isExpression(g.value))return;let b=await r(g.value,s,a,c,l,d,f);b!==void 0&&(u[h]=b)}return u}if(re.isMemberExpression(i)){let u=await o(i,s,a,c,l,d,f);if(!u)return;let g=s.getBinding(u.base);if(!g)return;let h=await t({currentFile:a,binding:g,readFile:c,exists:l,fileCache:d,visited:f});return!h||h.kind!=="static"?void 0:Qe(h.value,u.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 hg=typeof pl=="function"?pl:pl.default,fg=new WeakMap;function yg(e){try{return gg.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function hs(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=yg(n);return e.set(t,{source:n,ast:o}),o}function ys(e,t){return gl(ko(e).expressionRanges,t,!1)}function xg(e,t){return ko(e).exactExpressions.get(bg(t))??null}function ml(e,t){return gl(ko(e).jsxRanges,t,!0)}function ko(e){let t=fg.get(e);if(t)return t;let n={expressions:[],expressionRanges:[],jsxRanges:[],exactExpressions:new Map};return hg(e,{Expression(r){let o=r;n.expressions.push(o);let i=pg(o,n.expressions.length-1);if(!i)return;n.expressionRanges.push(i);let s=bg(i.range),a=n.exactExpressions.get(s);(!a||i.span<=(a.node.end??0)-(a.node.start??0))&&n.exactExpressions.set(s,o)},JSXElement(r){let o=pg(r,n.jsxRanges.length);o&&n.jsxRanges.push(o)}}),n.expressionRanges.sort(mg),n.jsxRanges.sort(mg),fg.set(e,n),n}function pg(e,t){let n=Io(e.node);return n?{path:e,range:n,traversalIndex:t,span:(e.node.end??0)-(e.node.start??0)}:null}function bg(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}function mg(e,t){return e.range.startLine-t.range.startLine||e.range.startColumn-t.range.startColumn||e.traversalIndex-t.traversalIndex}function gl(e,t,n,r){let o=0,i=e.length;for(;o<i;){let c=o+Math.floor((i-o)/2),l=e[c].range;l.startLine<t.startLine||l.startLine===t.startLine&&l.startColumn<t.startColumn?o=c+1:i=c}let s=null,a=n?1/0:-1;for(let c=o;c<e.length;c++){let l=e[c],d=l.range;if(d.startLine>t.endLine||d.startLine===t.endLine&&d.startColumn>t.endColumn)break;if(d.endLine>t.endLine||d.endLine===t.endLine&&d.endColumn>t.endColumn||r&&!r(l.path))continue;((n?l.span<a:l.span>a)||l.span===a&&(!s||l.traversalIndex>s.traversalIndex))&&(s=l,a=l.span)}return s?.path??null}function Io(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 xr(e,t){if(t)return hl(e,t);let n=ug(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function hl(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Co(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of ko(e).expressions){if(hl(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function Sg(e,t,n,r){return gl(ko(e).expressionRanges,r,!0,o=>hl(o.node,t)===n)}function br(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function Ro(e){let t=null;if(hg(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}async function Kt(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=yg(o),s={source:o,ast:i};return n.set(e,s),s}function yR(e){return $.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:$.isMemberExpression(e.callee)&&$.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function xR(e){if(!$.isNewExpression(e)||!$.isIdentifier(e.callee,{name:"Proxy"})||e.arguments.length!==2||!$.isIdentifier(e.arguments[0])||!$.isObjectExpression(e.arguments[1])||e.arguments[1].properties.length!==1)return null;let[t]=e.arguments[1].properties;if(!$.isObjectMethod(t)||t.kind!=="method"||t.computed||t.async||t.generator||!$.isIdentifier(t.key,{name:"get"})||t.params.length!==3||!t.params.every($.isIdentifier)||t.body.body.length!==2)return null;let[n,r,o]=t.params,[i,s]=t.body.body;if($.isIfStatement(i)&&$.isBlockStatement(i.consequent)&&i.consequent.body.length!==1)return null;let a=$.isIfStatement(i)?i.test:null,c=a&&$.isLogicalExpression(a,{operator:"&&"})?a.right:null,l=$.isIfStatement(i)?$.isBlockStatement(i.consequent)?i.consequent.body[0]:i.consequent:null,d=$.isReturnStatement(s)?s.argument:null;return!a||!$.isLogicalExpression(a,{operator:"&&"})||!$.isBinaryExpression(a.left,{operator:"==="})||!$.isUnaryExpression(a.left.left,{operator:"typeof"})||!$.isIdentifier(a.left.left.argument,{name:r.name})||!$.isStringLiteral(a.left.right,{value:"string"})||!$.isUnaryExpression(c,{operator:"!"})||!$.isBinaryExpression(c.argument,{operator:"in"})||!$.isIdentifier(c.argument.left,{name:r.name})||!$.isIdentifier(c.argument.right,{name:n.name})||!$.isReturnStatement(l)||!$.isIfStatement(i)||i.alternate||!$.isCallExpression(d)||!$.isMemberExpression(d.callee)||!$.isIdentifier(d.callee.object,{name:"Reflect"})||!$.isIdentifier(d.callee.property,{name:"get"})||d.arguments.length!==3||!$.isIdentifier(d.arguments[0],{name:n.name})||!$.isIdentifier(d.arguments[1],{name:r.name})||!$.isIdentifier(d.arguments[2],{name:o.name})?null:e.arguments[0].name}function bR(e){let t=e.getFunctionParent();if(!t)return null;if(t.isFunctionDeclaration()){let s=t.node.id?.name;if(!s)return null;let a=t.parentPath?.isExportDefaultDeclaration()?"default":(t.parentPath?.isExportNamedDeclaration(),s);return{componentName:s,exportName:a}}if(!t.isArrowFunctionExpression()&&!t.isFunctionExpression())return null;let n=t.parentPath;if(!n?.isVariableDeclarator()||!$.isIdentifier(n.node.id))return null;let r=n.node.id.name,o=n.parentPath,i=o?.parentPath?.isExportDefaultDeclaration()?"default":(o?.parentPath?.isExportNamedDeclaration(),r);return{componentName:r,exportName:i}}function SR(e,t){let n=bR(e.path);if(!n)return null;let r=cr(e,t);return r?{...n,...r}:null}function ER(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}function yl(e,t){let n=[{kind:"component-prop",file:t.file,displayName:`${t.componentName}.${t.propName}`,canEditHere:!0}];return e.kind==="external"?{...e,chainPrefix:[...n,...e.chainPrefix??[]],editMode:e.editMode==="readonly"?"readonly":"upstream"}:{...e,chainPrefix:[...n,...e.chainPrefix??[]],editMode:"upstream"}}function xl(e,t){for(let n of e.program.body){if(t==="default"&&$.isExportDefaultDeclaration(n))return $.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:($.isFunctionDeclaration(n.declaration)||$.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if($.isExportNamedDeclaration(n)){if(n.declaration){if($.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if($.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if(($.isFunctionDeclaration(n.declaration)||$.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if(($.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&$.isExportSpecifier(r))return n.source?{kind:"re-export",name:r.local.name,source:n.source.value}:{kind:"local-binding",name:r.local.name}}}return null}function Eg(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:y,visited:k}=u,C=`${g}::${h.kind}::${h.identifier.name}`;if(k.has(C))return null;k.add(C);try{let N=await a({currentFile:g,binding:h,readFile:b,exists:E,fileCache:y,visited:k});if(N)return N;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:y,visited:k});if(h.kind==="param")return null;if(h.path.isVariableDeclarator()){let T=h.path.node.init;if(!T||!$.isExpression(T))return null;let R=xR(T);if(R&&!h.path.scope.getBinding("Proxy")&&!h.path.scope.getBinding("Reflect")){let D=h.path.scope.getBinding(R),L=D?await s({...u,binding:D}):null;if(L?.kind==="static"&&L.value!==null&&!Array.isArray(L.value)&&typeof L.value=="object")return L}let A=h.path.get("init");if(A&&!Array.isArray(A)&&A.isExpression()){let D=await t({currentFile:g,expressionPath:A,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:k});if(D)return D;if(A.isCallExpression()){let L=await n({currentFile:g,callPath:A,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:k});if(L)return L}}let M=await r(T,h.path.scope,g,b,E,y,k);return M===void 0?null:{kind:"static",file:g,root:{kind:"binding",name:h.identifier.name},value:M,sourceKind:"binding"}}if(h.path.isIdentifier()&&h.path.parentPath?.isExportDefaultDeclaration()){let T=h.path.parentPath.node.declaration;if(!$.isExpression(T))return null;let R=await r(T,h.path.scope,g,b,E,y,k);return R===void 0?null:{kind:"static",file:g,root:{kind:"binding",name:h.identifier.name},value:R,sourceKind:"binding"}}return null}finally{k.delete(C)}}async function a(u){let{currentFile:g,binding:h,readFile:b,exists:E,fileCache:y,visited:k}=u;if(!h.path.isVariableDeclarator()||!h.path.get("id").isArrayPattern())return null;let C=h.path,N=C.node.init;if(!N||!$.isCallExpression(N))return null;let T=yR(N);if(!T||!$.isArrayPattern(C.node.id)||C.node.id.elements.findIndex(L=>$.isIdentifier(L)&&L.name===h.identifier.name)!==0)return null;let A=T==="useReducer"?1:0,M=N.arguments[A];if(!M||!$.isExpression(M))return null;let D=await r(M,C.scope,g,b,E,y,k);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=SR(u.binding,u.sourceInfo);if(!g||!u.graph)return null;let h=[...u.graph.elements.values()].filter(T=>ER(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 yl(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 yl(T,{componentName:g.componentName,propName:g.propName,file:b.sourceFile});let R=bp(u.binding,g.componentName,g.propName);if(!R||R.propName!==g.propName)return null;let A=await r(R.expressionPath.node,R.expressionPath.scope,u.currentFile,u.readFile,u.exists,u.fileCache,u.visited);if(A===void 0)return null;let M=g.remainingPath;return M.length>0&&Qe(A,M)===void 0?null:{kind:"value",file:u.currentFile,root:{kind:"binding",name:g.propName},path:M,sourceKind:"binding",semanticKind:"component-prop",displayExpression:R.displayPath,chainPrefix:[{kind:"component-prop",file:u.currentFile,displayName:R.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let y=await Kt(b.sourceFile,u.readFile,u.fileCache);if(!y.ast)return null;let k=Sg(y.ast,y.source,E.source.expression,E.sourceRange)??Co(y.ast,y.source,E.source.expression);if(!k)return null;let C={...E.source,expression:br(E.source.expression,g.remainingPath),path:[...E.source.path,...g.remainingPath]},N=await o({currentFile:b.sourceFile,expressionPath:k,sourceInfo:C,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});return N?yl(N.kind==="external"?N:{...N,displayExpression:C.expression},{componentName:g.componentName,propName:g.propName,file:b.sourceFile}):null}async function l(u){let g=await Kt(u.caller.sourceFile,u.readFile,u.fileCache);if(!g.ast)return null;let h=ml(g.ast,u.caller.sourceRange);if(!h)return null;let b=h.get("openingElement").get("attributes").find(C=>C.isJSXAttribute()&&C.node.name.type==="JSXIdentifier"&&C.node.name.name===u.propName);if(!b?.isJSXAttribute())return null;let E=b.get("value"),y=E.isStringLiteral()?E:E.isJSXExpressionContainer()?E.get("expression"):null;if(!y?.isExpression())return null;let k=Io(y.node);return k?{kind:"value",file:u.caller.sourceFile,root:{kind:"expression",sourceRange:k},path:u.remainingPath,sourceKind:"binding",semanticKind:"component-prop",displayExpression:u.propName,editMode:"upstream",diagnostics:[]}:null}async function d(u){let g=await Kt(u.caller.sourceFile,u.readFile,u.fileCache);if(!g.ast)return null;let h=ml(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 y=E.get("argument");if(!y.isExpression())continue;let k=await i({expression:y.node,scope:y.scope,source:g.source,currentFile:u.caller.sourceFile,readFile:u.readFile,exists:u.exists,fileCache:u.fileCache,visited:u.visited});if(!k)continue;let C=[{kind:"property",name:u.propName},...u.remainingPath],N={...k,expression:br(k.expression,C),path:[...k.path,...C]},T=await o({currentFile:u.caller.sourceFile,expressionPath:y,sourceInfo:N,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});if(T)return T.kind==="external"?T:{...T,displayExpression:N.expression}}return null}async function f(u){let{currentFile:g,binding:h,readFile:b,exists:E,fileCache:y,visited:k}=u,C=h.path.parentPath;if(!C||!C.isImportDeclaration())return null;let N=C.node.source.value;if(typeof N!="string")return null;let T=await Sn(g,N,E);if(!T)return null;if(h.path.isImportDefaultSpecifier()){let ee=await Kt(T,b,y),ge=ee.ast?xl(ee.ast,"default"):null,se=await m({file:T,exportName:"default",readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:k});return!se||se.kind!=="static"?null:{kind:"static",file:ge?.kind==="default-expression"?se.file:T,root:ge?.kind==="default-expression"?se.root:{kind:"default-export"},value:se.value,sourceKind:"imported-binding"}}if(!h.path.isImportSpecifier())return null;let R=h.path.node.imported,A=$.isIdentifier(R)?R.name:R.value,M=await Kt(T,b,y),D=M.ast?xl(M.ast,A):null,L=await m({file:T,exportName:A,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:k});return L?L.kind==="external"?L:{kind:"static",file:D?.kind==="re-export"?L.file:T,root:D?.kind==="re-export"||L.root.kind==="binding"&&L.root.name!==D?.name?L.root:{kind:"named-export",name:A},value:L.value,sourceKind:"imported-binding"}:null}async function m(u){let{file:g,exportName:h,readFile:b,exists:E,fileCache:y,visited:k}=u,C=`export::${g}::${h}`;if(!k.has(C)){k.add(C);try{let N=await Kt(g,b,y);if(!N.ast)return;let T=xl(N.ast,h);if(!T)return;if(T.kind==="default-expression"){let D=T.expression;if(!D||!$.isIdentifier(D))return;let L=Ro(N.ast).getBinding(D.name);return L?await s({currentFile:g,binding:L,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:k})??void 0:void 0}if(T.kind==="re-export"){if(!T.source||!T.name)return;let D=await Sn(g,T.source,E);return D?m({...u,file:D,exportName:T.name}):void 0}let R=T.name;if(!R)return;let A=Ro(N.ast).getBinding(R);return A?await s({currentFile:g,binding:A,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:k})??void 0:void 0}finally{k.delete(C)}}}return{resolveExportValue:m,resolveComponentPropBinding:c,resolveBindingTarget:s}}import*as H from"@babel/types";function Sl(e,t){let n=e.scope.getBinding(t);if(!n)return null;let r=n.path.getFunctionParent();if(!r||!r.isArrowFunctionExpression()&&!r.isFunctionExpression())return null;let o=r.node.params[0],i=It(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!vR(s,r)?null:{callPath:s,basePath:i}}function vR(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 Ig(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:Wi(r,t)}function vg(e,t){return e?H.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}function kg(e,t,n,r,o){let i=H.isExpression(e.body)?e.body:e.body.body.find(a=>H.isReturnStatement(a))?.argument;if(!i||!H.isExpression(i))return;let s=bl(i,t,n,r,o);return typeof s=="number"?s:void 0}function bl(e,t,n,r,o){if(H.isNumericLiteral(e)||H.isStringLiteral(e)||H.isBooleanLiteral(e))return e.value;if(H.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(H.isMemberExpression(e)){let i=gs(e,t);if(i)return Qe(r,i);let s=gs(e,n);return s?Qe(o,s):void 0}if(H.isBinaryExpression(e)&&e.operator==="-"){let i=H.isExpression(e.left)?bl(e.left,t,n,r,o):void 0,s=H.isExpression(e.right)?bl(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function kR(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 IR(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=gs(e,t);return r?Qe(n,r):void 0}if(H.isUnaryExpression(e)&&e.operator==="!"){let r=jn(e.argument,t,n);return r===void 0?void 0:!r}if(H.isLogicalExpression(e)){let r=jn(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&jn(e.right,t,n);if(e.operator==="||")return r||jn(e.right,t,n)}if(H.isBinaryExpression(e)){let r=H.isExpression(e.left)?jn(e.left,t,n):void 0,o=H.isExpression(e.right)?jn(e.right,t,n):void 0;if(r===void 0||o===void 0)return;switch(e.operator){case"===":return r===o;case"!==":return r!==o;case"==":return r==o;case"!=":return r!=o;default:return}}}function Cg(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 Rg(e){return e.some(t=>t.kind==="dynamic")}function CR(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}function wg(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 RR(e,t){let n=[],r=[];for(let o of t){let i=Qe(e,o);if(!Array.isArray(i))return null;for(let[s,a]of i.entries())n.push(a),r.push([...o,{kind:"index",index:s}])}return{value:n,collectionPathMap:r}}function Ng(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:y,visited:k}=u,C=h.node.callee;if(!H.isMemberExpression(C)||!H.isIdentifier(C.property)||C.property.name!=="map")return null;let N=h.get("callee");if(!N.isMemberExpression())return null;let T=N.get("object");if(Array.isArray(T)||!T.isExpression())return null;let R=await s({currentFile:g,expressionPath:T,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:k});return!R||!Array.isArray(R.value)||R.value.length===0?null:R}async function s(u){let{currentFile:g,expressionPath:h,readFile:b,exists:E,fileCache:y,visited:k}=u;if(h.isIdentifier()){let C=h.scope.getBinding(h.node.name);if(!C)return null;let N=await t({currentFile:g,binding:C,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:k});return N?.kind==="static"?N: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:y,visited:k});if(h.isTSAsExpression()||h.isTSSatisfiesExpression()||h.isTSNonNullExpression()){let C=h.get("expression");if(!Array.isArray(C)&&C.isExpression())return s({...u,expressionPath:C})}if(h.isArrayExpression()){let C=Io(h.node);if(!C)return null;let N=await n(h.node,h.scope,g,b,E,y,k);return Array.isArray(N)?{kind:"static",file:g,root:{kind:"expression",sourceRange:C},value:N,sourceKind:"binding"}:null}if(h.isMemberExpression()){let C=await r({expression:h.node,scope:h.scope,currentFile:g,readFile:b,exists:E,fileCache:y,visited:k});if(!C)return null;let N=await o({currentFile:g,expressionPath:h,sourceInfo:C,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:k});if(!N||N.kind==="external")return null;let T=await a({currentFile:g,expressionPath:h,provenance:N,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:y,visited:k});if(!T||T.kind!=="static")return null;if(N.collectionPathMap?.length){let A=RR(T.value,N.collectionPathMap);if(A)return{kind:"static",file:N.file,root:N.root,value:A.value,sourceKind:N.sourceKind,collectionPathMap:A.collectionPathMap}}let R=Qe(T.value,N.path);return Array.isArray(R)?{kind:"static",file:N.file,root:N.root,value:R,sourceKind:N.sourceKind,pathPrefix:N.path,collectionIndexMap:N.collectionIndexMap,collectionPathMap:N.collectionPathMap}:null}return null}async function a(u){let{provenance:g}=u;if(g.root.kind==="binding"){let y=u.expressionPath.scope.getBinding(g.root.name);if(!y&&g.file!==u.currentFile){let k=await Kt(g.file,u.readFile,u.fileCache);y=k.ast?Ro(k.ast).getBinding(g.root.name):void 0}return y?await t({currentFile:g.file,binding:y,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited}):null}if(g.root.kind!=="expression")return null;let h=await Kt(g.file,u.readFile,u.fileCache);if(!h.ast)return null;let b=xg(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 y=await s({currentFile:u.currentFile,expressionPath:E,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});if(!y||!Array.isArray(y.value))return null;let[k]=g.node.arguments;if(!H.isArrowFunctionExpression(k)&&!H.isFunctionExpression(k))return null;let C=k.params[0];if(!H.isIdentifier(C))return null;let N=kR(k);if(!N)return null;let T=[],R=[],A=[];for(let[M,D]of y.value.entries()){let L=IR(N,C.name,D);if(typeof L!="boolean")return null;if(L){T.push(D),R.push(y.collectionIndexMap?.[M]??M);let ee=y.collectionPathMap?.[M];ee&&A.push(ee)}}return{...y,value:T,pathPrefix:y.pathPrefix,collectionIndexMap:R,...A.length>0?{collectionPathMap:A}:{}}}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 y=await s({currentFile:u.currentFile,expressionPath:E,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});if(!y||!Array.isArray(y.value))return null;let[k,C]=g.node.arguments,N=vg(k,0),T=vg(C,y.value.length);if(N===null||T===null)return null;let R=Math.max(0,N<0?y.value.length+N:N),A=Math.max(0,T<0?y.value.length+T:T),M=y.value.map((L,ee)=>y.collectionIndexMap?.[ee]??ee).slice(R,A),D=y.collectionPathMap?.slice(R,A);return{...y,value:y.value.slice(R,A),pathPrefix:y.pathPrefix,collectionIndexMap:M,...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 y=await s({currentFile:u.currentFile,expressionPath:E,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});if(!y||!Array.isArray(y.value))return null;let[k]=g.node.arguments;if(!H.isArrowFunctionExpression(k)&&!H.isFunctionExpression(k))return null;let[C,N]=k.params;if(!H.isIdentifier(C)||!H.isIdentifier(N))return null;let T=y.value.map((A,M)=>({value:A,sourceIndex:y.collectionIndexMap?.[M]??M,originalIndex:M})),R=[...T];for(let A of T)for(let M of T)if(kg(k,C.name,N.name,A.value,M.value)===void 0)return null;return R.sort((A,M)=>{let D=kg(k,C.name,N.name,A.value,M.value)??0;return D===0?A.originalIndex-M.originalIndex:D}),{...y,value:R.map(A=>A.value),pathPrefix:y.pathPrefix,collectionIndexMap:R.map(A=>A.sourceIndex),...y.collectionPathMap?{collectionPathMap:R.map(A=>y.collectionPathMap?.[A.originalIndex]).filter(A=>!!A)}:{}}}async function m(u){let g=null,h,b=[];for(let y of u.segments){if(y.kind!=="dynamic")continue;let k=await r({expression:y.expression,scope:u.expressionPath.scope,source:u.fileCache.get(u.currentFile)?.source,currentFile:u.currentFile,readFile:u.readFile,exists:u.exists,fileCache:u.fileCache,visited:u.visited});if(!k)return null;let C=Sl(u.expressionPath,k.base);if(!C)return null;let N=await i({currentFile:u.currentFile,callPath:C.callPath,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});if(!N||!Array.isArray(N.value))return null;let T=N.value.map((R,A)=>{let M=Qe(N.value,[{kind:"index",index:A},...C.basePath,...k.path]);return CR(M)});if(T.some(R=>R===null)||g!==null&&g!==T.length)return null;g=T.length,h??=N.collectionIndexMap,b.push(T)}if(g===null||g===0)return null;let E=[];for(let y=0;y<g;y+=1){let k=[...u.rootPath],C=0;for(let N of u.segments){if(N.kind==="dynamic"){let T=b[C]?.[y];if(!T)return null;k.push(T),C+=1;continue}k.push({...N})}E.push(k)}return{...h?{collectionIndexMap:h}:{},collectionPathMap:E}}return{resolveRepeatCollectionTarget:i,resolveCollectionCallTarget:c,resolveDynamicMemberPathMap:m}}var{normalizeExpressionWithScope:wR,evaluateStaticExpression:xs}=dg({resolveBindingTarget:e=>bs(e)}),{resolveRepeatCollectionTarget:NR,resolveCollectionCallTarget:PR,resolveDynamicMemberPathMap:AR}=Ng({resolveBindingTarget:e=>bs(e),evaluateStaticExpression:xs,buildExpressionSourceInfo:Ut,resolveSourceInfoProvenance:St}),{resolveExportValue:TR,resolveComponentPropBinding:FR,resolveBindingTarget:bs}=Eg({resolveExternalExpression:wl,resolveCollectionCallTarget:PR,evaluateStaticExpression:xs,resolveSourceInfoProvenance:St,buildExpressionSourceInfo:Ut});function Dg(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}var Pg=new WeakMap;function _R(e){let t=Pg.get(e);return t||(t=new WeakMap,Pg.set(e,t)),t}function Ag(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 Bg(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=hs(s,t,n);if(!a)return null;let c=ys(a,r.sourceRange);if(!c)return null;let l=await Ut({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!l){let m=await Tl({currentFile:t,expressionPath:c,readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:new Set});return m?kl(m,xr(c.node,n)):null}let d=new Set,f=await tw({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?kl(f,l.expression):null}async function Sr(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=hs(i,t,n);if(!s)return null;let a=e.sourceRange?ys(s,e.sourceRange):e.expression!==void 0?Co(s,n,e.expression):null;if(!a)return null;let c=Ss(a);if(!c.isIdentifier()&&!c.isMemberExpression())return null;let l=new Set,d=await Ut({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 zg({currentFile:t,expressionPath:c,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:l});return kl(f,e.expression??xr(c.node,n))}async function Rl(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=hs(i,t,n);if(!s)return dt("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?MR({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}):OR({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}async function Ut(e){if(Q.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!Q.isMemberExpression(e.expression))return null;let t=await wR(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:xr(e.expression,e.source),base:t.base,path:t.path}:null}function kl(e,t){if(!e||e.kind==="value"&&e.editMode==="readonly")return null;if(e.kind==="external")return{kind:"external-entry",file:e.file,sourceType:e.sourceType,sourceId:e.sourceId,adapterId:e.adapterId,displayExpression:e.displayPath};let n={kind:"value",root:e.root,path:e.path.length>0?e.path:[]};return{kind:"value-binding",file:e.file,locator:n,root:e.root,path:e.path,displayExpression:e.displayExpression??t,sourceKind:e.sourceKind,...e.collectionIndexMap?{collectionIndexMap:e.collectionIndexMap}:{},...e.collectionPathMap?{collectionPathMap:e.collectionPathMap}:{}}}async function MR(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=ys(r,o.sourceRange),d=l?await Ut({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 Tg(t,o.value);let m=await Tl({currentFile:t,expressionPath:l,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});return m?m.kind==="external"?Lg(t,m):Cl(t,xr(l.node,n),m):LR({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return dt("unsupported-expression","Unable to locate text expression for provenance resolution");let f=await St({currentFile:t,expressionPath:l,sourceInfo:d,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});if(!f){let m=Il(l.node);if(m)return dt(m.code,m.message);let u=l.scope.getBinding(d.base);if(u?.path.isVariableDeclarator()){let g=Il(u.path.node.init);if(g)return dt(g.code,g.message)}return u?.path.isVariableDeclarator()&&Q.isCallExpression(u.path.node.init)?DR("unsupported-expression",Ug(u.path.node.init,e.functionCallContracts)):dt("unsupported-expression",`Unable to resolve provenance for expression "${d.expression}"`)}return f.kind==="external"?Lg(t,f):Cl(t,d.expression,f)}async function OR(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return dt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=Co(r,n,o.conditionExpression);if(!l)return dt("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let d=await St({currentFile:t,expressionPath:l,sourceInfo:o.conditionSource,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});if(!d)return dt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(d.kind==="external")return dt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let f=Cl(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 Tg(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 LR(e){let t=await $g(e);if(t.length===0)return dt("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(BR(e.expression))return jg(t);if(Kg(e.expression))return dt("unsupported-expression","i18n helpers require a static message id string");if(Q.isMemberExpression(e.expression)&&e.expression.computed&&!Q.isNumericLiteral(e.expression.property)&&!Q.isStringLiteral(e.expression.property))return dt("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return dt(n.code,n.message)}function dt(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function DR(e,t){return jg([{code:e,message:t}])}function jg(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function BR(e){return Q.isCallExpression(e)||Q.isConditionalExpression(e)||Q.isLogicalExpression(e)||Q.isBinaryExpression(e)}function No(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 $g(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=Il(t);if(l)return[l];if(Q.isCallExpression(t))return[{code:"unsupported-expression",message:Ug(t,c)}];if(Q.isMemberExpression(t)&&t.computed){let d=t.property;if(!Q.isNumericLiteral(d)&&!Q.isStringLiteral(d)){if(!Q.isExpression(d))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let m=await xs(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 Q.isBinaryExpression(t)?No([...await El(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):Q.isLogicalExpression(t)?No([...await El(t.left,t.right,e),{code:"unsupported-expression",message:t.operator==="??"||t.operator==="||"?"Fallback expressions are recognized but remain readonly until a safer composition editing strategy is available":"Complex conditional expressions are recognized but remain readonly until a safer editing strategy is available"}]):Q.isConditionalExpression(t)?No([...await El(t.test,t.consequent,t.alternate,e),{code:"unsupported-expression",message:"Complex conditional expressions are recognized but remain readonly until a safer editing strategy is available"}]):[]}function Il(e){return Kg(e)?Fg("i18n helpers require a static message id string"):UR(e)?Fg("CMS helpers require static entry id and field path string arguments"):null}async function El(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await $g({...t,expression:o}));return r}function jR(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:[$R(e.sourceType)]}}async function wl(e){for(let n of WR){if(!_g(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return Og(Mg(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(!_g(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return Og(Mg(r),e.externalAdapters)}return null}function $R(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function VR(e){return{code:"external-source-readonly",message:e}}function Fg(e){return{code:"unsupported-expression",message:e}}function Nl(e){return!e||!Q.isCallExpression(e)?null:Q.isIdentifier(e.callee)?e.callee.name:Q.isMemberExpression(e.callee)&&!e.callee.computed&&Q.isIdentifier(e.callee.object)&&Q.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function _g(e,t){if(!t||t.length===0)return!0;let n=Nl(e.node);return n?t.includes(n):!1}function Mg(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:No(e.diagnostics??[])}:{match:e,diagnostics:[]}}function Og(e,t){let n=jR(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:No([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function KR(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!Q.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!Q.isStringLiteral(n)||!Q.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 UR(e){return!!e&&Q.isCallExpression(e)&&Q.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!Q.isStringLiteral(e.arguments[0])||!Q.isStringLiteral(e.arguments[1]))}function Vg(e){if(!(!e||!Q.isCallExpression(e))){if(Q.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&Q.isStringLiteral(t)?t.value:null}if(Q.isMemberExpression(e.callee)&&!e.callee.computed&&Q.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&Q.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!Q.isObjectExpression(t))return null;for(let n of t.properties)if(Q.isObjectProperty(n)&&!n.computed&&(Q.isIdentifier(n.key)&&n.key.name==="id"||Q.isStringLiteral(n.key)&&n.key.value==="id")&&Q.isStringLiteral(n.value))return n.value.value;return null}}}function Kg(e){return Vg(e)===null}async function JR(e,t,n){let r=new Set,o=wo.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=wo.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"]:[wo.posix.join(i,"locales"),wo.posix.join(i,"messages")];for(let a of s){let c=wo.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function XR(e){let t=Vg(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await JR(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function zR(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!Q.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!Q.isExpression(n))return null;let o=await xs(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:[VR("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var WR=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>KR(e)},{helperNames:["apiField"],resolve:e=>zR(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>XR({currentFile:e,expressionPath:t,exists:n})}];function Pl(e){return{...e,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Derived display values are readonly because no identity-preserving write target exists"}]}}function Lg(e,t){return{finalSource:{kind:t.sourceType,file:t.file,locator:null,displayPath:t.displayPath,externalSource:{sourceType:t.sourceType,sourceId:t.sourceId,adapterId:t.adapterId}},chain:[...t.chainPrefix??[],{kind:t.sourceType,file:t.file,displayName:t.displayPath,canEditHere:t.editMode!=="readonly"}],confidence:"exact",editMode:t.editMode==="direct"?t.file===e?"direct":"proxy":t.editMode,diagnostics:t.diagnostics}}function Cl(e,t,n){let r={kind:"value",root:n.root,path:n.path.length>0?n.path:[]},o=n.path.some(l=>l.kind==="index"),i=ew(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 HR=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function Al(e,t){let n=[...HR,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function Ug(e,t){let n=e.callee;return Q.isIdentifier(n)&&Al(n.name,t)?.purity==="side-effect"?`Helper "${n.name}" is registered as side-effectful and remains readonly`:"Function calls remain readonly because purity does not establish an identity-preserving write target"}async function Tl(e){let t=await wl(e);if(t)return t;let n=await Jg({...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 Ut({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 QR(e)}async function Jg(e){let t=await Rt({...e,allowComposed:!1});if(t?.kind!=="source")return null;let n=Ss(e.expressionPath);return n.isIdentifier()||n.isMemberExpression()?t.provenance:Pl(t.provenance)}async function Rt(e){let t=Ss(e.expressionPath),n=ZR(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 Ut({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 Ut({expression:t.node,scope:t.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(!r)return null;let o=await St({currentFile:e.currentFile,expressionPath:t,sourceInfo:r,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return!o||o.kind==="external"?null:{kind:"source",provenance:o}}if(t.isConditionalExpression()){let r=t.get("test"),o=t.get("consequent"),i=t.get("alternate");if(Array.isArray(r)||Array.isArray(o)||Array.isArray(i)||!r.isExpression()||!o.isExpression()||!i.isExpression())return null;let s=await Rt({...e,expressionPath:r,allowComposed:!0}),a=await Rt({...e,expressionPath:o,allowComposed:!1}),c=await Rt({...e,expressionPath:i,allowComposed:!1});return vl(s,a,c)}if(t.isCallExpression())return GR({...e,expressionPath:t});if(!e.allowComposed)return null;if(t.isBinaryExpression()){let r=t.get("left"),o=t.get("right");if(Array.isArray(r)||Array.isArray(o)||!r.isExpression()||!o.isExpression())return null;let i=await Rt({...e,expressionPath:r,allowComposed:!0}),s=await Rt({...e,expressionPath:o,allowComposed:!0});return vl(i,s)}if(t.isLogicalExpression()){let r=t.get("left"),o=t.get("right");if(Array.isArray(r)||Array.isArray(o)||!r.isExpression()||!o.isExpression())return null;let i=await Rt({...e,expressionPath:r,allowComposed:!0}),s=await Rt({...e,expressionPath:o,allowComposed:!0});return vl(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:Rt({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function Ss(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 GR(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(Q.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:Rt({...e,expressionPath:o,allowComposed:!1})}}return null}function vl(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!YR(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function YR(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 ZR(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function QR(e){if(!e.expressionPath.isCallExpression())return null;let t=Nl(e.expressionPath.node);if(!t)return null;let n=Al(t,e.functionCallContracts);if(!n||n.purity!=="pure")return null;let r=n.sourceArgIndex??0,o=e.expressionPath.get(`arguments.${r}`);if(!o||Array.isArray(o)||!o.isExpression())return null;let i=await Xg({currentFile:e.currentFile,argumentPath:o,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return i?Pl(i):null}async function Xg(e){let t=await wl({currentFile:e.currentFile,expressionPath:e.argumentPath,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(t)return t;let n=await Ut({expression:e.argumentPath.node,scope:e.argumentPath.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(n){let r=await St({currentFile:e.currentFile,expressionPath:e.argumentPath,sourceInfo:n,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return!r||r.kind==="external"?r:{...r,displayExpression:n.expression}}return await Tl({currentFile:e.currentFile,expressionPath:e.argumentPath,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited})}async function qR(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!Q.isCallExpression(t))return null;let n=t.callee;if(!Q.isIdentifier(n))return null;let r=Al(n.name,e.functionCallContracts);if(!r||r.purity!=="pure")return null;let o=r.sourceArgIndex??0,i=e.binding.path.get("init");if(!i||Array.isArray(i)||!i.isCallExpression())return null;let s=i.get(`arguments.${o}`);if(!s||Array.isArray(s)||!s.isExpression())return null;let a=await Xg({currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited,argumentPath:s});return a?Pl(a):null}function ew(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=br(t,e.path);return{sourceId:o,displayPath:o}}async function tw(e){let t=e.segment.source;return t?St({currentFile:e.currentFile,expressionPath:e.expressionPath,sourceInfo:t,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited}):null}async function St(e){let t=e.sourceInfo,n=Sl(e.expressionPath,t.base);if(n){let l=await NR({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=Ig(n.callPath,[...n.basePath,...t.path]);return ao(h)?Ag(e.currentFile,h.sourceId,h.displayPath):null}let d=wg(l,[...n.basePath,...t.path]),f=l.collectionIndexMap?.[0]??0,m=[...l.pathPrefix??[],{kind:"index",index:f},...n.basePath,...t.path],u=[{kind:"index",index:0},...n.basePath,...t.path];return Qe(l.value,u)===void 0?null:{kind:"value",file:l.file,root:l.root,path:d?.[0]??m,sourceKind:"repeat-template",collectionIndexMap:l.collectionIndexMap,...d?{collectionPathMap:d}:{}}}let r=e.expressionPath.scope.getBinding(t.base);if(!r)return null;if(r.path.isImportNamespaceSpecifier()){let l=t.path[0],d=r.path.parentPath;if(!l||l.kind!=="property"||!d?.isImportDeclaration())return null;let f=await Sn(e.currentFile,d.node.source.value,e.exists);if(!f)return null;let m=await TR({file:f,exportName:l.name,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(!m||m.kind==="external")return null;let u=t.path.slice(1);return Qe(m.value,u)===void 0?null:{kind:"value",file:m.file,root:m.root,path:u,sourceKind:"imported-binding",collectionIndexMap:m.collectionIndexMap}}let o=yp(r);if(o){let l=o.expressionPath,d=await Ut({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:br(d.expression,t.path),path:[...d.path,...t.path]}});if(f)return f}else if(r.constant){let f=`dynamic-alias:${e.currentFile}:${l.node.start}`;if(e.visited.has(f))return null;e.visited.add(f);try{let m=await zg({...e,expressionPath:Ss(l),memberSuffix:t.path});if(m?.kind==="value")return m}finally{e.visited.delete(f)}}if(t.path.length===0){let f=await Jg({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 FR({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 qR({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=Xi(r,t.path,_R(e.fileCache));if(ao(s))return Ag(e.currentFile,s.sourceId,s.displayPath);let a=await bs({currentFile:e.currentFile,binding:r,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return a?a.kind==="external"?t.path.length===0?a:null:Qe(a.value,t.path)===void 0?null:{kind:"value",file:a.file,root:a.root,path:t.path,sourceKind:a.sourceKind,collectionIndexMap:a.collectionIndexMap}:null}async function zg(e){let t=Cg(e.expressionPath.node);if(!t||!Rg(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 AR({...e,rootPath:n.path,segments:t.segments});if(!r)return null;let o=r.collectionPathMap.map(i=>[...i,...e.memberSuffix??[]]);if(e.memberSuffix){let i=e.expressionPath.scope.getBinding(t.base),s=i?await bs({...e,binding:i}):null;if(s?.kind!=="static"||o.some(a=>Qe(s.value,a.slice(n.path.length))===void 0))return null}return{...n,path:o[0]??n.path,sourceKind:"repeat-template",displayExpression:xr(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:o}}async function Wg(e){let t=nw(e.propertyName);if(t.owner==="blocked")return yn(t.owner,t.diagnostic);if(t.owner==="class-name-source"||t.owner==="style")return yn(t.owner,{code:"owner-delegated",message:`Property '${e.propertyName}' is owned by ${t.owner}`});let n=e.element.attributes?.filter(l=>l.name===e.propertyName)??[];if(n.length>1)return yn("generic",{code:"duplicate-property-source",message:`Property '${e.propertyName}' has multiple explicit sources`});let r=n[0],o=[];r&&o.push({kind:"attribute",order:r.order??e.element.attributes.indexOf(r),attribute:r});let i=e.element.attributeSpreads??[];for(let l of i)o.push({kind:"spread",order:l.order,spread:l,target:await ow(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 yn("generic",{code:"ambiguous-property-source",message:`A spread may provide or override property '${e.propertyName}'`});if(s.kind==="spread")return s.target?{status:"binding",owner:"generic",target:s.target}:yn("generic",{code:"ambiguous-property-source",message:`The final spread source for '${e.propertyName}' is not provably writable`});let c=o.filter(l=>l.kind==="spread"&&l.order<s.order);return e.operation==="remove"&&c.length>0?yn("generic",{code:"remove-exposes-spread",message:`Removing '${e.propertyName}' would expose an earlier spread source`}):rw(e,s.attribute)}async function rw(e,t){if(t.resolution&&t.resolution.status!=="resolved"&&!t.source){let r=await Sr({file:e.file,source:e.source,sourceRange:t.sourceRange,expression:t.value,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache});return r&&r.kind!=="external-entry"?{status:"binding",owner:"generic",attribute:t,target:{kind:"value-binding",target:r}}:yn("generic",{code:"unsupported-property-source",message:`Property '${e.propertyName}' has an unresolved value source`})}if(!t.source?.expression)return{status:"direct",owner:"generic",attribute:t,target:{kind:"jsx-attribute",file:e.file,sourceRange:t.sourceRange}};let n=await Sr({file:e.file,source:e.source,sourceRange:t.sourceRange,expression:t.source.expression,sourceInfo:t.source,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache});return!n||n.kind==="external-entry"?yn("generic",{code:"unsupported-property-source",message:`Property '${e.propertyName}' does not have a local writable source`}):{status:"binding",owner:"generic",attribute:t,target:{kind:"value-binding",target:n}}}async function ow(e,t){let n=t.source?.expression;if(!n)return;let r=await Sr({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:iw(r,e.propertyName)}}function iw(e,t){let n=[...e.path??[],{kind:"property",name:t}];return{...e,path:n,locator:e.locator?{...e.locator,path:n}:{kind:"value",root:e.root??{kind:"binding",name:t},path:n}}}function yn(e,t){return{status:"blocked",owner:e,...t?{diagnostic:t}:{}}}function Hg(e){let t=new Map;for(let r of e.elements.values()){if(r.importedFrom===void 0)continue;let o=t.get(r.importedFrom);o||(o={candidates:[],keys:new Map},t.set(r.importedFrom,o)),o.candidates.push(r)}let n=r=>{if($n(r.tag))return r.identity.key;let o=t.get(r.sourceFile);if(!o)return null;if(o.keys.has(r.componentName))return o.keys.get(r.componentName);let i=o.candidates.filter(a=>lw(a,r.componentName)),s=i.length===1?i[0].identity.key:null;return o.keys.set(r.componentName,s),s};return r=>sw({...r,graph:e},n)}function sw(e,t){let{key:n,element:r,graph:o,provenances:i}=e,s=cw(n,r,o,t),a=s?.tag??($n(r.tag)?r.tag:r.componentName),c=s?.identity.key??t(r,o)??n,l=dw(s),d=fw(n,r,o,i,s),f=aw(n,r,o,i,c);return{componentName:a,instanceKey:c,templateOwner:uw(s??r,a),...l.length>0?{variantKeys:l}:{},...d.length>0?{slotKeys:d}:{},editableStrategy:f,impactScope:pw(f),alternativeStrategies:mw(f)}}function aw(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return Fl(e,n)?"instance":!$n(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function cw(e,t,n,r){if($n(t.tag))return t;let o=Fl(e,n);if(o)return o;let i=r(t,n);return i?n.elements.get(i)??null:null}function lw(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function uw(e,t){return $n(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function dw(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 fw(e,t,n,r,o){let i=new Set,s=Fl(e,n);s&&o?.identity.key===s.identity.key&&i.add("children");for(let a of r.values()){let c=a?.chain.find(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 Fl(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if($n(r.tag))return r;n=r.parentKey}return null}function $n(e){return/^[A-Z]/.test(e)}function pw(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function mw(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}function Zg(e){let t=e.isRepeat??(e.graph?kw(e.element,e.graph):!1),n=e.propertyProvenance??new Map,r=e.repeatTargets??new Map,o=vw(e.element.attributes??[]),i=[...r.values()].some(d=>d.ok),s=o.map(d=>gw({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:Iw(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 gw(e){let{attribute:t,provenance:n,repeatTarget:r}=e,o=e.selectionRef?.instanceIndex!==void 0&&r?.ok===!0?r:null,i=hw(t,n,e.isRepeat),s=["selection","template"].map(b=>({scope:b,result:es({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=yw(t,n,l,e.isRepeat),f=c?Sw(c,e.element,t.name):void 0,m=s.filter(({result:b})=>b.ok).map(({scope:b})=>b),u=m.length>0?bw(n,o,e.element):"unsupported",g=o?"repeat-item":e.isRepeat?"repeat-template":"node",h=Ew(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 hw(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 yw(e,t,n,r){return n?Gg(n.selectedResolution):t?.status==="blocked"?{status:"unresolved"}:r&&t?.status==="binding"?{status:"unresolved"}:Gg(xw(e))}function xw(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 Gg(e){return!e||e.status==="unresolved"?{status:"unresolved"}:e.status==="undefined"?{status:"undefined"}:{status:"resolved",value:e.value}}function bw(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 Sw(e,t,n){return e.kind==="repeat-property"?{kind:"value-path",file:e.target.sourceFile,isProxy:e.target.sourceFile!==t.sourceFile,displayPath:Yg({...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:Yg(e.locator)}:{kind:"jsx-node",file:t.sourceFile,isProxy:!1,displayPath:t.componentName+" > "+n}}function Ew(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 vw(e){let t=new Set;return e.filter(n=>t.has(n.name)?!1:(t.add(n.name),!0))}function kw(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 Yg(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 Iw(e,t){if(!t)return{start:e.startColumn,end:e.endColumn};let n=t.split(`
|
|
7
|
+
`),r=(o,i)=>n.slice(0,Math.max(0,o-1)).reduce((s,a)=>s+a.length+1,0)+i;return{start:r(e.startLine,e.startColumn),end:r(e.endLine,e.endColumn)}}function Cw(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var Rw=160;function Qg(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 qg(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=oh(m.textSegments,s),b=ih(e,t,m,g,h),E=h?Aw(h):void 0,y=Tw(i,h),k=m.textSegments.map(R=>({index:R.index,value:R.value,editable:sh(R,g,s?.get(R.index)??null),source:o.get(R.index)??null})),C=nh(m,t),N=m.childKeys.map(R=>{let A=t.elements.get(R);return A?{key:R,tag:A.tag,label:A.tag}:null}).filter(R=>R!==null),T=[];if(m.parentKey){let R=t.elements.get(m.parentKey);if(R)for(let A of R.childKeys){if(A===e)continue;let M=t.elements.get(A);M&&T.push({key:A,tag:M.tag,label:M.tag})}}return{composition:f,key:e,tag:m.tag,componentName:m.componentName,sourceFile:m.sourceFile,sourceLocator:th(m),label:m.tag,capabilities:b,writeTarget:i,effectiveWriteTarget:y,provenanceChain:E,componentSemantic:c,styleSource:l,conditional:a,...d?{dynamicData:d}:{},textSegments:k,boundaryKind:m.boundaryKind,isOpaque:m.isOpaque,ancestors:C,children:N,siblings:T}}function eh(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=oh(l.textSegments,i),u=ww(l);return{composition:c,key:e,tag:l.tag,...u?{linkSourceKind:u}:{},componentName:l.componentName,sourceFile:l.sourceFile,sourceLocator:th(l),label:l.tag,capabilities:ih(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:sh(g,f,i?.get(g.index)??null),source:h?{kind:h.kind}:null}}),boundaryKind:l.boundaryKind,isOpaque:l.isOpaque,ancestors:nh(l,t)}}function ww(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 th(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:Nw(e.sourceRange),structuralPath:e.identity.structuralPath,...Pw(e.textSegments)}}function nh(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 Nw(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function Pw(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,Rw)}:{}}function rh(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 oh(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function ih(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&&ah(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 sh(e,t,n){return!e.editable||!t.canUpdateText?!1:n?ah(n.editMode):!0}function ah(e){return e==="direct"||e==="proxy"||e==="upstream"}function Aw(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 Tw(e,t){return t?.finalSource?t.finalSource.kind==="jsx-literal"?{kind:"jsx-node",file:e.file,isProxy:e.isProxy}:t.finalSource.kind==="config-entry"&&t.finalSource.locator?{kind:"value-path",file:t.finalSource.file,isProxy:t.finalSource.file!==e.file,displayPath:t.finalSource.displayPath}:Cw(t.finalSource.kind)?{kind:"external-entry",file:t.finalSource.file,isProxy:!1,displayPath:t.finalSource.displayPath,sourceType:t.finalSource.externalSource?.sourceType,sourceId:t.finalSource.externalSource?.sourceId}:{kind:"value-path",file:t.finalSource.file,isProxy:t.finalSource.file!==e.file,displayPath:t.finalSource.displayPath}:{kind:e.kind==="route-export"?"route-export":"jsx-node",file:e.file,isProxy:e.isProxy}}var _l=["set-class-name-source","apply-style-draft"];function ch(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:_l,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element"}]};if(t.resolution&&t.resolution.status!=="resolved")return{kind:"class-name-source",className:"",sourceKind:"dynamic-expression",editable:!1,operationBoundary:[],sourcePath:t.source?.expression,diagnostics:[{code:"dynamic-binding",message:"Style binding is unresolved and cannot be edited"}]};if(t.source?.expression){let n=t.source.expression,r=typeof t.resolvedValue=="string"?t.resolvedValue:t.value!==n?t.value:void 0;return typeof r!="string"?{kind:"class-name-source",className:"",sourceKind:"dynamic-expression",editable:!1,operationBoundary:[],sourcePath:n,diagnostics:[{code:t.resolvedValue===void 0?"dynamic-binding":"non-string-binding",message:t.resolvedValue===void 0?"Style binding is dynamic and cannot be edited":"Style binding must resolve to a static string before it can be edited"}]}:{kind:"class-name-source",className:r,sourceKind:"static-expression",editable:!0,operationBoundary:_l,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:_l}}function lh(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}),uh(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function uh(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}),uh(s,t,n,r,o))}}import dh from"node:path";function Ol(){let e=Promise.resolve();return{async runExclusive(t){let n,r=new Promise(i=>{n=i}),o=e;e=o.then(()=>r,()=>r),await o;try{return await t()}finally{n()}}}}async function ph(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=Ow(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 Es(e){let t=()=>Fw(e);return e.mutex?e.mutex.runExclusive(t):t()}async function Fw(e){let t=await ph(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=_w(e.overlay,t.plan),r;try{r=await e.buildCandidate({overlay:n,plan:t.plan})}catch(l){return{ok:!1,stage:"build",reason:"Candidate build failed.",error:l,recoveryRequired:!1}}let o,i;try{o=await e.prepareHistory?.({candidate:r,plan:t.plan}),await e.reverify?.({candidate:r,plan:t.plan,history:o}),i=await e.writeCandidate({candidate:r,plan:t.plan}),await e.markCandidateWritten?.({candidate:r,plan:t.plan,history:o,receipt:i})}catch(l){return Ml({candidate:r,plan:t.plan,failedStage:"commit",error:l,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let s=r;try{let l=await e.validateCandidate({candidate:r,plan:t.plan,receipt:i});l!==void 0&&(s=l)}catch(l){return Ml({candidate:r,plan:t.plan,failedStage:"validate",error:l,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let a;try{a=await e.publishCandidate({candidate:s,plan:t.plan,history:o,receipt:i})}catch(l){return Ml({candidate:s,plan:t.plan,failedStage:"publish",error:l,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let c={candidate:s,plan:t.plan,history:o,receipt:i,published:a};try{await e.swapCandidate?.(c)}catch(l){return fh("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return fh("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 _w(e,t){let n=new Map(e);for(let r of t.intents)r.kind==="delete"?n.delete(r.path):n.set(r.path,r.content);return n}function Ml(e){return e.rollbackCandidate({candidate:e.candidate,plan:e.plan,failedStage:e.failedStage,error:e.error,...e.history===void 0?{}:{history:e.history},...e.receipt===void 0?{}:{receipt:e.receipt}}).then(()=>({ok:!1,stage:e.failedStage,reason:Mw(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 fh(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function Mw(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 Ow(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)||dh.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=dh.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 Lw=50,Dw=8*1024*1024;function yh(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??Lw),s=Math.max(0,t.maxUndoBytes??Dw);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:d,redo:f};async function a(R){let A=[...R.steps].sort((se,oe)=>se.order-oe.order),M=A.filter(se=>se.type!=="invoke-external-adapter");if(M.length!==A.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let D=new Set(M.map(se=>se.file)),L=await y(D),ee=new Map(L.map(se=>[se.file,se.exists===!1?"":se.content])),ge;for(let se of M){let oe=hh(se,ee.get(se.file)??"");if(!oe.ok)return{ok:!1,errorCode:oe.errorCode,reason:oe.reason};ee.set(se.file,oe.source),ge=oe.selectionRef??ge}return{ok:!0,filePlan:{operationId:R.operationId,kind:"source-edit",target:R.target,documentVersion:R.documentVersion,conflictPolicy:"compare-and-swap",edits:[...ee].map(([se,oe])=>({operation:"upsert",file:se,content:oe,baseContentHash:L.find(Oe=>Oe.file===se)?.sha256??null}))},...ge?{selectionRef:ge}:{}}}async function c(R){let A=[...R.steps].sort((Oe,Nt)=>Oe.order-Nt.order),M=A.filter(Oe=>Oe.type!=="invoke-external-adapter"),D=A.filter(Oe=>Oe.type==="invoke-external-adapter"),L=new Set(M.map(Oe=>Oe.file));if(M.length>0&&D.length>0)return{ok:!1,operationId:R.operationId,errorCode:"unsupported-operation",reason:"Mixed local file rewrites and external adapter writes require an explicit compensation contract.",rolledBack:!1};if(M.length===0)return b(R,D);let ee=await y(L),ge=new Map;for(let Oe of ee)ge.set(Oe.file,Oe.exists===!1?"":Oe.content);let se;for(let Oe of M){let Nt=ge.get(Oe.file)??"",qt=hh(Oe,Nt);if(!qt.ok)return{ok:!1,operationId:R.operationId,errorCode:qt.errorCode,reason:qt.reason,rolledBack:!1};ge.set(Oe.file,qt.source),qt.selectionRef&&(se=qt.selectionRef)}let oe=await C([...ge].map(([Oe,Nt])=>({file:Oe,content:Nt,exists:!0,version:0,sha256:Ie(Nt)})),ee);return oe.ok===!1?{ok:!1,operationId:R.operationId,errorCode:oe.rolledBack?"writeback-failed":"rollback-failed",reason:oe.reason,rolledBack:oe.rolledBack}:(n.push({operationId:R.operationId,preSnapshots:ee,postSnapshots:oe.snapshots,plan:R}),m(),r.length=0,{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:Math.max(...oe.snapshots.map(Oe=>Oe.version)),affectedFiles:[...L],...se?{selectionRef:se}:{}})}async function l(R){let A=new Set(R.edits.map(oe=>oe.file)),M=await y(A),D=E(R,M);if(D)return{ok:!1,operationId:R.operationId,errorCode:"stale-version",reason:D.reason,affectedFiles:[D.file],rolledBack:!1};let L=new Map(M.map(oe=>[oe.file,oe])),ee=R.edits.find(oe=>oe.operation==="create-only"&&L.get(oe.file)?.exists!==!1);if(ee)return{ok:!1,operationId:R.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${ee.file}`,affectedFiles:[ee.file],rolledBack:!1};let ge=R.edits.map(oe=>oe.operation==="delete"?{file:oe.file,content:"",exists:!1,version:0}:{file:oe.file,content:oe.content,exists:!0,version:0,sha256:Ie(oe.content)}),se=await C(ge,M,new Set(R.edits.filter(oe=>oe.operation==="create-only").map(oe=>oe.file)));return se.ok===!1?{ok:!1,operationId:R.operationId,errorCode:se.rolledBack?"writeback-failed":"rollback-failed",reason:se.reason,rolledBack:se.rolledBack}:(n.push({operationId:R.operationId,preSnapshots:M,postSnapshots:se.snapshots,plan:{operationId:R.operationId,kind:R.kind,target:R.target,documentVersion:R.documentVersion,steps:[],preSnapshots:M}}),m(),r.length=0,{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:Math.max(...se.snapshots.map(oe=>oe.version)),affectedFiles:[...A]})}async function d(){let R=n.at(-1);if(!R)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let A=await C(R.preSnapshots,R.postSnapshots);return A.ok===!1?{ok:!1,operationId:R.operationId,errorCode:A.rolledBack?"writeback-failed":"rollback-failed",reason:A.reason,rolledBack:A.rolledBack}:(n.pop(),r.push(R),{ok:!0,operationId:R.operationId,kind:R.plan.kind,target:R.plan.target,resultVersion:Math.max(...A.snapshots.map(M=>M.version)),affectedFiles:R.preSnapshots.map(M=>M.file)})}async function f(){let R=r.at(-1);if(!R)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let A=await C(R.postSnapshots,R.preSnapshots);return A.ok===!1?{ok:!1,operationId:R.operationId,errorCode:A.rolledBack?"writeback-failed":"rollback-failed",reason:A.reason,rolledBack:A.rolledBack}:(r.pop(),n.push(R),m(),{ok:!0,operationId:R.operationId,kind:R.plan.kind,target:R.plan.target,resultVersion:Math.max(...A.snapshots.map(M=>M.version)),affectedFiles:R.postSnapshots.map(M=>M.file)})}function m(){for(;n.length>i;)n.shift();for(;n.length>0&&u()>s;)n.shift()}function u(){return n.reduce((R,A)=>R+g(A),0)}function g(R){return h(R.preSnapshots)+h(R.postSnapshots)}function h(R){return R.reduce((A,M)=>A+M.file.length+M.content.length,0)}async function b(R,A){let M=[];for(let D of A){let L=D.capability??"write-text",ee=o.find(se=>se.sourceType===D.sourceType&&(D.adapterId===void 0||se.adapterId===D.adapterId)&&(se.capabilities===void 0||se.capabilities.includes(L)));if(!ee)return{ok:!1,operationId:R.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${D.sourceType}`,rolledBack:!1};let ge=await ee.execute(D);if(!ge.ok)return{ok:!1,operationId:R.operationId,errorCode:"writeback-failed",reason:ge.reason??`External adapter failed for ${D.sourceType}`,rolledBack:!1};M.push(D.file)}return{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:0,affectedFiles:M}}function E(R,A){if(R.conflictPolicy!=="compare-and-swap")return null;let M=new Map(A.map(D=>[D.file,D]));for(let D of R.edits){if(D.operation==="create-only")continue;if(D.baseContentHash===void 0)return{file:D.file,reason:`Source file ${D.file} is missing baseContentHash. Reopen the file before saving.`};let L=M.get(D.file),ee=D.baseContentHash;if(ee===null){if(L?.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(L?.exists===!1||L?.sha256!==ee)return{file:D.file,reason:`Source file ${D.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function y(R){let A=[];for(let M of R)A.push(await k(M));return A}async function k(R){if(!await e.exists(R))return{file:R,content:"",version:0,exists:!1};let M=Math.max(1,e.getVersion(R)),D=await e.readFile(R);return{file:R,content:D,version:M,exists:!0,sha256:Ie(D)}}async function C(R,A,M=new Set){let D=[];try{for(let L of R){if(M.has(L.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive(L.file,L.content)}else await N(L);let ee=e.bumpVersion(L.file);D.push(L.file),L.version=ee}}catch(L){let ee=await T(A.filter(se=>D.includes(se.file)));if(ee.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${ee.failedFiles.join(", ")}: ${gh(L)}`,rolledBack:!1,instanceConflict:mh(L)};let ge=mh(L);return{ok:!1,reason:`${ge?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${gh(L)}`,rolledBack:!0,instanceConflict:ge}}return{ok:!0,snapshots:R.map(Bw)}}async function N(R){if(R.exists===!1){await e.deleteFile(R.file);return}await e.writeFile(R.file,R.content)}async function T(R){let A=[];for(let M of R)try{await N(M),e.bumpVersion(M.file)}catch{A.push(M.file)}return A.length===0?{ok:!0}:{ok:!1,failedFiles:A}}}function mh(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function Bw(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:Ie(e.content)}:{}}}function gh(e){return e instanceof Error?e.message:String(e)}function hh(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(ei({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return We(Mr({source:t,locator:e.locator,next:e.value}));case"update-array-item":return We(Mr({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return We(ai({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return We(ni({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return We(ci({source:t,locator:e.locator,index:e.index}));case"move-array-item":return We(li({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return We(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(ri({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,repeatExpression:e.repeatExpression,selectionContext:e.selectionContext}));case"set-class-name-source":return jw(e,t);case"set-property-changes":return We(oi({source:t,locator:e.locator,changes:e.changes}));case"set-link-target":return We(ii({source:t,locator:e.locator,link:e.link,changes:e.changes}));case"set-property-binding":return We(si({source:t,locator:e.locator,name:e.name,object:e.object,property:e.property}));case"upsert-object-property":return We(di({source:t,objectLocator:e.locator,name:e.name,value:e.value}));default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function jw(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!xd(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!==Ie(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:yd({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 vs,SiteEditCompositionContextSchema as $w,SiteEditCompositionSelectorSchema as Vw}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 xh(e,t){throw new Ye("INVALID_COMPOSITION",e,{value:t})}function ks(e){let t=$w.safeParse(e);return t.success?t.data:xh("Invalid SiteEditCompositionContext.",e)}function bh(e){let t=[],n=new Map,r=new Map;for(let l of e.compositions){let d=ks(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=vs(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=ks(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=vs(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=Vw.safeParse(l);if(!d.success)return xh("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=ks(l),f=vs(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=ks(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=vs(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))]}}function Ll(e){let t=new Map,n=new Map;return{readFile(r){let o=t.get(r);return o||(o=e.readFile(r),t.set(r,o)),o},exists(r){let o=n.get(r);return o||(o=e.exists(r),n.set(r,o)),o}}}async function Sh(e,t){if(e.length===0)return[];if(e.length===1)return[await t(e[0])];let n=new Array(e.length),r=[],o=0,i=Array.from({length:Math.min(4,e.length)},async()=>{for(;o<e.length&&r.length===0;){let c=o++;try{n[c]=await t(e[c])}catch(l){r.push({index:c,error:l})}}}),s=await Promise.allSettled(i),a=r.sort((c,l)=>c.index-l.index)[0];if(a)throw a.error;for(let c of s)if(c.status==="rejected")throw c.reason;return n}import{composeSiteEditRepeatInstanceKey as Kw,stripSiteEditRepeatInstanceKeys as Eh}from"@vcp-dev/contracts";function vh(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=Eh(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 Uw(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 Is(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=Is(e.collectionPathMap?.[t])??Is(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:Is(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>Is(o)??[])}}function kh(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)=>Kw(u,g),c=(u,g,h)=>{let b=o.get(u);if(!b)return a(u,h);let E=a(u,h),y={...b,key:E,parentKey:g,childKeys:[]};return i.push(y),y.childKeys=b.childKeys.flatMap(k=>l(k,h,E)),E},l=(u,g,h)=>{if(!r.has(u))return[c(u,h,g)];let b=f(u,g),E=[];for(let y=0;y<b;y+=1)E.push(c(u,h,[...g,y]));return E},d=Array.from(new Set([...e.rootKeys,...e.entries.filter(u=>u.parentKey===null).map(u=>u.key)]));for(let u of d){if(!r.has(u)){c(u,null,[]);continue}let g=f(u,[]);for(let h=0;h<g;h+=1)c(u,null,[h])}return{...e,rootKeys:[...e.rootKeys],entries:i};function f(u,g){let h=new Set;for(let b of m(u)){let E=n.get(b);if(E){for(let y of[...E.textTargets.values(),...E.elementPropertyTargets.values()])if(!(y?.kind!=="value-binding"||y.sourceKind!=="repeat-template"))for(let k of Jw(y))k.length<=g.length||Xw(k,g)&&h.add(k[g.length])}}return h.size>0?h.size:Uw(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 Ih(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function Ch(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((Eh(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function Jw(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 Xw(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 Rh(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 wh(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 Nh(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function zw(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var Po=class extends Error{constructor(t){let n=t.map(Nh);super(zw(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function Ph(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof Po?{routeId:e,message:n,diagnostics:t.diagnostics.map(Nh)}:{routeId:e,message:n}}function Bl(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function jl(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function Er(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function Ah(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function $l(e,t,n,r){if(!e.has(t)&&e.size>=r){let o=e.keys().next().value;o&&e.delete(o)}e.set(t,n)}function Th(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 eN=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,tN=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],Fh=32,Vl=256;function nN(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var _h={maxEntries:50,maxBytes:8*1024*1024};function rN(){let e=new Map;return{async readFile(t){return(await import("node:fs/promises")).readFile(t,"utf-8")},async readFileBytes(t){return(await import("node:fs/promises")).readFile(t)},async getFileInfo(t){let n=await import("node:fs/promises");try{let r=await n.lstat(t);return!r.isFile()||r.isSymbolicLink()?null:{path:t,sizeBytes:r.size}}catch{return null}},async writeFile(t,n){await pi(t,n)},async deleteFile(t){await(await import("node:fs/promises")).rm(t,{force:!0})},async exists(t){let n=await import("node:fs/promises");try{return await n.access(t),!0}catch{return!1}},getVersion(t){return e.get(t)??1},bumpVersion(t){let n=(e.get(t)??1)+1;return e.set(t,n),n}}}async function oN(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 iN(){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>_h.maxEntries||sN(e)>_h.maxBytes;)e.shift()}}function sN(e){return e.reduce((t,n)=>t+aN(n),0)}function aN(e){return Mh(e.preSnapshots)+Mh(e.postSnapshots)+cN(e.provenance)}function cN(e){return e?new TextEncoder().encode(JSON.stringify(e)).byteLength:0}function Mh(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function Oh(e,t){return{key:Hw(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 Rs=class extends Error{constructor(t){super(t.reason),this.result=t}},Vn=class extends Error{constructor(t){super(Bl(t)),this.failedRoutes=t}};function Lh(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=ot(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(ot(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}function lN(e,t,n){if(!n)return;let r=ot(n.key)??n.key;if(n.key!==e&&n.key!==t&&r!==t)throw new Error(`Selection reference '${n.key}' does not match selected key '${e}'`);if(n.instanceIndex!==void 0&&(!Number.isInteger(n.instanceIndex)||n.instanceIndex<0))throw new Error("Selection reference instanceIndex must be non-negative");if(n.instanceCount!==void 0&&(!Number.isInteger(n.instanceCount)||n.instanceCount<=0))throw new Error("Selection reference instanceCount must be positive");if(n.instanceIndex!==void 0&&n.instanceCount!==void 0&&n.instanceIndex>=n.instanceCount)throw new Error("Selection reference instanceIndex must be smaller than instanceCount");return{...n,key:t}}var uN=/\.(?:[cm]?[jt]sx?)$/i,dN=/\.json$/i,fN=/\.(?:css|scss|sass)$/i,pN=/\.mdx$/i,mN=/\.ya?ml$/i;function gN(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 hN(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function yN(e,t){let n=new Map;for(let i of t)n.set(i.path,i.operation==="delete"?{exists:!1}:{exists:!0,content:i.content});let r=new Map,o=new Map;return{async readFile(i){let s=n.get(i);if(s){if(!s.exists)throw new Error(`Source file not found: ${i}`);return s.content}let a=r.get(i);return a||(a=e.readFile(i),r.set(i,a)),a},async writeFile(){throw new Error("Source edit preflight overlay is read-only.")},async deleteFile(){throw new Error("Source edit preflight overlay is read-only.")},async exists(i){let s=n.get(i);if(s)return s.exists;let a=o.get(i);return a||(a=e.exists(i),o.set(i,a)),a},async getFileInfo(i){let s=n.get(i);return s?s.exists?{path:i,sizeBytes:Buffer.byteLength(s.content,"utf8")}:null:e.getFileInfo?.(i)??null},async listFiles(i={}){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let s=Kh(await e.listFiles(i)),a=new Map(s.files.map(l=>[l.path,l]));for(let[l,d]of n)if(xN(l,i.roots??[])){if(!d.exists){a.delete(l);continue}a.set(l,{path:l,sizeBytes:Buffer.byteLength(d.content,"utf8")})}let c=[...a.values()].sort((l,d)=>l.path.localeCompare(d.path));return s.truncated?{files:c,truncated:s.truncated}:c},getVersion(i){return e.getVersion(i)},bumpVersion(i){return e.getVersion(i)}}}function xN(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function Kh(e){return Array.isArray(e)?{files:e}:e}function bN(e){if(!Yw(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!==Qw||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=Gw(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(uN.test(e.path)){let t=At({source:e.content,profile:vn({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(dN.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(fN.test(e.path)){let t=Dh({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(pN.test(e.path)){let t=Dh({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(mN.test(e.path))try{qw(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${qe(t)}`,details:{path:e.path}}}return{ok:!0}}function Dh({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 vr(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 vr(t,`Unexpected closing token "${m}" in ${t}.`);l=!1;continue}l=m===`
|
|
14
|
-
`||m==="\r"}if(s)return vr(t,`Unterminated block comment in ${t}.`);if(o)return vr(t,`Unterminated string literal in ${t}.`);if(c)return vr(t,`Unterminated MDX code fence in ${t}.`);let d=r.at(-1);return d?vr(t,`Unclosed token "${d.char}" in ${t}.`):{ok:!0}}function vr(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function ws(e){let t="idle",n=e.fileSystem??nN(),r=bd(),o=xh({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?lf(e.historyStore):oN()),d=hh(n,{externalAdapters:e.externalAdapters}),f=new Map,m=Pd(Vl),u=new Set,g=0,h=e.historyStore?.recoveryRequired??!1,b=Ol(),E=N();function y(p){return(Cs.isAbsolute(p)?Cs.relative(e.projectRoot,p):p).replace(/\\/g,"/").replace(/^\.\//,"")}function k(p,S){let x=Cs.posix.dirname(p),I=S.replace(/\.(?:tsx?|jsx?)$/i,""),P=Cs.posix.relative(x,I);return P.startsWith(".")?P:`./${P}`}function C(p,S){return p.startLine===S.startLine&&p.startColumn===S.startColumn&&p.endLine===S.endLine&&p.endColumn===S.endColumn}async function N(){let p=e.historyStore;if(p)try{let S=await p.readTransactionJournal();if(!S)return;let x=await p.readIndex(),I=await Promise.all(S.files.map(async _=>await n.exists(_.path)?Ie(await n.readFile(_.path)):null));if(Ah({journal:S,index:x,observedFileDigests:I})!=="ambiguous"){await p.clearTransactionJournal(S.transactionId);let _=await p.readStatus();_.recoveryRequired||(await p.cleanupTmp(),_=await p.readStatus()),h=_.recoveryRequired;return}await p.markRecoveryRequired(`Ambiguous transaction journal ${S.transactionId} at phase ${S.phase}`),h=!0}catch(S){h=!0,await p.markRecoveryRequired(`Transaction journal recovery failed: ${qe(S)}`).catch(()=>{})}}function T(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let p of o.entries){let S=Mh(p.context,p.entryFile);i.set(p.key,S),R(S,S.dependencyFiles)}function R(p,S){let x=new Set(S);A(p),p.dependencyFiles=x;for(let I of p.dependencyFiles){let P=s.get(I);P||(P=new Set,s.set(I,P)),P.add(p.key)}}function A(p){for(let S of p.dependencyFiles){let x=s.get(S);x&&(x.delete(p.key),x.size===0&&s.delete(S))}p.dependencyFiles.clear()}function M(p){let S=new Set;for(let x of p)for(let I of s.get(x)??[])S.add(I);return S}function D(p){for(let S of p)if(!s.has(S))return!1;return!0}async function L(p,S,x,I,P,_){let F=new Map,j=Wg(p),W=Lg(P.values()),K=Om(P.values()),B=typeof _.exists=="function"?Z=>_.exists(Z):async()=>!1;for(let[Z,te]of p.elements){let he=S.nodes.get(Z);if(!he)continue;let pe=x.get(te.sourceFile)??I.get(te.sourceFile),ke=new Map,Pe=new Map,O=new Map,U=[];for(let Ne of te.textSegments){if(!pe){ke.set(Ne.index,null);continue}let kr=await Dg({file:te.sourceFile,source:pe,segment:Ne,readFile:st=>_.readFile(st),exists:B,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:st,adapterId:xn,capabilities:Bs})=>({sourceType:st,adapterId:xn,capabilities:Bs})),functionCallContracts:e.functionCallContracts,fileCache:W}),Ze=await Rl({file:te.sourceFile,source:pe,target:{kind:"text-segment",segment:Ne},readFile:st=>_.readFile(st),exists:B,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:st,adapterId:xn,capabilities:Bs})=>({sourceType:st,adapterId:xn,capabilities:Bs})),functionCallContracts:e.functionCallContracts,fileCache:W}),ft=mN(kr);ke.set(Ne.index,ft),Pe.set(Ne.index,kr),O.set(Ne.index,Ze),U.push({editable:Ne.editable,source:ft})}let ae=new Map,me=new Map;if(pe)for(let Ne of te.attributes??[]){let kr=await Sr({file:te.sourceFile,source:pe,sourceRange:Ne.sourceRange,expression:Ne.source?.expression??Ne.value,sourceInfo:Ne.source,readFile:ft=>_.readFile(ft),exists:B,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:ft,adapterId:st,capabilities:xn})=>({sourceType:ft,adapterId:st,capabilities:xn})),functionCallContracts:e.functionCallContracts,fileCache:W}),Ze=await zg({element:te,file:te.sourceFile,source:pe,propertyName:Ne.name,readFile:ft=>_.readFile(ft),exists:B,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:ft,adapterId:st,capabilities:xn})=>({sourceType:ft,adapterId:st,capabilities:xn})),functionCallContracts:e.functionCallContracts,fileCache:W});me.set(Ne.name,Ze),ae.set(Ne.name,kr)}let Se=nh(gN(he.writeTarget),U),Ae=j({key:Z,element:te,provenances:O}),en=ah(te),it=pe?await Lm({element:te,graph:p,file:te.sourceFile,source:pe,readFile:Ne=>_.readFile(Ne),exists:B,fileCache:K}):void 0,Wn=p.regions.find(Ne=>Ne.kind==="conditional-region"&&Ne.childKeys.includes(Z)),cu,Ds=Wn?.sourceCandidates?.[0];if(pe&&Wn&&Ds?.kind==="conditional-branch"){let Ne=await Rl({file:te.sourceFile,source:pe,target:{kind:"conditional-branch",candidate:Ds},readFile:Ze=>_.readFile(Ze),exists:B,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Ze,adapterId:ft,capabilities:st})=>({sourceType:Ze,adapterId:ft,capabilities:st})),functionCallContracts:e.functionCallContracts,fileCache:W});cu={currentBranch:Wn.childKeys.indexOf(Z)<=0?"then":"else",availableBranches:Wn.childKeys.length>1?["then","else"]:["then"],conditionExpression:Ds.conditionExpression,provenance:{finalSource:Ne.finalSource?{kind:Ne.finalSource.kind,file:Ne.finalSource.file,displayPath:Ne.finalSource.displayPath}:null,chain:Ne.chain.map(Ze=>({kind:Ze.kind,file:Ze.file,displayName:Ze.displayName,canEditHere:Ze.canEditHere})),confidence:Ne.confidence,editMode:Ne.editMode,diagnostics:Ne.diagnostics.map(Ze=>({code:Ze.code,message:Ze.message}))}}}F.set(Z,{textSources:ke,textTargets:Pe,elementPropertyTargets:ae,propertyProvenances:me,isRepeat:MN(Z,p),provenances:O,writeTarget:Se,componentSemantic:Ae,styleSource:en,conditional:cu,dynamicData:it})}return F}function ee(p){return typeof n.getVersion=="function"?n.getVersion(p):0}function ge(p,S){let x=o.initialVersions.get(p.key)??0;for(let I of S.values())x=Math.max(x,I);return Math.max(x,p.graph?.version??0)}function se(p){return i.get(p)?.graph?.version??o.initialVersions.get(p)??0}function oe(p){try{return se(o.resolveSelector(p.composition).key)}catch{return 0}}async function Oe(p,S,x=n,I={}){let P=await Nd(p,S,_=>x.readFile(_),_=>x.exists(_),{additionalEntries:await qt(p,x),...I});if(P.diagnostics.length>0)throw new Po(P.diagnostics);return I.validationOnly||m.remember(P.parsedModules.values()),P}async function Nt(p,S,x={}){let I=i.get(p);if(!I)return null;let P=x.sourceCache??jl(f,[]),_=x.fileSystem??Ll(n),{graph:F,allSources:j,parsedModules:W,entryModule:K}=await Oe(I.entryFile,S,_,{version:I.graph?.version??1}),B=new Map;for(let it of j.keys())B.set(it,ee(it));let Z=Math.max(ge(I,B),x.minimumVersion??0);x.changed&&Z<=(I.graph?.version??0)&&(Z=(I.graph?.version??0)+1),F.version=Z;for(let[it,Wn]of j)$l(P,it,Wn,Vl);let te=await Jh(I.composition,I.entryFile,j,P,_);F.routeId=I.routeId,F.composition=I.composition;let he=ch(F),pe=md(he,F),ke=await L(F,he,j,P,W,_),Pe=Wh(F,pe,ke),O=zh(ke),U=vh(Zg(F,he,pe,{canUpdateTextByKey:Pe,dynamicDataSummaryByKey:O}),F,ke),ae=zf({route:I.routeId,composition:I.composition,entryFile:I.entryFile,version:Z,source:S,ast:K?.ast}),me=Wf(ae);ae.ok&&SN(U,F,ae.projection,W);let Se={...U,composition:I.composition,...te?{styleContext:te}:{},pageComposition:me},Ae=new Set([I.entryFile,...j.keys()]);if(te){Ae.add(te.entryCss.path);for(let it of te.stylesheets)Ae.add(it.path)}let en={...I,dependencyFiles:Ae,graph:F,topology:he,capabilities:pe,document:Se,pageComposition:me,pageCompositionProjection:ae.projection,pagePlacementByKey:ae.ok?ae.projection.placementByKey:null,pagePlacementUnitByKey:ae.ok?ae.projection.placementUnitByKey:null,pageUnitByKey:ae.ok?ae.projection.unitByKey:null,pagePlacementsByUnitKey:ae.ok?ae.projection.placementsByUnitKey:null,documentIndex:Eh(Se),detailProjections:ke,fileVersions:B,styleContext:te};if(x.publish===!1)return en;Er(f,P);for(let it of P.keys())u.delete(it);return R(I,Ae),Object.assign(I,en),I}async function qt(p,S=n){let x=[];for(let I of NN(p))typeof S.exists=="function"&&await S.exists(I)&&x.push({file:I,source:await S.readFile(I)});return x}async function Jh(p,S,x,I,P){let _=[];for(let[B,Z]of x){if(Kl(B)){_.push(B);continue}for(let te of AN(Z)){let he=$h(B,te);he&&_.push(he)}}if(!_.length){for(let B of PN(S))if(await P.exists(B)){_.push(B);break}}let F=new Map,j=_N(_).slice(0,Th);for(;j.length>0&&F.size<Th;){let B=j.shift();if(F.has(B)||!Kl(B))continue;let Z=await Xh(B,I,P);if(Z!==null){F.set(B,{path:B,content:Z});for(let te of TN(Z)){let he=$h(B,te);he&&!F.has(he)&&!j.includes(he)&&j.push(he)}}}let W=[...F.values()].map(B=>({...B,hash:Ie(B.content)})),K=W[0];return K?{composition:p,revision:Ie(JSON.stringify(W.map(({path:B,hash:Z})=>({path:B,hash:Z})))),entryCss:K,stylesheets:W.slice(1)}:null}async function Xh(p,S,x){let I=S.get(p);if(I!==void 0)return I;if(!await x.exists(p))return null;let P=await x.readFile(p);return $l(S,p,P,Vl),P}function zh(p){let S=new Map;for(let[x,I]of p)I.dynamicData?.bindings.length&&S.set(x,Hm(I.dynamicData.bindings));return S}function Wh(p,S,x){let I=new Map;for(let[P,_]of p.elements){if(!S.get(P)?.canUpdateText){I.set(P,!1);continue}let j=x.get(P),W=_.textSegments.some(K=>{if(!K.editable)return!1;let B=j?.provenances.get(K.index)??null;return!B||Hh(B)});I.set(P,W)}return I}function Hh(p){return p.editMode==="direct"||p.editMode==="proxy"||p.editMode==="upstream"}async function Fo(p,S={}){let x=[...new Set(p)],I=S.affectedCompositionKeys!==void 0,P=I?new Set(S.affectedCompositionKeys):M(x);if(!I&&(P.size===0||!D(x)))for(let K of i.values())Jl(K,x)&&P.add(K.key);let _=!I&&P.size===0&&x.some(jh),F=S.publish===!1?jl(f,x):void 0,j={rebuiltRoutes:[],failedRoutes:[],...S.publish===!1?{candidateRouteStates:[],candidateSourceCache:F}:{}},W=Ll(n);for(let K of i.values())if(!(S.excludedCompositionKeys?.has(K.key)||!(P.has(K.key)||_)))try{let Z=!!K.graph,te=await W.readFile(K.entryFile),he=await Nt(K.key,te,{...S,fileSystem:W,...F?{sourceCache:F}:{}});he?.graph&&(j.rebuiltRoutes.push({documentChanged:Z,composition:K.composition,routeId:K.routeId,version:he.graph.version}),j.candidateRouteStates?.push({composition:K.composition,key:K.key,routeId:K.routeId,state:he}))}catch(Z){j.failedRoutes.push({...Nh(K.routeId,Z),composition:K.composition})}return j}function Un(p){let S=[...new Set(p)],x=M(S);if(x.size>0&&D(S))return[...x];for(let I of i.values())Jl(I,S)&&x.add(I.key);return[...x]}function Gh(p){let S=new Set(Un(p));return o.entries.filter(x=>S.has(x.key)).map(x=>x.context)}function Yh(p){return[...new Set(Un(p))].sort((x,I)=>x<I?-1:x>I?1:0).map(x=>o.getByKey(x)?.context).filter(x=>x!==void 0)}function Zh(p,S){let x=new Set(Un(S)),I=p.provenance?.affectedCompositions??[];if(I.length===0)return x;if([...new Set(I.map(_=>o.resolveContext(_).key))].some(_=>!x.has(_)))throw new Error("History provenance does not match the affected composition index.");return x}function Qh(p,S){let x=p.composition??p.provenance?.initiatingComposition;if(x){let _=o.resolveContext(x);return{context:_.context,key:_.key}}let I=[...new Set(Un(S))];if(I.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${I.length}).`);let P=o.getByKey(I[0]);if(!P)throw new Error("Legacy history entry references an unknown affected composition.");return{context:P.context,key:P.key}}function Ts(p,S){r.emit({type:"operation-completed",composition:p.composition,result:p});for(let{composition:x,version:I}of S.rebuiltRoutes)r.emit({type:"document-changed",composition:x,version:I});for(let{composition:x,message:I}of S.failedRoutes)r.emit({type:"graph-error",composition:x,message:I})}function Jl(p,S){return S.some(x=>p.dependencyFiles.has(x)||p.entryFile===x||p.graph?.fileIndex.has(x))}function Xl(p){for(let S of p)a.add(S);c||T()||(c=(async()=>{t="building";let S=!1;try{for(;a.size>0;){if(T())return;await qh(),await b.runExclusive(async()=>{if(g>0||T())return;let x=[...a];a.clear();let I=await zl(x);if(I.length===0)return;let P=Un(I);for(let j of P){let W=i.get(j)?.composition;W&&r.emit({type:"graph-invalidated",composition:W})}let{rebuiltRoutes:_,failedRoutes:F}=await Fo(I,{changed:!0});for(let{documentChanged:j,composition:W,version:K}of _)r.emit({type:"graph-ready",composition:W,version:K}),j&&r.emit({type:"document-changed",composition:W,version:K});for(let{composition:j,message:W}of F)S=!0,r.emit({type:"graph-error",composition:j,message:W})})}}finally{c=null,t!=="disposed"&&(t=!S&&[...i.values()].some(x=>x.graph)?"ready":"idle"),a.size>0&&Xl([])}})())}async function qh(){for(;g>0;)await new Promise(p=>setTimeout(p,0))}async function zl(p){let S=[];for(let x of new Set(p)){let I=f.get(x);if(I===void 0){if(u.has(x)&&!await n.exists(x))continue;u.delete(x),S.push(x);continue}try{await n.readFile(x)!==I&&(u.delete(x),S.push(x))}catch(P){if(!bN(P))try{if(await n.exists(x))continue}catch{continue}u.add(x),S.push(x)}}return S}function Wl(p){Ph(f,p);for(let S of p)S.exists===!1?u.add(S.file):u.delete(S.file)}function Hl(p){u.clear();for(let S of p)u.add(S)}async function Gl(p){let S=await zl(p);if(S.length===0)return;let x=Un(S);for(let _ of x){let F=i.get(_)?.composition;F&&r.emit({type:"graph-invalidated",composition:F})}let{rebuiltRoutes:I,failedRoutes:P}=await Fo(S,{changed:!0});for(let{documentChanged:_,composition:F,version:j}of I)r.emit({type:"graph-ready",composition:F,version:j}),_&&r.emit({type:"document-changed",composition:F,version:j});for(let{composition:_,message:F}of P)r.emit({type:"graph-error",composition:_,message:F})}async function ey(p,S){let x=zn(p,S);if(!x?.graph)return;let I=ot(p)??p,P=x.graph.elements.get(I);P&&await Gl([P.sourceFile])}async function Yl(p){let S=new Set;if(p.target.kind==="node"){let x=zn(p.target.key,p.composition),I=ot(p.target.key)??p.target.key,P=x?.graph?.elements.get(I);P&&S.add(P.sourceFile)}else if(p.target.kind==="route"){let x=i.get(o.resolveSelector(p.target.composition).key);x&&S.add(x.entryFile)}else if(p.target.kind==="page-unit"){let x=i.get(o.resolveSelector(p.target.composition).key);x&&S.add(x.entryFile)}else if(p.target.kind==="source-file")S.add(p.target.path);else if(p.target.kind==="source-batch")for(let x of p.target.paths)S.add(x);if(p.params.kind==="move-node"&&!("kind"in p.params.target)){let x=[p.params.target.parentKey,...p.params.target.relation==="before"||p.params.target.relation==="after"?[p.params.target.anchorKey]:[]];for(let I of x){let P=zn(I,p.composition),_=ot(I)??I,F=P?.graph?.elements.get(_);F&&S.add(F.sourceFile)}}await Gl(S)}async function ty(p){if(p.params.kind!=="source-edit")return Fs(p,"invalid-params","source-edit requires source-edit params");for(let S of p.params.edits){let x=xN(S);if(!x.ok)return Fs(p,x.errorCode,x.message,x.details)}g+=1;try{let S=await sy(p.params.edits);if(!S.ok)return Fs(p,S.errorCode,S.message,S.details);await Yl(p);let x={operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:p.params.conflictPolicy,edits:p.params.edits.map(I=>I.operation==="delete"?{operation:"delete",file:I.path,baseContentHash:I.baseContentHash??null}:{operation:"upsert",file:I.path,baseContentHash:I.baseContentHash??null,content:I.content})};return await Xn({request:p,filePlan:x})}catch(S){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:oe(p),error:{code:V.INTERNAL_ERROR,message:qe(S)}}}finally{g-=1}}async function ny(p){if(p.target.kind!=="project"||p.params.kind!=="insert-page-resource")return ue(p,V.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");g+=1;try{let S=await Lo({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:[...p.params.artifact.components.flatMap(I=>I.materialization.files.map(P=>({path:P.pathTemplate,content:P.content}))),...p.params.artifact.pages.flatMap(I=>I.materialization.files.map(P=>({path:P.pathTemplate,content:P.content})))],exists:I=>n.exists(I),readFile:I=>n.readFile(I)});if(!S.ok)return ue(p,V.MATERIALIZATION_REJECTED,S.message);let x=await Za({artifact:p.params.artifact,exists:I=>n.exists(I)});return x.ok?await Xn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:"overwrite",edits:x.files},output:{kind:"insert-page-resource",package_instance_id:x.packageInstanceId,pages:x.pages},historyPolicy:"none"}):ue(p,x.code==="MATERIALIZATION_CONFLICT"?V.MATERIALIZATION_CONFLICT:V.MATERIALIZATION_REJECTED,x.message,x.path?{path:x.path}:void 0)}catch(S){return ue(p,V.INTERNAL_ERROR,qe(S))}finally{g-=1}}async function ry(p){if(p.target.kind!=="project"||p.params.kind!=="delete-page-source")return ue(p,V.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return ue(p,V.PLAN_FAILED,"Complete project file listing is required for page deletion.");g+=1;try{let S=Vh(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(S.truncated)return ue(p,V.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:S.truncated.reasons});let x=S.files.filter(({path:F})=>/\.(?:tsx?|jsx?)$/.test(F)),I=Object.fromEntries(await Promise.all(x.map(async({path:F})=>[F,await n.readFile(F)]))),P=hp({expectedUrlPath:p.params.expectedUrlPath,files:I});if(!P.ok)return ue(p,P.code==="HOME_PAGE_LOCKED"?V.HOME_PAGE_LOCKED:P.code==="ROUTE_NOT_FOUND"?V.ROUTE_NOT_FOUND:V.PLAN_FAILED,P.message);let _=await Promise.all(P.edits.map(async F=>({...F,baseContentHash:Ie(await n.readFile(F.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:P.deletedFiles,updated_files:P.updatedFiles,preserved_shared_files:P.preservedSharedFiles,warnings:P.warnings},historyPolicy:"none"})}catch(S){return ue(p,V.INTERNAL_ERROR,qe(S))}finally{g-=1}}async function oy(p,S){if(p.kind!=="insert-child"&&p.kind!=="replace-node")return ue(p,V.UNSUPPORTED_OPERATION,"Only page-unit insert-child and replace-node materialization are supported by this transaction.");if(p.params.kind!=="insert-child"&&p.params.kind!=="replace-node"||p.kind!==p.params.kind)return ue(p,V.INVALID_PARAMS,"Page-unit materialization operation kind must match its params.");if(p.params.kind==="insert-child"){if(!("kind"in p.params.position)||p.params.position.kind!=="page-composition")return ue(p,V.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(p.params.position.documentVersion!==p.documentVersion)return ue(p,V.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.")}let x=S.document,I=S.pageCompositionProjection;if(!x||x.pageComposition?.status!=="supported"||!I||I.status!=="supported")return ue(p,V.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==x.version||I.documentVersion!==x.version)return ue(p,V.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${x.version}).`);let P=p.params.node.kind==="component-call"?p.params.node.materialization:void 0;if(!P)return ue(p,V.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let _=p.params.kind==="insert-child"?p.params.position:null,F=await Lo({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:P.files.map(K=>({path:K.pathTemplate,content:K.content})),exists:K=>n.exists(K),readFile:K=>n.readFile(K)});if(!F.ok)return ue(p,V.MATERIALIZATION_REJECTED,F.message);let j=await rN(n,Object.keys(P.projectDependencies??{})),W=await Af({manifest:P,generatedRoot:"components/site/generated",controlledFiles:P.files.map(K=>({pathTemplate:K.pathTemplate})),exists:K=>n.exists(K),availableHostDependencies:j,commit:async K=>{let B=await n.readFile(S.entryFile),Z=S.document,te=S.pageCompositionProjection;if(!Z||Z.pageComposition?.status!=="supported"||Z.version!==p.documentVersion||!te||te.status!=="supported"||te.documentVersion!==Z.version)return{ok:!0,data:ue(p,V.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let he=K.entry.path,pe=py(K.instanceName),ke,Pe=[];if(p.params.kind==="insert-child"){if(!_||!("kind"in _)||_.kind!=="page-composition")return{ok:!0,data:ue(p,V.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.")};let me=oc({routeId:S.routeId,entryFile:S.entryFile,currentDocumentVersion:Z.version,expectedDocumentVersion:p.documentVersion,source:B,projection:te,placementKey:_.placementKey,component:{source:he,exportName:K.entry.export.kind==="default"?"default":K.entry.export.name,localName:pe}});if(!me.ok)return{ok:!0,data:ue(p,Ls(me.error.code),me.error.message,{diagnostics:me.error.diagnostics})};let Se=me.plan.rewriteStep,Ae;switch(Se.kind){case"insert-root-expression":Ae=Bi({source:B,locator:Se.locator,expectedSourceHash:Se.sourceHash,action:{kind:"insert",jsx:Se.node.jsx,placement:Se.placement,replaceOriginal:Se.replaceOriginal}});break;case"insert-child":Ae=Yn({source:B,locator:Se.parentLocator,node:Se.node,placement:Se.placement,...Se.anchorLocator?{anchorLocator:Se.anchorLocator}:{}});break;default:Ae={ok:!1,source:B,diagnostic:{code:"unsupported-syntax",message:`Unsupported route composition rewrite: ${String(Se)}`}}}if(!Ae.ok)return{ok:!0,data:ue(p,V.AST_PARSE_ERROR,Ae.diagnostic.message)};ke=Ae.source}else{let me=ic({routeId:S.routeId,composition:S.composition,entryFile:S.entryFile,currentDocumentVersion:Z.version,expectedDocumentVersion:p.documentVersion,source:B,projection:te,placementUnitKey:p.target.placementUnitKey,operation:"replace-node"});if(!me.ok)return{ok:!0,data:ue(p,Ls(me.error.code),me.error.message,{diagnostics:me.error.diagnostics})};let Se=me.plan.rewriteStep,Ae;switch(Se.kind){case"replace-root-expression":Ae=Bi({source:B,locator:Se.locator,expectedSourceHash:Se.sourceHash,action:{kind:"replace",jsx:`<${pe} />`}});break;case"replace-node":Ae=ti({source:B,locator:Se.locator,node:{jsx:`<${pe} />`}});break;default:Ae={ok:!1,source:B,diagnostic:{message:`Unsupported page-unit replacement rewrite: ${Se.kind}`}}}if(!Ae.ok)return{ok:!0,data:ue(p,V.AST_PARSE_ERROR,Ae.diagnostic.message)};let en=await Zl({routeState:S,placementUnitKey:p.target.placementUnitKey,source:B,mutatedSource:Ae.source});ke=en.source,Pe=await Promise.all(en.files.map(async it=>({operation:"delete",file:it,baseContentHash:Ie(await n.readFile(it))})))}let O=qn({source:ke,moduleSpecifier:k(S.entryFile,he),imports:K.entry.export.kind==="default"?[{kind:"default",local:pe}]:[{kind:"named",imported:K.entry.export.name,local:pe}]});if(!O.ok)return{ok:!0,data:ue(p,V.AST_PARSE_ERROR,O.diagnostic.message)};let U=K.files.map(me=>({operation:"create-only",file:me.path,content:me.content})),ae=[{operation:"upsert",file:S.entryFile,content:O.source,baseContentHash:Ie(B)},...U,...Pe];g+=1;try{let me=await Xn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:S.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:ae}});return!me.ok&&me.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:me.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:me}}finally{g-=1}}});return W.ok?W.data:ue(p,W.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?V.MATERIALIZATION_CONFLICT:V.MATERIALIZATION_REJECTED,W.error.message,{materializationCode:W.error.code})}async function iy(p,S){if(p.kind!=="move-node"&&p.kind!=="remove-node")return ue(p,V.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let x=S.document,I=S.pageCompositionProjection;if(!x||x.pageComposition?.status!=="supported"||!I||I.status!=="supported")return ue(p,V.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==x.version||I.documentVersion!==x.version)return ue(p,V.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${x.version}).`);let P=await n.readFile(S.entryFile),_=ic({routeId:S.routeId,composition:S.composition,entryFile:S.entryFile,currentDocumentVersion:x.version,expectedDocumentVersion:p.documentVersion,source:P,projection:I,placementUnitKey:p.target.placementUnitKey,operation:p.kind,targetPlacement:p.kind==="move-node"&&p.params.kind==="move-node"&&"kind"in p.params.target&&p.params.target.kind==="page-composition"?p.params.target:void 0});if(!_.ok)return ue(p,Ls(_.error.code),_.error.message,{diagnostics:_.error.diagnostics});let F=_.plan.rewriteStep,j;switch(F.kind){case"move-node":j=Zn({source:P,locator:F.locator,targetParentLocator:F.targetParentLocator,placement:F.placement,...F.anchorLocator?{anchorLocator:F.anchorLocator}:{}});break;case"remove-node":j=Gn({source:P,locator:F.locator});break;case"remove-root-expression":j=Bi({source:P,locator:F.locator,expectedSourceHash:F.sourceHash,action:{kind:"remove"}});break;default:j={ok:!1,source:P,diagnostic:{message:`Unsupported page-unit mutation rewrite: ${F.kind}`}}}if(!j.ok)return ue(p,V.AST_PARSE_ERROR,j.diagnostic.message);let W=j.source,K=[];if(p.kind==="remove-node"){let Z=await Zl({routeState:S,placementUnitKey:p.target.placementUnitKey,source:P,mutatedSource:W});W=Z.source,K=await Promise.all(Z.files.map(async te=>({operation:"delete",file:te,baseContentHash:Ie(await n.readFile(te))})))}let B=[{operation:"upsert",file:S.entryFile,content:W,baseContentHash:Ie(P)},...K];g+=1;try{return await Xn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:S.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:B}})}finally{g-=1}}async function Zl(p){let S={source:p.mutatedSource,files:[]},x=p.routeState.graph,I=p.routeState.pageCompositionProjection;if(!x||!I||I.status!=="supported"||!n.listFiles)return S;let _=I.placementUnitByKey.get(p.placementUnitKey)?.sourceRange;if(!_)return S;let F=[...x.elements.values()].find(O=>O.sourceFile===p.routeState.entryFile&&O.importedFrom&&C(O.sourceRange,_));if(!F?.importedFrom||!F.exportName)return S;let j=y(F.importedFrom),W="components/site/generated/";if(!j.startsWith(W))return S;let K=j.slice(W.length).split("/")[0];if(!K||!/-[0-9a-f]{8}$/i.test(K))return S;let B=`${W}${K}`;if([...x.elements.values()].filter(O=>O.sourceFile===p.routeState.entryFile&&y(O.importedFrom??"")===j).length!==1)return S;let te=await n.listFiles({maxFiles:5e3,maxDepth:32}),he=Array.isArray(te)?te:te.files;if(!Array.isArray(te)&&te.truncated)return S;let pe=he.map(({path:O})=>O).filter(O=>O===B||O.startsWith(`${B}/`));if(pe.length===0||!pe.includes(j))return S;for(let{path:O}of he)if(!(O===p.routeState.entryFile||O===B||O.startsWith(`${B}/`)))try{if((await n.readFile(O)).includes(K))return S}catch{return S}let ke=k(p.routeState.entryFile,j),Pe=er({source:p.mutatedSource,moduleSpecifier:ke,imports:F.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:F.exportName}]});return Pe.ok?Pe.source.includes(K)?{source:Pe.source,files:[]}:{source:Pe.source,files:pe.sort((O,U)=>O.localeCompare(U))}:S}async function sy(p){if(n.getFileInfo){for(let F of p)if(await n.exists(F.path)&&await n.getFileInfo(F.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${F.path}`,details:{path:F.path}}}for(let F of p){if(F.operation!=="upsert"||!/^(?:src\/)?app\/globals\.css$/i.test(F.path))continue;let j=await n.exists(F.path)?await qs(n,F.path):null;if(j?.ok){let W=zw(j.content,F.content);if(!W.ok)return{ok:!1,errorCode:"invalid-params",message:W.message,details:{path:F.path,code:W.code}}}}let S=ay(p);if(S.length===0)return{ok:!0};let x=hN(n,p),I=new Map,P=(F,j)=>{let W=I.get(F);if(W?.source===j)return W.result;let K=Jt(F,j);return I.set(F,{source:j,result:K}),K},_;try{_=await bh(S,async F=>{let j=i.get(F);return j?[...(await Oe(j.entryFile,await x.readFile(j.entryFile),x,{validationOnly:!0,parseModule:P,validatedImports:m.getImports})).parsedModules.values()]:[]})}catch(F){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${qe(F)}`,details:{compositionKeys:S}}}for(let F of _)m.remember(F);return{ok:!0}}function ay(p){return p.map(x=>x.path).some(jh)?[...i.keys()]:[]}function Fs(p,S,x,I){let P=Ao(S);return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:oe(p),error:{code:P,message:x,...I?{details:I}:{}}}}async function _s(p){let S=[];for(let x of new Set(p))S.push(await cy(x));return S}async function cy(p){if(!(typeof n.exists=="function"?await n.exists(p):!0))return{file:p,content:"",version:Math.max(0,ee(p)),exists:!1};let x=await n.readFile(p);return{file:p,content:x,version:Math.max(1,ee(p)),exists:!0,sha256:Ie(x)}}async function Ql(p,S,x,I){if(!e.historyStore)return null;let P=new Map(S.map(j=>[j.file,j])),_=new Map(x.map(j=>[j.file,j])),F=[...new Set([...P.keys(),..._.keys()])].sort().map(j=>{let W=P.get(j),K=_.get(j);return{path:j,preDigest:W?.exists===!1||!W?null:Ie(W.content),postDigest:K?.exists===!1||!K?null:Ie(K.content)}});return{schemaVersion:2,transactionId:`${p}:${I.expectedIndexDigest}`,operationId:p,phase:"prepared",historyTransition:I,files:F}}async function ql(p){return!p||!e.historyStore||await e.historyStore.writeTransactionJournal(p),p}async function Jn(p){p&&e.historyStore&&await e.historyStore.clearTransactionJournal(p.transactionId)}async function Ms(p,S){let x=[];try{for(let I of p)await eu(I),typeof n.bumpVersion=="function"&&n.bumpVersion(I.file),x.push(I.file)}catch(I){let P=await ly(S.filter(_=>x.includes(_.file)));return P.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${qe(I)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${P.failedFiles.join(", ")}: ${qe(I)}`,rolledBack:!1}}return{ok:!0,snapshots:p.map(uy)}}async function eu(p){if(p.exists===!1){await n.deleteFile(p.file);return}await n.writeFile(p.file,p.content)}async function ly(p){let S=[];for(let x of p)try{await eu(x),typeof n.bumpVersion=="function"&&n.bumpVersion(x.file)}catch{S.push(x.file)}return S.length===0?{ok:!0}:{ok:!1,failedFiles:S}}function uy(p){let S=p.exists!==!1;return{file:p.file,content:S?p.content:"",version:p.version,exists:S,...S?{sha256:Ie(p.content)}:{}}}async function Xn(p){return b.runExclusive(()=>dy(p))}async function dy(p){let S=p.filePlan.edits.map(O=>O.file),x=o.resolveSelector(p.request.composition),I=x.context,P=p.historyPolicy==="none"?void 0:{initiatingComposition:I,affectedCompositions:Yh(S)},_=await _s(S),F=new Map(_.filter(O=>O.exists!==!1).map(O=>[O.file,O.content])),j=nu(),W=new Map(f),K=new Set(u),B=new Set([...i.values()].filter(O=>p.filePlan.edits.some(U=>U.operation==="delete"&&U.file===O.entryFile)).map(O=>O.key)),Z=p.filePlan.edits.map(O=>O.operation==="delete"?{file:O.file,content:"",version:0,exists:!1}:{file:O.file,content:O.content,version:0,exists:!0,sha256:Ie(O.content)}),te={operationId:p.filePlan.operationId,intents:p.filePlan.edits.map(O=>O.operation==="delete"?{kind:"delete",path:O.file}:{kind:O.operation==="create-only"?"create-only":"upsert",path:O.file,content:O.content})},he=null,pe=!1,ke=await Es({overlay:F,exists:O=>n.exists(O),plan:te,buildCandidate:async({plan:O})=>({plan:O}),prepareHistory:async()=>{let O=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:Z,...p.selectionRef?{selectionRef:p.selectionRef}:{},...p.output?{output:p.output}:{},...P?{provenance:P}:{}}),U=O?.historyTransition?O.historyTransition:e.historyStore?tN(await e.historyStore.readIndex()):null;if(e.historyStore&&!U)throw new Error("Durable history did not provide an exact index transition.");return he=await Ql(p.request.id,_,Z,U),he=await ql(he),{history:O,historyTransition:U}},reverify:async()=>{},writeCandidate:async()=>{let O=await d.executeFilePlan(p.filePlan);if(!O.ok)throw new Rs(O);return{postSnapshots:await _s(O.affectedFiles),affectedFiles:O.affectedFiles,internalResultVersion:O.resultVersion}},validateCandidate:async({candidate:O,receipt:U})=>{let ae=await Fo(U.affectedFiles,{changed:!0,minimumVersion:U.internalResultVersion,publish:!1,excludedCompositionKeys:B});if(ae.failedRoutes.length>0)throw new Vn(ae.failedRoutes);let me=ou(j,ae.candidateRouteStates??[]),Se=ru(me,x.key);return{...O,rebuild:ae,routeSnapshots:me,resultVersion:Se,...Oh(p.selectionRef,me.map(Ae=>Ae.state.document))?{selectionRef:Oh(p.selectionRef,me.map(Ae=>Ae.state.document))}:{}}},publishCandidate:async({candidate:O,history:U,receipt:ae})=>{U?.history&&(await l.publishPrepared(U.history),pe=!0);let me=O.resultVersion??ae.internalResultVersion;return{composition:I,requestId:p.request.id,kind:p.request.kind,target:p.request.target,ok:!0,resultVersion:me,affectedFiles:ae.affectedFiles,fileChanges:ae.postSnapshots.map(Se=>({path:Se.file,operation:Se.exists===!1?"delete":"upsert"})),...p.output?{output:p.output}:{},...O.selectionRef?{selectionRef:O.selectionRef}:{}}},swapCandidate:({candidate:O,receipt:U})=>{O.routeSnapshots&&_o(O.routeSnapshots),O.rebuild?.candidateSourceCache&&Er(f,O.rebuild.candidateSourceCache),Wl(U.postSnapshots)},finalizeCandidate:async()=>{await Jn(he);for(let O of B)i.delete(O)},emitCommitted:({candidate:O,published:U})=>{Ts(U,O.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:O,receipt:U})=>{if(pe)throw new Error("history was published before transaction finalization failed");if(U){let ae=await Ms(_,U.postSnapshots);if(!ae.ok)throw new Error(ae.reason)}_o(j),Er(f,W),Hl(K),O?.history&&await l.discardPrepared?.(O.history),await Jn(he)}});if(ke.ok)return ke.published;if(ke.stage==="precheck"||ke.stage==="build")try{await Jn(he)}catch(O){let U=await Mo(qe(O));return ue(p.request,U,"Unable to clear an uncommitted transaction journal.")}if(ke.recoveryRequired){let O=await Mo(ke.reason);return ue(p.request,O===V.RECOVERY_PERSIST_FAILED?O:V.ROLLBACK_FAILED,ke.reason)}let Pe=ke.error;return Pe instanceof Rs?{...ue(p.request,Ao(Pe.result.errorCode),Pe.result.reason),...Pe.result.affectedFiles?{affectedFiles:Pe.result.affectedFiles}:{}}:Pe instanceof Vn?ue(p.request,V.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${Bl(Pe.failedRoutes)}`,{failedRoutes:Pe.failedRoutes}):ue(p.request,su(ke.stage),qe(Pe))}async function tu(p){return b.runExclusive(async()=>{let S=p==="undo"?await l.prepareUndo():await l.prepareRedo();return S?fy(p,S):{composition:o.entries[0].context,requestId:p,kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:o.initialVersions.get(o.entries[0].key)??0,error:{code:V.INTERNAL_ERROR,message:p==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function fy(p,S){let x=S.entry,I=p==="undo"?x.preSnapshots:x.postSnapshots,P=p==="undo"?x.postSnapshots:x.preSnapshots,_=I.map(U=>U.file),{context:F,key:j}=Qh(x,_),W=await _s(_),K=new Map(W.filter(U=>U.exists!==!1).map(U=>[U.file,U.content])),B=se(j),Z=nu(),te=new Map(f),he=new Set(u),pe=null,ke=!1,Pe,O=await Es({overlay:K,plan:{operationId:`${p}:${x.operationId}`,intents:I.map(U=>U.exists===!1?{kind:"delete",path:U.file}:{kind:"upsert",path:U.file,content:U.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(pe=await Ql(`${p}:${x.operationId}`,W,I,S.historyTransition),pe=await ql(pe),S),reverify:async()=>{},writeCandidate:async()=>{let U=await Ms(I,P);if(!U.ok)throw new Error(U.reason);return{snapshots:U.snapshots}},validateCandidate:async({candidate:U})=>{Pe=Zh(x,_);let ae=await Fo(_,{changed:!0,minimumVersion:B+1,publish:!1,affectedCompositionKeys:Pe});if(ae.failedRoutes.length>0)throw new Vn(ae.failedRoutes);let me=ou(Z,ae.candidateRouteStates??[]),Se=ru(me,j);return{...U,rebuild:ae,routeSnapshots:me,resultVersion:Se}},publishCandidate:async({candidate:U,history:ae,receipt:me})=>{if(!ae)throw new Error("history cursor intent is missing");await l.publishPrepared(ae),ke=!0;let Se=U.resultVersion??B+1;return{composition:F,requestId:p,kind:x.kind,target:x.target,ok:!0,resultVersion:Se,affectedFiles:_,fileChanges:me.snapshots.map(Ae=>({path:Ae.file,operation:Ae.exists===!1?"delete":"upsert"})),...x.output?{output:x.output}:{}}},swapCandidate:({candidate:U,receipt:ae})=>{U.routeSnapshots&&_o(U.routeSnapshots),U.rebuild?.candidateSourceCache&&Er(f,U.rebuild.candidateSourceCache),Wl(ae.snapshots)},finalizeCandidate:async()=>{await Jn(pe)},emitCommitted:({candidate:U,published:ae})=>Ts(ae,U.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:U,receipt:ae})=>{if(ke)throw new Error("history cursor was published before transaction finalization failed");if(ae){let me=await Ms(P,ae.snapshots);if(!me.ok)throw new Error(me.reason)}_o(Z),Er(f,te),Hl(he),U&&await l.discardPrepared?.(U),await Jn(pe)}});if(O.ok)return O.published;if(O.stage==="precheck"||O.stage==="build")try{await Jn(pe)}catch(U){let ae=await Mo(qe(U));return{composition:F,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:B,error:{code:ae,message:"Unable to clear an uncommitted transaction journal."}}}if(O.recoveryRequired){let U=await Mo(O.reason);return{composition:F,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:B,affectedFiles:_,error:{code:U===V.RECOVERY_PERSIST_FAILED?U:V.ROLLBACK_FAILED,message:O.reason}}}return{composition:F,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:B,affectedFiles:_,error:{code:O.error instanceof Vn?V.ROUTE_REBUILD_FAILED:su(O.stage),message:qe(O.error),...O.error instanceof Vn?{details:{failedRoutes:O.error.failedRoutes}}:{}}}}function nu(){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 ru(p,S){return p.find(I=>I.key===S)?.state.graph?.version??o.initialVersions.get(S)??0}function ou(p,S){let x=new Map(p.map(I=>[I.key,I]));for(let I of S)x.set(I.key,I);return[...x.values()]}function _o(p){for(let S of i.values())A(S);for(let S of p){let x={...S.state,dependencyFiles:new Set(S.state.dependencyFiles),fileVersions:new Map(S.state.fileVersions)};i.set(S.key,x),R(x,x.dependencyFiles)}}async function Os(p){let S=i.get(p);if(!S)throw new Error(`Composition not found: ${p}`);if(S.graph)return;let x=await n.readFile(S.entryFile);await Nt(p,x)}function zn(p,S){let x=i.get(o.resolveSelector(S).key)??null;return!x||!iu(x,p)?null:x}function iu(p,S){if(p.documentIndex?.entriesByKey.has(S)||p.graph?.elements.has(S))return!0;let x=ot(S);return x&&x!==S?p.graph?.elements.has(x)===!0:!1}function ue(p,S,x,I){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:oe(p),error:{code:S,message:x,...I?{details:I}:{}}}}function su(p){return p==="validate"?V.ROUTE_REBUILD_FAILED:p==="publish"?V.HISTORY_COMMIT_FAILED:V.WRITE_IO_ERROR}async function Mo(p){if(h=!0,!l.markRecoveryRequired)return V.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(p),V.RECOVERY_REQUIRED}catch{return V.RECOVERY_PERSIST_FAILED}}function py(p){let x=p.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(I=>I.charAt(0).toUpperCase()+I.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return x?`Prefab${x}`:"GeneratedPrefab"}function Ls(p){return p==="VERSION_STALE"?V.VERSION_STALE:p==="CROSS_PAGE_MOVE_UNSUPPORTED"?V.CROSS_PAGE_MOVE_UNSUPPORTED:V.UNSUPPORTED_OPERATION}async function au(p){if(p.target.kind==="route"){let x=i.get(o.resolveSelector(p.target.composition).key)??null;return x?(x.graph||await Os(x.key),x):ue(p,V.ROUTE_NOT_FOUND,"Composition not found for route target.")}if(p.target.kind==="page-unit"){let x=i.get(o.resolveSelector(p.target.composition).key)??null;return x?(x.graph||await Os(x.key),x):ue(p,V.ROUTE_NOT_FOUND,"Composition not found for page-unit target.")}if(p.target.kind!=="node")return ue(p,V.UNSUPPORTED_OPERATION,`${p.kind} source target execution is not implemented yet.`);let S=i.get(o.resolveSelector(p.composition).key)??null;return S?(S.graph||await Os(S.key),iu(S,p.target.key)?S:ue(p,V.NODE_NOT_FOUND,`Target key not found: ${p.target.key}`)):ue(p,V.ROUTE_NOT_FOUND,"Composition not found for node target.")}return{get status(){return t},dispose(){t="disposed",a.clear(),i.clear(),s.clear(),f.clear(),m.clear(),u.clear()},registerComposition(p,S){let x=o.register({context:p,entryFile:S}),I=i.get(x.key);if(I?.entryFile===S)return;I&&A(I);let P=Mh(x.context,S);i.set(x.key,P),R(P,P.dependencyFiles),r.emit({type:"graph-invalidated",composition:x.context})},unregisterComposition(p){let S=o.resolveSelector(p),x=i.get(S.key);x&&(A(x),i.delete(S.key),o.unregister(S.key),i.size===0&&(t="idle"),r.emit({type:"graph-invalidated",composition:S.context}))},getCompositionEntryFiles(){return[...i.values()].map(p=>p.entryFile)},getCompositionContext(p){return o.resolveSelector(p).context},async initializeComposition(p){let S=o.resolveSelector(p),x=i.get(S.key);if(!x)throw new Error(`Composition not registered: ${S.key}`);if(x.graph)t="ready";else{t="building";try{let I=await n.readFile(x.entryFile);await Nt(S.key,I),t="ready",r.emit({type:"graph-ready",composition:S.context,version:i.get(S.key)?.graph?.version??0})}catch(I){throw t="idle",r.emit({type:"graph-error",composition:S.context,message:qe(I)}),I}}},getDocument(p){let S=o.resolveSelector(p),x=i.get(S.key);if(!x)throw new Error(`Composition not registered: ${S.key}`);if(!x.document)throw new Error(`Composition not built: ${S.key}`);return x.document},async getHistoryStatus(){await E;let p=await l.getStatus?.();return p?{...p,recoveryRequired:h}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:h}},getObjectEditContext(p,S,x){let I=zn(p,S),P=ot(p)??p;if(I?.graph&&I.topology&&I.capabilities&&I.detailProjections){let _=I.detailProjections.get(P);if(_){let F=I.graph.elements.get(P);if(!F)throw new Error(`Key not found: ${p}`);let j=cN(p,P,x),W=new Map;if(_.isRepeat&&j?.instanceIndex!==void 0)for(let Z of F.attributes??[])W.set(Z.name,fl({file:F.sourceFile,source:f.get(F.sourceFile)??"",element:F,propertyName:Z.name,selectionRef:j,graph:I.graph,sources:f}));let K=Yg({element:F,graph:I.graph,source:f.get(F.sourceFile),documentVersion:I.graph.version,selectionRef:x,isRepeat:_.isRepeat,propertyProvenance:_.propertyProvenances,repeatTargets:W}),B=qg(P,I.graph,I.topology,I.capabilities,_.textSources,_.provenances,_.dynamicData,K);return p===P?B:Rh(B,p,I.document??null,I.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getRenderDetail(p,S){let x=zn(p,S),I=ot(p)??p;if(x?.graph&&x.topology&&x.capabilities&&x.detailProjections){let P=x.detailProjections.get(I);if(P){let _=Qg(I,x.graph,x.topology,x.capabilities,P.textSources,P.writeTarget,P.provenances,P.conditional,P.componentSemantic,P.styleSource,P.dynamicData);return p===I?_:Ch(_,p,x.document??null,x.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getClassNameSource(p,S){let x=zn(p,S),I=ot(p)??p;if(!x?.graph)throw new Error(`Key not found: ${p}`);let P=x.graph.elements.get(I);if(!P)throw new Error(`Key not found: ${p}`);let _=f.get(P.sourceFile);if(_===void 0)throw new Error(`Source not loaded: ${P.sourceFile}`);return xa({key:I,route:{composition:x.composition,routeId:x.routeId,graph:x.graph,source:_}})},refreshSourceForKey:ey,async execute(p){if(await E,h)return ue(p,V.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(p.kind==="source-edit")return ty(p);if(p.kind==="insert-page-resource")return ny(p);if(p.kind==="delete-page-source")return ry(p);let S=await au(p);if("ok"in S)return S;await Yl(p);let x=await au(p);if("ok"in x)return x;let I=x;if(p.target.kind==="page-unit"){let B=p;return p.kind==="insert-child"||p.kind==="replace-node"?oy(B,I):p.kind==="move-node"||p.kind==="remove-node"?iy(B,I):ue(p,V.UNSUPPORTED_OPERATION,"Only page-unit insert-child, replace-node, move-node, and remove-node are currently supported by the page composition transaction.")}let _=p.params,F=p.target.kind==="node"?p.target.key:null;if(_.kind==="move-node"&&"kind"in _.target&&_.target.kind==="source-sibling"){let B=_.target,Z=F?I.document?.entries.find(U=>U.key===F):null,te=I.document?.entries.find(U=>U.key===B.anchorKey),he=Z?.pageCompositionActionScope,pe=he?.kind==="source-siblings"?he.siblingKeys:null,ke=pe?.indexOf(Z?.key??"")??-1,Pe=pe?.indexOf(B.anchorKey)??-1,O=B.relation==="before"?ke-1:ke+1;if(!Z||!te||!pe||ke<0||Pe!==O||te.pageCompositionActionScope?.kind!=="source-siblings"||te.pageCompositionActionScope.siblingKeys.length!==pe.length||te.pageCompositionActionScope.siblingKeys.some((U,ae)=>U!==pe[ae])||!Z.operationSummary.canMove)return ue(p,V.INVALID_TARGET,"Source sibling move is unavailable because the current source sibling scope or adjacent anchor no longer matches.")}if(!I.graph||!I.topology||!I.capabilities)return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:oe(p),error:{code:p.target.kind==="route"?V.ROUTE_NOT_FOUND:V.NODE_NOT_FOUND,message:p.target.kind==="route"?"Composition not ready for route target.":p.target.kind==="node"?`Target key not found: ${p.target.key}`:`${p.kind} source target execution is not implemented yet.`}};let j=RN(I,I.graph,I.capabilities,f,i),W=await new is(j).plan(p);if(!W.ok)return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:oe(p),error:{code:Ao(W.errorCode),message:W.reason}};let K=W.plan;if(K.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:oe(p),affectedFiles:[]}:{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:oe(p),error:{code:V.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};g+=1;try{if(K.steps.some(Z=>Z.type==="invoke-external-adapter")){let Z=await d.execute(K);if(!Z.ok)return ue(p,Ao(Z.errorCode),Z.reason);let te={composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!0,resultVersion:Math.max(oe(p),Z.resultVersion),affectedFiles:Z.affectedFiles,...Z.selectionRef?{selectionRef:Z.selectionRef}:{}};return Ts(te,{rebuiltRoutes:[],failedRoutes:[]}),te}let B=await d.prepareRewritePlan(K);return B.ok?await Xn({request:p,filePlan:B.filePlan,...B.selectionRef?{selectionRef:B.selectionRef}:{}}):ue(p,Ao(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:oe(p),error:{code:V.INTERNAL_ERROR,message:qe(B)}}}finally{g-=1}},async undo(p){if(await E,h)return{composition:o.entries[0].context,requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:se(o.entries[0].key),error:{code:V.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};g+=1;try{return await tu("undo")}finally{g-=1}},async redo(p){if(await E,h)return{composition:o.entries[0].context,requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:se(o.entries[0].key),error:{code:V.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};g+=1;try{return await tu("redo")}finally{g-=1}},notifyFileChanged(p){Xl([p])},getAffectedCompositions(p){return Gh(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&&To(f.sourceRange,h.sourceRange)));if(!m)continue;let u=m.placementUnitKey;a(f,u)}let l=!0;for(;l;){l=!1;for(let f of t.elements.values()){if(f.sourceFile===n.entryFile||!f.importedFrom||!/^[A-Z]/.test(f.tag))continue;let m=c(f);if(m)for(let u of m)l=a(f,u)||l}}let d=n.placements.find(f=>f.placementKey===n.container.placementKey&&f.relation==="append");for(let f of e.entries){let m=ot(f.key)??f.key,u=t.elements.get(f.key)??t.elements.get(m);if(!u)continue;if(u.sourceFile===n.entryFile){if(n.container.sourceRange&&To(u.sourceRange,n.container.sourceRange)&&d){f.pageCompositionUnitKey=d.placementUnitKey;continue}let b=n.placements.find(E=>E.members.some(y=>y.sourceRange!==null&&(To(u.sourceRange,y.sourceRange)||CN(y.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&&To(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!==(ot(m.key)??m.key))continue;let g=r.get(u.sourceFile);if(!g)continue;let h=ce(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()&&_e(E))){d(u)===1&&Dh(b)&&(m.pageCompositionActionScope={kind:"route-unit"});continue}if(!Dh(E))continue;let y=f.get(E.node)??[];y.push({entry:m,element:u,parentPath:E}),f.set(E.node,y)}for(let m of f.values()){let u=m[0];if(!u)continue;let g=u.entry.pageCompositionUnitKey,h=[],b=!!(g&&d(u.element)===1);for(let y of u.parentPath.node.children){if(vN(y))continue;if(!kN(y)){b=!1;break}let k=[...t.elements.values()].find(N=>N.sourceFile===u.element.sourceFile&&N.componentName===u.element.componentName&&To(N.sourceRange,IN(y))),C=k?o.get(k.identity.key):null;if(!k||!C||C.parentKey||C.pageCompositionUnitKey!==g||d(k)!==1){b=!1;break}h.push(C)}if(!b||h.length!==m.length||m.some(({entry:y})=>!h.some(k=>k.key===y.key)))continue;if(h.length===1){h[0].pageCompositionActionScope={kind:"route-unit"};continue}if(h.length<2)continue;let E=h.map(y=>y.key);for(let y of h)y.pageCompositionActionScope={kind:"source-siblings",siblingKeys:E}}}function Dh(e){let t=e.parentPath;return!!(t?.isReturnStatement?.()||t?.isArrowFunctionExpression?.()&&t.node.body===e.node)}function 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 To(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function CN(e,t){return Bh(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&Bh(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function Bh(e,t,n,r){return e!==n?e-n:t-r}function 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=ot(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:xa({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(y=>y.name===f);return E?E.source?{status:"blocked",owner:"generic",diagnostic:{code:"unsupported-property-source",message:`Property '${f}' has an unresolved value source`}}:{status:"direct",owner:"generic",attribute:E,target:{kind:"jsx-attribute",file:g.sourceFile,sourceRange:E.sourceRange}}:(g.attributeSpreads?.length??0)>0?{status:"blocked",owner:"generic",diagnostic:{code:"ambiguous-property-source",message:`A spread may provide or override property '${f}'`}}:{status:"missing",owner:"generic"}},getRepeatPropertyTarget(d,f,m){let u=c(d),g=t.elements.get(u.baseKey);if(!g)return{ok:!1,errorCode:"repeat-not-found",reason:`Node not found: ${d}`};let h=m?{...m,key:u.baseKey}:u.repeatIndex!==null?{key:u.baseKey,instanceIndex:u.repeatIndex}:void 0;return fl({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=Yw(d);return f?{baseKey:f.baseKey,repeatIndex:Ih(e.document??null,d,f.baseKey,e.documentIndex)??kh(f)}:{baseKey:d,repeatIndex:null}}function l(d,f){let m=ot(d)??d,u=e.documentIndex?.entriesByKey.get(d);return{key:d,file:f.sourceFile,component:f.componentName,tag:f.tag,structuralPath:f.identity.structuralPath,sourceRange:f.sourceRange,parentKey:u?.parentKey??f.parentKey??void 0,isRepeatRegion:f.boundaryKind==="repeat-region"||s.has(m),isBoundary:!1,importedFrom:f.importedFrom,exportName:f.exportName,isRepeatItemRoot:i.has(m),repeatOwnerKey:i.get(m)??s.get(m),attributes:f.attributes?.map(g=>({name:g.name,value:g.value,source:g.source?{expression:g.source.expression,base:g.source.base,path:g.source.path.map(h=>({...h}))}:null,resolvedValue:g.resolvedValue}))}}}var wN={"stale-version":V.VERSION_STALE,"capability-denied":V.CAPABILITY_REJECTED,"invalid-params":V.INVALID_PARAMS,"locator-miss":V.LOCATOR_FAILED,"route-not-found":V.ROUTE_NOT_FOUND,"unsupported-operation":V.UNSUPPORTED_OPERATION,"invalid-target":V.INVALID_TARGET,"ast-error":V.AST_PARSE_ERROR,"writeback-failed":V.WRITE_IO_ERROR,"rollback-failed":V.RECOVERY_REQUIRED,unknown:V.INTERNAL_ERROR};function Ao(e){return wN[e]}function qe(e){return e instanceof Error&&e.message?e.message:String(e)}function jh(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function NN(e){let t=Kn(e);if(!qw.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 Kh(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function TN(e){return Kh(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function Kh(e,t){let n=[];for(let r of e.matchAll(t)){let o=Uh(r[1]??"");o&&n.push(o)}return n}function $h(e,t){let n=Uh(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?Kn(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?Kn(`${FN(e)}/${n}`):n.startsWith("/")?Kn(n.slice(1)):Kl(n)?Kn(n):null}function Uh(e){return e.split(/[?#]/,1)[0]?.trim()??""}function Kl(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 MN(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 Ns=class{constructor(t){this.options=t,this.fileSystem=new Cr(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}getDocument(t){return Ko(this.engine.getDocument(t),{siteId:this.options.siteId,snapshotId:this.options.snapshotId})}getInternalDocument(t){return this.engine.getDocument(t)}getStyleContext(t){return this.engine.getDocument(t).styleContext??null}getObjectEditContext(t,n,r){return Uo(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return zo(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}getSourceFile(t){return Wo(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}resolveSourceLocation(t){return Ho(t,this.engine.getRenderDetail(t.key,t.composition))}async planOperation(t){let n=LN.safeParse(t);if(!n.success)return{result:Vo(t,n.error.issues.map(i=>i.message))};let r=new Cr(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 ws({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=Jo(o,{siteId:this.options.siteId,snapshotId:this.options.snapshotId});i&&this.options.onEvent?.(i)}:void 0,dev:this.options.dev,...this.options.historyStore?{historyStore:this.options.historyStore}:{},...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,...this.options.initialDocumentVersions?{initialDocumentVersions:this.options.initialDocumentVersions}:{},resourceTranslationLocale:this.options.resourceTranslationLocale})}};function BN(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:Ie(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:Ie(e.before)},fullContent:e.after}}function jN(e){return new Ns(e)}import{SiteEditOperationRequestSchema as KN}from"@vcp-dev/contracts";import wt from"node:fs/promises";import et from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as $N,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as VN}from"@vcp-dev/contracts";var Ps=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=ws({...t,fileSystem:this.fileSystem})}get status(){return this.engine.status}registerComposition(t,n){this.engine.registerComposition(t,n)}unregisterComposition(t){this.engine.unregisterComposition(t)}getDocument(t){return this.engine.getDocument(t)}getAffectedCompositions(t){return this.engine.getAffectedCompositions(t)}getCompositionContext(t){return this.engine.getCompositionContext(t)}initializeComposition(t){return this.engine.initializeComposition(t)}getHistoryStatus(){return this.engine.getHistoryStatus()}getObjectEditContext(t,n,r){return r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n)}getRenderDetail(t,n){return this.engine.getRenderDetail(t,n)}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return zo(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.engine.getCompositionEntryFiles()})}getSourceFile(t){return Wo(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.engine.getCompositionEntryFiles()})}resolveSourceLocation(t){return Ho(t,this.engine.getRenderDetail(t.key,t.composition))}refreshSourceForKey(t,n){return this.engine.refreshSourceForKey(t,n)}execute(t){return this.engine.execute(t)}undo(t){return this.engine.undo(t)}redo(t){return this.engine.redo(t)}notifyFileChanged(t){this.engine.notifyFileChanged(t)}subscribe(t){return this.engine.subscribe(t)}dispose(){this.engine.dispose()}createFileSystem(){if(this.options.fileSystem)return this.options.fileSystem;let t=new Map,{projectRoot:n}=this.options;return{async readFile(r){return wt.readFile(et.join(n,r),"utf8")},async readFileBytes(r){return wt.readFile(et.join(n,r))},async getFileInfo(r){let o=et.join(n,...r.split("/"));try{let i=await wt.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await pi(et.join(n,r),o)},async createExclusive(r,o){let i=et.join(n,r);await wt.mkdir(et.dirname(i),{recursive:!0});let s=await wt.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await wt.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await wt.rm(et.join(n,r),{force:!0});let o=r.replace(/\\/g,"/"),i=["components/site/generated","src/components/site/generated"].find(c=>o.startsWith(`${c}/`));if(!i)return;let s=et.join(n,i),a=et.dirname(et.join(n,o));for(;a!==s&&a.startsWith(`${s}${et.sep}`);){try{await wt.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=et.dirname(a);continue}break}a=et.dirname(a)}},async exists(r){try{return await wt.access(et.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...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=et.join(n,...f.split("/")),h;try{h=await wt.lstat(g)}catch{return}if(h.isSymbolicLink())return;if(h.isFile()){let E=h.ino>0?`${String(h.dev)}:${String(h.ino)}`:null;if(E&&s.has(E))return;if(r.maxFiles!==void 0&&m.length>=r.maxFiles){a.add("max-files");return}if(r.maxTotalBytes!==void 0&&c+h.size>r.maxTotalBytes){a.add("max-total-bytes");return}E&&s.add(E),m.push({path:f,sizeBytes:h.size}),c+=h.size;return}if(!h.isDirectory())return;if(r.maxFiles!==void 0&&m.length>=r.maxFiles){a.add("max-files");return}let b=await wt.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 Ul(e){return new Ps(e)}var As=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=Ul({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=Jo(n,{siteId:t.siteId,snapshotId:t.snapshotId});if(r){t.onEvent?.(r);for(let o of this.listeners)o(r)}},dev:t.dev,...t.historyStore?{historyStore:t.historyStore}:{},...t.tenantId?{tenantId:t.tenantId}:{},...t.initialDocumentVersions!==void 0?{initialDocumentVersions:t.initialDocumentVersions}:{},siteId:t.siteId,snapshotId:t.snapshotId})}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}registerComposition(t,n){this.engine.registerComposition(t,n)}unregisterComposition(t){this.engine.unregisterComposition(t)}getDocument(t){return{ok:!0,composition:this.engine.getCompositionContext(t),data:Ko(this.engine.getDocument(t),{siteId:this.options.siteId,snapshotId:this.options.snapshotId})}}getInternalDocument(t){return this.engine.getDocument(t)}getStyleContext(t){return{ok:!0,composition:this.engine.getCompositionContext(t),data:this.engine.getDocument(t).styleContext??null}}async getHistoryStatus(){return{ok:!0,composition:this.options.compositions[0].context,data:await this.engine.getHistoryStatus()}}getObjectEditContext(t,n,r){return{ok:!0,composition:this.engine.getCompositionContext(n),data:Uo(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}}getClassNameSource(t,n){return{ok:!0,composition:this.engine.getCompositionContext(n),data:this.engine.getClassNameSource(t,n)}}async getSourceTree(t){return{ok:!0,composition:this.engine.getCompositionContext(t),data:await this.engine.getSourceTree(t)}}async getSourceFile(t){return{ok:!0,composition:this.engine.getCompositionContext(t.composition),data:await this.engine.getSourceFile(t)}}resolveSourceLocation(t){return{ok:!0,composition:this.engine.getCompositionContext(t.composition),data:this.engine.resolveSourceLocation(t)}}refreshSourceForKey(t,n){return this.engine.refreshSourceForKey(t,n)}async executeOperation(t,n){let r=n===void 0||t.mutationContext!==void 0?t:{...t,mutationContext:n},o=KN.safeParse(r);if(!o.success)return Vo(t,o.error.issues.map(s=>s.message));let i=await this.engine.execute(o.data);if(!i.ok){let s=i.error;if(!s)throw new Error("executeOperation failed without an error payload");return{ok:!1,composition:i.composition,error:{code:s.code,message:s.message,...s.details?{details:s.details}:{}},data:{requestId:i.requestId,kind:i.kind,composition:i.composition,target:i.target,resultVersion:i.resultVersion,...i.affectedFiles?.length?{affectedFiles:i.affectedFiles}:{}}}}return{ok:!0,composition:i.composition,data:Cn(i)}}async undo(t){let n=await this.engine.undo();if(!n.ok){let r=n.error;if(!r)throw new Error("undo failed without an error payload");return{ok:!1,composition:n.composition,error:{code:r.code,message:r.message},data:{requestId:n.requestId,kind:n.kind,composition:n.composition,target:n.target,resultVersion:n.resultVersion}}}return{ok:!0,composition:n.composition,data:Cn(n)}}async redo(t){let n=await this.engine.redo();if(!n.ok){let r=n.error;if(!r)throw new Error("redo failed without an error payload");return{ok:!1,composition:n.composition,error:{code:r.code,message:r.message},data:{requestId:n.requestId,kind:n.kind,composition:n.composition,target:n.target,resultVersion:n.resultVersion}}}return{ok:!0,composition:n.composition,data:Cn(n)}}notifyFileChanged(t){this.engine.notifyFileChanged(t)}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}dispose(){this.listeners.clear(),this.engine.dispose()}};function UN(e){return new As(e)}export{ie as FileHistoryStoreError,qr as PageTemplateManagedSourceError,As as PreviewFileSystemSiteEditEngineRuntime,pf as SITE_EDIT_RAW_COLOR_LITERAL_RE,Ns as SnapshotSiteEditEngineRuntime,Lo as checkComponentI18nHostCompatibility,op as computeManagedPageTemplatePaths,UN as createPreviewSiteEditEngineRuntime,jN as createSiteEditEngineRuntime,tp as decodePageTemplateKey,xc as encodePageTemplateId,Dy as instrumentSiteEditRuntimeAttributes,ip as isManagedPageTemplateSourcePath,Kd as openFileHistoryStore,Ey as parseSourceModule,vy as resolveImportBase,Ok as resolveManagedPageTemplateComposition,Vi as scanManagedPageTemplateCandidates,ap as scanSiteEditCompositionsFromFiles,zr as scanSiteEditThemeStyleViolations};
|
|
14
|
+
`||m==="\r"}if(s)return vr(t,`Unterminated block comment in ${t}.`);if(o)return vr(t,`Unterminated string literal in ${t}.`);if(c)return vr(t,`Unterminated MDX code fence in ${t}.`);let d=r.at(-1);return d?vr(t,`Unclosed token "${d.char}" in ${t}.`):{ok:!0}}function vr(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function ws(e){let t="idle",n=e.fileSystem??rN(),r=bd(),o=bh({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?lf(e.historyStore):iN()),d=yh(n,{externalAdapters:e.externalAdapters}),f=new Map,m=Pd(Vl),u=new Set,g=0,h=e.historyStore?.recoveryRequired??!1,b=Ol(),E=N();function y(p){return(Cs.isAbsolute(p)?Cs.relative(e.projectRoot,p):p).replace(/\\/g,"/").replace(/^\.\//,"")}function k(p,S){let x=Cs.posix.dirname(p),I=S.replace(/\.(?:tsx?|jsx?)$/i,""),P=Cs.posix.relative(x,I);return P.startsWith(".")?P:`./${P}`}function C(p,S){return p.startLine===S.startLine&&p.startColumn===S.startColumn&&p.endLine===S.endLine&&p.endColumn===S.endColumn}async function N(){let p=e.historyStore;if(p)try{let S=await p.readTransactionJournal();if(!S)return;let x=await p.readIndex(),I=await Promise.all(S.files.map(async _=>await n.exists(_.path)?Ie(await n.readFile(_.path)):null));if(Th({journal:S,index:x,observedFileDigests:I})!=="ambiguous"){await p.clearTransactionJournal(S.transactionId);let _=await p.readStatus();_.recoveryRequired||(await p.cleanupTmp(),_=await p.readStatus()),h=_.recoveryRequired;return}await p.markRecoveryRequired(`Ambiguous transaction journal ${S.transactionId} at phase ${S.phase}`),h=!0}catch(S){h=!0,await p.markRecoveryRequired(`Transaction journal recovery failed: ${qe(S)}`).catch(()=>{})}}function T(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let p of o.entries){let S=Oh(p.context,p.entryFile);i.set(p.key,S),R(S,S.dependencyFiles)}function R(p,S){let x=new Set(S);A(p),p.dependencyFiles=x;for(let I of p.dependencyFiles){let P=s.get(I);P||(P=new Set,s.set(I,P)),P.add(p.key)}}function A(p){for(let S of p.dependencyFiles){let x=s.get(S);x&&(x.delete(p.key),x.size===0&&s.delete(S))}p.dependencyFiles.clear()}function M(p){let S=new Set;for(let x of p)for(let I of s.get(x)??[])S.add(I);return S}function D(p){for(let S of p)if(!s.has(S))return!1;return!0}async function L(p,S,x,I,P,_){let F=new Map,j=Hg(p),W=Dg(P.values()),K=Lm(P.values()),B=typeof _.exists=="function"?Z=>_.exists(Z):async()=>!1;for(let[Z,te]of p.elements){let he=S.nodes.get(Z);if(!he)continue;let pe=x.get(te.sourceFile)??I.get(te.sourceFile),ke=new Map,Pe=new Map,O=new Map,U=[];for(let Ne of te.textSegments){if(!pe){ke.set(Ne.index,null);continue}let kr=await Bg({file:te.sourceFile,source:pe,segment:Ne,readFile:st=>_.readFile(st),exists:B,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:st,adapterId:xn,capabilities:Bs})=>({sourceType:st,adapterId:xn,capabilities:Bs})),functionCallContracts:e.functionCallContracts,fileCache:W}),Ze=await Rl({file:te.sourceFile,source:pe,target:{kind:"text-segment",segment:Ne},readFile:st=>_.readFile(st),exists:B,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:st,adapterId:xn,capabilities:Bs})=>({sourceType:st,adapterId:xn,capabilities:Bs})),functionCallContracts:e.functionCallContracts,fileCache:W}),ft=gN(kr);ke.set(Ne.index,ft),Pe.set(Ne.index,kr),O.set(Ne.index,Ze),U.push({editable:Ne.editable,source:ft})}let ae=new Map,me=new Map;if(pe)for(let Ne of te.attributes??[]){let kr=await Sr({file:te.sourceFile,source:pe,sourceRange:Ne.sourceRange,expression:Ne.source?.expression??Ne.value,sourceInfo:Ne.source,readFile:ft=>_.readFile(ft),exists:B,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:ft,adapterId:st,capabilities:xn})=>({sourceType:ft,adapterId:st,capabilities:xn})),functionCallContracts:e.functionCallContracts,fileCache:W}),Ze=await Wg({element:te,file:te.sourceFile,source:pe,propertyName:Ne.name,readFile:ft=>_.readFile(ft),exists:B,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:ft,adapterId:st,capabilities:xn})=>({sourceType:ft,adapterId:st,capabilities:xn})),functionCallContracts:e.functionCallContracts,fileCache:W});me.set(Ne.name,Ze),ae.set(Ne.name,kr)}let Se=rh(hN(he.writeTarget),U),Ae=j({key:Z,element:te,provenances:O}),en=ch(te),it=pe?await Dm({element:te,graph:p,file:te.sourceFile,source:pe,readFile:Ne=>_.readFile(Ne),exists:B,fileCache:K}):void 0,Wn=p.regions.find(Ne=>Ne.kind==="conditional-region"&&Ne.childKeys.includes(Z)),cu,Ds=Wn?.sourceCandidates?.[0];if(pe&&Wn&&Ds?.kind==="conditional-branch"){let Ne=await Rl({file:te.sourceFile,source:pe,target:{kind:"conditional-branch",candidate:Ds},readFile:Ze=>_.readFile(Ze),exists:B,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Ze,adapterId:ft,capabilities:st})=>({sourceType:Ze,adapterId:ft,capabilities:st})),functionCallContracts:e.functionCallContracts,fileCache:W});cu={currentBranch:Wn.childKeys.indexOf(Z)<=0?"then":"else",availableBranches:Wn.childKeys.length>1?["then","else"]:["then"],conditionExpression:Ds.conditionExpression,provenance:{finalSource:Ne.finalSource?{kind:Ne.finalSource.kind,file:Ne.finalSource.file,displayPath:Ne.finalSource.displayPath}:null,chain:Ne.chain.map(Ze=>({kind:Ze.kind,file:Ze.file,displayName:Ze.displayName,canEditHere:Ze.canEditHere})),confidence:Ne.confidence,editMode:Ne.editMode,diagnostics:Ne.diagnostics.map(Ze=>({code:Ze.code,message:Ze.message}))}}}F.set(Z,{textSources:ke,textTargets:Pe,elementPropertyTargets:ae,propertyProvenances:me,isRepeat:ON(Z,p),provenances:O,writeTarget:Se,componentSemantic:Ae,styleSource:en,conditional:cu,dynamicData:it})}return F}function ee(p){return typeof n.getVersion=="function"?n.getVersion(p):0}function ge(p,S){let x=o.initialVersions.get(p.key)??0;for(let I of S.values())x=Math.max(x,I);return Math.max(x,p.graph?.version??0)}function se(p){return i.get(p)?.graph?.version??o.initialVersions.get(p)??0}function oe(p){try{return se(o.resolveSelector(p.composition).key)}catch{return 0}}async function Oe(p,S,x=n,I={}){let P=await Nd(p,S,_=>x.readFile(_),_=>x.exists(_),{additionalEntries:await qt(p,x),...I});if(P.diagnostics.length>0)throw new Po(P.diagnostics);return I.validationOnly||m.remember(P.parsedModules.values()),P}async function Nt(p,S,x={}){let I=i.get(p);if(!I)return null;let P=x.sourceCache??jl(f,[]),_=x.fileSystem??Ll(n),{graph:F,allSources:j,parsedModules:W,entryModule:K}=await Oe(I.entryFile,S,_,{version:I.graph?.version??1}),B=new Map;for(let it of j.keys())B.set(it,ee(it));let Z=Math.max(ge(I,B),x.minimumVersion??0);x.changed&&Z<=(I.graph?.version??0)&&(Z=(I.graph?.version??0)+1),F.version=Z;for(let[it,Wn]of j)$l(P,it,Wn,Vl);let te=await Xh(I.composition,I.entryFile,j,P,_);F.routeId=I.routeId,F.composition=I.composition;let he=lh(F),pe=md(he,F),ke=await L(F,he,j,P,W,_),Pe=Hh(F,pe,ke),O=Wh(ke),U=kh(Qg(F,he,pe,{canUpdateTextByKey:Pe,dynamicDataSummaryByKey:O}),F,ke),ae=zf({route:I.routeId,composition:I.composition,entryFile:I.entryFile,version:Z,source:S,ast:K?.ast}),me=Wf(ae);ae.ok&&EN(U,F,ae.projection,W);let Se={...U,composition:I.composition,...te?{styleContext:te}:{},pageComposition:me},Ae=new Set([I.entryFile,...j.keys()]);if(te){Ae.add(te.entryCss.path);for(let it of te.stylesheets)Ae.add(it.path)}let en={...I,dependencyFiles:Ae,graph:F,topology:he,capabilities:pe,document:Se,pageComposition:me,pageCompositionProjection:ae.projection,pagePlacementByKey:ae.ok?ae.projection.placementByKey:null,pagePlacementUnitByKey:ae.ok?ae.projection.placementUnitByKey:null,pageUnitByKey:ae.ok?ae.projection.unitByKey:null,pagePlacementsByUnitKey:ae.ok?ae.projection.placementsByUnitKey:null,documentIndex:vh(Se),detailProjections:ke,fileVersions:B,styleContext:te};if(x.publish===!1)return en;Er(f,P);for(let it of P.keys())u.delete(it);return R(I,Ae),Object.assign(I,en),I}async function qt(p,S=n){let x=[];for(let I of PN(p))typeof S.exists=="function"&&await S.exists(I)&&x.push({file:I,source:await S.readFile(I)});return x}async function Xh(p,S,x,I,P){let _=[];for(let[B,Z]of x){if(Kl(B)){_.push(B);continue}for(let te of TN(Z)){let he=Vh(B,te);he&&_.push(he)}}if(!_.length){for(let B of AN(S))if(await P.exists(B)){_.push(B);break}}let F=new Map,j=MN(_).slice(0,Fh);for(;j.length>0&&F.size<Fh;){let B=j.shift();if(F.has(B)||!Kl(B))continue;let Z=await zh(B,I,P);if(Z!==null){F.set(B,{path:B,content:Z});for(let te of FN(Z)){let he=Vh(B,te);he&&!F.has(he)&&!j.includes(he)&&j.push(he)}}}let W=[...F.values()].map(B=>({...B,hash:Ie(B.content)})),K=W[0];return K?{composition:p,revision:Ie(JSON.stringify(W.map(({path:B,hash:Z})=>({path:B,hash:Z})))),entryCss:K,stylesheets:W.slice(1)}:null}async function zh(p,S,x){let I=S.get(p);if(I!==void 0)return I;if(!await x.exists(p))return null;let P=await x.readFile(p);return $l(S,p,P,Vl),P}function Wh(p){let S=new Map;for(let[x,I]of p)I.dynamicData?.bindings.length&&S.set(x,Gm(I.dynamicData.bindings));return S}function Hh(p,S,x){let I=new Map;for(let[P,_]of p.elements){if(!S.get(P)?.canUpdateText){I.set(P,!1);continue}let j=x.get(P),W=_.textSegments.some(K=>{if(!K.editable)return!1;let B=j?.provenances.get(K.index)??null;return!B||Gh(B)});I.set(P,W)}return I}function Gh(p){return p.editMode==="direct"||p.editMode==="proxy"||p.editMode==="upstream"}async function Fo(p,S={}){let x=[...new Set(p)],I=S.affectedCompositionKeys!==void 0,P=I?new Set(S.affectedCompositionKeys):M(x);if(!I&&(P.size===0||!D(x)))for(let K of i.values())Jl(K,x)&&P.add(K.key);let _=!I&&P.size===0&&x.some($h),F=S.publish===!1?jl(f,x):void 0,j={rebuiltRoutes:[],failedRoutes:[],...S.publish===!1?{candidateRouteStates:[],candidateSourceCache:F}:{}},W=Ll(n);for(let K of i.values())if(!(S.excludedCompositionKeys?.has(K.key)||!(P.has(K.key)||_)))try{let Z=!!K.graph,te=await W.readFile(K.entryFile),he=await Nt(K.key,te,{...S,fileSystem:W,...F?{sourceCache:F}:{}});he?.graph&&(j.rebuiltRoutes.push({documentChanged:Z,composition:K.composition,routeId:K.routeId,version:he.graph.version}),j.candidateRouteStates?.push({composition:K.composition,key:K.key,routeId:K.routeId,state:he}))}catch(Z){j.failedRoutes.push({...Ph(K.routeId,Z),composition:K.composition})}return j}function Un(p){let S=[...new Set(p)],x=M(S);if(x.size>0&&D(S))return[...x];for(let I of i.values())Jl(I,S)&&x.add(I.key);return[...x]}function Yh(p){let S=new Set(Un(p));return o.entries.filter(x=>S.has(x.key)).map(x=>x.context)}function Zh(p){return[...new Set(Un(p))].sort((x,I)=>x<I?-1:x>I?1:0).map(x=>o.getByKey(x)?.context).filter(x=>x!==void 0)}function Qh(p,S){let x=new Set(Un(S)),I=p.provenance?.affectedCompositions??[];if(I.length===0)return x;if([...new Set(I.map(_=>o.resolveContext(_).key))].some(_=>!x.has(_)))throw new Error("History provenance does not match the affected composition index.");return x}function qh(p,S){let x=p.composition??p.provenance?.initiatingComposition;if(x){let _=o.resolveContext(x);return{context:_.context,key:_.key}}let I=[...new Set(Un(S))];if(I.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${I.length}).`);let P=o.getByKey(I[0]);if(!P)throw new Error("Legacy history entry references an unknown affected composition.");return{context:P.context,key:P.key}}function Ts(p,S){r.emit({type:"operation-completed",composition:p.composition,result:p});for(let{composition:x,version:I}of S.rebuiltRoutes)r.emit({type:"document-changed",composition:x,version:I});for(let{composition:x,message:I}of S.failedRoutes)r.emit({type:"graph-error",composition:x,message:I})}function Jl(p,S){return S.some(x=>p.dependencyFiles.has(x)||p.entryFile===x||p.graph?.fileIndex.has(x))}function Xl(p){for(let S of p)a.add(S);c||T()||(c=(async()=>{t="building";let S=!1;try{for(;a.size>0;){if(T())return;await ey(),await b.runExclusive(async()=>{if(g>0||T())return;let x=[...a];a.clear();let I=await zl(x);if(I.length===0)return;let P=Un(I);for(let j of P){let W=i.get(j)?.composition;W&&r.emit({type:"graph-invalidated",composition:W})}let{rebuiltRoutes:_,failedRoutes:F}=await Fo(I,{changed:!0});for(let{documentChanged:j,composition:W,version:K}of _)r.emit({type:"graph-ready",composition:W,version:K}),j&&r.emit({type:"document-changed",composition:W,version:K});for(let{composition:j,message:W}of F)S=!0,r.emit({type:"graph-error",composition:j,message:W})})}}finally{c=null,t!=="disposed"&&(t=!S&&[...i.values()].some(x=>x.graph)?"ready":"idle"),a.size>0&&Xl([])}})())}async function ey(){for(;g>0;)await new Promise(p=>setTimeout(p,0))}async function zl(p){let S=[];for(let x of new Set(p)){let I=f.get(x);if(I===void 0){if(u.has(x)&&!await n.exists(x))continue;u.delete(x),S.push(x);continue}try{await n.readFile(x)!==I&&(u.delete(x),S.push(x))}catch(P){if(!SN(P))try{if(await n.exists(x))continue}catch{continue}u.add(x),S.push(x)}}return S}function Wl(p){Ah(f,p);for(let S of p)S.exists===!1?u.add(S.file):u.delete(S.file)}function Hl(p){u.clear();for(let S of p)u.add(S)}async function Gl(p){let S=await zl(p);if(S.length===0)return;let x=Un(S);for(let _ of x){let F=i.get(_)?.composition;F&&r.emit({type:"graph-invalidated",composition:F})}let{rebuiltRoutes:I,failedRoutes:P}=await Fo(S,{changed:!0});for(let{documentChanged:_,composition:F,version:j}of I)r.emit({type:"graph-ready",composition:F,version:j}),_&&r.emit({type:"document-changed",composition:F,version:j});for(let{composition:_,message:F}of P)r.emit({type:"graph-error",composition:_,message:F})}async function ty(p,S){let x=zn(p,S);if(!x?.graph)return;let I=ot(p)??p,P=x.graph.elements.get(I);P&&await Gl([P.sourceFile])}async function Yl(p){let S=new Set;if(p.target.kind==="node"){let x=zn(p.target.key,p.composition),I=ot(p.target.key)??p.target.key,P=x?.graph?.elements.get(I);P&&S.add(P.sourceFile)}else if(p.target.kind==="route"){let x=i.get(o.resolveSelector(p.target.composition).key);x&&S.add(x.entryFile)}else if(p.target.kind==="page-unit"){let x=i.get(o.resolveSelector(p.target.composition).key);x&&S.add(x.entryFile)}else if(p.target.kind==="source-file")S.add(p.target.path);else if(p.target.kind==="source-batch")for(let x of p.target.paths)S.add(x);if(p.params.kind==="move-node"&&!("kind"in p.params.target)){let x=[p.params.target.parentKey,...p.params.target.relation==="before"||p.params.target.relation==="after"?[p.params.target.anchorKey]:[]];for(let I of x){let P=zn(I,p.composition),_=ot(I)??I,F=P?.graph?.elements.get(_);F&&S.add(F.sourceFile)}}await Gl(S)}async function ny(p){if(p.params.kind!=="source-edit")return Fs(p,"invalid-params","source-edit requires source-edit params");for(let S of p.params.edits){let x=bN(S);if(!x.ok)return Fs(p,x.errorCode,x.message,x.details)}g+=1;try{let S=await ay(p.params.edits);if(!S.ok)return Fs(p,S.errorCode,S.message,S.details);await Yl(p);let x={operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:p.params.conflictPolicy,edits:p.params.edits.map(I=>I.operation==="delete"?{operation:"delete",file:I.path,baseContentHash:I.baseContentHash??null}:{operation:"upsert",file:I.path,baseContentHash:I.baseContentHash??null,content:I.content})};return await Xn({request:p,filePlan:x})}catch(S){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:oe(p),error:{code:V.INTERNAL_ERROR,message:qe(S)}}}finally{g-=1}}async function ry(p){if(p.target.kind!=="project"||p.params.kind!=="insert-page-resource")return ue(p,V.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");g+=1;try{let S=await Lo({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:[...p.params.artifact.components.flatMap(I=>I.materialization.files.map(P=>({path:P.pathTemplate,content:P.content}))),...p.params.artifact.pages.flatMap(I=>I.materialization.files.map(P=>({path:P.pathTemplate,content:P.content})))],exists:I=>n.exists(I),readFile:I=>n.readFile(I)});if(!S.ok)return ue(p,V.MATERIALIZATION_REJECTED,S.message);let x=await Za({artifact:p.params.artifact,exists:I=>n.exists(I)});return x.ok?await Xn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:"overwrite",edits:x.files},output:{kind:"insert-page-resource",package_instance_id:x.packageInstanceId,pages:x.pages},historyPolicy:"none"}):ue(p,x.code==="MATERIALIZATION_CONFLICT"?V.MATERIALIZATION_CONFLICT:V.MATERIALIZATION_REJECTED,x.message,x.path?{path:x.path}:void 0)}catch(S){return ue(p,V.INTERNAL_ERROR,qe(S))}finally{g-=1}}async function oy(p){if(p.target.kind!=="project"||p.params.kind!=="delete-page-source")return ue(p,V.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return ue(p,V.PLAN_FAILED,"Complete project file listing is required for page deletion.");g+=1;try{let S=Kh(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(S.truncated)return ue(p,V.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:S.truncated.reasons});let x=S.files.filter(({path:F})=>/\.(?:tsx?|jsx?)$/.test(F)),I=Object.fromEntries(await Promise.all(x.map(async({path:F})=>[F,await n.readFile(F)]))),P=hp({expectedUrlPath:p.params.expectedUrlPath,files:I});if(!P.ok)return ue(p,P.code==="HOME_PAGE_LOCKED"?V.HOME_PAGE_LOCKED:P.code==="ROUTE_NOT_FOUND"?V.ROUTE_NOT_FOUND:V.PLAN_FAILED,P.message);let _=await Promise.all(P.edits.map(async F=>({...F,baseContentHash:Ie(await n.readFile(F.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:P.deletedFiles,updated_files:P.updatedFiles,preserved_shared_files:P.preservedSharedFiles,warnings:P.warnings},historyPolicy:"none"})}catch(S){return ue(p,V.INTERNAL_ERROR,qe(S))}finally{g-=1}}async function iy(p,S){if(p.kind!=="insert-child"&&p.kind!=="replace-node")return ue(p,V.UNSUPPORTED_OPERATION,"Only page-unit insert-child and replace-node materialization are supported by this transaction.");if(p.params.kind!=="insert-child"&&p.params.kind!=="replace-node"||p.kind!==p.params.kind)return ue(p,V.INVALID_PARAMS,"Page-unit materialization operation kind must match its params.");if(p.params.kind==="insert-child"){if(!("kind"in p.params.position)||p.params.position.kind!=="page-composition")return ue(p,V.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(p.params.position.documentVersion!==p.documentVersion)return ue(p,V.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.")}let x=S.document,I=S.pageCompositionProjection;if(!x||x.pageComposition?.status!=="supported"||!I||I.status!=="supported")return ue(p,V.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==x.version||I.documentVersion!==x.version)return ue(p,V.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${x.version}).`);let P=p.params.node.kind==="component-call"?p.params.node.materialization:void 0;if(!P)return ue(p,V.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let _=p.params.kind==="insert-child"?p.params.position:null,F=await Lo({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:P.files.map(K=>({path:K.pathTemplate,content:K.content})),exists:K=>n.exists(K),readFile:K=>n.readFile(K)});if(!F.ok)return ue(p,V.MATERIALIZATION_REJECTED,F.message);let j=await oN(n,Object.keys(P.projectDependencies??{})),W=await Af({manifest:P,generatedRoot:"components/site/generated",controlledFiles:P.files.map(K=>({pathTemplate:K.pathTemplate})),exists:K=>n.exists(K),availableHostDependencies:j,commit:async K=>{let B=await n.readFile(S.entryFile),Z=S.document,te=S.pageCompositionProjection;if(!Z||Z.pageComposition?.status!=="supported"||Z.version!==p.documentVersion||!te||te.status!=="supported"||te.documentVersion!==Z.version)return{ok:!0,data:ue(p,V.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let he=K.entry.path,pe=my(K.instanceName),ke,Pe=[];if(p.params.kind==="insert-child"){if(!_||!("kind"in _)||_.kind!=="page-composition")return{ok:!0,data:ue(p,V.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.")};let me=oc({routeId:S.routeId,entryFile:S.entryFile,currentDocumentVersion:Z.version,expectedDocumentVersion:p.documentVersion,source:B,projection:te,placementKey:_.placementKey,component:{source:he,exportName:K.entry.export.kind==="default"?"default":K.entry.export.name,localName:pe}});if(!me.ok)return{ok:!0,data:ue(p,Ls(me.error.code),me.error.message,{diagnostics:me.error.diagnostics})};let Se=me.plan.rewriteStep,Ae;switch(Se.kind){case"insert-root-expression":Ae=Bi({source:B,locator:Se.locator,expectedSourceHash:Se.sourceHash,action:{kind:"insert",jsx:Se.node.jsx,placement:Se.placement,replaceOriginal:Se.replaceOriginal}});break;case"insert-child":Ae=Yn({source:B,locator:Se.parentLocator,node:Se.node,placement:Se.placement,...Se.anchorLocator?{anchorLocator:Se.anchorLocator}:{}});break;default:Ae={ok:!1,source:B,diagnostic:{code:"unsupported-syntax",message:`Unsupported route composition rewrite: ${String(Se)}`}}}if(!Ae.ok)return{ok:!0,data:ue(p,V.AST_PARSE_ERROR,Ae.diagnostic.message)};ke=Ae.source}else{let me=ic({routeId:S.routeId,composition:S.composition,entryFile:S.entryFile,currentDocumentVersion:Z.version,expectedDocumentVersion:p.documentVersion,source:B,projection:te,placementUnitKey:p.target.placementUnitKey,operation:"replace-node"});if(!me.ok)return{ok:!0,data:ue(p,Ls(me.error.code),me.error.message,{diagnostics:me.error.diagnostics})};let Se=me.plan.rewriteStep,Ae;switch(Se.kind){case"replace-root-expression":Ae=Bi({source:B,locator:Se.locator,expectedSourceHash:Se.sourceHash,action:{kind:"replace",jsx:`<${pe} />`}});break;case"replace-node":Ae=ti({source:B,locator:Se.locator,node:{jsx:`<${pe} />`}});break;default:Ae={ok:!1,source:B,diagnostic:{message:`Unsupported page-unit replacement rewrite: ${Se.kind}`}}}if(!Ae.ok)return{ok:!0,data:ue(p,V.AST_PARSE_ERROR,Ae.diagnostic.message)};let en=await Zl({routeState:S,placementUnitKey:p.target.placementUnitKey,source:B,mutatedSource:Ae.source});ke=en.source,Pe=await Promise.all(en.files.map(async it=>({operation:"delete",file:it,baseContentHash:Ie(await n.readFile(it))})))}let O=qn({source:ke,moduleSpecifier:k(S.entryFile,he),imports:K.entry.export.kind==="default"?[{kind:"default",local:pe}]:[{kind:"named",imported:K.entry.export.name,local:pe}]});if(!O.ok)return{ok:!0,data:ue(p,V.AST_PARSE_ERROR,O.diagnostic.message)};let U=K.files.map(me=>({operation:"create-only",file:me.path,content:me.content})),ae=[{operation:"upsert",file:S.entryFile,content:O.source,baseContentHash:Ie(B)},...U,...Pe];g+=1;try{let me=await Xn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:S.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:ae}});return!me.ok&&me.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:me.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:me}}finally{g-=1}}});return W.ok?W.data:ue(p,W.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?V.MATERIALIZATION_CONFLICT:V.MATERIALIZATION_REJECTED,W.error.message,{materializationCode:W.error.code})}async function sy(p,S){if(p.kind!=="move-node"&&p.kind!=="remove-node")return ue(p,V.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let x=S.document,I=S.pageCompositionProjection;if(!x||x.pageComposition?.status!=="supported"||!I||I.status!=="supported")return ue(p,V.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==x.version||I.documentVersion!==x.version)return ue(p,V.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${x.version}).`);let P=await n.readFile(S.entryFile),_=ic({routeId:S.routeId,composition:S.composition,entryFile:S.entryFile,currentDocumentVersion:x.version,expectedDocumentVersion:p.documentVersion,source:P,projection:I,placementUnitKey:p.target.placementUnitKey,operation:p.kind,targetPlacement:p.kind==="move-node"&&p.params.kind==="move-node"&&"kind"in p.params.target&&p.params.target.kind==="page-composition"?p.params.target:void 0});if(!_.ok)return ue(p,Ls(_.error.code),_.error.message,{diagnostics:_.error.diagnostics});let F=_.plan.rewriteStep,j;switch(F.kind){case"move-node":j=Zn({source:P,locator:F.locator,targetParentLocator:F.targetParentLocator,placement:F.placement,...F.anchorLocator?{anchorLocator:F.anchorLocator}:{}});break;case"remove-node":j=Gn({source:P,locator:F.locator});break;case"remove-root-expression":j=Bi({source:P,locator:F.locator,expectedSourceHash:F.sourceHash,action:{kind:"remove"}});break;default:j={ok:!1,source:P,diagnostic:{message:`Unsupported page-unit mutation rewrite: ${F.kind}`}}}if(!j.ok)return ue(p,V.AST_PARSE_ERROR,j.diagnostic.message);let W=j.source,K=[];if(p.kind==="remove-node"){let Z=await Zl({routeState:S,placementUnitKey:p.target.placementUnitKey,source:P,mutatedSource:W});W=Z.source,K=await Promise.all(Z.files.map(async te=>({operation:"delete",file:te,baseContentHash:Ie(await n.readFile(te))})))}let B=[{operation:"upsert",file:S.entryFile,content:W,baseContentHash:Ie(P)},...K];g+=1;try{return await Xn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:S.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:B}})}finally{g-=1}}async function Zl(p){let S={source:p.mutatedSource,files:[]},x=p.routeState.graph,I=p.routeState.pageCompositionProjection;if(!x||!I||I.status!=="supported"||!n.listFiles)return S;let _=I.placementUnitByKey.get(p.placementUnitKey)?.sourceRange;if(!_)return S;let F=[...x.elements.values()].find(O=>O.sourceFile===p.routeState.entryFile&&O.importedFrom&&C(O.sourceRange,_));if(!F?.importedFrom||!F.exportName)return S;let j=y(F.importedFrom),W="components/site/generated/";if(!j.startsWith(W))return S;let K=j.slice(W.length).split("/")[0];if(!K||!/-[0-9a-f]{8}$/i.test(K))return S;let B=`${W}${K}`;if([...x.elements.values()].filter(O=>O.sourceFile===p.routeState.entryFile&&y(O.importedFrom??"")===j).length!==1)return S;let te=await n.listFiles({maxFiles:5e3,maxDepth:32}),he=Array.isArray(te)?te:te.files;if(!Array.isArray(te)&&te.truncated)return S;let pe=he.map(({path:O})=>O).filter(O=>O===B||O.startsWith(`${B}/`));if(pe.length===0||!pe.includes(j))return S;for(let{path:O}of he)if(!(O===p.routeState.entryFile||O===B||O.startsWith(`${B}/`)))try{if((await n.readFile(O)).includes(K))return S}catch{return S}let ke=k(p.routeState.entryFile,j),Pe=er({source:p.mutatedSource,moduleSpecifier:ke,imports:F.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:F.exportName}]});return Pe.ok?Pe.source.includes(K)?{source:Pe.source,files:[]}:{source:Pe.source,files:pe.sort((O,U)=>O.localeCompare(U))}:S}async function ay(p){if(n.getFileInfo){for(let F of p)if(await n.exists(F.path)&&await n.getFileInfo(F.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${F.path}`,details:{path:F.path}}}for(let F of p){if(F.operation!=="upsert"||!/^(?:src\/)?app\/globals\.css$/i.test(F.path))continue;let j=await n.exists(F.path)?await qs(n,F.path):null;if(j?.ok){let W=Ww(j.content,F.content);if(!W.ok)return{ok:!1,errorCode:"invalid-params",message:W.message,details:{path:F.path,code:W.code}}}}let S=cy(p);if(S.length===0)return{ok:!0};let x=yN(n,p),I=new Map,P=(F,j)=>{let W=I.get(F);if(W?.source===j)return W.result;let K=Jt(F,j);return I.set(F,{source:j,result:K}),K},_;try{_=await Sh(S,async F=>{let j=i.get(F);return j?[...(await Oe(j.entryFile,await x.readFile(j.entryFile),x,{validationOnly:!0,parseModule:P,validatedImports:m.getImports})).parsedModules.values()]:[]})}catch(F){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${qe(F)}`,details:{compositionKeys:S}}}for(let F of _)m.remember(F);return{ok:!0}}function cy(p){return p.map(x=>x.path).some($h)?[...i.keys()]:[]}function Fs(p,S,x,I){let P=Ao(S);return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:oe(p),error:{code:P,message:x,...I?{details:I}:{}}}}async function _s(p){let S=[];for(let x of new Set(p))S.push(await ly(x));return S}async function ly(p){if(!(typeof n.exists=="function"?await n.exists(p):!0))return{file:p,content:"",version:Math.max(0,ee(p)),exists:!1};let x=await n.readFile(p);return{file:p,content:x,version:Math.max(1,ee(p)),exists:!0,sha256:Ie(x)}}async function Ql(p,S,x,I){if(!e.historyStore)return null;let P=new Map(S.map(j=>[j.file,j])),_=new Map(x.map(j=>[j.file,j])),F=[...new Set([...P.keys(),..._.keys()])].sort().map(j=>{let W=P.get(j),K=_.get(j);return{path:j,preDigest:W?.exists===!1||!W?null:Ie(W.content),postDigest:K?.exists===!1||!K?null:Ie(K.content)}});return{schemaVersion:2,transactionId:`${p}:${I.expectedIndexDigest}`,operationId:p,phase:"prepared",historyTransition:I,files:F}}async function ql(p){return!p||!e.historyStore||await e.historyStore.writeTransactionJournal(p),p}async function Jn(p){p&&e.historyStore&&await e.historyStore.clearTransactionJournal(p.transactionId)}async function Ms(p,S){let x=[];try{for(let I of p)await eu(I),typeof n.bumpVersion=="function"&&n.bumpVersion(I.file),x.push(I.file)}catch(I){let P=await uy(S.filter(_=>x.includes(_.file)));return P.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${qe(I)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${P.failedFiles.join(", ")}: ${qe(I)}`,rolledBack:!1}}return{ok:!0,snapshots:p.map(dy)}}async function eu(p){if(p.exists===!1){await n.deleteFile(p.file);return}await n.writeFile(p.file,p.content)}async function uy(p){let S=[];for(let x of p)try{await eu(x),typeof n.bumpVersion=="function"&&n.bumpVersion(x.file)}catch{S.push(x.file)}return S.length===0?{ok:!0}:{ok:!1,failedFiles:S}}function dy(p){let S=p.exists!==!1;return{file:p.file,content:S?p.content:"",version:p.version,exists:S,...S?{sha256:Ie(p.content)}:{}}}async function Xn(p){return b.runExclusive(()=>fy(p))}async function fy(p){let S=p.filePlan.edits.map(O=>O.file),x=o.resolveSelector(p.request.composition),I=x.context,P=p.historyPolicy==="none"?void 0:{initiatingComposition:I,affectedCompositions:Zh(S)},_=await _s(S),F=new Map(_.filter(O=>O.exists!==!1).map(O=>[O.file,O.content])),j=nu(),W=new Map(f),K=new Set(u),B=new Set([...i.values()].filter(O=>p.filePlan.edits.some(U=>U.operation==="delete"&&U.file===O.entryFile)).map(O=>O.key)),Z=p.filePlan.edits.map(O=>O.operation==="delete"?{file:O.file,content:"",version:0,exists:!1}:{file:O.file,content:O.content,version:0,exists:!0,sha256:Ie(O.content)}),te={operationId:p.filePlan.operationId,intents:p.filePlan.edits.map(O=>O.operation==="delete"?{kind:"delete",path:O.file}:{kind:O.operation==="create-only"?"create-only":"upsert",path:O.file,content:O.content})},he=null,pe=!1,ke=await Es({overlay:F,exists:O=>n.exists(O),plan:te,buildCandidate:async({plan:O})=>({plan:O}),prepareHistory:async()=>{let O=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:Z,...p.selectionRef?{selectionRef:p.selectionRef}:{},...p.output?{output:p.output}:{},...P?{provenance:P}:{}}),U=O?.historyTransition?O.historyTransition:e.historyStore?nN(await e.historyStore.readIndex()):null;if(e.historyStore&&!U)throw new Error("Durable history did not provide an exact index transition.");return he=await Ql(p.request.id,_,Z,U),he=await ql(he),{history:O,historyTransition:U}},reverify:async()=>{},writeCandidate:async()=>{let O=await d.executeFilePlan(p.filePlan);if(!O.ok)throw new Rs(O);return{postSnapshots:await _s(O.affectedFiles),affectedFiles:O.affectedFiles,internalResultVersion:O.resultVersion}},validateCandidate:async({candidate:O,receipt:U})=>{let ae=await Fo(U.affectedFiles,{changed:!0,minimumVersion:U.internalResultVersion,publish:!1,excludedCompositionKeys:B});if(ae.failedRoutes.length>0)throw new Vn(ae.failedRoutes);let me=ou(j,ae.candidateRouteStates??[]),Se=ru(me,x.key);return{...O,rebuild:ae,routeSnapshots:me,resultVersion:Se,...Lh(p.selectionRef,me.map(Ae=>Ae.state.document))?{selectionRef:Lh(p.selectionRef,me.map(Ae=>Ae.state.document))}:{}}},publishCandidate:async({candidate:O,history:U,receipt:ae})=>{U?.history&&(await l.publishPrepared(U.history),pe=!0);let me=O.resultVersion??ae.internalResultVersion;return{composition:I,requestId:p.request.id,kind:p.request.kind,target:p.request.target,ok:!0,resultVersion:me,affectedFiles:ae.affectedFiles,fileChanges:ae.postSnapshots.map(Se=>({path:Se.file,operation:Se.exists===!1?"delete":"upsert"})),...p.output?{output:p.output}:{},...O.selectionRef?{selectionRef:O.selectionRef}:{}}},swapCandidate:({candidate:O,receipt:U})=>{O.routeSnapshots&&_o(O.routeSnapshots),O.rebuild?.candidateSourceCache&&Er(f,O.rebuild.candidateSourceCache),Wl(U.postSnapshots)},finalizeCandidate:async()=>{await Jn(he);for(let O of B)i.delete(O)},emitCommitted:({candidate:O,published:U})=>{Ts(U,O.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:O,receipt:U})=>{if(pe)throw new Error("history was published before transaction finalization failed");if(U){let ae=await Ms(_,U.postSnapshots);if(!ae.ok)throw new Error(ae.reason)}_o(j),Er(f,W),Hl(K),O?.history&&await l.discardPrepared?.(O.history),await Jn(he)}});if(ke.ok)return ke.published;if(ke.stage==="precheck"||ke.stage==="build")try{await Jn(he)}catch(O){let U=await Mo(qe(O));return ue(p.request,U,"Unable to clear an uncommitted transaction journal.")}if(ke.recoveryRequired){let O=await Mo(ke.reason);return ue(p.request,O===V.RECOVERY_PERSIST_FAILED?O:V.ROLLBACK_FAILED,ke.reason)}let Pe=ke.error;return Pe instanceof Rs?{...ue(p.request,Ao(Pe.result.errorCode),Pe.result.reason),...Pe.result.affectedFiles?{affectedFiles:Pe.result.affectedFiles}:{}}:Pe instanceof Vn?ue(p.request,V.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${Bl(Pe.failedRoutes)}`,{failedRoutes:Pe.failedRoutes}):ue(p.request,su(ke.stage),qe(Pe))}async function tu(p){return b.runExclusive(async()=>{let S=p==="undo"?await l.prepareUndo():await l.prepareRedo();return S?py(p,S):{composition:o.entries[0].context,requestId:p,kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:o.initialVersions.get(o.entries[0].key)??0,error:{code:V.INTERNAL_ERROR,message:p==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function py(p,S){let x=S.entry,I=p==="undo"?x.preSnapshots:x.postSnapshots,P=p==="undo"?x.postSnapshots:x.preSnapshots,_=I.map(U=>U.file),{context:F,key:j}=qh(x,_),W=await _s(_),K=new Map(W.filter(U=>U.exists!==!1).map(U=>[U.file,U.content])),B=se(j),Z=nu(),te=new Map(f),he=new Set(u),pe=null,ke=!1,Pe,O=await Es({overlay:K,plan:{operationId:`${p}:${x.operationId}`,intents:I.map(U=>U.exists===!1?{kind:"delete",path:U.file}:{kind:"upsert",path:U.file,content:U.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(pe=await Ql(`${p}:${x.operationId}`,W,I,S.historyTransition),pe=await ql(pe),S),reverify:async()=>{},writeCandidate:async()=>{let U=await Ms(I,P);if(!U.ok)throw new Error(U.reason);return{snapshots:U.snapshots}},validateCandidate:async({candidate:U})=>{Pe=Qh(x,_);let ae=await Fo(_,{changed:!0,minimumVersion:B+1,publish:!1,affectedCompositionKeys:Pe});if(ae.failedRoutes.length>0)throw new Vn(ae.failedRoutes);let me=ou(Z,ae.candidateRouteStates??[]),Se=ru(me,j);return{...U,rebuild:ae,routeSnapshots:me,resultVersion:Se}},publishCandidate:async({candidate:U,history:ae,receipt:me})=>{if(!ae)throw new Error("history cursor intent is missing");await l.publishPrepared(ae),ke=!0;let Se=U.resultVersion??B+1;return{composition:F,requestId:p,kind:x.kind,target:x.target,ok:!0,resultVersion:Se,affectedFiles:_,fileChanges:me.snapshots.map(Ae=>({path:Ae.file,operation:Ae.exists===!1?"delete":"upsert"})),...x.output?{output:x.output}:{}}},swapCandidate:({candidate:U,receipt:ae})=>{U.routeSnapshots&&_o(U.routeSnapshots),U.rebuild?.candidateSourceCache&&Er(f,U.rebuild.candidateSourceCache),Wl(ae.snapshots)},finalizeCandidate:async()=>{await Jn(pe)},emitCommitted:({candidate:U,published:ae})=>Ts(ae,U.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:U,receipt:ae})=>{if(ke)throw new Error("history cursor was published before transaction finalization failed");if(ae){let me=await Ms(P,ae.snapshots);if(!me.ok)throw new Error(me.reason)}_o(Z),Er(f,te),Hl(he),U&&await l.discardPrepared?.(U),await Jn(pe)}});if(O.ok)return O.published;if(O.stage==="precheck"||O.stage==="build")try{await Jn(pe)}catch(U){let ae=await Mo(qe(U));return{composition:F,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:B,error:{code:ae,message:"Unable to clear an uncommitted transaction journal."}}}if(O.recoveryRequired){let U=await Mo(O.reason);return{composition:F,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:B,affectedFiles:_,error:{code:U===V.RECOVERY_PERSIST_FAILED?U:V.ROLLBACK_FAILED,message:O.reason}}}return{composition:F,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:B,affectedFiles:_,error:{code:O.error instanceof Vn?V.ROUTE_REBUILD_FAILED:su(O.stage),message:qe(O.error),...O.error instanceof Vn?{details:{failedRoutes:O.error.failedRoutes}}:{}}}}function nu(){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 ru(p,S){return p.find(I=>I.key===S)?.state.graph?.version??o.initialVersions.get(S)??0}function ou(p,S){let x=new Map(p.map(I=>[I.key,I]));for(let I of S)x.set(I.key,I);return[...x.values()]}function _o(p){for(let S of i.values())A(S);for(let S of p){let x={...S.state,dependencyFiles:new Set(S.state.dependencyFiles),fileVersions:new Map(S.state.fileVersions)};i.set(S.key,x),R(x,x.dependencyFiles)}}async function Os(p){let S=i.get(p);if(!S)throw new Error(`Composition not found: ${p}`);if(S.graph)return;let x=await n.readFile(S.entryFile);await Nt(p,x)}function zn(p,S){let x=i.get(o.resolveSelector(S).key)??null;return!x||!iu(x,p)?null:x}function iu(p,S){if(p.documentIndex?.entriesByKey.has(S)||p.graph?.elements.has(S))return!0;let x=ot(S);return x&&x!==S?p.graph?.elements.has(x)===!0:!1}function ue(p,S,x,I){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:oe(p),error:{code:S,message:x,...I?{details:I}:{}}}}function su(p){return p==="validate"?V.ROUTE_REBUILD_FAILED:p==="publish"?V.HISTORY_COMMIT_FAILED:V.WRITE_IO_ERROR}async function Mo(p){if(h=!0,!l.markRecoveryRequired)return V.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(p),V.RECOVERY_REQUIRED}catch{return V.RECOVERY_PERSIST_FAILED}}function my(p){let x=p.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(I=>I.charAt(0).toUpperCase()+I.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return x?`Prefab${x}`:"GeneratedPrefab"}function Ls(p){return p==="VERSION_STALE"?V.VERSION_STALE:p==="CROSS_PAGE_MOVE_UNSUPPORTED"?V.CROSS_PAGE_MOVE_UNSUPPORTED:V.UNSUPPORTED_OPERATION}async function au(p){if(p.target.kind==="route"){let x=i.get(o.resolveSelector(p.target.composition).key)??null;return x?(x.graph||await Os(x.key),x):ue(p,V.ROUTE_NOT_FOUND,"Composition not found for route target.")}if(p.target.kind==="page-unit"){let x=i.get(o.resolveSelector(p.target.composition).key)??null;return x?(x.graph||await Os(x.key),x):ue(p,V.ROUTE_NOT_FOUND,"Composition not found for page-unit target.")}if(p.target.kind!=="node")return ue(p,V.UNSUPPORTED_OPERATION,`${p.kind} source target execution is not implemented yet.`);let S=i.get(o.resolveSelector(p.composition).key)??null;return S?(S.graph||await Os(S.key),iu(S,p.target.key)?S:ue(p,V.NODE_NOT_FOUND,`Target key not found: ${p.target.key}`)):ue(p,V.ROUTE_NOT_FOUND,"Composition not found for node target.")}return{get status(){return t},dispose(){t="disposed",a.clear(),i.clear(),s.clear(),f.clear(),m.clear(),u.clear()},registerComposition(p,S){let x=o.register({context:p,entryFile:S}),I=i.get(x.key);if(I?.entryFile===S)return;I&&A(I);let P=Oh(x.context,S);i.set(x.key,P),R(P,P.dependencyFiles),r.emit({type:"graph-invalidated",composition:x.context})},unregisterComposition(p){let S=o.resolveSelector(p),x=i.get(S.key);x&&(A(x),i.delete(S.key),o.unregister(S.key),i.size===0&&(t="idle"),r.emit({type:"graph-invalidated",composition:S.context}))},getCompositionEntryFiles(){return[...i.values()].map(p=>p.entryFile)},getCompositionContext(p){return o.resolveSelector(p).context},async initializeComposition(p){let S=o.resolveSelector(p),x=i.get(S.key);if(!x)throw new Error(`Composition not registered: ${S.key}`);if(x.graph)t="ready";else{t="building";try{let I=await n.readFile(x.entryFile);await Nt(S.key,I),t="ready",r.emit({type:"graph-ready",composition:S.context,version:i.get(S.key)?.graph?.version??0})}catch(I){throw t="idle",r.emit({type:"graph-error",composition:S.context,message:qe(I)}),I}}},getDocument(p){let S=o.resolveSelector(p),x=i.get(S.key);if(!x)throw new Error(`Composition not registered: ${S.key}`);if(!x.document)throw new Error(`Composition not built: ${S.key}`);return x.document},async getHistoryStatus(){await E;let p=await l.getStatus?.();return p?{...p,recoveryRequired:h}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:h}},getObjectEditContext(p,S,x){let I=zn(p,S),P=ot(p)??p;if(I?.graph&&I.topology&&I.capabilities&&I.detailProjections){let _=I.detailProjections.get(P);if(_){let F=I.graph.elements.get(P);if(!F)throw new Error(`Key not found: ${p}`);let j=lN(p,P,x),W=new Map;if(_.isRepeat&&j?.instanceIndex!==void 0)for(let Z of F.attributes??[])W.set(Z.name,fl({file:F.sourceFile,source:f.get(F.sourceFile)??"",element:F,propertyName:Z.name,selectionRef:j,graph:I.graph,sources:f}));let K=Zg({element:F,graph:I.graph,source:f.get(F.sourceFile),documentVersion:I.graph.version,selectionRef:x,isRepeat:_.isRepeat,propertyProvenance:_.propertyProvenances,repeatTargets:W}),B=eh(P,I.graph,I.topology,I.capabilities,_.textSources,_.provenances,_.dynamicData,K);return p===P?B:wh(B,p,I.document??null,I.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getRenderDetail(p,S){let x=zn(p,S),I=ot(p)??p;if(x?.graph&&x.topology&&x.capabilities&&x.detailProjections){let P=x.detailProjections.get(I);if(P){let _=qg(I,x.graph,x.topology,x.capabilities,P.textSources,P.writeTarget,P.provenances,P.conditional,P.componentSemantic,P.styleSource,P.dynamicData);return p===I?_:Rh(_,p,x.document??null,x.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getClassNameSource(p,S){let x=zn(p,S),I=ot(p)??p;if(!x?.graph)throw new Error(`Key not found: ${p}`);let P=x.graph.elements.get(I);if(!P)throw new Error(`Key not found: ${p}`);let _=f.get(P.sourceFile);if(_===void 0)throw new Error(`Source not loaded: ${P.sourceFile}`);return xa({key:I,route:{composition:x.composition,routeId:x.routeId,graph:x.graph,source:_}})},refreshSourceForKey:ty,async execute(p){if(await E,h)return ue(p,V.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(p.kind==="source-edit")return ny(p);if(p.kind==="insert-page-resource")return ry(p);if(p.kind==="delete-page-source")return oy(p);let S=await au(p);if("ok"in S)return S;await Yl(p);let x=await au(p);if("ok"in x)return x;let I=x;if(p.target.kind==="page-unit"){let B=p;return p.kind==="insert-child"||p.kind==="replace-node"?iy(B,I):p.kind==="move-node"||p.kind==="remove-node"?sy(B,I):ue(p,V.UNSUPPORTED_OPERATION,"Only page-unit insert-child, replace-node, move-node, and remove-node are currently supported by the page composition transaction.")}let _=p.params,F=p.target.kind==="node"?p.target.key:null;if(_.kind==="move-node"&&"kind"in _.target&&_.target.kind==="source-sibling"){let B=_.target,Z=F?I.document?.entries.find(U=>U.key===F):null,te=I.document?.entries.find(U=>U.key===B.anchorKey),he=Z?.pageCompositionActionScope,pe=he?.kind==="source-siblings"?he.siblingKeys:null,ke=pe?.indexOf(Z?.key??"")??-1,Pe=pe?.indexOf(B.anchorKey)??-1,O=B.relation==="before"?ke-1:ke+1;if(!Z||!te||!pe||ke<0||Pe!==O||te.pageCompositionActionScope?.kind!=="source-siblings"||te.pageCompositionActionScope.siblingKeys.length!==pe.length||te.pageCompositionActionScope.siblingKeys.some((U,ae)=>U!==pe[ae])||!Z.operationSummary.canMove)return ue(p,V.INVALID_TARGET,"Source sibling move is unavailable because the current source sibling scope or adjacent anchor no longer matches.")}if(!I.graph||!I.topology||!I.capabilities)return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:oe(p),error:{code:p.target.kind==="route"?V.ROUTE_NOT_FOUND:V.NODE_NOT_FOUND,message:p.target.kind==="route"?"Composition not ready for route target.":p.target.kind==="node"?`Target key not found: ${p.target.key}`:`${p.kind} source target execution is not implemented yet.`}};let j=wN(I,I.graph,I.capabilities,f,i),W=await new is(j).plan(p);if(!W.ok)return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:oe(p),error:{code:Ao(W.errorCode),message:W.reason}};let K=W.plan;if(K.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:oe(p),affectedFiles:[]}:{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:oe(p),error:{code:V.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};g+=1;try{if(K.steps.some(Z=>Z.type==="invoke-external-adapter")){let Z=await d.execute(K);if(!Z.ok)return ue(p,Ao(Z.errorCode),Z.reason);let te={composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!0,resultVersion:Math.max(oe(p),Z.resultVersion),affectedFiles:Z.affectedFiles,...Z.selectionRef?{selectionRef:Z.selectionRef}:{}};return Ts(te,{rebuiltRoutes:[],failedRoutes:[]}),te}let B=await d.prepareRewritePlan(K);return B.ok?await Xn({request:p,filePlan:B.filePlan,...B.selectionRef?{selectionRef:B.selectionRef}:{}}):ue(p,Ao(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:oe(p),error:{code:V.INTERNAL_ERROR,message:qe(B)}}}finally{g-=1}},async undo(p){if(await E,h)return{composition:o.entries[0].context,requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:se(o.entries[0].key),error:{code:V.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};g+=1;try{return await tu("undo")}finally{g-=1}},async redo(p){if(await E,h)return{composition:o.entries[0].context,requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:se(o.entries[0].key),error:{code:V.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};g+=1;try{return await tu("redo")}finally{g-=1}},notifyFileChanged(p){Xl([p])},getAffectedCompositions(p){return Yh(p)},subscribe(p){return r.subscribe(p)}}}function SN(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function EN(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&&To(f.sourceRange,h.sourceRange)));if(!m)continue;let u=m.placementUnitKey;a(f,u)}let l=!0;for(;l;){l=!1;for(let f of t.elements.values()){if(f.sourceFile===n.entryFile||!f.importedFrom||!/^[A-Z]/.test(f.tag))continue;let m=c(f);if(m)for(let u of m)l=a(f,u)||l}}let d=n.placements.find(f=>f.placementKey===n.container.placementKey&&f.relation==="append");for(let f of e.entries){let m=ot(f.key)??f.key,u=t.elements.get(f.key)??t.elements.get(m);if(!u)continue;if(u.sourceFile===n.entryFile){if(n.container.sourceRange&&To(u.sourceRange,n.container.sourceRange)&&d){f.pageCompositionUnitKey=d.placementUnitKey;continue}let b=n.placements.find(E=>E.members.some(y=>y.sourceRange!==null&&(To(u.sourceRange,y.sourceRange)||RN(y.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)}vN(e,t,n,r)}function vN(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&&To(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!==(ot(m.key)??m.key))continue;let g=r.get(u.sourceFile);if(!g)continue;let h=ce(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()&&_e(E))){d(u)===1&&Bh(b)&&(m.pageCompositionActionScope={kind:"route-unit"});continue}if(!Bh(E))continue;let y=f.get(E.node)??[];y.push({entry:m,element:u,parentPath:E}),f.set(E.node,y)}for(let m of f.values()){let u=m[0];if(!u)continue;let g=u.entry.pageCompositionUnitKey,h=[],b=!!(g&&d(u.element)===1);for(let y of u.parentPath.node.children){if(kN(y))continue;if(!IN(y)){b=!1;break}let k=[...t.elements.values()].find(N=>N.sourceFile===u.element.sourceFile&&N.componentName===u.element.componentName&&To(N.sourceRange,CN(y))),C=k?o.get(k.identity.key):null;if(!k||!C||C.parentKey||C.pageCompositionUnitKey!==g||d(k)!==1){b=!1;break}h.push(C)}if(!b||h.length!==m.length||m.some(({entry:y})=>!h.some(k=>k.key===y.key)))continue;if(h.length===1){h[0].pageCompositionActionScope={kind:"route-unit"};continue}if(h.length<2)continue;let E=h.map(y=>y.key);for(let y of h)y.pageCompositionActionScope={kind:"source-siblings",siblingKeys:E}}}function Bh(e){let t=e.parentPath;return!!(t?.isReturnStatement?.()||t?.isArrowFunctionExpression?.()&&t.node.body===e.node)}function kN(e){return!!(e&&typeof e=="object"&&e.type==="JSXText"&&!(e.value??"").trim())}function IN(e){return!!(e&&typeof e=="object"&&e.type==="JSXElement")}function CN(e){return{startLine:e.loc?.start.line??-1,startColumn:e.loc?.start.column??-1,endLine:e.loc?.end.line??-1,endColumn:e.loc?.end.column??-1}}function To(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function RN(e,t){return jh(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&jh(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function jh(e,t,n,r){return e!==n?e-n:t-r}function wN(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=ot(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:xa({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(y=>y.name===f);return E?E.source?{status:"blocked",owner:"generic",diagnostic:{code:"unsupported-property-source",message:`Property '${f}' has an unresolved value source`}}:{status:"direct",owner:"generic",attribute:E,target:{kind:"jsx-attribute",file:g.sourceFile,sourceRange:E.sourceRange}}:(g.attributeSpreads?.length??0)>0?{status:"blocked",owner:"generic",diagnostic:{code:"ambiguous-property-source",message:`A spread may provide or override property '${f}'`}}:{status:"missing",owner:"generic"}},getRepeatPropertyTarget(d,f,m){let u=c(d),g=t.elements.get(u.baseKey);if(!g)return{ok:!1,errorCode:"repeat-not-found",reason:`Node not found: ${d}`};let h=m?{...m,key:u.baseKey}:u.repeatIndex!==null?{key:u.baseKey,instanceIndex:u.repeatIndex}:void 0;return fl({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=Zw(d);return f?{baseKey:f.baseKey,repeatIndex:Ch(e.document??null,d,f.baseKey,e.documentIndex)??Ih(f)}:{baseKey:d,repeatIndex:null}}function l(d,f){let m=ot(d)??d,u=e.documentIndex?.entriesByKey.get(d);return{key:d,file:f.sourceFile,component:f.componentName,tag:f.tag,structuralPath:f.identity.structuralPath,sourceRange:f.sourceRange,parentKey:u?.parentKey??f.parentKey??void 0,isRepeatRegion:f.boundaryKind==="repeat-region"||s.has(m),isBoundary:!1,importedFrom:f.importedFrom,exportName:f.exportName,isRepeatItemRoot:i.has(m),repeatOwnerKey:i.get(m)??s.get(m),attributes:f.attributes?.map(g=>({name:g.name,value:g.value,source:g.source?{expression:g.source.expression,base:g.source.base,path:g.source.path.map(h=>({...h}))}:null,resolvedValue:g.resolvedValue}))}}}var NN={"stale-version":V.VERSION_STALE,"capability-denied":V.CAPABILITY_REJECTED,"invalid-params":V.INVALID_PARAMS,"locator-miss":V.LOCATOR_FAILED,"route-not-found":V.ROUTE_NOT_FOUND,"unsupported-operation":V.UNSUPPORTED_OPERATION,"invalid-target":V.INVALID_TARGET,"ast-error":V.AST_PARSE_ERROR,"writeback-failed":V.WRITE_IO_ERROR,"rollback-failed":V.RECOVERY_REQUIRED,unknown:V.INTERNAL_ERROR};function Ao(e){return NN[e]}function qe(e){return e instanceof Error&&e.message?e.message:String(e)}function $h(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function PN(e){let t=Kn(e);if(!eN.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=>tN.map(a=>`${s}/${a}`))}function AN(e){let n=Kn(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function TN(e){return Uh(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function FN(e){return Uh(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function Uh(e,t){let n=[];for(let r of e.matchAll(t)){let o=Jh(r[1]??"");o&&n.push(o)}return n}function Vh(e,t){let n=Jh(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(`${_N(e)}/${n}`):n.startsWith("/")?Kn(n.slice(1)):Kl(n)?Kn(n):null}function Jh(e){return e.split(/[?#]/,1)[0]?.trim()??""}function Kl(e){return/\.css$/i.test(e)}function _N(e){let t=Kn(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function MN(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 Ns=class{constructor(t){this.options=t,this.fileSystem=new Cr(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}getDocument(t){return Ko(this.engine.getDocument(t),{siteId:this.options.siteId,snapshotId:this.options.snapshotId})}getInternalDocument(t){return this.engine.getDocument(t)}getStyleContext(t){return this.engine.getDocument(t).styleContext??null}getObjectEditContext(t,n,r){return Uo(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return zo(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}getSourceFile(t){return Wo(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}resolveSourceLocation(t){return Ho(t,this.engine.getRenderDetail(t.key,t.composition))}async planOperation(t){let n=DN.safeParse(t);if(!n.success)return{result:Vo(t,n.error.issues.map(i=>i.message))};let r=new Cr(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=BN.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(l=>jN(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 ws({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=Jo(o,{siteId:this.options.siteId,snapshotId:this.options.snapshotId});i&&this.options.onEvent?.(i)}:void 0,dev:this.options.dev,...this.options.historyStore?{historyStore:this.options.historyStore}:{},...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,...this.options.initialDocumentVersions?{initialDocumentVersions:this.options.initialDocumentVersions}:{},resourceTranslationLocale:this.options.resourceTranslationLocale})}};function jN(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:Ie(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:Ie(e.before)},fullContent:e.after}}function $N(e){return new Ns(e)}import{SiteEditOperationRequestSchema as UN}from"@vcp-dev/contracts";import wt from"node:fs/promises";import et from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as VN,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as KN}from"@vcp-dev/contracts";var Ps=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=ws({...t,fileSystem:this.fileSystem})}get status(){return this.engine.status}registerComposition(t,n){this.engine.registerComposition(t,n)}unregisterComposition(t){this.engine.unregisterComposition(t)}getDocument(t){return this.engine.getDocument(t)}getAffectedCompositions(t){return this.engine.getAffectedCompositions(t)}getCompositionContext(t){return this.engine.getCompositionContext(t)}initializeComposition(t){return this.engine.initializeComposition(t)}getHistoryStatus(){return this.engine.getHistoryStatus()}getObjectEditContext(t,n,r){return r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n)}getRenderDetail(t,n){return this.engine.getRenderDetail(t,n)}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return zo(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.engine.getCompositionEntryFiles()})}getSourceFile(t){return Wo(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.engine.getCompositionEntryFiles()})}resolveSourceLocation(t){return Ho(t,this.engine.getRenderDetail(t.key,t.composition))}refreshSourceForKey(t,n){return this.engine.refreshSourceForKey(t,n)}execute(t){return this.engine.execute(t)}undo(t){return this.engine.undo(t)}redo(t){return this.engine.redo(t)}notifyFileChanged(t){this.engine.notifyFileChanged(t)}subscribe(t){return this.engine.subscribe(t)}dispose(){this.engine.dispose()}createFileSystem(){if(this.options.fileSystem)return this.options.fileSystem;let t=new Map,{projectRoot:n}=this.options;return{async readFile(r){return wt.readFile(et.join(n,r),"utf8")},async readFileBytes(r){return wt.readFile(et.join(n,r))},async getFileInfo(r){let o=et.join(n,...r.split("/"));try{let i=await wt.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await pi(et.join(n,r),o)},async createExclusive(r,o){let i=et.join(n,r);await wt.mkdir(et.dirname(i),{recursive:!0});let s=await wt.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await wt.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await wt.rm(et.join(n,r),{force:!0});let o=r.replace(/\\/g,"/"),i=["components/site/generated","src/components/site/generated"].find(c=>o.startsWith(`${c}/`));if(!i)return;let s=et.join(n,i),a=et.dirname(et.join(n,o));for(;a!==s&&a.startsWith(`${s}${et.sep}`);){try{await wt.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=et.dirname(a);continue}break}a=et.dirname(a)}},async exists(r){try{return await wt.access(et.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...KN,...VN],i=[],s=new Set,a=new Set,c=0;for(let f of o)await d(f,i,1);let l=i.sort((f,m)=>f.path.localeCompare(m.path));return a.size>0?{files:l,truncated:{reasons:[...a]}}:{files:l};async function d(f,m,u){if(r.maxDepth!==void 0&&u>r.maxDepth){a.add("max-depth");return}let g=et.join(n,...f.split("/")),h;try{h=await wt.lstat(g)}catch{return}if(h.isSymbolicLink())return;if(h.isFile()){let E=h.ino>0?`${String(h.dev)}:${String(h.ino)}`:null;if(E&&s.has(E))return;if(r.maxFiles!==void 0&&m.length>=r.maxFiles){a.add("max-files");return}if(r.maxTotalBytes!==void 0&&c+h.size>r.maxTotalBytes){a.add("max-total-bytes");return}E&&s.add(E),m.push({path:f,sizeBytes:h.size}),c+=h.size;return}if(!h.isDirectory())return;if(r.maxFiles!==void 0&&m.length>=r.maxFiles){a.add("max-files");return}let b=await wt.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 Ul(e){return new Ps(e)}var As=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=Ul({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=Jo(n,{siteId:t.siteId,snapshotId:t.snapshotId});if(r){t.onEvent?.(r);for(let o of this.listeners)o(r)}},dev:t.dev,...t.historyStore?{historyStore:t.historyStore}:{},...t.tenantId?{tenantId:t.tenantId}:{},...t.initialDocumentVersions!==void 0?{initialDocumentVersions:t.initialDocumentVersions}:{},siteId:t.siteId,snapshotId:t.snapshotId})}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}registerComposition(t,n){this.engine.registerComposition(t,n)}unregisterComposition(t){this.engine.unregisterComposition(t)}getDocument(t){return{ok:!0,composition:this.engine.getCompositionContext(t),data:Ko(this.engine.getDocument(t),{siteId:this.options.siteId,snapshotId:this.options.snapshotId})}}getInternalDocument(t){return this.engine.getDocument(t)}getStyleContext(t){return{ok:!0,composition:this.engine.getCompositionContext(t),data:this.engine.getDocument(t).styleContext??null}}async getHistoryStatus(){return{ok:!0,composition:this.options.compositions[0].context,data:await this.engine.getHistoryStatus()}}getObjectEditContext(t,n,r){return{ok:!0,composition:this.engine.getCompositionContext(n),data:Uo(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}}getClassNameSource(t,n){return{ok:!0,composition:this.engine.getCompositionContext(n),data:this.engine.getClassNameSource(t,n)}}async getSourceTree(t){return{ok:!0,composition:this.engine.getCompositionContext(t),data:await this.engine.getSourceTree(t)}}async getSourceFile(t){return{ok:!0,composition:this.engine.getCompositionContext(t.composition),data:await this.engine.getSourceFile(t)}}resolveSourceLocation(t){return{ok:!0,composition:this.engine.getCompositionContext(t.composition),data:this.engine.resolveSourceLocation(t)}}refreshSourceForKey(t,n){return this.engine.refreshSourceForKey(t,n)}async executeOperation(t,n){let r=n===void 0||t.mutationContext!==void 0?t:{...t,mutationContext:n},o=UN.safeParse(r);if(!o.success)return Vo(t,o.error.issues.map(s=>s.message));let i=await this.engine.execute(o.data);if(!i.ok){let s=i.error;if(!s)throw new Error("executeOperation failed without an error payload");return{ok:!1,composition:i.composition,error:{code:s.code,message:s.message,...s.details?{details:s.details}:{}},data:{requestId:i.requestId,kind:i.kind,composition:i.composition,target:i.target,resultVersion:i.resultVersion,...i.affectedFiles?.length?{affectedFiles:i.affectedFiles}:{}}}}return{ok:!0,composition:i.composition,data:Cn(i)}}async undo(t){let n=await this.engine.undo();if(!n.ok){let r=n.error;if(!r)throw new Error("undo failed without an error payload");return{ok:!1,composition:n.composition,error:{code:r.code,message:r.message},data:{requestId:n.requestId,kind:n.kind,composition:n.composition,target:n.target,resultVersion:n.resultVersion}}}return{ok:!0,composition:n.composition,data:Cn(n)}}async redo(t){let n=await this.engine.redo();if(!n.ok){let r=n.error;if(!r)throw new Error("redo failed without an error payload");return{ok:!1,composition:n.composition,error:{code:r.code,message:r.message},data:{requestId:n.requestId,kind:n.kind,composition:n.composition,target:n.target,resultVersion:n.resultVersion}}}return{ok:!0,composition:n.composition,data:Cn(n)}}notifyFileChanged(t){this.engine.notifyFileChanged(t)}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}dispose(){this.listeners.clear(),this.engine.dispose()}};function JN(e){return new As(e)}export{ie as FileHistoryStoreError,qr as PageTemplateManagedSourceError,As as PreviewFileSystemSiteEditEngineRuntime,pf as SITE_EDIT_RAW_COLOR_LITERAL_RE,Ns as SnapshotSiteEditEngineRuntime,Lo as checkComponentI18nHostCompatibility,op as computeManagedPageTemplatePaths,JN as createPreviewSiteEditEngineRuntime,$N as createSiteEditEngineRuntime,tp as decodePageTemplateKey,xc as encodePageTemplateId,By as instrumentSiteEditRuntimeAttributes,ip as isManagedPageTemplateSourcePath,Kd as openFileHistoryStore,vy as parseSourceModule,ky as resolveImportBase,Lk as resolveManagedPageTemplateComposition,Vi as scanManagedPageTemplateCandidates,ap as scanSiteEditCompositionsFromFiles,zr as scanSiteEditThemeStyleViolations};
|