@vcp-dev/site-edit-engine 0.10.76 → 0.10.77

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 CHANGED
@@ -1,14 +1,14 @@
1
- import*as My from"@babel/parser";import*as Ye from"@babel/types";import*as rn from"node:path";var Zs=[".tsx",".ts",".jsx",".js"],Oy=Zs.map(e=>`/index${e}`),Ly=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 Iu(e){let t=e.replace(/[?#].*$/,""),n=/\.([a-z0-9]+)$/i.exec(t);return n!==null&&Ly.has(n[1].toLowerCase())}function Cu(e){let t=[];for(let n of e.program.body)Ye.isImportDeclaration(n)&&typeof n.source.value=="string"&&It(n.source.value)&&t.push(n.source.value),Ye.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&It(n.source.value)&&t.push(n.source.value),Ye.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&It(n.source.value)&&t.push(n.source.value);return Ye.traverseFast(e.program,n=>{let r=Ye.isImportExpression(n)?n.source:Ye.isCallExpression(n)&&Ye.isImport(n.callee)?n.arguments[0]:null;Ye.isStringLiteral(r)&&It(r.value)&&t.push(r.value)}),t}function It(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function In(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=rn.dirname(e);return rn.join(n,t).replace(/\\/g,"/")}async function Dy(e,t){if(Zs.some(n=>e.endsWith(n))&&await t(e))return e;for(let n of Zs){let r=`${e}${n}`;if(await t(r))return r}for(let n of Oy){let r=`${e}${n}`;if(await t(r))return r}return null}async function Cn(e,t,n){let r=await Ko(e,t,n);return r.ok?r.path:null}async function Ko(e,t,n){let r=In(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 Dy(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(!It(t)||t.includes("\0")||t.includes("\\")||rn.posix.isAbsolute(n))return!1;let r=rn.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!rn.posix.isAbsolute(e)}import{createHash as $y}from"node:crypto";import*as Ru from"@babel/parser";function Rn(e,t,n,r){return{code:e,message:t,locatorKind:n,details:r}}function X(e,t,n,r,o){return{ok:!1,source:e,diagnostic:Rn(t,n,r,o)}}function Qs(e,t,n,r,o){return{ok:!1,source:e,diagnostic:Rn(t,n,r,o)}}var jy={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function Mt(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:Ru.parse(t,{sourceType:"module",plugins:jy[n]})}}catch(r){return{ok:!1,source:t,diagnostic:Rn("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function qs(e,t){return Mt({source:e,profile:wu(t.kind)})}function Fr(e,t){return Mt({source:e,profile:wu(t)})}function wu(e){return"next-app-entry"}function wn(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 Wt=(e,t)=>{let n=Mt({source:t,profile:wn({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${$y("sha256").update(t).digest("hex")}`,ast:n.ast,imports:Cu(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};function Vy(e,t){return Wt(e,t)}function Ky(e,t){return In(e,t)}import{COMPONENT_I18N_FILE_SUFFIX as Uy,parseComponentI18nResourcesJson as Jy,resolveSiteTextDirection as Xy,SiteLocaleSchema as zy}from"@vcp-dev/contracts";var Wy=["i18next","react-i18next"],Hy="components/ui/site-locale-provider.tsx",Gy="components/ui/component-i18n-provider.tsx",Nu="app/layout.tsx";async function Uo(e){let t=e.files.filter(f=>f.path.endsWith(Uy));if(t.length===0)return{ok:!0};for(let f of["package.json",Nu,Hy,Gy])if(!await e.exists(f))return on(`Target snapshot is missing required i18n host file: ${f}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return on("Target snapshot package.json is invalid.")}let r=Pu(n)&&Pu(n.dependencies)?n.dependencies:{},o=Wy.filter(f=>typeof r[f]!="string"||r[f].trim().length===0);if(o.length>0)return on(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile(Nu),s=ea(i,"html","lang"),a=ea(i,"html","dir"),c=ea(i,"SiteLocaleProvider","locale"),l=zy.safeParse(s);if(!l.success||!a||!c||s!==c||a!==Xy(l.data))return on("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 on("Target snapshot root layout is not wired to SiteLocaleProvider.");let u=l.data;if(e.targetLocale&&e.targetLocale!==u)return on("Target snapshot locale does not match the authoritative site language.");let d=u.split("-")[0];for(let f of t){let g=Jy(f.content);if(!g.success)return on(`Component i18n resource is invalid: ${f.path}.`);if(!e.deferTargetLocale&&!Object.hasOwn(g.data,u)&&!Object.hasOwn(g.data,d))return on(`Component i18n resource ${f.path} has no locale for ${u} or ${d}.`)}return{ok:!0}}function ea(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 Pu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function on(e){return{ok:!1,message:e}}import na from"@babel/generator";import*as Ou from"@babel/parser";import ra from"@babel/traverse";import*as Ne from"@babel/types";import{computeSiteEditSourceIdentityKey as Zy}from"@vcp-dev/contracts";var Au="data-vcp-ui-component",Jo="components/ui";function Ht(e){if(!e)return!1;let t=ta(e);return t===Jo||t.startsWith(`${Jo}/`)||t.includes(`/${Jo}/`)||t.endsWith(`/${Jo}`)}function Nn(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?Ht(e.slice(2)):e.startsWith("./")||e.startsWith("../")?Ht(ta(`${Yy(t)}/${e}`)):Ht(e):!1}function ta(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 Yy(e){let t=ta(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}import{stripSiteEditRepeatInstanceKeys as kP}from"@vcp-dev/contracts";import{isSiteEditRuntimeContainerTag as CP,isSiteEditRuntimeTextTag as RP}from"@vcp-dev/contracts/site-edit-runtime-capability";var Tu={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 Qy=typeof na=="function"?na:na.default,qy=typeof ra=="function"?ra:ra.default,ex=new Set(["base","body","head","html","link","meta","noscript","script","style","template","title"]),tx="suppressHydrationWarning",nx=new Set(["SiteEditBootstrap"]);function rx(e){let t=sx(e.file,e.projectRoot);if(!ix(e.source)||Ht(t))return{code:e.source,elements:[]};let n=e.attributes??Tu,r=Ou.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]}),o=[],i=cx(r,t);return qy(r,{JSXElement(s){let a=s.node.openingElement,c=a.name;if(!ux(c)||Lu(a,n.key))return;let l=fx(s)??"default",u=mx(s),d=Zy(t,l,u),f=zo(c)??"unknown",g=ax(c)?"jsx":"component-call";if(g==="component-call"&&!px(s.node.children)&&nx.has(f))return;let m=g==="component-call"&&lx(f,i);dx(a,n.key,d),m&&Fu(a,Au),ox(s)&&Fu(a,tx),o.push({key:d,tag:f,componentName:l,sourceFile:t,sourceKind:g})}}),o.length===0?{code:e.source,elements:o}:{code:Qy(r,{jsescOption:{minimal:!0}}).code,elements:o}}function ox(e){return!e.findParent(t=>t.isJSXElement())}function ix(e){return/(?:^|[=(:,?;\[{>&|\n\r]|return\s+)\s*<(?:[A-Za-z][\w.:-]*|>)(?:\s|>|\/)/m.test(e)}function sx(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 ax(e){return Ne.isJSXIdentifier(e)&&/^[a-z]/.test(e.name)}function zo(e){return Ne.isJSXIdentifier(e)?e.name:Ne.isJSXMemberExpression(e)?Bu(e):null}function cx(e,t){let n=new Set;for(let r of e.program.body)if(!(!Ne.isImportDeclaration(r)||!Nn(r.source.value,t)))for(let o of r.specifiers)n.add(o.local.name);return n}function lx(e,t){let n=e.split(".")[0]??e;return t.has(n)}function ux(e){let t=zo(e);return!t||t==="Fragment"||t.endsWith(".Fragment")?!1:!ex.has(t)}function Lu(e,t){return e.attributes.some(n=>Ne.isJSXAttribute(n)&&Ne.isJSXIdentifier(n.name,{name:t}))}function dx(e,t,n){Du(e,Ne.jsxAttribute(Ne.jsxIdentifier(t),Ne.stringLiteral(n)))}function Fu(e,t){Lu(e,t)||Du(e,Ne.jsxAttribute(Ne.jsxIdentifier(t),null))}function Du(e,t){let n=e.attributes.findIndex(r=>Ne.isJSXSpreadAttribute(r));if(n>=0){e.attributes.splice(n,0,t);return}e.attributes.push(t)}function Bu(e){return`${Ne.isJSXIdentifier(e.object)?e.object.name:Bu(e.object)}.${e.property.name}`}function fx(e){let t=e;for(;t;){if(t.isFunctionDeclaration()||t.isClassDeclaration())return t.node.id?.name??null;if(t.isVariableDeclarator()&&Ne.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 px(e){return e.some(t=>Ne.isJSXElement(t)||Ne.isJSXFragment(t))}var _u=new WeakMap,Xo=new WeakMap,oa=new WeakMap;function mx(e){let t=_u.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=gx(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return _u.set(e.node,o),o}function gx(e){let t=zo(e.node.openingElement.name);return!t||t==="Fragment"||t.endsWith(".Fragment")?null:/^[A-Z]/.test(t)?`component:${t}#${Mu(e,t)}`:`${t}#${Mu(e,t)}`}function Mu(e,t){let n=ju(e)??e.getFunctionParent();if(!n)return 0;let r=oa.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=oa.get(n.node);o||(o=new Map,oa.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()?Wo(n):hx(n);for(let c of a)if(zo(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 hx(e){let t=Xo.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!ju(r)&&n.push(r)}}),Xo.set(e.node,n),n}function ju(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 Wo(e){let t=Xo.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(...Wo(o));continue}o.isJSXExpressionContainer()&&n.push(...Pn(o.get("expression")))}return Xo.set(e.node,n),n}function Pn(e){if(e.isJSXElement())return[e];if(e.isJSXFragment())return Wo(e);if(e.isParenthesizedExpression())return Pn(e.get("expression"));if(e.isLogicalExpression()&&e.node.operator==="&&")return Pn(e.get("right"));if(e.isConditionalExpression())return[...Pn(e.get("consequent")),...Pn(e.get("alternate"))];if(e.isCallExpression()&&xx(e.node)){let t=e.get("arguments")[0];return yx(t)}return[]}function yx(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return[t];if(t.isJSXFragment())return Wo(t);if(t.isParenthesizedExpression())return Pn(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?Pn(r):[]}return[]}function xx(e){return Ne.isMemberExpression(e.callee)&&Ne.isIdentifier(e.callee.property)&&e.callee.property.name==="map"}import{SiteEditOperationRequestSchema as qN,SiteEditPatchPlanSchema as eP}from"@vcp-dev/contracts";function An(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 Ho(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 Go(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 Yo(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:bx(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 Zo(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:An(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 bx(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 lN,computeSiteEditCompositionKey as uN,getSiteEditSourceDeleteProtectionReason as dN,isSiteEditTextSourcePath as fN,parseSiteEditRepeatInstanceKey as pN,SITE_EDIT_SOURCE_DELETE_CAPABILITY as mN,stripSiteEditRepeatInstanceKeys as at}from"@vcp-dev/contracts";import Ls from"node:path";import{parse as gN}from"yaml";import la from"node:path";import{TextDecoder as Ex}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as Vu,SITE_EDIT_SOURCE_ALLOWED_DIRS as Ku,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as Uu,SiteEditCompositionContextSchema as vx,SiteEditSourceFileResponseSchema as ia,SiteEditSourceLocationSchema as kx,SiteEditSourcePathSchema as Qo,SiteEditSourceTreeResponseSchema as Ix,isSiteEditTextSourcePath as Cx}from"@vcp-dev/contracts";import{createHash as Sx}from"node:crypto";var _r=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 Re(e){return`sha256:${Sx("sha256").update(e).digest("hex")}`}var Rx=[...Uu,...Vu,...Ku];function ua(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return vx.parse(e.composition)}var sa=2e3,aa=12,ca=24*1024*1024,$u=512*1024,wx=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),Nx={".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"},Px={".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"},Ax=new Ex("utf-8",{fatal:!0});async function qo(e,t={}){let n=ua(t),{files:r,truncated:o}=await Dx(e,t),i=$x(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 ei(e,t,n={}){let r=ua(n),o=Qo.parse(t.path),i=await Fx(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(fa(o)){let a=zu(o),c=await Mx(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return ia.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...c})}let s=await da(e,o);return s.ok?ia.parse({composition:r,path:o,kind:"text",language:Wu(o),sizeBytes:s.sizeBytes,contentHash:Re(s.content),readonly:!1,content:s.content}):ia.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function da(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=Tx(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 Tx(e){if(e.includes(0))return null;try{return Ax.decode(e)}catch{return null}}async function Fx(e,t,n){if(!Ox(t,n))return null;let r=await _x(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function _x(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=Ju(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(fa(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(!wx.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>$u)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>$u?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function Ox(e,t){return Uu.some(n=>n===e)||Vu.some(n=>n===e)||Ku.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=Qo.safeParse(n);return r.success&&r.data===e})}function ti(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return kx.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 Ju(e){return Array.isArray(e)?{files:e}:e}function Lx(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function Dx(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=Ju(await e.listFiles({roots:Bx(t),maxFiles:sa+1,maxDepth:aa,maxTotalBytes:ca+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=Qo.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>aa){o.add("max-depth");continue}if(r.size>=sa){o.add("max-files");break}if(i+a.sizeBytes>ca){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:jx(l,a.sizeBytes,ua(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:Lx([...o]),maxFiles:sa,maxDepth:aa,maxTotalBytes:ca}}:{}}}function Bx(e){let t=new Set(Rx);for(let n of e.routeEntryFiles??[]){let r=Qo.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function jx(e,t,n){return fa(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:zu(e),readonly:!0}:{composition:n,path:e,kind:"text",language:Wu(e),sizeBytes:t,readonly:!1}}function $x(e){let t=[];for(let n of e){let r=n.path.split("/"),o=t,i="";for(let[s,a]of r.entries()){i=i?`${i}/${a}`:a;let c=s===r.length-1,l=o.find(u=>u.name===a);if(l||(l=c?{kind:"file",name:a,path:i,file:n}:{kind:"directory",name:a,path:i,children:[]},o.push(l)),c){if(l.kind!=="file")throw new Error(`Source tree path collision: ${n.path}`);l.file=n}else{if(l.kind!=="directory")throw new Error(`Source tree path collision: ${n.path}`);o=l.children}}}return Xu(t)}function Xu(e){return e.map(t=>t.kind==="directory"?{...t,children:Xu(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 fa(e){return!Cx(e)}function zu(e){let t=la.posix.extname(e).toLowerCase();return!t&&la.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":Nx[t]??"application/octet-stream"}function Wu(e){let t=la.posix.extname(e).toLowerCase();return Px[t]??"plaintext"}import*as Fn from"@babel/types";import pa from"@babel/traverse";import*as Ot from"@babel/types";function Le(e){if(e.isJSXFragment())return!0;if(!e.isJSXElement())return!1;let t=e.node.openingElement.name;if(Ot.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(Ot.isIdentifier(s)&&s.name==="Fragment"||Ot.isStringLiteral(s)&&s.value==="Fragment")&&Hu(i.parentPath)}if(!Ot.isJSXMemberExpression(t)||!Ot.isJSXIdentifier(t.property)||t.property.name!=="Fragment"||!Ot.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())&&Hu(r.parentPath)}function Hu(e){return e?.isImportDeclaration()===!0&&e.node.source.value==="react"}var sn=typeof pa=="function"?pa:pa.default,ni=new WeakMap,ri=new WeakMap;function Lt(e,t){let n=qs(e,t);if(!n.ok)return Qs(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=ue(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}}:Qs(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function ue(e,t){return t.kind==="jsx-node"?Qu(e,t):t.kind==="jsx-attribute"?Wx(e,t):t.kind==="value"?Hx(e,t):t.kind==="expression"?Gx(e,t):t.kind==="directive"?Yx(e,t):t.kind==="export"?Zx(e,t):{ok:!1,diagnostic:Rn("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function Qu(e,t){return t.strategy==="source-range"?Kx(e,t):Ux(e,t)}function Kx(e,t){let n=null;if(sn(e,{JSXElement(o){if(!Tn(o.node,t.sourceRange))return;let i=je("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!Tn(o.node,t.sourceRange))return;let i=je("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!Tn(o.node,t.sourceRange))return;let i=je("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXText(o){if(!Tn(o.node,t.sourceRange))return;let i=je("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)}}),!n)return $e("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!lb(r.path,t.expectedIdentity)?$e("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function Ux(e,t){if(t.structuralPath===""){let r=Xx(e,t.component);if(r){let o=zx(r);if(o)return o}}let n=null;return sn(e,{JSXElement(r){if(Or(r)!==t.component||ga(r)!==t.structuralPath)return;let i=je("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(Or(r)!==t.component||ga(r)!==t.structuralPath)return;let i=je("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=Jx(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:$e("jsx-node","locator-miss","JSX node not found for structural-path locator")}function Jx(e,t,n){let r=null;return sn(e,{JSXElement(o){if(Or(o)!==t||!Tn(o.node,n))return;let i=je("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(Or(o)!==t||!Tn(o.node,n))return;let i=je("jsx-node",o);i&&(r=i,o.stop())}}),r}function Xx(e,t){let n=null;return sn(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 zx(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 $e("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?$e("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 $e("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function Wx(e,t){let n=Qu(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>ub(c,t.name));if(!s||!s.isJSXAttribute())return $e("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=je("jsx-attribute",s);return a?{ok:!0,match:a}:$e("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function Hx(e,t){let n=Qx(e,t);if(!n.ok)return n;let r=qx(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!Yt(r.match.path.node.loc,t.expectedRange)?$e("value","locator-miss","Resolved value does not match expected range"):{ok:!0,match:r.match}:r}function Gx(e,t){let n=null;return sn(e,{Identifier(r){if(!ib(r))return;let o=Yu(r);if(!o||!Zu(o,t))return;let i=je("expression",r);i&&(t.expectedRange&&!Yt(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=Yu(r);if(!o||!Zu(o,t))return;let i=je("expression",r);i&&(t.expectedRange&&!Yt(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:$e("expression","locator-miss","Expression not found")}function Yx(e,t){let n=null;return sn(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!Yt(i.node.loc,t.expectedRange))return;let s=je("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:$e("directive","locator-miss",`Directive '${t.value}' not found`)}function Zx(e,t){let n=null;return sn(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let c=r.get("declaration");if(c.isFunctionDeclaration()&&c.node.id?.name==="generateMetadata"){let f=je("export",c);if(!f||t.expectedRange&&!Yt(c.node.loc,t.expectedRange))return;n=f,r.stop();return}if(!c.isVariableDeclaration())return;let l=ha(c,"generateMetadata");if(!l||!l.isVariableDeclarator())return;let u=l.get("init");if(!u.node)return;let d=je("export",u);if(!d||t.expectedRange&&!Yt(u.node.loc,t.expectedRange))return;n=d,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=ha(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!Yt(s.node.loc,t.expectedRange))return;let a=je("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=je("export",o);i&&(t.expectedRange&&!Yt(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:$e("export","export-not-found",`Export '${cb(t)}' not found`)}function Qx(e,t){let n=null;return sn(e,{Expression(r){if(n||t.root.kind!=="expression"||!Tn(r.node,t.root.sourceRange))return;let o=je("value",r);o&&(n=o,r.stop())},VariableDeclarator(r){if(n)return;if(t.root.kind==="binding"){if(r.node.id.type!=="Identifier"||r.node.id.name!==t.root.name)return;let g=r.get("init");if(!g.node)return;let m=je("value",g);if(!m)return;n=m,r.stop();return}if(t.root.kind!=="hook-state")return;let o=t.root,i=r.get("id"),s=r.get("init");if(!i.isArrayPattern()||!s.isCallExpression()||i.node.elements.findIndex(g=>g?.type==="Identifier"&&g.name===o.name)!==0)return;let c=s.node.callee;if((c.type==="Identifier"?c.name:c.type==="MemberExpression"&&c.property.type==="Identifier"?c.property.name:null)!==o.hook)return;let u=o.hook==="useReducer"?1:0,d=r.get(`init.arguments.${u}`);if(!d||Array.isArray(d)||!d.node)return;let f=je("value",d);f&&(n=f,r.stop())},ExportNamedDeclaration(r){if(n||t.root.kind!=="named-export")return;let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=ha(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=je("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=je("value",o);i&&(n=i,r.stop())}}),n?{ok:!0,match:n}:$e("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 qx(e,t){let n=ma(e);for(let o of t){if(n=ma(n),o.kind==="property"){if(!n.isObjectExpression())return $e("value","unsupported-syntax","Property path requires object expression");let a=n.get("properties");if(a.some(l=>!l.isObjectProperty()))return $e("value","unsupported-syntax","Spread properties are not supported");let c=a.find(l=>db(l,o.name));if(!c||!c.isObjectProperty())return $e("value","property-not-found",`Property '${o.name}' not found`);n=c.get("value");continue}if(!n.isArrayExpression())return $e("value","unsupported-syntax","Array index path requires array expression");let i=n.get("elements");if(i.some(a=>a.node?.type==="SpreadElement"))return $e("value","unsupported-syntax","Spread array elements are not supported");let s=i[o.index];if(!s?.node)return $e("value","array-index-out-of-range",`Array index ${o.index} is out of range`);n=s}n=ma(n);let r=je("value",n);return r?{ok:!0,match:r}:$e("value","locator-miss","Resolved value has no source range")}function ma(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function je(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 Tn(e,t){return Yt(e.loc,t)}function Yt(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 ga(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!Le(n)){let o=ed(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${Gu(n,o)}`):t.unshift(`${o}#${Gu(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||rb(n.parentPath)&&!ob(n.parentPath))break;n=n.parentPath}return t.join("/")}function Gu(e,t){let n=qu(e)??e.getFunctionParent();if(!n)return 0;let r=ni.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=ni.get(n.node)?.get(t);if(!i){let a=ni.get(n.node);a||(a=new Map,ni.set(n.node,a)),i=new WeakMap,a.set(t,i)}let s=n.isJSXElement()||n.isJSXFragment()?Mr(n):eb(n);for(let a of s)if(ed(a.node.openingElement)===t){if(i.set(a.node,o),a.node===e.node)return o;o++}return i.get(e.node)??0}function eb(e){let t=ri.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!qu(r)&&n.push(r)}}),ri.set(e.node,n),n}function qu(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Le(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Mr(e){let t=ri.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(Le(o)){n.push(...Mr(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Mr(o));continue}o.isJSXExpressionContainer()&&n.push(...Gt(o.get("expression")))}return ri.set(e.node,n),n}function Gt(e){if(e.isJSXElement())return Le(e)?Mr(e):[e];if(e.isJSXFragment())return Mr(e);if(e.isParenthesizedExpression())return Gt(e.get("expression"));if(e.isLogicalExpression()&&tb(e.node.operator))return Gt(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(...Gt(c))}if(s.isReturnStatement()){let a=s.get("argument");a.isExpression()&&i.push(...Gt(a));break}}return i}else if(o.node&&o.isExpression())return Gt(o)}}}}return e.isConditionalExpression()?[...Gt(e.get("consequent")),...Gt(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Gt(t)):[]}function tb(e){return e==="&&"||e==="||"||e==="??"}function ed(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?nb(e.name):null}function nb(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 Or(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 rb(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function ob(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 ib(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function Yu(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 Zu(e,t){return e.base===t.base&&sb(e.path,t.path??[])}function sb(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 ab(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function cb(e){return e.exportKind==="named"?e.name:e.exportKind}function $e(e,t,n,r){return{ok:!1,diagnostic:Rn(t,n,e,r)}}function lb(e,t){return Or(e)!==t.component?!1:ga(e)===t.structuralPath}function ub(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function ha(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function db(e,t){return e.isObjectProperty()?ab(e.node)===t:!1}import*as nd from"@babel/parser";import{arrayExpression as hb,booleanLiteral as yb,identifier as xb,jsxAttribute as bb,jsxExpressionContainer as Sb,jsxIdentifier as Eb,nullLiteral as vb,numericLiteral as kb,objectExpression as Ib,objectProperty as Cb,stringLiteral as xa}from"@babel/types";import ya from"@babel/generator";var fb=typeof ya=="function"?ya:ya.default;function pb(e){let t=e.split(`
1
+ import*as My from"@babel/parser";import*as Ye from"@babel/types";import*as rn from"node:path";var Ys=[".tsx",".ts",".jsx",".js"],Oy=Ys.map(e=>`/index${e}`),Ly=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 Iu(e){let t=e.replace(/[?#].*$/,""),n=/\.([a-z0-9]+)$/i.exec(t);return n!==null&&Ly.has(n[1].toLowerCase())}function Cu(e){let t=[];for(let n of e.program.body)Ye.isImportDeclaration(n)&&typeof n.source.value=="string"&&It(n.source.value)&&t.push(n.source.value),Ye.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&It(n.source.value)&&t.push(n.source.value),Ye.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&It(n.source.value)&&t.push(n.source.value);return Ye.traverseFast(e.program,n=>{let r=Ye.isImportExpression(n)?n.source:Ye.isCallExpression(n)&&Ye.isImport(n.callee)?n.arguments[0]:null;Ye.isStringLiteral(r)&&It(r.value)&&t.push(r.value)}),t}function It(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function In(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=rn.dirname(e);return rn.join(n,t).replace(/\\/g,"/")}async function Dy(e,t){if(Ys.some(n=>e.endsWith(n))&&await t(e))return e;for(let n of Ys){let r=`${e}${n}`;if(await t(r))return r}for(let n of Oy){let r=`${e}${n}`;if(await t(r))return r}return null}async function Cn(e,t,n){let r=await Vo(e,t,n);return r.ok?r.path:null}async function Vo(e,t,n){let r=In(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 Dy(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(!It(t)||t.includes("\0")||t.includes("\\")||rn.posix.isAbsolute(n))return!1;let r=rn.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!rn.posix.isAbsolute(e)}import{createHash as $y}from"node:crypto";import*as Ru from"@babel/parser";function Rn(e,t,n,r){return{code:e,message:t,locatorKind:n,details:r}}function X(e,t,n,r,o){return{ok:!1,source:e,diagnostic:Rn(t,n,r,o)}}function Zs(e,t,n,r,o){return{ok:!1,source:e,diagnostic:Rn(t,n,r,o)}}var jy={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function Mt(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:Ru.parse(t,{sourceType:"module",plugins:jy[n]})}}catch(r){return{ok:!1,source:t,diagnostic:Rn("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function Qs(e,t){return Mt({source:e,profile:wu(t.kind)})}function Fr(e,t){return Mt({source:e,profile:wu(t)})}function wu(e){return"next-app-entry"}function wn(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 Wt=(e,t)=>{let n=Mt({source:t,profile:wn({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${$y("sha256").update(t).digest("hex")}`,ast:n.ast,imports:Cu(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};function Vy(e,t){return Wt(e,t)}function Ky(e,t){return In(e,t)}import{COMPONENT_I18N_FILE_SUFFIX as Uy,parseComponentI18nResourcesJson as Jy,resolveSiteTextDirection as Xy,SiteLocaleSchema as zy}from"@vcp-dev/contracts";var Wy=["i18next","react-i18next"],Hy="components/ui/site-locale-provider.tsx",Gy="components/ui/component-i18n-provider.tsx",Nu="app/layout.tsx";async function Ko(e){let t=e.files.filter(f=>f.path.endsWith(Uy));if(t.length===0)return{ok:!0};for(let f of["package.json",Nu,Hy,Gy])if(!await e.exists(f))return on(`Target snapshot is missing required i18n host file: ${f}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return on("Target snapshot package.json is invalid.")}let r=Pu(n)&&Pu(n.dependencies)?n.dependencies:{},o=Wy.filter(f=>typeof r[f]!="string"||r[f].trim().length===0);if(o.length>0)return on(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile(Nu),s=qs(i,"html","lang"),a=qs(i,"html","dir"),c=qs(i,"SiteLocaleProvider","locale"),l=zy.safeParse(s);if(!l.success||!a||!c||s!==c||a!==Xy(l.data))return on("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 on("Target snapshot root layout is not wired to SiteLocaleProvider.");let u=l.data;if(e.targetLocale&&e.targetLocale!==u)return on("Target snapshot locale does not match the authoritative site language.");let d=u.split("-")[0];for(let f of t){let g=Jy(f.content);if(!g.success)return on(`Component i18n resource is invalid: ${f.path}.`);if(!e.deferTargetLocale&&!Object.hasOwn(g.data,u)&&!Object.hasOwn(g.data,d))return on(`Component i18n resource ${f.path} has no locale for ${u} or ${d}.`)}return{ok:!0}}function qs(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 Pu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function on(e){return{ok:!1,message:e}}import ta from"@babel/generator";import*as Ou from"@babel/parser";import na from"@babel/traverse";import*as Ne from"@babel/types";import{computeSiteEditSourceIdentityKey as Zy}from"@vcp-dev/contracts";var Au="data-vcp-ui-component",Uo="components/ui";function Ht(e){if(!e)return!1;let t=ea(e);return t===Uo||t.startsWith(`${Uo}/`)||t.includes(`/${Uo}/`)||t.endsWith(`/${Uo}`)}function Nn(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?Ht(e.slice(2)):e.startsWith("./")||e.startsWith("../")?Ht(ea(`${Yy(t)}/${e}`)):Ht(e):!1}function ea(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 Yy(e){let t=ea(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}import{stripSiteEditRepeatInstanceKeys as RP}from"@vcp-dev/contracts";import{isSiteEditRuntimeContainerTag as NP,isSiteEditRuntimeTextTag as PP}from"@vcp-dev/contracts/site-edit-runtime-capability";var Tu={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 Qy=typeof ta=="function"?ta:ta.default,qy=typeof na=="function"?na:na.default,ex=new Set(["base","body","head","html","link","meta","noscript","script","style","template","title"]),tx="suppressHydrationWarning",nx=new Set(["SiteEditBootstrap"]);function rx(e){let t=sx(e.file,e.projectRoot);if(!ix(e.source)||Ht(t))return{code:e.source,elements:[]};let n=e.attributes??Tu,r=Ou.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]}),o=[],i=cx(r,t);return qy(r,{JSXElement(s){let a=s.node.openingElement,c=a.name;if(!ux(c)||Lu(a,n.key))return;let l=fx(s)??"default",u=mx(s),d=Zy(t,l,u),f=Xo(c)??"unknown",g=ax(c)?"jsx":"component-call";if(g==="component-call"&&!px(s.node.children)&&nx.has(f))return;let m=g==="component-call"&&lx(f,i);dx(a,n.key,d),m&&Fu(a,Au),ox(s)&&Fu(a,tx),o.push({key:d,tag:f,componentName:l,sourceFile:t,sourceKind:g})}}),o.length===0?{code:e.source,elements:o}:{code:Qy(r,{jsescOption:{minimal:!0}}).code,elements:o}}function ox(e){return!e.findParent(t=>t.isJSXElement())}function ix(e){return/(?:^|[=(:,?;\[{>&|\n\r]|return\s+)\s*<(?:[A-Za-z][\w.:-]*|>)(?:\s|>|\/)/m.test(e)}function sx(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 ax(e){return Ne.isJSXIdentifier(e)&&/^[a-z]/.test(e.name)}function Xo(e){return Ne.isJSXIdentifier(e)?e.name:Ne.isJSXMemberExpression(e)?Bu(e):null}function cx(e,t){let n=new Set;for(let r of e.program.body)if(!(!Ne.isImportDeclaration(r)||!Nn(r.source.value,t)))for(let o of r.specifiers)n.add(o.local.name);return n}function lx(e,t){let n=e.split(".")[0]??e;return t.has(n)}function ux(e){let t=Xo(e);return!t||t==="Fragment"||t.endsWith(".Fragment")?!1:!ex.has(t)}function Lu(e,t){return e.attributes.some(n=>Ne.isJSXAttribute(n)&&Ne.isJSXIdentifier(n.name,{name:t}))}function dx(e,t,n){Du(e,Ne.jsxAttribute(Ne.jsxIdentifier(t),Ne.stringLiteral(n)))}function Fu(e,t){Lu(e,t)||Du(e,Ne.jsxAttribute(Ne.jsxIdentifier(t),null))}function Du(e,t){let n=e.attributes.findIndex(r=>Ne.isJSXSpreadAttribute(r));if(n>=0){e.attributes.splice(n,0,t);return}e.attributes.push(t)}function Bu(e){return`${Ne.isJSXIdentifier(e.object)?e.object.name:Bu(e.object)}.${e.property.name}`}function fx(e){let t=e;for(;t;){if(t.isFunctionDeclaration()||t.isClassDeclaration())return t.node.id?.name??null;if(t.isVariableDeclarator()&&Ne.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 px(e){return e.some(t=>Ne.isJSXElement(t)||Ne.isJSXFragment(t))}var _u=new WeakMap,Jo=new WeakMap,ra=new WeakMap;function mx(e){let t=_u.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=gx(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return _u.set(e.node,o),o}function gx(e){let t=Xo(e.node.openingElement.name);return!t||t==="Fragment"||t.endsWith(".Fragment")?null:/^[A-Z]/.test(t)?`component:${t}#${Mu(e,t)}`:`${t}#${Mu(e,t)}`}function Mu(e,t){let n=ju(e)??e.getFunctionParent();if(!n)return 0;let r=ra.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=ra.get(n.node);o||(o=new Map,ra.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()?zo(n):hx(n);for(let c of a)if(Xo(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 hx(e){let t=Jo.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!ju(r)&&n.push(r)}}),Jo.set(e.node,n),n}function ju(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 zo(e){let t=Jo.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(...zo(o));continue}o.isJSXExpressionContainer()&&n.push(...Pn(o.get("expression")))}return Jo.set(e.node,n),n}function Pn(e){if(e.isJSXElement())return[e];if(e.isJSXFragment())return zo(e);if(e.isParenthesizedExpression())return Pn(e.get("expression"));if(e.isLogicalExpression()&&e.node.operator==="&&")return Pn(e.get("right"));if(e.isConditionalExpression())return[...Pn(e.get("consequent")),...Pn(e.get("alternate"))];if(e.isCallExpression()&&xx(e.node)){let t=e.get("arguments")[0];return yx(t)}return[]}function yx(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return[t];if(t.isJSXFragment())return zo(t);if(t.isParenthesizedExpression())return Pn(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?Pn(r):[]}return[]}function xx(e){return Ne.isMemberExpression(e.callee)&&Ne.isIdentifier(e.callee.property)&&e.callee.property.name==="map"}import{SiteEditOperationRequestSchema as $N,SiteEditPatchPlanSchema as VN}from"@vcp-dev/contracts";function An(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 Wo(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 Ho(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 Go(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:bx(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 Yo(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:An(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 bx(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 Yw,computeSiteEditCompositionKey as Zw,getSiteEditSourceDeleteProtectionReason as Qw,isSiteEditTextSourcePath as qw,parseSiteEditRepeatInstanceKey as eN,SITE_EDIT_SOURCE_DELETE_CAPABILITY as tN,stripSiteEditRepeatInstanceKeys as at}from"@vcp-dev/contracts";import Ms from"node:path";import{parse as nN}from"yaml";import ca from"node:path";import{TextDecoder as Ex}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as Vu,SITE_EDIT_SOURCE_ALLOWED_DIRS as Ku,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as Uu,SiteEditCompositionContextSchema as vx,SiteEditSourceFileResponseSchema as oa,SiteEditSourceLocationSchema as kx,SiteEditSourcePathSchema as Zo,SiteEditSourceTreeResponseSchema as Ix,isSiteEditTextSourcePath as Cx}from"@vcp-dev/contracts";import{createHash as Sx}from"node:crypto";var _r=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 Re(e){return`sha256:${Sx("sha256").update(e).digest("hex")}`}var Rx=[...Uu,...Vu,...Ku];function la(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return vx.parse(e.composition)}var ia=2e3,sa=12,aa=24*1024*1024,$u=512*1024,wx=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),Nx={".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"},Px={".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"},Ax=new Ex("utf-8",{fatal:!0});async function Qo(e,t={}){let n=la(t),{files:r,truncated:o}=await Dx(e,t),i=$x(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 qo(e,t,n={}){let r=la(n),o=Zo.parse(t.path),i=await Fx(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(da(o)){let a=zu(o),c=await Mx(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return oa.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...c})}let s=await ua(e,o);return s.ok?oa.parse({composition:r,path:o,kind:"text",language:Wu(o),sizeBytes:s.sizeBytes,contentHash:Re(s.content),readonly:!1,content:s.content}):oa.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function ua(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=Tx(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 Tx(e){if(e.includes(0))return null;try{return Ax.decode(e)}catch{return null}}async function Fx(e,t,n){if(!Ox(t,n))return null;let r=await _x(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function _x(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=Ju(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(da(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(!wx.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>$u)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>$u?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function Ox(e,t){return Uu.some(n=>n===e)||Vu.some(n=>n===e)||Ku.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=Zo.safeParse(n);return r.success&&r.data===e})}function ei(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return kx.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 Ju(e){return Array.isArray(e)?{files:e}:e}function Lx(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function Dx(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=Ju(await e.listFiles({roots:Bx(t),maxFiles:ia+1,maxDepth:sa,maxTotalBytes:aa+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=Zo.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>sa){o.add("max-depth");continue}if(r.size>=ia){o.add("max-files");break}if(i+a.sizeBytes>aa){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:jx(l,a.sizeBytes,la(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:Lx([...o]),maxFiles:ia,maxDepth:sa,maxTotalBytes:aa}}:{}}}function Bx(e){let t=new Set(Rx);for(let n of e.routeEntryFiles??[]){let r=Zo.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function jx(e,t,n){return da(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:zu(e),readonly:!0}:{composition:n,path:e,kind:"text",language:Wu(e),sizeBytes:t,readonly:!1}}function $x(e){let t=[];for(let n of e){let r=n.path.split("/"),o=t,i="";for(let[s,a]of r.entries()){i=i?`${i}/${a}`:a;let c=s===r.length-1,l=o.find(u=>u.name===a);if(l||(l=c?{kind:"file",name:a,path:i,file:n}:{kind:"directory",name:a,path:i,children:[]},o.push(l)),c){if(l.kind!=="file")throw new Error(`Source tree path collision: ${n.path}`);l.file=n}else{if(l.kind!=="directory")throw new Error(`Source tree path collision: ${n.path}`);o=l.children}}}return Xu(t)}function Xu(e){return e.map(t=>t.kind==="directory"?{...t,children:Xu(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 da(e){return!Cx(e)}function zu(e){let t=ca.posix.extname(e).toLowerCase();return!t&&ca.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":Nx[t]??"application/octet-stream"}function Wu(e){let t=ca.posix.extname(e).toLowerCase();return Px[t]??"plaintext"}import*as Fn from"@babel/types";import fa from"@babel/traverse";import*as Ot from"@babel/types";function Oe(e){if(e.isJSXFragment())return!0;if(!e.isJSXElement())return!1;let t=e.node.openingElement.name;if(Ot.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(Ot.isIdentifier(s)&&s.name==="Fragment"||Ot.isStringLiteral(s)&&s.value==="Fragment")&&Hu(i.parentPath)}if(!Ot.isJSXMemberExpression(t)||!Ot.isJSXIdentifier(t.property)||t.property.name!=="Fragment"||!Ot.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())&&Hu(r.parentPath)}function Hu(e){return e?.isImportDeclaration()===!0&&e.node.source.value==="react"}var sn=typeof fa=="function"?fa:fa.default,ti=new WeakMap,ni=new WeakMap;function Lt(e,t){let n=Qs(e,t);if(!n.ok)return Zs(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=ue(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}}:Zs(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function ue(e,t){return t.kind==="jsx-node"?Qu(e,t):t.kind==="jsx-attribute"?Wx(e,t):t.kind==="value"?Hx(e,t):t.kind==="expression"?Gx(e,t):t.kind==="directive"?Yx(e,t):t.kind==="export"?Zx(e,t):{ok:!1,diagnostic:Rn("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function Qu(e,t){return t.strategy==="source-range"?Kx(e,t):Ux(e,t)}function Kx(e,t){let n=null;if(sn(e,{JSXElement(o){if(!Tn(o.node,t.sourceRange))return;let i=je("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!Tn(o.node,t.sourceRange))return;let i=je("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!Tn(o.node,t.sourceRange))return;let i=je("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXText(o){if(!Tn(o.node,t.sourceRange))return;let i=je("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)}}),!n)return $e("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!lb(r.path,t.expectedIdentity)?$e("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function Ux(e,t){if(t.structuralPath===""){let r=Xx(e,t.component);if(r){let o=zx(r);if(o)return o}}let n=null;return sn(e,{JSXElement(r){if(Or(r)!==t.component||ma(r)!==t.structuralPath)return;let i=je("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(Or(r)!==t.component||ma(r)!==t.structuralPath)return;let i=je("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=Jx(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:$e("jsx-node","locator-miss","JSX node not found for structural-path locator")}function Jx(e,t,n){let r=null;return sn(e,{JSXElement(o){if(Or(o)!==t||!Tn(o.node,n))return;let i=je("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(Or(o)!==t||!Tn(o.node,n))return;let i=je("jsx-node",o);i&&(r=i,o.stop())}}),r}function Xx(e,t){let n=null;return sn(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 zx(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 $e("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?$e("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 $e("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function Wx(e,t){let n=Qu(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>ub(c,t.name));if(!s||!s.isJSXAttribute())return $e("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=je("jsx-attribute",s);return a?{ok:!0,match:a}:$e("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function Hx(e,t){let n=Qx(e,t);if(!n.ok)return n;let r=qx(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!Yt(r.match.path.node.loc,t.expectedRange)?$e("value","locator-miss","Resolved value does not match expected range"):{ok:!0,match:r.match}:r}function Gx(e,t){let n=null;return sn(e,{Identifier(r){if(!ib(r))return;let o=Yu(r);if(!o||!Zu(o,t))return;let i=je("expression",r);i&&(t.expectedRange&&!Yt(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=Yu(r);if(!o||!Zu(o,t))return;let i=je("expression",r);i&&(t.expectedRange&&!Yt(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:$e("expression","locator-miss","Expression not found")}function Yx(e,t){let n=null;return sn(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!Yt(i.node.loc,t.expectedRange))return;let s=je("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:$e("directive","locator-miss",`Directive '${t.value}' not found`)}function Zx(e,t){let n=null;return sn(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let c=r.get("declaration");if(c.isFunctionDeclaration()&&c.node.id?.name==="generateMetadata"){let f=je("export",c);if(!f||t.expectedRange&&!Yt(c.node.loc,t.expectedRange))return;n=f,r.stop();return}if(!c.isVariableDeclaration())return;let l=ga(c,"generateMetadata");if(!l||!l.isVariableDeclarator())return;let u=l.get("init");if(!u.node)return;let d=je("export",u);if(!d||t.expectedRange&&!Yt(u.node.loc,t.expectedRange))return;n=d,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=ga(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!Yt(s.node.loc,t.expectedRange))return;let a=je("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=je("export",o);i&&(t.expectedRange&&!Yt(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:$e("export","export-not-found",`Export '${cb(t)}' not found`)}function Qx(e,t){let n=null;return sn(e,{Expression(r){if(n||t.root.kind!=="expression"||!Tn(r.node,t.root.sourceRange))return;let o=je("value",r);o&&(n=o,r.stop())},VariableDeclarator(r){if(n)return;if(t.root.kind==="binding"){if(r.node.id.type!=="Identifier"||r.node.id.name!==t.root.name)return;let g=r.get("init");if(!g.node)return;let m=je("value",g);if(!m)return;n=m,r.stop();return}if(t.root.kind!=="hook-state")return;let o=t.root,i=r.get("id"),s=r.get("init");if(!i.isArrayPattern()||!s.isCallExpression()||i.node.elements.findIndex(g=>g?.type==="Identifier"&&g.name===o.name)!==0)return;let c=s.node.callee;if((c.type==="Identifier"?c.name:c.type==="MemberExpression"&&c.property.type==="Identifier"?c.property.name:null)!==o.hook)return;let u=o.hook==="useReducer"?1:0,d=r.get(`init.arguments.${u}`);if(!d||Array.isArray(d)||!d.node)return;let f=je("value",d);f&&(n=f,r.stop())},ExportNamedDeclaration(r){if(n||t.root.kind!=="named-export")return;let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=ga(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=je("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=je("value",o);i&&(n=i,r.stop())}}),n?{ok:!0,match:n}:$e("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 qx(e,t){let n=pa(e);for(let o of t){if(n=pa(n),o.kind==="property"){if(!n.isObjectExpression())return $e("value","unsupported-syntax","Property path requires object expression");let a=n.get("properties");if(a.some(l=>!l.isObjectProperty()))return $e("value","unsupported-syntax","Spread properties are not supported");let c=a.find(l=>db(l,o.name));if(!c||!c.isObjectProperty())return $e("value","property-not-found",`Property '${o.name}' not found`);n=c.get("value");continue}if(!n.isArrayExpression())return $e("value","unsupported-syntax","Array index path requires array expression");let i=n.get("elements");if(i.some(a=>a.node?.type==="SpreadElement"))return $e("value","unsupported-syntax","Spread array elements are not supported");let s=i[o.index];if(!s?.node)return $e("value","array-index-out-of-range",`Array index ${o.index} is out of range`);n=s}n=pa(n);let r=je("value",n);return r?{ok:!0,match:r}:$e("value","locator-miss","Resolved value has no source range")}function pa(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function je(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 Tn(e,t){return Yt(e.loc,t)}function Yt(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 ma(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!Oe(n)){let o=ed(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${Gu(n,o)}`):t.unshift(`${o}#${Gu(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||rb(n.parentPath)&&!ob(n.parentPath))break;n=n.parentPath}return t.join("/")}function Gu(e,t){let n=qu(e)??e.getFunctionParent();if(!n)return 0;let r=ti.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=ti.get(n.node)?.get(t);if(!i){let a=ti.get(n.node);a||(a=new Map,ti.set(n.node,a)),i=new WeakMap,a.set(t,i)}let s=n.isJSXElement()||n.isJSXFragment()?Mr(n):eb(n);for(let a of s)if(ed(a.node.openingElement)===t){if(i.set(a.node,o),a.node===e.node)return o;o++}return i.get(e.node)??0}function eb(e){let t=ni.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!qu(r)&&n.push(r)}}),ni.set(e.node,n),n}function qu(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Oe(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Mr(e){let t=ni.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(Oe(o)){n.push(...Mr(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Mr(o));continue}o.isJSXExpressionContainer()&&n.push(...Gt(o.get("expression")))}return ni.set(e.node,n),n}function Gt(e){if(e.isJSXElement())return Oe(e)?Mr(e):[e];if(e.isJSXFragment())return Mr(e);if(e.isParenthesizedExpression())return Gt(e.get("expression"));if(e.isLogicalExpression()&&tb(e.node.operator))return Gt(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(...Gt(c))}if(s.isReturnStatement()){let a=s.get("argument");a.isExpression()&&i.push(...Gt(a));break}}return i}else if(o.node&&o.isExpression())return Gt(o)}}}}return e.isConditionalExpression()?[...Gt(e.get("consequent")),...Gt(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Gt(t)):[]}function tb(e){return e==="&&"||e==="||"||e==="??"}function ed(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?nb(e.name):null}function nb(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 Or(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 rb(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function ob(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 ib(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function Yu(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 Zu(e,t){return e.base===t.base&&sb(e.path,t.path??[])}function sb(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 ab(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function cb(e){return e.exportKind==="named"?e.name:e.exportKind}function $e(e,t,n,r){return{ok:!1,diagnostic:Rn(t,n,e,r)}}function lb(e,t){return Or(e)!==t.component?!1:ma(e)===t.structuralPath}function ub(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function ga(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function db(e,t){return e.isObjectProperty()?ab(e.node)===t:!1}import*as nd from"@babel/parser";import{arrayExpression as hb,booleanLiteral as yb,identifier as xb,jsxAttribute as bb,jsxExpressionContainer as Sb,jsxIdentifier as Eb,nullLiteral as vb,numericLiteral as kb,objectExpression as Ib,objectProperty as Cb,stringLiteral as ya}from"@babel/types";import ha from"@babel/generator";var fb=typeof ha=="function"?ha:ha.default;function pb(e){let t=e.split(`
2
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 mb(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 gb(e,t){return e.split(`
3
3
  `).map(r=>mb(r,t)).join(`
4
- `)}function oi(e){let{ast:t,source:n}=e;try{let r=pb(n),i=fb(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=gb(i,r)),{ok:!0,source:i}}catch(r){return X(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}function td(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 Lr(e,t,n){return{ok:!0,source:t,operation:{type:n.kind,nodeId:n.target,kind:n.kind,target:n.target,beforeSourceHash:td(e),afterSourceHash:td(t),inverse:n.inverse}}}function be(e,t,n){let r=oi({ast:e,source:t});return r.ok?Lr(t,r.source,n):r}function Pe(e,t){let n=Fr(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function ii(e,t){return oi({ast:e,source:t})}function Rb(e,t,n){let r=ue(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function Qn(e,t,n){let r=Rb(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:X(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function an(e){return typeof e=="string"?xa(e):typeof e=="number"?kb(e):typeof e=="boolean"?yb(e):e===null?vb():Array.isArray(e)?hb(e.map(t=>an(t))):Ib(Object.entries(e).map(([t,n])=>{let r=Cb(ba(t),an(n));return t==="__proto__"&&(r.computed=!0),r}))}function wb(e){return typeof e=="string"?xa(e):Sb(an(e))}function Dr(e,t){return bb(Eb(e),wb(t))}function si(e,t){try{let r=nd.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:X(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:X(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function ba(e){return/^[$A-Z_][0-9A-Z_$]*$/i.test(e)?xb(e):xa(e)}function ai(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=Pe(t,"jsx-node");if(!i.ok)return i.result;let s=ue(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let c=Nb(s.match.path)[r];if(!c)return X(t,"locator-miss",`Text segment ${r} not found`,"jsx-node");switch(c.kind){case"jsx-text":{let l=c.path.node.value;if(o.trim().length===0){let d=l.match(/^\s*/)?.[0]??"",f=l.match(/\s*$/)?.[0]??"";c.path.replaceWithMultiple([...d?[Fn.jsxText(d)]:[],Fn.jsxExpressionContainer(Fn.stringLiteral("")),...f?[Fn.jsxText(f)]:[]]);break}let u=Pb(l,o);c.path.node.value=u,c.path.node.extra={rawValue:u,raw:u.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/{/g,"&#123;").replace(/}/g,"&#125;")};break}case"string-literal":c.path.node.value=o;break;case"template-literal":{let l=c.quasiIndex;c.path.node.quasis[l].value.raw=o.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${").replace(/\r/g,"\\r"),c.path.node.quasis[l].value.cooked=o;break}}return be(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function Nb(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=Ab(r.get("expression"));o.length>0&&t.push(...o)}}return t}function Pb(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function Ab(e){if(e.isStringLiteral())return[{kind:"string-literal",path:e}];if(e.isTemplateLiteral()){let t=[],n=e.node.quasis;for(let r=0;r<n.length;r++)(n[r].value.raw.trim().length>0||n.length===1&&e.node.expressions.length===0)&&t.push({kind:"template-literal",path:e,quasiIndex:r});if(t.length>0)return t}return e.isCallExpression()?[]:[]}import{nullLiteral as Sa}from"@babel/types";function qn(e){let{source:t,locator:n}=e,r=Pe(t,"jsx-node");if(!r.ok)return r.result;let o=ue(r.ast,n);return o.ok?(Tb(o.match.path),be(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function Tb(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Sa());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Sa());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Sa());return}e.remove()}import{cloneNode as Fb}from"@babel/types";function ci(e){let t=Pe(e.source,"jsx-node");if(!t.ok)return t.result;let n=ue(t.ast,e.locator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};let r=si(e.source,e.node.jsx);return r.ok?(n.match.path.replaceWith(Fb(r.node,!0)),be(t.ast,e.source,{kind:"replace-node",target:"jsx-node",inverse:"replace-node"})):r.result}import{cloneNode as Ub}from"@babel/types";import Ea from"@babel/traverse";import*as re from"@babel/types";function Br(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 _b=typeof Ea=="function"?Ea:Ea.default;function yt(e,t,n,r){if(!e.ok)return e;let o=ht(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=Ob(e,t);if(!r)return;let o=n.sourceLocator?rd(n.sourceLocator):void 0,i=n.targetParentLocator?rd(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??Db(r)??i?.component??o?.component;if(!(!s||!a))return{key:Br(s,a,Bb(r))}}function rd(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function Ob(e,t){let n=ld(e,t);return!n||n.node.type!=="JSXElement"?null:n}function ld(e,t){let n=null;return _b(e,{JSXElement(r){r.node===t&&(n=r,r.stop())},JSXFragment(r){r.node===t&&(n=r,r.stop())}}),n}function ht(e,t){if(!e)return null;if(re.isJSXElement(e))return Kb(t,e)?od(e.children,t):e;if(re.isJSXFragment(e))return od(e.children,t);if(re.isJSXExpressionContainer(e)||re.isParenthesizedExpression(e)||re.isTSAsExpression(e)||re.isTSSatisfiesExpression(e)||re.isTSTypeAssertion(e)||re.isTSNonNullExpression(e))return ht(e.expression,t);if(re.isLogicalExpression(e))return ht(e.right,t);if(re.isConditionalExpression(e))return ht(e.consequent,t)??ht(e.alternate,t);if(re.isCallExpression(e)||re.isOptionalCallExpression(e))return ud(e)?Lb(e.arguments[0],t):null;if(re.isArrayExpression(e))for(let n of e.elements){if(!n)continue;let r=ht(n,t);if(r)return r}return null}function od(e,t){for(let n of e){let r=ht(n,t);if(r)return r}return null}function Lb(e,t){return!e||!re.isArrowFunctionExpression(e)&&!re.isFunctionExpression(e)?null:re.isBlockStatement(e.body)?jr(e.body.body,t):ht(e.body,t)}function jr(e,t){for(let n of e){if(re.isReturnStatement(n)){let r=ht(n.argument,t);if(r)return r;continue}if(re.isBlockStatement(n)){let r=jr(n.body,t);if(r)return r;continue}if(re.isIfStatement(n)){let r=id(n.consequent,t);if(r)return r;let o=n.alternate?id(n.alternate,t):null;if(o)return o;continue}if(re.isSwitchStatement(n))for(let r of n.cases){let o=jr(r.consequent,t);if(o)return o}}return null}function id(e,t){return re.isBlockStatement(e)?jr(e.body,t):jr([e],t)}function Db(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(re.isFunctionDeclaration(n))return n.id?.name??"default"}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}var sd=new WeakMap,ad=new WeakMap,va=new WeakMap;function Bb(e){let t=sd.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=jb(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return sd.set(e.node,o),o}function jb(e){let t=dd(e.node.openingElement.name);return!t||Le(e)?null:/^[A-Z]/.test(t)?`component:${t}#${cd(e,t)}`:`${t}#${cd(e,t)}`}function cd(e,t){let n=$b(e);if(!n)return 0;let r=va.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=va.get(n.node);o||(o=new Map,va.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of _n(n))if(dd(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 $b(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Le(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function _n(e){let t=ad.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(Le(o)){n.push(..._n(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(..._n(o));continue}o.isJSXExpressionContainer()&&n.push(...Dt(o.get("expression")))}return ad.set(e.node,n),n}function Dt(e){if(e.isJSXElement())return Le(e)?_n(e):[e];if(e.isJSXFragment())return _n(e);if(e.isParenthesizedExpression())return Dt(e.get("expression"));if(e.isLogicalExpression())return Dt(e.get("right"));if(e.isConditionalExpression())return[...Dt(e.get("consequent")),...Dt(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Dt(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&ud(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 Le(t)?_n(t):[t];if(t.isJSXFragment())return _n(t);if(t.isParenthesizedExpression())return Dt(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return Dt(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(...Dt(s))}if(!r.isReturnStatement())continue;let o=r.get("argument");return o.node&&n.push(...Dt(o)),n}return n}function ud(e){let t=e.callee;return(re.isMemberExpression(t)||re.isOptionalMemberExpression(t))&&re.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function Kb(e,t){let n=ld(e,t);return n?Le(n):!1}function dd(e){return re.isJSXIdentifier(e)?e.name:re.isJSXMemberExpression(e)?fd(e):re.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function fd(e){return`${re.isJSXIdentifier(e.object)?e.object.name:fd(e.object)}.${e.property.name}`}function cn(e,t){if(t.parentPath===e&&t.listKey==="children"&&ka(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!ka(n))return null;let r=n;for(;r&&r!==e;){if(!ka(r)||!Le(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function ka(e){return e.isJSXElement()||e.isJSXFragment()}function er(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=Pe(t,"jsx-node");if(!a.ok)return a.result;let c=ue(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return X(t,"unsupported-syntax","insert-child target must be a JSXElement or JSXFragment","jsx-node");let l=c.match.path;if(c.match.path.isJSXElement()){let v=c.match.path.node;if(!v.closingElement||v.openingElement.selfClosing)return X(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=si(t,r.jsx);if(!u.ok)return u.result;let d=Ub(u.node,!0),f=l.node.children,g={...s,targetParentLocator:n},m=v=>s?yt(v,a.ast,d,g):v;if(o==="append")return f.push(d),m(be(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return f.unshift(d),m(be(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(!i)return X(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let h=ue(a.ast,i);if(!h.ok)return{ok:!1,source:t,diagnostic:h.diagnostic};let y=cn(c.match.path,h.match.path);if(!y)return X(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");l=y;let x=l.node.children,E=x.findIndex(v=>v===h.match.path.node);return E===-1?X(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(x.splice(o==="before"?E:E+1,0,d),m(be(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as pd from"@babel/parser";import{cloneNode as Jb}from"@babel/types";function li(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=Pe(t,"jsx-node");if(!a.ok)return a.result;let c=Xb(t,r);if(!c.ok)return c.result;let l=ue(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return X(t,"unsupported-syntax","insert-jsx-expression-child target must be a JSXElement or JSXFragment","jsx-node");if(l.match.path.isJSXElement()){let x=l.match.path.node;if(!x.closingElement||x.openingElement.selfClosing)return X(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=l.match.path,d=null;if(i){let x=ue(a.ast,i);if(!x.ok)return{ok:!1,source:t,diagnostic:x.diagnostic};let E=cn(l.match.path,x.match.path);if(!E)return X(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=E,d=x.match.path.node}else if(o==="before"||o==="after")return X(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let f=Jb(c.node,!0),g=u.node.children,m={...s,targetParentLocator:n},h=x=>s?yt(x,a.ast,f,m):x;if(o==="append")return g.push(f),h(be(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return g.unshift(f),h(be(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let y=g.findIndex(x=>x===d);return y===-1?X(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(g.splice(o==="before"?y:y+1,0,f),h(be(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function Xb(e,t){try{let r=pd.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:X(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:X(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as zb,nullLiteral as Ia}from"@babel/types";import*as ln from"@babel/types";import*as md from"@babel/types";function $r(e,t){let n=e.parentPath;if(!n?.isConditionalExpression()||e.key!=="consequent"||!md.isNullLiteral(n.node.alternate))return e;let r=n.parentPath;return!r?.isJSXExpressionContainer()||r.parentPath?.node!==t.node||r.listKey!=="children"?e:r}function tr(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=Pe(t,"jsx-node");if(!a.ok)return a.result;let c=ue(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let l=ue(a.ast,r);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return X(t,"unsupported-syntax","move-node target parent must be a JSXElement or JSXFragment","jsx-node");let u=l.match.path;if(l.match.path.isJSXElement()){let v=l.match.path.node;if(!v.closingElement||v.openingElement.selfClosing)return X(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let d=null;if(i){let v=ue(a.ast,i);if(!v.ok)return{ok:!1,source:t,diagnostic:v.diagnostic};let C=v.match.path.isJSXElement()?$r(v.match.path,l.match.path):v.match.path,P=cn(l.match.path,C);if(!P)return X(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=P,d=C}else if(o==="before"||o==="after")return X(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let f=d&&typeof d.key=="number"?d.key:-1;if(d&&f===-1)return X(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let g=c.match.path.isJSXElement()?$r(c.match.path,l.match.path):c.match.path,m=zb(g.node,!0);if(!ln.isJSXElement(m)&&!ln.isJSXExpressionContainer(m)&&!ln.isJSXFragment(m)&&!ln.isJSXText(m))return X(t,"unsupported-syntax","move-node source must resolve to a JSX child","jsx-node");let h=g.parentPath?.node===u.node&&typeof g.key=="number"?g.key:-1;if(d&&g.parentPath?.node===d.parentPath?.node&&g.key===d.key)return X(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");Wb(g);let y=u.node.children,x={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return y.push(m),yt(ii(a.ast,t),a.ast,m,x);if(o==="prepend")return y.unshift(m),yt(ii(a.ast,t),a.ast,m,x);let E=f-(h!==-1&&h<f?1:0);return y.splice(o==="before"?E:E+1,0,m),yt(ii(a.ast,t),a.ast,m,x)}function Wb(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Ia());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Ia());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Ia());return}e.remove()}import*as gd from"@babel/parser";import{cloneNode as Hb,nullLiteral as Ca}from"@babel/types";function ui(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,c=Pe(t,"jsx-node");if(!c.ok)return c.result;let l=Gb(t,s);if(!l.ok)return l.result;let u=ue(c.ast,n);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};let d=ue(c.ast,r);if(!d.ok)return{ok:!1,source:t,diagnostic:d.diagnostic};if(!d.match.path.isJSXElement()&&!d.match.path.isJSXFragment())return X(t,"unsupported-syntax","move-repeat-template-child target parent must be a JSXElement or JSXFragment","jsx-node");if(d.match.path.isJSXElement()){let v=d.match.path.node;if(!v.closingElement||v.openingElement.selfClosing)return X(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let f=d.match.path,g=null;if(i){let v=ue(c.ast,i);if(!v.ok)return{ok:!1,source:t,diagnostic:v.diagnostic};let C=cn(d.match.path,v.match.path);if(!C)return X(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");f=C,g=v.match.path.node}else if(o==="before"||o==="after")return X(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!u.match.path.isJSXElement())return X(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let m=f.node,h=Hb(l.node,!0);Yb(u.match.path);let y={...a,sourceLocator:n,targetParentLocator:r},x=m.children;if(o==="append")return x.push(h),yt(be(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,y);if(o==="prepend")return x.unshift(h),yt(be(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,y);let E=x.findIndex(v=>v===g);return E===-1?X(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(x.splice(o==="before"?E:E+1,0,h),yt(be(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,y))}function Gb(e,t){try{let r=gd.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:X(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:X(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function Yb(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{SiteEditSetPropsParamsSchema as Zb,classifySiteEditPropertyName as Qb}from"@vcp-dev/contracts";import*as nr from"@babel/types";function di(e){let t=Zb.safeParse({kind:"set-props",scope:"selection",changes:e.changes});if(!t.success)return X(e.source,"unsupported-syntax","Invalid typed JSX property changes","jsx-node",{issues:t.error.issues});let n=Pe(e.source,"jsx-node");if(!n.ok)return n.result;let r=Qn(n.ast,e.locator,e.source);if(!r.ok)return r.result;for(let a of t.data.changes){let c=Qb(a.name);if(c.owner!=="generic")return X(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(nr.isJSXAttribute),s=new Map;for(let a of i){let c=qb(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 X(e.source,"unsupported-syntax",`JSX attribute '${a.name}' has multiple sources`,"jsx-node");for(let a of t.data.changes){let c=s.get(a.name)?.[0];if(a.operation==="remove"){c&&(o.attributes=o.attributes.filter(u=>u!==c));continue}let l=Dr(a.name,a.value).value;c?c.value=l:o.attributes.push(Dr(a.name,a.value))}return be(n.ast,e.source,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}function qb(e){return nr.isJSXIdentifier(e.name)?e.name.name:nr.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{SiteEditOperationParamsSchema as eS}from"@vcp-dev/contracts";import*as H from"@babel/types";var hd=["prefetch","replace","scroll","locale","onNavigate"],tS=/^on(?:Click|DoubleClick|AuxClick|MouseDown|MouseUp|PointerDown|PointerUp|TouchStart|TouchEnd|KeyDown|KeyUp|ContextMenu)(?:Capture)?$/;function nS(e){let t=e;for(;t;){if(t.isJSXElement()&&t.node.openingElement.attributes.some(n=>H.isJSXAttribute(n)&&H.isJSXIdentifier(n.name)&&tS.test(n.name.name)))return!0;t=t.parentPath}return!1}function fi(e){let t=Pe(e.source,"jsx-node");if(!t.ok)return t.result;let n=Qn(t.ast,e.locator,e.source);if(!n.ok)return n.result;let r=eS.safeParse({kind:"set-link-target",scope:"selection",link:e.link,changes:e.changes});if(!r.success||r.data.kind!=="set-link-target")return Zt(e.source,"Invalid typed link-target changes");let o=n.match.path,i=o.node,s=i.openingElement,a=lS(s.name);if(!a)return Zt(e.source,"Unsupported JSX link tag");if(s.attributes.some(H.isJSXSpreadAttribute))return Zt(e.source,"Link elements with spread props cannot be transformed safely");let c=new Map;for(let m of s.attributes){if(!H.isJSXAttribute(m))continue;let h=wa(m);if(!h)return Zt(e.source,"Unsupported JSX attribute name");let y=c.get(h)??[];y.push(m),c.set(h,y)}if([...c.values()].some(m=>m.length>1))return Zt(e.source,"Duplicate JSX attributes cannot be transformed safely");let l=c.get("href")?.[0];if(l&&!cS(l))return Zt(e.source,"Dynamic link href cannot be transformed safely");let u=a==="a",d=u?null:iS(o,s.name);if(!u&&!d)return Zt(e.source,"Only native anchors and imported next/link components are supported");if(e.link.kind==="none"&&nS(o))return Zt(e.source,"A link with an active event handler in its JSX ancestry cannot become an inert anchor");let f=null;if(e.link.kind==="internal-route")if(d)f=a;else{let m=sS(t.ast,o);if(!m.ok)return Zt(e.source,m.reason);f=m.localName}if(d&&e.link.kind!=="internal-route"){let m=H.jsxIdentifier("a");s.name=m,i.closingElement&&(i.closingElement.name=H.jsxIdentifier("a")),aS(t.ast,d,o)}else f&&u&&(s.name=H.jsxIdentifier(f),i.closingElement&&(i.closingElement.name=H.jsxIdentifier(f)));let g=new Set;return e.link.kind==="none"?(g.add("href"),g.add("target"),g.add("rel"),hd.forEach(m=>g.add(m))):(g.add("href"),e.link.kind==="native-link"&&hd.forEach(m=>g.add(m))),s.attributes=s.attributes.filter(m=>{if(!H.isJSXAttribute(m))return!0;let h=wa(m);return!h||!g.has(h)}),e.link.kind!=="none"&&s.attributes.push(H.jsxAttribute(H.jsxIdentifier("href"),H.stringLiteral(e.link.href))),rS(s,e.changes),be(t.ast,e.source,{kind:"set-link-target",target:"jsx-node",inverse:"set-link-target"})}function rS(e,t){for(let n of t){let r=e.attributes.find(s=>H.isJSXAttribute(s)&&wa(s)===n.name);if(n.operation==="remove"){e.attributes=e.attributes.filter(s=>s!==r);continue}let o=typeof n.value=="string"?H.stringLiteral(n.value):H.jsxExpressionContainer(Ra(n.value)),i=H.jsxAttribute(H.jsxIdentifier(n.name),o);r&&H.isJSXAttribute(r)?r.value=i.value:e.attributes.push(i)}}function Ra(e){return e===null?H.nullLiteral():typeof e=="string"?H.stringLiteral(e):typeof e=="number"?H.numericLiteral(e):typeof e=="boolean"?H.booleanLiteral(e):Array.isArray(e)?H.arrayExpression(e.map(t=>Ra(t))):typeof e=="object"?H.objectExpression(Object.entries(e).map(([t,n])=>H.objectProperty(H.isValidIdentifier(t)?H.identifier(t):H.stringLiteral(t),Ra(n)))):H.nullLiteral()}function oS(e){return H.isImportDefaultSpecifier(e)||H.isImportSpecifier(e)&&e.importKind!=="type"&&(H.isIdentifier(e.imported,{name:"default"})||H.isStringLiteral(e.imported,{value:"default"}))}function yd(e){return!e.parentPath?.isImportDeclaration()||e.parentPath.node.importKind==="type"?!1:e.isImportDefaultSpecifier()||e.isImportSpecifier()&&e.node.importKind!=="type"&&(H.isIdentifier(e.node.imported,{name:"default"})||H.isStringLiteral(e.node.imported,{value:"default"}))}function iS(e,t){if(!H.isJSXIdentifier(t))return null;let n=e.scope.getBinding(t.name);if(!n||!yd(n.path))return null;let r=n.path.parentPath;return!r?.isImportDeclaration()||r.node.source.value!=="next/link"?null:t.name}function sS(e,t){let n=e.program.body.filter(c=>H.isImportDeclaration(c)&&c.source.value==="next/link"&&c.importKind!=="type"),r=n[0],o=n.flatMap(c=>c.specifiers).find(oS);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=H.importDefaultSpecifier(H.identifier(s));if(r)r.specifiers.unshift(a);else{let c=H.importDeclaration([a],H.stringLiteral("next/link")),l=0;for(;l<e.program.body.length&&H.isImportDeclaration(e.program.body[l]);)l+=1;e.program.body.splice(l,0,c)}return{ok:!0,localName:s}}function aS(e,t,n){let r=n.scope.getProgramParent();r.crawl();let o=r.getBinding(t);if(!o||!yd(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 cS(e){return!e.value||H.isStringLiteral(e.value)}function lS(e){return H.isJSXIdentifier(e)?e.name:null}function wa(e){return H.isJSXIdentifier(e.name)?e.name.name:null}function Zt(e,t){return X(e,"unsupported-syntax",t,"jsx-node")}import*as Ue from"@babel/types";import{classifySiteEditPropertyName as xd}from"@vcp-dev/contracts";function pi(e){let t=xd(e.name),n=xd(e.property);if(t.owner!=="generic"||n.owner!=="generic")return X(e.source,"unsupported-syntax","Property binding is only available for generic properties","jsx-node");if(!bd(e.object))return X(e.source,"unsupported-syntax","Property binding object must be a single identifier","jsx-node");if(e.property.length===0)return X(e.source,"unsupported-syntax","Property binding requires a non-empty property name","jsx-node");let r=Pe(e.source,"jsx-node");if(!r.ok)return r.result;let o=Qn(r.ast,e.locator,e.source);if(!o.ok)return o.result;let i=o.match.path.node.openingElement,s=i.attributes.filter(l=>Ue.isJSXAttribute(l)&&dS(l)===e.name);if(s.length>1)return X(e.source,"unsupported-syntax",`JSX attribute '${e.name}' has multiple sources`,"jsx-node");let a=uS(e.object,e.property),c=s[0];if(c)c.value=Ue.jsxExpressionContainer(a);else{let l=Dr(e.name,"");l.value=Ue.jsxExpressionContainer(a),i.attributes.push(l)}return be(r.ast,e.source,{kind:"set-property-binding",target:"jsx-node",inverse:"restore-property-binding"})}function uS(e,t){return bd(t)?Ue.memberExpression(Ue.identifier(e),Ue.identifier(t)):Ue.memberExpression(Ue.identifier(e),Ue.stringLiteral(t),!0)}function bd(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)}function dS(e){return Ue.isJSXIdentifier(e.name)?e.name.name:Ue.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{getBindingIdentifiers as pS,identifier as Vr,importDeclaration as mS,importDefaultSpecifier as gS,importNamespaceSpecifier as hS,importSpecifier as yS,isImportDefaultSpecifier as Sd,isImportNamespaceSpecifier as Ed,isImportSpecifier as vd,stringLiteral as xS}from"@babel/types";function rr(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(y=>!wS(y));if(o!==-1){let y=r[o],x=y&&typeof y=="object"&&"kind"in y?y.kind:void 0;return X(t,"unsupported-syntax",`Unsupported import spec kind: ${String(x)}`)}let i=IS(r);if(!i.ok)return X(t,"unsupported-syntax",i.message);let s=Pe(t);if(!s.ok)return s.result;let{ast:a}=s,c=a.program,l=c.body.filter(y=>y.type==="ImportDeclaration"&&y.source.value===n),u=new Set(l.flatMap(y=>y.specifiers.flatMap(x=>{let E=NS(y,x);return E?[E]:[]}))),d=i.imports.filter(y=>!u.has(Nd(y)));if(d.length===0)return Lr(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let f=CS(c.body),g=d.find(y=>f.has(Na(y)));if(g)return X(t,"unsupported-syntax",`Import local binding already exists: ${Na(g)}`);let m=kS(d);if(m.reduce((y,x)=>y+x.length,0)!==d.length)return X(t,"unsupported-syntax","Unsupported import specifier grouping");for(let y of m){if(!Rd(Id(y)))return X(t,"unsupported-syntax","Unsupported import specifier combination");let x=l.find(E=>bS(E,y));if(x)SS(x,y);else{let E=mS(kd(y),xS(n));RS(c.body,E),l.push(E)}}return be(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function bS(e,t){return e.importKind==="type"?!1:Rd(vS(ES(e),Id(t)))}function SS(e,t){let n=!1,r=new Set(e.specifiers.map(o=>Pa(o)));for(let o of kd(t)){let i=Pa(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return wd(e.specifiers),{changed:n}}function kd(e){let t=e.map(n=>{switch(n.kind){case"named":return yS(n.local?Vr(n.local):Vr(n.imported),Vr(n.imported));case"default":return gS(Vr(n.local));case"namespace":return hS(Vr(n.local));default:return n}});return wd(t),t}function Id(e){let t=Cd();for(let n of e)n.kind==="default"?t.defaultLocals.add(n.local):n.kind==="named"?t.hasNamed=!0:t.namespaceLocals.add(n.local);return t}function ES(e){let t=Cd();for(let n of e.specifiers)Sd(n)?t.defaultLocals.add(n.local.name):Ed(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function Cd(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function vS(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function Rd(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function wd(e){let t=[...e.filter(n=>Sd(n)),...e.filter(n=>Ed(n)),...e.filter(n=>vd(n))];e.splice(0,e.length,...t)}function kS(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=Nd(r);if(t.has(o))continue;let i=Na(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 CS(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(pS(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 RS(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 wS(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 Nd(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 Na(e){return e.kind==="named"?e.local??e.imported:e.local}function NS(e,t){return e.importKind==="type"||vd(t)&&t.importKind==="type"?null:Pa(t)}function Pa(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 or(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(u=>!AS(u));if(o!==-1){let u=r[o],d=u&&typeof u=="object"&&"kind"in u?u.kind:void 0;return X(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(d)}`)}let i=Pe(t);if(!i.ok)return i.result;let{ast:s}=i,a=s.program,c=a.body.findIndex(u=>u.type==="ImportDeclaration"&&u.source.value===n);if(c===-1)return Lr(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let l=a.body[c];return r.length===0?(a.body.splice(c,1),be(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(l.specifiers=l.specifiers.filter(u=>!r.some(d=>PS(u,d))),l.specifiers.length===0&&a.body.splice(c,1),be(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function PS(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 AS(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 Kr(e){let{source:t,locator:n,next:r}=e,o=yi(t,n);return o.ok?(o.path.replaceWith(an(r)),be(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function mi(e){let{source:t,locator:n,index:r,value:o}=e,i=yi(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(s=>s?.type==="SpreadElement")?X(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>i.path.node.elements.length?X(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,0,an(o)),be(i.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):X(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function gi(e){let{source:t,locator:n,index:r}=e,o=yi(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(i=>i?.type==="SpreadElement")?X(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=o.path.node.elements.length?X(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(o.path.node.elements.splice(r,1),be(o.ast,t,{kind:"remove-array-element",target:"value",inverse:"insert-array-element"})):X(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function hi(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=yi(t,n);if(!i.ok)return i.result;if(!i.path.isArrayExpression())return X(t,"unsupported-syntax","Array operations require array expression target","value");if(i.path.node.elements.some(c=>c?.type==="SpreadElement"))return X(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 X(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),be(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function yi(e,t){let n=Pe(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=ue(n.ast,t);return r.ok?{ok:!0,ast:n.ast,path:r.match.path}:{ok:!1,result:{ok:!1,source:e,diagnostic:r.diagnostic}}}import*as ze from"@babel/types";function xi(e){let t=Pe(e.source,"value");if(!t.ok)return t.result;let n=ue(t.ast,e.objectLocator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};if(!n.match.path.isObjectExpression())return X(e.source,"unsupported-syntax","Object property upsert requires an ObjectExpression parent","value");let r=n.match.path.node;if(r.properties.some(a=>ze.isSpreadElement(a)||ze.isObjectProperty(a)&&a.computed))return X(e.source,"unsupported-syntax","Object property upsert does not support spreads or computed keys","value");let o=r.properties.filter(a=>ze.isObjectProperty(a)&&TS(a.key)===e.name);if(o.length>1)return X(e.source,"unsupported-syntax",`Object property '${e.name}' has multiple sources`,"value");let i=e.value.kind==="undefined"?ze.unaryExpression("void",ze.numericLiteral(0)):an(e.value.value),s=o[0];if(s)s.value=i,s.shorthand=!1;else{let a=ze.objectProperty(ba(e.name),i);e.name==="__proto__"&&(a.computed=!0),r.properties.push(a)}return be(t.ast,e.source,{kind:"upsert-object-property",target:"value",inverse:"restore-object-property"})}function TS(e){return ze.isIdentifier(e)?e.name:ze.isStringLiteral(e)?e.value:ze.isNumericLiteral(e)?String(e.value):null}import{isSiteEditRuntimeContainerTag as FS,isSiteEditRuntimeVoidElementTag as _S}from"@vcp-dev/contracts/site-edit-runtime-capability";function ir(e){if(!e.composition)throw new Error("Composition unavailable for render source graph.");return e.composition}function MS(e,t,n){let r=ir(n),o=t.nodes.get(e),i=n.elements.get(e);if(!o||!i)return{composition:r,key:e,canUpdateText:!1,canInsertChild:!1,canMove:!1,canRemove:!1,constraints:[{kind:"opaque-region",message:"Node not found in graph"}]};let s=o.constraints.map(C=>({kind:C.kind,message:C.reason})),a=i.isOpaque,l=o.parentKey===null&&i.componentName==="Page",u=i.tag.toLowerCase(),d=i.tag!==u,f=!d&&_S(u),g=d||FS(u),m=d&&i.childKeys.length>0&&!i.isPublicUiComponent,h=i.textSegments.length>0&&i.textSegments.some(C=>C.editable);f&&!s.some(C=>C.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' is void: children cannot be inserted`}),!f&&!g&&!s.some(C=>C.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' cannot contain structured children`});let y=h&&(!a||i.importedFrom==="next/link"),x=!i.isPublicUiComponent&&!f&&g&&(!a||m);return{composition:r,key:e,canUpdateText:y,canInsertChild:x,canMove:!l,canRemove:!l,constraints:s}}function Pd(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,MS(r,e,t));return n}function Aa(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:Re(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=OS(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:Re(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Unable to locate JSX element for key ${t.identity.key}`}]};let r=n.node.openingElement,o=r.attributes.find(d=>d.type==="JSXAttribute"&&d.name.type==="JSXIdentifier"&&d.name.name==="className"),i={key:e.key,composition:e.route.composition,filePath:t.sourceFile,componentName:t.componentName,openingElementRange:Td(r),version:{documentVersion:e.route.graph.version,contentHash:Re(e.route.source)}};if(!o)return{...i,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element."}]};let s=o.value,a=s?.type==="StringLiteral"?"stringLiteral":"expression",c=n.get("openingElement").get("attributes").find(d=>d.node===o),l=c?.isJSXAttribute()?c.get("value"):null,u=l?.isJSXExpressionContainer()?LS(l.get("expression")):void 0;return{...i,sourceKind:a,attrRaw:Ad(e.route.source,o),valueRaw:s?Ad(e.route.source,s):null,...u===void 0?{}:{resolvedClassName:u},attrRange:Td(o),diagnostics:[]}}function Fd(e){let{source:t,oldAttrRange:n,openingElementRange:r,newAttrRaw:o}=e;if(n){let a=n.start>0&&/\s/.test(t[n.start-1]??"")?n.start-1:n.start,c=o?`${a<n.start?" ":""}${o}`:"";return t.slice(0,a)+c+t.slice(n.end)}if(!o)return t;let i=r.end,s=t.slice(Math.max(0,i-2),i)==="/>"?i-2:i-1;return t.slice(0,s)+` ${o}`+t.slice(s)}function OS(e,t){let n=Mt({source:e,profile:wn({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=ue(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:DS(t.sourceRange)});return!r.ok||!r.match.path.isJSXElement()?null:r.match.path}function LS(e){let t=new Set,n=e;if(n.isIdentifier()){for(;n.isIdentifier();){let r=n.scope.getBinding(n.node.name);if(!r?.constant||!r.path.isVariableDeclarator()||!r.path.get("id").isIdentifier({name:n.node.name})||!r.path.parentPath.isVariableDeclaration({kind:"const"})||t.has(r.path.node))return;t.add(r.path.node);let o=r.path.get("init");if(!o.isExpression())return;n=o}if(n.isStringLiteral())return n.node.value;if(n.isTemplateLiteral()&&n.node.expressions.length===0)return n.node.quasis.map(r=>r.value.cooked??r.value.raw).join("")}}function _d(e){let t=Mt({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 Ad(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function Td(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 DS(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function Md(){let e=new Set;return{emit(t){for(let n of Array.from(e))try{n(t)}catch{}},subscribe(t){return e.add(t),()=>{e.delete(t)}}}}import{randomUUID as BS}from"node:crypto";import bi from"node:fs/promises";import Ta from"node:path";import{setTimeout as jS}from"node:timers/promises";var $S={async mkdir(e,t){await bi.mkdir(e,t)},async writeFile(e,t,n){await bi.writeFile(e,t,n)},async rename(e,t){await bi.rename(e,t)},async rm(e,t){await bi.rm(e,t)}},VS=new Set(["EACCES","EBUSY","EPERM"]),KS=[10,20,40,80,160];async function US(e,t,n){for(let r of KS)try{await e.rename(t,n);return}catch(o){if(!JS(o))throw o;await jS(r)}await e.rename(t,n)}function JS(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&VS.has(e.code)}async function Si(e,t,n=$S){let r=Ta.dirname(e),o=Ta.basename(e),i=Ta.join(r,`.${o}.${process.pid}.${BS()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await US(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import Fa from"@babel/traverse";import*as I from"@babel/types";import*as me from"@babel/types";function Bt(e,t={}){if(me.isTSAsExpression(e)||me.isTSSatisfiesExpression(e)||me.isTSNonNullExpression(e)||me.isTypeCastExpression(e)||me.isParenthesizedExpression(e))return Bt(e.expression,t);if(me.isStringLiteral(e))return{status:"resolved",value:e.value};if(me.isNumericLiteral(e))return Number.isFinite(e.value)?{status:"resolved",value:e.value}:{status:"unresolved"};if(me.isBooleanLiteral(e))return{status:"resolved",value:e.value};if(me.isNullLiteral(e))return{status:"resolved",value:null};if(me.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(me.isIdentifier(e))return e.name==="undefined"&&!t.resolveIdentifier?{status:"undefined"}:t.resolveIdentifier?.(e.name)??{status:"unresolved"};if(me.isUnaryExpression(e)&&e.operator==="void"&&me.isNumericLiteral(e.argument)&&e.argument.value===0)return{status:"undefined"};if(me.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||me.isSpreadElement(r))return{status:"unresolved"};let o=Bt(r,t);if(o.status!=="resolved")return{status:"unresolved"};n.push(o.value)}return{status:"resolved",value:n}}if(me.isObjectExpression(e)){let n=Object.create(null);for(let r of e.properties){if(!me.isObjectProperty(r)||r.computed||!me.isExpression(r.value))return{status:"unresolved"};let o=XS(r.key);if(o===null)return{status:"unresolved"};let i=Bt(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 me.isMemberExpression(e)||me.isOptionalMemberExpression(e)?t.resolveMember?.(e)??{status:"unresolved"}:{status:"unresolved"}}function XS(e){return me.isIdentifier(e)?e.name:me.isStringLiteral(e)?e.value:me.isNumericLiteral(e)?String(e.value):null}var zS=typeof Fa=="function"?Fa:Fa.default;function Ze(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 Da(e){let t=e.openingElement;return I.isJSXIdentifier(t.name)?t.name.name==="Fragment":I.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function ar(e){return I.isJSXFragment(e)}function Ld(e){return I.isJSXIdentifier(e.name)?e.name.name:I.isJSXMemberExpression(e.name)?Dd(e.name):I.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function Dd(e){return I.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:I.isJSXMemberExpression(e.object)?`${Dd(e.object)}.${e.property.name}`:e.property.name}function HS(e){return e.split(".")[0]??e}function GS(e){let t=e;for(;t;){let n=t.node;if(I.isFunctionDeclaration(n)&&n.id||I.isVariableDeclarator(n)&&I.isIdentifier(n.id))return n.id.name;if(I.isExportDefaultDeclaration(n)){let r=n.declaration;if(I.isFunctionDeclaration(r)&&r.id)return r.id.name;if(I.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function YS(){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 ZS(e){let t=new Map;for(let n of e.program.body){if(!I.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(I.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(I.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(I.isImportSpecifier(o)){let i=I.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function Qt(e,t=[]){if(I.isIdentifier(e))return t.push(e.name),t;if(I.isObjectPattern(e)){for(let n of e.properties)I.isObjectProperty(n)?Qt(n.value,t):I.isRestElement(n)&&Qt(n.argument,t);return t}if(I.isArrayPattern(e)){for(let n of e.elements)n&&(I.isRestElement(n)?Qt(n.argument,t):Qt(n,t));return t}return I.isAssignmentPattern(e)?(Qt(e.left,t),t):(I.isRestElement(e)&&Qt(e.argument,t),t)}function Ct(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Ur(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 QS(e,t,n){e.set(t,{resolved:!0,value:n})}function Ba(e,t){e.set(t,{resolved:!1})}function Bd(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 Ve(e,t,n){if(I.isTSAsExpression(e)||I.isTSSatisfiesExpression(e)||I.isTSNonNullExpression(e)||I.isTypeCastExpression(e)||I.isParenthesizedExpression(e))return Ve(e.expression,t,n);if(I.isLogicalExpression(e))return Ei([Ve(e.left,t,n),Ve(e.right,t,n)]);if(I.isBinaryExpression(e))return Ei([I.isExpression(e.left)?Ve(e.left,t,n):null,I.isExpression(e.right)?Ve(e.right,t,n):null]);if(I.isConditionalExpression(e))return Ei([Ve(e.consequent,t,n),Ve(e.alternate,t,n)]);if(I.isTemplateLiteral(e))return Ei(e.expressions.filter(I.isExpression).map(i=>Ve(i,t,n)));if(I.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!I.isMemberExpression(e)&&!I.isOptionalMemberExpression(e))return null;let r=[],o=e;for(;I.isMemberExpression(o)||I.isOptionalMemberExpression(o);){if(o.computed)if(I.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(I.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&I.isExpression(o.property)){let i=un(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(!I.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return I.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:Ct(e,t),base:o.name,path:r}:null}function Ei(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 un(e,t){if(I.isStringLiteral(e)||I.isNumericLiteral(e)||I.isBooleanLiteral(e))return e.value;if(I.isNullLiteral(e))return null;if(I.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(I.isIdentifier(e)){let n=Ur(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(I.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||I.isSpreadElement(r))return;let o=un(r,t);if(o===void 0)return;n.push(o)}return n}if(I.isObjectExpression(e)){let n={};for(let r of e.properties){if(!I.isObjectProperty(r)||r.computed||!I.isExpression(r.value))return;let o=null;if(I.isIdentifier(r.key)?o=r.key.name:I.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!I.isIdentifier(r.value))return;let s=Ur(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=un(r.value,t);if(i===void 0)return;n[o]=i}return n}if(I.isMemberExpression(e)){let n=Ve(e,"",t);if(!n)return;let r=Ur(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=Bd(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(I.isCallExpression(e))return $d(e,t)??void 0}function jd(e,t,n){let r=Ve(e,n,t);if(!r)return I.isMemberExpression(e)||I.isBinaryExpression(e)||I.isLogicalExpression(e)||I.isConditionalExpression(e)||I.isCallExpression(e)?{value:Ct(e,n),source:null}:null;let o=Ur(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?Bd(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 _a(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:YS(),parentStack:[],valueScopes:i,importMap:o}}function Oa(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of Qt(o.id))Ba(n,s);if(!I.isIdentifier(o.id)||!o.init||!I.isExpression(o.init))continue;let i=un(o.init,t);i!==void 0&&QS(n,o.id.name,i)}}function qS(e){let t=[];for(let n of e){if(I.isVariableDeclaration(n)){t.push(n);continue}I.isExportNamedDeclaration(n)&&n.declaration&&I.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function eE(e,t,n){let r=[],o=0;for(let i of e)if(I.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:Ze(i),editable:!0,source:null})}else if(I.isJSXExpressionContainer(i)&&I.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:Ze(i),editable:!0,source:null});else if(I.isJSXExpressionContainer(i)&&I.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:Ze(i),editable:!0,source:null}):r.push({index:o++,value:Ct(s,n),sourceRange:Ze(i),editable:!0,source:Ve(s,n,t)})}else if(I.isJSXExpressionContainer(i)&&I.isExpression(i.expression)){let s=jd(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:Ze(i),editable:!0,source:s.source})}return r}function tE(e,t,n){let r=[];for(let[o,i]of e.attributes.entries()){if(!I.isJSXAttribute(i))continue;let s=rE(i.name);if(!s)continue;let a=Ct(i,n);if(I.isStringLiteral(i.value)){r.push({name:s,value:i.value.value,sourceRange:Ze(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:Ze(i),source:null,syntaxKind:"boolean-shorthand",raw:a,order:o,resolution:{status:"resolved",value:!0},resolvedValue:!0});continue}if(I.isJSXExpressionContainer(i.value)&&I.isExpression(i.value.expression)){let c=un(i.value.expression,t);if(s==="className"){let g=typeof c=="string"?c:c===void 0?$d(i.value.expression,t):null;if(g){r.push({name:s,value:g,sourceRange:Ze(i),source:null,resolvedValue:g,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:g}});continue}}let l=jd(i.value.expression,t,n);if(c!==void 0){r.push({name:s,value:uE(c),sourceRange:Ze(i),source:Ve(i.value.expression,n,t),resolvedValue:c,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:c}});continue}let u=oE(i.value.expression,t),d=Ve(i.value.expression,n,t),f=l?.value??Ct(i.value.expression,n);r.push({name:s,value:u.status==="undefined"?"undefined":f,sourceRange:Ze(i),source:l?.source??d,syntaxKind:"expression",raw:a,order:o,resolution:u})}}return r}function nE(e,t,n){return e.attributes.flatMap((r,o)=>!I.isJSXSpreadAttribute(r)||!I.isExpression(r.argument)?[]:[{raw:Ct(r.argument,n),sourceRange:Ze(r),order:o,source:Ve(r.argument,n,t)}])}function rE(e){return I.isJSXIdentifier(e)?e.name:I.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function oE(e,t){return Bt(e,{resolveIdentifier(n){let r=Ur(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=un(n,t);return r===void 0?{status:"unresolved"}:{status:"resolved",value:r}}})}function $d(e,t){let n=sr(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function sr(e,t){if(I.isStringLiteral(e))return[e.value];if(I.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(I.isNullLiteral(e))return[];if(I.isBooleanLiteral(e))return e.value?null:[];if(I.isIdentifier(e)||I.isMemberExpression(e)){if(I.isIdentifier(e)&&e.name==="undefined")return[];let n=un(e,t);return typeof n=="string"?[n]:null}if(I.isConditionalExpression(e)){let n=sr(e.consequent,t),r=sr(e.alternate,t);return!n||!r?null:[...n,...r]}if(I.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=un(e.left,t);return n===!1||n===null?[]:sr(e.right,t)}if(I.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||I.isSpreadElement(r))return null;let o=sr(r,t);if(!o)return null;n.push(...o)}return n}if(I.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!I.isObjectProperty(r))return null;let o=sE(r.key);if(!o)return null;n.push(o)}return n}if(I.isCallExpression(e)){let n=iE(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!I.isExpression(o))return null;let i=sr(o,t);if(!i)return null;r.push(...i)}return r}return null}function iE(e){return I.isIdentifier(e)?e.name:I.isMemberExpression(e)&&I.isIdentifier(e.property)?e.property.name:null}function sE(e){return I.isIdentifier(e)?e.name:I.isStringLiteral(e)?e.value:null}function aE(e,t){let n=e.attributes.find(r=>I.isJSXAttribute(r)&&I.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!I.isJSXAttribute(n)||!I.isJSXExpressionContainer(n.value)?null:n.value.expression}function cE(e,t){for(let n of t){let r=aE(e,n);if(r)return r}return null}function lE(e){return I.isJSXIdentifier(e.name)?e.name.name:null}function uE(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function dE(e){if(!I.isCallExpression(e)&&!I.isOptionalCallExpression(e))return null;let t=e.callee;return!I.isMemberExpression(t)&&!I.isOptionalMemberExpression(t)||!I.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!I.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function Ma(e){return I.isArrowFunctionExpression(e)||I.isFunctionExpression(e)}function fE(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function pE(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function Od(e,t,n,r){if(!e||!I.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:Ct(e,n),collectionSource:Ve(e,n,r)};if(t){let i=t.params[0],s=t.params[1];I.isIdentifier(i)&&(o.itemParamName=i.name),I.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function qt(e,t,n){if(!e)return[];if(I.isJSXElement(e)){if(Da(e))return Ri(e.children,t,n);let r=Ii(e,t,n);return r?[r]:[]}return ar(e)?Ci(e,t,n):I.isParenthesizedExpression(e)?qt(e.expression,t,n):I.isExpression(e)?wi(e,t,n):[]}function vi(e,t,n){let r=new Map;for(let o of e.params)for(let i of Qt(o))Ba(r,i);t.valueScopes.push(r);try{if(!I.isBlockStatement(e.body))return qt(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return Vd(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function Vd(e,t,n){let r=[];for(let o of e){if(I.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];if(i){Oa([o],t,i);for(let s of o.declarations)I.isIdentifier(s.id)&&(I.isJSXElement(s.init)||I.isJSXFragment(s.init))&&r.push(...qt(s.init,t,n))}continue}r.push(...La(o,t,n))}return r}function La(e,t,n){if(I.isReturnStatement(e))return e.argument?qt(e.argument,t,n):[];if(I.isBlockStatement(e))return Mn(e.body,t,n);if(I.isIfStatement(e)){let r=I.isBlockStatement(e.consequent)?Mn(e.consequent.body,t,n):La(e.consequent,t,n),o=e.alternate?I.isBlockStatement(e.alternate)?Mn(e.alternate.body,t,n):La(e.alternate,t,n):[];return[...r,...o]}if(I.isSwitchStatement(e))return Mn(e.cases.flatMap(r=>r.consequent),t,n);if(I.isTryStatement(e)){let r=Mn(e.block.body,t,n);return e.handler&&r.push(...Mn(e.handler.body.body,t,n)),e.finalizer&&r.push(...Mn(e.finalizer.body,t,n)),r}return[]}function Mn(e,t,n){let r=new Map;t.valueScopes.push(r);try{return Vd(e,t,n)}finally{t.valueScopes.pop()}}function ki(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:Ze(r),sourceCandidates:i&&i.length>0?i:void 0})}function mE(e,t,n,r){let o=cE(e.openingElement,["items","dataSource","data"]),i={key:t,tag:Ld(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!I.isJSXAttribute(s))continue;let a=lE(s);if(!a||!I.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!I.isJSXEmptyExpression(c)){if(fE(a)&&Ma(c)){let l=vi(c,n,r),u=Od(o,c,r,n);ki(n,"repeat-region",t,s,l,u?[u]:void 0);continue}if(pE(a)){let l=Ma(c)?vi(c,n,r):qt(c,n,r);ki(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!I.isJSXExpressionContainer(s)||!Ma(s.expression))continue;let a=vi(s.expression,n,r),c=Od(o,s.expression,r,n);ki(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function Ii(e,t,n){let r=Ld(e.openingElement);if(r==="Fragment"||Da(e))return Ri(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,u=Br(t.file,t.componentName,l),d={file:t.file,component:t.componentName,structuralPath:l,key:u},f=s?"component-boundary":null,g=eE(e.children,t,n),m=tE(e.openingElement,t,n),h=nE(e.openingElement,t,n),y,x,E=!1;if(s){let C=t.importMap.get(r)??t.importMap.get(HS(r));C&&(y=C.specifier,x=C.exportName,E=Nn(C.specifier,t.file))}let v={identity:d,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:Ze(e),parentKey:i,childKeys:[],textSegments:g,attributes:m.length>0?m:void 0,attributeSpreads:h.length>0?h:void 0,boundaryKind:f,isOpaque:s,...E?{isPublicUiComponent:!0}:{},importedFrom:y,exportName:x};return t.elements.set(u,v),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(u),mE(e,u,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:u,tag:r}),gE(e.children,t,n),t.parentStack.pop()),u}function Ci(e,t,n){return Ri(e.children,t,n)}function Ri(e,t,n){let r=[];for(let o of e)if(I.isJSXElement(o))if(Da(o))r.push(...Ri(o.children,t,n));else{let i=Ii(o,t,n);i&&r.push(i)}else ar(o)?r.push(...Ci(o,t,n)):I.isJSXExpressionContainer(o)&&r.push(...wi(o.expression,t,n));return r}function gE(e,t,n){for(let r of e)I.isJSXElement(r)?Ii(r,t,n):ar(r)?Ci(r,t,n):I.isJSXExpressionContainer(r)&&wi(r.expression,t,n)}function hE(e){return e==="&&"||e==="||"||e==="??"}function wi(e,t,n){if(I.isJSXEmptyExpression(e))return[];let r=dE(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,c={kind:"repeat-template",collectionExpression:Ct(r.collection,n),collectionSource:Ve(r.collection,n,t)};if(I.isArrowFunctionExpression(a)||I.isFunctionExpression(a)){let u=a.params[0],d=a.params[1];I.isIdentifier(u)&&(c.itemParamName=u.name),I.isIdentifier(d)&&(c.indexParamName=d.name)}s.push(c);let l={kind:"repeat-region",ownerKey:i?.key??"",childKeys:[],sourceRange:Ze(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(l),(I.isArrowFunctionExpression(a)||I.isFunctionExpression(a))&&l.childKeys.push(...vi(a,t,n)),l.childKeys}if(I.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:Ct(e.test,n),conditionSource:Ve(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Ze(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...qt(e.consequent,t,n)),s.childKeys.push(...qt(e.alternate,t,n)),s.childKeys}if(I.isLogicalExpression(e)&&hE(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:Ct(e.left,n),conditionSource:Ve(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Ze(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...qt(e.right,t,n)),s.childKeys}if(I.isParenthesizedExpression(e))return wi(e.expression,t,n);if(I.isJSXElement(e)){let o=Ii(e,t,n);return o?[o]:[]}return ar(e)?Ci(e,t,n):[]}function yE(e){let t=e.argument;return t&&(I.isExpression(t)||ar(t))?t:null}function Jr(e,t){let n=[];for(let r of e){if(I.isReturnStatement(r)){let o=yE(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(I.isIfStatement(r)){let o=I.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...Jr(o,r.test)),r.alternate){let i=I.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...Jr(i,r.test))}continue}if(I.isSwitchStatement(r))for(let o of r.cases){let i=o.test?I.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...Jr(o.consequent,i))}}return n}function Ni(e){return{routeId:e,rootKeys:[],elements:new Map,regions:[],fileIndex:new Map,version:1,diagnostics:[]}}function Kd(e){let{file:t,source:n,ast:r}=e,o=e.imports.map(f=>f.specifier);if(!I.traverseFast(r,f=>{if(I.isJSXElement(f)||I.isJSXFragment(f))return I.traverseFast.stop}))return{graph:Ni(t),localImports:o};let s=new Map,a=[],c=[],l=new Map,u=ZS(r);zS(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(f){let g=GS(f);if(!g)return;let m=f.node,h=[];if(I.isArrowFunctionExpression(m))I.isExpression(m.body)||ar(m.body)?h=[{argument:m.body,statement:I.returnStatement(I.isExpression(m.body)?m.body:null)}]:I.isBlockStatement(m.body)&&(h=Jr(m.body.body));else{let P=m.body;I.isBlockStatement(P)&&(h=Jr(P.body))}if(h.length===0){f.skip();return}let y=new Map;Oa(qS(r.program.body),_a(t,g,s,a,u,[y]),y);let x=new Map;for(let P of m.params)for(let F of Qt(P))Ba(x,F);let E=I.isBlockStatement(m.body)?m.body.body:[],v=h[0]?.statement??null;for(let P of E){if(v&&P===v)break;I.isVariableDeclaration(P)&&Oa([P],_a(t,g,s,a,u,[y,x]),x)}let C=_a(t,g,s,a,u,[y,x]);for(let P of h){let F=qt(P.argument,C,n);for(let R of F)c.includes(R)||c.push(R);if(P.condition){let R={kind:"conditional-branch",conditionExpression:Ct(P.condition,n),conditionSource:Ve(P.condition,n,C)};ki(C,"conditional-region","",P.statement,F,[R])}}f.skip()}});let d=[...s.keys()];return d.length>0&&l.set(t,d),{graph:{routeId:t,rootKeys:c,elements:s,regions:a,fileIndex:l,version:1,diagnostics:[]},localImports:o}}function ja(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function Pi(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function Ud(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 Jd(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??Wt,c=new Map,l=new Map,u=new Map,d=[],f=new Set,g=x=>{let E=`${x.path}\0${x.code}\0${x.message}\0${JSON.stringify(x.details??{})}`;f.has(E)||(f.add(E),d.push(x))},m=[{file:e,source:t,depth:0,diagnosticEntryFile:e,importStack:[]},...(o.additionalEntries??[]).map(x=>({file:x.file,source:x.source,depth:0,diagnosticEntryFile:x.file,importStack:[]}))],h=new Set;for(;m.length>0;){let x=m.shift(),{file:E,source:v,depth:C,diagnosticEntryFile:P,importStack:F}=x;if(h.has(E))continue;h.add(E),c.set(E,v);let R=o.validationOnly&&C<i?o.validatedImports?.(E,v):void 0,N,T;if(R)N=Ni(E),T=R;else{let D=a(E,v);if(!D.ok){g(Pi(D.diagnostic,P,F));continue}u.set(E,D.module);let Z=o.validationOnly&&C<i?{graph:Ni(E),localImports:D.module.imports.map(fe=>fe.specifier)}:Kd(D.module);N=Z.graph,T=Z.localImports}let L=[...new Set([...N.elements.values()].map(D=>D.importedFrom).filter(D=>typeof D=="string"&&It(D)))],q=L.length?await Ud(L,D=>Ko(E,D,r)):[],W=new Map(L.map((D,Z)=>[D,q[Z]]));for(let D of N.elements.values())if(D.importedFrom&&It(D.importedFrom)){let Z=D.importedFrom,fe=W.get(Z);fe.ok?(D.importedFrom=fe.path,Ht(fe.path)&&(D.isPublicUiComponent=!0)):Nn(Z,E)||g(Pi(fe.diagnostic,P,ja(F,E,Z,fe.diagnostic.path)))}if(l.set(E,N),C>=i)continue;let oe=await Ud(T,async D=>{if(Iu(D))return null;let Z=W.get(D)??await Ko(E,D,r);if(!Z.ok)return Nn(D,E)?null:{diagnostic:Pi(Z.diagnostic,P,ja(F,E,D,Z.diagnostic.path))};let fe=Z.path;if(h.has(fe)||Ht(fe))return null;let ct=ja(F,E,D,fe);try{let rt=await n(fe);return{entry:{file:fe,source:rt,depth:C+1,diagnosticEntryFile:P,importStack:ct}}}catch(rt){return{diagnostic:Pi({path:fe,code:"import-read-failed",message:`Failed to read imported file: ${fe}`,details:{fromFile:E,specifier:D,reason:rt instanceof Error?rt.message:String(rt)}},P,ct)}}});for(let D of oe)D&&"entry"in D?m.push(D.entry):D&&g(D.diagnostic)}let y=xE(e,l,s,(o.additionalEntries??[]).map(x=>x.file));return y.diagnostics=d,{graph:y,allSources:c,diagnostics:d,parsedModules:u,entryModule:u.get(e)??null}}function xE(e,t,n,r=[]){let o=new Map,i=[],s=new Map,a=[];for(let[c,l]of t){for(let[u,d]of l.elements)o.set(u,d);for(let u of l.regions)i.push(u);for(let[u,d]of l.fileIndex){let f=s.get(u)??[];s.set(u,[...f,...d])}if(c===e){a=l.rootKeys;continue}r.includes(c)&&(a=[...a,...l.rootKeys])}return{routeId:e,rootKeys:a,elements:o,regions:i,fileIndex:s,version:n}}function Xd(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 bE,randomUUID as Ga}from"node:crypto";import De from"node:fs/promises";import Be from"node:path";var tf=new WeakMap;function cr(e){return tf.get(e)?.()??e.readIndex()}var xt=1,Va=1,SE=2,EE="index.json",vE="recovery.json",kE="transaction-journal.json",IE="document-version.json",Fi={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},se={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"},ce=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};function en(){return{entries:new Map,blobSizes:new Map}}function Ai(e,t){let n={entries:new Map,blobs:new Map,objectBytes:0};for(let r of e)nf(n,r,t);return n}function nf(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 rf(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 of(e,t={}){let n=VE(e),r=XE(t.limits),o=$a(n),i=KE(n),s=await ot(i),a=await ot(o)||s;a||(await _E(n),await ME(n)),a||await zE(n);let c=en(),l=await Mi(n,c),u=new Set(a?(await ji(n)).map(E=>E.stageId):[]);a||await Yd(n,l.entryIds,c);let d=l.digest,f=Ai(l.entryIds,c),g=async E=>{let{index:v,sizeBytes:C}=await Gr(n);if(ff(v,E),v.digest!==d){let P=en();await lf(n,v.entryIds,P,C),f=Ai(v.entryIds,P),d=v.digest}return{...$i(v),totalBytes:f.objectBytes+C}},m=async E=>{Ya(E),await g(),await Hd(n,f,[E.entryId],E.blobIds,E.stageId),await _i(n,E.stageId)},h=async(E,v)=>{let C=await g(v);af(E,C.entryIds.length);let P=en();for(let F of C.entryIds.slice(Math.min(C.cursor,E)+1,Math.max(C.cursor,E)+1))await zr(n,F,P);return C},y=async()=>{if(await ot(o)||s)throw new ce(se.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")},x={rootDir:n,recoveryRequired:a,async readDocumentVersion(){return qd(n)},async writeDocumentVersion(E){if(await y(),!Number.isInteger(E)||E<0)throw new ce(se.INVALID_SCHEMA,"document version must be a non-negative integer");let v=await qd(n);E<=v||await Xr(hf(n),{schemaVersion:1,version:Math.max(v,E)})},async stageAppend(E,v={}){await y();let C=await wE(E,r),P={schemaVersion:Va,stageId:Ga(),entryId:C.entryId,blobIds:C.blobs.map(F=>F.digest)};try{await NE(n,C),await AE(n,P,v.durableManifest!==!1)}catch(F){try{await m(P)}catch(R){throw new ce(se.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:R})}throw F}return{stageId:P.stageId,entryId:P.entryId,blobIds:P.blobIds}},async discardStage(E){await y(),Ja(E);let v=await Ka(n,E);v&&await m(v)},async previewStagedAppend(E,v){await y();let C=await g(v);return(await zd(n,r,E,C,f)).transition},async previewCursor(E,v){await y();let C=await h(E,v);return sf(C,C.entryIds,E)},async publishStagedAppend(E,v,C){if(await y(),Li(E,"entryId"),C){Ja(C);let T=await Ka(n,C);if(!T||T.entryId!==E)throw new ce(se.INVALID_SCHEMA,"history stage does not match the published entry")}let P=await g(v),F=f,R=await zd(n,r,E,P,F),N=await Qd({rootDir:n,previousDigest:R.current.digest,entryIds:R.entryIds,cursor:R.cursor,readback:async()=>Zd(n,R.usage),afterWrite:async()=>{C?await _i(n,C):await FE(n,E),await Hd(n,R.usage,[...F.entries.keys()].filter(T=>!R.usage.entries.has(T)),[...F.blobs.keys()].filter(T=>!R.usage.blobs.has(T)))}});return f=R.usage,d=N.digest,N},async append(E){await y();let v=await g(),C=await x.stageAppend(E);try{return await x.publishStagedAppend(C.entryId,v.digest,C.stageId)}catch(P){throw await x.discardStage(C.stageId),P}},async readEntry(E){return Li(E,"entryId"),zr(n,E)},async readBlob(E){Li(E,"blobId");let v=await xf(n,E),C=await Wr(v,se.NOT_FOUND,"blob");return gf(C,E,v),C},async readIndex(){let E=en(),v=await Mi(n,E);return f=Ai(v.entryIds,E),d=v.digest,v},async readStatus(){let E=await Oi(n);return{canUndo:E.undoIds.length>0,canRedo:E.redoIds.length>0,undoDepth:E.undoIds.length,redoDepth:E.redoIds.length,cursor:E.cursor,recoveryRequired:await ot(o)||await ot(i)}},async readUndoRedoIds(){let E=await Oi(n);return{undoIds:E.undoIds,redoIds:E.redoIds,currentId:E.currentId}},async setCursor(E,v){await y();let C=await h(E,v),P=await Qd({rootDir:n,previousDigest:C.digest,entryIds:C.entryIds,cursor:E,readback:async()=>Zd(n,f)});return d=P.digest,P},async markRecoveryRequired(E){await ot(o)||await Xr($a(n),{schemaVersion:xt,reason:UE(E),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await De.rm($a(n),{force:!0})},async readTransactionJournal(){return await ot(i)?Ti(i):null},async writeTransactionJournal(E){await y(),yf(E);try{await Xr(i,E)}catch(C){let P=await Ti(i).catch(()=>null);if(P&&Buffer.from(it(P)).equals(Buffer.from(it(E))))return;throw P?new ce(se.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:C}):C}let v=await Ti(i);if(!Buffer.from(it(v)).equals(Buffer.from(it(E))))throw new ce(se.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(E){let v=await ot(i)?await Ti(i):null;if(v&&v.transactionId!==E)throw new ce(se.INVALID_SCHEMA,"transaction journal changed concurrently");try{await De.rm(i,{force:!0})}catch(C){if(!await ot(i))return;throw C}if(await ot(i))throw new ce(se.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await y();for(let C of u)await _i(n,C),u.delete(C);await OE(n);let E=en(),v=await Mi(n,E);await Yd(n,v.entryIds,E),f=Ai(v.entryIds,E),d=v.digest}};return tf.set(x,()=>Oi(n)),x}async function zd(e,t,n,r,o){Li(n,"entryId");let i=en(),s=await zr(e,n,i),a={entries:new Map(o.entries),blobs:new Map(o.blobs),objectBytes:o.objectBytes},c=r.entryIds.slice(0,r.cursor+1);for(let u of r.entryIds.slice(r.cursor+1))rf(a,u);nf(a,s.id,i),c.push(s.id);let l=PE(c,t,a);return{current:r,entryIds:l.entryIds,cursor:l.cursor,usage:a,transition:sf(r,l.entryIds,l.cursor)}}function sf(e,t,n){return af(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:CE(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function CE(e,t){return dn(it({schemaVersion:xt,entryIds:e,cursor:t}))}function af(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new ce(se.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function RE(e){if(!Rt(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!ut(e.expectedIndexDigest)||!ut(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!ut(n)?!1:t===-1?n===null:ut(n)}async function wE(e,t){if(!e.kind.trim())throw new ce(se.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new ce(se.INVALID_JSON,"history blob name must not be empty");let l=$E(c.data),u=dn(l);n.push({name:c.name,bytes:l,digest:u,sizeBytes:l.byteLength}),r.push({name:c.name,digest:u,sizeBytes:l.byteLength})}let o={schemaVersion:xt,kind:e.kind,manifest:e.manifest,blobs:r},i=it({...o}),s=dn(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new ce(se.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function NE(e,t){let n=ec(e,t.entryId),r={id:t.entryId,...t.entryBody},o=new Map(t.blobs.map(c=>[c.digest,c])),i=[...Array.from(o.values(),c=>Wd(tc(e,c.digest),c.bytes,{kind:"blob",digest:c.digest},rc(e,c.digest))),Wd(n,it(r),{kind:"entry",digest:t.entryId},nc(e,t.entryId))],a=(await Promise.allSettled(i)).find(c=>c.status==="rejected");if(a)throw a.reason}async function Wd(e,t,n,r){let o=await Wa(e)??(r?await Wa(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new ce(n.kind==="blob"?se.BLOB_CORRUPT:se.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await pf(e,t)}function PE(e,t,n){let r=[...e],o=r.length-1;for(;;){if(n.objectBytes+it(df(r,o)).byteLength<=t.maxSessionBytes&&r.length<=t.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new ce(se.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");rf(n,r.shift()),o-=1}}async function AE(e,t,n){Ya(t);let r=qa(e,t.stageId);if(n){await Xr(r,t);return}await jE(r,t)}async function Ka(e,t){let n=await Wa(qa(e,t));if(n===null)return null;let r=Yr(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=Ya(r);if(o.stageId!==t)throw new ce(se.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function ji(e){let t=[];for(let n of await Bi(Qa(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);Ja(r);let o=await Ka(e,r);o&&t.push(o)}return t}async function Hd(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 ji(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 Gd(ec(e,a),nc(e,a));for(let a of new Set(r))!t.blobs.has(a)&&!s.has(a)&&await Gd(tc(e,a),rc(e,a));await Ha(Zr(e)),await Ha(Qr(e))}async function _i(e,t){await Ua(qa(e,t)),await TE(e)}async function TE(e){try{await De.rmdir(Qa(e))}catch(t){if(qr(t)||Rt(t)&&t.code==="ENOTEMPTY")return;throw t}}async function FE(e,t){for(let n of await ji(e))n.entryId===t&&await _i(e,n.stageId)}async function Ua(e){if(await De.rm(e,{force:!0}),await ot(e))throw new ce(se.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function Gd(e,t){await Ua(e),await Ua(t)}function Ya(e){if(!Rt(e)||e.schemaVersion!==Va||typeof e.stageId!="string"||!cf(e.stageId)||!ut(e.entryId))throw new ce(se.INVALID_SCHEMA,"history stage schema is invalid");let t=mf(e.blobIds,"history stage blobIds");return{schemaVersion:Va,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function Ja(e){if(!cf(e))throw new ce(se.INVALID_PATH,"history stageId must be a UUID")}function cf(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 Yd(e,t,n=en()){let r=new Set(t),o=new Set;for(let l of t){let u=await zr(e,l,n);for(let d of u.blobs)o.add(d.digest)}for(let l of await ji(e)){r.add(l.entryId);for(let u of l.blobIds)o.add(u)}let i=Zr(e),s=await Bi(i);for(let l of s){if(!l.endsWith(".json"))continue;let u=ef(l.slice(0,-5));u&&!r.has(u)&&await Di(Be.join(i,l))}let a=Qr(e),c=await Bi(a);for(let l of c){let u=ef(l);u&&!o.has(u)&&await Di(Be.join(a,l))}}async function Mi(e,t=en()){let{index:n,sizeBytes:r}=await Gr(e),{totalBytes:o}=await lf(e,n.entryIds,t,r);return{...$i(n),totalBytes:o}}async function Zd(e,t){let{index:n,sizeBytes:r}=await Gr(e);return{...$i(n),totalBytes:t.objectBytes+r}}async function Gr(e){let t=Za(e),n=await Wr(t,se.NOT_FOUND,"index"),r=Yr(Buffer.from(n).toString("utf8"),"index");return{index:LE(r),sizeBytes:n.byteLength}}async function Oi(e){return $i((await Gr(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:xt,digest:e.digest,entryIds:t,cursor:e.cursor,currentId:t[e.cursor]??null,undoIds:n,redoIds:r}}async function lf(e,t,n,r){let o=0,i=new Set;o+=r??(await Gr(e)).sizeBytes;for(let s of new Set(t)){let a=await zr(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 zr(e,t,n=en()){let r=n.entries.get(t);if(r)return r.entry;let o=await JE(e,t),i=await Wr(o,se.NOT_FOUND,"entry"),s=Yr(Buffer.from(i).toString("utf8"),`entry ${t}`),a=DE(s);if(a.id!==t)throw new ce(se.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(dn(it({schemaVersion:a.schemaVersion,kind:a.kind,manifest:a.manifest,blobs:a.blobs}))!==t)throw new ce(se.ENTRY_CORRUPT,`entry hash mismatch for ${t}`);let l=[...new Set(a.blobs.map(d=>d.digest))].filter(d=>!n.blobSizes.has(d)),u=async d=>{let f=await xf(e,d),g=await Wr(f,se.NOT_FOUND,"blob");return gf(g,d,f),g.byteLength};if(l.length===1)n.blobSizes.set(l[0],await u(l[0]));else if(l.length>1){let d=new Array(l.length),f=[],g=0,m=Array.from({length:Math.min(4,l.length)},async()=>{for(;g<l.length&&f.length===0;){let x=g++;try{d[x]=await u(l[x])}catch(E){f.push({index:x,error:E})}}}),h=await Promise.allSettled(m),y=f.sort((x,E)=>x.index-E.index)[0];if(y)throw y.error;for(let x of h)if(x.status==="rejected")throw x.reason;for(let x=0;x<l.length;x++)n.blobSizes.set(l[x],d[x])}return n.entries.set(t,{entry:a,sizeBytes:i.byteLength}),a}async function uf(e,t,n){await Xr(Za(e),df(t,n))}function df(e,t){return{schemaVersion:xt,digest:dn(it({schemaVersion:xt,entryIds:e,cursor:t})),entryIds:e,cursor:t}}function ff(e,t){if(t!==void 0&&e.digest!==t)throw new ce(se.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function Qd(e){ff(await Oi(e.rootDir),e.previousDigest);let t=dn(it({schemaVersion:xt,entryIds:e.entryIds,cursor:e.cursor}));try{await uf(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.();let n=await e.readback();if(n.digest!==t)throw new ce(se.INDEX_CORRUPT,"history index readback did not match the published transition");return n}catch(n){let r=await Mi(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new ce(se.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function _E(e){await De.mkdir(e,{recursive:!0}),await De.mkdir(Zr(e),{recursive:!0}),await De.mkdir(Qr(e),{recursive:!0}),await De.mkdir(Hr(e),{recursive:!0})}async function ME(e){await De.rm(Hr(e),{recursive:!0,force:!0}),await De.mkdir(Hr(e),{recursive:!0})}async function OE(e){let t=Hr(e);await De.mkdir(t,{recursive:!0});for(let n of await Bi(t))n!=="stages"&&await De.rm(Be.join(t,n),{recursive:!0,force:!0})}function LE(e){if(!Rt(e))throw new ce(se.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==xt)throw new ce(se.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=mf(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new ce(se.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!ut(o))throw new ce(se.INDEX_CORRUPT,"index digest is invalid");let i=dn(it({schemaVersion:xt,entryIds:t,cursor:r}));if(o!==i)throw new ce(se.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:xt,digest:o,entryIds:t,cursor:r}}function DE(e){if(!Rt(e))throw new ce(se.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==xt)throw new ce(se.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!ut(t))throw new ce(se.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new ce(se.ENTRY_CORRUPT,"entry kind is invalid");let r=za(e.manifest,"entry.manifest"),o=BE(e.blobs);return{id:t,schemaVersion:xt,kind:n,manifest:r,blobs:o}}function BE(e){if(!Array.isArray(e))throw new ce(se.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!Rt(t))throw new ce(se.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new ce(se.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!ut(o))throw new ce(se.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new ce(se.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function Xr(e,t){await pf(e,it(t))}async function jE(e,t){let n=Be.dirname(e),r=Be.basename(e),o=Be.join(n,`.${r}.${process.pid}.${Ga()}.tmp`);await De.mkdir(n,{recursive:!0});try{await De.writeFile(o,it(t),{flag:"wx"}),await De.rename(o,e)}finally{await Di(o)}}async function pf(e,t){let n=Be.dirname(e),r=Be.basename(e),o=Be.join(n,`.${r}.${process.pid}.${Ga()}.tmp`);await De.mkdir(n,{recursive:!0});try{let i=await De.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await De.rename(o,e),await Ha(n)}finally{await Di(o)}}function it(e){return Buffer.from(JSON.stringify(Xa(e)),"utf8")}function Xa(e){if(Array.isArray(e))return e.map(t=>Xa(t));if(Rt(e)){let t={};for(let n of Object.keys(e).sort())t[n]=Xa(e[n]);return t}return e}function Yr(e,t){try{return JSON.parse(e)}catch(n){throw new ce(se.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function za(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=>za(n,t));if(Rt(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=za(o,t);return n}break}throw new ce(se.INVALID_JSON,`${t} must be JSON-serializable`)}function mf(e,t){if(!Array.isArray(e))throw new ce(se.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!ut(n))throw new ce(se.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function Li(e,t){if(!ut(e))throw new ce(se.INVALID_PATH,`${t} must be a sha256 digest`)}function ut(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function dn(e){return`sha256:${bE("sha256").update(e).digest("hex")}`}function $E(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function Wr(e,t,n){try{return await De.readFile(e)}catch(r){throw new ce(t,`${n} not found: ${e}`,{cause:r})}}async function Wa(e){try{return await De.readFile(e)}catch(t){if(qr(t))return null;throw t}}function gf(e,t,n){if(dn(e)!==t)throw new ce(se.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function ot(e){try{return await De.access(e),!0}catch(t){if(qr(t))return!1;throw t}}async function Di(e){try{await De.rm(e,{force:!0,recursive:!0})}catch{}}async function Ha(e){try{let t=await De.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function Bi(e){try{return await De.readdir(e)}catch(t){if(qr(t))return[];throw t}}function VE(e){if(typeof e!="string"||e.trim().length===0)throw new ce(se.INVALID_ROOT,"history store rootDir must be a non-empty string");return Be.resolve(e)}function Za(e){return Be.join(e,EE)}function $a(e){return Be.join(e,vE)}function KE(e){return Be.join(e,kE)}function hf(e){return Be.join(e,IE)}async function qd(e){try{let t=await De.readFile(hf(e),"utf8"),n=Yr(t,"document version");if(!Rt(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new ce(se.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(qr(t))return 0;throw t}}async function Ti(e){let t=await Wr(e,se.RECOVERY_PENDING,"transaction journal"),n=Yr(Buffer.from(t).toString("utf8"),"transaction journal");return yf(n),n}function yf(e){if(!Rt(e)||e.schemaVersion!==SE||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!RE(e.historyTransition)||!Array.isArray(e.files))throw new ce(se.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!Rt(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!ut(t.preDigest)||t.postDigest!==null&&!ut(t.postDigest))throw new ce(se.INVALID_SCHEMA,"transaction journal file digest is invalid")}function UE(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function Zr(e){return Be.join(e,"entries")}function Qr(e){return Be.join(e,"blobs")}function Hr(e){return Be.join(e,"tmp")}function Qa(e){return Be.join(Hr(e),"stages")}function qa(e,t){return Be.join(Qa(e),`${t}.json`)}function ec(e,t){return Be.join(Zr(e),`${Sf(t)}.json`)}function tc(e,t){return Be.join(Qr(e),Sf(t))}function nc(e,t){return Be.join(Zr(e),`${t}.json`)}function rc(e,t){return Be.join(Qr(e),t)}async function JE(e,t){return bf(ec(e,t),nc(e,t))}async function xf(e,t){return bf(tc(e,t),rc(e,t))}async function bf(e,t){return await ot(e)?e:await ot(t)?t:e}function Sf(e){return e.slice(7)}function ef(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return ut(t)?t:null}function Rt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qr(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function XE(e){return{maxEntries:e?.maxEntries??Fi.maxEntries,maxSessionBytes:e?.maxSessionBytes??Fi.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??Fi.maxEntryBytes}}async function zE(e){let t=Za(e);await ot(t)||await uf(e,[],-1)}var HE={affectedCompositions:[]};function Cf(e){let t=null,n=new WeakMap;async function r(){return t??=GE(e),t}async function o(i){if(!i)return null;let s=oc(i);return s?YE(e,s):i}return{async prepareAppend(i){let s=await cr(e),a=await e.stageAppend(kf(i),{durableManifest:!1}),c;try{c=await e.previewStagedAppend(a.entryId,s.digest)}catch(u){throw await e.discardStage(a.stageId),u}let l={kind:"append",entry:i,historyTransition:c};return n.set(l,{expectedDigest:s.digest,stageId:a.stageId,entryId:a.entryId}),l},async prepareUndo(){let i=await r(),s=await o(i.undo.at(-1));if(!s?.historyId)return null;let a=await cr(e),c=a.entryIds.indexOf(s.historyId);if(c<0)throw new Error("undo entry is missing from index");if(c!==a.cursor)throw new Error("undo state changed before prepare");let l=c-1,u=await e.previewCursor(l,a.digest),d={kind:"undo",entry:s,historyTransition:u};return n.set(d,{expectedDigest:a.digest,cursor:l}),d},async prepareRedo(){let i=await r(),s=await o(i.redo.at(-1));if(!s?.historyId)return null;let a=await cr(e),c=a.entryIds.indexOf(s.historyId);if(c<0)throw new Error("redo entry is missing from index");if(c!==a.cursor+1)throw new Error("redo state changed before prepare");let l=c,u=await e.previewCursor(l,a.digest),d={kind:"redo",entry:s,historyTransition:u};return n.set(d,{expectedDigest:a.digest,cursor:l}),d},async publishPrepared(i){let s=n.get(i);if(!s)throw new Error("history mutation was not prepared");let a=await r();if(i.kind==="append"){if(!s.entryId)throw new Error("staged entry id is missing");let c=await e.publishStagedAppend(s.entryId,s.expectedDigest,s.stageId);Ef(c,i.historyTransition),i.entry.historyId=s.entryId,Object.assign(a,lr(c))}else{if(s.cursor===void 0)throw new Error("prepared cursor is missing");let c=i.kind==="undo"?a.undo:a.redo;if(oc(c.at(-1))!==oc(i.entry))throw new Error("history state changed before publish");let l=await e.setCursor(s.cursor,s.expectedDigest);Ef(l,i.historyTransition),Object.assign(a,lr(l))}n.delete(i)},async discardPrepared(i){let s=n.get(i);if(!s)return;let a=i.historyTransition;if(a){let c=await cr(e);if(c.digest===a.publishedIndexDigest&&c.cursor===a.publishedCursor&&c.currentId===a.publishedCurrentId)throw new Error("cannot discard a history mutation whose index was published")}s.stageId&&await e.discardStage(s.stageId),n.delete(i)},async peekUndo(){return o((await r()).undo.at(-1))},async pushUndo(i){let s=await r(),a=i;if(a.historyId){let u=s.entryIds.indexOf(a.historyId);if(u>=0)try{let d=await e.setCursor(u);Object.assign(s,lr(d));return}catch(d){throw s.redo.push(i),d}}let c=await e.append(kf(i)),l=c.currentId;if(!l)throw new Error("history store did not publish an entry");i.historyId=l,Object.assign(s,lr(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,lr(l))}catch(l){throw s.undo.push(i),l}},async popRedo(){let i=await r(),s=await o(i.redo.at(-1));return i.redo.pop(),s},async clearRedo(){(await r()).redo.length=0},async getStatus(){let i=await e.readStatus();return{canUndo:i.canUndo,canRedo:i.canRedo,undoDepth:i.undoDepth,redoDepth:i.redoDepth,recoveryRequired:i.recoveryRequired}},async markRecoveryRequired(i){await e.markRecoveryRequired(i)}}}function Ef(e,t){if(!t)throw new Error("durable history transition is missing");if(e.digest!==t.publishedIndexDigest||e.cursor!==t.publishedCursor||e.currentId!==t.publishedCurrentId)throw new Error("durable history published an unexpected index state")}function oc(e){return typeof e=="string"?e:e?.historyId}async function GE(e){let t=await cr(e);return lr(t)}function lr(e){return{undo:[...e.undoIds].reverse(),redo:[...e.redoIds].reverse(),entryIds:[...e.entryIds],cursor:e.cursor}}async function YE(e,t){let n=await e.readEntry(t),r=ZE(n),o=r.provenance??HE;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 vf(e,n,r.preSnapshots),postSnapshots:await vf(e,n,r.postSnapshots)}}async function vf(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(ev(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function kf(e){let t=[],n=(i,s)=>i.map((a,c)=>{let l={file:a.file,exists:a.exists!==!1,version:a.version,...a.sha256?{sha256:a.sha256}:{}};if(l.exists){let u=`${s}-${c}`;l.blobName=u,t.push({name:u,data:a.content})}return l}),r=QE(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 ZE(e){if(!wf(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:Rf(t.provenance)}:{},preSnapshots:If(t.preSnapshots,"preSnapshots"),postSnapshots:If(t.postSnapshots,"postSnapshots")}}function QE(e){if(e.provenance!==void 0)return Rf(e.provenance);if(e.composition)return{initiatingComposition:e.composition,affectedCompositions:[]}}function Rf(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 If(e,t){return e.map((n,r)=>{if(!wf(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&&!qE(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 qE(e){return/^sha256:[0-9a-f]{64}$/.test(e)}function ev(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function wf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{randomBytes as gv}from"node:crypto";import Ki from"node:path";import{parse as Df}from"@babel/parser";import hv from"@babel/traverse";import*as Bf from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as sc,PageResourceArtifactSchema as yv,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as xv,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as bv,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as Sv,parseComponentI18nResourcesJson as Ev}from"@vcp-dev/contracts";var Pf=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,Af=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,tv=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,nv=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,rv=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,ov=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,iv=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,sv=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,av=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,cv=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,lv=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,uv=/\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,dv=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,fv=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function eo(e,t){let n=Vi([...bt(e,tv),...bt(e,nv),...bt(e,rv),...bt(e,t.includeRgbBackgroundImage?ov:iv),...t.includeExtendedColorFunctions?[...bt(e,sv),...bt(e,av)]:[]]),r=Vi([...bt(e,cv),...bt(e,lv)]).filter(o=>t.colorMixPolicy==="always"||Pf.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...bt(e,uv).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...bt(e,fv).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:Vi(bt(e,Af)),hardCodedSurfaceOccurrences:mv(e),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?Vi(bt(e,dv)):[]}}function bt(e,t){return e.match(new RegExp(t.source,t.flags))??[]}var Nf=160,pv=/((?:[a-z][a-z0-9-]*(?:\[[^\]]*\])?:)+)$/;function mv(e){let t=new RegExp(Af.source,"g"),n=[0];for(let s=0;s<e.length;s+=1)e[s]===`
5
- `&&n.push(s+1);let r=s=>{let a=0,c=n.length-1;for(;a<c;){let l=Math.ceil((a+c)/2);(n[l]??0)<=s?a=l:c=l-1}return a},o=[],i;for(;(i=t.exec(e))!==null;){let s=i[0],a=s.endsWith("/")?s.slice(0,-1):s,c=/^\/(\d+)/.exec(e.slice(i.index+a.length)),l=e.slice(Math.max(0,i.index-64),i.index),u=pv.exec(l),d=r(i.index),f=e.indexOf(`
6
- `,i.index),g=e.slice(n[d]??0,f===-1?void 0:f).trim();o.push({token:a,variant:u?.[1]??"",alpha:c?Number(c[1]):null,line:d+1,snippet:g.length>Nf?`${g.slice(0,Nf-1)}\u2026`:g})}return o}function Vi(e){return[...new Set(e)]}var ac="{{$INSTANCE}}",vv=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,kv=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,cc="components/site/generated",Iv=/\.(?:tsx?|json)$/,Cv=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,Rv=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],wv=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),ic=hv,Nv=typeof ic=="function"?ic:ic.default;async function lc(e){let t=yv.safeParse(e.artifact);if(!t.success)return Me("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>gv(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=Dv(r());if(!i)return Me("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 v of n.pages){let C=v.final_route.slice(1);a.set(v.template_page_id,v.final_route),c.set(v.template_page_id,v.title),l.push({template_page_id:v.template_page_id,title:v.title,final_route:v.final_route,route_file_path:`app/${C}/page.tsx`})}let u=[],d=new Set,f=new Set,g=new Map,m=new Map,h=[],y=new Set(n.pages.flatMap(v=>v.components.map(C=>C.component_id)));for(let v of n.components){if(!y.has(v.component_id))continue;let C=Tf({materialization:v.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c});if(!C.ok)return C;for(let P of C.files){let F=_f(P,d,u);if(F)return F}f.add(C.entry),m.set(C.entry,C.entryExport),g.set(v.component_id,C.entry)}for(let[v,C]of n.pages.entries()){let P=l[v],F=Tf({materialization:C.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c,pageEntryTarget:P.route_file_path,pageTitle:P.title});if(!F.ok)return F;for(let R of F.files){let N=_f(R,d,u);if(N)return N}f.add(F.entry),m.set(F.entry,F.entryExport),h.push({entry:F.entry,declaredComponentIds:new Set(C.components.map(R=>R.component_id))})}let x=Av(u,f,s,g,h,m);if(!x.ok)return x;for(let v of u)if(await e.exists(v.file))return!v.file.startsWith("app/")&&o>1?lc({...e,randomHex:r,maxAttempts:o-1}):{ok:!1,code:"MATERIALIZATION_CONFLICT",message:`Page resource create-only target already exists: ${v.file}`,path:v.file};let E=Tv(u);return E||(u.sort((v,C)=>v.file.localeCompare(C.file)),{ok:!0,packageInstanceId:s,pages:l,files:u})}function Tf(e){let t=e.materialization.entry.pathTemplate,n=[];for(let o of e.materialization.files){let i=o.pathTemplate===t,s=i&&e.pageEntryTarget?e.pageEntryTarget:Ff(o.pathTemplate,e.packageInstanceId);if(!s)return Me("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=Pv(o.content,e.packageInstanceId,e.routeByPage,e.titleByPage);if(!a.ok)return a;let c=i&&e.pageTitle!==void 0?_v(a.data,e.pageTitle,s):a;if(!c.ok)return c;n.push({operation:"create-only",file:s,content:c.data})}let r=e.pageEntryTarget??Ff(t,e.packageInstanceId);return!r||!n.some(o=>o.file===r)?Me("Materialization entry must match one controlled source file.",t):{ok:!0,files:n,entry:r,entryExport:e.materialization.entry.export}}function Pv(e,t,n,r){let o,i=e.replace(vv,(c,l)=>{let u=n.get(l);return u||(o=l,c)});if(o)return Me(`Page route placeholder references unknown template page: ${o}`);let s=i.replace(kv,(c,l)=>{let u=r.get(l);return u?JSON.stringify(u):(o=l,c)});if(o)return Me(`Page title placeholder references unknown template page: ${o}`);let a=s.replaceAll(ac,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?Me("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function Ff(e,t){let n=`${cc}/${t}`;if(e.split(ac).length>2)return null;let o=e.replace(ac,t),i=`${cc}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=Ki.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!Iv.test(a)||Cv.test(a)?null:a}function _f(e,t,n){return t.has(e.file)?Me(`Page resource materializations resolve duplicate target: ${e.file}`,e.file):(t.add(e.file),n.push(e),null)}function Av(e,t,n,r,o,i){let s=new Set(e.map(g=>g.file)),a=`${cc}/${n}`,c=new Map(e.map(g=>[g.file,new Set])),l=new Map;for(let g of e){if(g.file.endsWith(".json")){try{JSON.parse(g.content)}catch{return Me("Materialization JSON file must contain valid JSON.",g.file)}if(g.file.endsWith(sc)&&!Ev(g.content).success)return Me("Materialization component i18n resources are invalid.",g.file);continue}try{let h=Df(g.content,{sourceType:"module",plugins:["jsx","typescript"]});l.set(g.file,h);for(let x of h.program.body)if((x.type==="ImportDeclaration"||x.type==="ExportAllDeclaration"||x.type==="ExportNamedDeclaration"&&x.source)&&x.source){let E=x.source.value,v=Ov(g.file,E,s,a);if(!v.allowed)return Me(`Materialization import is outside the controlled package: ${E}`,g.file);v.internalPath&&c.get(g.file).add(v.internalPath)}let y;if(Nv(h,{Identifier(x){x.isReferencedIdentifier()&&wv.has(x.node.name)&&(y??=x.node.name,x.stop())},JSXAttribute(x){x.node.name.type==="JSXIdentifier"&&x.node.name.name==="style"&&(y??="inline style",x.stop())},JSXOpeningElement(x){x.node.name.type==="JSXIdentifier"&&x.node.name.name.toLowerCase()==="style"&&(y??="style element",x.stop())}}),y)return Me(`Materialization source uses forbidden capability: ${y}`,g.file)}catch{return Me("Materialization source must parse as TS/TSX.",g.file)}let m=eo(g.content,{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0});if(m.hardCodedSurfaceHits.length>0||m.rawColorHits.length>0||m.privateTokenHits.length>0)return Me("Materialization source violates the public theme token policy.",g.file)}if([...t].some(g=>!s.has(g)))return Me("Materialization entry is outside the controlled package.");for(let g of t)if(g.endsWith(".json"))return Me("Materialization JSON files cannot be package entries.");for(let[g,m]of i){let h=l.get(g);if(!h||!Fv(h,m))return Me("Materialization entry does not declare its contracted export.",g)}let u=new Map([...r].map(([g,m])=>[m,g]));for(let g of o){let m=Lf(g.entry,c);for(let h of g.declaredComponentIds){let y=r.get(h);if(!y||!m.has(y))return Me(`Page entry does not reach declared component: ${h}`,g.entry)}for(let h of m){let y=u.get(h);if(y&&!g.declaredComponentIds.has(y))return Me(`Page entry imports undeclared component: ${y}`,g.entry)}}let d=new Set;for(let g of t)for(let m of Lf(g,c))d.add(m);if(d.size!==e.length)return Me("Every materialization file must be reachable from a package entry.");let f=Lv(e,l,c);return f||{ok:!0}}function Tv(e){if(e.length>xv)return Me("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>bv)return Me("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>Sv?Me("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 _v(e,t,n){let r;try{r=Df(e,{sourceType:"module",sourceFilename:n,plugins:["jsx","typescript"]})}catch{return Me("Page materialization PAGE_SEO must parse as TS/TSX.",n)}for(let o of r.program.body){let i=o.type==="VariableDeclaration"?o:o.type==="ExportNamedDeclaration"&&o.declaration?.type==="VariableDeclaration"?o.declaration:null;if(i)for(let s of i.declarations){if(s.id.type!=="Identifier"||s.id.name!=="PAGE_SEO")continue;let a=Mf(s.init);if(a?.type!=="ObjectExpression")return{ok:!0,data:e};let c=a.properties.find(u=>u.type==="ObjectProperty"&&!u.computed&&Mv(u.key));if(!c||c.type!=="ObjectProperty")return{ok:!0,data:e};let l=Mf(c.value);return l?l.type!=="StringLiteral"&&l.type!=="TemplateLiteral"||l.type==="TemplateLiteral"&&l.expressions.length>0||typeof l.start!="number"||typeof l.end!="number"?{ok:!0,data:e}:{ok:!0,data:e.slice(0,l.start)+JSON.stringify(t)+e.slice(l.end)}:{ok:!0,data:e}}}return{ok:!0,data:e}}function Mf(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&Bf.isExpression(t)?t:null}function Mv(e){return e.type==="Identifier"&&e.name==="title"||e.type==="StringLiteral"&&e.value==="title"}function Ov(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=Of(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:Rv.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=Ki.posix.normalize(Ki.posix.join(Ki.posix.dirname(e),t)),i=Of(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function Of(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 Lv(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(sc))continue;let i=o.file.slice(0,-sc.length),s=[`${i}.tsx`,`${i}.ts`].find(u=>r.has(u));if(!s)return Me("Component i18n resources require a same-name TS/TSX companion.",o.file);let c=t.get(s)?.program.directives.some(u=>u.value.value==="use client"),l=[...n].filter(([,u])=>u.has(o.file));if(!c||l.length!==1||l[0]?.[0]!==s)return Me("Component i18n resources must have exactly one same-name Client Component static importer.",s)}return null}function Lf(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 Dv(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 Me(e,t){return{ok:!1,code:"MATERIALIZATION_REJECTED",message:e,...t?{path:t}:{}}}import{randomBytes as jv}from"node:crypto";import tn from"node:path";import{parse as $v}from"@babel/parser";import Vv from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as Ui,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as jf,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as Kv,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as Uv,SiteEditMaterializationSchema as Jv,parseComponentI18nResourcesJson as Xv}from"@vcp-dev/contracts";var fc="components/site/generated",$f="{{$INSTANCE}}",Ji=5,zv=/^[a-z][a-z0-9-]{0,48}$/,Wv=/^[a-f0-9]{8}$/,Vf=/\.tsx?$/,Hv=/\.json$/,Gv=/\.(?:tsx?|json)$/,Yv=/^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/,Zv=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,Qv=["react","react/","next","next/","lucide-react","react-i18next","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],uc=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),dc=Vv,qv=typeof dc=="function"?dc:dc.default;function ek(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>jf)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=dk(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=Jv.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=ck(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${fc}.`,path:e.generatedRoot}};if(!Wf(r.data.instanceBaseName))return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_INVALID",message:"Static prefab instanceBaseName must contain at least one safe word.",path:r.data.instanceBaseName}};let i=Jf(r.data.files),s=Jf(e.controlledFiles);if(!fk(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>jf)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let a=0;for(let[c,l]of r.data.files.entries()){let u=Buffer.byteLength(l.content,"utf8");if(u>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+=u}return a>Uv?{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 tk(e){let t=ek(e);if(!t.ok)return t;let n=Object.keys(e.manifest.projectDependencies??{}),r=new Set(e.availableHostDependencies??[]),o=n.find(u=>!Yv.test(u)||!r.has(u));if(o)return{ok:!1,error:{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:`Declared project dependency is not available in the target site host: ${o}.`,path:o}};let i=n.flatMap(u=>[u,`${u}/`]),s=[...e.allowedExternalImports??Qv,...i],a=t.data.generatedRoot,c=Wf(e.manifest.instanceBaseName),l=Math.max(1,Math.min(Ji,e.maxAttempts??Ji));for(let u=0;u<l;u+=1){let d=lk(e.instanceNameGenerator?.()??jv(4).toString("hex"));if(!d)return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_INVALID",message:"Static prefab instance suffix must be 8 lowercase hex chars."}};let f=`${c}-${d}`,g=Gf(a,f),m=nk({manifest:e.manifest,generatedRoot:a,instanceName:f,instanceRoot:g,allowedExternalImports:s});if(!m.ok)return m;if(!await rk(e.exists,g,m.data.files))return{ok:!0,data:m.data}}return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:"Unable to allocate a create-only static prefab instance after repeated conflicts."}}}async function zf(e){let t=Math.max(1,Math.min(Ji,e.maxAttempts??Ji));for(let n=0;n<t;n+=1){let r=await tk({...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 nk(e){let t=[],n=new Set;for(let i of e.manifest.files){let s=Kf({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=Kf({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=ok(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 rk(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function Kf(e){if(e.pathTemplate.split($f).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($f,e.instanceName),n=uk(t);return n?Gf(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||!Gv.test(n)||Zv.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 ok(e,t,n,r,o){let i=new Set(e.map(d=>d.path)),s=new Map,a=new Map(e.map(d=>[d.path,new Set])),c=new Map;for(let d of e){if(Hv.test(d.path)){if(d.path.endsWith(Ui)){let m=Xv(d.content);if(!m.success)return On("MATERIALIZATION_DATA_UNSUPPORTED",m.error.message,d.path);c.set(d.path,new Set)}else try{JSON.parse(d.content)}catch{return On("MATERIALIZATION_DATA_UNSUPPORTED","Static prefab JSON file must contain valid JSON.",d.path)}continue}let f;try{f=$v(d.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:d.path}}}let g=eo(d.content,{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0});if(g.hardCodedSurfaceHits.length>0||g.rawColorHits.length>0||g.privateTokenHits.length>0)return{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:d.path}};s.set(d.path,f)}for(let d of e){if(!Vf.test(d.path))continue;let f=s.get(d.path),g=null;if(qv(f,{ImportDeclaration(m){let h=Uf({importer:d.path,source:m.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});if(!h.allowed)g??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab imports must resolve within the controlled instance or match the starter allowlist.",file:d.path},m.stop();else if(h.internalPath&&(a.get(d.path).add(h.internalPath),h.internalPath.endsWith(Ui))){let y=ik({importer:d.path,imported:h.internalPath,source:m.node.source.value,ast:f});y.ok?c.get(h.internalPath).add(d.path):(g??=y.error,m.stop())}},ExportAllDeclaration(m){g??={code:"MATERIALIZATION_ENTRY_INVALID",message:"Static prefab files cannot use export-star declarations.",file:d.path},m.stop()},ExportNamedDeclaration(m){if(m.node.source){let h=Uf({importer:d.path,source:m.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});!h.allowed||!h.internalPath?(g??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab re-exports must resolve within the controlled instance.",file:d.path},m.stop()):a.get(d.path).add(h.internalPath)}},CallExpression(m){if(m.node.callee.type==="Import"){g??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use dynamic import().",file:d.path},m.stop();return}m.node.callee.type==="Identifier"&&m.node.callee.name==="require"&&(g??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use require().",file:d.path},m.stop())},NewExpression(m){m.node.callee.type==="Identifier"&&m.node.callee.name==="Function"&&(g??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot construct functions dynamically.",file:d.path},m.stop())},MetaProperty(m){m.node.meta.type==="Identifier"&&m.node.meta.name==="import"&&(g??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot use import.meta.",file:d.path},m.stop())},MemberExpression(m){let h=Xf(m.node);h&&uc.has(h)&&(g??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h}.`,file:d.path},m.stop())},OptionalMemberExpression(m){let h=Xf(m.node);h&&uc.has(h)&&(g??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h}.`,file:d.path},m.stop())},Identifier(m){m.isReferencedIdentifier()&&uc.has(m.node.name)&&(g??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${m.node.name}.`,file:d.path},m.stop())},JSXAttribute(m){m.node.name.type==="JSXIdentifier"&&m.node.name.name==="style"&&(g??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot use inline style attributes.",file:d.path},m.stop())},JSXOpeningElement(m){m.node.name.type==="JSXIdentifier"&&m.node.name.name.toLowerCase()==="style"&&(g??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot declare style elements.",file:d.path},m.stop())}}),g)return{ok:!1,error:g}}if(!Vf.test(n))return On("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must be a .ts/.tsx source module.",n);let l=s.get(n);if(!l)return On("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",n);if(!sk(l,r))return On("MATERIALIZATION_EXPORT_MISSING","Static prefab entry does not declare the manifest export.",n);for(let[d,f]of c)if(f.size!==1)return On("MATERIALIZATION_IMPORT_FORBIDDEN","Each component .i18n.json file must have exactly one same-name Client Component static importer.",d);return ak(n,a).size!==e.length?On("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",n):{ok:!0,data:{kind:"static-prefab-materialization",instanceName:"",generatedRoot:fc,instanceRoot:"",entry:{path:"",export:{kind:"default"}},files:[]}}}function Uf(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=tn.posix.normalize(tn.posix.join(tn.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 ik(e){let t=tn.posix.dirname(e.importer),n=tn.posix.dirname(e.imported),r=tn.posix.basename(e.importer).replace(/\.tsx?$/,""),o=tn.posix.basename(e.imported).slice(0,-Ui.length),i=`./${r}${Ui}`;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 sk(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 ak(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 On(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function ck(e){let t=Hf(e);return t===fc?t:null}function lk(e){let t=e.trim().toLowerCase();return Wv.test(t)?t:null}function Wf(e){let t=e.trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,49).replace(/-+$/g,"");return zv.test(t)?t:null}function Hf(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=tn.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function uk(e){let t=Hf(e);return!t||t!==e?null:t}function Gf(...e){return tn.posix.join(...e)}function Jf(e){return new Set(e.map(t=>t.pathTemplate))}function dk(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 fk(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Xf(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 wc}from"node:crypto";import Sc from"@babel/traverse";function pc(e){let t=new Map,n=new Map;for(let s of e){if(t.has(s.placementKey))throw new Error(`Duplicate placement key in page composition projection: ${s.placementKey}`);t.set(s.placementKey,s);let a=n.get(s.placementUnitKey)??[];a.push(s),n.set(s.placementUnitKey,a)}let r=new Map,o=new Map,i=new Map;for(let[s,a]of n){let c=Object.freeze([...a]),l=c.find(u=>u.anchorSourceRange!==null&&u.members.length>0)??c.find(u=>u.members.length>0)??c[0];l&&(o.set(s,c),i.set(s,l),r.set(s,Object.freeze({placementUnitKey:s,placementKeys:Object.freeze(c.map(u=>u.placementKey)),sourcePlacementKey:l.placementKey})))}return{placementByKey:t,unitByKey:r,placementsByUnitKey:o,sourcePlacementByUnitKey:i}}import{createHash as pk}from"node:crypto";import Yf from"node:path";import*as tp from"@babel/parser";import mc from"@babel/generator";import*as Je from"@babel/types";var Zf=typeof mc=="function"?mc:mc.default;function hc(e){let t=rp(e);if(t)return{ok:!1,error:t};let n=e.projection,r=bc(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=hk(n,o),s={jsx:`<${e.component.localName} />`},a=mk(e);if(i){let g=gc(e);return g.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:g.locator,sourceHash:g.sourceHash,node:s,placement:o.relation,replaceOriginal:n.container.kind==="starter-placeholder"}}}:g.result}let c=o.containerSourceRange??n.container.sourceRange,l=o.containerSourceHash??(xc(c,n.container.sourceRange)?n.container.sourceHash:null);if(!c||!l)return to("Route page composition does not expose a verifiable container boundary.");let u=ro(c),d=qf(e.source,u,l,"Route page composition container");if(!d.ok)return d.result;let f=o.anchorSourceRange?ro(o.anchorSourceRange):void 0;if(f){if(!o.anchorSourceHash)return to("Route page composition placement does not expose a verifiable anchor boundary.");let g=qf(e.source,f,o.anchorSourceHash,"Route page composition anchor");if(!g.ok)return g.result}return{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:o.placementUnitKey,importStep:a,rewriteStep:{kind:"insert-child",parentLocator:u,node:s,placement:o.relation,...f?{anchorLocator:f}:{}}}}}function mk(e){let t=Sk(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 Xi(e){if(e.locator.root.kind!=="expression"||e.locator.path?.length)return Ln(e.source,"Root expression rewrite requires an exact expression locator.");let t=Fr(e.source,"value");if(!t.ok)return Ln(e.source,t.diagnostic.message);let n=ue(t.ast,e.locator);if(!n.ok)return Ln(e.source,n.diagnostic.message);let r=n.match.path;if(!r.isExpression())return Ln(e.source,"Resolved value locator does not point to an expression.");let o=ur(e.source,r.node.start??null,r.node.end??null);if(!o||o!==e.expectedSourceHash)return Ln(e.source,"Root expression hash no longer matches the current source.");if(e.action.kind==="remove")return r.replaceWith(Je.nullLiteral()),{ok:!0,source:Zf(t.ast,{}).code};let i;try{i=tp.parseExpression(e.action.jsx,{plugins:["jsx","typescript"]})}catch(s){return Ln(e.source,s instanceof Error?s.message:String(s))}return!Je.isJSXElement(i)&&!Je.isJSXFragment(i)?Ln(e.source,"Root expression rewrite requires a JSX insertion expression."):(e.action.kind==="replace"?r.replaceWith(i):r.replaceWith(gk(r.node,i,e.action.placement,e.action.replaceOriginal)),{ok:!0,source:Zf(t.ast,{}).code})}function gk(e,t,n,r){if(Je.isNullLiteral(e)||r)return t;let o=Je.isJSXFragment(e)?[...e.children]:[Je.isJSXElement(e)?e:Je.jsxExpressionContainer(e)],s=n==="before"||n==="prepend"?[t,...o]:[...o,t];return Je.jsxFragment(Je.jsxOpeningFragment(),Je.jsxClosingFragment(),s)}function Ln(e,t){return{ok:!1,source:e,diagnostic:{message:t}}}function yc(e){let t=rp(e);if(t)return{ok:!1,error:t};let n=e.projection,r=op(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(yk(n,o)){let h=gc(e);return h.ok?e.operation==="remove-node"&&!Qf(n,o.placementUnitKey)?to("The last editable page unit cannot be deleted."):e.operation==="move-node"?to("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=ro(o.sourceRange),a=Lt(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?[]:[no(a.diagnostic)]}};if(ur(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=gc(e);return h.ok?Qf(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}}}:to("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||!bk(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=bc(n,e.targetPlacement.placementKey,e.expectedDocumentVersion);if(!l.ok)return{ok:!1,error:{code:l.diagnostic.code==="DOCUMENT_VERSION_STALE"?"VERSION_STALE":"NO_SAFE_PAGE_PLACEMENT",message:l.diagnostic.message,diagnostics:[l.diagnostic]}};let u=l.placement;if(u.placementUnitKey!==e.targetPlacement.placementUnitKey||u.relation!==e.targetPlacement.relation)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Page-unit target placement metadata does not match the cached projection.",diagnostics:[]}};let d=u.containerSourceRange;if(!d||!u.containerSourceHash)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable container boundary.",diagnostics:[]}};let f=ro(d),g=Lt(e.source,f);if(!g.ok||!g.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:g.ok===!1?g.diagnostic.message:"Route page composition target container could not be resolved.",diagnostics:g.ok?[]:[no(g.diagnostic)]}};if(ur(e.source,g.match.node.start??null,g.match.node.end??null)!==u.containerSourceHash)return ep("Route page composition target container hash no longer matches the current source.");if(u.relation==="before"||u.relation==="after"){let h=u.anchorSourceRange,y=u.anchorSourceHash;if(!h||!y)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable anchor boundary.",diagnostics:[]}};let x=ro(h),E=Lt(e.source,x);return!E.ok||!E.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:E.ok===!1?E.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:E.ok?[]:[no(E.diagnostic)]}}:ur(e.source,E.match.node.start??null,E.match.node.end??null)!==y?ep("Route page composition target anchor hash no longer matches the current source."):{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"move-node",locator:s,targetParentLocator:f,anchorLocator:x,placement:u.relation}}}}return{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"move-node",locator:s,targetParentLocator:f,placement:u.relation}}}}function Qf(e,t){for(let n of e.placementUnitByKey.values())if(n.placementUnitKey!==t&&n.members.length>0)return!0;return!1}function hk(e,t){let n=e.placementUnitByKey.get(t.placementUnitKey);return n&&e.container.kind!=="jsx-container"&&xc(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 yk(e,t){return e.container.kind!=="jsx-container"&&xc(t.sourceRange,e.mutationTarget.sourceRange)&&t.sourceHash===e.mutationTarget.sourceHash}function gc(e){let t=e.projection.mutationTarget,n={kind:"value",root:{kind:"expression",sourceRange:t.sourceRange}},r=Lt(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?[]:[no(r.diagnostic)]}}}:ur(e.source,r.match.node.start??null,r.match.node.end??null)!==t.sourceHash?{ok:!1,result:np("Route mutation target hash no longer matches the current source.")}:{ok:!0,locator:n,sourceHash:t.sourceHash}}function qf(e,t,n,r){let o=Lt(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?[]:[no(o.diagnostic)]}}}:ur(e,o.match.node.start??null,o.match.node.end??null)!==n?{ok:!1,result:np(`${r} hash no longer matches the current source.`)}:{ok:!0}}function np(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function to(e){return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:e,diagnostics:[]}}}function ep(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function no(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function rp(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&&!xk(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 xk(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function bk(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function Sk(e,t){let n=Yf.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Yf.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function ro(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function ur(e,t,n){return t==null||n==null?null:`sha256:${pk("sha256").update(e.slice(t,n)).digest("hex")}`}function xc(e,t){return e===null||t===null?e===t:e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}var Ek=typeof Sc=="function"?Sc:Sc.default;function cp(e){if(!e.ast)return wt(e,[Ke("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=Pk(e.ast);if(!t)return wt(e,[Ke("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=Tk(t);if(!n.ok)return wt(e,[n.diagnostic]);let r=n.expression;if(r.isIdentifier()){let o=_k(r,t);if(o.status==="resolved")r=o.expression;else if(o.status==="invalid")return wt(e,[Ke("UNSUPPORTED_PAGE_SHAPE","Route default export local binding is not a supported JSX root")])}if(Ok(r,t))return wt(e,[Ke("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(r.isNullLiteral())return vc(e,t,"virtual-route-root",r);if(Mk(r)){let o=jk({input:e,source:e.source,expression:r});return Ec(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"},r)}if(r.isConditionalExpression())return wt(e,[Ke("UNSUPPORTED_PAGE_SHAPE","Route conditional root contains an unsupported branch shape",{reason:"ambiguous-placement"})]);if(r.isJSXElement()&&!Le(r)&&!fn(r)){let o=Cc(r),i=ap({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[o]});return Ec(e,t,i,{kind:"virtual-route-root",sourceKind:"jsx-element"},r)}if(r.isJSXElement()||r.isJSXFragment()){let o=Dk(r);if(!o.ok)return wt(e,[o.diagnostic]);let i=dr(o.path);if(i.unsupported)return wt(e,[Ke("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);if(Lk(e.source,r,i.members))return vc(e,t,"starter-placeholder",r);let s=r.isJSXFragment()||Le(r);if(i.members.length===0&&s)return vc(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=ap({input:e,containerKind:a,sourceKind:c,source:e.source,containerPath:o.path,members:i.members});return Ec(e,t,l,{kind:a,sourceKind:c},r)}return wt(e,[Ke("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")])}function bc(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Ke("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:Ke("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function op(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Ke("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:Ke("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function lp(e){return e.ok?vk(e.projection):kk(e.projection)}function vk(e){let t=new Map,n=[];for(let l of e.placements)l.members.length===0&&e.placements.length>1||l.members.length>0&&!l.anchorSourceRange||t.has(l.placementUnitKey)||t.set(l.placementUnitKey,l);let r=new Map,o=new Map;for(let[l,u]of t){let d=u.members.flatMap((h,y)=>up(e,u,h,y,e.container.placementKey)),f=d.filter(({member:h})=>h.isBusinessMember).map(({sourceMember:h})=>Ck(l,h,u.independent)),g=d.length>0?d:[{sourceMember:{key:`source:${l}:empty`,kind:e.container.kind==="starter-placeholder"?"starter-placeholder":"null-return",containerKey:e.container.placementKey,label:"empty-page",sourceFile:e.entryFile,isAtomic:!0},member:null}];r.set(l,g.map(({sourceMember:h})=>h)),o.set(l,f);let m=g[0]?.sourceMember.key??l;n.push({key:l,containerKey:m,businessMemberKeys:f.map(h=>h.key),isMultiMember:u.memberCount>1})}let i=[...r.values()].flat(),s=[...o.values()].flat(),a=i[0]?.key??null,c=e.placements.map(l=>({kind:"page-composition",placementKey:l.placementKey,documentVersion:e.documentVersion,composition:e.composition,placementUnitKey:l.placementUnitKey,relation:l.relation}));return{status:"supported",version:e.version,composition:e.composition,container:Ik(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function kk(e){let t=e.diagnostics.map(Rk);return{status:"unsupported",version:e.version,composition:e.composition,reason:wk(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 up(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)=>up(e,t,a,c,i))]}function Ck(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function Rk(e){return{code:Nk(e),message:e.message}}function wk(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 Nk(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 Pk(e){let t=null;return Ek(e,{ExportDefaultDeclaration(n){let r=n.get("declaration");if(r.isArrowFunctionExpression()||r.isFunctionDeclaration()||r.isFunctionExpression()){t=r,n.stop();return}if(!r.isIdentifier())return;let o=n.scope.getBinding(r.node.name);if(!o)return;let i=Ak(o.path);i&&(t=i,n.stop())}}),t}function Ak(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 Tk(e){let t=e.get("body");if(!t.isBlockStatement()){let s=io(t);return s?{ok:!0,expression:s}:{ok:!1,diagnostic:Ke("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:Ke("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")};if(!r.isReturnStatement())return{ok:!1,diagnostic:Ke("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:Ke("UNSUPPORTED_PAGE_SHAPE","Route guard return shape is not statically safe",{reason:"guard-shape"})};continue}if(dp(s)||fp(s))return{ok:!1,diagnostic:Ke("UNSUPPORTED_PAGE_SHAPE","Route default export contains unsupported control flow before the terminal return",{reason:"control-flow-return"})}}let o=r.get("argument"),i=io(o);return i?{ok:!0,expression:i}:{ok:!1,diagnostic:Ke("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(dp(o)||fp(o))return null;return r}function dp(e){return e.isForStatement()||e.isForInStatement()||e.isForOfStatement()||e.isWhileStatement()||e.isDoWhileStatement()||e.isSwitchStatement()||e.isTryStatement()||e.isWithStatement()}function fp(e){let t=!1;return e.traverse({Function(n){n.skip()},ReturnStatement(){t=!0}}),t}function _k(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=io(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()?ip(io(e.get("consequent")))&&ip(io(e.get("alternate"))):!1}function ip(e){return!!(e&&(e.isJSXElement()||e.isJSXFragment()||e.isNullLiteral()))}function io(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 Ok(e,t){if(e.isIdentifier())return sp(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return sp(n.node.name,t)}return!1}function sp(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 Lk(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&Ic(t)}function Ic(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(!Ic(t))return!1;continue}if(t.isJSXElement()&&!Ic(t))return!1}return!0}function Dk(e){let t=e;if(e.isJSXFragment()||Le(e)){let r=oo(e),o=r[0];if(r.length===1&&o?.isJSXElement()&&fn(o))t=o;else return{ok:!0,path:t}}for(;t.isJSXElement()&&fn(t);){let r=oo(t);if(r.length!==1)return{ok:!0,path:t};let o=r[0];if(!o?.isJSXElement()||!fn(o))return{ok:!0,path:t};if(oo(o).length<=1)return{ok:!0,path:t};t=o}return{ok:!0,path:t}}function oo(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(...oo(n));continue}n.isJSXElement()&&(Le(n)?t.push(...oo(n)):t.push(n))}return t}function dr(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:Rc(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:St(r.node.loc),businessMemberCount:0,parentSourceRange:St(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=dr(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=fn(o)?dr(o):null;n||=i?.unsupported??!1,t.push({...Cc(o,i?.members),sourceRange:St(r.node.loc),parentSourceRange:St(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:Rc(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:St(r.node.loc),businessMemberCount:1,parentSourceRange:St(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&Le(r)){let o=dr(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=fn(r)?dr(r):null;n||=o?.unsupported??!1,t.push({...Cc(r,o?.members),parentSourceRange:St(e.node.loc)})}}return{members:t,unsupported:n}}function Cc(e,t){let n=e.isJSXElement()&&fn(e)?t??dr(e).members:[],r=e.isJSXElement()&&!fn(e)&&!Le(e);return{memberKey:Rc(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:St(e.node.loc),businessMemberCount:r?1:pp(n),parentSourceRange:St(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:Bk(e)}}function fn(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 pp(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function zi(e){return e.length===0?0:Math.max(1,pp(e))}function ap(e){let t=St(e.containerPath.node.loc),n=Nc(e.source,e.containerPath.node.start,e.containerPath.node.end),r=Et(e.input,e.containerKind,e.sourceKind,t),o=Et(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:zi(e.members)<=1,memberCount:zi(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function jk(e){let t=St(e.expression.node.loc),n=Nc(e.source,e.expression.node.start,e.expression.node.end),r=Et(e.input,"virtual-route-root","atomic-expression",t),o=Et(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:Et(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 mp(e,t){let n=St(t.node.loc),r=Nc(e.source,t.node.start,t.node.end);return!n||!r?null:{kind:"expression",documentVersion:e.version,sourceRange:n,sourceHash:r}}function Ec(e,t,n,r,o){let i=mp(e,o);if(!i)return wt(e,[Ke("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let s=n.containerSourceRange??n.sourceRange,a=$k(e,n,s),c=pc(a),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:hp(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 $k(e,t,n){if(t.members.length===0)return[t];let r=[],o=(l,u,d,f,g,m,h=n)=>({...t,placementKey:u,placementUnitKey:d,containerKey:t.placementKey,independent:zi(m)<=1,memberCount:zi(m),sourceRange:f,sourceHash:f?kc(e.source,f):null,relation:l,containerSourceRange:h,containerSourceHash:h?kc(e.source,h):null,anchorSourceRange:g,anchorSourceHash:g?kc(e.source,g):null,members:m}),i=t.placementKey,s=t.members.map(l=>Et(e,i,"placement-unit",l.sourceRange)),a=s[0]??t.placementUnitKey,c=s.at(-1)??t.placementUnitKey;r.push(o("prepend",Et(e,i,"prepend",n),a,n,null,[]));for(let l of t.members){let u=l.parentSourceRange??n,d=Et(e,i,"placement-unit",l.sourceRange);r.push(o("before",Et(e,d,"before",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u)),r.push(o("after",Et(e,d,"after",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u))}return r.push(o("append",i,c,n,null,[])),r}function vc(e,t,n,r){let o=mp(e,r);if(!o)return wt(e,[Ke("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let i=Et(e,n,"empty-container",void 0),s=Et(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=pc([a]),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:hp(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 wt(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 Ke(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function Et(e,t,n,r){return gp([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function Rc(e,t,n){return gp(["member",e,String(t??-1),String(n??-1)])}function gp(e){return`pc_${wc("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function Nc(e,t,n){return t==null||n==null?null:`sha256:${wc("sha256").update(e.slice(t,n)).digest("hex")}`}function kc(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:${wc("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function St(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function hp(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 Qk}from"@vcp-dev/contracts";import w_ from"node:fs";import P_ from"node:path";var Kk=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function so(e){let t=e.map(r=>Zk(r.path)),n=Uk(t);return n?t.filter(r=>Xk(n,r)).map(r=>({routeId:zk(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function Pc(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=Yk(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function Uk(e){return e.some(r=>r.startsWith("app/")&&!Jk(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function Jk(e){return/^(?:src\/)?app\/(?:_vcp|\.vcp)/.test(e)}function Xk(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 zk(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(Hk).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function Wk(e){return e.startsWith("(")&&e.endsWith(")")}function Hk(e){return!e||e.startsWith("@")||e.startsWith("_")||Wk(e)?null:Gk(e)}function Gk(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function Yk(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function Zk(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var ao=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function st(e,t={}){throw new ao("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Invalid page-template source (${e}): ${t.path??t.routeId??t.templateId??""}`,{reason:e,...t})}function Ac(e){return Qk.safeParse(e).success||st("invalid-template-id",{templateId:e}),Buffer.from(e,"utf8").toString("base64url")}function yp(e){/^[A-Za-z0-9_-]{1,255}$/.test(e)||st("invalid-template-key",{path:e});let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.from(e,"base64url"))}catch{return st("invalid-template-key",{path:e})}return Ac(t)!==e&&st("noncanonical-template-key",{path:e}),t}function qk(e){let t=Pc(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("(")||eI(r)&&!xp(r)))&&st("invalid-public-route",{routeId:e}),t}function eI(e){return e.includes("[")||e.includes("]")}function xp(e){return/^\[\[\.\.\.[^\[\]]+\]\]$|^\[[^\[\]]+\]$/.test(e)}function bp(e){return e.some(xp)}function Sp(e,t,n="app"){n!=="app"&&n!=="src/app"&&st("invalid-app-root");let r=qk(e),o=Ac(t),i=bp(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))&&st("path-too-long",{path:a}),{appRoot:n,routeRoot:s,templateKey:o,templateEntryFile:a}}function Ep(e){return/^(?:src\/)?app\/\.vcp\/page-templates\//.test(e)}function vp(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===".")&&st("invalid-file-path",{path:i}),n.has(i)&&st("duplicate-file-path",{path:i}),n.set(i,o)}return n}function Hi(e){let t=vp(e.files),n=so([...t.keys()].map(i=>({path:i}))),r=new Map;for(let i of n){if(r.has(i.routeId))throw new ao("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(!Ep(i))continue;let s=/^(app|src\/app)\/\.vcp\/page-templates\/(.+)\/page\.tsx$/.exec(i);s||st("candidate-must-be-single-page",{path:i});let a=s[1],c=s[2].split("/"),l=bp(c),u=l?c[0]:c.pop(),d=l?c.slice(1):c,f=yp(u),g=d.length?`/${d.join("/")}`:"/";Sp(g,f,a).templateEntryFile!==i&&st("candidate-path-mismatch",{path:i,routeId:g});let h=r.get(g);(!h||!h.startsWith(`${a}/`))&&st("canonical-entry-missing",{path:i,routeId:g}),o.push({routeId:g,templateId:f,entryFile:i,canonicalEntryFile:h,appRoot:a})}return o.sort((i,s)=>Wi(i.routeId,s.routeId)||Wi(i.templateId,s.templateId))}function kp(e){let t=vp(e.files),n=Hi({files:t}),r=so([...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)=>Wi(o.context.routeId,i.context.routeId)||(o.context.effectiveTemplateId===void 0?-1:i.context.effectiveTemplateId===void 0?1:Wi(o.context.effectiveTemplateId,i.context.effectiveTemplateId)))}function tI(e){let t=Pc(e.selector.routeId),n=kp({files:e.files}),r=n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===void 0);(!r||r.entryFile!==e.canonicalEntryFile)&&st("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||st("template-selection-not-found",{routeId:t,templateId:e.selector.templateId}),{...o,mode:e.selector.templateId===void 0?"direct":"candidate",effectiveEntryFile:o.entryFile}}function Wi(e,t){return e<t?-1:e>t?1:0}import{HOME_PAGE_URL_PATH as mI}from"@vcp-dev/contracts";import{parse as TM}from"@babel/parser";import{parse as B_}from"@babel/parser";import{FormBlockIdSchema as $_,FormSpecV1Schema as V_}from"@vcp-dev/contracts";var co="components/site/generated/forms",K_=`${co}/vcp-form-runtime.tsx`,Gi="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",U_=new RegExp(`^${co}/form-(${Gi})\\.spec\\.ts$`),J_=new RegExp(`^${co}/form-(${Gi})\\.tsx$`),X_=new RegExp(`^@/${co}/form-(${Gi})$`),z_=new RegExp(`(?:^|/)${co}/form-(${Gi})(?:\\.tsx?)?$`);var W_=Symbol("invalid-literal");import{createHash as Y_}from"node:crypto";import{posix as Q_}from"node:path";import{parse as eM}from"@babel/parser";import{FormSpecV1Schema as nM}from"@vcp-dev/contracts";var rM=Symbol("dynamic");import{parse as nI}from"@babel/parser";function Yi(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.type=="string"):[]}var rI=/^(?:src\/)?app\/(.*)page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function Ip(e){let t=rI.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 oI(e){let t=e;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Cp(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function iI(e){let t=e;for(;t&&(t.type==="TSAsExpression"||t.type==="TSSatisfiesExpression"||t.type==="ParenthesizedExpression");)t=t.expression??null;return t}function Tc(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(Tc);if(t?.type==="ObjectExpression"){let n={};for(let r of Yi(t.properties)){if(r.type!=="ObjectProperty"||r.computed)throw new Error("dynamic object property");let o=Cp(r.key);if(!o)throw new Error("unsupported object key");n[o]=Tc(r.value)}return n}throw new Error(`unsupported static value: ${t?.type??"unknown"}`)}function Fc(e,t){let n=[],r=Ip(t);if(r===null)return{found:!1,seo:null,diagnostics:n};let o;try{o=nI(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 Yi(o.program.body)){let u=l.type==="ExportNamedDeclaration"?l.declaration:l;if(u?.type==="VariableDeclaration")for(let d of Yi(u.declarations)){let f=d.id;f?.type==="Identifier"&&f.name==="PAGE_SEO"&&(i=d.init)}}if(i==null)return{found:!1,seo:null,diagnostics:n};let s=iI(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 Yi(s.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=Cp(l.key);if(!(u!=="path"&&u!=="title"&&u!=="description"&&u!=="keywords"&&u!=="meta_tags_json"&&u!=="schema_json"&&u!=="breadcrumbs_json")){if(u==="path"||u==="title"||u==="description"||u==="keywords"){let d=oI(l.value);if(d===void 0){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} is not a static string; skipped`});continue}a[u]=d;continue}try{let d=Tc(l.value);u==="meta_tags_json"&&d!==null&&typeof d=="object"&&!Array.isArray(d)?a.meta_tags_json=d:u==="schema_json"&&d!==null&&typeof d=="object"?a.schema_json=d:u==="breadcrumbs_json"&&Array.isArray(d)?a.breadcrumbs_json=d:n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} has unsupported static shape; skipped`})}catch(d){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} is not a static JSON-like value; skipped: ${d instanceof Error?d.message:String(d)}`})}}}let c=r;return a.path!==void 0&&(a.path!==r&&n.push({code:"page-seo.path-mismatch",message:`PAGE_SEO.path "${a.path}" != derived "${r}"; using PAGE_SEO.path`}),c=a.path),{found:!0,seo:{path:c,...a.title!==void 0?{title:a.title}:{},...a.description!==void 0?{description:a.description}:{},...a.keywords!==void 0?{keywords:a.keywords}:{},...a.meta_tags_json!==void 0?{meta_tags_json:a.meta_tags_json}:{},...a.schema_json!==void 0?{schema_json:a.schema_json}:{},...a.breadcrumbs_json!==void 0?{breadcrumbs_json:a.breadcrumbs_json}:{}},diagnostics:n}}import{parse as sI}from"@babel/parser";var Rp=["page","anchor","external","email","phone","group","file"],aI=["link","cta"],Np=["description","badge","iconKey"],_c=["label","targetType","href","role","openInNewTab","nofollow","children",...Np],cI=new Set(_c);function uo(e){return Array.isArray(e)?e:[]}function lo(e){let t=e;return t?.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function lI(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function wp(e){let t=e;return t?.type==="BooleanLiteral"&&typeof t.value=="boolean"?t.value:void 0}function Mc(e){let t=[],n;try{n=sI(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 uo(n.program.body)){let s=i.type==="ExportNamedDeclaration"?i.declaration:i;if(s?.type==="VariableDeclaration")for(let a of uo(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 uo(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 uo(e.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=lI(l.key);u&&(r[u]=l.value)}let o=lo(r.label),i=lo(r.targetType);if(!o)return n.push({severity:"fatal",path:`${t}.label`,message:"label must be a static string"}),null;if(!i||!Rp.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${Rp.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 Np){if(r[l]===void 0)continue;let u=lo(r[l]);u!==void 0?s[l]=u:n.push({severity:"warning",path:`${t}.${l}`,message:`${l} ignored: not a static string`})}r.icon!==void 0&&n.push({severity:"warning",path:`${t}.icon`,message:"icon component ref ignored; use static iconKey"});for(let l of Object.keys(r))cI.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 ${_c.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=[];uo(r.children.elements).forEach((u,d)=>{let f=Pp(u,`${t}.children[${d}]`,n);f&&l.push(f)}),s.children=l}if(i==="group")return s.children?s:(n.push({severity:"fatal",path:`${t}.children`,message:"group item requires children"}),null);let a=lo(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=lo(r.role);if(c!==void 0&&(aI.includes(c)?s.role=c:n.push({severity:"warning",path:`${t}.role`,message:"role ignored: not link/cta"})),r.openInNewTab!==void 0){let l=wp(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=wp(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 uI}from"@babel/parser";function fo(e){return Array.isArray(e)?e:[]}function Ap(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function dI(e){let t;try{t=uI(e,{sourceType:"module",plugins:["typescript","jsx"],tokens:!0})}catch{return{status:"unsupported"}}let n=[];for(let o of fo(t.program.body)){let i=o.type==="ExportNamedDeclaration"?o.declaration:o;if(i?.type==="VariableDeclaration")for(let s of fo(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=Ap(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 Oc(e,t){let n=Tp(t);if(!n)return{status:"unsupported",source:e};let r=dI(e);if(r.status!=="ok")return{status:r.status,source:e};let o=r.array;if(Mc(e).diagnostics.some(({severity:l})=>l==="fatal"))return{status:"unsupported",source:e};let s=[],a=l=>{let u=fo(l.elements);for(let[d,f]of u.entries()){if(pI(f,n)){let m=u[d+1],h=u[d-1],y=f.start,x=f.end;if(typeof y!="number"||typeof x!="number")continue;if(m&&typeof m.start=="number")s.push({start:y,end:m.start});else if(h&&typeof h.end=="number")s.push({start:h.end,end:x});else{let E=/^\s*,/.exec(e.slice(x));s.push({start:y,end:E?x+E[0].length:x})}continue}let g=fI(f);g&&a(g)}};if(a(o),s.length===0)return{status:"not_found",source:e};let c=e;for(let l of s.sort((u,d)=>d.start-u.start))c=c.slice(0,l.start)+c.slice(l.end);return{status:"removed",source:c,removedCount:s.length}}function fI(e){if(e.type==="ObjectExpression")for(let t of fo(e.properties)){if(t.type!=="ObjectProperty")continue;let n=t.key;if((n?.name??n?.value)==="children")return Ap(t.value)}}function Tp(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function pI(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of fo(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"&&Tp(n??"")===t}import{estimateNavLabelWidth as pM}from"@vcp-dev/contracts";import{parse as hM}from"@babel/parser";var gI="components/site/generated/",po=[".tsx",".ts",".jsx",".js"];function Fp(e){if(e.expectedUrlPath===mI)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set(so(Object.keys(e.files).map(h=>({path:h}))).map(h=>h.entryFile)),n=Object.entries(e.files).filter(([h,y])=>{let x=h.replace(/\\/g,"/");if(!t.has(x))return!1;let E=Fc(y,x);return E.found&&E.seo?.path===e.expectedUrlPath});if(n.length===0)return{ok:!1,code:"ROUTE_NOT_FOUND",message:"No route uniquely matches the requested page identity."};if(n.length>1)return{ok:!1,code:"ROUTE_AMBIGUOUS",message:"Multiple routes match the requested page identity."};let[r]=n[0],o=new Set([r]);try{let h=Hi({files:new Map(Object.entries(e.files))});for(let y of h)y.canonicalEntryFile===r&&o.add(y.entryFile)}catch(h){return{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:h instanceof Error?h.message:"Invalid page template source."}}let i=hI(e.files);if(!i.ok)return i.error;let s=i.graph,a=SI(o,s),c=EI(o,a,s),l=[...a].filter(h=>!c.has(h)).sort((h,y)=>h.localeCompare(y)),u=[...o,...[...c].sort((h,y)=>h.localeCompare(y))],d=new Set(u),f=u.map(h=>({operation:"delete",file:h})),g=[],m=[];for(let[h,y]of Object.entries(e.files))if(!d.has(h)){if(y.includes("NAV_ITEMS")){let x=Oc(y,e.expectedUrlPath);x.status==="removed"?(f.push({operation:"upsert",file:h,content:x.source}),g.push(h)):x.status==="unsupported"&&m.push(`unsupported_navigation:${h}`)}y.includes(e.expectedUrlPath)&&!y.includes("NAV_ITEMS")&&m.push(`preserved_link:${h}`)}return{ok:!0,edits:f,deletedFiles:u,updatedFiles:g,preservedSharedFiles:l,warnings:m}}function hI(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")||!yI(r))continue;let s=Wt(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(xI(c))continue;let l=In(r,c),u=bI(l,t);if(!u)return{ok:!1,error:{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:`Page source dependencies could not be proven safe: ${r} -> ${c} (import-not-found).`}};a.add(u)}n.set(r,a)}return{ok:!0,graph:n}}function yI(e){let t=e.toLowerCase();return po.some(n=>t.endsWith(n))}function xI(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!po.some(n=>e.endsWith(n)))}function bI(e,t){let n=e.replace(/\\/g,"/");return(po.some(o=>n.endsWith(o))?[n]:[...po.map(o=>`${n}${o}`),...po.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function SI(e,t){let n=new Set,r=[...e].flatMap(o=>[...t.get(o)??[]]);for(;r.length>0;){let o=r.pop();!o.startsWith(gI)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function EI(e,t,n){let r=new Set(t),o=!0;for(;o;){o=!1;for(let i of[...r])[...n].some(([a,c])=>!e.has(a)&&!r.has(a)&&c.has(i))&&(r.delete(i),o=!0)}return r}import*as _m from"@babel/parser";import*as ge from"@babel/types";import*as ps from"node:path";import*as ke from"@babel/types";function _p(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 jt(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return Dn(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(ke.isObjectPattern(n)||ke.isArrayPattern(n))return Dn(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(kI(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function Dn(e,t,n=!1){return ke.isIdentifier(e)?e.name===t&&n:ke.isObjectPattern(e)?e.properties.some(r=>ke.isObjectProperty(r)?Dn(r.value,t,n):Dn(r.argument,t,n)):ke.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=ke.isRestElement(r)?r.argument:r;return Dn(o,t,n)}):ke.isAssignmentPattern(e)?Dn(e.left,t,!0):ke.isRestElement(e)?Dn(e.argument,t,n):!1}function fr(e,t){if(e.path.isObjectPattern()){if(t){let r=Nt(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:jt(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:jt(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=Mp(r),i=!1,s=o?o.initBinding&&Lc(o.initBinding)?(i=jt(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=fr(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=Nt(e.path.node.id,e.identifier.name);if(s&&a){let c=[...s,...a],[l,...u]=c;return!l||l.kind!=="property"?null:{propName:l.name,remainingPath:[...u,...t?.path??[]],hasDefault:i||jt(e)}}}}let n=RI(e);if(n){let r=vI(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||jt(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:jt(e)}}let i=mo(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:jt(e)}:null}if(Lc(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:jt(e)}}return null}function vI(e,t){let n=e.findParent(u=>u.isVariableDeclarator());if(!n?.isVariableDeclarator())return null;let r=n.get("init");if(!r?.isExpression())return null;let o=Mp(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=Lc(i)?(a=jt(i),[...s]):(()=>{let u=fr(i,{kind:"identifier",expression:i.identifier.name,base:i.identifier.name,path:[]});return a=u?.hasDefault??!1,u?[{kind:"property",name:u.propName},...u.remainingPath,...s]:null})();if(!c)return null;let l=Nt(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||jt(t)}:null}function Mp(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=wI(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function Lc(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function kI(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=Nt(i.node,t);if(a)return a}return null}function Op(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=Zi(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=mo(a.node);if(!c||n&&c!==n)continue;let l=a.get("value");if(!l.isAssignmentPattern())continue;let u=l.get("right");if(u.isExpression())return{propName:c,componentName:t,expressionPath:u,displayPath:`${t}.${c}.default`}}let r=CI(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=mo(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 Zi(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=mo(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&Nt(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=Zi(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=Zi(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=Zi(r,t);if(o)return o}}return null}function Nt(e,t,n=[]){if(ke.isIdentifier(e))return e.name===t?n:null;if(ke.isObjectPattern(e)){for(let r of e.properties)if(ke.isObjectProperty(r)){let o=mo(r);if(!o)continue;let i=Nt(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(ke.isRestElement(r)){let o=Nt(r.argument,t,n);if(o)return o}}if(ke.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=ke.isRestElement(o)?o.argument:o,s=Nt(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return ke.isAssignmentPattern(e)?Nt(e.left,t,n):null}function CI(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function RI(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 mo(e){return e.computed?null:ke.isIdentifier(e.key)?e.key.name:ke.isStringLiteral(e.key)?e.key.value:null}function wI(e){let t=[],n=e;for(;ke.isMemberExpression(n);){if(n.computed)if(ke.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(ke.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(ke.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return ke.isIdentifier(n)?{base:n.name,path:t}:null}import*as Vp from"@babel/parser";import jc from"@babel/traverse";import*as pr from"@babel/types";import*as de from"@babel/types";var Lp=new WeakMap;function es(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?Qi(n,t):null}if(e.isMemberExpression()){let n=_I(e.node),r=NI(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?Qi(o,[...r,...t]):null}return e.isAwaitExpression()||Bc(e.node)?pn(OI(e.node),t,"awaited or fetched expression"):null}function NI(e){let t=[],n=e;for(;de.isMemberExpression(n);){if(n.computed)if(de.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(de.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(de.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return de.isIdentifier(n)?t:null}function Qi(e,t=[],n){let r=PI(e,t);if(r)return r;let o=AI(e,t,n);if(o)return o;let i=TI(e,t,n);return i||null}function ho(e){return e?.kind==="api-source"}function PI(e,t){if(e.path.isVariableDeclarator()&&de.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&Dc(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return pn(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&de.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(c=>de.isObjectProperty(c)&&jp(c)==="data"&&go(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&Dc(a.node))return pn(e.identifier.name,t,"query hook data binding")}let n=FI(e);if(!n||jp(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()||!Dc(i.node)?null:pn(e.identifier.name,t,"query hook data binding")}function AI(e,t,n){if(e.path.isVariableDeclarator()&&de.isArrayPattern(e.path.node.id)){let c=e.path.get("init");if(!c?.isCallExpression()||!Bp(c.node))return null;let[l,u]=e.path.node.id.elements;return!de.isIdentifier(l)||l.name!==e.identifier.name||!de.isIdentifier(u)?null:Dp(e,u.name,n)?pn(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()||!Bp(i.node)||r.node.elements.findIndex(c=>c===e.path.node)!==0)return null;let a=r.node.elements[1];return de.isIdentifier(a)&&Dp(e,a.name,n)?pn(e.identifier.name,t,"state setter is updated by API data"):null}function TI(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()?pn(e.identifier.name,t,"awaited binding result"):Bc(o.node,n)?pn(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 go(e,t){return de.isIdentifier(e)?e.name===t:de.isAssignmentPattern(e)?go(e.left,t):de.isObjectPattern(e)?e.properties.some(n=>de.isObjectProperty(n)?go(n.value,t):go(n.argument,t)):de.isArrayPattern(e)?e.elements.some(n=>!!n&&go(de.isRestElement(n)?n.argument:n,t)):!1}function Dp(e,t,n){let r=!1,o=!1,i=e.scope.path,s;if(n){let c=Lp.get(n);c||(c=new WeakMap,Lp.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){Bc(c.node)&&(r=!0),(MI(c.node.callee,t)||c.node.arguments.some(l=>de.isIdentifier(l)&&l.name===t))&&(o=!0)}});let a=r&&o;return s?.set(t,a),a}function Dc(e){let t=ts(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function Bp(e){return ts(e.callee)==="useState"}function Bc(e,t){let n=t?.get(e);if(n!==void 0)return n;let r=qi(e,o=>de.isCallExpression(o)&&ts(o.callee)==="fetch");return t?.set(e,r),r}function _I(e){let t=e;for(;de.isMemberExpression(t);)t=t.object;return de.isIdentifier(t)?t.name:null}function jp(e){return e.computed?null:de.isIdentifier(e.key)?e.key.name:de.isStringLiteral(e.key)?e.key.value:null}function ts(e){return de.isIdentifier(e)?e.name:de.isMemberExpression(e)&&de.isIdentifier(e.property)?e.property.name:null}function MI(e,t){return qi(e,n=>de.isIdentifier(n)&&n.name===t)}function qi(e,t){if(t(e))return!0;let n=de.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(de.isNode(i)&&qi(i,t))return!0;continue}if(de.isNode(o)&&qi(o,t))return!0}return!1}function OI(e){return de.isIdentifier(e)?e.name:de.isCallExpression(e)?ts(e.callee)??"api":de.isAwaitExpression(e)?"awaited-api":"api"}function pn(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:LI(e,t),reason:n}}function LI(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var Kp=typeof jc=="function"?jc:jc.default;function Up(e,t){let n=Xp(e);if(!n)return{allowed:!0};let r=!1;return Kp(n,{CallExpression(o){if(!zp(o.node,t.sourceRange)||!DI(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||ho(es(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function Jp(e,t){let n=Xp(e);if(!n)return{allowed:!0};let r=!1;return Kp(n,{JSXExpressionContainer(o){zp(o.node,t.sourceRange)&&(pr.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 Xp(e){try{return Vp.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function DI(e){let t=e.callee;return pr.isMemberExpression(t)&&pr.isIdentifier(t.property)&&t.property.name==="map"}function zp(e,t){let n=e.loc;return n?$p({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&$p({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function $p(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 z from"@babel/types";import*as Wp from"@babel/parser";import $c from"@babel/traverse";import*as Oe from"@babel/types";import*as mr from"node:path";var Pt=typeof $c=="function"?$c:$c.default;function Xe(e){try{return Wp.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Vc(e){return e.computed?Oe.isStringLiteral(e.key)||Oe.isNumericLiteral(e.key)?String(e.key.value):null:BI(e.key)}function BI(e){return Oe.isIdentifier(e)?e.name:Oe.isStringLiteral(e)||Oe.isNumericLiteral(e)?String(e.value):null}function Bn(e){return Oe.isParenthesizedExpression(e)||Oe.isTSAsExpression(e)||Oe.isTSSatisfiesExpression(e)||Oe.isTSNonNullExpression(e)||Oe.isTSTypeAssertion(e)?Bn(e.expression):Oe.isExpression(e)?e:null}function Kc(e){if(Oe.isIdentifier(e))return[e.name];if((Oe.isMemberExpression(e)||Oe.isOptionalMemberExpression(e))&&!e.computed&&Oe.isIdentifier(e.property)){let t=Bn(e.object),n=t?Kc(t):null;return n?[...n,e.property.name]:null}return null}function jn(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?mr.normalize(mr.join(mr.dirname(e),t)).replace(/\\/g,"/"):t}function dt(e,t){return ns(e)===ns(t)}function ns(e){let t=gr(e);return t.endsWith("/index")?t.slice(0,-6):t}function gr(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function Yp(e,t,n){let r=em(e,t);if(tm(e,r),nm(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 Pt(e,{JSXElement(s){sm(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:rs(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 Zp(e,t){let n=new Map,r=i=>{let s=hr(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 jI(i,n))o=r(s)||o}return[...n.values()]}function jI(e,t){let n=[],r=$I(e,t);for(let o of e.ast.program.body){if(z.isExportDefaultDeclaration(o)&&z.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=yo(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(z.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=jn(e.file,o.source.value);for(let s of o.specifiers){if(z.isExportNamespaceSpecifier(s)){let l=mn(s.exported);for(let u of t.values())dt(u.file,i)&&n.push({file:e.file,namespace:Uc(l,u.namespace),exportName:u.exportName});continue}if(!z.isExportSpecifier(s))continue;let a=mn(s.local),c=[...t.values()].filter(l=>dt(l.file,i)&&$n(l.namespace,a));if(c.length>0){let l=mn(s.exported);for(let u of c){let d=yo(u.namespace,a,l);d&&n.push({file:e.file,namespace:d,exportName:u.exportName})}continue}t.has(hr({file:i,exportName:a}))&&n.push({file:e.file,exportName:mn(s.exported)})}continue}if(z.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!z.isExportSpecifier(i))continue;let s=mn(i.local),a=r.get(s)??[];if(a.length>0){let c=mn(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let u=yo(l.namespace,s,c);u&&n.push({file:e.file,namespace:u,exportName:l.exportName})}}}continue}if(z.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=jn(e.file,o.source.value),s=o.exported;if(s){let a=mn(s);for(let c of t.values())dt(c.file,i)&&n.push({file:e.file,namespace:Uc(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())dt(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function Uc(e,t){return t?`${e}.${t}`:e}function $n(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function yo(e,t,n){return!$n(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function $I(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(!z.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=jn(e.file,i.source.value);for(let a of i.specifiers){if(z.isImportDefaultSpecifier(a)){let c=t.get(hr({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(u=>dt(u.file,s)&&$n(u.namespace,"default"));for(let u of l){let d=yo(u.namespace,"default",a.local.name);d&&r(a.local.name,{...u,namespace:d})}continue}if(z.isImportSpecifier(a)){let c=mn(a.imported),l=[...t.values()].filter(d=>dt(d.file,s)&&$n(d.namespace,c));for(let d of l)r(a.local.name,d);let u=t.get(hr({file:s,exportName:c}));u&&r(a.local.name,u);continue}if(z.isImportNamespaceSpecifier(a))for(let c of t.values())dt(c.file,s)&&r(a.local.name,{...c,namespace:Uc(a.local.name,c.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(z.isVariableDeclaration(i))for(let s of i.declarations){if(!z.isIdentifier(s.id)||!s.init)continue;let a=Bn(s.init);if(!a||!z.isIdentifier(a))continue;let c=n.get(a.name)??[];if(c.length===0)continue;let l=n.get(s.id.name)??[],u=new Set(l.map(hr));for(let d of c){let f=yo(d.namespace,a.name,s.id.name),g=f?{...d,namespace:f}:d,m=hr(g);u.has(m)||(r(s.id.name,g),u.add(m),o=!0)}}}return n}function hr(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${ns(e.file)}#${t}`}function mn(e){return z.isIdentifier(e)?e.name:e.value}function Qp(e,t){for(let n of e.program.body){if(z.isExportDefaultDeclaration(n)){let o=n.declaration;if((z.isFunctionDeclaration(o)||z.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(z.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!z.isExportNamedDeclaration(n))continue;let r=n.declaration;if((z.isFunctionDeclaration(r)||z.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(z.isVariableDeclaration(r)){for(let o of r.declarations)if(z.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!z.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:z.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function Xc(e){let t=VI(e),n=[],r=nm(e.ast,t);return Pt(e.ast,{JSXElement(o){dt(e.file,e.sourceFile)&&rs(o)===e.sourceComponent||sm(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function qp(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function em(e,t){let n=qp();return Pt(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function VI(e){let t=qp();return dt(e.file,e.sourceFile)&&KI(t,em(e.ast,e.sourceComponent)),Pt(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=jn(e.file,o),s=e.componentIdentities.filter(a=>dt(a.file,i));if(s.length!==0)for(let a of r.specifiers){let c=n.scope.getBinding(a.local.name);if(c){if(z.isImportDefaultSpecifier(a)&&s.some(l=>l.exportName==="default")&&t.localBindings.add(c),z.isImportDefaultSpecifier(a)){let l=s.filter(u=>$n(u.namespace,"default"));if(l.length>0){let u=t.namespaceMembers.get(c)??new Set;for(let d of l){let f=Gp(d,"default");f&&u.add(f)}t.namespaceMembers.set(c,u)}continue}if(z.isImportSpecifier(a)){let l=z.isIdentifier(a.imported)?a.imported.name:a.imported.value,u=s.filter(d=>$n(d.namespace,l));if(u.length>0){let d=t.namespaceMembers.get(c)??new Set;for(let f of u){let g=Gp(f,l);g&&d.add(g)}t.namespaceMembers.set(c,d);continue}s.some(d=>!d.namespace&&d.exportName===l)&&t.localBindings.add(c);continue}if(z.isImportNamespaceSpecifier(a))for(let l of s){let u=l.namespace?`${l.namespace}.${l.exportName}`:l.exportName,d=t.namespaceMembers.get(c)??new Set;d.add(u),t.namespaceMembers.set(c,d)}}}}}),tm(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 tm(e,t){Pt(e,{VariableDeclarator(n){if(!n.node.init)return;let r=Bn(n.node.init);if(r){if(z.isIdentifier(n.node.id)){let o=Vn(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&Jc(t,i,o);return}if(z.isObjectPattern(n.node.id)){let o=Vn(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&im(n.node.id,o.namespaceMembers,t,n)}}}})}function nm(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return Pt(e,{ReferencedIdentifier(r){if(n){r.stop();return}UI(r)||!r.isIdentifier()||!rm(r,t)||JI(r,t)||XI(r)||(n=!0,r.stop())}}),n}function UI(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 rm(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)&&Vn(r.node,t,r)?r:null}function JI(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!Hp(e,r))return!1;let o=rm(e,t);if(!o)return!1;if(Bn(r.node)===o.node)return!!Vn(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&Hp(e,a)&&!!Vn(a.node,t,a)}function XI(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function Hp(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Vn(e,t,n){let r=Bn(e);if(!r)return null;if(z.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(z.isObjectExpression(r))return zI(r,t,n);let o=Kc(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?om(s,o.slice(1).join(".")):null}function zI(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!z.isObjectProperty(i))continue;let s=Vc(i);if(!s||!z.isExpression(i.value)){z.isExpression(i.value)&&(o||=Vn(i.value,t,n)!==null);continue}let a=Vn(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 om(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 Jc(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 im(e,t,n,r){for(let o of e.properties){if(z.isRestElement(o)){if(z.isIdentifier(o.argument)){let c=r.scope.getBinding(o.argument.name);c&&Jc(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!z.isObjectProperty(o))continue;let i=Vc(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=om(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=z.isAssignmentPattern(o.value)?o.value.left:o.value;if(z.isIdentifier(a)){let c=r.scope.getBinding(a.name);c&&Jc(n,c,s);continue}if(z.isObjectPattern(a)&&s.namespaceMembers.size>0){im(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function Gp(e,t){if(!$n(e.namespace,t))return null;if(e.namespace===t)return e.exportName;let n=e.namespace?.slice(t.length+1);return n?`${n}.${e.exportName}`:e.exportName}function sm(e,t){let n=e.node.openingElement.name;if(z.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=am(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 am(e){if(z.isJSXIdentifier(e))return[e.name];if(z.isJSXMemberExpression(e)){let t=am(e.object);return t?[...t,e.property.name]:null}return null}function rs(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()&&z.isIdentifier(n.node.id))return n.node.id.name}return null}function cm(e,t){let n=Xe(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=Xc({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 Ee(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 Se(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function $t(e,t){let n=Se(e);return!!(n&&ft(t,n))}function ft(e,t){return t.start>=e.start&&t.end<=e.end}function vt(e,t){let n=ue(e,Ee(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:os(e,t)}function yr(e,t){let n=Se(t);return n?e.slice(n.start,n.end):""}function lm(e,t){return e.start===t.start&&e.end===t.end}function os(e,t){let n=null;return Pt(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 is(e,t){return zc(e,t).length>0}function ss(e,t){let n=Se(e.node),r=Se(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=Se(e.node.consequent);if(r&&ft(r,t)&&!ft(r,n))return!1;let o=e.node.alternate?Se(e.node.alternate):null;return!(o&&ft(o,t)&&!ft(o,n))}function zc(e,t){let n=Se(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=Se(o.node.consequent),a=Se(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()&&Wc(o.node.operator)){let s=Se(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 Wc(e){return e==="&&"||e==="||"||e==="??"}function um(e,t){let n=Se(e.consequent);if(n&&ft(n,t))return n;let r=Se(e.alternate);return r&&ft(r,t)?r:null}function dm(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=>gr(a.file)));if(!t.has(gr(e.sourceFile))||!t.has(gr(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(gr(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=Qp(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=Xe(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=Zp(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=Xc({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!dt(s.file,e.targetFile)||rs(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 qI}from"@vcp-dev/contracts";function as(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 xo();let a=s.target,c=a.locator;if(a.sourceKind==="repeat-template"){let l=o?.instanceIndex;if(l===void 0)return xo();let u=HI(a,l,o?.instanceCount);if(!u)return xo();c=u}return{ok:!0,target:{kind:"value-binding",file:a.file,locator:c}}}return o?.instanceIndex!==void 0?n!=="selection"||!i?.ok?{ok:!1,code:"repeat-target-failed",reason:i&&!i.ok?i.reason:"No safe selected repeat property target is available"}:{ok:!0,target:{kind:"repeat-property",target:i}}:e.isRepeat&&n!=="template"||t.status==="direct"&&t.target?.kind!=="jsx-attribute"?xo():{ok:!0,target:{kind:"jsx-attribute"}}}function xo(){return{ok:!1,code:"unsupported-binding",reason:"Property does not have a safe typed binding write target for this scope and operation"}}function HI(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 Vt from"@babel/types";import{SiteEditSetPropsParamsSchema as GI}from"@vcp-dev/contracts";function fm(e){let t=e.changes??(e.change?[e.change]:[]);if(!GI.safeParse({kind:"set-props",scope:"selection",changes:t}).success)return bo("invalid-change","Repeat property changes are invalid");if(t.length!==1||t[0].name!==e.target.propertyName)return bo("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=Pe(e.source,"value");if(!o.ok)return bo("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=ue(o.ast,a);if(!c.ok||!c.match.path.isObjectExpression())return bo("unsupported-object",`Repeat item ${s} is not a writable object expression`);let l=s===e.target.sourceItemIndex?YI(r):ZI(c.match.path.node,r.name);if(!l)return bo("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 YI(e){return e.operation==="set"?{kind:"value",value:e.value}:{kind:"undefined"}}function ZI(e,t){let n=e.properties.filter(i=>Vt.isObjectProperty(i)&&QI(i.key)===t);if(n.length>1)return null;let r=n[0];if(!r)return{kind:"undefined"};if(!Vt.isExpression(r.value))return null;let o=Bt(r.value);return o.status==="undefined"?{kind:"undefined"}:o.status!=="resolved"?null:{kind:"value",value:o.value}}function QI(e){return Vt.isIdentifier(e)?e.name:Vt.isStringLiteral(e)?e.value:Vt.isNumericLiteral(e)?String(e.value):null}function bo(e,t){return{ok:!1,errorCode:e,reason:t}}function pm(e){if(e.change.name!=="className"&&e.change.name!=="class")return So("unsupported-owner",`No specialized property owner is available for '${e.change.name}'`);let t=e.classNameSource;if(!t||t.filePath!==e.node.file)return So("owner-source-unavailable","className source details are unavailable for the selected node");if(e.change.name==="class"&&t.sourceKind==="missing")return So("owner-source-unavailable","The class alias requires an existing className source");if(t.sourceKind==="expression")return So("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 So("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 So(e,t){return{ok:!1,errorCode:e,reason:t}}async function gm(e){let t=qI.safeParse({kind:"set-props",scope:e.scope,changes:e.changes});if(!t.success)return gn("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 gn("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 eC(e,r);if(o){if(!o.ok)return gn("owner-plan-failed",o.reason);mm(n,o.steps);continue}let i=await e.getPropertyState(e.node.key,r.name,e.selectionRef);if(!i)return gn("missing-property-state",`No authoritative property state is available for '${r.name}'`);if(i.status==="blocked")return gn("readonly-property",i.diagnostic?.message??`Property '${r.name}' is not writable`);if(rC(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=as({state:i,scope:e.scope,operation:r.operation,selectionRef:e.selectionRef,repeatTarget:s});if(!a.ok)return gn(a.code,a.reason);let c=a.target;if(c.kind==="value-binding"&&r.operation==="set"){Hc(n,{type:"update-value",order:n.length,file:c.file,locator:c.locator,value:r.value});continue}if(c.kind==="repeat-property"){let l=fm({source:e.getFileContent(c.target.sourceFile),target:c.target,changes:[r]});if(!l.ok)return gn("repeat-target-failed",l.reason);mm(n,l.steps);continue}Hc(n,{type:"set-property-changes",order:n.length,file:e.node.file,locator:tC(e.node),scope:e.scope,changes:[r]})}return n.forEach((r,o)=>{r.order=o}),nC(n)?gn("step-conflict","Property changes resolve to conflicting write steps"):{ok:!0,steps:n}}async function eC(e,t){return t.name!=="className"&&t.name!=="class"?null:pm({node:e.node,change:t,classNameSource:e.classNameSource})}function tC(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 nC(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 mm(e,t){for(let n of t)Hc(e,{...n,order:e.length})}function Hc(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 rC(e,t){if(t.operation!=="set"||e.status!=="direct")return!1;let n=e.attribute?.resolution;return n?.status==="resolved"?Gc(n.value,t.value):e.attribute?.source===null&&e.attribute.value===t.value}function Gc(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)=>Gc(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=>Gc(n[i],r[i]))}return!1}function gn(e,t){return{ok:!1,errorCode:e,reason:t}}import*as br from"@babel/types";import*as Q from"@babel/types";function Yc(e,t,n){let r=vt(t,n);return r?Kt(e,r):null}function Kt(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(!Q.isIdentifier(l)||l.name!=="map"||c.computed)return null;let u=a.get("object"),d=yr(e,u.node),f=r.node.params.map(h=>yr(e,h)),g=Se(i.node),m=Se(r.node);return!d||f.some(h=>h.length===0)||!g||!m?null:{callStart:g.start,callEnd:g.end,callbackStart:m.start,callbackEnd:m.end,collectionExpression:d,callbackParams:f,mapOperator:Q.isOptionalMemberExpression(c)&&c.optional?"?.map":".map",collectionNeedsParens:cs(u.node),callbackPath:r,collectionPath:u}}function Eo(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function oC(e,t){let n=Se(e.node);return n?iC(t).some(r=>{let o=Se(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function iC(e){let t=e.callbackPath.node.body;return Q.isBlockStatement(t)?hn(t.body):yn(t)}function hn(e){let t=[];for(let n of e){if(Q.isReturnStatement(n)){n.argument&&t.push(...yn(n.argument));continue}if(Q.isBlockStatement(n)){t.push(...hn(n.body));continue}if(Q.isIfStatement(n)){let r=Q.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...hn(r)),n.alternate){let o=Q.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...hn(o))}continue}if(Q.isSwitchStatement(n)){for(let r of n.cases)t.push(...hn(r.consequent));continue}Q.isTryStatement(n)&&(t.push(...hn(n.block.body)),n.handler&&t.push(...hn(n.handler.body.body)),n.finalizer&&t.push(...hn(n.finalizer.body)))}return t}function yn(e){return Q.isJSXElement(e)?sC(e)?hm(e.children):[e]:Q.isJSXFragment(e)?hm(e.children):Q.isParenthesizedExpression(e)||Q.isTSAsExpression(e)||Q.isTSSatisfiesExpression(e)||Q.isTSNonNullExpression(e)||Q.isTSTypeAssertion(e)?yn(e.expression):Q.isConditionalExpression(e)?[...yn(e.consequent),...yn(e.alternate)]:Q.isLogicalExpression(e)&&Wc(e.operator)?yn(e.right):[]}function hm(e){return e.flatMap(t=>Q.isJSXElement(t)||Q.isJSXFragment(t)?yn(t):Q.isJSXExpressionContainer(t)&&(Q.isJSXElement(t.expression)||Q.isJSXFragment(t.expression)||Q.isConditionalExpression(t.expression)||Q.isLogicalExpression(t.expression))?yn(t.expression):[])}function sC(e){let t=e.openingElement.name;return Q.isJSXIdentifier(t)?t.name==="Fragment":Q.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function ym(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function cs(e){return!(Q.isIdentifier(e)||Q.isThisExpression(e)||Q.isMemberExpression(e)||Q.isOptionalMemberExpression(e)||Q.isCallExpression(e)||Q.isOptionalCallExpression(e))}function xm(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(Q.isMemberExpression(n)||Q.isOptionalMemberExpression(n))&&Q.isIdentifier(n.property)&&n.property.name==="map"&&!n.computed}function xr(e,t){let n=Xe(e);if(!n)return t.isRepeatItemRoot===!0;let r=ue(n,Ee(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:os(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=Kt(e,o);return i?oC(o,i):t.isRepeatItemRoot===!0}function bm(e,t){let n=Xe(e);if(!n)return!1;let r=ue(n,Ee(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:os(n,t);return o?!!o.findParent(i=>{if(!i.isCallExpression()&&!i.isOptionalCallExpression())return!1;let s=i.node.callee;return(Q.isMemberExpression(s)||Q.isOptionalMemberExpression(s))&&Q.isIdentifier(s.property)&&s.property.name==="map"}):!1}import*as we from"@babel/types";function Zc(e){if(we.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(we.isJSXMemberExpression(e)){let t=e;for(;we.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function aC(e,t){let n=Se(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);!a||$t(a.path.node,n)||xn(a,i,t)||r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=Zc(i.node.name);s&&o(s,i)}}),[...r].sort()}function Qc(e,t,n){let r=Xe(e);if(!r)return{ok:!0};let o=ue(r,Ee(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=ue(r,Ee(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};let s=$r(o.match.path,i.match.path);if(is(s,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let a=aC(s,i.match.path);return a.length>0?{ok:!1,bindingNames:a}:{ok:!0}}function Em(e){let t=e;for(;we.isTSQualifiedName(t);)t=t.left;return we.isIdentifier(t)?t.name:null}function vo(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function ls(e){let t=[],n=r=>{if(r){if(we.isIdentifier(r)){t.push(r.name);return}if(we.isObjectPattern(r)){for(let o of r.properties){if(we.isRestElement(o)){n(o.argument);continue}we.isObjectProperty(o)&&n(o.value)}return}if(we.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(we.isAssignmentPattern(r)){n(r.left);return}if(we.isRestElement(r)){n(r.argument);return}we.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function qc(e,t){let n=Se(e.node),r=Se(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=Sm(e),i=Sm(t);if(!o||!i||!lm(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=um(s.node,n);if(a&&!ft(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=Se(s.node.right);if(a&&ft(a,n)&&!ft(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())&&xm(s)){let a=Se(s.node.body)??Se(s.node);if(a&&!ft(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 Sm(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?Se(t.node.argument):null;if(t.isArrowFunctionExpression()&&(we.isJSXElement(t.node.body)||we.isJSXFragment(t.node.body)||we.isConditionalExpression(t.node.body)||we.isLogicalExpression(t.node.body)))return Se(t.node.body);t=t.parentPath}return null}function xn(e,t,n){return n.scope.getBinding(t)===e}function el(e,t,n,r={}){if(!r.preserveConditionalBoundary&&is(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=Se(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(c=>ls(c)).map(c=>n.callbackPath.scope.getBinding(c)?.path.node).filter(Boolean)),s=new Set,a=(c,l)=>{let u=l.scope.getBinding(c);!u||$t(u.path.node,o)||i.has(u.path.node)||xn(u,c,t)||s.add(c)};return e.traverse({ReferencedIdentifier(c){a(c.node.name,c)},JSXOpeningElement(c){let l=Zc(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function tl(e,t,n){let r=Se(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>ls(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return vo(e,s=>{let a=s.scope.getBinding(s.node.name);!a||$t(a.path.node,r)||o.has(a.path.node)||xn(a,s.node.name,t)||i.add(s.node.name)}),i.size>0?{ok:!1,bindingNames:[...i].sort()}:{ok:!0}}function vm(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>ls(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)||xn(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(br.isIdentifier(l))o(l.name,c);else{let u=Em(l);u&&o(u,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function nl(e,t){let n=Se(e.node),r=new Set;return vo(e,o=>{let i=o.scope.getBinding(o.node.name);i&&(n&&$t(i.path.node,n)||xn(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 km(e){let t=[];for(let n of e.callbackPath.node.params){if(br.isIdentifier(n)){t.push(n.name);continue}if(br.isRestElement(n)&&br.isIdentifier(n.argument)){t.push(`...${n.argument.name}`);continue}return{ok:!1,reason:"Cannot move cross-file repeat child because the callback parameters are not portable to the target file"}}return{ok:!0,callbackParams:t}}function Im(e,t){return{...e,callbackParams:t}}function rl(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function ko(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 Kn(e){return{file:e.file,component:e.component}}function cC(e){return e.target.kind==="node"?e.target.key:null}function lC(e){return"kind"in e}function us(e){return!lC(e)}function cl(e,t){let n=ps.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=ps.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function ol(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=Lt(n,Ee(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function ul(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 uC(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function dC(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 il(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function fC(e){let t=Yp(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=qc(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=pC({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=Mm(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?cs(o):!0}}}function pC(e){let t=Se(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||$t(a.path.node,t))return;let c=hC(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=xC(e.callSitePath,c.propName,e.source);if(!l.ok){o=l.reason;return}let u=mC(l.expression,c.remainingPath);if(!u){o="Cannot move prop-backed repeat child because the mapped prop path is not a portable expression";return}let d=nl(l.expressionPath,e.targetParentPath);if(!d.ok){o=d.reason??`Cannot move prop-backed repeat child because the mapped prop source is not visible at the target: ${d.bindingNames.join(", ")}`;return}n.set(`${c.range.start}:${c.range.end}`,{...c.range,text:u});return}xn(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:bC(e.source,t,[...n.values()])}}function mC(e,t){if(t.length===0)return e;let n=Mm(e);if(!n)return null;let r=cs(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=gC(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function gC(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function hC(e,t,n){let r=yC(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=fr(t,o);if(!i)return null;let s=r?.range??Se(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function yC(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!$t(n.node,t)||n.node.computed||!ge.isIdentifier(n.node.property))return null;let r=Se(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function xC(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()&&ge.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=yr(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 bC(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 Mm(e){try{let n=_m.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=ge.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&ge.isExpression(r)?r:null}catch{return null}}function SC(e){let t=Se(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||$t(s.path.node,t))return;let a=Rm(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let u=Rm(c,e.targetFile,e.targetFile);(!u||u.moduleFile!==a.moduleFile||!EC(u.importSpec,a.importSpec))&&r.add(a.localName);return}let l=n.get(a.moduleSpecifier)??[];l.some(u=>JSON.stringify(u)===JSON.stringify(a.importSpec))||l.push(a.importSpec),n.set(a.moduleSpecifier,l);return}r.add(i.node.name)};return vo(e.sourceContext.collectionPath,o),r.size>0?{ok:!1,reason:`Cannot move cross-file repeat child because the collection depends on non-importable bindings: ${[...r].sort().join(", ")}`}:{ok:!0,imports:[...n.entries()].map(([i,s])=>({moduleSpecifier:i,imports:s}))}}function EC(e,t){return e.kind!==t.kind?!1:e.kind==="named"&&t.kind==="named"?e.imported===t.imported&&e.local===t.local:e.kind==="default"&&t.kind==="default"||e.kind==="namespace"&&t.kind==="namespace"?e.local===t.local:!1}function Rm(e,t,n){let r=vC(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=jn(t,i),a=i.startsWith(".")?cl(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=ge.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 vC(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function wm(e,t,n,r){let o=zc(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=yr(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=kC(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${CC(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function kC(e,t){return IC(e.node)?t:`(${t})`}function IC(e){return ge.isIdentifier(e)||ge.isThisExpression(e)||ge.isSuper(e)||ge.isMemberExpression(e)||ge.isOptionalMemberExpression(e)||ge.isCallExpression(e)||ge.isOptionalCallExpression(e)||ge.isBooleanLiteral(e)||ge.isNumericLiteral(e)||ge.isStringLiteral(e)||ge.isNullLiteral(e)||ge.isUnaryExpression(e)}function CC(e){return e.trim().startsWith("<")?e:`(${e})`}var RC={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 ds(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=RC[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 wC(e,t){for(let n of e.program.body){if(!ge.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>ge.isImportDefaultSpecifier(o));if(r&&ge.isImportDefaultSpecifier(r))return r.local.name}return null}function NC(e,t,n){for(let r of e.program.body){if(!ge.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>ge.isImportSpecifier(i)&&(ge.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&ge.isImportSpecifier(o))return o.local.name}return null}function Nm(e){let t=new Set;return Pt(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 PC(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=ul(e),o=Xe(t);if(n.exportName!=="default"){let a=o?NC(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?Pm(r,Nm(o)):r;return{localName:c,importStep:sl(e,c)}}if(!o)return{localName:r,importStep:sl(e,r)};let i=wC(o,n.source);if(i)return{localName:i};let s=Pm(r,Nm(o));return{localName:s,importStep:sl(e,s)}}function AC(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??ul(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 TC(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=>ll(t[1])))}function ll(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(ll):typeof e=="object"?Object.values(e).every(ll):!1}function sl(e,t=ul(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 Am(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 _C(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function Sr(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function dl(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function Io(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:dl(e,t.slice(0,n)),index:r.index}}return null}function al(e,t){return e.locator?e.collectionPathMap?.[t]?dl(e.locator,e.collectionPathMap[t]):Io(e.locator)?OC(e.locator,LC(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:Om(o,t)}function Om(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=Om(r,t);return o===void 0?void 0:{[n.name]:o}}function OC(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},dl(e,i)}return null}function LC(e,t){return t?.[e]??e}function Tm(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 DC(e,t){return BC(e.root,t.root)&&$C(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&&jC(e.sourceRange,t.sourceRange)}}function jC(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function $C(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 fs=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:Sr(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:Sr(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:Sr(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:Sr(t.kind,t.params.kind)};let r=t;if(!us(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=Am(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:Sr(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:Sr(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=cC(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):Fm(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 Fm(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:Ee(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?gm({node:t.node,scope:t.scope,changes:t.changes,selectionRef:t.selectionRef,getPropertyState:n,getRepeatPropertyTarget:this.graph.getRepeatPropertyTarget,getFileContent:r=>this.graph.getFileContent(r),getFileVersion:r=>this.graph.getFileVersion(r),classNameSource:this.graph.getClassNameSource?.(t.node.key)??void 0}):{ok:!1,errorCode:"missing-property-state",reason:"Typed property planning requires authoritative property provenance"}}async buildStyleDraftPropertySteps(t){let{initialOrder:n,node:r,props:o,selectionRef:i}=t,s=[],a=[];for(let[c,l]of Object.entries(o)){if(l===void 0)continue;let u=await this.graph.getElementPropertyWriteTarget?.(r.key,c),d=r.attributes?.find(g=>g.name===c);if((await this.graph.getPropertyState?.(r.key,c,i))?.status==="blocked"||!u&&d?.source)return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite a derived or unresolved property '${c}'`};if(!(typeof d?.resolvedValue=="string"&&d.resolvedValue===l||d?.source===null&&d.value===l)){if(u?.kind==="external-entry")return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite readonly external property '${c}'`};if(u?.kind==="value-binding"&&u.locator){let g=u.locator;if(u.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let m=al(u,i.instanceIndex);if(!m)return{ok:!1,errorCode:"invalid-params",reason:"apply-style-draft could not resolve the selected repeat item"};g=m}s.push({order:n+s.length,file:u.file,type:"update-value",locator:g,value:l});continue}a.push({operation:"set",name:c,value:l})}}return a.length>0&&s.push({order:n+s.length,file:r.file,type:"set-property-changes",locator:Ee(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=al(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:Ee(t),segmentIndex:n,newText:r}]}}coerceTextValueForValueTarget(t,n,r,o="update-text"){let i=this.graph.getFileContent(t),s=Xe(i);if(!s)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not inspect the value source`};let a=ue(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!uC(a.match.path))return{ok:!0,value:r};let c=dC(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=al(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=Xe(this.graph.getFileContent(t));if(!o)return!1;let i=ue(o,n);if(!i.ok)return!1;let s=i.match.path;if(s.isStringLiteral())return typeof r=="string"&&s.node.value===r;if(s.isNumericLiteral())return typeof r=="number"&&Object.is(s.node.value,r);if(s.isBooleanLiteral())return typeof r=="boolean"&&s.node.value===r;if(s.isNullLiteral())return r===null;if(s.isUnaryExpression({operator:"-"})){let a=s.get("argument");return typeof r=="number"&&!Array.isArray(a)&&a.isNumericLiteral()&&Object.is(-a.node.value,r)}return!1}planUpdateText(t,n,r,o,i){let s=this.graph.getTextProvenance?.(r.key,n.params.segmentIndex);if(s&&(s.editMode==="readonly"||s.editMode==="unsupported"))return{ok:!1,errorCode:"unsupported-operation",reason:"Text has no identity-preserving write target"};if(!o.canUpdateText)return{ok:!1,errorCode:"capability-denied",reason:"Cannot update text on this node"};let a=this.buildTextRewriteSteps(r,n.params.segmentIndex,n.params.value,i,n.selectionRef);return a.ok?this.buildPlan(t,n,a.steps,o):a}async planRemoveNode(t,n,r,o){if(!o.canRemove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot remove this node"};let i=await this.graph.getTextWriteTarget(r.key,0);if(i?.kind==="external-entry")return this.buildPlan(t,n,[{order:0,file:`external:${i.sourceId}`,type:"invoke-external-adapter",sourceType:i.sourceType,sourceId:i.sourceId,adapterId:i.adapterId,capability:"remove-node",value:{operation:"remove-node"}}],o);if(r.isRepeatItemRoot){let d=i;if(d?.kind==="value-binding"&&d.locator){let f=Io(d.locator);if(f)return this.buildPlan(t,n,[{order:0,file:d.file,type:"remove-bound-array-item",locator:f.locator,index:f.index}],o)}return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed node removal requires a writable array target"}}let s=ko(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:Ee(r),removeWhitespace:!0}],u=this.buildRemoveComponentImportStep(r);return u&&l.push({...u,order:l.length}),this.buildPlan(t,n,l,o)}buildRemoveComponentImportStep(t,n=this.graph.getFileContent(t.file)){if(!t.importedFrom||!t.exportName||!t.tag||cm(n,t)>1)return null;let r=cl(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(!us(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=ko(r,a,s!==null?this.graph.getTextProvenance?.(r.key,s)??null:null);if(c)return{ok:!1,errorCode:"unsupported-operation",reason:c};let l=await this.getUpstreamBackedDescendantReason(r);if(l)return{ok:!1,errorCode:"unsupported-operation",reason:l};let u=await this.planExternalBackedInsertChild(t,n,r,o,i,a);if(u)return u;let d=await this.planRepeatBackedInsertChild(t,n,r,o);if(d)return d;let f=this.getRepeatBackedTemplateStructureReason(r);if(f)return{ok:!1,errorCode:"unsupported-operation",reason:f};let g=Up(this.graph.getFileContent(r.file),r);if(!g.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:g.reason??"Cannot insert child into this node"};let m=ds(r,n.params.node);if(m)return{ok:!1,errorCode:"unsupported-operation",reason:m};let h=[],y=0,x=n.params.node.kind==="component-call"?PC(n.params.node,this.graph.getFileContent(r.file)):void 0,E=x?.importStep;return E&&h.push({order:y++,file:r.file,type:"add-import",moduleSpecifier:E.moduleSpecifier,imports:E.imports}),h.push({order:y++,file:r.file,type:"insert-child",parentLocator:Ee(r),node:{jsx:AC(n.params.node,x?.localName)},placement:n.params.position.relation,anchorLocator:i?Ee(i):void 0}),this.buildPlan(t,n,h,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!us(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:TC(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(!us(n.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};if(n.params.position.relation!=="append"&&n.params.position.relation!=="prepend")return null;let i=n.params.node;if(i.kind!=="native-tag"||i.text===void 0||!this.graph.getChildNodes)return null;let s=this.graph.getChildNodes(r.key).find(d=>d.isRepeatItemRoot&&d.tag?.toLowerCase()===i.tag.toLowerCase());if(!s)return null;let a=await this.graph.getTextWriteTarget(s.key,0);if(!a||a.kind!=="value-binding"||!a.locator)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires a writable value target"};let c=Io(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 u=n.params.position.relation==="prepend"?Tm(0,a.collectionIndexMap):Tm(a.collectionIndexMap?.length??c.index+1,a.collectionIndexMap);return this.buildPlan(t,n,[{order:0,file:a.file,type:"insert-bound-array-item",locator:c.locator,index:u,value:l}],o)}async getUpstreamBackedDescendantReason(t){if(!this.graph.getChildNodes)return null;let n=[...this.graph.getChildNodes(t.key)];for(;n.length>0;){let r=n.shift();if(!r)continue;let o=this.graph.getEditableTextSegmentIndex(r.key),i=o!==null?await this.graph.getTextWriteTarget(r.key,o):null,s=ko(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 xr(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:")||bm(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&&xr(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=Xe(c);if(!l)return null;let u=vt(l,r),d=vt(l,o);if(!u||!d)return null;let f=Kt(c,u),g=Kt(c,d);if(!Eo(f,g))return null;if(a&&(s==="before"||s==="after")){let h=vt(l,a),y=h?Kt(c,h):null;if(!Eo(f,y))return null}if(ss(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let m=Qc(c,r,o);return m.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:Ee(r),targetParentLocator:Ee(o),placement:s,anchorLocator:a?Ee(a):void 0,selectionContext:Kn(o)}],i):{ok:!1,errorCode:"unsupported-operation",reason:m.reason??`Cannot move node because it depends on bindings outside the target scope: ${m.bindingNames.join(", ")}`}}planRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&xr(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=Xe(c);if(!l)return null;let u=vt(l,r),d=vt(l,o);if(!u||!d)return null;let f=Kt(c,u);if(!f)return null;let g=Kt(c,d);if(Eo(f,g))return null;if(g&&!ym(g,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")){let v=Yc(c,l,a);if(g&&!Eo(g,v)||!g&&v)return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child relative to a repeat-template anchor outside the target scope"}}if(r.tag&&r.tag.toLowerCase()===r.tag){let v=ds(o,{kind:"native-tag",tag:r.tag});if(v)return{ok:!1,errorCode:"unsupported-operation",reason:v}}let m=ol(this.graph,r);if(!m)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(ss(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let h=wm(c,u,d,m);for(let v of h.conditionPaths){let C=tl(v,d,f);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 y=el(u,d,f,{preserveConditionalBoundary:h.conditionPaths.length>0});if(!y.ok)return{ok:!1,errorCode:"unsupported-operation",reason:y.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${y.bindingNames.join(", ")}`};let x=vm(f,d);if(!x.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its callback parameters depend on bindings outside the target scope: ${x.bindingNames.join(", ")}`};let E=f;if(r.component!==o.component){let v=fC({source:c,ast:l,sourceContext:f,sourceNode:r,targetParent:o,targetParentPath:d});if(!v.ok)return{ok:!1,errorCode:"unsupported-operation",reason:v.reason};E=v.context}else{let v=nl(f.collectionPath,d);if(!v.ok)return{ok:!1,errorCode:"unsupported-operation",reason:v.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${v.bindingNames.join(", ")}`}}return this.buildPlan(t,n,[{order:0,file:r.file,type:"move-repeat-template-child",locator:Ee(r),targetParentLocator:Ee(o),placement:s,anchorLocator:a?Ee(a):void 0,repeatExpression:rl(E,h.sourceJsx),selectionContext:Kn(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&xr(this.graph.getFileContent(r.file),r)||r.file===o.file)return null;let c=this.graph.getFileContent(r.file),l=this.graph.getFileContent(o.file),u=Xe(c),d=Xe(l);if(!u||!d)return null;let f=dm({knownSourceFiles:this.graph.getKnownSourceFiles?.(),routeEntryFiles:this.graph.getRouteEntryFiles?.(),sourceAst:u,sourceFile:r.file,targetFile:o.file,sourceComponent:r.component,targetComponent:o.component});if(!f.ok)return{ok:!1,errorCode:"unsupported-operation",reason:f.reason};let g=vt(u,r),m=vt(d,o);if(!g||!m)return null;let h=qc(f.callSitePath,m);if(!h.ok)return{ok:!1,errorCode:"unsupported-operation",reason:h.reason};let y=Kt(c,g);if(!y)return null;if(Kt(l,m))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")&&Yc(l,d,a))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child relative to a repeat-template anchor outside the target scope"};if(r.tag&&r.tag.toLowerCase()===r.tag){let T=ds(o,{kind:"native-tag",tag:r.tag});if(T)return{ok:!1,errorCode:"unsupported-operation",reason:T}}let E=ol(this.graph,r);if(!E)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(ss(g,m))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let v=wm(c,g,m,E);for(let T of v.conditionPaths){let L=tl(T,m,y);if(!L.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${L.bindingNames.join(", ")}`}}let C=el(g,m,y,{preserveConditionalBoundary:v.conditionPaths.length>0});if(!C.ok)return{ok:!1,errorCode:"unsupported-operation",reason:C.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${C.bindingNames.join(", ")}`};let P=SC({sourceFile:r.file,targetFile:o.file,sourceContext:y,targetParentPath:m});if(!P.ok)return{ok:!1,errorCode:"unsupported-operation",reason:P.reason};let F=km(y);if(!F.ok)return{ok:!1,errorCode:"unsupported-operation",reason:F.reason};let R=Im(y,F.callbackParams),N=[{order:0,file:r.file,type:"remove-node",locator:Ee(r),removeWhitespace:!0}];for(let T of P.imports)N.push({order:N.length,file:o.file,type:"add-import",moduleSpecifier:T.moduleSpecifier,imports:T.imports});return N.push({order:N.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:Ee(o),expression:rl(R,v.sourceJsx),placement:s,anchorLocator:a?Ee(a):void 0,selectionContext:Kn(o)}),this.buildPlan(t,n,N,i)}async planMoveNode(t,n,r,o){if(!o.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};if("kind"in n.params.target&&n.params.target.kind==="source-sibling"){let v=n.params.target,C=this.graph.getNode(v.anchorKey);if(!C||r.file!==C.file||r.component!==C.component)return{ok:!1,errorCode:"locator-miss",reason:"Source sibling move requires a sibling in the same component file"};let P=this.graph.getFileVersion(r.file);if(n.documentVersion!==P)return{ok:!1,errorCode:"stale-version",reason:`Document version ${n.documentVersion} is stale or otherwise does not match source sibling file version (current: ${P})`};let F=this.graph.getFileContent(r.file),R=Xe(F),N=R?vt(R,r):null,T=R?vt(R,C):null,L=N?.parentPath,q=T?.parentPath;if(!N||!T||!L||!q||L.node!==q.node||!L.isJSXFragment()&&!(L.isJSXElement()&&Le(L)))return{ok:!1,errorCode:"unsupported-operation",reason:"Source sibling move requires two direct children of the same transparent Fragment"};let W=L.node.loc;return W?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:Ee(r),targetParentLocator:{kind:"jsx-node",strategy:"source-range",sourceRange:{startLine:W.start.line,startColumn:W.start.column,endLine:W.end.line,endColumn:W.end.column}},placement:v.relation,anchorLocator:Ee(C),selectionContext:Kn(r)}],o):{ok:!1,errorCode:"locator-miss",reason:"Source Fragment has no stable source range"}}let i=Am(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(_C(s.key,r.key,this.graph))return{ok:!1,errorCode:"capability-denied",reason:"Cannot move node into its own subtree"};if(r.isRepeatRegion&&s.isBoundary)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move repeat-region node across boundary"};if(!this.graph.getCapability(s.key).canInsertChild)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move node into this parent"};let c=await this.graph.getTextWriteTarget(r.key,0);if(c?.kind==="external-entry"){let v=n.params.target.relation,C=i.anchorNode&&(v==="before"||v==="after")?await this.graph.getTextWriteTarget(i.anchorNode.key,0):null;return this.buildPlan(t,n,[{order:0,file:`external:${c.sourceId}`,type:"invoke-external-adapter",sourceType:c.sourceType,sourceId:c.sourceId,adapterId:c.adapterId,capability:"move-node",value:{operation:"move-node",relation:v,anchorSourceId:C?.kind==="external-entry"?C.sourceId:null,parentKey:"parentKey"in n.params.target?n.params.target.parentKey:null}}],o)}let l=r.file!==s.file,u=n.params.target.relation,d=i.anchorNode,f=this.graph.getTextProvenance?.(r.key,0)??null,g=ko(r,c,f);if(g&&!il(g)&&!Cm(r,s,c,f))return{ok:!1,errorCode:"unsupported-operation",reason:g};if(r.isRepeatItemRoot&&d?.isRepeatItemRoot&&r.repeatOwnerKey&&r.repeatOwnerKey===d.repeatOwnerKey&&(u==="before"||u==="after")){let v=c,C=await this.graph.getTextWriteTarget(d.key,0);if(v?.kind==="value-binding"&&C?.kind==="value-binding"&&v.locator&&C.locator){let P=Io(v.locator),F=Io(C.locator);if(P&&F&&v.file===C.file&&DC(P.locator,F.locator)){let R=P.index,N=F.index,T=u==="before"?N-(R<N?1:0):N+(R<N?0:1);return this.buildPlan(t,n,[{order:0,file:v.file,type:"move-array-item",locator:P.locator,fromIndex:R,toIndex:T}],o)}}}if(r.isRepeatItemRoot&&xr(this.graph.getFileContent(r.file),r))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed item outside its collection"};let m=this.getRepeatBackedTemplateStructureReason(r),h=il(g)?g:m;if(h&&il(h)){let v=this.planRepeatTemplateInternalMove(t,n,r,s,o,u,d);if(v)return v;let C=this.planRepeatTemplateHoistMove(t,n,r,s,o,u,d);if(C)return C;let P=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,u,d);return P||{ok:!1,errorCode:"unsupported-operation",reason:h}}if(m)return{ok:!1,errorCode:"unsupported-operation",reason:m};let y=await this.getUpstreamBackedDescendantReason(r);if(y)return{ok:!1,errorCode:"unsupported-operation",reason:y};if(r.tag&&r.tag.toLowerCase()===r.tag){let v=ds(s,{kind:"native-tag",tag:r.tag});if(v)return{ok:!1,errorCode:"unsupported-operation",reason:v}}if(l)return this.planCrossFileMove(t,n,r,s,o,u,d);let x=Qc(this.graph.getFileContent(r.file),r,s);if(!x.ok)return{ok:!1,errorCode:"unsupported-operation",reason:x.reason??`Cannot move node because it depends on bindings outside the target scope: ${x.bindingNames.join(", ")}`};let E=[{order:0,file:r.file,type:"move-node",locator:Ee(r),targetParentLocator:Ee(s),placement:u,anchorLocator:d?Ee(d):void 0,selectionContext:Kn(s)}];return this.buildPlan(t,n,E,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,u=this.graph.getFileContent(r.file),d=ol(this.graph,r)??`<${r.component} />`,f=Jp(u,r);if(!f.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:f.reason??"Cannot move subtree across files"};if(c.push({order:l++,file:r.file,type:"remove-node",locator:Ee(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let m=r.tag??r.component,y={moduleSpecifier:cl(o.file,r.importedFrom),imports:r.exportName==="default"?[{kind:"default",local:m}]:[{kind:"named",imported:r.exportName,local:m===r.exportName?void 0:m}]};c.push({order:l++,file:o.file,type:"add-import",moduleSpecifier:y.moduleSpecifier,imports:y.imports}),c.push({order:l++,file:o.file,type:"insert-child",parentLocator:Ee(o),node:{jsx:d},placement:s,anchorLocator:a?Ee(a):void 0,selectionContext:Kn(o)})}else c.push({order:l++,file:o.file,type:"insert-child",parentLocator:Ee(o),node:{jsx:d},placement:s,anchorLocator:a?Ee(a):void 0,selectionContext:Kn(o)});let g=this.buildRemoveComponentImportStep(r,u);return g&&c.push({...g,order:l++}),this.buildPlan(t,n,c,i)}buildPlan(t,n,r,o){let s=[...new Set(r.map(a=>a.file))].map(a=>({file:a,content:this.graph.getFileContent(a),version:this.graph.getFileVersion(a),exists:!0,sha256:Re(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 Fm(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 yl from"@babel/generator";import{parse as tR}from"@babel/parser";import*as k from"@babel/types";import*as Ut from"@babel/types";import fl from"@babel/generator";import*as Ie from"@babel/types";var VC=typeof fl=="function"?fl:fl.default,KC=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,UC=/^((?:https?:)?\/\/)[^/@\s]+@/i,JC=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function Dm(e,t){let n=At(e.callee);if(!n)return null;if(n==="fetch")return pl(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(Lm(r))return pl(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(Lm(r))return pl(e.arguments[0],r,t,["ky client contract"])}return null}function pl(e,t,n,r){if(!e||Ie.isSpreadElement(e)||Ie.isJSXNamespacedName(e))return HC(t,n,r,"missing url argument");let o=Co(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 Co(e){if(Ie.isStringLiteral(e))return Er(e.value);if(Ie.isTemplateLiteral(e))return Er(XC(e));if(Ie.isBinaryExpression(e)&&e.operator==="+"){let t=Co(e.left),n=Co(e.right);return!t&&!n?void 0:Er(`${t??ml(e.left)}${n??ml(e.right)}`)}if(Ie.isMemberExpression(e)){let t=Bm(e);if(t)return`env:${t}`}if(!(Ie.isCallExpression(e)&&At(e.callee)==="new URL")){if(Ie.isNewExpression(e)&&Ie.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!Ie.isSpreadElement(t)?Co(t):void 0,o=n&&!Ie.isSpreadElement(n)?Co(n):void 0;return o&&r?Er(`${o} + ${r}`):r??o}if(Ie.isIdentifier(e))return`:${e.name}`}}function XC(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+=ml(r))}return t}function ml(e){if(Ie.isIdentifier(e))return`:${e.name}`;if(Ie.isMemberExpression(e)){let t=Bm(e);if(t)return`env:${t}`}return`:${zC(e)}`}function zC(e){return VC(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function Er(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(UC,"$1<redacted>@").replace(JC,"$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 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 HC(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function Lm(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function Bm(e){return!Ie.isMemberExpression(e.object)||!Ie.isIdentifier(e.object.object,{name:"process"})||!GC(e.object.property,"env")?null:Ie.isIdentifier(e.property)?e.property.name:Ie.isStringLiteral(e.property)?e.property.value:null}function GC(e,t){return Ie.isIdentifier(e)&&e.name===t}function At(e){if(Ie.isIdentifier(e))return e.name;if(Ie.isMemberExpression(e)){let t=At(e.object),n=Ie.isIdentifier(e.property)?e.property.name:Ie.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var YC=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),ZC=new Set(["getConfig","submit"]);function jm(e,t){let n=QC(At(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!YC.has(i))return null;let s=gl(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(!ZC.has(i))return null;let s=gl(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=gl(e,0)??qC(e,0,"path")??"/cms/:path",s=eR(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 QC(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 $m(e,t){let n=At(e);return n==="cms.settings"?{sourceKind:"vcp-cms-settings",sourceType:"cms-field",operation:"settings",endpointPattern:"/settings",confidence:"exact",evidence:[{file:t.file,symbol:n,reason:"VCP CMS settings facade"}]}:n==="cms.navigation"?{sourceKind:"vcp-cms-navigation",sourceType:"cms-field",operation:"navigation",endpointPattern:"/navigation",confidence:"exact",evidence:[{file:t.file,symbol:n,reason:"VCP CMS navigation facade"}]}:null}function Vm(e){let t=At(e.callee);return typeof t=="string"&&t.startsWith("cms.field.")}function gl(e,t){let n=e.arguments[t];return Ut.isStringLiteral(n)?n.value:null}function qC(e,t,n){let r=e.arguments[t];if(!Ut.isObjectExpression(r))return null;for(let o of r.properties)if(Ut.isObjectProperty(o)&&!o.computed&&(Ut.isIdentifier(o.key)&&o.key.name===n||Ut.isStringLiteral(o.key)&&o.key.value===n)&&Ut.isStringLiteral(o.value))return o.value.value;return null}function eR(e){return/^\/collections\/([^/]+)(?:\/|$)/.exec(e)?.[1]??null}function Km(e=4096){if(!Number.isSafeInteger(e)||e<1)throw new RangeError("Re-export relation capacity must be positive.");let t=new Map,n=new Set,r=o=>{let i=t.get(o.fromFile),s=i?.get(o.exportName),a=s?.get(o.targetFile);a?.get(o.maxImportDepth)===o&&(a.delete(o.maxImportDepth),a.size===0&&s.delete(o.targetFile),s.size===0&&i.delete(o.exportName),i.size===0&&t.delete(o.fromFile),n.delete(o))};return{resolve(o,i){let{fromFile:s,exportName:a,targetFile:c,maxImportDepth:l}=o,u=t.get(s)?.get(a)?.get(c)?.get(l);if(u)return u.pending;let d=i();n.size>=e&&r(n.values().next().value);let f={fromFile:s,exportName:a,targetFile:c,maxImportDepth:l,pending:d},g=t.get(s)??new Map,m=g.get(a)??new Map,h=m.get(c)??new Map;return h.set(l,f),m.set(c,h),g.set(a,m),t.set(s,g),n.add(f),d.catch(()=>{r(f)}),d}}}import*as K from"@babel/types";function vr(e,t,n=new Set){if(n.has(e))return;let r=new Set(n).add(e);if(K.isBooleanLiteral(e))return e.value;if(K.isUnaryExpression(e,{operator:"!"})){let c=vr(e.argument,t,r);return c===void 0?void 0:!c}if(K.isLogicalExpression(e)){let c=vr(e.left,t,r),l=vr(e.right,t,r);if(e.operator==="&&")return c===!1||l===!1?!1:c===!0?l:void 0;if(e.operator==="||")return c===!0||l===!0?!0:c===!1?l:void 0}if(!K.isCallExpression(e)||!K.isIdentifier(e.callee))return;let o=t.imports.get(e.callee.name);if(o?.importedName==="isProductionBuildPhase"&&/(?:^|\/)lib\/cms\/build-sample(?:\.[jt]s)?$/.test(o.source))return!1;let i=t.functions.get(e.callee.name);if(!i||n.has(i))return;let s=K.isExpression(i.body)?i.body:i.body.body.length===1&&K.isReturnStatement(i.body.body[0])?i.body.body[0].argument:null;if(!s||!K.isExpression(s))return;let a=i.params.flatMap(c=>K.isIdentifier(c)?[c.name]:[]);return vr(s,{imports:new Map([...t.imports].filter(([c])=>!a.includes(c))),functions:new Map([...t.functions].filter(([c])=>!a.includes(c)))},r.add(i))}function Jm(e){return K.isAwaitExpression(e)||K.isTSAsExpression(e)||K.isTSNonNullExpression(e)||K.isParenthesizedExpression(e)?Jm(e.type==="AwaitExpression"?e.argument:e.expression):e}function Um(e){return K.isMemberExpression(e)&&!e.computed&&K.isIdentifier(e.object)&&K.isIdentifier(e.property,{name:"id"})?e.object.name:void 0}function hl(e,t){if(K.isLogicalExpression(e,{operator:"&&"}))return hl(e.left,t)??hl(e.right,t);if(!K.isBinaryExpression(e,{operator:"==="}))return;let n=Um(e.left),r=Um(e.right);return n===t&&r!==t?r:r===t&&n!==t?n:void 0}function Xm(e){return K.isReturnStatement(e)?K.isNullLiteral(e.argument):K.isThrowStatement(e)?!0:K.isBlockStatement(e)&&e.body.length===1&&Xm(e.body[0])}async function zm(e,t,n){let r=new Map;if(!K.isBlockStatement(e.body))return r;let o=new Map,i=new Set,s=new Set;for(let a of e.body.body){let c=!1;if(K.traverseFast(a,d=>{d===t&&(c=!0)}),c)break;let l=d=>{if(!K.isFunction(d)){if(K.isAssignmentExpression(d)||K.isUpdateExpression(d)){let f=K.isAssignmentExpression(d)?d.left:d.argument;for(;K.isMemberExpression(f);)f=f.object;K.isIdentifier(f)&&s.add(f.name)}for(let f of K.VISITOR_KEYS[d.type]??[]){let g=d[f];for(let m of Array.isArray(g)?g:[g])K.isNode(m)&&l(m)}}};if(l(a),K.isVariableDeclaration(a,{kind:"const"}))for(let d of a.declarations){if(!K.isIdentifier(d.id)||!K.isExpression(d.init))continue;let f=Jm(d.init);if(!K.isCallExpression(f)||!K.isMemberExpression(f.callee)||f.callee.computed||!K.isIdentifier(f.callee.property,{name:"find"}))continue;let g=f.arguments[0];if(!(K.isArrowFunctionExpression(g)||K.isFunctionExpression(g))||!K.isIdentifier(g.params[0]))continue;let m=K.isExpression(g.body)?g.body:g.body.body.length===1&&K.isReturnStatement(g.body.body[0])?g.body.body[0].argument:null;if(!m||!K.isExpression(m))continue;let h=hl(m,g.params[0].name);if(!h)continue;let[y,x]=await Promise.all([n(f.callee.object),n(K.identifier(h))]);y?.sourceKind==="vcp-cms-collection"&&y.collection&&(y.operation==="listStrict"||y.operation==="list")&&x?.sourceKind==="vcp-cms-collection"&&(x.operation==="getByUrlStrict"||x.operation==="getByUrl")&&o.set(d.id.name,{record:h,collection:y.collection})}if(!K.isIfStatement(a)||!K.isUnaryExpression(a.test,{operator:"!"})||!K.isIdentifier(a.test.argument)||!Xm(a.consequent))continue;let u=o.get(a.test.argument.name);u&&(r.has(u.record)&&r.get(u.record)!==u.collection&&i.add(u.record),r.set(u.record,u.collection))}for(let a of[...i,...s])r.delete(a);return r}var bL=typeof yl=="function"?yl:yl.default,eg=new WeakMap;function tg(e){let t=new Map;return eg.set(t,new Map([...e].map(n=>[n.file,n]))),t}var nR={maxFunctionDepth:8,maxImportDepth:6},rR=new Set(["src","href","alt","poster","content","title","aria-label"]),Wm=new WeakMap;function oR(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 u=0;for(let d of e.elements.values()){let f={element:d,order:u++};d.importedFrom&&d.exportName&&o.imported.push(f);let g=o.local.get(d.sourceFile);g||(g=new Map,o.local.set(d.sourceFile,g));let m=g.get(d.tag)??[];m.push(f),g.set(d.tag,m)}r.set(e,o)}let i=o.local.get(t.file)?.get(n)??[],s=o.imported,a=[],c=0,l=0;for(;c<s.length||l<i.length;){let u=s[c],d=i[l];u&&(!d||u.order<d.order)?(a.push(u.element),c++):d&&(!u||d.order<u.order)?(a.push(d.element),l++):(a.push(u.element),c++,l++)}return a}async function ng(e){let t=e.element.attributes?.find(u=>u.name==="data-cms-collection"),n=t?.resolution?.status==="resolved"?t.resolution.value:t?.syntaxKind==="literal"?t.value:void 0,r=typeof n=="string"?n.trim():"",o=r?[{sourceKind:"vcp-cms-collection",sourceType:"cms-field",collection:r,targetKind:"attribute",targetName:"data-cms-collection",confidence:"exact",readonly:!0,evidence:[{file:e.file,reason:"Explicit CMS collection binding"}]}]:[];if(!e.element.textSegments.some(u=>u.source)&&!(e.element.attributes??[]).some(u=>(u.source||u.syntaxKind==="expression"&&u.resolution?.status!=="resolved")&&Gm(u,e.element))&&!e.graph.regions.some(u=>u.ownerKey===e.element.identity.key&&(u.kind==="repeat-region"||u.kind==="conditional-region")))return{hasDynamicData:o.length>0,bindings:o};let i=e.fileCache??new Map,s=Cl(e.file,e.source,i),a={file:e.file,analysis:s,readFile:e.readFile,exists:e.exists,fileCache:i,options:{...nR,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,paramArguments:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:mg(s,e.element.componentName),scopeFunction:Rl(s,e.element.componentName)};await rg(e.element.componentName,e.graph,a);let c=[...o];c.push(...await cR(e.element,e.graph,a),...await lR(e.element,e.graph,a));for(let u of e.element.textSegments){let d=await uR(u,e.element,e.graph,a);d&&c.push(Ss(d,"text","children"))}for(let u of e.element.attributes??[]){let d=Gm(u,e.element);if(!d)continue;let f=await sg(u.source,e.element,e.graph,a);if(!f&&u.syntaxKind==="expression"){let m=s.jsxElementsByRange.get(Sl(e.element.sourceRange))?.openingElement.attributes.find(h=>k.isJSXAttribute(h)&&k.isJSXIdentifier(h.name,{name:u.name}));k.isJSXExpressionContainer(m?.value)&&k.isExpression(m.value.expression)&&(f=await _e(m.value.expression,a))}f&&c.push(Ss(f,d,u.name))}let l=IR(c).sort(fg);return{hasDynamicData:l.length>0,bindings:l}}async function rg(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 oR(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 iR(l.importedFrom,l.exportName,n.file,n))&&s.push(l)}if(s.length===0)return;let a=new Map;for(let l of s){let u=`${n.file}#${e}<-${l.identity.key}`;if(!n.resolvingComponentProps.has(u)){n.resolvingComponentProps.add(u);try{let d=await ig(l.sourceFile,n);if(!d)continue;let f=Rr(d,n,{importDepth:n.importDepth+1});f.paramSources.clear(),f.scopeVariables=mg(d,l.componentName),f.scopeFunction=Rl(d,l.componentName),f.lexicalContext=void 0,await rg(l.componentName,t,f);let g=await sR(l,t,f);for(let[m,h]of g){if(!h)continue;let y=a.get(m)??[];y.push(h),a.set(m,y)}}finally{n.resolvingComponentProps.delete(u)}}}let c=new Map;for(let[l,u]of a){let d=Il(u);d.length===1&&c.set(l,d[0])}aR(o,c,n)}var Hm=new WeakMap;function iR(e,t,n,r){let o=Hm.get(r.fileCache);return o||(o=Km(),Hm.set(r.fileCache,o)),o.resolve({fromFile:e,exportName:t,targetFile:n,maxImportDepth:r.options.maxImportDepth},()=>og(e,t,n,r))}async function og(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 ig(e,r))?.imports.get(t);if(!s||!It(s.source))return!1;let a=await yg(e,s.source,r.exists);return a?a===n?!0:og(a,s.importedName,n,r,o):!1}async function sR(e,t,n){let r=new Map,o=n.analysis.jsxElementsByRange.get(Sl(e.sourceRange));if(o)for(let s of o.openingElement.attributes)!k.isJSXAttribute(s)||!k.isJSXIdentifier(s.name)||!k.isJSXExpressionContainer(s.value)||!k.isExpression(s.value.expression)||r.set(s.name.name,s.value.expression);let i=new Map;for(let[s,a]of r){let c=await ag(e.attributes?.find(l=>l.name===s)?.source??null,e,t,n)??await _e(a,n);c&&i.set(s,c)}return i}function Sl(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}async function ig(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 aR(e,t,n){if(k.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,bs(Object.fromEntries(t),n.file));return}if(k.isObjectPattern(e))for(let r of e.properties){if(!k.isObjectProperty(r)||r.computed||!k.isIdentifier(r.key))continue;let o=t.get(r.key.name);if(!o)continue;let i=k.isAssignmentPattern(r.value)?r.value.left:r.value;k.isIdentifier(i)&&n.paramSources.set(i.name,We(o))}}function Gm(e,t){return e.name==="dangerouslySetInnerHTML"?"richtext":rR.has(e.name)?"attribute":t.importedFrom||/^[A-Z]/.test(t.tag)?"component-prop":null}async function cR(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 Es(i.collectionSource,n);s&&r.push(Ss(Sn(s),"repeat-region",i.collectionExpression))}return r}async function lR(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 Es(i.conditionSource,n);s&&r.push(Ss(Sn(s),"conditional-region",i.conditionExpression))}return r}async function uR(e,t,n,r){return sg(e.source,t,n,r)}async function sg(e,t,n,r){let o=await ag(e,t,n,r);return o||Es(e,r)}async function ag(e,t,n,r){if(!e)return null;let o=dR(e.base,t,n);if(!o)return null;let i=await Es(o.collectionSource,r);return i?wo(i,e.path,!0):null}function dR(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 Es(e,t){if(!e)return null;let n=await El(e.base,t);return n?wo(n,e.path,!1):null}async function El(e,t){let n=t.paramSources.get(e);if(n)return We(n);if(t.variableCache.has(e))return CR(t.variableCache.get(e)??null);let r=Ir(e,t);if(r&&r!==t)return El(e,r);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let o=await pR(e,t);if(o)return t.variableCache.set(e,We(o)),t.resolvingVariables.delete(e),o;let i=t.scopeVariables?.has(e),s=i?t.scopeVariables.get(e):r?null:t.analysis.variables.get(e);if(s){let c=k.isArrayExpression(s)&&s.elements.length===0?await fR(e,t):await _e(s,t),l=t.recordCollections?.get(e);return c?.sourceKind==="vcp-cms-collection"&&!c.collection&&l&&(c.operation==="getByUrlStrict"||c.operation==="getByUrl")&&(c={...c,collection:l,confidence:"safe-derived",evidence:[...c.evidence,{file:t.file,symbol:e,reason:"record id matched CMS collection and missing membership exits before return"}]}),t.variableCache.set(e,c?We(c):null),t.resolvingVariables.delete(e),c}if(i||r)return t.resolvingVariables.delete(e),t.variableCache.set(e,null),null;let a=t.analysis.imports.get(e);if(a&&t.importDepth<t.options.maxImportDepth){let c=await gg(a,t);if(c){let l=Rr(c,t,{importDepth:t.importDepth+1}),u=hg(a,c);if(u){let g=(await Un(u,[],l)).returnSource;return t.variableCache.set(e,g?We(g):null),t.resolvingVariables.delete(e),g}let d=c.variables.get(a.importedName);if(d){let f=await _e(d,l);return t.variableCache.set(e,f?We(f):null),t.resolvingVariables.delete(e),f}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}function Ir(e,t){return t.scopeVariables?.has(e)||t.scopeFunction?.params.some(n=>En(n).includes(e))?t:t.lexicalContext?Ir(e,t.lexicalContext):void 0}function ms(e,t,n=new Set){if(k.isIdentifier(e)){let s=Ir(e.name,t);if(s&&s!==t)return ms(e,s,n)}if(n.has(e))return null;if(n.add(e),k.isStringLiteral(e))return e.value;if(!k.isIdentifier(e))return null;let r=Ir(e.name,t),o=t.paramArguments.get(e.name);if(o)return ms(o.expression,o.context,n);let i=t.scopeVariables?.has(e.name)?t.scopeVariables.get(e.name):r?null:t.analysis.variables.get(e.name);return i?ms(i,t,n):null}function bn(e,t,n=new Set){if(n.has(e))return null;let r=new Set(n).add(e);if(k.isStringLiteral(e))return e.value;if(k.isIdentifier(e)){if(/token|secret|password|authorization|cookie|credential/i.test(e.name))return":redacted";let o=Ir(e.name,t),i=o??t,s=i.paramArguments.get(e.name),a=i.scopeVariables?.has(e.name)?i.scopeVariables.get(e.name):o?null:i.analysis.variables.get(e.name);return(s?bn(s.expression,s.context,r):a?bn(a,i,r):null)??`:${e.name}`}if(k.isBinaryExpression(e,{operator:"+"})){let o=bn(e.left,t,r),i=bn(e.right,t,r);return o!==null&&i!==null?o+i:null}if(k.isTemplateLiteral(e)){let o=e.quasis[0]?.value.cooked??"";for(let[i,s]of e.expressions.entries()){if(!k.isExpression(s))return null;o+=(bn(s,t,r)??":param")+(e.quasis[i+1]?.value.cooked??"")}return o}if(k.isCallExpression(e)&&k.isIdentifier(e.callee)&&["encodeURIComponent","decodeURIComponent"].includes(e.callee.name)&&k.isExpression(e.arguments[0])){let o=bn(e.arguments[0],t,r);if(o===null||o.startsWith(":"))return o;try{return e.callee.name==="encodeURIComponent"?encodeURIComponent(o):decodeURIComponent(o)}catch{return null}}return k.isTSAsExpression(e)||k.isTSNonNullExpression(e)||k.isParenthesizedExpression(e)?bn(e.expression,t,r):null}async function fR(e,t){let n=t.scopeFunction;if(!n)return null;let r=[],o=!1,i=0,s=u=>{let d=!1;return k.traverseFast(u,f=>{k.isIdentifier(f,{name:e})&&(d=!0)}),d},a=u=>{let d=u;for(;k.isMemberExpression(d);)d=d.object;return k.isIdentifier(d,{name:e})},c=async(u,d)=>{if(!o){if(k.isFunction(u)){s(u)&&(o=!0);return}if(k.isVariableDeclarator(u)&&(En(u.id).includes(e)&&i++,u.init&&s(u.init)&&(o=!0)),(k.isAssignmentExpression(u)||k.isUpdateExpression(u))&&a(k.isAssignmentExpression(u)?u.left:u.argument)){o=!0;return}if(k.isUnaryExpression(u,{operator:"delete"})&&a(u.argument)){o=!0;return}if(k.isCallExpression(u)){if(k.isMemberExpression(u.callee)&&k.isIdentifier(u.callee.object,{name:e})){if(!k.isIdentifier(u.callee.property,{name:"push"})||u.callee.computed||!u.arguments.length){o=!0;return}for(let f of u.arguments){let g=k.isSpreadElement(f)?f.argument:f,m=k.isExpression(g)?await _e(g,d):null;m?r.push(xl(m)):o=!0}return}if(u.arguments.some(f=>s(f))){o=!0;return}}if(k.isForOfStatement(u)){let f=await _e(u.right,d),g=Rr(d.analysis,d),m=k.isVariableDeclaration(u.left)?u.left.declarations[0]?.id:u.left;f&&m&&ys(m,xl(f),g),await c(u.body,g);return}for(let f of k.VISITOR_KEYS[u.type]??[]){let g=u[f];for(let m of Array.isArray(g)?g:[g])k.isNode(m)&&await c(m,d)}}};await c(n.body,t);let l=Il(r);return!o&&i===1&&l.length===1?Sn(l[0]):null}async function pR(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 _e(o,t);if(i)return i}return null}async function _e(e,t){if(k.isIdentifier(e))return El(e.name,t);if(k.isMemberExpression(e)||k.isOptionalMemberExpression(e)){let n=k.isMemberExpression(e)?$m(e,{file:t.file}):null;if(n)return ug(n);let r=await mR(e,t);if(!r)return null;let o=kR(e);return wo(r,o,!1)}if(k.isAwaitExpression(e))return k.isExpression(e.argument)?_e(e.argument,t):null;if((k.isCallExpression(e)||k.isOptionalCallExpression(e))&&(k.isMemberExpression(e.callee)||k.isOptionalMemberExpression(e.callee))&&!e.callee.computed&&k.isIdentifier(e.callee.property)&&["trim","trimStart","trimEnd"].includes(e.callee.property.name)&&e.arguments.length===0&&k.isExpression(e.callee.object))return kr(await _e(e.callee.object,t));if(k.isCallExpression(e))return cg(e,t);if(k.isObjectExpression(e)){let n=await lg(e,t);return Object.keys(n).length>0?bs(n,t.file):null}if(k.isArrayExpression(e)){let n={};for(let[r,o]of e.elements.entries()){if(!k.isExpression(o))continue;let i=await _e(o,t);i&&(n[String(r)]=i)}return Object.keys(n).length?bs(n,t.file):null}if(k.isConditionalExpression(e)){let n=await _e(e.consequent,t),r=await _e(e.alternate,t);return kr(Zm(n,r))}if(k.isLogicalExpression(e)){let n=await _e(e.left,t),r=await _e(e.right,t);return kr(Zm(n,r))}return k.isTSAsExpression(e)||k.isTSSatisfiesExpression(e)||k.isTSNonNullExpression(e)||k.isTypeCastExpression(e)||k.isParenthesizedExpression(e)?_e(e.expression,t):null}async function mR(e,t){let n=e;for(;k.isMemberExpression(n)||k.isOptionalMemberExpression(n);)n=n.object;return k.isExpression(n)?_e(n,t):null}async function cg(e,t){let n=e.arguments[0],r=k.isExpression(n)?ms(n,t):null,o=jm(r!==null&&!k.isStringLiteral(n)?{...e,arguments:[k.stringLiteral(r),...e.arguments.slice(1)]}:e,{file:t.file,imports:t.analysis.imports});if(o){if((o.operation==="getByUrl"||o.operation==="getByUrlStrict")&&k.isExpression(n)){let g=bn(n,t);g?.startsWith("/")&&(o.endpointPattern=Er(g))}return ug(o)}if(At(e.callee)==="Promise.all"&&k.isArrayExpression(n))return _e(n,t);if(Vm(e)){let g=e.arguments[0];if(g&&k.isExpression(g))return kr(await _e(g,t))}let i=await gR(e,t);if(i)return i;let s=Dm(e,{file:t.file});if(s)return{sourceKind:s.sourceKind,sourceType:"api-field",endpointPattern:s.endpointPattern,valuePath:s.valuePath,confidence:s.confidence,readonly:!0,evidence:s.evidence};let a=await xR(e,t);if(a)return a;let c=await bR(e,t);if(c)return c;let l=await SR(e,t);if(l)return l;let u=await ER(e,t);if(u)return u;let d=[];for(let g of e.arguments)if(k.isExpression(g)){let m=await _e(g,t);m&&d.push(m)}let f=Il(d);return f.length===1?kr(f[0]):null}async function gR(e,t){let n=At(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=yR(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(k.isIdentifier(s)){let a=await Cr(s.name,t);if(a)return(await Un(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!k.isObjectExpression(r))return gs(t.file,`${n} without static options`);let o=hR(r,"queryFn");if(!o)return gs(t.file,`${n} without queryFn`);if(k.isIdentifier(o)){let i=await Cr(o.name,t);return i?(await Un(i.node,[],i.context)).returnSource:gs(t.file,`${n} queryFn unresolved`)}return k.isArrowFunctionExpression(o)||k.isFunctionExpression(o)?(await Un(o,[],t)).returnSource:k.isCallExpression(o)?cg(o,t):null}function hR(e,t){for(let n of e.properties){if(!k.isObjectProperty(n)||!k.isExpression(n.value))continue;if(vl(n)===t)return n.value}return null}function yR(e,t,n){return k.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 xR(e,t){if(!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property))return null;let n=e.callee.property.name;if(!["map","filter","slice","sort","toSorted"].includes(n))return null;let r=k.isExpression(e.callee.object)?await _e(e.callee.object,t):null;if(!r)return null;if(n!=="map")return Sn(r);let o=e.arguments[0];if(k.isIdentifier(o)){let i=await Cr(o.name,t);if(!i)return Sn(r);let s=await Un(i.node,[r],i.context);return{...Sn(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(k.isArrowFunctionExpression(o)||k.isFunctionExpression(o)){let i=await Un(o,[r],t);return{...Sn(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return Sn(r)}async function bR(e,t){return!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property,{name:"json"})||!k.isExpression(e.callee.object)?null:_e(e.callee.object,t)}async function SR(e,t){return!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property,{name:"then"})||!k.isExpression(e.callee.object)?null:kr(await _e(e.callee.object,t))}async function ER(e,t){if(!k.isIdentifier(e.callee))return null;let n=await Cr(e.callee.name,t);if(!n)return null;let r=[];for(let i of e.arguments){if(!k.isExpression(i)){r.push(gs(t.file,`unsupported argument for ${e.callee.name}`));continue}let s=await _e(i,t);r.push(s)}return(await Un(n.node,r,n.context,{arguments:e.arguments,context:t})).returnSource}async function Cr(e,t,n=new Set){let r=t.paramArguments.get(e);if(r&&!n.has(r.expression)){if(n.add(r.expression),bl(r.expression))return{node:r.expression,context:r.context};if(k.isIdentifier(r.expression))return Cr(r.expression.name,r.context,n)}let o=t.analysis.functions.get(e);if(o)return{node:o,context:t};let i=t.analysis.imports.get(e);if(!i||t.importDepth>=t.options.maxImportDepth)return null;let s=await gg(i,t);if(!s)return null;let a=Rr(s,t,{importDepth:t.importDepth+1}),c=hg(i,s);return c?{node:c,context:a}:Cr(i.importedName,a)}async function Un(e,t,n,r){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let o=Rr(n.analysis,n,{functionDepth:n.functionDepth+1}),i=n.analysis.functionParents.get(e),s=n;for(;s&&(s.analysis!==n.analysis||s.scopeFunction!==i);)s=s.lexicalContext;o.lexicalContext=s,o.paramSources=new Map,o.paramArguments=new Map,o.recordCollections=void 0,o.scopeVariables=n.analysis.functionVariables.get(e),o.scopeFunction=e,e.params.forEach((d,f)=>{for(let y of En(d))o.paramSources.delete(y),o.paramArguments.delete(y);let g=k.isAssignmentPattern(d)?d.left:d,m=r?.arguments[f];k.isIdentifier(g)&&k.isExpression(m)&&r&&o.paramArguments.set(g.name,{expression:m,context:r.context});let h=t[f];h&&ys(d,xl(h),o)});let a=vR(e,o),c=null,l,u=!1;for(let d of a){let f=Rr(n.analysis,o);if(f.recordCollections=await zm(e,d,m=>_e(m,o)),k.isObjectExpression(d)){l={...l??{},...await lg(d,f)},c=c??bs(l,n.file);continue}let g=await _e(d,f);if(g){if(!c){c=g;continue}let m=kl(c,g);if(!m){u=!0,c=null;continue}c=m}}return{returnSource:u?null:c,...l?{objectReturnMap:l}:{}}}function ys(e,t,n){if(k.isIdentifier(e)){n.paramSources.set(e.name,We(t));return}if(k.isAssignmentPattern(e)){ys(e.left,t,n);return}if(k.isObjectPattern(e))for(let r of e.properties){if(!k.isObjectProperty(r)||r.computed||!k.isIdentifier(r.key))continue;let o=wo(t,[{kind:"property",name:r.key.name}],!0),i=k.isAssignmentPattern(r.value)?r.value.left:r.value;o&&ys(i,o,n)}}function vR(e,t){if(k.isArrowFunctionExpression(e)&&k.isExpression(e.body))return[e.body];let n=[],r=e.body;if(!k.isBlockStatement(r))return n;let o=i=>{if(k.isFunction(i)&&i!==e)return;if(k.isReturnStatement(i)){i.argument&&k.isExpression(i.argument)&&n.push(i.argument);return}if(k.isIfStatement(i)){let a=vr(i.test,{imports:new Map([...t.analysis.imports].filter(([c])=>!Ir(c,t))),functions:t.analysis.functions});if(a!==void 0){a?o(i.consequent):i.alternate&&o(i.alternate);return}}let s=k.VISITOR_KEYS[i.type];for(let a of s??[]){let c=i[a];if(Array.isArray(c))for(let l of c)k.isNode(l)&&o(l);else k.isNode(c)&&o(c)}};return o(r),n}async function lg(e,t){let n={};for(let r of e.properties){if(!k.isObjectProperty(r))continue;let o=vl(r);if(!o||!k.isExpression(r.value))continue;let i=await _e(r.value,t);i&&(n[o]=i)}return n}function vl(e){return k.isIdentifier(e.key)&&!e.computed?e.key.name:k.isStringLiteral(e.key)?e.key.value:null}function kR(e){let t=[],n=e;for(;k.isMemberExpression(n)||k.isOptionalMemberExpression(n);){let r=n.property;n.computed?k.isStringLiteral(r)?t.unshift({kind:"property",name:r.value}):k.isNumericLiteral(r)&&t.unshift({kind:"index",index:r.value}):k.isIdentifier(r)&&t.unshift({kind:"property",name:r.name}),n=n.object}return k.isIdentifier(n),t}function wo(e,t,n){if(t.length===0)return We(e);let r=t[0],o=r?.kind==="property"?r.name:r?String(r.index):null;if(e.fieldMap&&o!==null){let s=e.fieldMap[o];return s?wo(s,t.slice(1),n):null}let i=We(e);if(i.sourceType==="cms-field"){let s=t.filter(a=>a.kind==="property").map(a=>a.name);return s[0]==="data"&&s[1]==="items"?(i.valuePath=Ro(i.valuePath,"data.items[]"),i.cmsFieldRoot=!1,i):s[0]==="fields"?(i.fieldPath=Ro(i.fieldPath,s.slice(1).join(".")),i.cmsFieldRoot=!0,i):i.cmsFieldRoot||n||i.fieldMap?(i.fieldPath=Ro(i.fieldPath,s.join(".")),i):(i.valuePath=Ro(i.valuePath,Ym(t)),i)}return i.valuePath=Ro(i.valuePath,Ym(t)),i}function Ym(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function Ro(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function ug(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 Sn(e){let t=We(e);return t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function xl(e){let t=We(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&(t.cmsFieldRoot=!1),t}function kr(e){return e?{...We(e),confidence:e.confidence==="unknown"?"unknown":"safe-derived",evidence:[...e.evidence,{file:e.evidence[0]?.file??"unknown",reason:"safe derived expression"}]}:null}function Zm(e,t){return e?t?kl(e,t):We(e):t?We(t):null}function kl(e,t){if(xs(e)!==xs(t))return null;let n=pg(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function Il(e){let t=new Map;for(let n of e){let r=xs(n),o=t.get(r);t.set(r,o?kl(o,n):We(n))}return[...t.values()]}function xs(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,xs(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 bs(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 gs(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function Ss(e,t,n){return{sourceKind:e.sourceKind,sourceType:e.sourceType,...e.endpointPattern?{endpointPattern:e.endpointPattern}:{},...e.operation?{operation:e.operation}:{},...e.collection?{collection:e.collection}:{},...e.fieldPath?{fieldPath:e.fieldPath}:{},...e.valuePath?{valuePath:e.valuePath}:{},targetKind:t,targetName:n,confidence:e.confidence,readonly:!0,evidence:e.evidence.map(r=>({...r}))}}function dg(e){let t=[...e].sort(fg),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 fg(e,t){return Qm(e.targetKind)-Qm(t.targetKind)||pg(e.confidence,t.confidence)||qm(e.sourceKind)-qm(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function Qm(e){return{"repeat-region":0,"conditional-region":1,text:2,richtext:3,attribute:4,"component-prop":5}[e]}function qm(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function pg(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=eg.get(n)?.get(e),i=o?.source===t?o.ast:tR(t,{sourceType:"module",plugins:["jsx","typescript"]}),s={file:e,source:t,ast:i,variables:new Map,functions:new Map,imports:new Map,stateSetters:new Map,stateSetterCandidates:new Map,jsxElementsByRange:new Map,functionVariables:new WeakMap,functionParents:new WeakMap},a=[],c=[];k.traverse(i,{enter(d){switch(k.isFunction(d)&&(s.functionParents.set(d,a.at(-1)??null),a.push(d)),d.type){case"CallExpression":c.push(d);break;case"JSXElement":{let f=d.loc;if(!f)return;let g=Sl({startLine:f.start.line,startColumn:f.start.column,endLine:f.end.line,endColumn:f.end.column});s.jsxElementsByRange.has(g)||s.jsxElementsByRange.set(g,d);break}case"ImportDeclaration":{let f=d.source.value;for(let g of d.specifiers)k.isImportSpecifier(g)&&k.isIdentifier(g.local)?s.imports.set(g.local.name,{source:f,importedName:k.isIdentifier(g.imported)?g.imported.name:g.imported.value,localName:g.local.name,isDefault:!1}):k.isImportDefaultSpecifier(g)&&s.imports.set(g.local.name,{source:f,importedName:"default",localName:g.local.name,isDefault:!0});break}case"FunctionDeclaration":{d.id?.name&&s.functions.set(d.id.name,d);break}case"VariableDeclarator":{let f=a.at(-1),g=f&&(k.isFunctionDeclaration(f)||k.isFunctionExpression(f)||k.isArrowFunctionExpression(f))?f:null,m=g?s.functionVariables.get(g)??new Map:s.variables;g&&!s.functionVariables.has(g)&&s.functionVariables.set(g,m);for(let[h,y]of hs(d.id,k.isExpression(d.init)?d.init:null))m.set(h,y);if(k.isArrayPattern(d.id)&&k.isCallExpression(d.init)&&At(d.init.callee)==="useState"){let[h,y]=d.id.elements;k.isIdentifier(h)&&k.isIdentifier(y)&&s.stateSetters.set(h.name,y.name)}k.isIdentifier(d.id)&&bl(d.init)&&s.functions.set(d.id.name,d.init);break}case"ExportNamedDeclaration":{let f=d.declaration,g=d.source?.value;if(g)for(let m of d.specifiers){if(!k.isExportSpecifier(m))continue;let h=k.isIdentifier(m.exported)?m.exported.name:m.exported.value,y=m.local.name;s.imports.set(h,{source:g,importedName:y,localName:h,isDefault:y==="default"})}if(k.isFunctionDeclaration(f)&&f.id?.name&&s.functions.set(f.id.name,f),k.isVariableDeclaration(f))for(let m of f.declarations)k.isIdentifier(m.id)&&bl(m.init)&&s.functions.set(m.id.name,m.init);break}case"ExportDefaultDeclaration":{let f=d.declaration;if((k.isFunctionDeclaration(f)||k.isFunctionExpression(f)||k.isArrowFunctionExpression(f))&&s.functions.set("default",f),k.isIdentifier(f)){let g=s.functions.get(f.name);g&&s.functions.set("default",g)}break}}},exit(d){k.isFunction(d)&&a.pop()}});let l=new Set(s.stateSetters.values()),u=(d,f)=>{let g=s.stateSetterCandidates.get(d)??[];g.push(f),s.stateSetterCandidates.set(d,g)};if(l.size>0)for(let d of c){let f=k.isIdentifier(d.callee)?d.callee.name:null;f&&l.has(f)&&k.isExpression(d.arguments[0])&&u(f,d.arguments[0]);let g=new Set;for(let m of d.arguments)k.isIdentifier(m)&&m.name!==f&&l.has(m.name)&&g.add(m.name);for(let m of g)u(m,d)}return n.set(e,s),s}function hs(e,t){return k.isIdentifier(e)?[[e.name,t]]:k.isAssignmentPattern(e)?hs(e.left,t):k.isArrayPattern(e)?e.elements.flatMap((n,r)=>n&&!k.isRestElement(n)?hs(n,t?k.memberExpression(t,k.numericLiteral(r),!0):null):[]):k.isObjectPattern(e)?e.properties.flatMap(n=>{if(!k.isObjectProperty(n)||n.computed)return[];let r=vl(n);return r?hs(n.value,t?k.memberExpression(t,k.stringLiteral(r),!0):null):[]}):[]}function En(e){return!e||k.isVoidPattern(e)?[]:k.isIdentifier(e)?[e.name]:k.isObjectPattern(e)?e.properties.flatMap(t=>k.isObjectProperty(t)?En(t.value):En(t.argument)):k.isArrayPattern(e)?e.elements.flatMap(t=>t?En(k.isRestElement(t)?t.argument:t):[]):k.isAssignmentPattern(e)?En(e.left):k.isRestElement(e)?En(e.argument):[]}function bl(e){return k.isFunctionExpression(e)||k.isArrowFunctionExpression(e)}function mg(e,t){let n=Rl(e,t);return n?e.functionVariables.get(n):void 0}function Rl(e,t){return e.functions.get(t)??e.functions.get("default")}async function gg(e,t){let n=await yg(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return Cl(n,r,t.fileCache)}function hg(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function yg(e,t,n){return It(t)?Cn(e,t,n):null}function Rr(e,t,n={}){return{file:e.file,analysis:e,readFile:t.readFile,exists:t.exists,fileCache:t.fileCache,options:t.options,variableCache:new Map,functionDepth:n.functionDepth??t.functionDepth,importDepth:n.importDepth??t.importDepth,paramSources:new Map(t.paramSources),paramArguments:e===t.analysis?new Map(t.paramArguments):new Map,resolvingVariables:new Set,resolvingComponentProps:t.resolvingComponentProps,scopeVariables:e===t.analysis?t.scopeVariables:void 0,scopeFunction:e===t.analysis?t.scopeFunction:void 0,lexicalContext:e===t.analysis?t.lexicalContext:void 0,recordCollections:e===t.analysis?t.recordCollections:void 0}}function CR(e){return e?We(e):null}function We(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,We(n)]))}:{}}}import*as Nl from"@babel/parser";import wl from"@babel/traverse";import*as ee from"@babel/types";import{classifySiteEditPropertyName as RR}from"@vcp-dev/contracts";var Pl=typeof wl=="function"?wl:wl.default;function Al(e){let t=RR(e.propertyName);if(t.owner!=="generic")return pt("invalid-property",t.diagnostic?.message??`Property '${e.propertyName}' is not a generic property`);let n=e.selectionRef;if(!n)return pt("missing-selection-ref","A repeat property target requires a complete selection reference");if(n.key!==e.element.identity.key)return pt("selection-mismatch","Selection reference does not identify the requested element");if(n.instanceIndex===void 0)return pt("missing-instance-index","A repeat property target requires an instance index");let r;try{r=Nl.parse(e.source,{sourceType:"module",plugins:["typescript","jsx"]})}catch(y){return pt("repeat-not-found",`Unable to parse repeat source: ${y instanceof Error?y.message:String(y)}`)}let o=wR(r,e.element.sourceRange);if(!o)return pt("repeat-not-found","The selected element is not inside a supported map repeat");if(!ee.isIdentifier(o.callback.params[0]))return pt("unsupported-callback","Repeat property materialization requires an identifier callback item");let i=NR(r,o.collection,e.file,e.sources);if(!i)return pt("collection-not-found","The repeat collection is not a visible local static array");let{array:s,locator:a,sourceFile:c}=i,l=[],u=[];for(let[y,x]of s.elements.entries()){if(!x||!ee.isObjectExpression(x)||!kg(x))return pt("unsafe-collection","Repeat materialization requires an array of local static objects without spreads");let E=[{kind:"index",index:y}];l.push(E),u.push({kind:"value",root:a.root,path:E})}let d=u.length;if(n.instanceCount!==void 0&&n.instanceCount!==d)return pt("count-mismatch",`Selection reports ${n.instanceCount} instances but the source collection has ${d}`);let f=n.instanceIndex;if(f>=d)return pt("index-out-of-range",`Selected repeat instance ${f} is outside the source collection`);let g=s.elements[f];if(!g||!ee.isObjectExpression(g))return pt("unsafe-collection","Selected repeat item is not an object");let m=MR(e.element,e.propertyName),h=FR(g,e.propertyName);return h?{ok:!0,sourceFile:c,templateFile:e.file,collectionLocator:a,parentObjectLocators:u,selectedParentObjectLocator:u[f],sourceItemIndex:f,sourceItemPath:l[f],collectionIndexMap:Array.from({length:d},(y,x)=>x),callbackItemName:o.callback.params[0].name,targetElementLocator:{kind:"jsx-node",strategy:"structural-path",file:e.element.identity.file,component:e.element.identity.component,structuralPath:e.element.identity.structuralPath,expectedRange:e.element.sourceRange},propertyName:e.propertyName,propertyState:h,selectedResolution:_R(g,e.propertyName),...m?{property:m}:{},selectionRef:n}:pt("unsafe-property-source",`Property '${e.propertyName}' has a dynamic or unsupported source in the repeat item`)}function wR(e,t){let n=[];return Pl(e,{CallExpression(r){let o=xg(r.node);o&&Sg(o.callback,t)&&n.push({...o,span:bg(r.node)})},OptionalCallExpression(r){let o=xg(r.node);o&&Sg(o.callback,t)&&n.push({...o,span:bg(r.node)})}}),n.sort((r,o)=>r.span-o.span),n[0]??null}function xg(e){let t=e.callee;if(!ee.isMemberExpression(t)&&!ee.isOptionalMemberExpression(t)||t.computed||!ee.isIdentifier(t.property)||t.property.name!=="map"||!ee.isExpression(t.object))return null;let n=e.arguments[0];return!n||!ee.isExpression(n)||!ee.isArrowFunctionExpression(n)&&!ee.isFunctionExpression(n)?null:{collection:t.object,callback:n}}function NR(e,t,n,r){let o=No(t);if(o&&ee.isArrayExpression(o))return{array:o,locator:{kind:"value",root:{kind:"expression",sourceRange:Cg(o)}},sourceFile:n};if(!ee.isIdentifier(t))return null;let i=[];if(Pl(e,{VariableDeclarator(s){ee.isIdentifier(s.node.id)&&s.node.id.name===t.name&&s.node.init&&i.push(s.node)}}),i.length===1){let s=No(i[0].init);return!s||!ee.isArrayExpression(s)?null:{array:s,locator:{kind:"value",root:{kind:"binding",name:t.name}},sourceFile:n}}return PR(e,t.name,n,r)}function PR(e,t,n,r){if(!r)return null;for(let o of e.program.body){if(!ee.isImportDeclaration(o))continue;let i=o.specifiers.find(f=>f.local.name===t);if(!i||!ee.isStringLiteral(o.source)||!ee.isImportSpecifier(i))continue;let s=TR(n,o.source.value,r);if(!s)return null;let a=ee.isIdentifier(i.imported)?i.imported.name:i.imported.value,c=r.get(s);if(c===void 0)return null;let l;try{l=Nl.parse(c,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}let u=AR(l,a),d=u?No(u):null;return!d||!ee.isArrayExpression(d)?null:{array:d,locator:{kind:"value",root:{kind:"binding",name:a}},sourceFile:s}}return null}function AR(e,t){let n=null;return Pl(e,{VariableDeclarator(r){n||!ee.isIdentifier(r.node.id)||r.node.id.name!==t||!r.node.init||!ee.isExpression(r.node.init)||(n=r.node.init)}}),n}function TR(e,t,n){let r=In(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 No(e){return ee.isParenthesizedExpression(e)?No(e.expression):ee.isTSAsExpression(e)?vg(e.typeAnnotation)?No(e.expression):null:ee.isTSSatisfiesExpression(e)?null:e}function vg(e){return ee.isTSTypeReference(e)&&ee.isIdentifier(e.typeName)&&e.typeName.name==="const"}function kg(e){return e.properties.every(t=>!ee.isObjectProperty(t)||t.computed||!ee.isExpression(t.value)?!1:vs(t.value))}function vs(e){if(ee.isTSAsExpression(e)&&vg(e.typeAnnotation))return vs(e.expression);if(ee.isTSSatisfiesExpression(e))return!1;if(ee.isArrayExpression(e))return e.elements.every(n=>!n||ee.isSpreadElement(n)||!ee.isExpression(n)?!1:vs(n));if(ee.isObjectExpression(e))return kg(e);let t=Bt(e);return t.status==="resolved"||t.status==="undefined"}function FR(e,t){let n=e.properties.filter(o=>ee.isObjectProperty(o)&&Ig(o.key)===t);if(n.length>1)return null;let r=n[0];return r?ee.isExpression(r.value)?vs(r.value)?"static":ee.isIdentifier(r.value)||ee.isMemberExpression(r.value)?"binding":null:null:"missing"}function _R(e,t){let n=e.properties.filter(o=>ee.isObjectProperty(o)&&Ig(o.key)===t);if(n.length>1)return{status:"unresolved"};let r=n[0];return!r||!ee.isExpression(r.value)?{status:"undefined"}:Bt(r.value)}function MR(e,t){let n=e.attributes?.filter(r=>r.name===t)??[];return n.length===1?n[0]:void 0}function Ig(e){return ee.isIdentifier(e)?e.name:ee.isStringLiteral(e)?e.value:ee.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 bg(e){return e.start==null||e.end==null?Number.MAX_SAFE_INTEGER:e.end-e.start}function Sg(e,t){let n=Cg(e);return Eg(n.startLine,n.startColumn,t.startLine,t.startColumn)<=0&&Eg(n.endLine,n.endColumn,t.endLine,t.endColumn)>=0}function Eg(e,t,n,r){return e===n?t-r:e-n}function pt(e,t){return{ok:!1,errorCode:e,reason:t}}import{classifySiteEditPropertyName as xw}from"@vcp-dev/contracts";import*as ne from"@babel/types";import _o from"node:path";import*as j from"@babel/types";import*as Tg from"@babel/parser";import Tl from"@babel/traverse";import*as ae from"@babel/types";function Is(e,t){let n=[],r=e;for(;ae.isMemberExpression(r);){if(r.computed)if(ae.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(ae.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!ae.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!ae.isIdentifier(r)||r.name!==t?null:n}function Rg(e){if(ae.isIdentifier(e))return{base:e.name,path:[]};if(!ae.isMemberExpression(e))return null;let t=[],n=e;for(;ae.isMemberExpression(n);){if(n.computed)if(ae.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(ae.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!ae.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return ae.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 Jt=Symbol("not-closed-literal");function ks(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:Jt;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":return ks(e.expression);case"ArrayExpression":{let t=[];for(let n of e.elements){if(!n||ae.isSpreadElement(n))return Jt;let r=ks(n);if(r===Jt)return Jt;t.push(r)}return t}case"ObjectExpression":{let t={};for(let n of e.properties){if(!ae.isObjectProperty(n)||n.computed||n.shorthand||!ae.isExpression(n.value))return Jt;let r=ae.isIdentifier(n.key)?n.key.name:ae.isStringLiteral(n.key)?n.key.value:null;if(!r)return Jt;let o=ks(n.value);if(o===Jt)return Jt;t[r]=o}return t}default:return Jt}}function wg(e){let{resolveBindingTarget:t}=e;async function n(i,s,a,c,l,u,d){let f=ks(i);if(f!==Jt)return f;if(!ae.isTemplateLiteral(i)){if(ae.isTSAsExpression(i)||ae.isTSSatisfiesExpression(i)||ae.isTSNonNullExpression(i))return await n(i.expression,s,a,c,l,u,d);if(ae.isIdentifier(i)){let g=s.getBinding(i.name);if(!g)return;let m=await t({currentFile:a,binding:g,readFile:c,exists:l,fileCache:u,visited:d});return m?.kind==="static"?m.value:void 0}if(ae.isArrayExpression(i)){let g=[];for(let m of i.elements){if(!m||ae.isSpreadElement(m))return;let h=await r(m,s,a,c,l,u,d);if(h===void 0)return;g.push(h)}return g}if(ae.isObjectExpression(i)){let g={};for(let m of i.properties){if(!ae.isObjectProperty(m)||m.computed)return;let h=null;if(ae.isIdentifier(m.key)?h=m.key.name:ae.isStringLiteral(m.key)&&(h=m.key.value),!h)return;if(m.shorthand){if(!ae.isIdentifier(m.value))return;let x=await r(m.value,s,a,c,l,u,d);if(x===void 0)return;g[h]=x;continue}if(!ae.isExpression(m.value))return;let y=await r(m.value,s,a,c,l,u,d);y!==void 0&&(g[h]=y)}return g}if(ae.isMemberExpression(i)){let g=await o(i,s,a,c,l,u,d);if(!g)return;let m=s.getBinding(g.base);if(!m)return;let h=await t({currentFile:a,binding:m,readFile:c,exists:l,fileCache:u,visited:d});return!h||h.kind!=="static"?void 0:Qe(h.value,g.path)}}}async function r(i,s,a,c,l,u,d){if(!ae.isSpreadElement(i))return await n(i,s,a,c,l,u,d)}async function o(i,s,a,c,l,u,d){if(ae.isIdentifier(i))return{base:i.name,path:[]};if(!ae.isMemberExpression(i))return null;let f=[],g=i;for(;ae.isMemberExpression(g);){if(g.computed){let m=g.property;if(ae.isNumericLiteral(m))f.unshift({kind:"index",index:m.value});else if(ae.isStringLiteral(m))f.unshift({kind:"property",name:m.value});else{let h=ae.isExpression(m)?await n(m,s,a,c,l,u,d):void 0;if(typeof h=="string")f.unshift({kind:"property",name:h});else if(Number.isInteger(h))f.unshift({kind:"index",index:h});else return null}}else{if(!ae.isIdentifier(g.property))return null;f.unshift({kind:"property",name:g.property.name})}g=g.object}return ae.isIdentifier(g)?{base:g.name,path:f}:null}return{normalizeExpressionWithScope:o,evaluateStaticExpression:n}}var Fg=typeof Tl=="function"?Tl:Tl.default,Ng=new WeakMap;function _g(e){try{return Tg.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Cs(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=_g(n);return e.set(t,{source:n,ast:o}),o}function Rs(e,t){return Fl(Po(e).expressionRanges,t,!1)}function Mg(e,t){return Po(e).exactExpressions.get(Og(t))??null}function ws(e,t){return Fl(Po(e).jsxRanges,t,!0)}function Po(e){let t=Ng.get(e);if(t)return t;let n={expressions:[],expressionRanges:[],jsxRanges:[],exactExpressions:new Map};return Fg(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=Og(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(Ag),n.jsxRanges.sort(Ag),Ng.set(e,n),n}function Pg(e,t){let n=Ao(e.node);return n?{path:e,range:n,traversalIndex:t,span:(e.node.end??0)-(e.node.start??0)}:null}function Og(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}function Ag(e,t){return e.range.startLine-t.range.startLine||e.range.startColumn-t.range.startColumn||e.traversalIndex-t.traversalIndex}function Fl(e,t,n,r){let o=0,i=e.length;for(;o<i;){let c=o+Math.floor((i-o)/2),l=e[c].range;l.startLine<t.startLine||l.startLine===t.startLine&&l.startColumn<t.startColumn?o=c+1:i=c}let s=null,a=n?1/0:-1;for(let c=o;c<e.length;c++){let l=e[c],u=l.range;if(u.startLine>t.endLine||u.startLine===t.endLine&&u.startColumn>t.endColumn)break;if(u.endLine>t.endLine||u.endLine===t.endLine&&u.endColumn>t.endColumn||r&&!r(l.path))continue;((n?l.span<a:l.span>a)||l.span===a&&(!s||l.traversalIndex>s.traversalIndex))&&(s=l,a=l.span)}return s?.path??null}function Ao(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 wr(e,t){if(t)return _l(e,t);let n=Rg(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function _l(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function To(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of Po(e).expressions){if(_l(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function Lg(e,t,n,r){return Fl(Po(e).expressionRanges,r,!0,o=>_l(o.node,t)===n)}function Nr(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function Fo(e){let t=null;if(Fg(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}async function Tt(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=_g(o),s={source:o,ast:i};return n.set(e,s),s}function OR(e){return j.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:j.isMemberExpression(e.callee)&&j.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function LR(e){if(!j.isNewExpression(e)||!j.isIdentifier(e.callee,{name:"Proxy"})||e.arguments.length!==2||!j.isIdentifier(e.arguments[0])||!j.isObjectExpression(e.arguments[1])||e.arguments[1].properties.length!==1)return null;let[t]=e.arguments[1].properties;if(!j.isObjectMethod(t)||t.kind!=="method"||t.computed||t.async||t.generator||!j.isIdentifier(t.key,{name:"get"})||t.params.length!==3||!t.params.every(j.isIdentifier)||t.body.body.length!==2)return null;let[n,r,o]=t.params,[i,s]=t.body.body;if(j.isIfStatement(i)&&j.isBlockStatement(i.consequent)&&i.consequent.body.length!==1)return null;let a=j.isIfStatement(i)?i.test:null,c=a&&j.isLogicalExpression(a,{operator:"&&"})?a.right:null,l=j.isIfStatement(i)?j.isBlockStatement(i.consequent)?i.consequent.body[0]:i.consequent:null,u=j.isReturnStatement(s)?s.argument:null;return!a||!j.isLogicalExpression(a,{operator:"&&"})||!j.isBinaryExpression(a.left,{operator:"==="})||!j.isUnaryExpression(a.left.left,{operator:"typeof"})||!j.isIdentifier(a.left.left.argument,{name:r.name})||!j.isStringLiteral(a.left.right,{value:"string"})||!j.isUnaryExpression(c,{operator:"!"})||!j.isBinaryExpression(c.argument,{operator:"in"})||!j.isIdentifier(c.argument.left,{name:r.name})||!j.isIdentifier(c.argument.right,{name:n.name})||!j.isReturnStatement(l)||!j.isIfStatement(i)||i.alternate||!j.isCallExpression(u)||!j.isMemberExpression(u.callee)||!j.isIdentifier(u.callee.object,{name:"Reflect"})||!j.isIdentifier(u.callee.property,{name:"get"})||u.arguments.length!==3||!j.isIdentifier(u.arguments[0],{name:n.name})||!j.isIdentifier(u.arguments[1],{name:r.name})||!j.isIdentifier(u.arguments[2],{name:o.name})?null:e.arguments[0].name}function DR(e){let t=e.getFunctionParent();if(!t)return null;if(t.isFunctionDeclaration()){let s=t.node.id?.name;if(!s)return null;let a=t.parentPath?.isExportDefaultDeclaration()?"default":(t.parentPath?.isExportNamedDeclaration(),s);return{componentName:s,exportName:a}}if(!t.isArrowFunctionExpression()&&!t.isFunctionExpression())return null;let n=t.parentPath;if(!n?.isVariableDeclarator()||!j.isIdentifier(n.node.id))return null;let r=n.node.id.name,o=n.parentPath,i=o?.parentPath?.isExportDefaultDeclaration()?"default":(o?.parentPath?.isExportNamedDeclaration(),r);return{componentName:r,exportName:i}}function Dg(e,t){let n=DR(e.path);if(!n)return null;let r=fr(e,t);return r?{...n,...r}:null}function Bg(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}function Ml(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 Ol(e,t){for(let n of e.program.body){if(t==="default"&&j.isExportDefaultDeclaration(n))return j.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:(j.isFunctionDeclaration(n.declaration)||j.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if(j.isExportNamedDeclaration(n)){if(n.declaration){if(j.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if(j.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if((j.isFunctionDeclaration(n.declaration)||j.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if((j.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&j.isExportSpecifier(r))return n.source?{kind:"re-export",name:r.local.name,source:n.source.value}:{kind:"local-binding",name:r.local.name}}}return null}function jg(e){let{resolveExternalExpression:t,resolveCollectionCallTarget:n,evaluateStaticExpression:r,resolveSourceInfoProvenance:o,buildExpressionSourceInfo:i}=e;async function s(h){let{currentFile:y,binding:x,readFile:E,exists:v,fileCache:C,visited:P}=h,F=`${y}::${x.kind}::${x.identifier.name}`;if(P.has(F))return null;P.add(F);try{let R=await a({currentFile:y,binding:x,readFile:E,exists:v,fileCache:C,visited:P});if(R)return R;if(x.path.isImportSpecifier()||x.path.isImportDefaultSpecifier())return await g({currentFile:y,binding:x,readFile:E,exists:v,graph:h.graph,externalSourceResolvers:h.externalSourceResolvers,externalAdapters:h.externalAdapters,fileCache:C,visited:P});if(x.kind==="param")return null;if(x.path.isVariableDeclarator()){let N=x.path.node.init;if(!N||!j.isExpression(N))return null;let T=LR(N);if(T&&!x.path.scope.getBinding("Proxy")&&!x.path.scope.getBinding("Reflect")){let W=x.path.scope.getBinding(T),oe=W?await s({...h,binding:W}):null;if(oe?.kind==="static"&&oe.value!==null&&!Array.isArray(oe.value)&&typeof oe.value=="object")return oe}let L=x.path.get("init");if(L&&!Array.isArray(L)&&L.isExpression()){let W=await t({currentFile:y,expressionPath:L,readFile:E,exists:v,graph:h.graph,externalSourceResolvers:h.externalSourceResolvers,externalAdapters:h.externalAdapters,functionCallContracts:h.functionCallContracts,fileCache:C,visited:P});if(W)return W;if(L.isCallExpression()){let oe=await n({currentFile:y,callPath:L,readFile:E,exists:v,graph:h.graph,externalSourceResolvers:h.externalSourceResolvers,externalAdapters:h.externalAdapters,functionCallContracts:h.functionCallContracts,fileCache:C,visited:P});if(oe)return oe}}let q=await r(N,x.path.scope,y,E,v,C,P);return q===void 0?null:{kind:"static",file:y,root:{kind:"binding",name:x.identifier.name},value:q,sourceKind:"binding"}}if(x.path.isIdentifier()&&x.path.parentPath?.isExportDefaultDeclaration()){let N=x.path.parentPath.node.declaration;if(!j.isExpression(N))return null;let T=await r(N,x.path.scope,y,E,v,C,P);return T===void 0?null:{kind:"static",file:y,root:{kind:"binding",name:x.identifier.name},value:T,sourceKind:"binding"}}return null}finally{P.delete(F)}}async function a(h){let{currentFile:y,binding:x,readFile:E,exists:v,fileCache:C,visited:P}=h;if(!x.path.isVariableDeclarator()||!x.path.get("id").isArrayPattern())return null;let F=x.path,R=F.node.init;if(!R||!j.isCallExpression(R))return null;let N=OR(R);if(!N||!j.isArrayPattern(F.node.id)||F.node.id.elements.findIndex(oe=>j.isIdentifier(oe)&&oe.name===x.identifier.name)!==0)return null;let L=N==="useReducer"?1:0,q=R.arguments[L];if(!q||!j.isExpression(q))return null;let W=await r(q,F.scope,y,E,v,C,P);return W===void 0?null:{kind:"static",file:y,root:{kind:"hook-state",name:x.identifier.name,hook:N},value:W,sourceKind:"binding"}}async function c(h){let y=h.expressionPath.scope.getBinding(h.sourceInfo.base);if(!y||!y.constant||y.kind!=="param"||!h.graph)return null;let x=Dg(y,h.sourceInfo);if(!x)return null;let E=[...h.graph.elements.values()].filter(C=>Bg(C,h.currentFile,x.componentName,x.exportName));if(!E.length)return null;let v=[];for(let C of E){if(C.sourceFile!==E[0].sourceFile||C.componentName!==E[0].componentName||C.attributeSpreads?.length)return null;let P=await Tt(C.sourceFile,h.readFile,h.fileCache),F=P.ast?ws(P.ast,C.sourceRange):null;if(!F)return null;let R=F.parentPath;for(;R&&!R.isFunction();){if(R.isJSXElement()){let D=R.node.openingElement.name;if(!j.isJSXIdentifier(D)||!/^[a-z]/.test(D.name))return null}else if(!R.isJSXFragment()&&!R.isReturnStatement()&&!R.isBlockStatement())return null;R=R.parentPath}if(!R)return null;let N=F.get("openingElement").get("attributes").filter(D=>D.isJSXAttribute()&&j.isJSXIdentifier(D.node.name,{name:x.propName}));if(N.length!==1)return null;let T=N[0];if(!T?.isJSXAttribute())return null;let L=T.get("value"),q=L.isJSXExpressionContainer()?L.get("expression"):L;if(!q.isExpression())return null;let W=await r(q.node,q.scope,C.sourceFile,h.readFile,h.exists,h.fileCache,h.visited),oe=W===void 0?void 0:Qe(W,x.remainingPath);if(oe===void 0)return null;v.push(oe)}return v}async function l(h){let y=Dg(h.binding,h.sourceInfo);if(!y||!h.graph)return null;let x=["component-prop",h.currentFile,h.binding.identifier.start??h.binding.path.node.start??-1,y.componentName,y.propName].join(":");if(h.visited.has(x))return null;h.visited.add(x);try{return await u(h,y,h.graph)}finally{h.visited.delete(x)}}async function u(h,y,x){let E=[...x.elements.values()].filter(T=>Bg(T,h.currentFile,y.componentName,y.exportName));if(E.length!==1)return null;let v=E[0],C=v.attributes?.find(T=>T.name===y.propName);if(C&&!C.source){let T=await d({caller:v,propName:y.propName,remainingPath:y.remainingPath,readFile:h.readFile,fileCache:h.fileCache});if(T)return Ml(T,{componentName:y.componentName,propName:y.propName,file:v.sourceFile})}if(!C?.source){let T=await f({caller:v,propName:y.propName,remainingPath:y.remainingPath,readFile:h.readFile,exists:h.exists,graph:h.graph,externalSourceResolvers:h.externalSourceResolvers,externalAdapters:h.externalAdapters,functionCallContracts:h.functionCallContracts,fileCache:h.fileCache,visited:h.visited});if(T)return Ml(T,{componentName:y.componentName,propName:y.propName,file:v.sourceFile});let L=Op(h.binding,y.componentName,y.propName);if(!L||L.propName!==y.propName)return null;let q=await r(L.expressionPath.node,L.expressionPath.scope,h.currentFile,h.readFile,h.exists,h.fileCache,h.visited);if(q===void 0)return null;let W=y.remainingPath;return W.length>0&&Qe(q,W)===void 0?null:{kind:"value",file:h.currentFile,root:{kind:"binding",name:y.propName},path:W,sourceKind:"binding",semanticKind:"component-prop",displayExpression:L.displayPath,chainPrefix:[{kind:"component-prop",file:h.currentFile,displayName:L.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let P=await Tt(v.sourceFile,h.readFile,h.fileCache);if(!P.ast)return null;let F=Lg(P.ast,P.source,C.source.expression,C.sourceRange)??To(P.ast,P.source,C.source.expression);if(!F)return null;let R={...C.source,expression:Nr(C.source.expression,y.remainingPath),path:[...C.source.path,...y.remainingPath]},N=await o({currentFile:v.sourceFile,expressionPath:F,sourceInfo:R,readFile:h.readFile,exists:h.exists,graph:h.graph,externalSourceResolvers:h.externalSourceResolvers,externalAdapters:h.externalAdapters,functionCallContracts:h.functionCallContracts,fileCache:h.fileCache,visited:h.visited});return N?Ml(N.kind==="external"?N:{...N,displayExpression:R.expression},{componentName:y.componentName,propName:y.propName,file:v.sourceFile}):null}async function d(h){let y=await Tt(h.caller.sourceFile,h.readFile,h.fileCache);if(!y.ast)return null;let x=ws(y.ast,h.caller.sourceRange);if(!x)return null;let E=x.get("openingElement").get("attributes").find(F=>F.isJSXAttribute()&&F.node.name.type==="JSXIdentifier"&&F.node.name.name===h.propName);if(!E?.isJSXAttribute())return null;let v=E.get("value"),C=v.isStringLiteral()?v:v.isJSXExpressionContainer()?v.get("expression"):null;if(!C?.isExpression())return null;let P=Ao(C.node);return P?{kind:"value",file:h.caller.sourceFile,root:{kind:"expression",sourceRange:P},path:h.remainingPath,sourceKind:"binding",semanticKind:"component-prop",displayExpression:h.propName,editMode:"upstream",diagnostics:[]}:null}async function f(h){let y=await Tt(h.caller.sourceFile,h.readFile,h.fileCache);if(!y.ast)return null;let x=ws(y.ast,h.caller.sourceRange);if(!x)return null;let E=x.get("openingElement");for(let v of E.get("attributes")){if(!v.isJSXSpreadAttribute())continue;let C=v.get("argument");if(!C.isExpression())continue;let P=await i({expression:C.node,scope:C.scope,source:y.source,currentFile:h.caller.sourceFile,readFile:h.readFile,exists:h.exists,fileCache:h.fileCache,visited:h.visited});if(!P)continue;let F=[{kind:"property",name:h.propName},...h.remainingPath],R={...P,expression:Nr(P.expression,F),path:[...P.path,...F]},N=await o({currentFile:h.caller.sourceFile,expressionPath:C,sourceInfo:R,readFile:h.readFile,exists:h.exists,graph:h.graph,externalSourceResolvers:h.externalSourceResolvers,externalAdapters:h.externalAdapters,functionCallContracts:h.functionCallContracts,fileCache:h.fileCache,visited:h.visited});if(N)return N.kind==="external"?N:{...N,displayExpression:R.expression}}return null}async function g(h){let{currentFile:y,binding:x,readFile:E,exists:v,fileCache:C,visited:P}=h,F=x.path.parentPath;if(!F||!F.isImportDeclaration())return null;let R=F.node.source.value;if(typeof R!="string")return null;let N=await Cn(y,R,v);if(!N)return null;if(x.path.isImportDefaultSpecifier()){let D=await Tt(N,E,C),Z=D.ast?Ol(D.ast,"default"):null,fe=await m({file:N,exportName:"default",readFile:E,exists:v,graph:h.graph,externalSourceResolvers:h.externalSourceResolvers,externalAdapters:h.externalAdapters,functionCallContracts:h.functionCallContracts,fileCache:C,visited:P});return!fe||fe.kind!=="static"?null:{kind:"static",file:Z?.kind==="default-expression"?fe.file:N,root:Z?.kind==="default-expression"?fe.root:{kind:"default-export"},value:fe.value,sourceKind:"imported-binding"}}if(!x.path.isImportSpecifier())return null;let T=x.path.node.imported,L=j.isIdentifier(T)?T.name:T.value,q=await Tt(N,E,C),W=q.ast?Ol(q.ast,L):null,oe=await m({file:N,exportName:L,readFile:E,exists:v,graph:h.graph,externalSourceResolvers:h.externalSourceResolvers,externalAdapters:h.externalAdapters,functionCallContracts:h.functionCallContracts,fileCache:C,visited:P});return oe?oe.kind==="external"?oe:{kind:"static",file:W?.kind==="re-export"?oe.file:N,root:W?.kind==="re-export"||oe.root.kind==="binding"&&oe.root.name!==W?.name?oe.root:{kind:"named-export",name:L},value:oe.value,sourceKind:"imported-binding"}:null}async function m(h){let{file:y,exportName:x,readFile:E,exists:v,fileCache:C,visited:P}=h,F=`export::${y}::${x}`;if(!P.has(F)){P.add(F);try{let R=await Tt(y,E,C);if(!R.ast)return;let N=Ol(R.ast,x);if(!N)return;if(N.kind==="default-expression"){let W=N.expression;if(!W||!j.isIdentifier(W))return;let oe=Fo(R.ast).getBinding(W.name);return oe?await s({currentFile:y,binding:oe,readFile:E,exists:v,graph:h.graph,externalSourceResolvers:h.externalSourceResolvers,externalAdapters:h.externalAdapters,functionCallContracts:h.functionCallContracts,fileCache:C,visited:P})??void 0:void 0}if(N.kind==="re-export"){if(!N.source||!N.name)return;let W=await Cn(y,N.source,v);return W?m({...h,file:W,exportName:N.name}):void 0}let T=N.name;if(!T)return;let L=Fo(R.ast).getBinding(T);return L?await s({currentFile:y,binding:L,readFile:E,exists:v,graph:h.graph,externalSourceResolvers:h.externalSourceResolvers,externalAdapters:h.externalAdapters,functionCallContracts:h.functionCallContracts,fileCache:C,visited:P})??void 0:void 0}finally{P.delete(F)}}}return{resolveExportValue:m,resolveComponentPropBinding:l,resolveComponentPropValues:c,resolveBindingTarget:s}}import*as Y from"@babel/types";function Dl(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=Nt(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!BR(s,r)?null:{callPath:s,basePath:i}}function BR(e,t){let n=e.node.callee;return!Y.isMemberExpression(n)||!Y.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}function Ug(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:es(r,t)}function $g(e,t){return e?Y.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}function Vg(e,t,n,r,o){let i=Y.isExpression(e.body)?e.body:e.body.body.find(a=>Y.isReturnStatement(a))?.argument;if(!i||!Y.isExpression(i))return;let s=Ll(i,t,n,r,o);return typeof s=="number"?s:void 0}function Ll(e,t,n,r,o){if(Y.isNumericLiteral(e)||Y.isStringLiteral(e)||Y.isBooleanLiteral(e))return e.value;if(Y.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(Y.isMemberExpression(e)){let i=Is(e,t);if(i)return Qe(r,i);let s=Is(e,n);return s?Qe(o,s):void 0}if(Y.isBinaryExpression(e)&&e.operator==="-"){let i=Y.isExpression(e.left)?Ll(e.left,t,n,r,o):void 0,s=Y.isExpression(e.right)?Ll(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function jR(e){if(Y.isExpression(e.body))return e.body;for(let t of e.body.body)if(Y.isReturnStatement(t)&&t.argument&&Y.isExpression(t.argument))return t.argument;return null}function $R(e,t,n){let r=Jn(e,t,n);return typeof r=="boolean"?r:void 0}function Jn(e,t,n){if(Y.isStringLiteral(e)||Y.isNumericLiteral(e)||Y.isBooleanLiteral(e))return e.value;if(Y.isNullLiteral(e))return null;if(Y.isIdentifier(e))return e.name===t?n:void 0;if(Y.isMemberExpression(e)){let r=Is(e,t);return r?Qe(n,r):void 0}if(Y.isUnaryExpression(e)&&e.operator==="!"){let r=Jn(e.argument,t,n);return r===void 0?void 0:!r}if(Y.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(Y.isBinaryExpression(e)){let r=Y.isExpression(e.left)?Jn(e.left,t,n):void 0,o=Y.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 Jg(e){let t=[],n=e;for(;Y.isMemberExpression(n)||Y.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(Y.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(Y.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(Y.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(Y.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return Y.isIdentifier(n)?{base:n.name,segments:t}:null}function Xg(e){return e.some(t=>t.kind==="dynamic")}function Kg(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}function zg(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 VR(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,resolveComponentPropValues:i}=e;async function s(m){let{currentFile:h,callPath:y,readFile:x,exists:E,fileCache:v,visited:C}=m,P=y.node.callee;if(!Y.isMemberExpression(P)||!Y.isIdentifier(P.property)||P.property.name!=="map")return null;let F=y.get("callee");if(!F.isMemberExpression())return null;let R=F.get("object");if(Array.isArray(R)||!R.isExpression())return null;let N=await a({currentFile:h,expressionPath:R,readFile:x,exists:E,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:v,visited:C});return!N||!Array.isArray(N.value)||N.value.length===0?null:N}async function a(m){let{currentFile:h,expressionPath:y,readFile:x,exists:E,fileCache:v,visited:C}=m;if(y.isIdentifier()){let P=y.scope.getBinding(y.node.name);if(!P)return null;let F=await t({currentFile:h,binding:P,readFile:x,exists:E,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:v,visited:C});return F?.kind==="static"?F:null}if(y.isCallExpression())return l({currentFile:h,callPath:y,readFile:x,exists:E,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:v,visited:C});if(y.isTSAsExpression()||y.isTSSatisfiesExpression()||y.isTSNonNullExpression()){let P=y.get("expression");if(!Array.isArray(P)&&P.isExpression())return a({...m,expressionPath:P})}if(y.isArrayExpression()){let P=Ao(y.node);if(!P)return null;let F=await n(y.node,y.scope,h,x,E,v,C);return Array.isArray(F)?{kind:"static",file:h,root:{kind:"expression",sourceRange:P},value:F,sourceKind:"binding"}:null}if(y.isMemberExpression()){let P=await r({expression:y.node,scope:y.scope,currentFile:h,readFile:x,exists:E,fileCache:v,visited:C});if(!P)return null;let F=await o({currentFile:h,expressionPath:y,sourceInfo:P,readFile:x,exists:E,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:v,visited:C});if(!F||F.kind==="external")return null;let R=await c({currentFile:h,expressionPath:y,provenance:F,readFile:x,exists:E,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:v,visited:C});if(!R||R.kind!=="static")return null;if(F.collectionPathMap?.length){let T=VR(R.value,F.collectionPathMap);if(T)return{kind:"static",file:F.file,root:F.root,value:T.value,sourceKind:F.sourceKind,collectionPathMap:T.collectionPathMap}}let N=Qe(R.value,F.path);return Array.isArray(N)?{kind:"static",file:F.file,root:F.root,value:N,sourceKind:F.sourceKind,pathPrefix:F.path,collectionIndexMap:F.collectionIndexMap,collectionPathMap:F.collectionPathMap}:null}return null}async function c(m){let{provenance:h}=m;if(h.root.kind==="binding"){let v=m.expressionPath.scope.getBinding(h.root.name);if(!v&&h.file!==m.currentFile){let C=await Tt(h.file,m.readFile,m.fileCache);v=C.ast?Fo(C.ast).getBinding(h.root.name):void 0}return v?await t({currentFile:h.file,binding:v,readFile:m.readFile,exists:m.exists,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:m.fileCache,visited:m.visited}):null}if(h.root.kind!=="expression")return null;let y=await Tt(h.file,m.readFile,m.fileCache);if(!y.ast)return null;let x=Mg(y.ast,h.root.sourceRange);if(!x)return null;let E=await n(x.node,x.scope,h.file,m.readFile,m.exists,m.fileCache,m.visited);return E===void 0?null:{kind:"static",file:h.file,root:h.root,value:E,sourceKind:h.sourceKind}}async function l(m){return await u(m)??await d(m)??await f(m)}async function u(m){let{callPath:h}=m,y=h.node.callee;if(!Y.isMemberExpression(y)||!Y.isIdentifier(y.property)||y.property.name!=="filter")return null;let x=h.get("callee");if(!x.isMemberExpression())return null;let E=x.get("object");if(Array.isArray(E)||!E.isExpression())return null;let v=await a({currentFile:m.currentFile,expressionPath:E,readFile:m.readFile,exists:m.exists,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:m.fileCache,visited:m.visited});if(!v||!Array.isArray(v.value))return null;let[C]=h.node.arguments;if(!Y.isArrowFunctionExpression(C)&&!Y.isFunctionExpression(C))return null;let P=C.params[0];if(!Y.isIdentifier(P))return null;let F=jR(C);if(!F)return null;let R=[],N=[],T=[];for(let[L,q]of v.value.entries()){let W=$R(F,P.name,q);if(typeof W!="boolean")return null;if(W){R.push(q),N.push(v.collectionIndexMap?.[L]??L);let oe=v.collectionPathMap?.[L];oe&&T.push(oe)}}return{...v,value:R,pathPrefix:v.pathPrefix,collectionIndexMap:N,...T.length>0?{collectionPathMap:T}:{}}}async function d(m){let{callPath:h}=m,y=h.node.callee;if(!Y.isMemberExpression(y)||!Y.isIdentifier(y.property)||y.property.name!=="slice")return null;let x=h.get("callee");if(!x.isMemberExpression())return null;let E=x.get("object");if(Array.isArray(E)||!E.isExpression())return null;let v=await a({currentFile:m.currentFile,expressionPath:E,readFile:m.readFile,exists:m.exists,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:m.fileCache,visited:m.visited});if(!v||!Array.isArray(v.value))return null;let[C,P]=h.node.arguments,F=$g(C,0),R=$g(P,v.value.length);if(F===null||R===null)return null;let N=Math.max(0,F<0?v.value.length+F:F),T=Math.max(0,R<0?v.value.length+R:R),L=v.value.map((W,oe)=>v.collectionIndexMap?.[oe]??oe).slice(N,T),q=v.collectionPathMap?.slice(N,T);return{...v,value:v.value.slice(N,T),pathPrefix:v.pathPrefix,collectionIndexMap:L,...q?{collectionPathMap:q}:{}}}async function f(m){let{callPath:h}=m,y=h.node.callee;if(!Y.isMemberExpression(y)||!Y.isIdentifier(y.property)||y.property.name!=="sort"&&y.property.name!=="toSorted")return null;let x=h.get("callee");if(!x.isMemberExpression())return null;let E=x.get("object");if(Array.isArray(E)||!E.isExpression())return null;let v=await a({currentFile:m.currentFile,expressionPath:E,readFile:m.readFile,exists:m.exists,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:m.fileCache,visited:m.visited});if(!v||!Array.isArray(v.value))return null;let[C]=h.node.arguments;if(!Y.isArrowFunctionExpression(C)&&!Y.isFunctionExpression(C))return null;let[P,F]=C.params;if(!Y.isIdentifier(P)||!Y.isIdentifier(F))return null;let R=v.value.map((T,L)=>({value:T,sourceIndex:v.collectionIndexMap?.[L]??L,originalIndex:L})),N=[...R];for(let T of R)for(let L of R)if(Vg(C,P.name,F.name,T.value,L.value)===void 0)return null;return N.sort((T,L)=>{let q=Vg(C,P.name,F.name,T.value,L.value)??0;return q===0?T.originalIndex-L.originalIndex:q}),{...v,value:N.map(T=>T.value),pathPrefix:v.pathPrefix,collectionIndexMap:N.map(T=>T.sourceIndex),...v.collectionPathMap?{collectionPathMap:N.map(T=>v.collectionPathMap?.[T.originalIndex]).filter(T=>!!T)}:{}}}async function g(m){let h=null,y=!1,x,E=[];for(let C of m.segments){if(C.kind!=="dynamic")continue;let P=await r({expression:C.expression,scope:m.expressionPath.scope,source:m.fileCache.get(m.currentFile)?.source,currentFile:m.currentFile,readFile:m.readFile,exists:m.exists,fileCache:m.fileCache,visited:m.visited});if(!P)return null;let F=Dl(m.expressionPath,P.base),R;if(F){y=!0;let N=await s({currentFile:m.currentFile,callPath:F.callPath,readFile:m.readFile,exists:m.exists,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:m.fileCache,visited:m.visited});if(!N||!Array.isArray(N.value))return null;R=N.value.map((T,L)=>{let q=Qe(N.value,[{kind:"index",index:L},...F.basePath,...P.path]);return Kg(q)}),x??=N.collectionIndexMap}else{let N=await i({...m,sourceInfo:P});if(!N)return null;R=N.map(Kg)}if(R.some(N=>N===null)||h!==null&&h!==R.length)return null;h=R.length,E.push(R)}if(h===null||h===0)return null;let v=[];for(let C=0;C<h;C+=1){let P=[...m.rootPath],F=0;for(let R of m.segments){if(R.kind==="dynamic"){let N=E[F]?.[C];if(!N)return null;P.push(N),F+=1;continue}P.push({...R})}v.push(P)}return{sourceKind:y||h>1?"repeat-template":"binding",...x?{collectionIndexMap:x}:{},collectionPathMap:v}}return{resolveRepeatCollectionTarget:s,resolveCollectionCallTarget:l,resolveDynamicMemberPathMap:g}}var{normalizeExpressionWithScope:KR,evaluateStaticExpression:Ns}=wg({resolveBindingTarget:e=>Ps(e)}),{resolveRepeatCollectionTarget:UR,resolveCollectionCallTarget:JR,resolveDynamicMemberPathMap:XR}=Wg({resolveBindingTarget:e=>Ps(e),evaluateStaticExpression:Ns,buildExpressionSourceInfo:Xt,resolveSourceInfoProvenance:kt,resolveComponentPropValues:e=>HR(e)}),{resolveExportValue:zR,resolveComponentPropBinding:WR,resolveComponentPropValues:HR,resolveBindingTarget:Ps}=jg({resolveExternalExpression:Jl,resolveCollectionCallTarget:JR,evaluateStaticExpression:Ns,resolveSourceInfoProvenance:kt,buildExpressionSourceInfo:Xt});function nh(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}var Hg=new WeakMap;function GR(e){let t=Hg.get(e);return t||(t=new WeakMap,Hg.set(e,t)),t}function Gg(e,t,n){return{kind:"external",file:e,sourceType:"api-field",sourceId:t,displayPath:n,editMode:"readonly",diagnostics:[{code:"external-source-readonly",message:"Dynamic API data is read-only for content edits"}]}}async function rh(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=Cs(s,t,n);if(!a)return null;let c=Rs(a,r.sourceRange);if(!c)return null;let l=await Xt({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!l){let f=await Hl({currentFile:t,expressionPath:c,readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:new Set});return f?$l(f,wr(c.node,n)):null}let u=new Set,d=await yw({currentFile:t,expressionPath:c,segment:{...r,source:l},readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:u});return d?$l(d,l.expression):null}async function Pr(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Cs(i,t,n);if(!s)return null;let a=e.sourceRange?Rs(s,e.sourceRange):e.expression!==void 0?To(s,n,e.expression):null;if(!a)return null;let c=As(a);if(!c.isIdentifier()&&!c.isMemberExpression())return null;let l=new Set,u=await Xt({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:l}),d=u?await kt({currentFile:t,expressionPath:c,sourceInfo:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:l}):await dh({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 $l(d,e.expression??wr(c.node,n))}async function Ul(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Cs(i,t,n);if(!s)return mt("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?YR({file:t,source:n,ast:s,segment:e.target.segment,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:a}):ZR({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}async function Xt(e){if(ne.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!ne.isMemberExpression(e.expression))return null;let t=await KR(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:wr(e.expression,e.source),base:t.base,path:t.path}:null}function $l(e,t){if(!e||e.kind==="value"&&e.editMode==="readonly")return null;if(e.kind==="external")return{kind:"external-entry",file:e.file,sourceType:e.sourceType,sourceId:e.sourceId,adapterId:e.adapterId,displayExpression:e.displayPath};let n={kind:"value",root:e.root,path:e.path.length>0?e.path:[]};return{kind:"value-binding",file:e.file,locator:n,root:e.root,path:e.path,displayExpression:e.displayExpression??t,sourceKind:e.sourceKind,...e.collectionIndexMap?{collectionIndexMap:e.collectionIndexMap}:{},...e.collectionPathMap?{collectionPathMap:e.collectionPathMap}:{}}}async function YR(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=Rs(r,o.sourceRange),u=l?await Xt({expression:l.node,scope:l.scope,source:n,currentFile:t,readFile:i,exists:s,fileCache:a,visited:c}):null;if(!u){if(!l||l.isStringLiteral()||l.isTemplateLiteral()&&l.node.expressions.length===0)return Yg(t,o.value);let f=await Hl({currentFile:t,expressionPath:l,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});return f?f.kind==="external"?th(t,f):Kl(t,wr(l.node,n),f):QR({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return mt("unsupported-expression","Unable to locate text expression for provenance resolution");let d=await kt({currentFile:t,expressionPath:l,sourceInfo:u,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});if(!d){let f=Vl(l.node);if(f)return mt(f.code,f.message);let g=l.scope.getBinding(u.base);if(g?.path.isVariableDeclarator()){let m=Vl(g.path.node.init);if(m)return mt(m.code,m.message)}return g?.path.isVariableDeclarator()&&ne.isCallExpression(g.path.node.init)?qR("unsupported-expression",ch(g.path.node.init,e.functionCallContracts)):mt("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return d.kind==="external"?th(t,d):Kl(t,u.expression,d)}async function ZR(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return mt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=To(r,n,o.conditionExpression);if(!l)return mt("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await kt({currentFile:t,expressionPath:l,sourceInfo:o.conditionSource,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});if(!u)return mt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(u.kind==="external")return mt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let d=Kl(t,o.conditionExpression,u);return d.finalSource?{...d,finalSource:{...d.finalSource,kind:"conditional-branch",displayPath:o.conditionExpression},chain:[...d.chain,{kind:"conditional-branch",file:u.file,displayName:o.conditionExpression,canEditHere:!0}]}:d}function Yg(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 QR(e){let t=await ih(e);if(t.length===0)return mt("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(ew(e.expression))return oh(t);if(ah(e.expression))return mt("unsupported-expression","i18n helpers require a static message id string");if(ne.isMemberExpression(e.expression)&&e.expression.computed&&!ne.isNumericLiteral(e.expression.property)&&!ne.isStringLiteral(e.expression.property))return mt("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return mt(n.code,n.message)}function mt(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function qR(e,t){return oh([{code:e,message:t}])}function oh(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function ew(e){return ne.isCallExpression(e)||ne.isConditionalExpression(e)||ne.isLogicalExpression(e)||ne.isBinaryExpression(e)}function Mo(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 ih(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=Vl(t);if(l)return[l];if(ne.isCallExpression(t))return[{code:"unsupported-expression",message:ch(t,c)}];if(ne.isMemberExpression(t)&&t.computed){let u=t.property;if(!ne.isNumericLiteral(u)&&!ne.isStringLiteral(u)){if(!ne.isExpression(u))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let f=await Ns(u,n,r,o,i,s,a);if(typeof f!="string"&&!Number.isInteger(f))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}]}}return ne.isBinaryExpression(t)?Mo([...await Bl(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):ne.isLogicalExpression(t)?Mo([...await Bl(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"}]):ne.isConditionalExpression(t)?Mo([...await Bl(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 Vl(e){return ah(e)?Zg("i18n helpers require a static message id string"):iw(e)?Zg("CMS helpers require static entry id and field path string arguments"):null}async function Bl(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await ih({...t,expression:o}));return r}function tw(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:[nw(e.sourceType)]}}async function Jl(e){for(let n of lw){if(!Qg(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return eh(qg(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(!Qg(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return eh(qg(r),e.externalAdapters)}return null}function nw(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function rw(e){return{code:"external-source-readonly",message:e}}function Zg(e){return{code:"unsupported-expression",message:e}}function Xl(e){return!e||!ne.isCallExpression(e)?null:ne.isIdentifier(e.callee)?e.callee.name:ne.isMemberExpression(e.callee)&&!e.callee.computed&&ne.isIdentifier(e.callee.object)&&ne.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function Qg(e,t){if(!t||t.length===0)return!0;let n=Xl(e.node);return n?t.includes(n):!1}function qg(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:Mo(e.diagnostics??[])}:{match:e,diagnostics:[]}}function eh(e,t){let n=tw(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:Mo([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function ow(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!ne.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!ne.isStringLiteral(n)||!ne.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 iw(e){return!!e&&ne.isCallExpression(e)&&ne.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!ne.isStringLiteral(e.arguments[0])||!ne.isStringLiteral(e.arguments[1]))}function sh(e){if(!(!e||!ne.isCallExpression(e))){if(ne.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&ne.isStringLiteral(t)?t.value:null}if(ne.isMemberExpression(e.callee)&&!e.callee.computed&&ne.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&ne.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!ne.isObjectExpression(t))return null;for(let n of t.properties)if(ne.isObjectProperty(n)&&!n.computed&&(ne.isIdentifier(n.key)&&n.key.name==="id"||ne.isStringLiteral(n.key)&&n.key.value==="id")&&ne.isStringLiteral(n.value))return n.value.value;return null}}}function ah(e){return sh(e)===null}async function sw(e,t,n){let r=new Set,o=_o.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=_o.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"]:[_o.posix.join(i,"locales"),_o.posix.join(i,"messages")];for(let a of s){let c=_o.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function aw(e){let t=sh(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await sw(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function cw(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!ne.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!ne.isExpression(n))return null;let o=await Ns(n,e.expressionPath.scope,e.currentFile,e.readFile,e.exists,e.fileCache,e.visited);if(typeof o!="string"||o.length===0)return null;let i={sourceType:"api-field",sourceId:o,file:`api://${o}`,displayPath:o};return r?{match:i,editMode:"readonly",diagnostics:[rw("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var lw=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>ow(e)},{helperNames:["apiField"],resolve:e=>cw(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>aw({currentFile:e,expressionPath:t,exists:n})}];function zl(e){return{...e,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Derived display values are readonly because no identity-preserving write target exists"}]}}function th(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 Kl(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=hw(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 uw=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function Wl(e,t){let n=[...uw,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function ch(e,t){let n=e.callee;return ne.isIdentifier(n)&&Wl(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 Hl(e){let t=await Jl(e);if(t)return t;let n=await lh({...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 Xt({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 kt({...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 mw(e)}async function lh(e){let t=await Ft({...e,allowComposed:!1});if(t?.kind!=="source")return null;let n=As(e.expressionPath);return n.isIdentifier()||n.isMemberExpression()?t.provenance:zl(t.provenance)}async function Ft(e){let t=As(e.expressionPath),n=pw(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 Xt({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 kt({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 Xt({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 kt({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 Ft({...e,expressionPath:r,allowComposed:!0}),a=await Ft({...e,expressionPath:o,allowComposed:!1}),c=await Ft({...e,expressionPath:i,allowComposed:!1});return jl(s,a,c)}if(t.isCallExpression())return dw({...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 Ft({...e,expressionPath:r,allowComposed:!0}),s=await Ft({...e,expressionPath:o,allowComposed:!0});return jl(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 Ft({...e,expressionPath:r,allowComposed:!0}),s=await Ft({...e,expressionPath:o,allowComposed:!0});return jl(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:Ft({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function As(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 dw(e){let t=Xl(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:Ft({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(ne.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:Ft({...e,expressionPath:o,allowComposed:!1})}}return null}function jl(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!fw(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function fw(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 pw(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function mw(e){if(!e.expressionPath.isCallExpression())return null;let t=Xl(e.expressionPath.node);if(!t)return null;let n=Wl(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 uh({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?zl(i):null}async function uh(e){let t=await Jl({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 Xt({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 kt({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 Hl({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 gw(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!ne.isCallExpression(t))return null;let n=t.callee;if(!ne.isIdentifier(n))return null;let r=Wl(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 uh({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?zl(a):null}function hw(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=Nr(t,e.path);return{sourceId:o,displayPath:o}}async function yw(e){let t=e.segment.source;return t?kt({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 kt(e){let t=e.sourceInfo,n=Dl(e.expressionPath,t.base);if(n){let l=await UR({currentFile:e.currentFile,callPath:n.callPath,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,fileCache:e.fileCache,visited:e.visited});if(!l){let h=Ug(n.callPath,[...n.basePath,...t.path]);return ho(h)?Gg(e.currentFile,h.sourceId,h.displayPath):null}let u=zg(l,[...n.basePath,...t.path]),d=l.collectionIndexMap?.[0]??0,f=[...l.pathPrefix??[],{kind:"index",index:d},...n.basePath,...t.path],g=[{kind:"index",index:0},...n.basePath,...t.path];return Qe(l.value,g)===void 0?null:{kind:"value",file:l.file,root:l.root,path:u?.[0]??f,sourceKind:"repeat-template",collectionIndexMap:l.collectionIndexMap,...u?{collectionPathMap:u}:{}}}let r=e.expressionPath.scope.getBinding(t.base);if(!r)return null;if(r.path.isImportNamespaceSpecifier()){let l=t.path[0],u=r.path.parentPath;if(!l||l.kind!=="property"||!u?.isImportDeclaration())return null;let d=await Cn(e.currentFile,u.node.source.value,e.exists);if(!d)return null;let f=await zR({file:d,exportName:l.name,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(!f||f.kind==="external")return null;let g=t.path.slice(1);return Qe(f.value,g)===void 0?null:{kind:"value",file:f.file,root:f.root,path:g,sourceKind:"imported-binding",collectionIndexMap:f.collectionIndexMap}}let o=_p(r);if(o){let l=o.expressionPath,u=await Xt({expression:l.node,scope:l.scope,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(u){let d=await kt({...e,expressionPath:l,sourceInfo:{...u,expression:Nr(u.expression,t.path),path:[...u.path,...t.path]}});if(d)return d}else if(r.constant){let d=`dynamic-alias:${e.currentFile}:${l.node.start}`;if(e.visited.has(d))return null;e.visited.add(d);try{let f=await dh({...e,expressionPath:As(l),memberSuffix:t.path});if(f?.kind==="value")return f}finally{e.visited.delete(d)}}if(t.path.length===0){let d=await lh({currentFile:e.currentFile,expressionPath:l,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(d)return d}}if(r.kind==="param")return WR({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 gw({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=Qi(r,t.path,GR(e.fileCache));if(ho(s))return Gg(e.currentFile,s.sourceId,s.displayPath);let a=await Ps({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 dh(e){let t=Jg(e.expressionPath.node);if(!t||!Xg(t.segments))return null;let n=await kt({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 XR({...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 Ps({...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:r.sourceKind,displayExpression:wr(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:o}}async function fh(e){let t=xw(e.propertyName);if(t.owner==="blocked")return vn(t.owner,t.diagnostic);if(t.owner==="class-name-source"||t.owner==="style")return vn(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 vn("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 Sw(e,l)});o.sort((l,u)=>l.order-u.order);let s=o.at(-1);if(!s)return{status:"missing",owner:"generic"};if(o.filter(l=>l.kind==="spread"&&l.order>s.order).some(l=>!l.target))return vn("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}:vn("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?vn("generic",{code:"remove-exposes-spread",message:`Removing '${e.propertyName}' would expose an earlier spread source`}):bw(e,s.attribute)}async function bw(e,t){if(t.resolution&&t.resolution.status!=="resolved"&&!t.source){let r=await Pr({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}}:vn("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 Pr({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"?vn("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 Sw(e,t){let n=t.source?.expression;if(!n)return;let r=await Pr({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:Ew(r,e.propertyName)}}function Ew(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 vn(e,t){return{status:"blocked",owner:e,...t?{diagnostic:t}:{}}}function ph(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(Xn(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=>vw({...r,graph:e},n)}function vw(e,t){let{key:n,element:r,graph:o,provenances:i}=e,s=Iw(n,r,o,t),a=s?.tag??(Xn(r.tag)?r.tag:r.componentName),c=s?.identity.key??t(r,o)??n,l=ww(s),u=Nw(n,r,o,i,s),d=kw(n,r,o,i,c);return{componentName:a,instanceKey:c,templateOwner:Rw(s??r,a),...l.length>0?{variantKeys:l}:{},...u.length>0?{slotKeys:u}:{},editableStrategy:d,impactScope:Pw(d),alternativeStrategies:Aw(d)}}function kw(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return Gl(e,n)?"instance":!Xn(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function Iw(e,t,n,r){if(Xn(t.tag))return t;let o=Gl(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 Rw(e,t){return Xn(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function ww(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 Nw(e,t,n,r,o){let i=new Set,s=Gl(e,n);s&&o?.identity.key===s.identity.key&&i.add("children");for(let a of r.values()){let c=a?.chain.find(u=>u.kind==="component-prop");if(!c)continue;let l=c.displayName.split(".").pop();l&&i.add(l)}return i.size===0&&Xn(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function Gl(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(Xn(r.tag))return r;n=r.parentKey}return null}function Xn(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 Aw(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}function hh(e){let t=e.isRepeat??(e.graph?jw(e.element,e.graph):!1),n=e.propertyProvenance??new Map,r=e.repeatTargets??new Map,o=Bw(e.element.attributes??[]),i=[...r.values()].some(u=>u.ok),s=o.map(u=>Tw({attribute:u,element:e.element,isRepeat:t,selectionRef:e.selectionRef,provenance:n.get(u.name),repeatTarget:r.get(u.name)})),a=(e.element.attributeSpreads?.length??0)>0,c=(e.element.attributeSpreads??[]).slice().sort((u,d)=>u.order-d.order).map(u=>({raw:u.raw,sourceRange:$w(u.sourceRange,e.source),order:u.order,diagnostics:u.source?[]:[{code:"unsupported-spread-source",message:"The spread source cannot be resolved safely, so property ownership is conservative."}]})),l=t&&e.selectionRef?.instanceIndex!==void 0&&i;return{documentVersion:e.documentVersion,...e.selectionRef?{selectionRef:e.selectionRef}:{},items:s,spreads:c,creation:t?{selection:l?"materialize":"unsupported",template:"unsupported"}:{selection:a?"unsupported":"direct",template:a?"unsupported":"direct"}}}function Tw(e){let{attribute:t,provenance:n,repeatTarget:r}=e,o=e.selectionRef?.instanceIndex!==void 0&&r?.ok===!0?r:null,i=Fw(t,n,e.isRepeat),s=["selection","template"].map(y=>({scope:y,result:as({state:n,scope:y,operation:"set",selectionRef:e.selectionRef,isRepeat:e.isRepeat,repeatTarget:r})})),a=s.find(({result:y})=>y.ok)?.result,c=a?.ok?a.target:void 0,l=c?.kind==="value-binding"&&o&&(JSON.stringify(c.locator.root)!==JSON.stringify(o.selectedParentObjectLocator.root)||JSON.stringify(c.locator.path??[])!==JSON.stringify([...o.selectedParentObjectLocator.path??[],{kind:"property",name:t.name}]))?null:o,u=_w(t,n,l,e.isRepeat),d=c?Lw(c,e.element,t.name):void 0,f=s.filter(({result:y})=>y.ok).map(({scope:y})=>y),g=f.length>0?Ow(n,o,e.element):"unsupported",m=o?"repeat-item":e.isRepeat?"repeat-template":"node",h=Dw(t,n,r);if(f.length===0&&h.length===0){let y=s.find(({result:x})=>!x.ok)?.result;y&&!y.ok&&h.push({code:y.code,message:y.reason})}return{name:t.name,source:i,resolution:u,editMode:g,sourceScope:m,allowedWriteScopes:f,...d?{effectiveWriteTarget:d}:{},diagnostics:h}}function Fw(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 _w(e,t,n,r){return n?mh(n.selectedResolution):t?.status==="blocked"?{status:"unresolved"}:r&&t?.status==="binding"?{status:"unresolved"}:mh(Mw(e))}function Mw(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 mh(e){return!e||e.status==="unresolved"?{status:"unresolved"}:e.status==="undefined"?{status:"undefined"}:{status:"resolved",value:e.value}}function Ow(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 Lw(e,t,n){return e.kind==="repeat-property"?{kind:"value-path",file:e.target.sourceFile,isProxy:e.target.sourceFile!==t.sourceFile,displayPath:gh({...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:gh(e.locator)}:{kind:"jsx-node",file:t.sourceFile,isProxy:!1,displayPath:t.componentName+" > "+n}}function Dw(e,t,n){let r=[];return t?.diagnostic&&r.push({code:t.diagnostic.code,message:t.diagnostic.message}),n&&!n.ok&&t?.status!=="missing"&&r.push({code:`repeat-${n.errorCode}`,message:n.reason}),e.resolution?.status==="unresolved"&&r.length===0&&r.push({code:"unsupported-property-source",message:`Property '${e.name}' has an unresolved value source`}),r}function Bw(e){let t=new Set;return e.filter(n=>t.has(n.name)?!1:(t.add(n.name),!0))}function jw(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 gh(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 $w(e,t){if(!t)return{start:e.startColumn,end:e.endColumn};let n=t.split(`
7
- `),r=(o,i)=>n.slice(0,Math.max(0,o-1)).reduce((s,a)=>s+a.length+1,0)+i;return{start:r(e.startLine,e.startColumn),end:r(e.endLine,e.endColumn)}}function Vw(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var Kw=160;function yh(e,t,n,r={}){let o=ir(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 xh(e,t,n,r,o,i,s,a,c,l,u){let d=ir(t),f=t.elements.get(e),g=n.nodes.get(e),m=r.get(e);if(!f||!g||!m)throw new Error(`Node not found: ${e}`);let h=kh(f.textSegments,s),y=Ih(e,t,f,m,h),x=h?zw(h):void 0,E=Ww(i,h),v=f.textSegments.map(R=>({index:R.index,value:R.value,editable:Ch(R,m,s?.get(R.index)??null),source:o.get(R.index)??null})),C=Eh(f,t),P=f.childKeys.map(R=>{let N=t.elements.get(R);return N?{key:R,tag:N.tag,label:N.tag}:null}).filter(R=>R!==null),F=[];if(f.parentKey){let R=t.elements.get(f.parentKey);if(R)for(let N of R.childKeys){if(N===e)continue;let T=t.elements.get(N);T&&F.push({key:N,tag:T.tag,label:T.tag})}}return{composition:d,key:e,tag:f.tag,componentName:f.componentName,sourceFile:f.sourceFile,sourceLocator:Sh(f),label:f.tag,capabilities:y,writeTarget:i,effectiveWriteTarget:E,provenanceChain:x,componentSemantic:c,styleSource:l,conditional:a,...u?{dynamicData:u}:{},textSegments:v,boundaryKind:f.boundaryKind,isOpaque:f.isOpaque,ancestors:C,children:P,siblings:F}}function bh(e,t,n,r,o,i,s,a){let c=ir(t),l=t.elements.get(e),u=n.nodes.get(e),d=r.get(e);if(!l||!u||!d)throw new Error(`Node not found: ${e}`);let f=kh(l.textSegments,i),g=Uw(l);return{composition:c,key:e,tag:l.tag,...g?{linkSourceKind:g}:{},componentName:l.componentName,sourceFile:l.sourceFile,sourceLocator:Sh(l),label:l.tag,capabilities:Ih(e,t,l,d,f),provenanceChain:f?{editMode:f.editMode,diagnostics:f.diagnostics.map(m=>({code:m.code,message:m.message}))}:void 0,...s?{dynamicData:s}:{},...a?{properties:a}:{},textSegments:l.textSegments.map(m=>{let h=o.get(m.index);return{index:m.index,editable:Ch(m,d,i?.get(m.index)??null),source:h?{kind:h.kind}:null}}),boundaryKind:l.boundaryKind,isOpaque:l.isOpaque,ancestors:Eh(l,t)}}function Uw(e){if(e.tag==="a")return"native-anchor";if(e.importedFrom==="next/link"&&e.exportName==="default")return"next-link";if(e.tag==="Link")return"unsupported"}function Sh(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:Jw(e.sourceRange),structuralPath:e.identity.structuralPath,...Xw(e.textSegments)}}function Eh(e,t){let n=[],r=e.parentKey;for(;r;){let o=t.elements.get(r);if(!o)break;n.push({key:r,tag:o.tag,label:o.tag}),r=o.parentKey}return n.reverse(),n}function Jw(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function Xw(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,Kw)}:{}}function vh(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 kh(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(u=>u.kind==="repeat-region"&&u.childKeys.includes(e)),a=o?.diagnostics.find(u=>u.code==="missing-adapter"||u.code==="external-source-readonly")?.code,c=r.canUpdateText?{mode:o?.editMode??"direct",reasonCode:a??(o?.editMode==="upstream"?"component-prop":o?.finalSource?.kind==="repeat-template"?"repeat-item-data":void 0)}:{mode:"unsupported",reasonCode:"capability-denied"},l=r.canUpdateText&&Rh(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 Ch(e,t,n){return!e.editable||!t.canUpdateText?!1:n?Rh(n.editMode):!0}function Rh(e){return e==="direct"||e==="proxy"||e==="upstream"}function zw(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 Ww(e,t){return t?.finalSource?t.finalSource.kind==="jsx-literal"?{kind:"jsx-node",file:e.file,isProxy:e.isProxy}:t.finalSource.kind==="config-entry"&&t.finalSource.locator?{kind:"value-path",file:t.finalSource.file,isProxy:t.finalSource.file!==e.file,displayPath:t.finalSource.displayPath}:Vw(t.finalSource.kind)?{kind:"external-entry",file:t.finalSource.file,isProxy:!1,displayPath:t.finalSource.displayPath,sourceType:t.finalSource.externalSource?.sourceType,sourceId:t.finalSource.externalSource?.sourceId}:{kind:"value-path",file:t.finalSource.file,isProxy:t.finalSource.file!==e.file,displayPath:t.finalSource.displayPath}:{kind:e.kind==="route-export"?"route-export":"jsx-node",file:e.file,isProxy:e.isProxy}}var Yl=["set-class-name-source","apply-style-draft"];function wh(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:Yl,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:Yl,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:Yl}}function Nh(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}),Ph(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function Ph(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}),Ph(s,t,n,r,o))}}import Ah from"node:path";function Ql(){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=Zw(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 Ts(e){let t=()=>Hw(e);return e.mutex?e.mutex.runExclusive(t):t()}async function Hw(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=Gw(e.overlay,t.plan),r;try{r=await e.buildCandidate({overlay:n,plan:t.plan})}catch(l){return{ok:!1,stage:"build",reason:"Candidate build failed.",error:l,recoveryRequired:!1}}let o,i;try{o=await e.prepareHistory?.({candidate:r,plan:t.plan}),await e.reverify?.({candidate:r,plan:t.plan,history:o}),i=await e.writeCandidate({candidate:r,plan:t.plan}),await e.markCandidateWritten?.({candidate:r,plan:t.plan,history:o,receipt:i})}catch(l){return Zl({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 Zl({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 Zl({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 Th("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return Th("finalize",l,"Transaction finalization failed after live state swap.")}try{e.emitCommitted?.({candidate:s,plan:t.plan,published:a})}catch{}return{ok:!0,stage:"publish",published:a,plan:t.plan}}function Gw(e,t){let n=new Map(e);for(let r of t.intents)r.kind==="delete"?n.delete(r.path):n.set(r.path,r.content);return n}function Zl(e){return e.rollbackCandidate({candidate:e.candidate,plan:e.plan,failedStage:e.failedStage,error:e.error,...e.history===void 0?{}:{history:e.history},...e.receipt===void 0?{}:{receipt:e.receipt}}).then(()=>({ok:!1,stage:e.failedStage,reason:Yw(e.failedStage),error:e.error,recoveryRequired:!1})).catch(t=>({ok:!1,stage:"rollback",reason:"Rollback failed after candidate commit/validation/publish failure.",error:t,recoveryRequired:!0,cause:e.error}))}function Th(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function Yw(e){switch(e){case"commit":return"Candidate write or commit verification failed.";case"validate":return"Candidate validation failed.";case"publish":return"Candidate publish failed."}}function Zw(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)||Ah.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=Ah.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 Qw=50,qw=8*1024*1024;function Lh(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??Qw),s=Math.max(0,t.maxUndoBytes??qw);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:u,redo:d};async function a(R){let N=[...R.steps].sort((D,Z)=>D.order-Z.order),T=N.filter(D=>D.type!=="invoke-external-adapter");if(T.length!==N.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let L=new Set(T.map(D=>D.file)),q=await E(L),W=new Map(q.map(D=>[D.file,D.exists===!1?"":D.content])),oe;for(let D of T){let Z=Oh(D,W.get(D.file)??"");if(!Z.ok)return{ok:!1,errorCode:Z.errorCode,reason:Z.reason};W.set(D.file,Z.source),oe=Z.selectionRef??oe}return{ok:!0,filePlan:{operationId:R.operationId,kind:"source-edit",target:R.target,documentVersion:R.documentVersion,conflictPolicy:"compare-and-swap",edits:[...W].map(([D,Z])=>({operation:"upsert",file:D,content:Z,baseContentHash:q.find(fe=>fe.file===D)?.sha256??null}))},...oe?{selectionRef:oe}:{}}}async function c(R){let N=[...R.steps].sort((fe,ct)=>fe.order-ct.order),T=N.filter(fe=>fe.type!=="invoke-external-adapter"),L=N.filter(fe=>fe.type==="invoke-external-adapter"),q=new Set(T.map(fe=>fe.file));if(T.length>0&&L.length>0)return{ok:!1,operationId:R.operationId,errorCode:"unsupported-operation",reason:"Mixed local file rewrites and external adapter writes require an explicit compensation contract.",rolledBack:!1};if(T.length===0)return y(R,L);let W=await E(q),oe=new Map;for(let fe of W)oe.set(fe.file,fe.exists===!1?"":fe.content);let D;for(let fe of T){let ct=oe.get(fe.file)??"",rt=Oh(fe,ct);if(!rt.ok)return{ok:!1,operationId:R.operationId,errorCode:rt.errorCode,reason:rt.reason,rolledBack:!1};oe.set(fe.file,rt.source),rt.selectionRef&&(D=rt.selectionRef)}let Z=await C([...oe].map(([fe,ct])=>({file:fe,content:ct,exists:!0,version:0,sha256:Re(ct)})),W);return Z.ok===!1?{ok:!1,operationId:R.operationId,errorCode:Z.rolledBack?"writeback-failed":"rollback-failed",reason:Z.reason,rolledBack:Z.rolledBack}:(n.push({operationId:R.operationId,preSnapshots:W,postSnapshots:Z.snapshots,plan:R}),f(),r.length=0,{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:Math.max(...Z.snapshots.map(fe=>fe.version)),affectedFiles:[...q],...D?{selectionRef:D}:{}})}async function l(R){let N=new Set(R.edits.map(Z=>Z.file)),T=await E(N),L=x(R,T);if(L)return{ok:!1,operationId:R.operationId,errorCode:"stale-version",reason:L.reason,affectedFiles:[L.file],rolledBack:!1};let q=new Map(T.map(Z=>[Z.file,Z])),W=R.edits.find(Z=>Z.operation==="create-only"&&q.get(Z.file)?.exists!==!1);if(W)return{ok:!1,operationId:R.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${W.file}`,affectedFiles:[W.file],rolledBack:!1};let oe=R.edits.map(Z=>Z.operation==="delete"?{file:Z.file,content:"",exists:!1,version:0}:{file:Z.file,content:Z.content,exists:!0,version:0,sha256:Re(Z.content)}),D=await C(oe,T,new Set(R.edits.filter(Z=>Z.operation==="create-only").map(Z=>Z.file)));return D.ok===!1?{ok:!1,operationId:R.operationId,errorCode:D.rolledBack?"writeback-failed":"rollback-failed",reason:D.reason,rolledBack:D.rolledBack}:(n.push({operationId:R.operationId,preSnapshots:T,postSnapshots:D.snapshots,plan:{operationId:R.operationId,kind:R.kind,target:R.target,documentVersion:R.documentVersion,steps:[],preSnapshots:T}}),f(),r.length=0,{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:Math.max(...D.snapshots.map(Z=>Z.version)),affectedFiles:[...N]})}async function u(){let R=n.at(-1);if(!R)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let N=await C(R.preSnapshots,R.postSnapshots);return N.ok===!1?{ok:!1,operationId:R.operationId,errorCode:N.rolledBack?"writeback-failed":"rollback-failed",reason:N.reason,rolledBack:N.rolledBack}:(n.pop(),r.push(R),{ok:!0,operationId:R.operationId,kind:R.plan.kind,target:R.plan.target,resultVersion:Math.max(...N.snapshots.map(T=>T.version)),affectedFiles:R.preSnapshots.map(T=>T.file)})}async function d(){let R=r.at(-1);if(!R)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let N=await C(R.postSnapshots,R.preSnapshots);return N.ok===!1?{ok:!1,operationId:R.operationId,errorCode:N.rolledBack?"writeback-failed":"rollback-failed",reason:N.reason,rolledBack:N.rolledBack}:(r.pop(),n.push(R),f(),{ok:!0,operationId:R.operationId,kind:R.plan.kind,target:R.plan.target,resultVersion:Math.max(...N.snapshots.map(T=>T.version)),affectedFiles:R.postSnapshots.map(T=>T.file)})}function f(){for(;n.length>i;)n.shift();for(;n.length>0&&g()>s;)n.shift()}function g(){return n.reduce((R,N)=>R+m(N),0)}function m(R){return h(R.preSnapshots)+h(R.postSnapshots)}function h(R){return R.reduce((N,T)=>N+T.file.length+T.content.length,0)}async function y(R,N){let T=[];for(let L of N){let q=L.capability??"write-text",W=o.find(D=>D.sourceType===L.sourceType&&(L.adapterId===void 0||D.adapterId===L.adapterId)&&(D.capabilities===void 0||D.capabilities.includes(q)));if(!W)return{ok:!1,operationId:R.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${L.sourceType}`,rolledBack:!1};let oe=await W.execute(L);if(!oe.ok)return{ok:!1,operationId:R.operationId,errorCode:"writeback-failed",reason:oe.reason??`External adapter failed for ${L.sourceType}`,rolledBack:!1};T.push(L.file)}return{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:0,affectedFiles:T}}function x(R,N){if(R.conflictPolicy!=="compare-and-swap")return null;let T=new Map(N.map(L=>[L.file,L]));for(let L of R.edits){if(L.operation==="create-only")continue;if(L.baseContentHash===void 0)return{file:L.file,reason:`Source file ${L.file} is missing baseContentHash. Reopen the file before saving.`};let q=T.get(L.file),W=L.baseContentHash;if(W===null){if(q?.exists!==!1)return{file:L.file,reason:`Source file ${L.file} was created or changed before save.`};continue}if(!W)return{file:L.file,reason:`Source file ${L.file} is missing baseContentHash. Reopen the file before saving.`};if(q?.exists===!1||q?.sha256!==W)return{file:L.file,reason:`Source file ${L.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function E(R){let N=[];for(let T of R)N.push(await v(T));return N}async function v(R){if(!await e.exists(R))return{file:R,content:"",version:0,exists:!1};let T=Math.max(1,e.getVersion(R)),L=await e.readFile(R);return{file:R,content:L,version:T,exists:!0,sha256:Re(L)}}async function C(R,N,T=new Set){let L=[];try{for(let q of R){if(T.has(q.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive(q.file,q.content)}else await P(q);let W=e.bumpVersion(q.file);L.push(q.file),q.version=W}}catch(q){let W=await F(N.filter(D=>L.includes(D.file)));if(W.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${W.failedFiles.join(", ")}: ${Mh(q)}`,rolledBack:!1,instanceConflict:_h(q)};let oe=_h(q);return{ok:!1,reason:`${oe?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${Mh(q)}`,rolledBack:!0,instanceConflict:oe}}return{ok:!0,snapshots:R.map(eN)}}async function P(R){if(R.exists===!1){await e.deleteFile(R.file);return}await e.writeFile(R.file,R.content)}async function F(R){let N=[];for(let T of R)try{await P(T),e.bumpVersion(T.file)}catch{N.push(T.file)}return N.length===0?{ok:!0}:{ok:!1,failedFiles:N}}}function _h(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function eN(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:Re(e.content)}:{}}}function Mh(e){return e instanceof Error?e.message:String(e)}function Oh(e,t){switch(e.type){case"invoke-external-adapter":return{ok:!1,reason:"External adapter steps must be executed asynchronously",errorCode:"unsupported-operation"};case"add-import":return He(rr({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return He(or({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return He(qn({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return He(er({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return He(ai({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return He(Kr({source:t,locator:e.locator,next:e.value}));case"update-array-item":return He(Kr({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return He(mi({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return He(li({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return He(gi({source:t,locator:e.locator,index:e.index}));case"move-array-item":return He(hi({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return He(tr({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return He(ui({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 tN(e,t);case"set-property-changes":return He(di({source:t,locator:e.locator,changes:e.changes}));case"set-link-target":return He(fi({source:t,locator:e.locator,link:e.link,changes:e.changes}));case"set-property-binding":return He(pi({source:t,locator:e.locator,name:e.name,object:e.object,property:e.property}));case"upsert-object-property":return He(xi({source:t,objectLocator:e.locator,name:e.name,value:e.value}));default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function tN(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!_d(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!==Re(t))return{ok:!1,reason:"The source file changed before className save.",errorCode:"stale-version"};if(n.oldAttrRange){if(t.slice(n.oldAttrRange.start,n.oldAttrRange.end)!==n.oldAttrRaw)return{ok:!1,reason:"The className attribute changed before save.",errorCode:"stale-version"}}else if(n.oldAttrRaw!==null)return{ok:!1,reason:"The className attribute range no longer matches.",errorCode:"stale-version"};return{ok:!0,source:Fd({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function He(e){if(e.ok)return{ok:!0,source:e.source,...e.selectionRef?{selectionRef:e.selectionRef}:{}};switch(e.diagnostic.code){case"locator-miss":return{ok:!1,reason:e.diagnostic.message,errorCode:"locator-miss"};case"unsupported-syntax":case"binding-not-found":case"export-not-found":case"property-not-found":case"array-index-out-of-range":case"directive-conflict":case"metadata-shape-unsupported":return{ok:!1,reason:e.diagnostic.message,errorCode:"unsupported-operation"};case"invalid-parent-child-relation":case"self-closing-element":return{ok:!1,reason:e.diagnostic.message,errorCode:"invalid-target"};case"parse-failed":case"printer-failed":return{ok:!1,reason:e.diagnostic.message,errorCode:"ast-error"};default:return{ok:!1,reason:e.diagnostic.message,errorCode:"writeback-failed"}}}import{computeSiteEditCompositionKey as Fs,SiteEditCompositionContextSchema as nN,SiteEditCompositionSelectorSchema as rN}from"@vcp-dev/contracts";var qe=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="SiteEditCompositionError"}};function Dh(e,t){throw new qe("INVALID_COMPOSITION",e,{value:t})}function _s(e){let t=nN.safeParse(e);return t.success?t.data:Dh("Invalid SiteEditCompositionContext.",e)}function Bh(e){let t=[],n=new Map,r=new Map;for(let l of e.compositions){let u=_s(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new qe("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=Fs(u);if(n.has(d))throw new qe("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u});let f=r.get(l.entryFile);if(f)throw new qe("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:f});let g={context:u,entryFile:l.entryFile,key:d};t.push(g),n.set(d,g),r.set(l.entryFile,d)}if(t.length===0)throw new qe("INVALID_COMPOSITION","At least one composition must be registered.");let o=new Map;for(let l of e.initialDocumentVersions??[]){let u=_s(l?.composition);if(!Number.isInteger(l?.version)||(l?.version??-1)<0)throw new qe("INVALID_INITIAL_DOCUMENT_VERSION","Initial document version must be a non-negative integer.",{context:u,version:l?.version});let d=Fs(u);if(!n.has(d))throw new qe("UNKNOWN_COMPOSITION","Initial document version references an unregistered composition.",{context:u,key:d});if(o.has(d))throw new qe("DUPLICATE_COMPOSITION","Initial document versions must contain each composition at most once.",{context:u,key:d});o.set(d,l.version)}function i(l){let u=rN.safeParse(l);if(!u.success)return Dh("Invalid SiteEditCompositionSelector.",l);let d=t.filter(({context:f})=>f.routeId===u.data.routeId&&(u.data.templateId===void 0?f.effectiveTemplateId===void 0:f.effectiveTemplateId===u.data.templateId));if(d.length===1)return d[0];throw d.length>1?new qe("AMBIGUOUS_COMPOSITION","The composition selector matches multiple registered contexts.",{selector:u.data}):new qe("UNKNOWN_COMPOSITION","The composition selector is not registered.",{selector:u.data})}function s(l){let u=_s(l),d=Fs(u),f=n.get(d);if(!f)throw new qe("UNKNOWN_COMPOSITION","The composition context is not registered.",{context:u,key:d});return f}function a(l){let u=_s(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new qe("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=Fs(u),f=n.get(d);if(f){if(f.entryFile===l.entryFile)return f;throw new qe("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u})}let g=[...n.values()].find(h=>h.entryFile===l.entryFile);if(g)throw new qe("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:g.context});let m={context:u,entryFile:l.entryFile,key:d};return t.push(m),n.set(d,m),m}function c(l){let u=n.get(l);if(!u)return;n.delete(l);let d=t.findIndex(f=>f.key===l);return d>=0&&t.splice(d,1),o.delete(l),u}return{entries:t,byKey:n,initialVersions:o,register:a,unregister:c,resolveSelector:i,resolveContext:s,getByKey:l=>n.get(l),routeIds:()=>[...new Set(t.map(({context:l})=>l.routeId))]}}function ql(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 jh(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 oN,stripSiteEditRepeatInstanceKeys as $h}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=$h(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 iN(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 Ms(e){return e?.map(t=>({...t}))}function eu(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=Ms(e.collectionPathMap?.[t])??Ms(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:Ms(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>Ms(o)??[])}}function Kh(e,t,n){let r=new Set;for(let g of t.regions)if(g.kind==="repeat-region")for(let m of g.childKeys)r.add(m);if(r.size===0)return e;let o=new Map(e.entries.map(g=>[g.key,g])),i=[],s=new Map,a=(g,m)=>oN(g,m),c=(g,m,h)=>{let y=o.get(g);if(!y)return a(g,h);let x=a(g,h),E={...y,key:x,parentKey:m,childKeys:[]};return i.push(E),E.childKeys=y.childKeys.flatMap(v=>l(v,h,x)),x},l=(g,m,h)=>{if(!r.has(g))return[c(g,h,m)];let y=d(g,m),x=[];for(let E=0;E<y;E+=1)x.push(c(g,h,[...m,E]));return x},u=Array.from(new Set([...e.rootKeys,...e.entries.filter(g=>g.parentKey===null).map(g=>g.key)]));for(let g of u){if(!r.has(g)){c(g,null,[]);continue}let m=d(g,[]);for(let h=0;h<m;h+=1)c(g,null,[h])}return{...e,rootKeys:[...e.rootKeys],entries:i};function d(g,m){let h=new Set;for(let y of f(g)){let x=n.get(y);if(x){for(let E of[...x.textTargets.values(),...x.elementPropertyTargets.values()])if(!(E?.kind!=="value-binding"||E.sourceKind!=="repeat-template"))for(let v of sN(E))v.length<=m.length||aN(v,m)&&h.add(v[m.length])}}return h.size>0?h.size:iN(n.get(g))}function f(g){let m=s.get(g);if(m)return m;let h=[g],y=o.get(g);for(let x of y?.childKeys??[])h.push(...f(x));return s.set(g,h),h}}function Uh(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function Jh(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(($h(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function sN(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 aN(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 Xh(e,t,n,r){if(!n)return{...e,key:t};let o=r??new Map(n.entries.map(u=>[u.key,u])),i=o.get(t);if(!i)return{...e,key:t};let s=[],a=i.parentKey;for(;a;){let u=o.get(a);if(!u)break;s.push({key:u.key,tag:u.tag,label:u.label}),a=u.parentKey}s.reverse();let c=i.childKeys.map(u=>o.get(u)).filter(u=>u!==void 0).map(u=>({key:u.key,tag:u.tag,label:u.label})),l=i.parentKey===null?[]:(o.get(i.parentKey)?.childKeys??[]).filter(u=>u!==i.key).map(u=>o.get(u)).filter(u=>u!==void 0).map(u=>({key:u.key,tag:u.tag,label:u.label}));return{...e,key:i.key,ancestors:s,children:c,siblings:l}}function zh(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 cN(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var Oo=class extends Error{constructor(t){let n=t.map(Wh);super(cN(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function Hh(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof Oo?{routeId:e,message:n,diagnostics:t.diagnostics.map(Wh)}:{routeId:e,message:n}}function tu(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function nu(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function Lo(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function Gh(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function Os(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 Yh(e){let{journal:t,index:n,observedFileDigests:r}=e;if(r.length!==t.files.length)return"ambiguous";let o=t.files.every((l,u)=>l.preDigest===r[u]),i=t.files.every((l,u)=>l.postDigest===r[u]),s=t.historyTransition,a=n.digest===s.expectedIndexDigest,c=n.digest===s.publishedIndexDigest&&n.cursor===s.publishedCursor&&n.currentId===s.publishedCurrentId;return o&&a?"safely-uncommitted":i&&c?"durably-committed":"ambiguous"}var hN=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,yN=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],Zh=32,Ds=256;function xN(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var Qh={maxEntries:50,maxBytes:8*1024*1024};function bN(){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 Si(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 SN(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 EN(){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>Qh.maxEntries||vN(e)>Qh.maxBytes;)e.shift()}}function vN(e){return e.reduce((t,n)=>t+kN(n),0)}function kN(e){return qh(e.preSnapshots)+qh(e.postSnapshots)+IN(e.provenance)}function IN(e){return e?new TextEncoder().encode(JSON.stringify(e)).byteLength:0}function qh(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function ey(e,t){return{key:uN(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 Bs=class extends Error{constructor(t){super(t.reason),this.result=t}},zn=class extends Error{constructor(t){super(tu(t)),this.failedRoutes=t}};function ty(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=at(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(at(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}function CN(e,t,n){if(!n)return;let r=at(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 RN=/\.(?:[cm]?[jt]sx?)$/i,wN=/\.json$/i,NN=/\.(?:css|scss|sass)$/i,PN=/\.mdx$/i,AN=/\.ya?ml$/i;function TN(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 FN(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function _N(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=ay(await e.listFiles(i)),a=new Map(s.files.map(l=>[l.path,l]));for(let[l,u]of n)if(MN(l,i.roots??[])){if(!u.exists){a.delete(l);continue}a.set(l,{path:l,sizeBytes:Buffer.byteLength(u.content,"utf8")})}let c=[...a.values()].sort((l,u)=>l.path.localeCompare(u.path));return s.truncated?{files:c,truncated:s.truncated}:c},getVersion(i){return e.getVersion(i)},bumpVersion(i){return e.getVersion(i)}}}function MN(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function ay(e){return Array.isArray(e)?{files:e}:e}function ON(e){if(!fN(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!==mN||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=dN(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(RN.test(e.path)){let t=Mt({source:e.content,profile:wn({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(wN.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${tt(t)}`,details:{path:e.path}}}if(NN.test(e.path)){let t=ny({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(PN.test(e.path)){let t=ny({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(AN.test(e.path))try{gN(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${tt(t)}`,details:{path:e.path}}}return{ok:!0}}function ny({content:e,path:t,profile:n}){let r=[],o=null,i=!1,s=!1,a=!1,c=!1,l=!0;for(let d=0;d<e.length;d+=1){let f=e[d]??"",g=e[d+1]??"";if(n==="mdx"&&l&&e.startsWith("```",d)){c=!c;let m=e.indexOf(`
4
+ `)}function ri(e){let{ast:t,source:n}=e;try{let r=pb(n),i=fb(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=gb(i,r)),{ok:!0,source:i}}catch(r){return X(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}function td(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 Lr(e,t,n){return{ok:!0,source:t,operation:{type:n.kind,nodeId:n.target,kind:n.kind,target:n.target,beforeSourceHash:td(e),afterSourceHash:td(t),inverse:n.inverse}}}function be(e,t,n){let r=ri({ast:e,source:t});return r.ok?Lr(t,r.source,n):r}function Pe(e,t){let n=Fr(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function oi(e,t){return ri({ast:e,source:t})}function Rb(e,t,n){let r=ue(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function Qn(e,t,n){let r=Rb(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:X(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function an(e){return typeof e=="string"?ya(e):typeof e=="number"?kb(e):typeof e=="boolean"?yb(e):e===null?vb():Array.isArray(e)?hb(e.map(t=>an(t))):Ib(Object.entries(e).map(([t,n])=>{let r=Cb(xa(t),an(n));return t==="__proto__"&&(r.computed=!0),r}))}function wb(e){return typeof e=="string"?ya(e):Sb(an(e))}function Dr(e,t){return bb(Eb(e),wb(t))}function ii(e,t){try{let r=nd.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:X(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:X(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function xa(e){return/^[$A-Z_][0-9A-Z_$]*$/i.test(e)?xb(e):ya(e)}function si(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=Pe(t,"jsx-node");if(!i.ok)return i.result;let s=ue(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let c=Nb(s.match.path)[r];if(!c)return X(t,"locator-miss",`Text segment ${r} not found`,"jsx-node");switch(c.kind){case"jsx-text":{let l=c.path.node.value;if(o.trim().length===0){let d=l.match(/^\s*/)?.[0]??"",f=l.match(/\s*$/)?.[0]??"";c.path.replaceWithMultiple([...d?[Fn.jsxText(d)]:[],Fn.jsxExpressionContainer(Fn.stringLiteral("")),...f?[Fn.jsxText(f)]:[]]);break}let u=Pb(l,o);c.path.node.value=u,c.path.node.extra={rawValue:u,raw:u.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/{/g,"&#123;").replace(/}/g,"&#125;")};break}case"string-literal":c.path.node.value=o;break;case"template-literal":{let l=c.quasiIndex;c.path.node.quasis[l].value.raw=o.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${").replace(/\r/g,"\\r"),c.path.node.quasis[l].value.cooked=o;break}}return be(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function Nb(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=Ab(r.get("expression"));o.length>0&&t.push(...o)}}return t}function Pb(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function Ab(e){if(e.isStringLiteral())return[{kind:"string-literal",path:e}];if(e.isTemplateLiteral()){let t=[],n=e.node.quasis;for(let r=0;r<n.length;r++)(n[r].value.raw.trim().length>0||n.length===1&&e.node.expressions.length===0)&&t.push({kind:"template-literal",path:e,quasiIndex:r});if(t.length>0)return t}return e.isCallExpression()?[]:[]}import{nullLiteral as ba}from"@babel/types";function qn(e){let{source:t,locator:n}=e,r=Pe(t,"jsx-node");if(!r.ok)return r.result;let o=ue(r.ast,n);return o.ok?(Tb(o.match.path),be(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function Tb(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(ba());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(ba());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(ba());return}e.remove()}import{cloneNode as Fb}from"@babel/types";function ai(e){let t=Pe(e.source,"jsx-node");if(!t.ok)return t.result;let n=ue(t.ast,e.locator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};let r=ii(e.source,e.node.jsx);return r.ok?(n.match.path.replaceWith(Fb(r.node,!0)),be(t.ast,e.source,{kind:"replace-node",target:"jsx-node",inverse:"replace-node"})):r.result}import{cloneNode as Ub}from"@babel/types";import Sa from"@babel/traverse";import*as re from"@babel/types";function Br(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 _b=typeof Sa=="function"?Sa:Sa.default;function yt(e,t,n,r){if(!e.ok)return e;let o=ht(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=Ob(e,t);if(!r)return;let o=n.sourceLocator?rd(n.sourceLocator):void 0,i=n.targetParentLocator?rd(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??Db(r)??i?.component??o?.component;if(!(!s||!a))return{key:Br(s,a,Bb(r))}}function rd(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function Ob(e,t){let n=ld(e,t);return!n||n.node.type!=="JSXElement"?null:n}function ld(e,t){let n=null;return _b(e,{JSXElement(r){r.node===t&&(n=r,r.stop())},JSXFragment(r){r.node===t&&(n=r,r.stop())}}),n}function ht(e,t){if(!e)return null;if(re.isJSXElement(e))return Kb(t,e)?od(e.children,t):e;if(re.isJSXFragment(e))return od(e.children,t);if(re.isJSXExpressionContainer(e)||re.isParenthesizedExpression(e)||re.isTSAsExpression(e)||re.isTSSatisfiesExpression(e)||re.isTSTypeAssertion(e)||re.isTSNonNullExpression(e))return ht(e.expression,t);if(re.isLogicalExpression(e))return ht(e.right,t);if(re.isConditionalExpression(e))return ht(e.consequent,t)??ht(e.alternate,t);if(re.isCallExpression(e)||re.isOptionalCallExpression(e))return ud(e)?Lb(e.arguments[0],t):null;if(re.isArrayExpression(e))for(let n of e.elements){if(!n)continue;let r=ht(n,t);if(r)return r}return null}function od(e,t){for(let n of e){let r=ht(n,t);if(r)return r}return null}function Lb(e,t){return!e||!re.isArrowFunctionExpression(e)&&!re.isFunctionExpression(e)?null:re.isBlockStatement(e.body)?jr(e.body.body,t):ht(e.body,t)}function jr(e,t){for(let n of e){if(re.isReturnStatement(n)){let r=ht(n.argument,t);if(r)return r;continue}if(re.isBlockStatement(n)){let r=jr(n.body,t);if(r)return r;continue}if(re.isIfStatement(n)){let r=id(n.consequent,t);if(r)return r;let o=n.alternate?id(n.alternate,t):null;if(o)return o;continue}if(re.isSwitchStatement(n))for(let r of n.cases){let o=jr(r.consequent,t);if(o)return o}}return null}function id(e,t){return re.isBlockStatement(e)?jr(e.body,t):jr([e],t)}function Db(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(re.isFunctionDeclaration(n))return n.id?.name??"default"}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}var sd=new WeakMap,ad=new WeakMap,Ea=new WeakMap;function Bb(e){let t=sd.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=jb(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return sd.set(e.node,o),o}function jb(e){let t=dd(e.node.openingElement.name);return!t||Oe(e)?null:/^[A-Z]/.test(t)?`component:${t}#${cd(e,t)}`:`${t}#${cd(e,t)}`}function cd(e,t){let n=$b(e);if(!n)return 0;let r=Ea.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Ea.get(n.node);o||(o=new Map,Ea.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of _n(n))if(dd(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 $b(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Oe(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function _n(e){let t=ad.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(Oe(o)){n.push(..._n(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(..._n(o));continue}o.isJSXExpressionContainer()&&n.push(...Dt(o.get("expression")))}return ad.set(e.node,n),n}function Dt(e){if(e.isJSXElement())return Oe(e)?_n(e):[e];if(e.isJSXFragment())return _n(e);if(e.isParenthesizedExpression())return Dt(e.get("expression"));if(e.isLogicalExpression())return Dt(e.get("right"));if(e.isConditionalExpression())return[...Dt(e.get("consequent")),...Dt(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Dt(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&ud(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 Oe(t)?_n(t):[t];if(t.isJSXFragment())return _n(t);if(t.isParenthesizedExpression())return Dt(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return Dt(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(...Dt(s))}if(!r.isReturnStatement())continue;let o=r.get("argument");return o.node&&n.push(...Dt(o)),n}return n}function ud(e){let t=e.callee;return(re.isMemberExpression(t)||re.isOptionalMemberExpression(t))&&re.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function Kb(e,t){let n=ld(e,t);return n?Oe(n):!1}function dd(e){return re.isJSXIdentifier(e)?e.name:re.isJSXMemberExpression(e)?fd(e):re.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function fd(e){return`${re.isJSXIdentifier(e.object)?e.object.name:fd(e.object)}.${e.property.name}`}function cn(e,t){if(t.parentPath===e&&t.listKey==="children"&&va(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!va(n))return null;let r=n;for(;r&&r!==e;){if(!va(r)||!Oe(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function va(e){return e.isJSXElement()||e.isJSXFragment()}function er(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=Pe(t,"jsx-node");if(!a.ok)return a.result;let c=ue(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return X(t,"unsupported-syntax","insert-child target must be a JSXElement or JSXFragment","jsx-node");let l=c.match.path;if(c.match.path.isJSXElement()){let v=c.match.path.node;if(!v.closingElement||v.openingElement.selfClosing)return X(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=ii(t,r.jsx);if(!u.ok)return u.result;let d=Ub(u.node,!0),f=l.node.children,g={...s,targetParentLocator:n},m=v=>s?yt(v,a.ast,d,g):v;if(o==="append")return f.push(d),m(be(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return f.unshift(d),m(be(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(!i)return X(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let h=ue(a.ast,i);if(!h.ok)return{ok:!1,source:t,diagnostic:h.diagnostic};let y=cn(c.match.path,h.match.path);if(!y)return X(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");l=y;let b=l.node.children,S=b.findIndex(v=>v===h.match.path.node);return S===-1?X(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(b.splice(o==="before"?S:S+1,0,d),m(be(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as pd from"@babel/parser";import{cloneNode as Jb}from"@babel/types";function ci(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=Pe(t,"jsx-node");if(!a.ok)return a.result;let c=Xb(t,r);if(!c.ok)return c.result;let l=ue(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return X(t,"unsupported-syntax","insert-jsx-expression-child target must be a JSXElement or JSXFragment","jsx-node");if(l.match.path.isJSXElement()){let b=l.match.path.node;if(!b.closingElement||b.openingElement.selfClosing)return X(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=l.match.path,d=null;if(i){let b=ue(a.ast,i);if(!b.ok)return{ok:!1,source:t,diagnostic:b.diagnostic};let S=cn(l.match.path,b.match.path);if(!S)return X(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=S,d=b.match.path.node}else if(o==="before"||o==="after")return X(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let f=Jb(c.node,!0),g=u.node.children,m={...s,targetParentLocator:n},h=b=>s?yt(b,a.ast,f,m):b;if(o==="append")return g.push(f),h(be(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return g.unshift(f),h(be(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let y=g.findIndex(b=>b===d);return y===-1?X(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(g.splice(o==="before"?y:y+1,0,f),h(be(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function Xb(e,t){try{let r=pd.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:X(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:X(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as zb,nullLiteral as ka}from"@babel/types";import*as ln from"@babel/types";import*as md from"@babel/types";function $r(e,t){let n=e.parentPath;if(!n?.isConditionalExpression()||e.key!=="consequent"||!md.isNullLiteral(n.node.alternate))return e;let r=n.parentPath;return!r?.isJSXExpressionContainer()||r.parentPath?.node!==t.node||r.listKey!=="children"?e:r}function tr(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=Pe(t,"jsx-node");if(!a.ok)return a.result;let c=ue(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let l=ue(a.ast,r);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return X(t,"unsupported-syntax","move-node target parent must be a JSXElement or JSXFragment","jsx-node");let u=l.match.path;if(l.match.path.isJSXElement()){let v=l.match.path.node;if(!v.closingElement||v.openingElement.selfClosing)return X(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let d=null;if(i){let v=ue(a.ast,i);if(!v.ok)return{ok:!1,source:t,diagnostic:v.diagnostic};let C=v.match.path.isJSXElement()?$r(v.match.path,l.match.path):v.match.path,P=cn(l.match.path,C);if(!P)return X(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=P,d=C}else if(o==="before"||o==="after")return X(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let f=d&&typeof d.key=="number"?d.key:-1;if(d&&f===-1)return X(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let g=c.match.path.isJSXElement()?$r(c.match.path,l.match.path):c.match.path,m=zb(g.node,!0);if(!ln.isJSXElement(m)&&!ln.isJSXExpressionContainer(m)&&!ln.isJSXFragment(m)&&!ln.isJSXText(m))return X(t,"unsupported-syntax","move-node source must resolve to a JSX child","jsx-node");let h=g.parentPath?.node===u.node&&typeof g.key=="number"?g.key:-1;if(d&&g.parentPath?.node===d.parentPath?.node&&g.key===d.key)return X(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");Wb(g);let y=u.node.children,b={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return y.push(m),yt(oi(a.ast,t),a.ast,m,b);if(o==="prepend")return y.unshift(m),yt(oi(a.ast,t),a.ast,m,b);let S=f-(h!==-1&&h<f?1:0);return y.splice(o==="before"?S:S+1,0,m),yt(oi(a.ast,t),a.ast,m,b)}function Wb(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(ka());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(ka());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(ka());return}e.remove()}import*as gd from"@babel/parser";import{cloneNode as Hb,nullLiteral as Ia}from"@babel/types";function li(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,c=Pe(t,"jsx-node");if(!c.ok)return c.result;let l=Gb(t,s);if(!l.ok)return l.result;let u=ue(c.ast,n);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};let d=ue(c.ast,r);if(!d.ok)return{ok:!1,source:t,diagnostic:d.diagnostic};if(!d.match.path.isJSXElement()&&!d.match.path.isJSXFragment())return X(t,"unsupported-syntax","move-repeat-template-child target parent must be a JSXElement or JSXFragment","jsx-node");if(d.match.path.isJSXElement()){let v=d.match.path.node;if(!v.closingElement||v.openingElement.selfClosing)return X(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let f=d.match.path,g=null;if(i){let v=ue(c.ast,i);if(!v.ok)return{ok:!1,source:t,diagnostic:v.diagnostic};let C=cn(d.match.path,v.match.path);if(!C)return X(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");f=C,g=v.match.path.node}else if(o==="before"||o==="after")return X(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!u.match.path.isJSXElement())return X(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let m=f.node,h=Hb(l.node,!0);Yb(u.match.path);let y={...a,sourceLocator:n,targetParentLocator:r},b=m.children;if(o==="append")return b.push(h),yt(be(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,y);if(o==="prepend")return b.unshift(h),yt(be(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,y);let S=b.findIndex(v=>v===g);return S===-1?X(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(b.splice(o==="before"?S:S+1,0,h),yt(be(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,y))}function Gb(e,t){try{let r=gd.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:X(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:X(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function Yb(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Ia());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Ia());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Ia());return}e.remove()}import{SiteEditSetPropsParamsSchema as Zb,classifySiteEditPropertyName as Qb}from"@vcp-dev/contracts";import*as nr from"@babel/types";function ui(e){let t=Zb.safeParse({kind:"set-props",scope:"selection",changes:e.changes});if(!t.success)return X(e.source,"unsupported-syntax","Invalid typed JSX property changes","jsx-node",{issues:t.error.issues});let n=Pe(e.source,"jsx-node");if(!n.ok)return n.result;let r=Qn(n.ast,e.locator,e.source);if(!r.ok)return r.result;for(let a of t.data.changes){let c=Qb(a.name);if(c.owner!=="generic")return X(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(nr.isJSXAttribute),s=new Map;for(let a of i){let c=qb(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 X(e.source,"unsupported-syntax",`JSX attribute '${a.name}' has multiple sources`,"jsx-node");for(let a of t.data.changes){let c=s.get(a.name)?.[0];if(a.operation==="remove"){c&&(o.attributes=o.attributes.filter(u=>u!==c));continue}let l=Dr(a.name,a.value).value;c?c.value=l:o.attributes.push(Dr(a.name,a.value))}return be(n.ast,e.source,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}function qb(e){return nr.isJSXIdentifier(e.name)?e.name.name:nr.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{SiteEditOperationParamsSchema as eS}from"@vcp-dev/contracts";import*as H from"@babel/types";var hd=["prefetch","replace","scroll","locale","onNavigate"],tS=/^on(?:Click|DoubleClick|AuxClick|MouseDown|MouseUp|PointerDown|PointerUp|TouchStart|TouchEnd|KeyDown|KeyUp|ContextMenu)(?:Capture)?$/;function nS(e){let t=e;for(;t;){if(t.isJSXElement()&&t.node.openingElement.attributes.some(n=>H.isJSXAttribute(n)&&H.isJSXIdentifier(n.name)&&tS.test(n.name.name)))return!0;t=t.parentPath}return!1}function di(e){let t=Pe(e.source,"jsx-node");if(!t.ok)return t.result;let n=Qn(t.ast,e.locator,e.source);if(!n.ok)return n.result;let r=eS.safeParse({kind:"set-link-target",scope:"selection",link:e.link,changes:e.changes});if(!r.success||r.data.kind!=="set-link-target")return Zt(e.source,"Invalid typed link-target changes");let o=n.match.path,i=o.node,s=i.openingElement,a=lS(s.name);if(!a)return Zt(e.source,"Unsupported JSX link tag");if(s.attributes.some(H.isJSXSpreadAttribute))return Zt(e.source,"Link elements with spread props cannot be transformed safely");let c=new Map;for(let m of s.attributes){if(!H.isJSXAttribute(m))continue;let h=Ra(m);if(!h)return Zt(e.source,"Unsupported JSX attribute name");let y=c.get(h)??[];y.push(m),c.set(h,y)}if([...c.values()].some(m=>m.length>1))return Zt(e.source,"Duplicate JSX attributes cannot be transformed safely");let l=c.get("href")?.[0];if(l&&!cS(l))return Zt(e.source,"Dynamic link href cannot be transformed safely");let u=a==="a",d=u?null:iS(o,s.name);if(!u&&!d)return Zt(e.source,"Only native anchors and imported next/link components are supported");if(e.link.kind==="none"&&nS(o))return Zt(e.source,"A link with an active event handler in its JSX ancestry cannot become an inert anchor");let f=null;if(e.link.kind==="internal-route")if(d)f=a;else{let m=sS(t.ast,o);if(!m.ok)return Zt(e.source,m.reason);f=m.localName}if(d&&e.link.kind!=="internal-route"){let m=H.jsxIdentifier("a");s.name=m,i.closingElement&&(i.closingElement.name=H.jsxIdentifier("a")),aS(t.ast,d,o)}else f&&u&&(s.name=H.jsxIdentifier(f),i.closingElement&&(i.closingElement.name=H.jsxIdentifier(f)));let g=new Set;return e.link.kind==="none"?(g.add("href"),g.add("target"),g.add("rel"),hd.forEach(m=>g.add(m))):(g.add("href"),e.link.kind==="native-link"&&hd.forEach(m=>g.add(m))),s.attributes=s.attributes.filter(m=>{if(!H.isJSXAttribute(m))return!0;let h=Ra(m);return!h||!g.has(h)}),e.link.kind!=="none"&&s.attributes.push(H.jsxAttribute(H.jsxIdentifier("href"),H.stringLiteral(e.link.href))),rS(s,e.changes),be(t.ast,e.source,{kind:"set-link-target",target:"jsx-node",inverse:"set-link-target"})}function rS(e,t){for(let n of t){let r=e.attributes.find(s=>H.isJSXAttribute(s)&&Ra(s)===n.name);if(n.operation==="remove"){e.attributes=e.attributes.filter(s=>s!==r);continue}let o=typeof n.value=="string"?H.stringLiteral(n.value):H.jsxExpressionContainer(Ca(n.value)),i=H.jsxAttribute(H.jsxIdentifier(n.name),o);r&&H.isJSXAttribute(r)?r.value=i.value:e.attributes.push(i)}}function Ca(e){return e===null?H.nullLiteral():typeof e=="string"?H.stringLiteral(e):typeof e=="number"?H.numericLiteral(e):typeof e=="boolean"?H.booleanLiteral(e):Array.isArray(e)?H.arrayExpression(e.map(t=>Ca(t))):typeof e=="object"?H.objectExpression(Object.entries(e).map(([t,n])=>H.objectProperty(H.isValidIdentifier(t)?H.identifier(t):H.stringLiteral(t),Ca(n)))):H.nullLiteral()}function oS(e){return H.isImportDefaultSpecifier(e)||H.isImportSpecifier(e)&&e.importKind!=="type"&&(H.isIdentifier(e.imported,{name:"default"})||H.isStringLiteral(e.imported,{value:"default"}))}function yd(e){return!e.parentPath?.isImportDeclaration()||e.parentPath.node.importKind==="type"?!1:e.isImportDefaultSpecifier()||e.isImportSpecifier()&&e.node.importKind!=="type"&&(H.isIdentifier(e.node.imported,{name:"default"})||H.isStringLiteral(e.node.imported,{value:"default"}))}function iS(e,t){if(!H.isJSXIdentifier(t))return null;let n=e.scope.getBinding(t.name);if(!n||!yd(n.path))return null;let r=n.path.parentPath;return!r?.isImportDeclaration()||r.node.source.value!=="next/link"?null:t.name}function sS(e,t){let n=e.program.body.filter(c=>H.isImportDeclaration(c)&&c.source.value==="next/link"&&c.importKind!=="type"),r=n[0],o=n.flatMap(c=>c.specifiers).find(oS);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=H.importDefaultSpecifier(H.identifier(s));if(r)r.specifiers.unshift(a);else{let c=H.importDeclaration([a],H.stringLiteral("next/link")),l=0;for(;l<e.program.body.length&&H.isImportDeclaration(e.program.body[l]);)l+=1;e.program.body.splice(l,0,c)}return{ok:!0,localName:s}}function aS(e,t,n){let r=n.scope.getProgramParent();r.crawl();let o=r.getBinding(t);if(!o||!yd(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 cS(e){return!e.value||H.isStringLiteral(e.value)}function lS(e){return H.isJSXIdentifier(e)?e.name:null}function Ra(e){return H.isJSXIdentifier(e.name)?e.name.name:null}function Zt(e,t){return X(e,"unsupported-syntax",t,"jsx-node")}import*as Ue from"@babel/types";import{classifySiteEditPropertyName as xd}from"@vcp-dev/contracts";function fi(e){let t=xd(e.name),n=xd(e.property);if(t.owner!=="generic"||n.owner!=="generic")return X(e.source,"unsupported-syntax","Property binding is only available for generic properties","jsx-node");if(!bd(e.object))return X(e.source,"unsupported-syntax","Property binding object must be a single identifier","jsx-node");if(e.property.length===0)return X(e.source,"unsupported-syntax","Property binding requires a non-empty property name","jsx-node");let r=Pe(e.source,"jsx-node");if(!r.ok)return r.result;let o=Qn(r.ast,e.locator,e.source);if(!o.ok)return o.result;let i=o.match.path.node.openingElement,s=i.attributes.filter(l=>Ue.isJSXAttribute(l)&&dS(l)===e.name);if(s.length>1)return X(e.source,"unsupported-syntax",`JSX attribute '${e.name}' has multiple sources`,"jsx-node");let a=uS(e.object,e.property),c=s[0];if(c)c.value=Ue.jsxExpressionContainer(a);else{let l=Dr(e.name,"");l.value=Ue.jsxExpressionContainer(a),i.attributes.push(l)}return be(r.ast,e.source,{kind:"set-property-binding",target:"jsx-node",inverse:"restore-property-binding"})}function uS(e,t){return bd(t)?Ue.memberExpression(Ue.identifier(e),Ue.identifier(t)):Ue.memberExpression(Ue.identifier(e),Ue.stringLiteral(t),!0)}function bd(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)}function dS(e){return Ue.isJSXIdentifier(e.name)?e.name.name:Ue.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{getBindingIdentifiers as pS,identifier as Vr,importDeclaration as mS,importDefaultSpecifier as gS,importNamespaceSpecifier as hS,importSpecifier as yS,isImportDefaultSpecifier as Sd,isImportNamespaceSpecifier as Ed,isImportSpecifier as vd,stringLiteral as xS}from"@babel/types";function rr(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(y=>!wS(y));if(o!==-1){let y=r[o],b=y&&typeof y=="object"&&"kind"in y?y.kind:void 0;return X(t,"unsupported-syntax",`Unsupported import spec kind: ${String(b)}`)}let i=IS(r);if(!i.ok)return X(t,"unsupported-syntax",i.message);let s=Pe(t);if(!s.ok)return s.result;let{ast:a}=s,c=a.program,l=c.body.filter(y=>y.type==="ImportDeclaration"&&y.source.value===n),u=new Set(l.flatMap(y=>y.specifiers.flatMap(b=>{let S=NS(y,b);return S?[S]:[]}))),d=i.imports.filter(y=>!u.has(Nd(y)));if(d.length===0)return Lr(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let f=CS(c.body),g=d.find(y=>f.has(wa(y)));if(g)return X(t,"unsupported-syntax",`Import local binding already exists: ${wa(g)}`);let m=kS(d);if(m.reduce((y,b)=>y+b.length,0)!==d.length)return X(t,"unsupported-syntax","Unsupported import specifier grouping");for(let y of m){if(!Rd(Id(y)))return X(t,"unsupported-syntax","Unsupported import specifier combination");let b=l.find(S=>bS(S,y));if(b)SS(b,y);else{let S=mS(kd(y),xS(n));RS(c.body,S),l.push(S)}}return be(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function bS(e,t){return e.importKind==="type"?!1:Rd(vS(ES(e),Id(t)))}function SS(e,t){let n=!1,r=new Set(e.specifiers.map(o=>Na(o)));for(let o of kd(t)){let i=Na(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return wd(e.specifiers),{changed:n}}function kd(e){let t=e.map(n=>{switch(n.kind){case"named":return yS(n.local?Vr(n.local):Vr(n.imported),Vr(n.imported));case"default":return gS(Vr(n.local));case"namespace":return hS(Vr(n.local));default:return n}});return wd(t),t}function Id(e){let t=Cd();for(let n of e)n.kind==="default"?t.defaultLocals.add(n.local):n.kind==="named"?t.hasNamed=!0:t.namespaceLocals.add(n.local);return t}function ES(e){let t=Cd();for(let n of e.specifiers)Sd(n)?t.defaultLocals.add(n.local.name):Ed(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function Cd(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function vS(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function Rd(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function wd(e){let t=[...e.filter(n=>Sd(n)),...e.filter(n=>Ed(n)),...e.filter(n=>vd(n))];e.splice(0,e.length,...t)}function kS(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=Nd(r);if(t.has(o))continue;let i=wa(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 CS(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(pS(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 RS(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 wS(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 Nd(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 wa(e){return e.kind==="named"?e.local??e.imported:e.local}function NS(e,t){return e.importKind==="type"||vd(t)&&t.importKind==="type"?null:Na(t)}function Na(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 or(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(u=>!AS(u));if(o!==-1){let u=r[o],d=u&&typeof u=="object"&&"kind"in u?u.kind:void 0;return X(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(d)}`)}let i=Pe(t);if(!i.ok)return i.result;let{ast:s}=i,a=s.program,c=a.body.findIndex(u=>u.type==="ImportDeclaration"&&u.source.value===n);if(c===-1)return Lr(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let l=a.body[c];return r.length===0?(a.body.splice(c,1),be(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(l.specifiers=l.specifiers.filter(u=>!r.some(d=>PS(u,d))),l.specifiers.length===0&&a.body.splice(c,1),be(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function PS(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 AS(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 Kr(e){let{source:t,locator:n,next:r}=e,o=hi(t,n);return o.ok?(o.path.replaceWith(an(r)),be(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function pi(e){let{source:t,locator:n,index:r,value:o}=e,i=hi(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(s=>s?.type==="SpreadElement")?X(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>i.path.node.elements.length?X(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,0,an(o)),be(i.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):X(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function mi(e){let{source:t,locator:n,index:r}=e,o=hi(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(i=>i?.type==="SpreadElement")?X(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=o.path.node.elements.length?X(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(o.path.node.elements.splice(r,1),be(o.ast,t,{kind:"remove-array-element",target:"value",inverse:"insert-array-element"})):X(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function gi(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=hi(t,n);if(!i.ok)return i.result;if(!i.path.isArrayExpression())return X(t,"unsupported-syntax","Array operations require array expression target","value");if(i.path.node.elements.some(c=>c?.type==="SpreadElement"))return X(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 X(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),be(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function hi(e,t){let n=Pe(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=ue(n.ast,t);return r.ok?{ok:!0,ast:n.ast,path:r.match.path}:{ok:!1,result:{ok:!1,source:e,diagnostic:r.diagnostic}}}import*as ze from"@babel/types";function yi(e){let t=Pe(e.source,"value");if(!t.ok)return t.result;let n=ue(t.ast,e.objectLocator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};if(!n.match.path.isObjectExpression())return X(e.source,"unsupported-syntax","Object property upsert requires an ObjectExpression parent","value");let r=n.match.path.node;if(r.properties.some(a=>ze.isSpreadElement(a)||ze.isObjectProperty(a)&&a.computed))return X(e.source,"unsupported-syntax","Object property upsert does not support spreads or computed keys","value");let o=r.properties.filter(a=>ze.isObjectProperty(a)&&TS(a.key)===e.name);if(o.length>1)return X(e.source,"unsupported-syntax",`Object property '${e.name}' has multiple sources`,"value");let i=e.value.kind==="undefined"?ze.unaryExpression("void",ze.numericLiteral(0)):an(e.value.value),s=o[0];if(s)s.value=i,s.shorthand=!1;else{let a=ze.objectProperty(xa(e.name),i);e.name==="__proto__"&&(a.computed=!0),r.properties.push(a)}return be(t.ast,e.source,{kind:"upsert-object-property",target:"value",inverse:"restore-object-property"})}function TS(e){return ze.isIdentifier(e)?e.name:ze.isStringLiteral(e)?e.value:ze.isNumericLiteral(e)?String(e.value):null}import{isSiteEditRuntimeContainerTag as FS,isSiteEditRuntimeVoidElementTag as _S}from"@vcp-dev/contracts/site-edit-runtime-capability";function ir(e){if(!e.composition)throw new Error("Composition unavailable for render source graph.");return e.composition}function MS(e,t,n){let r=ir(n),o=t.nodes.get(e),i=n.elements.get(e);if(!o||!i)return{composition:r,key:e,canUpdateText:!1,canInsertChild:!1,canMove:!1,canRemove:!1,constraints:[{kind:"opaque-region",message:"Node not found in graph"}]};let s=o.constraints.map(C=>({kind:C.kind,message:C.reason})),a=i.isOpaque,l=o.parentKey===null&&i.componentName==="Page",u=i.tag.toLowerCase(),d=i.tag!==u,f=!d&&_S(u),g=d||FS(u),m=d&&i.childKeys.length>0&&!i.isPublicUiComponent,h=i.textSegments.length>0&&i.textSegments.some(C=>C.editable);f&&!s.some(C=>C.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' is void: children cannot be inserted`}),!f&&!g&&!s.some(C=>C.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' cannot contain structured children`});let y=h&&(!a||i.importedFrom==="next/link"),b=!i.isPublicUiComponent&&!f&&g&&(!a||m);return{composition:r,key:e,canUpdateText:y,canInsertChild:b,canMove:!l,canRemove:!l,constraints:s}}function Pd(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,MS(r,e,t));return n}function Pa(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:Re(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=OS(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:Re(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Unable to locate JSX element for key ${t.identity.key}`}]};let r=n.node.openingElement,o=r.attributes.find(d=>d.type==="JSXAttribute"&&d.name.type==="JSXIdentifier"&&d.name.name==="className"),i={key:e.key,composition:e.route.composition,filePath:t.sourceFile,componentName:t.componentName,openingElementRange:Td(r),version:{documentVersion:e.route.graph.version,contentHash:Re(e.route.source)}};if(!o)return{...i,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element."}]};let s=o.value,a=s?.type==="StringLiteral"?"stringLiteral":"expression",c=n.get("openingElement").get("attributes").find(d=>d.node===o),l=c?.isJSXAttribute()?c.get("value"):null,u=l?.isJSXExpressionContainer()?LS(l.get("expression")):void 0;return{...i,sourceKind:a,attrRaw:Ad(e.route.source,o),valueRaw:s?Ad(e.route.source,s):null,...u===void 0?{}:{resolvedClassName:u},attrRange:Td(o),diagnostics:[]}}function Fd(e){let{source:t,oldAttrRange:n,openingElementRange:r,newAttrRaw:o}=e;if(n){let a=n.start>0&&/\s/.test(t[n.start-1]??"")?n.start-1:n.start,c=o?`${a<n.start?" ":""}${o}`:"";return t.slice(0,a)+c+t.slice(n.end)}if(!o)return t;let i=r.end,s=t.slice(Math.max(0,i-2),i)==="/>"?i-2:i-1;return t.slice(0,s)+` ${o}`+t.slice(s)}function OS(e,t){let n=Mt({source:e,profile:wn({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=ue(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:DS(t.sourceRange)});return!r.ok||!r.match.path.isJSXElement()?null:r.match.path}function LS(e){let t=new Set,n=e;if(n.isIdentifier()){for(;n.isIdentifier();){let r=n.scope.getBinding(n.node.name);if(!r?.constant||!r.path.isVariableDeclarator()||!r.path.get("id").isIdentifier({name:n.node.name})||!r.path.parentPath.isVariableDeclaration({kind:"const"})||t.has(r.path.node))return;t.add(r.path.node);let o=r.path.get("init");if(!o.isExpression())return;n=o}if(n.isStringLiteral())return n.node.value;if(n.isTemplateLiteral()&&n.node.expressions.length===0)return n.node.quasis.map(r=>r.value.cooked??r.value.raw).join("")}}function _d(e){let t=Mt({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 Ad(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function Td(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 DS(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function Md(){let e=new Set;return{emit(t){for(let n of Array.from(e))try{n(t)}catch{}},subscribe(t){return e.add(t),()=>{e.delete(t)}}}}import{randomUUID as BS}from"node:crypto";import xi from"node:fs/promises";import Aa from"node:path";import{setTimeout as jS}from"node:timers/promises";var $S={async mkdir(e,t){await xi.mkdir(e,t)},async writeFile(e,t,n){await xi.writeFile(e,t,n)},async rename(e,t){await xi.rename(e,t)},async rm(e,t){await xi.rm(e,t)}},VS=new Set(["EACCES","EBUSY","EPERM"]),KS=[10,20,40,80,160];async function US(e,t,n){for(let r of KS)try{await e.rename(t,n);return}catch(o){if(!JS(o))throw o;await jS(r)}await e.rename(t,n)}function JS(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&VS.has(e.code)}async function bi(e,t,n=$S){let r=Aa.dirname(e),o=Aa.basename(e),i=Aa.join(r,`.${o}.${process.pid}.${BS()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await US(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import Ta from"@babel/traverse";import*as I from"@babel/types";import*as me from"@babel/types";function Bt(e,t={}){if(me.isTSAsExpression(e)||me.isTSSatisfiesExpression(e)||me.isTSNonNullExpression(e)||me.isTypeCastExpression(e)||me.isParenthesizedExpression(e))return Bt(e.expression,t);if(me.isStringLiteral(e))return{status:"resolved",value:e.value};if(me.isNumericLiteral(e))return Number.isFinite(e.value)?{status:"resolved",value:e.value}:{status:"unresolved"};if(me.isBooleanLiteral(e))return{status:"resolved",value:e.value};if(me.isNullLiteral(e))return{status:"resolved",value:null};if(me.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(me.isIdentifier(e))return e.name==="undefined"&&!t.resolveIdentifier?{status:"undefined"}:t.resolveIdentifier?.(e.name)??{status:"unresolved"};if(me.isUnaryExpression(e)&&e.operator==="void"&&me.isNumericLiteral(e.argument)&&e.argument.value===0)return{status:"undefined"};if(me.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||me.isSpreadElement(r))return{status:"unresolved"};let o=Bt(r,t);if(o.status!=="resolved")return{status:"unresolved"};n.push(o.value)}return{status:"resolved",value:n}}if(me.isObjectExpression(e)){let n=Object.create(null);for(let r of e.properties){if(!me.isObjectProperty(r)||r.computed||!me.isExpression(r.value))return{status:"unresolved"};let o=XS(r.key);if(o===null)return{status:"unresolved"};let i=Bt(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 me.isMemberExpression(e)||me.isOptionalMemberExpression(e)?t.resolveMember?.(e)??{status:"unresolved"}:{status:"unresolved"}}function XS(e){return me.isIdentifier(e)?e.name:me.isStringLiteral(e)?e.value:me.isNumericLiteral(e)?String(e.value):null}var zS=typeof Ta=="function"?Ta:Ta.default;function Ze(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 La(e){let t=e.openingElement;return I.isJSXIdentifier(t.name)?t.name.name==="Fragment":I.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function ar(e){return I.isJSXFragment(e)}function Ld(e){return I.isJSXIdentifier(e.name)?e.name.name:I.isJSXMemberExpression(e.name)?Dd(e.name):I.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function Dd(e){return I.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:I.isJSXMemberExpression(e.object)?`${Dd(e.object)}.${e.property.name}`:e.property.name}function HS(e){return e.split(".")[0]??e}function GS(e){let t=e;for(;t;){let n=t.node;if(I.isFunctionDeclaration(n)&&n.id||I.isVariableDeclarator(n)&&I.isIdentifier(n.id))return n.id.name;if(I.isExportDefaultDeclaration(n)){let r=n.declaration;if(I.isFunctionDeclaration(r)&&r.id)return r.id.name;if(I.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function YS(){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 ZS(e){let t=new Map;for(let n of e.program.body){if(!I.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(I.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(I.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(I.isImportSpecifier(o)){let i=I.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function Qt(e,t=[]){if(I.isIdentifier(e))return t.push(e.name),t;if(I.isObjectPattern(e)){for(let n of e.properties)I.isObjectProperty(n)?Qt(n.value,t):I.isRestElement(n)&&Qt(n.argument,t);return t}if(I.isArrayPattern(e)){for(let n of e.elements)n&&(I.isRestElement(n)?Qt(n.argument,t):Qt(n,t));return t}return I.isAssignmentPattern(e)?(Qt(e.left,t),t):(I.isRestElement(e)&&Qt(e.argument,t),t)}function Ct(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Ur(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 QS(e,t,n){e.set(t,{resolved:!0,value:n})}function Da(e,t){e.set(t,{resolved:!1})}function Bd(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 Ve(e,t,n){if(I.isTSAsExpression(e)||I.isTSSatisfiesExpression(e)||I.isTSNonNullExpression(e)||I.isTypeCastExpression(e)||I.isParenthesizedExpression(e))return Ve(e.expression,t,n);if(I.isLogicalExpression(e))return Si([Ve(e.left,t,n),Ve(e.right,t,n)]);if(I.isBinaryExpression(e))return Si([I.isExpression(e.left)?Ve(e.left,t,n):null,I.isExpression(e.right)?Ve(e.right,t,n):null]);if(I.isConditionalExpression(e))return Si([Ve(e.consequent,t,n),Ve(e.alternate,t,n)]);if(I.isTemplateLiteral(e))return Si(e.expressions.filter(I.isExpression).map(i=>Ve(i,t,n)));if(I.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!I.isMemberExpression(e)&&!I.isOptionalMemberExpression(e))return null;let r=[],o=e;for(;I.isMemberExpression(o)||I.isOptionalMemberExpression(o);){if(o.computed)if(I.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(I.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&I.isExpression(o.property)){let i=un(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(!I.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return I.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:Ct(e,t),base:o.name,path:r}:null}function Si(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 un(e,t){if(I.isStringLiteral(e)||I.isNumericLiteral(e)||I.isBooleanLiteral(e))return e.value;if(I.isNullLiteral(e))return null;if(I.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(I.isIdentifier(e)){let n=Ur(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(I.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||I.isSpreadElement(r))return;let o=un(r,t);if(o===void 0)return;n.push(o)}return n}if(I.isObjectExpression(e)){let n={};for(let r of e.properties){if(!I.isObjectProperty(r)||r.computed||!I.isExpression(r.value))return;let o=null;if(I.isIdentifier(r.key)?o=r.key.name:I.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!I.isIdentifier(r.value))return;let s=Ur(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=un(r.value,t);if(i===void 0)return;n[o]=i}return n}if(I.isMemberExpression(e)){let n=Ve(e,"",t);if(!n)return;let r=Ur(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=Bd(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(I.isCallExpression(e))return $d(e,t)??void 0}function jd(e,t,n){let r=Ve(e,n,t);if(!r)return I.isMemberExpression(e)||I.isBinaryExpression(e)||I.isLogicalExpression(e)||I.isConditionalExpression(e)||I.isCallExpression(e)?{value:Ct(e,n),source:null}:null;let o=Ur(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?Bd(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 Fa(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:YS(),parentStack:[],valueScopes:i,importMap:o}}function Ma(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of Qt(o.id))Da(n,s);if(!I.isIdentifier(o.id)||!o.init||!I.isExpression(o.init))continue;let i=un(o.init,t);i!==void 0&&QS(n,o.id.name,i)}}function qS(e){let t=[];for(let n of e){if(I.isVariableDeclaration(n)){t.push(n);continue}I.isExportNamedDeclaration(n)&&n.declaration&&I.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function eE(e,t,n){let r=[],o=0;for(let i of e)if(I.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:Ze(i),editable:!0,source:null})}else if(I.isJSXExpressionContainer(i)&&I.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:Ze(i),editable:!0,source:null});else if(I.isJSXExpressionContainer(i)&&I.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:Ze(i),editable:!0,source:null}):r.push({index:o++,value:Ct(s,n),sourceRange:Ze(i),editable:!0,source:Ve(s,n,t)})}else if(I.isJSXExpressionContainer(i)&&I.isExpression(i.expression)){let s=jd(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:Ze(i),editable:!0,source:s.source})}return r}function tE(e,t,n){let r=[];for(let[o,i]of e.attributes.entries()){if(!I.isJSXAttribute(i))continue;let s=rE(i.name);if(!s)continue;let a=Ct(i,n);if(I.isStringLiteral(i.value)){r.push({name:s,value:i.value.value,sourceRange:Ze(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:Ze(i),source:null,syntaxKind:"boolean-shorthand",raw:a,order:o,resolution:{status:"resolved",value:!0},resolvedValue:!0});continue}if(I.isJSXExpressionContainer(i.value)&&I.isExpression(i.value.expression)){let c=un(i.value.expression,t);if(s==="className"){let g=typeof c=="string"?c:c===void 0?$d(i.value.expression,t):null;if(g){r.push({name:s,value:g,sourceRange:Ze(i),source:null,resolvedValue:g,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:g}});continue}}let l=jd(i.value.expression,t,n);if(c!==void 0){r.push({name:s,value:uE(c),sourceRange:Ze(i),source:Ve(i.value.expression,n,t),resolvedValue:c,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:c}});continue}let u=oE(i.value.expression,t),d=Ve(i.value.expression,n,t),f=l?.value??Ct(i.value.expression,n);r.push({name:s,value:u.status==="undefined"?"undefined":f,sourceRange:Ze(i),source:l?.source??d,syntaxKind:"expression",raw:a,order:o,resolution:u})}}return r}function nE(e,t,n){return e.attributes.flatMap((r,o)=>!I.isJSXSpreadAttribute(r)||!I.isExpression(r.argument)?[]:[{raw:Ct(r.argument,n),sourceRange:Ze(r),order:o,source:Ve(r.argument,n,t)}])}function rE(e){return I.isJSXIdentifier(e)?e.name:I.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function oE(e,t){return Bt(e,{resolveIdentifier(n){let r=Ur(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=un(n,t);return r===void 0?{status:"unresolved"}:{status:"resolved",value:r}}})}function $d(e,t){let n=sr(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function sr(e,t){if(I.isStringLiteral(e))return[e.value];if(I.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(I.isNullLiteral(e))return[];if(I.isBooleanLiteral(e))return e.value?null:[];if(I.isIdentifier(e)||I.isMemberExpression(e)){if(I.isIdentifier(e)&&e.name==="undefined")return[];let n=un(e,t);return typeof n=="string"?[n]:null}if(I.isConditionalExpression(e)){let n=sr(e.consequent,t),r=sr(e.alternate,t);return!n||!r?null:[...n,...r]}if(I.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=un(e.left,t);return n===!1||n===null?[]:sr(e.right,t)}if(I.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||I.isSpreadElement(r))return null;let o=sr(r,t);if(!o)return null;n.push(...o)}return n}if(I.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!I.isObjectProperty(r))return null;let o=sE(r.key);if(!o)return null;n.push(o)}return n}if(I.isCallExpression(e)){let n=iE(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!I.isExpression(o))return null;let i=sr(o,t);if(!i)return null;r.push(...i)}return r}return null}function iE(e){return I.isIdentifier(e)?e.name:I.isMemberExpression(e)&&I.isIdentifier(e.property)?e.property.name:null}function sE(e){return I.isIdentifier(e)?e.name:I.isStringLiteral(e)?e.value:null}function aE(e,t){let n=e.attributes.find(r=>I.isJSXAttribute(r)&&I.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!I.isJSXAttribute(n)||!I.isJSXExpressionContainer(n.value)?null:n.value.expression}function cE(e,t){for(let n of t){let r=aE(e,n);if(r)return r}return null}function lE(e){return I.isJSXIdentifier(e.name)?e.name.name:null}function uE(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function dE(e){if(!I.isCallExpression(e)&&!I.isOptionalCallExpression(e))return null;let t=e.callee;return!I.isMemberExpression(t)&&!I.isOptionalMemberExpression(t)||!I.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!I.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function _a(e){return I.isArrowFunctionExpression(e)||I.isFunctionExpression(e)}function fE(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function pE(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function Od(e,t,n,r){if(!e||!I.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:Ct(e,n),collectionSource:Ve(e,n,r)};if(t){let i=t.params[0],s=t.params[1];I.isIdentifier(i)&&(o.itemParamName=i.name),I.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function qt(e,t,n){if(!e)return[];if(I.isJSXElement(e)){if(La(e))return Ci(e.children,t,n);let r=ki(e,t,n);return r?[r]:[]}return ar(e)?Ii(e,t,n):I.isParenthesizedExpression(e)?qt(e.expression,t,n):I.isExpression(e)?Ri(e,t,n):[]}function Ei(e,t,n){let r=new Map;for(let o of e.params)for(let i of Qt(o))Da(r,i);t.valueScopes.push(r);try{if(!I.isBlockStatement(e.body))return qt(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return Vd(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function Vd(e,t,n){let r=[];for(let o of e){if(I.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];if(i){Ma([o],t,i);for(let s of o.declarations)I.isIdentifier(s.id)&&(I.isJSXElement(s.init)||I.isJSXFragment(s.init))&&r.push(...qt(s.init,t,n))}continue}r.push(...Oa(o,t,n))}return r}function Oa(e,t,n){if(I.isReturnStatement(e))return e.argument?qt(e.argument,t,n):[];if(I.isBlockStatement(e))return Mn(e.body,t,n);if(I.isIfStatement(e)){let r=I.isBlockStatement(e.consequent)?Mn(e.consequent.body,t,n):Oa(e.consequent,t,n),o=e.alternate?I.isBlockStatement(e.alternate)?Mn(e.alternate.body,t,n):Oa(e.alternate,t,n):[];return[...r,...o]}if(I.isSwitchStatement(e))return Mn(e.cases.flatMap(r=>r.consequent),t,n);if(I.isTryStatement(e)){let r=Mn(e.block.body,t,n);return e.handler&&r.push(...Mn(e.handler.body.body,t,n)),e.finalizer&&r.push(...Mn(e.finalizer.body,t,n)),r}return[]}function Mn(e,t,n){let r=new Map;t.valueScopes.push(r);try{return Vd(e,t,n)}finally{t.valueScopes.pop()}}function vi(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:Ze(r),sourceCandidates:i&&i.length>0?i:void 0})}function mE(e,t,n,r){let o=cE(e.openingElement,["items","dataSource","data"]),i={key:t,tag:Ld(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!I.isJSXAttribute(s))continue;let a=lE(s);if(!a||!I.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!I.isJSXEmptyExpression(c)){if(fE(a)&&_a(c)){let l=Ei(c,n,r),u=Od(o,c,r,n);vi(n,"repeat-region",t,s,l,u?[u]:void 0);continue}if(pE(a)){let l=_a(c)?Ei(c,n,r):qt(c,n,r);vi(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!I.isJSXExpressionContainer(s)||!_a(s.expression))continue;let a=Ei(s.expression,n,r),c=Od(o,s.expression,r,n);vi(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function ki(e,t,n){let r=Ld(e.openingElement);if(r==="Fragment"||La(e))return Ci(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,u=Br(t.file,t.componentName,l),d={file:t.file,component:t.componentName,structuralPath:l,key:u},f=s?"component-boundary":null,g=eE(e.children,t,n),m=tE(e.openingElement,t,n),h=nE(e.openingElement,t,n),y,b,S=!1;if(s){let C=t.importMap.get(r)??t.importMap.get(HS(r));C&&(y=C.specifier,b=C.exportName,S=Nn(C.specifier,t.file))}let v={identity:d,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:Ze(e),parentKey:i,childKeys:[],textSegments:g,attributes:m.length>0?m:void 0,attributeSpreads:h.length>0?h:void 0,boundaryKind:f,isOpaque:s,...S?{isPublicUiComponent:!0}:{},importedFrom:y,exportName:b};return t.elements.set(u,v),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(u),mE(e,u,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:u,tag:r}),gE(e.children,t,n),t.parentStack.pop()),u}function Ii(e,t,n){return Ci(e.children,t,n)}function Ci(e,t,n){let r=[];for(let o of e)if(I.isJSXElement(o))if(La(o))r.push(...Ci(o.children,t,n));else{let i=ki(o,t,n);i&&r.push(i)}else ar(o)?r.push(...Ii(o,t,n)):I.isJSXExpressionContainer(o)&&r.push(...Ri(o.expression,t,n));return r}function gE(e,t,n){for(let r of e)I.isJSXElement(r)?ki(r,t,n):ar(r)?Ii(r,t,n):I.isJSXExpressionContainer(r)&&Ri(r.expression,t,n)}function hE(e){return e==="&&"||e==="||"||e==="??"}function Ri(e,t,n){if(I.isJSXEmptyExpression(e))return[];let r=dE(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,c={kind:"repeat-template",collectionExpression:Ct(r.collection,n),collectionSource:Ve(r.collection,n,t)};if(I.isArrowFunctionExpression(a)||I.isFunctionExpression(a)){let u=a.params[0],d=a.params[1];I.isIdentifier(u)&&(c.itemParamName=u.name),I.isIdentifier(d)&&(c.indexParamName=d.name)}s.push(c);let l={kind:"repeat-region",ownerKey:i?.key??"",childKeys:[],sourceRange:Ze(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(l),(I.isArrowFunctionExpression(a)||I.isFunctionExpression(a))&&l.childKeys.push(...Ei(a,t,n)),l.childKeys}if(I.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:Ct(e.test,n),conditionSource:Ve(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Ze(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...qt(e.consequent,t,n)),s.childKeys.push(...qt(e.alternate,t,n)),s.childKeys}if(I.isLogicalExpression(e)&&hE(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:Ct(e.left,n),conditionSource:Ve(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Ze(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...qt(e.right,t,n)),s.childKeys}if(I.isParenthesizedExpression(e))return Ri(e.expression,t,n);if(I.isJSXElement(e)){let o=ki(e,t,n);return o?[o]:[]}return ar(e)?Ii(e,t,n):[]}function yE(e){let t=e.argument;return t&&(I.isExpression(t)||ar(t))?t:null}function Jr(e,t){let n=[];for(let r of e){if(I.isReturnStatement(r)){let o=yE(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(I.isIfStatement(r)){let o=I.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...Jr(o,r.test)),r.alternate){let i=I.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...Jr(i,r.test))}continue}if(I.isSwitchStatement(r))for(let o of r.cases){let i=o.test?I.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...Jr(o.consequent,i))}}return n}function wi(e){return{routeId:e,rootKeys:[],elements:new Map,regions:[],fileIndex:new Map,version:1,diagnostics:[]}}function Kd(e){let{file:t,source:n,ast:r}=e,o=e.imports.map(f=>f.specifier);if(!I.traverseFast(r,f=>{if(I.isJSXElement(f)||I.isJSXFragment(f))return I.traverseFast.stop}))return{graph:wi(t),localImports:o};let s=new Map,a=[],c=[],l=new Map,u=ZS(r);zS(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(f){let g=GS(f);if(!g)return;let m=f.node,h=[];if(I.isArrowFunctionExpression(m))I.isExpression(m.body)||ar(m.body)?h=[{argument:m.body,statement:I.returnStatement(I.isExpression(m.body)?m.body:null)}]:I.isBlockStatement(m.body)&&(h=Jr(m.body.body));else{let P=m.body;I.isBlockStatement(P)&&(h=Jr(P.body))}if(h.length===0){f.skip();return}let y=new Map;Ma(qS(r.program.body),Fa(t,g,s,a,u,[y]),y);let b=new Map;for(let P of m.params)for(let F of Qt(P))Da(b,F);let S=I.isBlockStatement(m.body)?m.body.body:[],v=h[0]?.statement??null;for(let P of S){if(v&&P===v)break;I.isVariableDeclaration(P)&&Ma([P],Fa(t,g,s,a,u,[y,b]),b)}let C=Fa(t,g,s,a,u,[y,b]);for(let P of h){let F=qt(P.argument,C,n);for(let R of F)c.includes(R)||c.push(R);if(P.condition){let R={kind:"conditional-branch",conditionExpression:Ct(P.condition,n),conditionSource:Ve(P.condition,n,C)};vi(C,"conditional-region","",P.statement,F,[R])}}f.skip()}});let d=[...s.keys()];return d.length>0&&l.set(t,d),{graph:{routeId:t,rootKeys:c,elements:s,regions:a,fileIndex:l,version:1,diagnostics:[]},localImports:o}}function Ba(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function Ni(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function Ud(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 Jd(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??Wt,c=new Map,l=new Map,u=new Map,d=[],f=new Set,g=b=>{let S=`${b.path}\0${b.code}\0${b.message}\0${JSON.stringify(b.details??{})}`;f.has(S)||(f.add(S),d.push(b))},m=[{file:e,source:t,depth:0,diagnosticEntryFile:e,importStack:[]},...(o.additionalEntries??[]).map(b=>({file:b.file,source:b.source,depth:0,diagnosticEntryFile:b.file,importStack:[]}))],h=new Set;for(;m.length>0;){let b=m.shift(),{file:S,source:v,depth:C,diagnosticEntryFile:P,importStack:F}=b;if(h.has(S))continue;h.add(S),c.set(S,v);let R=o.validationOnly&&C<i?o.validatedImports?.(S,v):void 0,N,T;if(R)N=wi(S),T=R;else{let D=a(S,v);if(!D.ok){g(Ni(D.diagnostic,P,F));continue}u.set(S,D.module);let Z=o.validationOnly&&C<i?{graph:wi(S),localImports:D.module.imports.map(fe=>fe.specifier)}:Kd(D.module);N=Z.graph,T=Z.localImports}let L=[...new Set([...N.elements.values()].map(D=>D.importedFrom).filter(D=>typeof D=="string"&&It(D)))],q=L.length?await Ud(L,D=>Vo(S,D,r)):[],W=new Map(L.map((D,Z)=>[D,q[Z]]));for(let D of N.elements.values())if(D.importedFrom&&It(D.importedFrom)){let Z=D.importedFrom,fe=W.get(Z);fe.ok?(D.importedFrom=fe.path,Ht(fe.path)&&(D.isPublicUiComponent=!0)):Nn(Z,S)||g(Ni(fe.diagnostic,P,Ba(F,S,Z,fe.diagnostic.path)))}if(l.set(S,N),C>=i)continue;let oe=await Ud(T,async D=>{if(Iu(D))return null;let Z=W.get(D)??await Vo(S,D,r);if(!Z.ok)return Nn(D,S)?null:{diagnostic:Ni(Z.diagnostic,P,Ba(F,S,D,Z.diagnostic.path))};let fe=Z.path;if(h.has(fe)||Ht(fe))return null;let ct=Ba(F,S,D,fe);try{let rt=await n(fe);return{entry:{file:fe,source:rt,depth:C+1,diagnosticEntryFile:P,importStack:ct}}}catch(rt){return{diagnostic:Ni({path:fe,code:"import-read-failed",message:`Failed to read imported file: ${fe}`,details:{fromFile:S,specifier:D,reason:rt instanceof Error?rt.message:String(rt)}},P,ct)}}});for(let D of oe)D&&"entry"in D?m.push(D.entry):D&&g(D.diagnostic)}let y=xE(e,l,s,(o.additionalEntries??[]).map(b=>b.file));return y.diagnostics=d,{graph:y,allSources:c,diagnostics:d,parsedModules:u,entryModule:u.get(e)??null}}function xE(e,t,n,r=[]){let o=new Map,i=[],s=new Map,a=[];for(let[c,l]of t){for(let[u,d]of l.elements)o.set(u,d);for(let u of l.regions)i.push(u);for(let[u,d]of l.fileIndex){let f=s.get(u)??[];s.set(u,[...f,...d])}if(c===e){a=l.rootKeys;continue}r.includes(c)&&(a=[...a,...l.rootKeys])}return{routeId:e,rootKeys:a,elements:o,regions:i,fileIndex:s,version:n}}function Xd(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 bE,randomUUID as Ha}from"node:crypto";import Le from"node:fs/promises";import Be from"node:path";var tf=new WeakMap;function cr(e){return tf.get(e)?.()??e.readIndex()}var xt=1,$a=1,SE=2,EE="index.json",vE="recovery.json",kE="transaction-journal.json",IE="document-version.json",Ti={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},se={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"},ce=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};function en(){return{entries:new Map,blobSizes:new Map}}function Pi(e,t){let n={entries:new Map,blobs:new Map,objectBytes:0};for(let r of e)nf(n,r,t);return n}function nf(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 rf(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 of(e,t={}){let n=VE(e),r=XE(t.limits),o=ja(n),i=KE(n),s=await ot(i),a=await ot(o)||s;a||(await _E(n),await ME(n)),a||await zE(n);let c=en(),l=await _i(n,c),u=new Set(a?(await Bi(n)).map(S=>S.stageId):[]);a||await Yd(n,l.entryIds,c);let d=l.digest,f=Pi(l.entryIds,c),g=async S=>{let{index:v,sizeBytes:C}=await Gr(n);if(ff(v,S),v.digest!==d){let P=en();await lf(n,v.entryIds,P,C),f=Pi(v.entryIds,P),d=v.digest}return{...ji(v),totalBytes:f.objectBytes+C}},m=async S=>{Ga(S),await g(),await Hd(n,f,[S.entryId],S.blobIds,S.stageId),await Fi(n,S.stageId)},h=async(S,v)=>{let C=await g(v);af(S,C.entryIds.length);let P=en();for(let F of C.entryIds.slice(Math.min(C.cursor,S)+1,Math.max(C.cursor,S)+1))await zr(n,F,P);return C},y=async()=>{if(await ot(o)||s)throw new ce(se.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")},b={rootDir:n,recoveryRequired:a,async readDocumentVersion(){return qd(n)},async writeDocumentVersion(S){if(await y(),!Number.isInteger(S)||S<0)throw new ce(se.INVALID_SCHEMA,"document version must be a non-negative integer");let v=await qd(n);S<=v||await Xr(hf(n),{schemaVersion:1,version:Math.max(v,S)})},async stageAppend(S,v={}){await y();let C=await wE(S,r),P={schemaVersion:$a,stageId:Ha(),entryId:C.entryId,blobIds:C.blobs.map(F=>F.digest)};try{await NE(n,C),await AE(n,P,v.durableManifest!==!1)}catch(F){try{await m(P)}catch(R){throw new ce(se.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:R})}throw F}return{stageId:P.stageId,entryId:P.entryId,blobIds:P.blobIds}},async discardStage(S){await y(),Ua(S);let v=await Va(n,S);v&&await m(v)},async previewStagedAppend(S,v){await y();let C=await g(v);return(await zd(n,r,S,C,f)).transition},async previewCursor(S,v){await y();let C=await h(S,v);return sf(C,C.entryIds,S)},async publishStagedAppend(S,v,C){if(await y(),Oi(S,"entryId"),C){Ua(C);let T=await Va(n,C);if(!T||T.entryId!==S)throw new ce(se.INVALID_SCHEMA,"history stage does not match the published entry")}let P=await g(v),F=f,R=await zd(n,r,S,P,F),N=await Qd({rootDir:n,previousDigest:R.current.digest,entryIds:R.entryIds,cursor:R.cursor,readback:async()=>Zd(n,R.usage),afterWrite:async()=>{C?await Fi(n,C):await FE(n,S),await Hd(n,R.usage,[...F.entries.keys()].filter(T=>!R.usage.entries.has(T)),[...F.blobs.keys()].filter(T=>!R.usage.blobs.has(T)))}});return f=R.usage,d=N.digest,N},async append(S){await y();let v=await g(),C=await b.stageAppend(S);try{return await b.publishStagedAppend(C.entryId,v.digest,C.stageId)}catch(P){throw await b.discardStage(C.stageId),P}},async readEntry(S){return Oi(S,"entryId"),zr(n,S)},async readBlob(S){Oi(S,"blobId");let v=await xf(n,S),C=await Wr(v,se.NOT_FOUND,"blob");return gf(C,S,v),C},async readIndex(){let S=en(),v=await _i(n,S);return f=Pi(v.entryIds,S),d=v.digest,v},async readStatus(){let S=await Mi(n);return{canUndo:S.undoIds.length>0,canRedo:S.redoIds.length>0,undoDepth:S.undoIds.length,redoDepth:S.redoIds.length,cursor:S.cursor,recoveryRequired:await ot(o)||await ot(i)}},async readUndoRedoIds(){let S=await Mi(n);return{undoIds:S.undoIds,redoIds:S.redoIds,currentId:S.currentId}},async setCursor(S,v){await y();let C=await h(S,v),P=await Qd({rootDir:n,previousDigest:C.digest,entryIds:C.entryIds,cursor:S,readback:async()=>Zd(n,f)});return d=P.digest,P},async markRecoveryRequired(S){await ot(o)||await Xr(ja(n),{schemaVersion:xt,reason:UE(S),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await Le.rm(ja(n),{force:!0})},async readTransactionJournal(){return await ot(i)?Ai(i):null},async writeTransactionJournal(S){await y(),yf(S);try{await Xr(i,S)}catch(C){let P=await Ai(i).catch(()=>null);if(P&&Buffer.from(it(P)).equals(Buffer.from(it(S))))return;throw P?new ce(se.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:C}):C}let v=await Ai(i);if(!Buffer.from(it(v)).equals(Buffer.from(it(S))))throw new ce(se.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(S){let v=await ot(i)?await Ai(i):null;if(v&&v.transactionId!==S)throw new ce(se.INVALID_SCHEMA,"transaction journal changed concurrently");try{await Le.rm(i,{force:!0})}catch(C){if(!await ot(i))return;throw C}if(await ot(i))throw new ce(se.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await y();for(let C of u)await Fi(n,C),u.delete(C);await OE(n);let S=en(),v=await _i(n,S);await Yd(n,v.entryIds,S),f=Pi(v.entryIds,S),d=v.digest}};return tf.set(b,()=>Mi(n)),b}async function zd(e,t,n,r,o){Oi(n,"entryId");let i=en(),s=await zr(e,n,i),a={entries:new Map(o.entries),blobs:new Map(o.blobs),objectBytes:o.objectBytes},c=r.entryIds.slice(0,r.cursor+1);for(let u of r.entryIds.slice(r.cursor+1))rf(a,u);nf(a,s.id,i),c.push(s.id);let l=PE(c,t,a);return{current:r,entryIds:l.entryIds,cursor:l.cursor,usage:a,transition:sf(r,l.entryIds,l.cursor)}}function sf(e,t,n){return af(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:CE(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function CE(e,t){return dn(it({schemaVersion:xt,entryIds:e,cursor:t}))}function af(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new ce(se.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function RE(e){if(!Rt(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!ut(e.expectedIndexDigest)||!ut(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!ut(n)?!1:t===-1?n===null:ut(n)}async function wE(e,t){if(!e.kind.trim())throw new ce(se.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new ce(se.INVALID_JSON,"history blob name must not be empty");let l=$E(c.data),u=dn(l);n.push({name:c.name,bytes:l,digest:u,sizeBytes:l.byteLength}),r.push({name:c.name,digest:u,sizeBytes:l.byteLength})}let o={schemaVersion:xt,kind:e.kind,manifest:e.manifest,blobs:r},i=it({...o}),s=dn(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new ce(se.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function NE(e,t){let n=qa(e,t.entryId),r={id:t.entryId,...t.entryBody},o=new Map(t.blobs.map(c=>[c.digest,c])),i=[...Array.from(o.values(),c=>Wd(ec(e,c.digest),c.bytes,{kind:"blob",digest:c.digest},nc(e,c.digest))),Wd(n,it(r),{kind:"entry",digest:t.entryId},tc(e,t.entryId))],a=(await Promise.allSettled(i)).find(c=>c.status==="rejected");if(a)throw a.reason}async function Wd(e,t,n,r){let o=await za(e)??(r?await za(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new ce(n.kind==="blob"?se.BLOB_CORRUPT:se.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await pf(e,t)}function PE(e,t,n){let r=[...e],o=r.length-1;for(;;){if(n.objectBytes+it(df(r,o)).byteLength<=t.maxSessionBytes&&r.length<=t.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new ce(se.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");rf(n,r.shift()),o-=1}}async function AE(e,t,n){Ga(t);let r=Qa(e,t.stageId);if(n){await Xr(r,t);return}await jE(r,t)}async function Va(e,t){let n=await za(Qa(e,t));if(n===null)return null;let r=Yr(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=Ga(r);if(o.stageId!==t)throw new ce(se.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function Bi(e){let t=[];for(let n of await Di(Za(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);Ua(r);let o=await Va(e,r);o&&t.push(o)}return t}async function Hd(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 Bi(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 Gd(qa(e,a),tc(e,a));for(let a of new Set(r))!t.blobs.has(a)&&!s.has(a)&&await Gd(ec(e,a),nc(e,a));await Wa(Zr(e)),await Wa(Qr(e))}async function Fi(e,t){await Ka(Qa(e,t)),await TE(e)}async function TE(e){try{await Le.rmdir(Za(e))}catch(t){if(qr(t)||Rt(t)&&t.code==="ENOTEMPTY")return;throw t}}async function FE(e,t){for(let n of await Bi(e))n.entryId===t&&await Fi(e,n.stageId)}async function Ka(e){if(await Le.rm(e,{force:!0}),await ot(e))throw new ce(se.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function Gd(e,t){await Ka(e),await Ka(t)}function Ga(e){if(!Rt(e)||e.schemaVersion!==$a||typeof e.stageId!="string"||!cf(e.stageId)||!ut(e.entryId))throw new ce(se.INVALID_SCHEMA,"history stage schema is invalid");let t=mf(e.blobIds,"history stage blobIds");return{schemaVersion:$a,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function Ua(e){if(!cf(e))throw new ce(se.INVALID_PATH,"history stageId must be a UUID")}function cf(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 Yd(e,t,n=en()){let r=new Set(t),o=new Set;for(let l of t){let u=await zr(e,l,n);for(let d of u.blobs)o.add(d.digest)}for(let l of await Bi(e)){r.add(l.entryId);for(let u of l.blobIds)o.add(u)}let i=Zr(e),s=await Di(i);for(let l of s){if(!l.endsWith(".json"))continue;let u=ef(l.slice(0,-5));u&&!r.has(u)&&await Li(Be.join(i,l))}let a=Qr(e),c=await Di(a);for(let l of c){let u=ef(l);u&&!o.has(u)&&await Li(Be.join(a,l))}}async function _i(e,t=en()){let{index:n,sizeBytes:r}=await Gr(e),{totalBytes:o}=await lf(e,n.entryIds,t,r);return{...ji(n),totalBytes:o}}async function Zd(e,t){let{index:n,sizeBytes:r}=await Gr(e);return{...ji(n),totalBytes:t.objectBytes+r}}async function Gr(e){let t=Ya(e),n=await Wr(t,se.NOT_FOUND,"index"),r=Yr(Buffer.from(n).toString("utf8"),"index");return{index:LE(r),sizeBytes:n.byteLength}}async function Mi(e){return ji((await Gr(e)).index)}function ji(e){let t=[...e.entryIds],n=t.slice(0,e.cursor+1).reverse(),r=t.slice(e.cursor+1);return{schemaVersion:xt,digest:e.digest,entryIds:t,cursor:e.cursor,currentId:t[e.cursor]??null,undoIds:n,redoIds:r}}async function lf(e,t,n,r){let o=0,i=new Set;o+=r??(await Gr(e)).sizeBytes;for(let s of new Set(t)){let a=await zr(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 zr(e,t,n=en()){let r=n.entries.get(t);if(r)return r.entry;let o=await JE(e,t),i=await Wr(o,se.NOT_FOUND,"entry"),s=Yr(Buffer.from(i).toString("utf8"),`entry ${t}`),a=DE(s);if(a.id!==t)throw new ce(se.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(dn(it({schemaVersion:a.schemaVersion,kind:a.kind,manifest:a.manifest,blobs:a.blobs}))!==t)throw new ce(se.ENTRY_CORRUPT,`entry hash mismatch for ${t}`);let l=[...new Set(a.blobs.map(d=>d.digest))].filter(d=>!n.blobSizes.has(d)),u=async d=>{let f=await xf(e,d),g=await Wr(f,se.NOT_FOUND,"blob");return gf(g,d,f),g.byteLength};if(l.length===1)n.blobSizes.set(l[0],await u(l[0]));else if(l.length>1){let d=new Array(l.length),f=[],g=0,m=Array.from({length:Math.min(4,l.length)},async()=>{for(;g<l.length&&f.length===0;){let b=g++;try{d[b]=await u(l[b])}catch(S){f.push({index:b,error:S})}}}),h=await Promise.allSettled(m),y=f.sort((b,S)=>b.index-S.index)[0];if(y)throw y.error;for(let b of h)if(b.status==="rejected")throw b.reason;for(let b=0;b<l.length;b++)n.blobSizes.set(l[b],d[b])}return n.entries.set(t,{entry:a,sizeBytes:i.byteLength}),a}async function uf(e,t,n){await Xr(Ya(e),df(t,n))}function df(e,t){return{schemaVersion:xt,digest:dn(it({schemaVersion:xt,entryIds:e,cursor:t})),entryIds:e,cursor:t}}function ff(e,t){if(t!==void 0&&e.digest!==t)throw new ce(se.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function Qd(e){ff(await Mi(e.rootDir),e.previousDigest);let t=dn(it({schemaVersion:xt,entryIds:e.entryIds,cursor:e.cursor}));try{await uf(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.();let n=await e.readback();if(n.digest!==t)throw new ce(se.INDEX_CORRUPT,"history index readback did not match the published transition");return n}catch(n){let r=await _i(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new ce(se.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function _E(e){await Le.mkdir(e,{recursive:!0}),await Le.mkdir(Zr(e),{recursive:!0}),await Le.mkdir(Qr(e),{recursive:!0}),await Le.mkdir(Hr(e),{recursive:!0})}async function ME(e){await Le.rm(Hr(e),{recursive:!0,force:!0}),await Le.mkdir(Hr(e),{recursive:!0})}async function OE(e){let t=Hr(e);await Le.mkdir(t,{recursive:!0});for(let n of await Di(t))n!=="stages"&&await Le.rm(Be.join(t,n),{recursive:!0,force:!0})}function LE(e){if(!Rt(e))throw new ce(se.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==xt)throw new ce(se.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=mf(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new ce(se.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!ut(o))throw new ce(se.INDEX_CORRUPT,"index digest is invalid");let i=dn(it({schemaVersion:xt,entryIds:t,cursor:r}));if(o!==i)throw new ce(se.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:xt,digest:o,entryIds:t,cursor:r}}function DE(e){if(!Rt(e))throw new ce(se.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==xt)throw new ce(se.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!ut(t))throw new ce(se.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new ce(se.ENTRY_CORRUPT,"entry kind is invalid");let r=Xa(e.manifest,"entry.manifest"),o=BE(e.blobs);return{id:t,schemaVersion:xt,kind:n,manifest:r,blobs:o}}function BE(e){if(!Array.isArray(e))throw new ce(se.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!Rt(t))throw new ce(se.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new ce(se.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!ut(o))throw new ce(se.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new ce(se.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function Xr(e,t){await pf(e,it(t))}async function jE(e,t){let n=Be.dirname(e),r=Be.basename(e),o=Be.join(n,`.${r}.${process.pid}.${Ha()}.tmp`);await Le.mkdir(n,{recursive:!0});try{await Le.writeFile(o,it(t),{flag:"wx"}),await Le.rename(o,e)}finally{await Li(o)}}async function pf(e,t){let n=Be.dirname(e),r=Be.basename(e),o=Be.join(n,`.${r}.${process.pid}.${Ha()}.tmp`);await Le.mkdir(n,{recursive:!0});try{let i=await Le.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await Le.rename(o,e),await Wa(n)}finally{await Li(o)}}function it(e){return Buffer.from(JSON.stringify(Ja(e)),"utf8")}function Ja(e){if(Array.isArray(e))return e.map(t=>Ja(t));if(Rt(e)){let t={};for(let n of Object.keys(e).sort())t[n]=Ja(e[n]);return t}return e}function Yr(e,t){try{return JSON.parse(e)}catch(n){throw new ce(se.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function Xa(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=>Xa(n,t));if(Rt(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=Xa(o,t);return n}break}throw new ce(se.INVALID_JSON,`${t} must be JSON-serializable`)}function mf(e,t){if(!Array.isArray(e))throw new ce(se.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!ut(n))throw new ce(se.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function Oi(e,t){if(!ut(e))throw new ce(se.INVALID_PATH,`${t} must be a sha256 digest`)}function ut(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function dn(e){return`sha256:${bE("sha256").update(e).digest("hex")}`}function $E(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function Wr(e,t,n){try{return await Le.readFile(e)}catch(r){throw new ce(t,`${n} not found: ${e}`,{cause:r})}}async function za(e){try{return await Le.readFile(e)}catch(t){if(qr(t))return null;throw t}}function gf(e,t,n){if(dn(e)!==t)throw new ce(se.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function ot(e){try{return await Le.access(e),!0}catch(t){if(qr(t))return!1;throw t}}async function Li(e){try{await Le.rm(e,{force:!0,recursive:!0})}catch{}}async function Wa(e){try{let t=await Le.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function Di(e){try{return await Le.readdir(e)}catch(t){if(qr(t))return[];throw t}}function VE(e){if(typeof e!="string"||e.trim().length===0)throw new ce(se.INVALID_ROOT,"history store rootDir must be a non-empty string");return Be.resolve(e)}function Ya(e){return Be.join(e,EE)}function ja(e){return Be.join(e,vE)}function KE(e){return Be.join(e,kE)}function hf(e){return Be.join(e,IE)}async function qd(e){try{let t=await Le.readFile(hf(e),"utf8"),n=Yr(t,"document version");if(!Rt(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new ce(se.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(qr(t))return 0;throw t}}async function Ai(e){let t=await Wr(e,se.RECOVERY_PENDING,"transaction journal"),n=Yr(Buffer.from(t).toString("utf8"),"transaction journal");return yf(n),n}function yf(e){if(!Rt(e)||e.schemaVersion!==SE||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!RE(e.historyTransition)||!Array.isArray(e.files))throw new ce(se.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!Rt(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!ut(t.preDigest)||t.postDigest!==null&&!ut(t.postDigest))throw new ce(se.INVALID_SCHEMA,"transaction journal file digest is invalid")}function UE(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function Zr(e){return Be.join(e,"entries")}function Qr(e){return Be.join(e,"blobs")}function Hr(e){return Be.join(e,"tmp")}function Za(e){return Be.join(Hr(e),"stages")}function Qa(e,t){return Be.join(Za(e),`${t}.json`)}function qa(e,t){return Be.join(Zr(e),`${Sf(t)}.json`)}function ec(e,t){return Be.join(Qr(e),Sf(t))}function tc(e,t){return Be.join(Zr(e),`${t}.json`)}function nc(e,t){return Be.join(Qr(e),t)}async function JE(e,t){return bf(qa(e,t),tc(e,t))}async function xf(e,t){return bf(ec(e,t),nc(e,t))}async function bf(e,t){return await ot(e)?e:await ot(t)?t:e}function Sf(e){return e.slice(7)}function ef(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return ut(t)?t:null}function Rt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qr(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function XE(e){return{maxEntries:e?.maxEntries??Ti.maxEntries,maxSessionBytes:e?.maxSessionBytes??Ti.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??Ti.maxEntryBytes}}async function zE(e){let t=Ya(e);await ot(t)||await uf(e,[],-1)}var HE={affectedCompositions:[]};function Cf(e){let t=null,n=new WeakMap;async function r(){return t??=GE(e),t}async function o(i){if(!i)return null;let s=rc(i);return s?YE(e,s):i}return{async prepareAppend(i){let s=await cr(e),a=await e.stageAppend(kf(i),{durableManifest:!1}),c;try{c=await e.previewStagedAppend(a.entryId,s.digest)}catch(u){throw await e.discardStage(a.stageId),u}let l={kind:"append",entry:i,historyTransition:c};return n.set(l,{expectedDigest:s.digest,stageId:a.stageId,entryId:a.entryId}),l},async prepareUndo(){let i=await r(),s=await o(i.undo.at(-1));if(!s?.historyId)return null;let a=await cr(e),c=a.entryIds.indexOf(s.historyId);if(c<0)throw new Error("undo entry is missing from index");if(c!==a.cursor)throw new Error("undo state changed before prepare");let l=c-1,u=await e.previewCursor(l,a.digest),d={kind:"undo",entry:s,historyTransition:u};return n.set(d,{expectedDigest:a.digest,cursor:l}),d},async prepareRedo(){let i=await r(),s=await o(i.redo.at(-1));if(!s?.historyId)return null;let a=await cr(e),c=a.entryIds.indexOf(s.historyId);if(c<0)throw new Error("redo entry is missing from index");if(c!==a.cursor+1)throw new Error("redo state changed before prepare");let l=c,u=await e.previewCursor(l,a.digest),d={kind:"redo",entry:s,historyTransition:u};return n.set(d,{expectedDigest:a.digest,cursor:l}),d},async publishPrepared(i){let s=n.get(i);if(!s)throw new Error("history mutation was not prepared");let a=await r();if(i.kind==="append"){if(!s.entryId)throw new Error("staged entry id is missing");let c=await e.publishStagedAppend(s.entryId,s.expectedDigest,s.stageId);Ef(c,i.historyTransition),i.entry.historyId=s.entryId,Object.assign(a,lr(c))}else{if(s.cursor===void 0)throw new Error("prepared cursor is missing");let c=i.kind==="undo"?a.undo:a.redo;if(rc(c.at(-1))!==rc(i.entry))throw new Error("history state changed before publish");let l=await e.setCursor(s.cursor,s.expectedDigest);Ef(l,i.historyTransition),Object.assign(a,lr(l))}n.delete(i)},async discardPrepared(i){let s=n.get(i);if(!s)return;let a=i.historyTransition;if(a){let c=await cr(e);if(c.digest===a.publishedIndexDigest&&c.cursor===a.publishedCursor&&c.currentId===a.publishedCurrentId)throw new Error("cannot discard a history mutation whose index was published")}s.stageId&&await e.discardStage(s.stageId),n.delete(i)},async peekUndo(){return o((await r()).undo.at(-1))},async pushUndo(i){let s=await r(),a=i;if(a.historyId){let u=s.entryIds.indexOf(a.historyId);if(u>=0)try{let d=await e.setCursor(u);Object.assign(s,lr(d));return}catch(d){throw s.redo.push(i),d}}let c=await e.append(kf(i)),l=c.currentId;if(!l)throw new Error("history store did not publish an entry");i.historyId=l,Object.assign(s,lr(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,lr(l))}catch(l){throw s.undo.push(i),l}},async popRedo(){let i=await r(),s=await o(i.redo.at(-1));return i.redo.pop(),s},async clearRedo(){(await r()).redo.length=0},async getStatus(){let i=await e.readStatus();return{canUndo:i.canUndo,canRedo:i.canRedo,undoDepth:i.undoDepth,redoDepth:i.redoDepth,recoveryRequired:i.recoveryRequired}},async markRecoveryRequired(i){await e.markRecoveryRequired(i)}}}function Ef(e,t){if(!t)throw new Error("durable history transition is missing");if(e.digest!==t.publishedIndexDigest||e.cursor!==t.publishedCursor||e.currentId!==t.publishedCurrentId)throw new Error("durable history published an unexpected index state")}function rc(e){return typeof e=="string"?e:e?.historyId}async function GE(e){let t=await cr(e);return lr(t)}function lr(e){return{undo:[...e.undoIds].reverse(),redo:[...e.redoIds].reverse(),entryIds:[...e.entryIds],cursor:e.cursor}}async function YE(e,t){let n=await e.readEntry(t),r=ZE(n),o=r.provenance??HE;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 vf(e,n,r.preSnapshots),postSnapshots:await vf(e,n,r.postSnapshots)}}async function vf(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(ev(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function kf(e){let t=[],n=(i,s)=>i.map((a,c)=>{let l={file:a.file,exists:a.exists!==!1,version:a.version,...a.sha256?{sha256:a.sha256}:{}};if(l.exists){let u=`${s}-${c}`;l.blobName=u,t.push({name:u,data:a.content})}return l}),r=QE(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 ZE(e){if(!wf(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:Rf(t.provenance)}:{},preSnapshots:If(t.preSnapshots,"preSnapshots"),postSnapshots:If(t.postSnapshots,"postSnapshots")}}function QE(e){if(e.provenance!==void 0)return Rf(e.provenance);if(e.composition)return{initiatingComposition:e.composition,affectedCompositions:[]}}function Rf(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 If(e,t){return e.map((n,r)=>{if(!wf(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&&!qE(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 qE(e){return/^sha256:[0-9a-f]{64}$/.test(e)}function ev(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function wf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{randomBytes as tv}from"node:crypto";import $i from"node:path";import{parse as Mf}from"@babel/parser";import nv from"@babel/traverse";import*as Of from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as ic,PageResourceArtifactSchema as rv,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as ov,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as iv,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as sv,parseComponentI18nResourcesJson as av}from"@vcp-dev/contracts";var sc="{{$INSTANCE}}",cv=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,lv=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,ac="components/site/generated",uv=/\.(?:tsx?|json)$/,dv=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,fv=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],pv=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),oc=nv,mv=typeof oc=="function"?oc:oc.default;async function cc(e){let t=rv.safeParse(e.artifact);if(!t.success)return De("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>tv(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=kv(r());if(!i)return De("Random instance suffix must be 8 lowercase hex chars.");let s=`${Iv(n.resource_id)}-${i}`,a=new Map,c=new Map,l=[];for(let v of n.pages){let C=v.final_route.slice(1);a.set(v.template_page_id,v.final_route),c.set(v.template_page_id,v.title),l.push({template_page_id:v.template_page_id,title:v.title,final_route:v.final_route,route_file_path:`app/${C}/page.tsx`})}let u=[],d=new Set,f=new Set,g=new Map,m=new Map,h=[],y=new Set(n.pages.flatMap(v=>v.components.map(C=>C.component_id)));for(let v of n.components){if(!y.has(v.component_id))continue;let C=Nf({materialization:v.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c});if(!C.ok)return C;for(let P of C.files){let F=Af(P,d,u);if(F)return F}f.add(C.entry),m.set(C.entry,C.entryExport),g.set(v.component_id,C.entry)}for(let[v,C]of n.pages.entries()){let P=l[v],F=Nf({materialization:C.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c,pageEntryTarget:P.route_file_path,pageTitle:P.title});if(!F.ok)return F;for(let R of F.files){let N=Af(R,d,u);if(N)return N}f.add(F.entry),m.set(F.entry,F.entryExport),h.push({entry:F.entry,declaredComponentIds:new Set(C.components.map(R=>R.component_id))})}let b=hv(u,f,s,g,h,m);if(!b.ok)return b;for(let v of u)if(await e.exists(v.file))return!v.file.startsWith("app/")&&o>1?cc({...e,randomHex:r,maxAttempts:o-1}):{ok:!1,code:"MATERIALIZATION_CONFLICT",message:`Page resource create-only target already exists: ${v.file}`,path:v.file};let S=yv(u);return S||(u.sort((v,C)=>v.file.localeCompare(C.file)),{ok:!0,packageInstanceId:s,pages:l,files:u})}function Nf(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:Pf(o.pathTemplate,e.packageInstanceId);if(!s)return De("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=gv(o.content,e.packageInstanceId,e.routeByPage,e.titleByPage);if(!a.ok)return a;let c=i&&e.pageTitle!==void 0?bv(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??Pf(t,e.packageInstanceId);return!r||!n.some(o=>o.file===r)?De("Materialization entry must match one controlled source file.",t):{ok:!0,files:n,entry:r,entryExport:e.materialization.entry.export}}function gv(e,t,n,r){let o,i=e.replace(cv,(c,l)=>{let u=n.get(l);return u||(o=l,c)});if(o)return De(`Page route placeholder references unknown template page: ${o}`);let s=i.replace(lv,(c,l)=>{let u=r.get(l);return u?JSON.stringify(u):(o=l,c)});if(o)return De(`Page title placeholder references unknown template page: ${o}`);let a=s.replaceAll(sc,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?De("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function Pf(e,t){let n=`${ac}/${t}`;if(e.split(sc).length>2)return null;let o=e.replace(sc,t),i=`${ac}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=$i.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!uv.test(a)||dv.test(a)?null:a}function Af(e,t,n){return t.has(e.file)?De(`Page resource materializations resolve duplicate target: ${e.file}`,e.file):(t.add(e.file),n.push(e),null)}function hv(e,t,n,r,o,i){let s=new Set(e.map(g=>g.file)),a=`${ac}/${n}`,c=new Map(e.map(g=>[g.file,new Set])),l=new Map;for(let g of e){if(g.file.endsWith(".json")){try{JSON.parse(g.content)}catch{return De("Materialization JSON file must contain valid JSON.",g.file)}if(g.file.endsWith(ic)&&!av(g.content).success)return De("Materialization component i18n resources are invalid.",g.file);continue}try{let m=Mf(g.content,{sourceType:"module",plugins:["jsx","typescript"]});l.set(g.file,m);for(let y of m.program.body)if((y.type==="ImportDeclaration"||y.type==="ExportAllDeclaration"||y.type==="ExportNamedDeclaration"&&y.source)&&y.source){let b=y.source.value,S=Ev(g.file,b,s,a);if(!S.allowed)return De(`Materialization import is outside the controlled package: ${b}`,g.file);S.internalPath&&c.get(g.file).add(S.internalPath)}let h;if(mv(m,{Identifier(y){y.isReferencedIdentifier()&&pv.has(y.node.name)&&(h??=y.node.name,y.stop())},JSXOpeningElement(y){y.node.name.type==="JSXIdentifier"&&y.node.name.name.toLowerCase()==="style"&&(h??="style element",y.stop())}}),h)return De(`Materialization source uses forbidden capability: ${h}`,g.file)}catch{return De("Materialization source must parse as TS/TSX.",g.file)}}if([...t].some(g=>!s.has(g)))return De("Materialization entry is outside the controlled package.");for(let g of t)if(g.endsWith(".json"))return De("Materialization JSON files cannot be package entries.");for(let[g,m]of i){let h=l.get(g);if(!h||!xv(h,m))return De("Materialization entry does not declare its contracted export.",g)}let u=new Map([...r].map(([g,m])=>[m,g]));for(let g of o){let m=_f(g.entry,c);for(let h of g.declaredComponentIds){let y=r.get(h);if(!y||!m.has(y))return De(`Page entry does not reach declared component: ${h}`,g.entry)}for(let h of m){let y=u.get(h);if(y&&!g.declaredComponentIds.has(y))return De(`Page entry imports undeclared component: ${y}`,g.entry)}}let d=new Set;for(let g of t)for(let m of _f(g,c))d.add(m);if(d.size!==e.length)return De("Every materialization file must be reachable from a package entry.");let f=vv(e,l,c);return f||{ok:!0}}function yv(e){if(e.length>ov)return De("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>iv)return De("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>sv?De("Page resource exceeds the aggregate content byte limit."):null}function xv(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 bv(e,t,n){let r;try{r=Mf(e,{sourceType:"module",sourceFilename:n,plugins:["jsx","typescript"]})}catch{return De("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=Tf(s.init);if(a?.type!=="ObjectExpression")return{ok:!0,data:e};let c=a.properties.find(u=>u.type==="ObjectProperty"&&!u.computed&&Sv(u.key));if(!c||c.type!=="ObjectProperty")return{ok:!0,data:e};let l=Tf(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 Tf(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&Of.isExpression(t)?t:null}function Sv(e){return e.type==="Identifier"&&e.name==="title"||e.type==="StringLiteral"&&e.value==="title"}function Ev(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=Ff(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:fv.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=$i.posix.normalize($i.posix.join($i.posix.dirname(e),t)),i=Ff(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function Ff(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 vv(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(ic))continue;let i=o.file.slice(0,-ic.length),s=[`${i}.tsx`,`${i}.ts`].find(u=>r.has(u));if(!s)return De("Component i18n resources require a same-name TS/TSX companion.",o.file);let c=t.get(s)?.program.directives.some(u=>u.value.value==="use client"),l=[...n].filter(([,u])=>u.has(o.file));if(!c||l.length!==1||l[0]?.[0]!==s)return De("Component i18n resources must have exactly one same-name Client Component static importer.",s)}return null}function _f(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 kv(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function Iv(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"page-resource"}function De(e,t){return{ok:!1,code:"MATERIALIZATION_REJECTED",message:e,...t?{path:t}:{}}}import{randomBytes as Cv}from"node:crypto";import tn from"node:path";import{parse as Rv}from"@babel/parser";import wv from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as Vi,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as Lf,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as Nv,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as Pv,SiteEditMaterializationSchema as Av,parseComponentI18nResourcesJson as Tv}from"@vcp-dev/contracts";var dc="components/site/generated",Df="{{$INSTANCE}}",Ki=5,Fv=/^[a-z][a-z0-9-]{0,48}$/,_v=/^[a-f0-9]{8}$/,Bf=/\.tsx?$/,Mv=/\.json$/,Ov=/\.(?:tsx?|json)$/,Lv=/^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/,Dv=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,Bv=["react","react/","next","next/","lucide-react","react-i18next","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],lc=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),uc=wv,jv=typeof uc=="function"?uc:uc.default;function $v(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>Lf)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=Av.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=Hv(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${dc}.`,path:e.generatedRoot}};if(!Jf(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=Vf(r.data.files),s=Vf(e.controlledFiles);if(!Qv(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>Lf)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let a=0;for(let[c,l]of r.data.files.entries()){let u=Buffer.byteLength(l.content,"utf8");if(u>Nv)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file exceeds the per-file content limit.",file:l.pathTemplate,path:`files[${c}]`}};a+=u}return a>Pv?{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 Vv(e){let t=$v(e);if(!t.ok)return t;let n=Object.keys(e.manifest.projectDependencies??{}),r=new Set(e.availableHostDependencies??[]),o=n.find(u=>!Lv.test(u)||!r.has(u));if(o)return{ok:!1,error:{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:`Declared project dependency is not available in the target site host: ${o}.`,path:o}};let i=n.flatMap(u=>[u,`${u}/`]),s=[...e.allowedExternalImports??Bv,...i],a=t.data.generatedRoot,c=Jf(e.manifest.instanceBaseName),l=Math.max(1,Math.min(Ki,e.maxAttempts??Ki));for(let u=0;u<l;u+=1){let d=Gv(e.instanceNameGenerator?.()??Cv(4).toString("hex"));if(!d)return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_INVALID",message:"Static prefab instance suffix must be 8 lowercase hex chars."}};let f=`${c}-${d}`,g=zf(a,f),m=Kv({manifest:e.manifest,generatedRoot:a,instanceName:f,instanceRoot:g,allowedExternalImports:s});if(!m.ok)return m;if(!await Uv(e.exists,g,m.data.files))return{ok:!0,data:m.data}}return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:"Unable to allocate a create-only static prefab instance after repeated conflicts."}}}async function Uf(e){let t=Math.max(1,Math.min(Ki,e.maxAttempts??Ki));for(let n=0;n<t;n+=1){let r=await Vv({...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 Kv(e){let t=[],n=new Set;for(let i of e.manifest.files){let s=jf({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=jf({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 Uv(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function jf(e){if(e.pathTemplate.split(Df).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(Df,e.instanceName),n=Yv(t);return n?zf(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||!Ov.test(n)||Dv.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(d=>d.path)),s=new Map,a=new Map(e.map(d=>[d.path,new Set])),c=new Map;for(let d of e){if(Mv.test(d.path)){if(d.path.endsWith(Vi)){let g=Tv(d.content);if(!g.success)return On("MATERIALIZATION_DATA_UNSUPPORTED",g.error.message,d.path);c.set(d.path,new Set)}else try{JSON.parse(d.content)}catch{return On("MATERIALIZATION_DATA_UNSUPPORTED","Static prefab JSON file must contain valid JSON.",d.path)}continue}let f;try{f=Rv(d.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:d.path}}}s.set(d.path,f)}for(let d of e){if(!Bf.test(d.path))continue;let f=s.get(d.path),g=null;if(jv(f,{ImportDeclaration(m){let h=$f({importer:d.path,source:m.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});if(!h.allowed)g??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab imports must resolve within the controlled instance or match the starter allowlist.",file:d.path},m.stop();else if(h.internalPath&&(a.get(d.path).add(h.internalPath),h.internalPath.endsWith(Vi))){let y=Xv({importer:d.path,imported:h.internalPath,source:m.node.source.value,ast:f});y.ok?c.get(h.internalPath).add(d.path):(g??=y.error,m.stop())}},ExportAllDeclaration(m){g??={code:"MATERIALIZATION_ENTRY_INVALID",message:"Static prefab files cannot use export-star declarations.",file:d.path},m.stop()},ExportNamedDeclaration(m){if(m.node.source){let h=$f({importer:d.path,source:m.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});!h.allowed||!h.internalPath?(g??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab re-exports must resolve within the controlled instance.",file:d.path},m.stop()):a.get(d.path).add(h.internalPath)}},CallExpression(m){if(m.node.callee.type==="Import"){g??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use dynamic import().",file:d.path},m.stop();return}m.node.callee.type==="Identifier"&&m.node.callee.name==="require"&&(g??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use require().",file:d.path},m.stop())},NewExpression(m){m.node.callee.type==="Identifier"&&m.node.callee.name==="Function"&&(g??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot construct functions dynamically.",file:d.path},m.stop())},MetaProperty(m){m.node.meta.type==="Identifier"&&m.node.meta.name==="import"&&(g??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot use import.meta.",file:d.path},m.stop())},MemberExpression(m){let h=Kf(m.node);h&&lc.has(h)&&(g??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h}.`,file:d.path},m.stop())},OptionalMemberExpression(m){let h=Kf(m.node);h&&lc.has(h)&&(g??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h}.`,file:d.path},m.stop())},Identifier(m){m.isReferencedIdentifier()&&lc.has(m.node.name)&&(g??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${m.node.name}.`,file:d.path},m.stop())},JSXOpeningElement(m){m.node.name.type==="JSXIdentifier"&&m.node.name.name.toLowerCase()==="style"&&(g??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot declare style elements.",file:d.path},m.stop())}}),g)return{ok:!1,error:g}}if(!Bf.test(n))return On("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must be a .ts/.tsx source module.",n);let l=s.get(n);if(!l)return On("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",n);if(!zv(l,r))return On("MATERIALIZATION_EXPORT_MISSING","Static prefab entry does not declare the manifest export.",n);for(let[d,f]of c)if(f.size!==1)return On("MATERIALIZATION_IMPORT_FORBIDDEN","Each component .i18n.json file must have exactly one same-name Client Component static importer.",d);return Wv(n,a).size!==e.length?On("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",n):{ok:!0,data:{kind:"static-prefab-materialization",instanceName:"",generatedRoot:dc,instanceRoot:"",entry:{path:"",export:{kind:"default"}},files:[]}}}function $f(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=tn.posix.normalize(tn.posix.join(tn.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 Xv(e){let t=tn.posix.dirname(e.importer),n=tn.posix.dirname(e.imported),r=tn.posix.basename(e.importer).replace(/\.tsx?$/,""),o=tn.posix.basename(e.imported).slice(0,-Vi.length),i=`./${r}${Vi}`;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 zv(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 Wv(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 On(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function Hv(e){let t=Xf(e);return t===dc?t:null}function Gv(e){let t=e.trim().toLowerCase();return _v.test(t)?t:null}function Jf(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 Fv.test(t)?t:null}function Xf(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=tn.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function Yv(e){let t=Xf(e);return!t||t!==e?null:t}function zf(...e){return tn.posix.join(...e)}function Vf(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 Qv(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Kf(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 Rc}from"node:crypto";import bc from"@babel/traverse";function fc(e){let t=new Map,n=new Map;for(let s of e){if(t.has(s.placementKey))throw new Error(`Duplicate placement key in page composition projection: ${s.placementKey}`);t.set(s.placementKey,s);let a=n.get(s.placementUnitKey)??[];a.push(s),n.set(s.placementUnitKey,a)}let r=new Map,o=new Map,i=new Map;for(let[s,a]of n){let c=Object.freeze([...a]),l=c.find(u=>u.anchorSourceRange!==null&&u.members.length>0)??c.find(u=>u.members.length>0)??c[0];l&&(o.set(s,c),i.set(s,l),r.set(s,Object.freeze({placementUnitKey:s,placementKeys:Object.freeze(c.map(u=>u.placementKey)),sourcePlacementKey:l.placementKey})))}return{placementByKey:t,unitByKey:r,placementsByUnitKey:o,sourcePlacementByUnitKey:i}}import{createHash as qv}from"node:crypto";import Wf from"node:path";import*as Qf from"@babel/parser";import pc from"@babel/generator";import*as Je from"@babel/types";var Hf=typeof pc=="function"?pc:pc.default;function gc(e){let t=ep(e);if(t)return{ok:!1,error:t};let n=e.projection,r=xc(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=nk(n,o),s={jsx:`<${e.component.localName} />`},a=ek(e);if(i){let g=mc(e);return g.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:g.locator,sourceHash:g.sourceHash,node:s,placement:o.relation,replaceOriginal:n.container.kind==="starter-placeholder"}}}:g.result}let c=o.containerSourceRange??n.container.sourceRange,l=o.containerSourceHash??(yc(c,n.container.sourceRange)?n.container.sourceHash:null);if(!c||!l)return eo("Route page composition does not expose a verifiable container boundary.");let u=no(c),d=Yf(e.source,u,l,"Route page composition container");if(!d.ok)return d.result;let f=o.anchorSourceRange?no(o.anchorSourceRange):void 0;if(f){if(!o.anchorSourceHash)return eo("Route page composition placement does not expose a verifiable anchor boundary.");let g=Yf(e.source,f,o.anchorSourceHash,"Route page composition anchor");if(!g.ok)return g.result}return{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:o.placementUnitKey,importStep:a,rewriteStep:{kind:"insert-child",parentLocator:u,node:s,placement:o.relation,...f?{anchorLocator:f}:{}}}}}function ek(e){let t=sk(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 Ui(e){if(e.locator.root.kind!=="expression"||e.locator.path?.length)return Ln(e.source,"Root expression rewrite requires an exact expression locator.");let t=Fr(e.source,"value");if(!t.ok)return Ln(e.source,t.diagnostic.message);let n=ue(t.ast,e.locator);if(!n.ok)return Ln(e.source,n.diagnostic.message);let r=n.match.path;if(!r.isExpression())return Ln(e.source,"Resolved value locator does not point to an expression.");let o=ur(e.source,r.node.start??null,r.node.end??null);if(!o||o!==e.expectedSourceHash)return Ln(e.source,"Root expression hash no longer matches the current source.");if(e.action.kind==="remove")return r.replaceWith(Je.nullLiteral()),{ok:!0,source:Hf(t.ast,{}).code};let i;try{i=Qf.parseExpression(e.action.jsx,{plugins:["jsx","typescript"]})}catch(s){return Ln(e.source,s instanceof Error?s.message:String(s))}return!Je.isJSXElement(i)&&!Je.isJSXFragment(i)?Ln(e.source,"Root expression rewrite requires a JSX insertion expression."):(e.action.kind==="replace"?r.replaceWith(i):r.replaceWith(tk(r.node,i,e.action.placement,e.action.replaceOriginal)),{ok:!0,source:Hf(t.ast,{}).code})}function tk(e,t,n,r){if(Je.isNullLiteral(e)||r)return t;let o=Je.isJSXFragment(e)?[...e.children]:[Je.isJSXElement(e)?e:Je.jsxExpressionContainer(e)],s=n==="before"||n==="prepend"?[t,...o]:[...o,t];return Je.jsxFragment(Je.jsxOpeningFragment(),Je.jsxClosingFragment(),s)}function Ln(e,t){return{ok:!1,source:e,diagnostic:{message:t}}}function hc(e){let t=ep(e);if(t)return{ok:!1,error:t};let n=e.projection,r=tp(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(rk(n,o)){let h=mc(e);return h.ok?e.operation==="remove-node"&&!Gf(n,o.placementUnitKey)?eo("The last editable page unit cannot be deleted."):e.operation==="move-node"?eo("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=no(o.sourceRange),a=Lt(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?[]:[to(a.diagnostic)]}};if(ur(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=mc(e);return h.ok?Gf(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}}}:eo("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||!ik(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=xc(n,e.targetPlacement.placementKey,e.expectedDocumentVersion);if(!l.ok)return{ok:!1,error:{code:l.diagnostic.code==="DOCUMENT_VERSION_STALE"?"VERSION_STALE":"NO_SAFE_PAGE_PLACEMENT",message:l.diagnostic.message,diagnostics:[l.diagnostic]}};let u=l.placement;if(u.placementUnitKey!==e.targetPlacement.placementUnitKey||u.relation!==e.targetPlacement.relation)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Page-unit target placement metadata does not match the cached projection.",diagnostics:[]}};let d=u.containerSourceRange;if(!d||!u.containerSourceHash)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable container boundary.",diagnostics:[]}};let f=no(d),g=Lt(e.source,f);if(!g.ok||!g.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:g.ok===!1?g.diagnostic.message:"Route page composition target container could not be resolved.",diagnostics:g.ok?[]:[to(g.diagnostic)]}};if(ur(e.source,g.match.node.start??null,g.match.node.end??null)!==u.containerSourceHash)return Zf("Route page composition target container hash no longer matches the current source.");if(u.relation==="before"||u.relation==="after"){let h=u.anchorSourceRange,y=u.anchorSourceHash;if(!h||!y)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable anchor boundary.",diagnostics:[]}};let b=no(h),S=Lt(e.source,b);return!S.ok||!S.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:S.ok===!1?S.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:S.ok?[]:[to(S.diagnostic)]}}:ur(e.source,S.match.node.start??null,S.match.node.end??null)!==y?Zf("Route page composition target anchor hash no longer matches the current source."):{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"move-node",locator:s,targetParentLocator:f,anchorLocator:b,placement:u.relation}}}}return{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"move-node",locator:s,targetParentLocator:f,placement:u.relation}}}}function Gf(e,t){for(let n of e.placementUnitByKey.values())if(n.placementUnitKey!==t&&n.members.length>0)return!0;return!1}function nk(e,t){let n=e.placementUnitByKey.get(t.placementUnitKey);return n&&e.container.kind!=="jsx-container"&&yc(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 rk(e,t){return e.container.kind!=="jsx-container"&&yc(t.sourceRange,e.mutationTarget.sourceRange)&&t.sourceHash===e.mutationTarget.sourceHash}function mc(e){let t=e.projection.mutationTarget,n={kind:"value",root:{kind:"expression",sourceRange:t.sourceRange}},r=Lt(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?[]:[to(r.diagnostic)]}}}:ur(e.source,r.match.node.start??null,r.match.node.end??null)!==t.sourceHash?{ok:!1,result:qf("Route mutation target hash no longer matches the current source.")}:{ok:!0,locator:n,sourceHash:t.sourceHash}}function Yf(e,t,n,r){let o=Lt(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?[]:[to(o.diagnostic)]}}}:ur(e,o.match.node.start??null,o.match.node.end??null)!==n?{ok:!1,result:qf(`${r} hash no longer matches the current source.`)}:{ok:!0}}function qf(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function eo(e){return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:e,diagnostics:[]}}}function Zf(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function to(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function ep(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&&!ok(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 ok(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function ik(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function sk(e,t){let n=Wf.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Wf.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function no(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function ur(e,t,n){return t==null||n==null?null:`sha256:${qv("sha256").update(e.slice(t,n)).digest("hex")}`}function yc(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 ak=typeof bc=="function"?bc:bc.default;function ip(e){if(!e.ast)return wt(e,[Ke("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=gk(e.ast);if(!t)return wt(e,[Ke("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=yk(t);if(!n.ok)return wt(e,[n.diagnostic]);let r=n.expression;if(r.isIdentifier()){let o=bk(r,t);if(o.status==="resolved")r=o.expression;else if(o.status==="invalid")return wt(e,[Ke("UNSUPPORTED_PAGE_SHAPE","Route default export local binding is not a supported JSX root")])}if(Ek(r,t))return wt(e,[Ke("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(r.isNullLiteral())return Ec(e,t,"virtual-route-root",r);if(Sk(r)){let o=Ck({input:e,source:e.source,expression:r});return Sc(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"},r)}if(r.isConditionalExpression())return wt(e,[Ke("UNSUPPORTED_PAGE_SHAPE","Route conditional root contains an unsupported branch shape",{reason:"ambiguous-placement"})]);if(r.isJSXElement()&&!Oe(r)&&!fn(r)){let o=Ic(r),i=op({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[o]});return Sc(e,t,i,{kind:"virtual-route-root",sourceKind:"jsx-element"},r)}if(r.isJSXElement()||r.isJSXFragment()){let o=kk(r);if(!o.ok)return wt(e,[o.diagnostic]);let i=dr(o.path);if(i.unsupported)return wt(e,[Ke("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);if(vk(e.source,r,i.members))return Ec(e,t,"starter-placeholder",r);let s=r.isJSXFragment()||Oe(r);if(i.members.length===0&&s)return Ec(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=op({input:e,containerKind:a,sourceKind:c,source:e.source,containerPath:o.path,members:i.members});return Sc(e,t,l,{kind:a,sourceKind:c},r)}return wt(e,[Ke("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")])}function xc(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Ke("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:Ke("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function tp(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Ke("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:Ke("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function sp(e){return e.ok?ck(e.projection):lk(e.projection)}function ck(e){let t=new Map,n=[];for(let l of e.placements)l.members.length===0&&e.placements.length>1||l.members.length>0&&!l.anchorSourceRange||t.has(l.placementUnitKey)||t.set(l.placementUnitKey,l);let r=new Map,o=new Map;for(let[l,u]of t){let d=u.members.flatMap((h,y)=>ap(e,u,h,y,e.container.placementKey)),f=d.filter(({member:h})=>h.isBusinessMember).map(({sourceMember:h})=>dk(l,h,u.independent)),g=d.length>0?d:[{sourceMember:{key:`source:${l}:empty`,kind:e.container.kind==="starter-placeholder"?"starter-placeholder":"null-return",containerKey:e.container.placementKey,label:"empty-page",sourceFile:e.entryFile,isAtomic:!0},member:null}];r.set(l,g.map(({sourceMember:h})=>h)),o.set(l,f);let m=g[0]?.sourceMember.key??l;n.push({key:l,containerKey:m,businessMemberKeys:f.map(h=>h.key),isMultiMember:u.memberCount>1})}let i=[...r.values()].flat(),s=[...o.values()].flat(),a=i[0]?.key??null,c=e.placements.map(l=>({kind:"page-composition",placementKey:l.placementKey,documentVersion:e.documentVersion,composition:e.composition,placementUnitKey:l.placementUnitKey,relation:l.relation}));return{status:"supported",version:e.version,composition:e.composition,container:uk(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function lk(e){let t=e.diagnostics.map(fk);return{status:"unsupported",version:e.version,composition:e.composition,reason:pk(e.diagnostics),diagnostics:t}}function uk(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 ap(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)=>ap(e,t,a,c,i))]}function dk(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function fk(e){return{code:mk(e),message:e.message}}function pk(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 mk(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 gk(e){let t=null;return ak(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=hk(o.path);i&&(t=i,n.stop())}}),t}function hk(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 yk(e){let t=e.get("body");if(!t.isBlockStatement()){let s=oo(t);return s?{ok:!0,expression:s}:{ok:!1,diagnostic:Ke("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:Ke("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")};if(!r.isReturnStatement())return{ok:!1,diagnostic:Ke("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(!xk(s))return{ok:!1,diagnostic:Ke("UNSUPPORTED_PAGE_SHAPE","Route guard return shape is not statically safe",{reason:"guard-shape"})};continue}if(cp(s)||lp(s))return{ok:!1,diagnostic:Ke("UNSUPPORTED_PAGE_SHAPE","Route default export contains unsupported control flow before the terminal return",{reason:"control-flow-return"})}}let o=r.get("argument"),i=oo(o);return i?{ok:!0,expression:i}:{ok:!1,diagnostic:Ke("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})}}function xk(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(cp(o)||lp(o))return null;return r}function cp(e){return e.isForStatement()||e.isForInStatement()||e.isForOfStatement()||e.isWhileStatement()||e.isDoWhileStatement()||e.isSwitchStatement()||e.isTryStatement()||e.isWithStatement()}function lp(e){let t=!1;return e.traverse({Function(n){n.skip()},ReturnStatement(){t=!0}}),t}function bk(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=oo(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 Sk(e){return e.isConditionalExpression()?np(oo(e.get("consequent")))&&np(oo(e.get("alternate"))):!1}function np(e){return!!(e&&(e.isJSXElement()||e.isJSXFragment()||e.isNullLiteral()))}function oo(e){if(!e.node)return null;let t=e;for(;;){if(t.isParenthesizedExpression()){t=t.get("expression");continue}if(t.isTSAsExpression()||t.isTSTypeAssertion()){t=t.get("expression");continue}if(t.isTSNonNullExpression()||t.isTypeCastExpression()){t=t.get("expression");continue}break}return t.isExpression()?t:null}function Ek(e,t){if(e.isIdentifier())return rp(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return rp(n.node.name,t)}return!1}function rp(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 vk(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&kc(t)}function kc(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(!kc(t))return!1;continue}if(t.isJSXElement()&&!kc(t))return!1}return!0}function kk(e){let t=e;if(e.isJSXFragment()||Oe(e)){let r=ro(e),o=r[0];if(r.length===1&&o?.isJSXElement()&&fn(o))t=o;else return{ok:!0,path:t}}for(;t.isJSXElement()&&fn(t);){let r=ro(t);if(r.length!==1)return{ok:!0,path:t};let o=r[0];if(!o?.isJSXElement()||!fn(o))return{ok:!0,path:t};if(ro(o).length<=1)return{ok:!0,path:t};t=o}return{ok:!0,path:t}}function ro(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(...ro(n));continue}n.isJSXElement()&&(Oe(n)?t.push(...ro(n)):t.push(n))}return t}function dr(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:Cc(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:bt(r.node.loc),businessMemberCount:0,parentSourceRange:bt(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=dr(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=fn(o)?dr(o):null;n||=i?.unsupported??!1,t.push({...Ic(o,i?.members),sourceRange:bt(r.node.loc),parentSourceRange:bt(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:Cc(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:bt(r.node.loc),businessMemberCount:1,parentSourceRange:bt(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&Oe(r)){let o=dr(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=fn(r)?dr(r):null;n||=o?.unsupported??!1,t.push({...Ic(r,o?.members),parentSourceRange:bt(e.node.loc)})}}return{members:t,unsupported:n}}function Ic(e,t){let n=e.isJSXElement()&&fn(e)?t??dr(e).members:[],r=e.isJSXElement()&&!fn(e)&&!Oe(e);return{memberKey:Cc(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:bt(e.node.loc),businessMemberCount:r?1:up(n),parentSourceRange:bt(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:Ik(e)}}function fn(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name[0]===t.name[0]?.toLowerCase()}function Ik(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 up(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function Ji(e){return e.length===0?0:Math.max(1,up(e))}function op(e){let t=bt(e.containerPath.node.loc),n=wc(e.source,e.containerPath.node.start,e.containerPath.node.end),r=St(e.input,e.containerKind,e.sourceKind,t),o=St(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 Ck(e){let t=bt(e.expression.node.loc),n=wc(e.source,e.expression.node.start,e.expression.node.end),r=St(e.input,"virtual-route-root","atomic-expression",t),o=St(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:St(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 dp(e,t){let n=bt(t.node.loc),r=wc(e.source,t.node.start,t.node.end);return!n||!r?null:{kind:"expression",documentVersion:e.version,sourceRange:n,sourceHash:r}}function Sc(e,t,n,r,o){let i=dp(e,o);if(!i)return wt(e,[Ke("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let s=n.containerSourceRange??n.sourceRange,a=Rk(e,n,s),c=fc(a),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:pp(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 Rk(e,t,n){if(t.members.length===0)return[t];let r=[],o=(l,u,d,f,g,m,h=n)=>({...t,placementKey:u,placementUnitKey:d,containerKey:t.placementKey,independent:Ji(m)<=1,memberCount:Ji(m),sourceRange:f,sourceHash:f?vc(e.source,f):null,relation:l,containerSourceRange:h,containerSourceHash:h?vc(e.source,h):null,anchorSourceRange:g,anchorSourceHash:g?vc(e.source,g):null,members:m}),i=t.placementKey,s=t.members.map(l=>St(e,i,"placement-unit",l.sourceRange)),a=s[0]??t.placementUnitKey,c=s.at(-1)??t.placementUnitKey;r.push(o("prepend",St(e,i,"prepend",n),a,n,null,[]));for(let l of t.members){let u=l.parentSourceRange??n,d=St(e,i,"placement-unit",l.sourceRange);r.push(o("before",St(e,d,"before",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u)),r.push(o("after",St(e,d,"after",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u))}return r.push(o("append",i,c,n,null,[])),r}function Ec(e,t,n,r){let o=dp(e,r);if(!o)return wt(e,[Ke("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let i=St(e,n,"empty-container",void 0),s=St(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=fc([a]),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:pp(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 wt(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 Ke(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function St(e,t,n,r){return fp([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function Cc(e,t,n){return fp(["member",e,String(t??-1),String(n??-1)])}function fp(e){return`pc_${Rc("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function wc(e,t,n){return t==null||n==null?null:`sha256:${Rc("sha256").update(e.slice(t,n)).digest("hex")}`}function vc(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:${Rc("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function bt(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function pp(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 Bk}from"@vcp-dev/contracts";import w_ from"node:fs";import P_ from"node:path";var Nk=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function io(e){let t=e.map(r=>Dk(r.path)),n=Pk(t);return n?t.filter(r=>Tk(n,r)).map(r=>({routeId:Fk(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function Nc(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=Lk(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function Pk(e){return e.some(r=>r.startsWith("app/")&&!Ak(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function Ak(e){return/^(?:src\/)?app\/(?:_vcp|\.vcp)/.test(e)}function Tk(e,t){if(!t.startsWith(`${e}/`))return!1;let n=t.slice(t.lastIndexOf("/")+1);return Nk.test(n)?t.slice(e.length+1,-n.length-1).split("/").filter(Boolean).every(r=>!r.startsWith("_")&&!r.startsWith(".")):!1}function Fk(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(Mk).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function _k(e){return e.startsWith("(")&&e.endsWith(")")}function Mk(e){return!e||e.startsWith("@")||e.startsWith("_")||_k(e)?null:Ok(e)}function Ok(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function Lk(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function Dk(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var so=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function st(e,t={}){throw new so("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Invalid page-template source (${e}): ${t.path??t.routeId??t.templateId??""}`,{reason:e,...t})}function Pc(e){return Bk.safeParse(e).success||st("invalid-template-id",{templateId:e}),Buffer.from(e,"utf8").toString("base64url")}function mp(e){/^[A-Za-z0-9_-]{1,255}$/.test(e)||st("invalid-template-key",{path:e});let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.from(e,"base64url"))}catch{return st("invalid-template-key",{path:e})}return Pc(t)!==e&&st("noncanonical-template-key",{path:e}),t}function jk(e){let t=Nc(e),n=t.slice(1).split("/");return(!e.startsWith("/")||/[?#\\%\u0000-\u001f]/.test(e)||t.startsWith("/.vcp")||t!=="/"&&n.some(r=>!r||r==="."||r===".."||r.startsWith("@")||r.startsWith("_")||r.startsWith("(")||$k(r)&&!gp(r)))&&st("invalid-public-route",{routeId:e}),t}function $k(e){return e.includes("[")||e.includes("]")}function gp(e){return/^\[\[\.\.\.[^\[\]]+\]\]$|^\[[^\[\]]+\]$/.test(e)}function hp(e){return e.some(gp)}function yp(e,t,n="app"){n!=="app"&&n!=="src/app"&&st("invalid-app-root");let r=jk(e),o=Pc(t),i=hp(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))&&st("path-too-long",{path:a}),{appRoot:n,routeRoot:s,templateKey:o,templateEntryFile:a}}function xp(e){return/^(?:src\/)?app\/\.vcp\/page-templates\//.test(e)}function bp(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===".")&&st("invalid-file-path",{path:i}),n.has(i)&&st("duplicate-file-path",{path:i}),n.set(i,o)}return n}function zi(e){let t=bp(e.files),n=io([...t.keys()].map(i=>({path:i}))),r=new Map;for(let i of n){if(r.has(i.routeId))throw new so("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(!xp(i))continue;let s=/^(app|src\/app)\/\.vcp\/page-templates\/(.+)\/page\.tsx$/.exec(i);s||st("candidate-must-be-single-page",{path:i});let a=s[1],c=s[2].split("/"),l=hp(c),u=l?c[0]:c.pop(),d=l?c.slice(1):c,f=mp(u),g=d.length?`/${d.join("/")}`:"/";yp(g,f,a).templateEntryFile!==i&&st("candidate-path-mismatch",{path:i,routeId:g});let h=r.get(g);(!h||!h.startsWith(`${a}/`))&&st("canonical-entry-missing",{path:i,routeId:g}),o.push({routeId:g,templateId:f,entryFile:i,canonicalEntryFile:h,appRoot:a})}return o.sort((i,s)=>Xi(i.routeId,s.routeId)||Xi(i.templateId,s.templateId))}function Sp(e){let t=bp(e.files),n=zi({files:t}),r=io([...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)=>Xi(o.context.routeId,i.context.routeId)||(o.context.effectiveTemplateId===void 0?-1:i.context.effectiveTemplateId===void 0?1:Xi(o.context.effectiveTemplateId,i.context.effectiveTemplateId)))}function Vk(e){let t=Nc(e.selector.routeId),n=Sp({files:e.files}),r=n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===void 0);(!r||r.entryFile!==e.canonicalEntryFile)&&st("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||st("template-selection-not-found",{routeId:t,templateId:e.selector.templateId}),{...o,mode:e.selector.templateId===void 0?"direct":"candidate",effectiveEntryFile:o.entryFile}}function Xi(e,t){return e<t?-1:e>t?1:0}import{HOME_PAGE_URL_PATH as tI}from"@vcp-dev/contracts";import{parse as jM}from"@babel/parser";import{parse as X_}from"@babel/parser";import{FormBlockIdSchema as W_,FormSpecV1Schema as H_}from"@vcp-dev/contracts";import{posix as B_}from"node:path";import Kk from"@babel/traverse";var Ac=Kk,$_=typeof Ac=="function"?Ac:Ac.default,V_=Symbol("unknown-member");var ao="components/site/generated/forms",Y_=`${ao}/vcp-form-runtime.tsx`,Wi="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",Z_=new RegExp(`^${ao}/form-(${Wi})\\.spec\\.ts$`),Q_=new RegExp(`^${ao}/form-(${Wi})\\.tsx$`),q_=new RegExp(`^@/${ao}/form-(${Wi})$`),eM=new RegExp(`(?:^|/)${ao}/form-(${Wi})(?:\\.tsx?)?$`);var tM=Symbol("invalid-literal");import{createHash as oM}from"node:crypto";import{posix as sM}from"node:path";import{parse as cM}from"@babel/parser";import{FormSpecV1Schema as uM}from"@vcp-dev/contracts";var dM=Symbol("dynamic");import{parse as Uk}from"@babel/parser";function Hi(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.type=="string"):[]}var Jk=/^(?:src\/)?app\/(.*)page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function Ep(e){let t=Jk.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 Xk(e){let t=e;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function vp(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function zk(e){let t=e;for(;t&&(t.type==="TSAsExpression"||t.type==="TSSatisfiesExpression"||t.type==="ParenthesizedExpression");)t=t.expression??null;return t}function Tc(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(Tc);if(t?.type==="ObjectExpression"){let n={};for(let r of Hi(t.properties)){if(r.type!=="ObjectProperty"||r.computed)throw new Error("dynamic object property");let o=vp(r.key);if(!o)throw new Error("unsupported object key");n[o]=Tc(r.value)}return n}throw new Error(`unsupported static value: ${t?.type??"unknown"}`)}function Fc(e,t){let n=[],r=Ep(t);if(r===null)return{found:!1,seo:null,diagnostics:n};let o;try{o=Uk(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 Hi(o.program.body)){let u=l.type==="ExportNamedDeclaration"?l.declaration:l;if(u?.type==="VariableDeclaration")for(let d of Hi(u.declarations)){let f=d.id;f?.type==="Identifier"&&f.name==="PAGE_SEO"&&(i=d.init)}}if(i==null)return{found:!1,seo:null,diagnostics:n};let s=zk(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 Hi(s.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=vp(l.key);if(!(u!=="path"&&u!=="title"&&u!=="description"&&u!=="keywords"&&u!=="meta_tags_json"&&u!=="schema_json"&&u!=="breadcrumbs_json")){if(u==="path"||u==="title"||u==="description"||u==="keywords"){let d=Xk(l.value);if(d===void 0){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} is not a static string; skipped`});continue}a[u]=d;continue}try{let d=Tc(l.value);u==="meta_tags_json"&&d!==null&&typeof d=="object"&&!Array.isArray(d)?a.meta_tags_json=d:u==="schema_json"&&d!==null&&typeof d=="object"?a.schema_json=d:u==="breadcrumbs_json"&&Array.isArray(d)?a.breadcrumbs_json=d:n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} has unsupported static shape; skipped`})}catch(d){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} is not a static JSON-like value; skipped: ${d instanceof Error?d.message:String(d)}`})}}}let c=r;return a.path!==void 0&&(a.path!==r&&n.push({code:"page-seo.path-mismatch",message:`PAGE_SEO.path "${a.path}" != derived "${r}"; using PAGE_SEO.path`}),c=a.path),{found:!0,seo:{path:c,...a.title!==void 0?{title:a.title}:{},...a.description!==void 0?{description:a.description}:{},...a.keywords!==void 0?{keywords:a.keywords}:{},...a.meta_tags_json!==void 0?{meta_tags_json:a.meta_tags_json}:{},...a.schema_json!==void 0?{schema_json:a.schema_json}:{},...a.breadcrumbs_json!==void 0?{breadcrumbs_json:a.breadcrumbs_json}:{}},diagnostics:n}}import{parse as Wk}from"@babel/parser";var kp=["page","anchor","external","email","phone","group","file"],Hk=["link","cta"],Cp=["description","badge","iconKey"],_c=["label","targetType","href","role","openInNewTab","nofollow","children",...Cp],Gk=new Set(_c);function lo(e){return Array.isArray(e)?e:[]}function co(e){let t=e;return t?.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function Yk(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Ip(e){let t=e;return t?.type==="BooleanLiteral"&&typeof t.value=="boolean"?t.value:void 0}function Mc(e){let t=[],n;try{n=Wk(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 lo(n.program.body)){let s=i.type==="ExportNamedDeclaration"?i.declaration:i;if(s?.type==="VariableDeclaration")for(let a of lo(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 lo(r.elements).forEach((i,s)=>{let a=Rp(i,`NAV_ITEMS[${s}]`,t);a&&o.push(a)}),{items:o,diagnostics:t}}function Rp(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 lo(e.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=Yk(l.key);u&&(r[u]=l.value)}let o=co(r.label),i=co(r.targetType);if(!o)return n.push({severity:"fatal",path:`${t}.label`,message:"label must be a static string"}),null;if(!i||!kp.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${kp.join("/")}`}),null;r.group!==void 0&&n.push({severity:"warning",code:"leaf-group-field",path:`${t}.group`,message:'unsupported leaf group field ignored; use a canonical targetType: "group" node with children'});let s={label:o,targetType:i};for(let l of Cp){if(r[l]===void 0)continue;let u=co(r[l]);u!==void 0?s[l]=u:n.push({severity:"warning",path:`${t}.${l}`,message:`${l} ignored: not a static string`})}r.icon!==void 0&&n.push({severity:"warning",path:`${t}.icon`,message:"icon component ref ignored; use static iconKey"});for(let l of Object.keys(r))Gk.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 ${_c.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=[];lo(r.children.elements).forEach((u,d)=>{let f=Rp(u,`${t}.children[${d}]`,n);f&&l.push(f)}),s.children=l}if(i==="group")return s.children?s:(n.push({severity:"fatal",path:`${t}.children`,message:"group item requires children"}),null);let a=co(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=co(r.role);if(c!==void 0&&(Hk.includes(c)?s.role=c:n.push({severity:"warning",path:`${t}.role`,message:"role ignored: not link/cta"})),r.openInNewTab!==void 0){let l=Ip(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=Ip(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 Zk}from"@babel/parser";function uo(e){return Array.isArray(e)?e:[]}function wp(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function Qk(e){let t;try{t=Zk(e,{sourceType:"module",plugins:["typescript","jsx"],tokens:!0})}catch{return{status:"unsupported"}}let n=[];for(let o of uo(t.program.body)){let i=o.type==="ExportNamedDeclaration"?o.declaration:o;if(i?.type==="VariableDeclaration")for(let s of uo(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=wp(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 Oc(e,t){let n=Np(t);if(!n)return{status:"unsupported",source:e};let r=Qk(e);if(r.status!=="ok")return{status:r.status,source:e};let o=r.array;if(Mc(e).diagnostics.some(({severity:l})=>l==="fatal"))return{status:"unsupported",source:e};let s=[],a=l=>{let u=uo(l.elements);for(let[d,f]of u.entries()){if(eI(f,n)){let m=u[d+1],h=u[d-1],y=f.start,b=f.end;if(typeof y!="number"||typeof b!="number")continue;if(m&&typeof m.start=="number")s.push({start:y,end:m.start});else if(h&&typeof h.end=="number")s.push({start:h.end,end:b});else{let S=/^\s*,/.exec(e.slice(b));s.push({start:y,end:S?b+S[0].length:b})}continue}let g=qk(f);g&&a(g)}};if(a(o),s.length===0)return{status:"not_found",source:e};let c=e;for(let l of s.sort((u,d)=>d.start-u.start))c=c.slice(0,l.start)+c.slice(l.end);return{status:"removed",source:c,removedCount:s.length}}function qk(e){if(e.type==="ObjectExpression")for(let t of uo(e.properties)){if(t.type!=="ObjectProperty")continue;let n=t.key;if((n?.name??n?.value)==="children")return wp(t.value)}}function Np(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function eI(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of uo(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"&&Np(n??"")===t}import{estimateNavLabelWidth as EM}from"@vcp-dev/contracts";import{parse as IM}from"@babel/parser";var nI="components/site/generated/",fo=[".tsx",".ts",".jsx",".js"];function Pp(e){if(e.expectedUrlPath===tI)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set(io(Object.keys(e.files).map(h=>({path:h}))).map(h=>h.entryFile)),n=Object.entries(e.files).filter(([h,y])=>{let b=h.replace(/\\/g,"/");if(!t.has(b))return!1;let S=Fc(y,b);return S.found&&S.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=zi({files:new Map(Object.entries(e.files))});for(let y of h)y.canonicalEntryFile===r&&o.add(y.entryFile)}catch(h){return{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:h instanceof Error?h.message:"Invalid page template source."}}let i=rI(e.files);if(!i.ok)return i.error;let s=i.graph,a=aI(o,s),c=cI(o,a,s),l=[...a].filter(h=>!c.has(h)).sort((h,y)=>h.localeCompare(y)),u=[...o,...[...c].sort((h,y)=>h.localeCompare(y))],d=new Set(u),f=u.map(h=>({operation:"delete",file:h})),g=[],m=[];for(let[h,y]of Object.entries(e.files))if(!d.has(h)){if(y.includes("NAV_ITEMS")){let b=Oc(y,e.expectedUrlPath);b.status==="removed"?(f.push({operation:"upsert",file:h,content:b.source}),g.push(h)):b.status==="unsupported"&&m.push(`unsupported_navigation:${h}`)}y.includes(e.expectedUrlPath)&&!y.includes("NAV_ITEMS")&&m.push(`preserved_link:${h}`)}return{ok:!0,edits:f,deletedFiles:u,updatedFiles:g,preservedSharedFiles:l,warnings:m}}function rI(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")||!oI(r))continue;let s=Wt(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(iI(c))continue;let l=In(r,c),u=sI(l,t);if(!u)return{ok:!1,error:{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:`Page source dependencies could not be proven safe: ${r} -> ${c} (import-not-found).`}};a.add(u)}n.set(r,a)}return{ok:!0,graph:n}}function oI(e){let t=e.toLowerCase();return fo.some(n=>t.endsWith(n))}function iI(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!fo.some(n=>e.endsWith(n)))}function sI(e,t){let n=e.replace(/\\/g,"/");return(fo.some(o=>n.endsWith(o))?[n]:[...fo.map(o=>`${n}${o}`),...fo.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function aI(e,t){let n=new Set,r=[...e].flatMap(o=>[...t.get(o)??[]]);for(;r.length>0;){let o=r.pop();!o.startsWith(nI)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function cI(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 Am from"@babel/parser";import*as ge from"@babel/types";import*as ds from"node:path";import*as ke from"@babel/types";function Ap(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 jt(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return Dn(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(ke.isObjectPattern(n)||ke.isArrayPattern(n))return Dn(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(uI(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function Dn(e,t,n=!1){return ke.isIdentifier(e)?e.name===t&&n:ke.isObjectPattern(e)?e.properties.some(r=>ke.isObjectProperty(r)?Dn(r.value,t,n):Dn(r.argument,t,n)):ke.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=ke.isRestElement(r)?r.argument:r;return Dn(o,t,n)}):ke.isAssignmentPattern(e)?Dn(e.left,t,!0):ke.isRestElement(e)?Dn(e.argument,t,n):!1}function fr(e,t){if(e.path.isObjectPattern()){if(t){let r=Nt(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:jt(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:jt(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=Tp(r),i=!1,s=o?o.initBinding&&Lc(o.initBinding)?(i=jt(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=fr(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=Nt(e.path.node.id,e.identifier.name);if(s&&a){let c=[...s,...a],[l,...u]=c;return!l||l.kind!=="property"?null:{propName:l.name,remainingPath:[...u,...t?.path??[]],hasDefault:i||jt(e)}}}}let n=pI(e);if(n){let r=lI(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||jt(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=dI(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:jt(e)}}let i=po(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:jt(e)}:null}if(Lc(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:jt(e)}}return null}function lI(e,t){let n=e.findParent(u=>u.isVariableDeclarator());if(!n?.isVariableDeclarator())return null;let r=n.get("init");if(!r?.isExpression())return null;let o=Tp(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=Lc(i)?(a=jt(i),[...s]):(()=>{let u=fr(i,{kind:"identifier",expression:i.identifier.name,base:i.identifier.name,path:[]});return a=u?.hasDefault??!1,u?[{kind:"property",name:u.propName},...u.remainingPath,...s]:null})();if(!c)return null;let l=Nt(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||jt(t)}:null}function Tp(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=mI(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function Lc(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function uI(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function dI(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=Nt(i.node,t);if(a)return a}return null}function Fp(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=Gi(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=po(a.node);if(!c||n&&c!==n)continue;let l=a.get("value");if(!l.isAssignmentPattern())continue;let u=l.get("right");if(u.isExpression())return{propName:c,componentName:t,expressionPath:u,displayPath:`${t}.${c}.default`}}let r=fI(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=po(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 Gi(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=po(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&Nt(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=Gi(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=Gi(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=Gi(r,t);if(o)return o}}return null}function Nt(e,t,n=[]){if(ke.isIdentifier(e))return e.name===t?n:null;if(ke.isObjectPattern(e)){for(let r of e.properties)if(ke.isObjectProperty(r)){let o=po(r);if(!o)continue;let i=Nt(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(ke.isRestElement(r)){let o=Nt(r.argument,t,n);if(o)return o}}if(ke.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=ke.isRestElement(o)?o.argument:o,s=Nt(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return ke.isAssignmentPattern(e)?Nt(e.left,t,n):null}function fI(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function pI(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 po(e){return e.computed?null:ke.isIdentifier(e.key)?e.key.name:ke.isStringLiteral(e.key)?e.key.value:null}function mI(e){let t=[],n=e;for(;ke.isMemberExpression(n);){if(n.computed)if(ke.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(ke.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(ke.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return ke.isIdentifier(n)?{base:n.name,path:t}:null}import*as Bp from"@babel/parser";import jc from"@babel/traverse";import*as pr from"@babel/types";import*as de from"@babel/types";var _p=new WeakMap;function Qi(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?Yi(n,t):null}if(e.isMemberExpression()){let n=SI(e.node),r=gI(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?Yi(o,[...r,...t]):null}return e.isAwaitExpression()||Bc(e.node)?pn(vI(e.node),t,"awaited or fetched expression"):null}function gI(e){let t=[],n=e;for(;de.isMemberExpression(n);){if(n.computed)if(de.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(de.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(de.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return de.isIdentifier(n)?t:null}function Yi(e,t=[],n){let r=hI(e,t);if(r)return r;let o=yI(e,t,n);if(o)return o;let i=xI(e,t,n);return i||null}function go(e){return e?.kind==="api-source"}function hI(e,t){if(e.path.isVariableDeclarator()&&de.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&Dc(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return pn(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&de.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(c=>de.isObjectProperty(c)&&Lp(c)==="data"&&mo(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&Dc(a.node))return pn(e.identifier.name,t,"query hook data binding")}let n=bI(e);if(!n||Lp(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()||!Dc(i.node)?null:pn(e.identifier.name,t,"query hook data binding")}function yI(e,t,n){if(e.path.isVariableDeclarator()&&de.isArrayPattern(e.path.node.id)){let c=e.path.get("init");if(!c?.isCallExpression()||!Op(c.node))return null;let[l,u]=e.path.node.id.elements;return!de.isIdentifier(l)||l.name!==e.identifier.name||!de.isIdentifier(u)?null:Mp(e,u.name,n)?pn(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()||!Op(i.node)||r.node.elements.findIndex(c=>c===e.path.node)!==0)return null;let a=r.node.elements[1];return de.isIdentifier(a)&&Mp(e,a.name,n)?pn(e.identifier.name,t,"state setter is updated by API data"):null}function xI(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()?pn(e.identifier.name,t,"awaited binding result"):Bc(o.node,n)?pn(e.identifier.name,t,"fetch-backed binding result"):null:null}function bI(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 mo(e,t){return de.isIdentifier(e)?e.name===t:de.isAssignmentPattern(e)?mo(e.left,t):de.isObjectPattern(e)?e.properties.some(n=>de.isObjectProperty(n)?mo(n.value,t):mo(n.argument,t)):de.isArrayPattern(e)?e.elements.some(n=>!!n&&mo(de.isRestElement(n)?n.argument:n,t)):!1}function Mp(e,t,n){let r=!1,o=!1,i=e.scope.path,s;if(n){let c=_p.get(n);c||(c=new WeakMap,_p.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){Bc(c.node)&&(r=!0),(EI(c.node.callee,t)||c.node.arguments.some(l=>de.isIdentifier(l)&&l.name===t))&&(o=!0)}});let a=r&&o;return s?.set(t,a),a}function Dc(e){let t=qi(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function Op(e){return qi(e.callee)==="useState"}function Bc(e,t){let n=t?.get(e);if(n!==void 0)return n;let r=Zi(e,o=>de.isCallExpression(o)&&qi(o.callee)==="fetch");return t?.set(e,r),r}function SI(e){let t=e;for(;de.isMemberExpression(t);)t=t.object;return de.isIdentifier(t)?t.name:null}function Lp(e){return e.computed?null:de.isIdentifier(e.key)?e.key.name:de.isStringLiteral(e.key)?e.key.value:null}function qi(e){return de.isIdentifier(e)?e.name:de.isMemberExpression(e)&&de.isIdentifier(e.property)?e.property.name:null}function EI(e,t){return Zi(e,n=>de.isIdentifier(n)&&n.name===t)}function Zi(e,t){if(t(e))return!0;let n=de.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(de.isNode(i)&&Zi(i,t))return!0;continue}if(de.isNode(o)&&Zi(o,t))return!0}return!1}function vI(e){return de.isIdentifier(e)?e.name:de.isCallExpression(e)?qi(e.callee)??"api":de.isAwaitExpression(e)?"awaited-api":"api"}function pn(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:kI(e,t),reason:n}}function kI(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var jp=typeof jc=="function"?jc:jc.default;function $p(e,t){let n=Kp(e);if(!n)return{allowed:!0};let r=!1;return jp(n,{CallExpression(o){if(!Up(o.node,t.sourceRange)||!II(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||go(Qi(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function Vp(e,t){let n=Kp(e);if(!n)return{allowed:!0};let r=!1;return jp(n,{JSXExpressionContainer(o){Up(o.node,t.sourceRange)&&(pr.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 Kp(e){try{return Bp.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function II(e){let t=e.callee;return pr.isMemberExpression(t)&&pr.isIdentifier(t.property)&&t.property.name==="map"}function Up(e,t){let n=e.loc;return n?Dp({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&Dp({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function Dp(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 z from"@babel/types";import*as Jp from"@babel/parser";import $c from"@babel/traverse";import*as Me from"@babel/types";import*as mr from"node:path";var Pt=typeof $c=="function"?$c:$c.default;function Xe(e){try{return Jp.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Vc(e){return e.computed?Me.isStringLiteral(e.key)||Me.isNumericLiteral(e.key)?String(e.key.value):null:CI(e.key)}function CI(e){return Me.isIdentifier(e)?e.name:Me.isStringLiteral(e)||Me.isNumericLiteral(e)?String(e.value):null}function Bn(e){return Me.isParenthesizedExpression(e)||Me.isTSAsExpression(e)||Me.isTSSatisfiesExpression(e)||Me.isTSNonNullExpression(e)||Me.isTSTypeAssertion(e)?Bn(e.expression):Me.isExpression(e)?e:null}function Kc(e){if(Me.isIdentifier(e))return[e.name];if((Me.isMemberExpression(e)||Me.isOptionalMemberExpression(e))&&!e.computed&&Me.isIdentifier(e.property)){let t=Bn(e.object),n=t?Kc(t):null;return n?[...n,e.property.name]:null}return null}function jn(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?mr.normalize(mr.join(mr.dirname(e),t)).replace(/\\/g,"/"):t}function dt(e,t){return es(e)===es(t)}function es(e){let t=gr(e);return t.endsWith("/index")?t.slice(0,-6):t}function gr(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function Wp(e,t,n){let r=Zp(e,t);if(Qp(e,r),qp(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 Pt(e,{JSXElement(s){rm(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:ts(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 Hp(e,t){let n=new Map,r=i=>{let s=hr(i);return n.has(s)?!1:(n.set(s,i),!0)};r(t);let o=!0;for(;o;){o=!1;for(let i of e)for(let s of RI(i,n))o=r(s)||o}return[...n.values()]}function RI(e,t){let n=[],r=wI(e,t);for(let o of e.ast.program.body){if(z.isExportDefaultDeclaration(o)&&z.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=ho(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(z.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=jn(e.file,o.source.value);for(let s of o.specifiers){if(z.isExportNamespaceSpecifier(s)){let l=mn(s.exported);for(let u of t.values())dt(u.file,i)&&n.push({file:e.file,namespace:Uc(l,u.namespace),exportName:u.exportName});continue}if(!z.isExportSpecifier(s))continue;let a=mn(s.local),c=[...t.values()].filter(l=>dt(l.file,i)&&$n(l.namespace,a));if(c.length>0){let l=mn(s.exported);for(let u of c){let d=ho(u.namespace,a,l);d&&n.push({file:e.file,namespace:d,exportName:u.exportName})}continue}t.has(hr({file:i,exportName:a}))&&n.push({file:e.file,exportName:mn(s.exported)})}continue}if(z.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!z.isExportSpecifier(i))continue;let s=mn(i.local),a=r.get(s)??[];if(a.length>0){let c=mn(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let u=ho(l.namespace,s,c);u&&n.push({file:e.file,namespace:u,exportName:l.exportName})}}}continue}if(z.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=jn(e.file,o.source.value),s=o.exported;if(s){let a=mn(s);for(let c of t.values())dt(c.file,i)&&n.push({file:e.file,namespace:Uc(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())dt(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function Uc(e,t){return t?`${e}.${t}`:e}function $n(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function ho(e,t,n){return!$n(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function wI(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(!z.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=jn(e.file,i.source.value);for(let a of i.specifiers){if(z.isImportDefaultSpecifier(a)){let c=t.get(hr({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(u=>dt(u.file,s)&&$n(u.namespace,"default"));for(let u of l){let d=ho(u.namespace,"default",a.local.name);d&&r(a.local.name,{...u,namespace:d})}continue}if(z.isImportSpecifier(a)){let c=mn(a.imported),l=[...t.values()].filter(d=>dt(d.file,s)&&$n(d.namespace,c));for(let d of l)r(a.local.name,d);let u=t.get(hr({file:s,exportName:c}));u&&r(a.local.name,u);continue}if(z.isImportNamespaceSpecifier(a))for(let c of t.values())dt(c.file,s)&&r(a.local.name,{...c,namespace:Uc(a.local.name,c.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(z.isVariableDeclaration(i))for(let s of i.declarations){if(!z.isIdentifier(s.id)||!s.init)continue;let a=Bn(s.init);if(!a||!z.isIdentifier(a))continue;let c=n.get(a.name)??[];if(c.length===0)continue;let l=n.get(s.id.name)??[],u=new Set(l.map(hr));for(let d of c){let f=ho(d.namespace,a.name,s.id.name),g=f?{...d,namespace:f}:d,m=hr(g);u.has(m)||(r(s.id.name,g),u.add(m),o=!0)}}}return n}function hr(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${es(e.file)}#${t}`}function mn(e){return z.isIdentifier(e)?e.name:e.value}function Gp(e,t){for(let n of e.program.body){if(z.isExportDefaultDeclaration(n)){let o=n.declaration;if((z.isFunctionDeclaration(o)||z.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(z.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!z.isExportNamedDeclaration(n))continue;let r=n.declaration;if((z.isFunctionDeclaration(r)||z.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(z.isVariableDeclaration(r)){for(let o of r.declarations)if(z.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!z.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:z.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function Xc(e){let t=NI(e),n=[],r=qp(e.ast,t);return Pt(e.ast,{JSXElement(o){dt(e.file,e.sourceFile)&&ts(o)===e.sourceComponent||rm(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function Yp(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function Zp(e,t){let n=Yp();return Pt(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function NI(e){let t=Yp();return dt(e.file,e.sourceFile)&&PI(t,Zp(e.ast,e.sourceComponent)),Pt(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=jn(e.file,o),s=e.componentIdentities.filter(a=>dt(a.file,i));if(s.length!==0)for(let a of r.specifiers){let c=n.scope.getBinding(a.local.name);if(c){if(z.isImportDefaultSpecifier(a)&&s.some(l=>l.exportName==="default")&&t.localBindings.add(c),z.isImportDefaultSpecifier(a)){let l=s.filter(u=>$n(u.namespace,"default"));if(l.length>0){let u=t.namespaceMembers.get(c)??new Set;for(let d of l){let f=zp(d,"default");f&&u.add(f)}t.namespaceMembers.set(c,u)}continue}if(z.isImportSpecifier(a)){let l=z.isIdentifier(a.imported)?a.imported.name:a.imported.value,u=s.filter(d=>$n(d.namespace,l));if(u.length>0){let d=t.namespaceMembers.get(c)??new Set;for(let f of u){let g=zp(f,l);g&&d.add(g)}t.namespaceMembers.set(c,d);continue}s.some(d=>!d.namespace&&d.exportName===l)&&t.localBindings.add(c);continue}if(z.isImportNamespaceSpecifier(a))for(let l of s){let u=l.namespace?`${l.namespace}.${l.exportName}`:l.exportName,d=t.namespaceMembers.get(c)??new Set;d.add(u),t.namespaceMembers.set(c,d)}}}}}),Qp(e.ast,t),t}function PI(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 Qp(e,t){Pt(e,{VariableDeclarator(n){if(!n.node.init)return;let r=Bn(n.node.init);if(r){if(z.isIdentifier(n.node.id)){let o=Vn(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&Jc(t,i,o);return}if(z.isObjectPattern(n.node.id)){let o=Vn(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&nm(n.node.id,o.namespaceMembers,t,n)}}}})}function qp(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return Pt(e,{ReferencedIdentifier(r){if(n){r.stop();return}AI(r)||!r.isIdentifier()||!em(r,t)||TI(r,t)||FI(r)||(n=!0,r.stop())}}),n}function AI(e){let t=e;for(;t.parentPath?.isJSXMemberExpression();)t=t.parentPath;let n=t.parentPath;return!!(n?.isJSXOpeningElement()&&n.node.name===t.node||n?.isJSXClosingElement()&&n.node.name===t.node)}function em(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)&&Vn(r.node,t,r)?r:null}function TI(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!Xp(e,r))return!1;let o=em(e,t);if(!o)return!1;if(Bn(r.node)===o.node)return!!Vn(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&Xp(e,a)&&!!Vn(a.node,t,a)}function FI(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function Xp(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Vn(e,t,n){let r=Bn(e);if(!r)return null;if(z.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(z.isObjectExpression(r))return _I(r,t,n);let o=Kc(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?tm(s,o.slice(1).join(".")):null}function _I(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!z.isObjectProperty(i))continue;let s=Vc(i);if(!s||!z.isExpression(i.value)){z.isExpression(i.value)&&(o||=Vn(i.value,t,n)!==null);continue}let a=Vn(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 tm(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 Jc(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 nm(e,t,n,r){for(let o of e.properties){if(z.isRestElement(o)){if(z.isIdentifier(o.argument)){let c=r.scope.getBinding(o.argument.name);c&&Jc(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!z.isObjectProperty(o))continue;let i=Vc(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=tm(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=z.isAssignmentPattern(o.value)?o.value.left:o.value;if(z.isIdentifier(a)){let c=r.scope.getBinding(a.name);c&&Jc(n,c,s);continue}if(z.isObjectPattern(a)&&s.namespaceMembers.size>0){nm(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function zp(e,t){if(!$n(e.namespace,t))return null;if(e.namespace===t)return e.exportName;let n=e.namespace?.slice(t.length+1);return n?`${n}.${e.exportName}`:e.exportName}function rm(e,t){let n=e.node.openingElement.name;if(z.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=om(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 om(e){if(z.isJSXIdentifier(e))return[e.name];if(z.isJSXMemberExpression(e)){let t=om(e.object);return t?[...t,e.property.name]:null}return null}function ts(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()&&z.isIdentifier(n.node.id))return n.node.id.name}return null}function im(e,t){let n=Xe(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=Xc({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 Ee(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 Se(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function $t(e,t){let n=Se(e);return!!(n&&ft(t,n))}function ft(e,t){return t.start>=e.start&&t.end<=e.end}function Et(e,t){let n=ue(e,Ee(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:ns(e,t)}function yr(e,t){let n=Se(t);return n?e.slice(n.start,n.end):""}function sm(e,t){return e.start===t.start&&e.end===t.end}function ns(e,t){let n=null;return Pt(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 rs(e,t){return zc(e,t).length>0}function os(e,t){let n=Se(e.node),r=Se(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()&&!MI(o,n,r)))return!0;o=o.parentPath}return!1}function MI(e,t,n){let r=Se(e.node.consequent);if(r&&ft(r,t)&&!ft(r,n))return!1;let o=e.node.alternate?Se(e.node.alternate):null;return!(o&&ft(o,t)&&!ft(o,n))}function zc(e,t){let n=Se(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=Se(o.node.consequent),a=Se(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()&&Wc(o.node.operator)){let s=Se(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 Wc(e){return e==="&&"||e==="||"||e==="??"}function am(e,t){let n=Se(e.consequent);if(n&&ft(n,t))return n;let r=Se(e.alternate);return r&&ft(r,t)?r:null}function cm(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=>gr(a.file)));if(!t.has(gr(e.sourceFile))||!t.has(gr(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(gr(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=Gp(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=Xe(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=Hp(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=Xc({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!dt(s.file,e.targetFile)||ts(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 is(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 yo();let a=s.target,c=a.locator;if(a.sourceKind==="repeat-template"){let l=o?.instanceIndex;if(l===void 0)return yo();let u=OI(a,l,o?.instanceCount);if(!u)return yo();c=u}return{ok:!0,target:{kind:"value-binding",file:a.file,locator:c}}}return o?.instanceIndex!==void 0?n!=="selection"||!i?.ok?{ok:!1,code:"repeat-target-failed",reason:i&&!i.ok?i.reason:"No safe selected repeat property target is available"}:{ok:!0,target:{kind:"repeat-property",target:i}}:e.isRepeat&&n!=="template"||t.status==="direct"&&t.target?.kind!=="jsx-attribute"?yo():{ok:!0,target:{kind:"jsx-attribute"}}}function yo(){return{ok:!1,code:"unsupported-binding",reason:"Property does not have a safe typed binding write target for this scope and operation"}}function OI(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 Vt from"@babel/types";import{SiteEditSetPropsParamsSchema as LI}from"@vcp-dev/contracts";function lm(e){let t=e.changes??(e.change?[e.change]:[]);if(!LI.safeParse({kind:"set-props",scope:"selection",changes:t}).success)return xo("invalid-change","Repeat property changes are invalid");if(t.length!==1||t[0].name!==e.target.propertyName)return xo("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=Pe(e.source,"value");if(!o.ok)return xo("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=ue(o.ast,a);if(!c.ok||!c.match.path.isObjectExpression())return xo("unsupported-object",`Repeat item ${s} is not a writable object expression`);let l=s===e.target.sourceItemIndex?DI(r):BI(c.match.path.node,r.name);if(!l)return xo("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 DI(e){return e.operation==="set"?{kind:"value",value:e.value}:{kind:"undefined"}}function BI(e,t){let n=e.properties.filter(i=>Vt.isObjectProperty(i)&&jI(i.key)===t);if(n.length>1)return null;let r=n[0];if(!r)return{kind:"undefined"};if(!Vt.isExpression(r.value))return null;let o=Bt(r.value);return o.status==="undefined"?{kind:"undefined"}:o.status!=="resolved"?null:{kind:"value",value:o.value}}function jI(e){return Vt.isIdentifier(e)?e.name:Vt.isStringLiteral(e)?e.value:Vt.isNumericLiteral(e)?String(e.value):null}function xo(e,t){return{ok:!1,errorCode:e,reason:t}}function um(e){if(e.change.name!=="className"&&e.change.name!=="class")return bo("unsupported-owner",`No specialized property owner is available for '${e.change.name}'`);let t=e.classNameSource;if(!t||t.filePath!==e.node.file)return bo("owner-source-unavailable","className source details are unavailable for the selected node");if(e.change.name==="class"&&t.sourceKind==="missing")return bo("owner-source-unavailable","The class alias requires an existing className source");if(t.sourceKind==="expression")return bo("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 bo("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 bo(e,t){return{ok:!1,errorCode:e,reason:t}}async function fm(e){let t=$I.safeParse({kind:"set-props",scope:e.scope,changes:e.changes});if(!t.success)return gn("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 gn("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 VI(e,r);if(o){if(!o.ok)return gn("owner-plan-failed",o.reason);dm(n,o.steps);continue}let i=await e.getPropertyState(e.node.key,r.name,e.selectionRef);if(!i)return gn("missing-property-state",`No authoritative property state is available for '${r.name}'`);if(i.status==="blocked")return gn("readonly-property",i.diagnostic?.message??`Property '${r.name}' is not writable`);if(JI(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=is({state:i,scope:e.scope,operation:r.operation,selectionRef:e.selectionRef,repeatTarget:s});if(!a.ok)return gn(a.code,a.reason);let c=a.target;if(c.kind==="value-binding"&&r.operation==="set"){Hc(n,{type:"update-value",order:n.length,file:c.file,locator:c.locator,value:r.value});continue}if(c.kind==="repeat-property"){let l=lm({source:e.getFileContent(c.target.sourceFile),target:c.target,changes:[r]});if(!l.ok)return gn("repeat-target-failed",l.reason);dm(n,l.steps);continue}Hc(n,{type:"set-property-changes",order:n.length,file:e.node.file,locator:KI(e.node),scope:e.scope,changes:[r]})}return n.forEach((r,o)=>{r.order=o}),UI(n)?gn("step-conflict","Property changes resolve to conflicting write steps"):{ok:!0,steps:n}}async function VI(e,t){return t.name!=="className"&&t.name!=="class"?null:um({node:e.node,change:t,classNameSource:e.classNameSource})}function KI(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 UI(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 dm(e,t){for(let n of t)Hc(e,{...n,order:e.length})}function Hc(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 JI(e,t){if(t.operation!=="set"||e.status!=="direct")return!1;let n=e.attribute?.resolution;return n?.status==="resolved"?Gc(n.value,t.value):e.attribute?.source===null&&e.attribute.value===t.value}function Gc(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)=>Gc(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=>Gc(n[i],r[i]))}return!1}function gn(e,t){return{ok:!1,errorCode:e,reason:t}}import*as br from"@babel/types";import*as Q from"@babel/types";function Yc(e,t,n){let r=Et(t,n);return r?Kt(e,r):null}function Kt(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(!Q.isIdentifier(l)||l.name!=="map"||c.computed)return null;let u=a.get("object"),d=yr(e,u.node),f=r.node.params.map(h=>yr(e,h)),g=Se(i.node),m=Se(r.node);return!d||f.some(h=>h.length===0)||!g||!m?null:{callStart:g.start,callEnd:g.end,callbackStart:m.start,callbackEnd:m.end,collectionExpression:d,callbackParams:f,mapOperator:Q.isOptionalMemberExpression(c)&&c.optional?"?.map":".map",collectionNeedsParens:ss(u.node),callbackPath:r,collectionPath:u}}function So(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function XI(e,t){let n=Se(e.node);return n?zI(t).some(r=>{let o=Se(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function zI(e){let t=e.callbackPath.node.body;return Q.isBlockStatement(t)?hn(t.body):yn(t)}function hn(e){let t=[];for(let n of e){if(Q.isReturnStatement(n)){n.argument&&t.push(...yn(n.argument));continue}if(Q.isBlockStatement(n)){t.push(...hn(n.body));continue}if(Q.isIfStatement(n)){let r=Q.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...hn(r)),n.alternate){let o=Q.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...hn(o))}continue}if(Q.isSwitchStatement(n)){for(let r of n.cases)t.push(...hn(r.consequent));continue}Q.isTryStatement(n)&&(t.push(...hn(n.block.body)),n.handler&&t.push(...hn(n.handler.body.body)),n.finalizer&&t.push(...hn(n.finalizer.body)))}return t}function yn(e){return Q.isJSXElement(e)?WI(e)?pm(e.children):[e]:Q.isJSXFragment(e)?pm(e.children):Q.isParenthesizedExpression(e)||Q.isTSAsExpression(e)||Q.isTSSatisfiesExpression(e)||Q.isTSNonNullExpression(e)||Q.isTSTypeAssertion(e)?yn(e.expression):Q.isConditionalExpression(e)?[...yn(e.consequent),...yn(e.alternate)]:Q.isLogicalExpression(e)&&Wc(e.operator)?yn(e.right):[]}function pm(e){return e.flatMap(t=>Q.isJSXElement(t)||Q.isJSXFragment(t)?yn(t):Q.isJSXExpressionContainer(t)&&(Q.isJSXElement(t.expression)||Q.isJSXFragment(t.expression)||Q.isConditionalExpression(t.expression)||Q.isLogicalExpression(t.expression))?yn(t.expression):[])}function WI(e){let t=e.openingElement.name;return Q.isJSXIdentifier(t)?t.name==="Fragment":Q.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function mm(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function ss(e){return!(Q.isIdentifier(e)||Q.isThisExpression(e)||Q.isMemberExpression(e)||Q.isOptionalMemberExpression(e)||Q.isCallExpression(e)||Q.isOptionalCallExpression(e))}function gm(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(Q.isMemberExpression(n)||Q.isOptionalMemberExpression(n))&&Q.isIdentifier(n.property)&&n.property.name==="map"&&!n.computed}function xr(e,t){let n=Xe(e);if(!n)return t.isRepeatItemRoot===!0;let r=ue(n,Ee(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:ns(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=Kt(e,o);return i?XI(o,i):t.isRepeatItemRoot===!0}function hm(e,t){let n=Xe(e);if(!n)return!1;let r=ue(n,Ee(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:ns(n,t);return o?!!o.findParent(i=>{if(!i.isCallExpression()&&!i.isOptionalCallExpression())return!1;let s=i.node.callee;return(Q.isMemberExpression(s)||Q.isOptionalMemberExpression(s))&&Q.isIdentifier(s.property)&&s.property.name==="map"}):!1}import*as we from"@babel/types";function Zc(e){if(we.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(we.isJSXMemberExpression(e)){let t=e;for(;we.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function HI(e,t){let n=Se(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);!a||$t(a.path.node,n)||xn(a,i,t)||r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=Zc(i.node.name);s&&o(s,i)}}),[...r].sort()}function Qc(e,t,n){let r=Xe(e);if(!r)return{ok:!0};let o=ue(r,Ee(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=ue(r,Ee(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};let s=$r(o.match.path,i.match.path);if(rs(s,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let a=HI(s,i.match.path);return a.length>0?{ok:!1,bindingNames:a}:{ok:!0}}function xm(e){let t=e;for(;we.isTSQualifiedName(t);)t=t.left;return we.isIdentifier(t)?t.name:null}function Eo(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function as(e){let t=[],n=r=>{if(r){if(we.isIdentifier(r)){t.push(r.name);return}if(we.isObjectPattern(r)){for(let o of r.properties){if(we.isRestElement(o)){n(o.argument);continue}we.isObjectProperty(o)&&n(o.value)}return}if(we.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(we.isAssignmentPattern(r)){n(r.left);return}if(we.isRestElement(r)){n(r.argument);return}we.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function qc(e,t){let n=Se(e.node),r=Se(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=ym(e),i=ym(t);if(!o||!i||!sm(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=am(s.node,n);if(a&&!ft(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=Se(s.node.right);if(a&&ft(a,n)&&!ft(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())&&gm(s)){let a=Se(s.node.body)??Se(s.node);if(a&&!ft(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 ym(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?Se(t.node.argument):null;if(t.isArrowFunctionExpression()&&(we.isJSXElement(t.node.body)||we.isJSXFragment(t.node.body)||we.isConditionalExpression(t.node.body)||we.isLogicalExpression(t.node.body)))return Se(t.node.body);t=t.parentPath}return null}function xn(e,t,n){return n.scope.getBinding(t)===e}function el(e,t,n,r={}){if(!r.preserveConditionalBoundary&&rs(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=Se(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(c=>as(c)).map(c=>n.callbackPath.scope.getBinding(c)?.path.node).filter(Boolean)),s=new Set,a=(c,l)=>{let u=l.scope.getBinding(c);!u||$t(u.path.node,o)||i.has(u.path.node)||xn(u,c,t)||s.add(c)};return e.traverse({ReferencedIdentifier(c){a(c.node.name,c)},JSXOpeningElement(c){let l=Zc(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function tl(e,t,n){let r=Se(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>as(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return Eo(e,s=>{let a=s.scope.getBinding(s.node.name);!a||$t(a.path.node,r)||o.has(a.path.node)||xn(a,s.node.name,t)||i.add(s.node.name)}),i.size>0?{ok:!1,bindingNames:[...i].sort()}:{ok:!0}}function bm(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>as(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)||xn(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(br.isIdentifier(l))o(l.name,c);else{let u=xm(l);u&&o(u,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function nl(e,t){let n=Se(e.node),r=new Set;return Eo(e,o=>{let i=o.scope.getBinding(o.node.name);i&&(n&&$t(i.path.node,n)||xn(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(br.isIdentifier(n)){t.push(n.name);continue}if(br.isRestElement(n)&&br.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 Em(e,t){return{...e,callbackParams:t}}function rl(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function vo(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 vm(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 Kn(e){return{file:e.file,component:e.component}}function GI(e){return e.target.kind==="node"?e.target.key:null}function YI(e){return"kind"in e}function cs(e){return!YI(e)}function cl(e,t){let n=ds.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=ds.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function ol(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=Lt(n,Ee(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function ul(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 ZI(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function QI(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 il(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function qI(e){let t=Wp(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=qc(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=eC({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=Tm(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?ss(o):!0}}}function eC(e){let t=Se(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||$t(a.path.node,t))return;let c=rC(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=iC(e.callSitePath,c.propName,e.source);if(!l.ok){o=l.reason;return}let u=tC(l.expression,c.remainingPath);if(!u){o="Cannot move prop-backed repeat child because the mapped prop path is not a portable expression";return}let d=nl(l.expressionPath,e.targetParentPath);if(!d.ok){o=d.reason??`Cannot move prop-backed repeat child because the mapped prop source is not visible at the target: ${d.bindingNames.join(", ")}`;return}n.set(`${c.range.start}:${c.range.end}`,{...c.range,text:u});return}xn(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:sC(e.source,t,[...n.values()])}}function tC(e,t){if(t.length===0)return e;let n=Tm(e);if(!n)return null;let r=ss(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=nC(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function nC(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function rC(e,t,n){let r=oC(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=fr(t,o);if(!i)return null;let s=r?.range??Se(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function oC(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!$t(n.node,t)||n.node.computed||!ge.isIdentifier(n.node.property))return null;let r=Se(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function iC(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()&&ge.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=yr(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 sC(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 Tm(e){try{let n=Am.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=ge.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&ge.isExpression(r)?r:null}catch{return null}}function aC(e){let t=Se(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||$t(s.path.node,t))return;let a=km(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let u=km(c,e.targetFile,e.targetFile);(!u||u.moduleFile!==a.moduleFile||!cC(u.importSpec,a.importSpec))&&r.add(a.localName);return}let l=n.get(a.moduleSpecifier)??[];l.some(u=>JSON.stringify(u)===JSON.stringify(a.importSpec))||l.push(a.importSpec),n.set(a.moduleSpecifier,l);return}r.add(i.node.name)};return Eo(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 cC(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 km(e,t,n){let r=lC(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=jn(t,i),a=i.startsWith(".")?cl(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=ge.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 lC(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function Im(e,t,n,r){let o=zc(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=yr(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=uC(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${fC(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function uC(e,t){return dC(e.node)?t:`(${t})`}function dC(e){return ge.isIdentifier(e)||ge.isThisExpression(e)||ge.isSuper(e)||ge.isMemberExpression(e)||ge.isOptionalMemberExpression(e)||ge.isCallExpression(e)||ge.isOptionalCallExpression(e)||ge.isBooleanLiteral(e)||ge.isNumericLiteral(e)||ge.isStringLiteral(e)||ge.isNullLiteral(e)||ge.isUnaryExpression(e)}function fC(e){return e.trim().startsWith("<")?e:`(${e})`}var pC={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 ls(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=pC[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 mC(e,t){for(let n of e.program.body){if(!ge.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>ge.isImportDefaultSpecifier(o));if(r&&ge.isImportDefaultSpecifier(r))return r.local.name}return null}function gC(e,t,n){for(let r of e.program.body){if(!ge.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>ge.isImportSpecifier(i)&&(ge.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&ge.isImportSpecifier(o))return o.local.name}return null}function Cm(e){let t=new Set;return Pt(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function Rm(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function hC(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=ul(e),o=Xe(t);if(n.exportName!=="default"){let a=o?gC(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?Rm(r,Cm(o)):r;return{localName:c,importStep:sl(e,c)}}if(!o)return{localName:r,importStep:sl(e,r)};let i=mC(o,n.source);if(i)return{localName:i};let s=Rm(r,Cm(o));return{localName:s,importStep:sl(e,s)}}function yC(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??ul(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 xC(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?bC(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function bC(e){return Object.fromEntries(Object.entries(e).filter(t=>ll(t[1])))}function ll(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(ll):typeof e=="object"?Object.values(e).every(ll):!1}function sl(e,t=ul(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 wm(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 SC(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function Sr(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function dl(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function ko(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:dl(e,t.slice(0,n)),index:r.index}}return null}function al(e,t){return e.locator?e.collectionPathMap?.[t]?dl(e.locator,e.collectionPathMap[t]):ko(e.locator)?vC(e.locator,kC(t,e.collectionIndexMap)):null:null}function EC(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:Fm(o,t)}function Fm(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=Fm(r,t);return o===void 0?void 0:{[n.name]:o}}function vC(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},dl(e,i)}return null}function kC(e,t){return t?.[e]??e}function Nm(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 IC(e,t){return CC(e.root,t.root)&&wC(e.path??[],t.path??[])}function CC(e,t){if(e.kind!==t.kind)return!1;switch(e.kind){case"binding":case"hook-state":case"named-export":return"name"in t&&e.name===t.name;case"default-export":return!0;case"expression":return"sourceRange"in t&&RC(e.sourceRange,t.sourceRange)}}function RC(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function wC(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 us=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:Sr(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:Sr(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:Sr(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:Sr(t.kind,t.params.kind)};let r=t;if(!cs(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=wm(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:Sr(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:Sr(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=GI(t);if(!n)return{ok:!1,result:{ok:!1,errorCode:"invalid-target",reason:`Operation '${t.kind}' requires a node target`}};let r=this.graph.getNode(n);return r?{ok:!0,node:r}:{ok:!1,result:{ok:!1,errorCode:"locator-miss",reason:`Target key '${n}' not found in graph`}}}planNodeAttributeOperation(t,n,r){let o=r.file,i=this.graph.getCapability(r.key);return n.params.filePath!==o?{ok:!1,errorCode:"stale-version",reason:"The className source file changed before save."}:this.buildPlan(t,n,[{order:0,file:o,type:"set-class-name-source",request:{...n.params,key:r.key}}],i)}async planSetProps(t,n,r){let o=this.graph.getCapability(r.key),i=await this.buildTypedPropertySteps({node:r,scope:n.params.scope,changes:n.params.changes,selectionRef:n.selectionRef});return i.ok?this.buildPlan(t,n,i.steps,o):Pm(i)}async planSetLinkTarget(t,n,r){if(r.tag!=="a"&&!(r.importedFrom==="next/link"&&r.exportName==="default"))return{ok:!1,errorCode:"capability-denied",reason:"Only native anchors and source-verified next/link nodes can be changed"};if(r.structuralPath.includes("#repeat:")||r.isRepeatRegion||r.isRepeatItemRoot)return{ok:!1,errorCode:"capability-denied",reason:"Link target changes are not supported inside repeat templates"};if(n.selectionRef?.instanceIndex!==void 0||(n.selectionRef?.instanceCount??1)>1)return{ok:!1,errorCode:"capability-denied",reason:"Link target changes require a single non-repeated selection"};if(n.params.changes.length>0){let o=await this.buildTypedPropertySteps({node:r,scope:"selection",changes:n.params.changes,selectionRef:n.selectionRef});if(!o.ok)return Pm(o);if(o.steps.some(i=>i.type!=="set-property-changes"||i.file!==r.file))return{ok:!1,errorCode:"capability-denied",reason:"Link descriptions must have a direct, unique source in the selected file"}}return this.buildPlan(t,n,[{type:"set-link-target",order:0,file:r.file,locator:Ee(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?fm({node:t.node,scope:t.scope,changes:t.changes,selectionRef:t.selectionRef,getPropertyState:n,getRepeatPropertyTarget:this.graph.getRepeatPropertyTarget,getFileContent:r=>this.graph.getFileContent(r),getFileVersion:r=>this.graph.getFileVersion(r),classNameSource:this.graph.getClassNameSource?.(t.node.key)??void 0}):{ok:!1,errorCode:"missing-property-state",reason:"Typed property planning requires authoritative property provenance"}}async buildStyleDraftPropertySteps(t){let{initialOrder:n,node:r,props:o,selectionRef:i}=t,s=[],a=[];for(let[c,l]of Object.entries(o)){if(l===void 0)continue;let u=await this.graph.getElementPropertyWriteTarget?.(r.key,c),d=r.attributes?.find(g=>g.name===c);if((await this.graph.getPropertyState?.(r.key,c,i))?.status==="blocked"||!u&&d?.source)return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite a derived or unresolved property '${c}'`};if(!(typeof d?.resolvedValue=="string"&&d.resolvedValue===l||d?.source===null&&d.value===l)){if(u?.kind==="external-entry")return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite readonly external property '${c}'`};if(u?.kind==="value-binding"&&u.locator){let g=u.locator;if(u.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let m=al(u,i.instanceIndex);if(!m)return{ok:!1,errorCode:"invalid-params",reason:"apply-style-draft could not resolve the selected repeat item"};g=m}s.push({order:n+s.length,file:u.file,type:"update-value",locator:g,value:l});continue}a.push({operation:"set",name:c,value:l})}}return a.length>0&&s.push({order:n+s.length,file:r.file,type:"set-property-changes",locator:Ee(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=al(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:Ee(t),segmentIndex:n,newText:r}]}}coerceTextValueForValueTarget(t,n,r,o="update-text"){let i=this.graph.getFileContent(t),s=Xe(i);if(!s)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not inspect the value source`};let a=ue(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!ZI(a.match.path))return{ok:!0,value:r};let c=QI(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=al(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=Xe(this.graph.getFileContent(t));if(!o)return!1;let i=ue(o,n);if(!i.ok)return!1;let s=i.match.path;if(s.isStringLiteral())return typeof r=="string"&&s.node.value===r;if(s.isNumericLiteral())return typeof r=="number"&&Object.is(s.node.value,r);if(s.isBooleanLiteral())return typeof r=="boolean"&&s.node.value===r;if(s.isNullLiteral())return r===null;if(s.isUnaryExpression({operator:"-"})){let a=s.get("argument");return typeof r=="number"&&!Array.isArray(a)&&a.isNumericLiteral()&&Object.is(-a.node.value,r)}return!1}planUpdateText(t,n,r,o,i){let s=this.graph.getTextProvenance?.(r.key,n.params.segmentIndex);if(s&&(s.editMode==="readonly"||s.editMode==="unsupported"))return{ok:!1,errorCode:"unsupported-operation",reason:"Text has no identity-preserving write target"};if(!o.canUpdateText)return{ok:!1,errorCode:"capability-denied",reason:"Cannot update text on this node"};let a=this.buildTextRewriteSteps(r,n.params.segmentIndex,n.params.value,i,n.selectionRef);return a.ok?this.buildPlan(t,n,a.steps,o):a}async planRemoveNode(t,n,r,o){if(!o.canRemove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot remove this node"};let i=await this.graph.getTextWriteTarget(r.key,0);if(i?.kind==="external-entry")return this.buildPlan(t,n,[{order:0,file:`external:${i.sourceId}`,type:"invoke-external-adapter",sourceType:i.sourceType,sourceId:i.sourceId,adapterId:i.adapterId,capability:"remove-node",value:{operation:"remove-node"}}],o);if(r.isRepeatItemRoot){let d=i;if(d?.kind==="value-binding"&&d.locator){let f=ko(d.locator);if(f)return this.buildPlan(t,n,[{order:0,file:d.file,type:"remove-bound-array-item",locator:f.locator,index:f.index}],o)}return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed node removal requires a writable array target"}}let s=vo(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:Ee(r),removeWhitespace:!0}],u=this.buildRemoveComponentImportStep(r);return u&&l.push({...u,order:l.length}),this.buildPlan(t,n,l,o)}buildRemoveComponentImportStep(t,n=this.graph.getFileContent(t.file)){if(!t.importedFrom||!t.exportName||!t.tag||im(n,t)>1)return null;let r=cl(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(!cs(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=vo(r,a,s!==null?this.graph.getTextProvenance?.(r.key,s)??null:null);if(c)return{ok:!1,errorCode:"unsupported-operation",reason:c};let l=await this.getUpstreamBackedDescendantReason(r);if(l)return{ok:!1,errorCode:"unsupported-operation",reason:l};let u=await this.planExternalBackedInsertChild(t,n,r,o,i,a);if(u)return u;let d=await this.planRepeatBackedInsertChild(t,n,r,o);if(d)return d;let f=this.getRepeatBackedTemplateStructureReason(r);if(f)return{ok:!1,errorCode:"unsupported-operation",reason:f};let g=$p(this.graph.getFileContent(r.file),r);if(!g.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:g.reason??"Cannot insert child into this node"};let m=ls(r,n.params.node);if(m)return{ok:!1,errorCode:"unsupported-operation",reason:m};let h=[],y=0,b=n.params.node.kind==="component-call"?hC(n.params.node,this.graph.getFileContent(r.file)):void 0,S=b?.importStep;return S&&h.push({order:y++,file:r.file,type:"add-import",moduleSpecifier:S.moduleSpecifier,imports:S.imports}),h.push({order:y++,file:r.file,type:"insert-child",parentLocator:Ee(r),node:{jsx:yC(n.params.node,b?.localName)},placement:n.params.position.relation,anchorLocator:i?Ee(i):void 0}),this.buildPlan(t,n,h,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!cs(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:xC(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(!cs(n.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};if(n.params.position.relation!=="append"&&n.params.position.relation!=="prepend")return null;let i=n.params.node;if(i.kind!=="native-tag"||i.text===void 0||!this.graph.getChildNodes)return null;let s=this.graph.getChildNodes(r.key).find(d=>d.isRepeatItemRoot&&d.tag?.toLowerCase()===i.tag.toLowerCase());if(!s)return null;let a=await this.graph.getTextWriteTarget(s.key,0);if(!a||a.kind!=="value-binding"||!a.locator)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires a writable value target"};let c=ko(a.locator);if(!c)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let l=EC(a.locator,i.text);if(l===void 0)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child could not infer an item shape from the template"};let u=n.params.position.relation==="prepend"?Nm(0,a.collectionIndexMap):Nm(a.collectionIndexMap?.length??c.index+1,a.collectionIndexMap);return this.buildPlan(t,n,[{order:0,file:a.file,type:"insert-bound-array-item",locator:c.locator,index:u,value:l}],o)}async getUpstreamBackedDescendantReason(t){if(!this.graph.getChildNodes)return null;let n=[...this.graph.getChildNodes(t.key)];for(;n.length>0;){let r=n.shift();if(!r)continue;let o=this.graph.getEditableTextSegmentIndex(r.key),i=o!==null?await this.graph.getTextWriteTarget(r.key,o):null,s=vo(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 xr(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:")||hm(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&&xr(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=Xe(c);if(!l)return null;let u=Et(l,r),d=Et(l,o);if(!u||!d)return null;let f=Kt(c,u),g=Kt(c,d);if(!So(f,g))return null;if(a&&(s==="before"||s==="after")){let h=Et(l,a),y=h?Kt(c,h):null;if(!So(f,y))return null}if(os(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let m=Qc(c,r,o);return m.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:Ee(r),targetParentLocator:Ee(o),placement:s,anchorLocator:a?Ee(a):void 0,selectionContext:Kn(o)}],i):{ok:!1,errorCode:"unsupported-operation",reason:m.reason??`Cannot move node because it depends on bindings outside the target scope: ${m.bindingNames.join(", ")}`}}planRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&xr(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=Xe(c);if(!l)return null;let u=Et(l,r),d=Et(l,o);if(!u||!d)return null;let f=Kt(c,u);if(!f)return null;let g=Kt(c,d);if(So(f,g))return null;if(g&&!mm(g,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")){let v=Yc(c,l,a);if(g&&!So(g,v)||!g&&v)return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child relative to a repeat-template anchor outside the target scope"}}if(r.tag&&r.tag.toLowerCase()===r.tag){let v=ls(o,{kind:"native-tag",tag:r.tag});if(v)return{ok:!1,errorCode:"unsupported-operation",reason:v}}let m=ol(this.graph,r);if(!m)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(os(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let h=Im(c,u,d,m);for(let v of h.conditionPaths){let C=tl(v,d,f);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 y=el(u,d,f,{preserveConditionalBoundary:h.conditionPaths.length>0});if(!y.ok)return{ok:!1,errorCode:"unsupported-operation",reason:y.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${y.bindingNames.join(", ")}`};let b=bm(f,d);if(!b.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its callback parameters depend on bindings outside the target scope: ${b.bindingNames.join(", ")}`};let S=f;if(r.component!==o.component){let v=qI({source:c,ast:l,sourceContext:f,sourceNode:r,targetParent:o,targetParentPath:d});if(!v.ok)return{ok:!1,errorCode:"unsupported-operation",reason:v.reason};S=v.context}else{let v=nl(f.collectionPath,d);if(!v.ok)return{ok:!1,errorCode:"unsupported-operation",reason:v.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${v.bindingNames.join(", ")}`}}return this.buildPlan(t,n,[{order:0,file:r.file,type:"move-repeat-template-child",locator:Ee(r),targetParentLocator:Ee(o),placement:s,anchorLocator:a?Ee(a):void 0,repeatExpression:rl(S,h.sourceJsx),selectionContext:Kn(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&xr(this.graph.getFileContent(r.file),r)||r.file===o.file)return null;let c=this.graph.getFileContent(r.file),l=this.graph.getFileContent(o.file),u=Xe(c),d=Xe(l);if(!u||!d)return null;let f=cm({knownSourceFiles:this.graph.getKnownSourceFiles?.(),routeEntryFiles:this.graph.getRouteEntryFiles?.(),sourceAst:u,sourceFile:r.file,targetFile:o.file,sourceComponent:r.component,targetComponent:o.component});if(!f.ok)return{ok:!1,errorCode:"unsupported-operation",reason:f.reason};let g=Et(u,r),m=Et(d,o);if(!g||!m)return null;let h=qc(f.callSitePath,m);if(!h.ok)return{ok:!1,errorCode:"unsupported-operation",reason:h.reason};let y=Kt(c,g);if(!y)return null;if(Kt(l,m))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")&&Yc(l,d,a))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child relative to a repeat-template anchor outside the target scope"};if(r.tag&&r.tag.toLowerCase()===r.tag){let T=ls(o,{kind:"native-tag",tag:r.tag});if(T)return{ok:!1,errorCode:"unsupported-operation",reason:T}}let S=ol(this.graph,r);if(!S)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(os(g,m))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let v=Im(c,g,m,S);for(let T of v.conditionPaths){let L=tl(T,m,y);if(!L.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${L.bindingNames.join(", ")}`}}let C=el(g,m,y,{preserveConditionalBoundary:v.conditionPaths.length>0});if(!C.ok)return{ok:!1,errorCode:"unsupported-operation",reason:C.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${C.bindingNames.join(", ")}`};let P=aC({sourceFile:r.file,targetFile:o.file,sourceContext:y,targetParentPath:m});if(!P.ok)return{ok:!1,errorCode:"unsupported-operation",reason:P.reason};let F=Sm(y);if(!F.ok)return{ok:!1,errorCode:"unsupported-operation",reason:F.reason};let R=Em(y,F.callbackParams),N=[{order:0,file:r.file,type:"remove-node",locator:Ee(r),removeWhitespace:!0}];for(let T of P.imports)N.push({order:N.length,file:o.file,type:"add-import",moduleSpecifier:T.moduleSpecifier,imports:T.imports});return N.push({order:N.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:Ee(o),expression:rl(R,v.sourceJsx),placement:s,anchorLocator:a?Ee(a):void 0,selectionContext:Kn(o)}),this.buildPlan(t,n,N,i)}async planMoveNode(t,n,r,o){if(!o.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};if("kind"in n.params.target&&n.params.target.kind==="source-sibling"){let v=n.params.target,C=this.graph.getNode(v.anchorKey);if(!C||r.file!==C.file||r.component!==C.component)return{ok:!1,errorCode:"locator-miss",reason:"Source sibling move requires a sibling in the same component file"};let P=this.graph.getFileVersion(r.file);if(n.documentVersion!==P)return{ok:!1,errorCode:"stale-version",reason:`Document version ${n.documentVersion} is stale or otherwise does not match source sibling file version (current: ${P})`};let F=this.graph.getFileContent(r.file),R=Xe(F),N=R?Et(R,r):null,T=R?Et(R,C):null,L=N?.parentPath,q=T?.parentPath;if(!N||!T||!L||!q||L.node!==q.node||!L.isJSXFragment()&&!(L.isJSXElement()&&Oe(L)))return{ok:!1,errorCode:"unsupported-operation",reason:"Source sibling move requires two direct children of the same transparent Fragment"};let W=L.node.loc;return W?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:Ee(r),targetParentLocator:{kind:"jsx-node",strategy:"source-range",sourceRange:{startLine:W.start.line,startColumn:W.start.column,endLine:W.end.line,endColumn:W.end.column}},placement:v.relation,anchorLocator:Ee(C),selectionContext:Kn(r)}],o):{ok:!1,errorCode:"locator-miss",reason:"Source Fragment has no stable source range"}}let i=wm(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(SC(s.key,r.key,this.graph))return{ok:!1,errorCode:"capability-denied",reason:"Cannot move node into its own subtree"};if(r.isRepeatRegion&&s.isBoundary)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move repeat-region node across boundary"};if(!this.graph.getCapability(s.key).canInsertChild)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move node into this parent"};let c=await this.graph.getTextWriteTarget(r.key,0);if(c?.kind==="external-entry"){let v=n.params.target.relation,C=i.anchorNode&&(v==="before"||v==="after")?await this.graph.getTextWriteTarget(i.anchorNode.key,0):null;return this.buildPlan(t,n,[{order:0,file:`external:${c.sourceId}`,type:"invoke-external-adapter",sourceType:c.sourceType,sourceId:c.sourceId,adapterId:c.adapterId,capability:"move-node",value:{operation:"move-node",relation:v,anchorSourceId:C?.kind==="external-entry"?C.sourceId:null,parentKey:"parentKey"in n.params.target?n.params.target.parentKey:null}}],o)}let l=r.file!==s.file,u=n.params.target.relation,d=i.anchorNode,f=this.graph.getTextProvenance?.(r.key,0)??null,g=vo(r,c,f);if(g&&!il(g)&&!vm(r,s,c,f))return{ok:!1,errorCode:"unsupported-operation",reason:g};if(r.isRepeatItemRoot&&d?.isRepeatItemRoot&&r.repeatOwnerKey&&r.repeatOwnerKey===d.repeatOwnerKey&&(u==="before"||u==="after")){let v=c,C=await this.graph.getTextWriteTarget(d.key,0);if(v?.kind==="value-binding"&&C?.kind==="value-binding"&&v.locator&&C.locator){let P=ko(v.locator),F=ko(C.locator);if(P&&F&&v.file===C.file&&IC(P.locator,F.locator)){let R=P.index,N=F.index,T=u==="before"?N-(R<N?1:0):N+(R<N?0:1);return this.buildPlan(t,n,[{order:0,file:v.file,type:"move-array-item",locator:P.locator,fromIndex:R,toIndex:T}],o)}}}if(r.isRepeatItemRoot&&xr(this.graph.getFileContent(r.file),r))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed item outside its collection"};let m=this.getRepeatBackedTemplateStructureReason(r),h=il(g)?g:m;if(h&&il(h)){let v=this.planRepeatTemplateInternalMove(t,n,r,s,o,u,d);if(v)return v;let C=this.planRepeatTemplateHoistMove(t,n,r,s,o,u,d);if(C)return C;let P=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,u,d);return P||{ok:!1,errorCode:"unsupported-operation",reason:h}}if(m)return{ok:!1,errorCode:"unsupported-operation",reason:m};let y=await this.getUpstreamBackedDescendantReason(r);if(y)return{ok:!1,errorCode:"unsupported-operation",reason:y};if(r.tag&&r.tag.toLowerCase()===r.tag){let v=ls(s,{kind:"native-tag",tag:r.tag});if(v)return{ok:!1,errorCode:"unsupported-operation",reason:v}}if(l)return this.planCrossFileMove(t,n,r,s,o,u,d);let b=Qc(this.graph.getFileContent(r.file),r,s);if(!b.ok)return{ok:!1,errorCode:"unsupported-operation",reason:b.reason??`Cannot move node because it depends on bindings outside the target scope: ${b.bindingNames.join(", ")}`};let S=[{order:0,file:r.file,type:"move-node",locator:Ee(r),targetParentLocator:Ee(s),placement:u,anchorLocator:d?Ee(d):void 0,selectionContext:Kn(s)}];return this.buildPlan(t,n,S,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,u=this.graph.getFileContent(r.file),d=ol(this.graph,r)??`<${r.component} />`,f=Vp(u,r);if(!f.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:f.reason??"Cannot move subtree across files"};if(c.push({order:l++,file:r.file,type:"remove-node",locator:Ee(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let m=r.tag??r.component,y={moduleSpecifier:cl(o.file,r.importedFrom),imports:r.exportName==="default"?[{kind:"default",local:m}]:[{kind:"named",imported:r.exportName,local:m===r.exportName?void 0:m}]};c.push({order:l++,file:o.file,type:"add-import",moduleSpecifier:y.moduleSpecifier,imports:y.imports}),c.push({order:l++,file:o.file,type:"insert-child",parentLocator:Ee(o),node:{jsx:d},placement:s,anchorLocator:a?Ee(a):void 0,selectionContext:Kn(o)})}else c.push({order:l++,file:o.file,type:"insert-child",parentLocator:Ee(o),node:{jsx:d},placement:s,anchorLocator:a?Ee(a):void 0,selectionContext:Kn(o)});let g=this.buildRemoveComponentImportStep(r,u);return g&&c.push({...g,order:l++}),this.buildPlan(t,n,c,i)}buildPlan(t,n,r,o){let s=[...new Set(r.map(a=>a.file))].map(a=>({file:a,content:this.graph.getFileContent(a),version:this.graph.getFileVersion(a),exists:!0,sha256:Re(this.graph.getFileContent(a))}));return{ok:!0,plan:{operationId:t,kind:n.kind,target:n.target,documentVersion:n.documentVersion,steps:r,preSnapshots:s,validatedCapability:o}}}};function Pm(e){return{ok:!1,errorCode:e.errorCode==="readonly-property"?"capability-denied":e.errorCode==="missing-property-state"||e.errorCode==="repeat-target-failed"||e.errorCode==="unsupported-binding"?"unsupported-operation":"invalid-params",reason:e.reason}}import yl from"@babel/generator";import{parse as KC}from"@babel/parser";import*as k from"@babel/types";import*as Ut from"@babel/types";import fl from"@babel/generator";import*as Ie from"@babel/types";var NC=typeof fl=="function"?fl:fl.default,PC=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,AC=/^((?:https?:)?\/\/)[^/@\s]+@/i,TC=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function Mm(e,t){let n=At(e.callee);if(!n)return null;if(n==="fetch")return pl(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(_m(r))return pl(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(_m(r))return pl(e.arguments[0],r,t,["ky client contract"])}return null}function pl(e,t,n,r){if(!e||Ie.isSpreadElement(e)||Ie.isJSXNamespacedName(e))return OC(t,n,r,"missing url argument");let o=Io(e);return{sourceKind:MC(o),...o?{endpointPattern:o}:{},method:t,confidence:o?"exact":"partial",evidence:[{file:n.file,reason:[...r,o?"endpoint pattern resolved":"endpoint pattern unresolved"].join("; ")}]}}function Io(e){if(Ie.isStringLiteral(e))return Er(e.value);if(Ie.isTemplateLiteral(e))return Er(FC(e));if(Ie.isBinaryExpression(e)&&e.operator==="+"){let t=Io(e.left),n=Io(e.right);return!t&&!n?void 0:Er(`${t??ml(e.left)}${n??ml(e.right)}`)}if(Ie.isMemberExpression(e)){let t=Om(e);if(t)return`env:${t}`}if(!(Ie.isCallExpression(e)&&At(e.callee)==="new URL")){if(Ie.isNewExpression(e)&&Ie.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!Ie.isSpreadElement(t)?Io(t):void 0,o=n&&!Ie.isSpreadElement(n)?Io(n):void 0;return o&&r?Er(`${o} + ${r}`):r??o}if(Ie.isIdentifier(e))return`:${e.name}`}}function FC(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+=ml(r))}return t}function ml(e){if(Ie.isIdentifier(e))return`:${e.name}`;if(Ie.isMemberExpression(e)){let t=Om(e);if(t)return`env:${t}`}return`:${_C(e)}`}function _C(e){return NC(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function Er(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(AC,"$1<redacted>@").replace(TC,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?PC.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function MC(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 OC(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function _m(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function Om(e){return!Ie.isMemberExpression(e.object)||!Ie.isIdentifier(e.object.object,{name:"process"})||!LC(e.object.property,"env")?null:Ie.isIdentifier(e.property)?e.property.name:Ie.isStringLiteral(e.property)?e.property.value:null}function LC(e,t){return Ie.isIdentifier(e)&&e.name===t}function At(e){if(Ie.isIdentifier(e))return e.name;if(Ie.isMemberExpression(e)){let t=At(e.object),n=Ie.isIdentifier(e.property)?e.property.name:Ie.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var DC=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),BC=new Set(["getConfig","submit"]);function Lm(e,t){let n=jC(At(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!DC.has(i))return null;let s=gl(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(!BC.has(i))return null;let s=gl(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=gl(e,0)??$C(e,0,"path")??"/cms/:path",s=VC(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 jC(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 Dm(e,t){let n=At(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 Bm(e){let t=At(e.callee);return typeof t=="string"&&t.startsWith("cms.field.")}function gl(e,t){let n=e.arguments[t];return Ut.isStringLiteral(n)?n.value:null}function $C(e,t,n){let r=e.arguments[t];if(!Ut.isObjectExpression(r))return null;for(let o of r.properties)if(Ut.isObjectProperty(o)&&!o.computed&&(Ut.isIdentifier(o.key)&&o.key.name===n||Ut.isStringLiteral(o.key)&&o.key.value===n)&&Ut.isStringLiteral(o.value))return o.value.value;return null}function VC(e){return/^\/collections\/([^/]+)(?:\/|$)/.exec(e)?.[1]??null}function jm(e=4096){if(!Number.isSafeInteger(e)||e<1)throw new RangeError("Re-export relation capacity must be positive.");let t=new Map,n=new Set,r=o=>{let i=t.get(o.fromFile),s=i?.get(o.exportName),a=s?.get(o.targetFile);a?.get(o.maxImportDepth)===o&&(a.delete(o.maxImportDepth),a.size===0&&s.delete(o.targetFile),s.size===0&&i.delete(o.exportName),i.size===0&&t.delete(o.fromFile),n.delete(o))};return{resolve(o,i){let{fromFile:s,exportName:a,targetFile:c,maxImportDepth:l}=o,u=t.get(s)?.get(a)?.get(c)?.get(l);if(u)return u.pending;let d=i();n.size>=e&&r(n.values().next().value);let f={fromFile:s,exportName:a,targetFile:c,maxImportDepth:l,pending:d},g=t.get(s)??new Map,m=g.get(a)??new Map,h=m.get(c)??new Map;return h.set(l,f),m.set(c,h),g.set(a,m),t.set(s,g),n.add(f),d.catch(()=>{r(f)}),d}}}import*as K from"@babel/types";function vr(e,t,n=new Set){if(n.has(e))return;let r=new Set(n).add(e);if(K.isBooleanLiteral(e))return e.value;if(K.isUnaryExpression(e,{operator:"!"})){let c=vr(e.argument,t,r);return c===void 0?void 0:!c}if(K.isLogicalExpression(e)){let c=vr(e.left,t,r),l=vr(e.right,t,r);if(e.operator==="&&")return c===!1||l===!1?!1:c===!0?l:void 0;if(e.operator==="||")return c===!0||l===!0?!0:c===!1?l:void 0}if(!K.isCallExpression(e)||!K.isIdentifier(e.callee))return;let o=t.imports.get(e.callee.name);if(o?.importedName==="isProductionBuildPhase"&&/(?:^|\/)lib\/cms\/build-sample(?:\.[jt]s)?$/.test(o.source))return!1;let i=t.functions.get(e.callee.name);if(!i||n.has(i))return;let s=K.isExpression(i.body)?i.body:i.body.body.length===1&&K.isReturnStatement(i.body.body[0])?i.body.body[0].argument:null;if(!s||!K.isExpression(s))return;let a=i.params.flatMap(c=>K.isIdentifier(c)?[c.name]:[]);return vr(s,{imports:new Map([...t.imports].filter(([c])=>!a.includes(c))),functions:new Map([...t.functions].filter(([c])=>!a.includes(c)))},r.add(i))}function Vm(e){return K.isAwaitExpression(e)||K.isTSAsExpression(e)||K.isTSNonNullExpression(e)||K.isParenthesizedExpression(e)?Vm(e.type==="AwaitExpression"?e.argument:e.expression):e}function $m(e){return K.isMemberExpression(e)&&!e.computed&&K.isIdentifier(e.object)&&K.isIdentifier(e.property,{name:"id"})?e.object.name:void 0}function hl(e,t){if(K.isLogicalExpression(e,{operator:"&&"}))return hl(e.left,t)??hl(e.right,t);if(!K.isBinaryExpression(e,{operator:"==="}))return;let n=$m(e.left),r=$m(e.right);return n===t&&r!==t?r:r===t&&n!==t?n:void 0}function Km(e){return K.isReturnStatement(e)?K.isNullLiteral(e.argument):K.isThrowStatement(e)?!0:K.isBlockStatement(e)&&e.body.length===1&&Km(e.body[0])}async function Um(e,t,n){let r=new Map;if(!K.isBlockStatement(e.body))return r;let o=new Map,i=new Set,s=new Set;for(let a of e.body.body){let c=!1;if(K.traverseFast(a,d=>{d===t&&(c=!0)}),c)break;let l=d=>{if(!K.isFunction(d)){if(K.isAssignmentExpression(d)||K.isUpdateExpression(d)){let f=K.isAssignmentExpression(d)?d.left:d.argument;for(;K.isMemberExpression(f);)f=f.object;K.isIdentifier(f)&&s.add(f.name)}for(let f of K.VISITOR_KEYS[d.type]??[]){let g=d[f];for(let m of Array.isArray(g)?g:[g])K.isNode(m)&&l(m)}}};if(l(a),K.isVariableDeclaration(a,{kind:"const"}))for(let d of a.declarations){if(!K.isIdentifier(d.id)||!K.isExpression(d.init))continue;let f=Vm(d.init);if(!K.isCallExpression(f)||!K.isMemberExpression(f.callee)||f.callee.computed||!K.isIdentifier(f.callee.property,{name:"find"}))continue;let g=f.arguments[0];if(!(K.isArrowFunctionExpression(g)||K.isFunctionExpression(g))||!K.isIdentifier(g.params[0]))continue;let m=K.isExpression(g.body)?g.body:g.body.body.length===1&&K.isReturnStatement(g.body.body[0])?g.body.body[0].argument:null;if(!m||!K.isExpression(m))continue;let h=hl(m,g.params[0].name);if(!h)continue;let[y,b]=await Promise.all([n(f.callee.object),n(K.identifier(h))]);y?.sourceKind==="vcp-cms-collection"&&y.collection&&(y.operation==="listStrict"||y.operation==="list")&&b?.sourceKind==="vcp-cms-collection"&&(b.operation==="getByUrlStrict"||b.operation==="getByUrl")&&o.set(d.id.name,{record:h,collection:y.collection})}if(!K.isIfStatement(a)||!K.isUnaryExpression(a.test,{operator:"!"})||!K.isIdentifier(a.test.argument)||!Km(a.consequent))continue;let u=o.get(a.test.argument.name);u&&(r.has(u.record)&&r.get(u.record)!==u.collection&&i.add(u.record),r.set(u.record,u.collection))}for(let a of[...i,...s])r.delete(a);return r}var wL=typeof yl=="function"?yl:yl.default,Zm=new WeakMap;function Qm(e){let t=new Map;return Zm.set(t,new Map([...e].map(n=>[n.file,n]))),t}var UC={maxFunctionDepth:8,maxImportDepth:6},JC=new Set(["src","href","alt","poster","content","title","aria-label"]),Jm=new WeakMap;function XC(e,t,n){let r=Jm.get(t.fileCache);r||(r=new WeakMap,Jm.set(t.fileCache,r));let o=r.get(e);if(!o){o={imported:[],local:new Map};let u=0;for(let d of e.elements.values()){let f={element:d,order:u++};d.importedFrom&&d.exportName&&o.imported.push(f);let g=o.local.get(d.sourceFile);g||(g=new Map,o.local.set(d.sourceFile,g));let m=g.get(d.tag)??[];m.push(f),g.set(d.tag,m)}r.set(e,o)}let i=o.local.get(t.file)?.get(n)??[],s=o.imported,a=[],c=0,l=0;for(;c<s.length||l<i.length;){let u=s[c],d=i[l];u&&(!d||u.order<d.order)?(a.push(u.element),c++):d&&(!u||d.order<u.order)?(a.push(d.element),l++):(a.push(u.element),c++,l++)}return a}async function qm(e){let t=e.element.attributes?.find(u=>u.name==="data-cms-collection"),n=t?.resolution?.status==="resolved"?t.resolution.value:t?.syntaxKind==="literal"?t.value:void 0,r=typeof n=="string"?n.trim():"",o=r?[{sourceKind:"vcp-cms-collection",sourceType:"cms-field",collection:r,targetKind:"attribute",targetName:"data-cms-collection",confidence:"exact",readonly:!0,evidence:[{file:e.file,reason:"Explicit CMS collection binding"}]}]:[];if(!e.element.textSegments.some(u=>u.source)&&!(e.element.attributes??[]).some(u=>(u.source||u.syntaxKind==="expression"&&u.resolution?.status!=="resolved")&&zm(u,e.element))&&!e.graph.regions.some(u=>u.ownerKey===e.element.identity.key&&(u.kind==="repeat-region"||u.kind==="conditional-region")))return{hasDynamicData:o.length>0,bindings:o};let i=e.fileCache??new Map,s=Cl(e.file,e.source,i),a={file:e.file,analysis:s,readFile:e.readFile,exists:e.exists,fileCache:i,options:{...UC,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,paramArguments:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:dg(s,e.element.componentName),scopeFunction:Rl(s,e.element.componentName)};await eg(e.element.componentName,e.graph,a);let c=[...o];c.push(...await GC(e.element,e.graph,a),...await YC(e.element,e.graph,a));for(let u of e.element.textSegments){let d=await ZC(u,e.element,e.graph,a);d&&c.push(xs(d,"text","children"))}for(let u of e.element.attributes??[]){let d=zm(u,e.element);if(!d)continue;let f=await rg(u.source,e.element,e.graph,a);if(!f&&u.syntaxKind==="expression"){let m=s.jsxElementsByRange.get(Sl(e.element.sourceRange))?.openingElement.attributes.find(h=>k.isJSXAttribute(h)&&k.isJSXIdentifier(h.name,{name:u.name}));k.isJSXExpressionContainer(m?.value)&&k.isExpression(m.value.expression)&&(f=await _e(m.value.expression,a))}f&&c.push(xs(f,d,u.name))}let l=dR(c).sort(lg);return{hasDynamicData:l.length>0,bindings:l}}async function eg(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 XC(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 zC(l.importedFrom,l.exportName,n.file,n))&&s.push(l)}if(s.length===0)return;let a=new Map;for(let l of s){let u=`${n.file}#${e}<-${l.identity.key}`;if(!n.resolvingComponentProps.has(u)){n.resolvingComponentProps.add(u);try{let d=await ng(l.sourceFile,n);if(!d)continue;let f=Rr(d,n,{importDepth:n.importDepth+1});f.paramSources.clear(),f.scopeVariables=dg(d,l.componentName),f.scopeFunction=Rl(d,l.componentName),f.lexicalContext=void 0,await eg(l.componentName,t,f);let g=await WC(l,t,f);for(let[m,h]of g){if(!h)continue;let y=a.get(m)??[];y.push(h),a.set(m,y)}}finally{n.resolvingComponentProps.delete(u)}}}let c=new Map;for(let[l,u]of a){let d=Il(u);d.length===1&&c.set(l,d[0])}HC(o,c,n)}var Xm=new WeakMap;function zC(e,t,n,r){let o=Xm.get(r.fileCache);return o||(o=jm(),Xm.set(r.fileCache,o)),o.resolve({fromFile:e,exportName:t,targetFile:n,maxImportDepth:r.options.maxImportDepth},()=>tg(e,t,n,r))}async function tg(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 ng(e,r))?.imports.get(t);if(!s||!It(s.source))return!1;let a=await mg(e,s.source,r.exists);return a?a===n?!0:tg(a,s.importedName,n,r,o):!1}async function WC(e,t,n){let r=new Map,o=n.analysis.jsxElementsByRange.get(Sl(e.sourceRange));if(o)for(let s of o.openingElement.attributes)!k.isJSXAttribute(s)||!k.isJSXIdentifier(s.name)||!k.isJSXExpressionContainer(s.value)||!k.isExpression(s.value.expression)||r.set(s.name.name,s.value.expression);let i=new Map;for(let[s,a]of r){let c=await og(e.attributes?.find(l=>l.name===s)?.source??null,e,t,n)??await _e(a,n);c&&i.set(s,c)}return i}function Sl(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}async function ng(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 HC(e,t,n){if(k.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,ys(Object.fromEntries(t),n.file));return}if(k.isObjectPattern(e))for(let r of e.properties){if(!k.isObjectProperty(r)||r.computed||!k.isIdentifier(r.key))continue;let o=t.get(r.key.name);if(!o)continue;let i=k.isAssignmentPattern(r.value)?r.value.left:r.value;k.isIdentifier(i)&&n.paramSources.set(i.name,We(o))}}function zm(e,t){return e.name==="dangerouslySetInnerHTML"?"richtext":JC.has(e.name)?"attribute":t.importedFrom||/^[A-Z]/.test(t.tag)?"component-prop":null}async function GC(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 bs(i.collectionSource,n);s&&r.push(xs(Sn(s),"repeat-region",i.collectionExpression))}return r}async function YC(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 bs(i.conditionSource,n);s&&r.push(xs(Sn(s),"conditional-region",i.conditionExpression))}return r}async function ZC(e,t,n,r){return rg(e.source,t,n,r)}async function rg(e,t,n,r){let o=await og(e,t,n,r);return o||bs(e,r)}async function og(e,t,n,r){if(!e)return null;let o=QC(e.base,t,n);if(!o)return null;let i=await bs(o.collectionSource,r);return i?Ro(i,e.path,!0):null}function QC(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 bs(e,t){if(!e)return null;let n=await El(e.base,t);return n?Ro(n,e.path,!1):null}async function El(e,t){let n=t.paramSources.get(e);if(n)return We(n);if(t.variableCache.has(e))return fR(t.variableCache.get(e)??null);let r=Ir(e,t);if(r&&r!==t)return El(e,r);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let o=await eR(e,t);if(o)return t.variableCache.set(e,We(o)),t.resolvingVariables.delete(e),o;let i=t.scopeVariables?.has(e),s=i?t.scopeVariables.get(e):r?null:t.analysis.variables.get(e);if(s){let c=k.isArrayExpression(s)&&s.elements.length===0?await qC(e,t):await _e(s,t),l=t.recordCollections?.get(e);return c?.sourceKind==="vcp-cms-collection"&&!c.collection&&l&&(c.operation==="getByUrlStrict"||c.operation==="getByUrl")&&(c={...c,collection:l,confidence:"safe-derived",evidence:[...c.evidence,{file:t.file,symbol:e,reason:"record id matched CMS collection and missing membership exits before return"}]}),t.variableCache.set(e,c?We(c):null),t.resolvingVariables.delete(e),c}if(i||r)return t.resolvingVariables.delete(e),t.variableCache.set(e,null),null;let a=t.analysis.imports.get(e);if(a&&t.importDepth<t.options.maxImportDepth){let c=await fg(a,t);if(c){let l=Rr(c,t,{importDepth:t.importDepth+1}),u=pg(a,c);if(u){let g=(await Un(u,[],l)).returnSource;return t.variableCache.set(e,g?We(g):null),t.resolvingVariables.delete(e),g}let d=c.variables.get(a.importedName);if(d){let f=await _e(d,l);return t.variableCache.set(e,f?We(f):null),t.resolvingVariables.delete(e),f}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}function Ir(e,t){return t.scopeVariables?.has(e)||t.scopeFunction?.params.some(n=>En(n).includes(e))?t:t.lexicalContext?Ir(e,t.lexicalContext):void 0}function fs(e,t,n=new Set){if(k.isIdentifier(e)){let s=Ir(e.name,t);if(s&&s!==t)return fs(e,s,n)}if(n.has(e))return null;if(n.add(e),k.isStringLiteral(e))return e.value;if(!k.isIdentifier(e))return null;let r=Ir(e.name,t),o=t.paramArguments.get(e.name);if(o)return fs(o.expression,o.context,n);let i=t.scopeVariables?.has(e.name)?t.scopeVariables.get(e.name):r?null:t.analysis.variables.get(e.name);return i?fs(i,t,n):null}function bn(e,t,n=new Set){if(n.has(e))return null;let r=new Set(n).add(e);if(k.isStringLiteral(e))return e.value;if(k.isIdentifier(e)){if(/token|secret|password|authorization|cookie|credential/i.test(e.name))return":redacted";let o=Ir(e.name,t),i=o??t,s=i.paramArguments.get(e.name),a=i.scopeVariables?.has(e.name)?i.scopeVariables.get(e.name):o?null:i.analysis.variables.get(e.name);return(s?bn(s.expression,s.context,r):a?bn(a,i,r):null)??`:${e.name}`}if(k.isBinaryExpression(e,{operator:"+"})){let o=bn(e.left,t,r),i=bn(e.right,t,r);return o!==null&&i!==null?o+i:null}if(k.isTemplateLiteral(e)){let o=e.quasis[0]?.value.cooked??"";for(let[i,s]of e.expressions.entries()){if(!k.isExpression(s))return null;o+=(bn(s,t,r)??":param")+(e.quasis[i+1]?.value.cooked??"")}return o}if(k.isCallExpression(e)&&k.isIdentifier(e.callee)&&["encodeURIComponent","decodeURIComponent"].includes(e.callee.name)&&k.isExpression(e.arguments[0])){let o=bn(e.arguments[0],t,r);if(o===null||o.startsWith(":"))return o;try{return e.callee.name==="encodeURIComponent"?encodeURIComponent(o):decodeURIComponent(o)}catch{return null}}return k.isTSAsExpression(e)||k.isTSNonNullExpression(e)||k.isParenthesizedExpression(e)?bn(e.expression,t,r):null}async function qC(e,t){let n=t.scopeFunction;if(!n)return null;let r=[],o=!1,i=0,s=u=>{let d=!1;return k.traverseFast(u,f=>{k.isIdentifier(f,{name:e})&&(d=!0)}),d},a=u=>{let d=u;for(;k.isMemberExpression(d);)d=d.object;return k.isIdentifier(d,{name:e})},c=async(u,d)=>{if(!o){if(k.isFunction(u)){s(u)&&(o=!0);return}if(k.isVariableDeclarator(u)&&(En(u.id).includes(e)&&i++,u.init&&s(u.init)&&(o=!0)),(k.isAssignmentExpression(u)||k.isUpdateExpression(u))&&a(k.isAssignmentExpression(u)?u.left:u.argument)){o=!0;return}if(k.isUnaryExpression(u,{operator:"delete"})&&a(u.argument)){o=!0;return}if(k.isCallExpression(u)){if(k.isMemberExpression(u.callee)&&k.isIdentifier(u.callee.object,{name:e})){if(!k.isIdentifier(u.callee.property,{name:"push"})||u.callee.computed||!u.arguments.length){o=!0;return}for(let f of u.arguments){let g=k.isSpreadElement(f)?f.argument:f,m=k.isExpression(g)?await _e(g,d):null;m?r.push(xl(m)):o=!0}return}if(u.arguments.some(f=>s(f))){o=!0;return}}if(k.isForOfStatement(u)){let f=await _e(u.right,d),g=Rr(d.analysis,d),m=k.isVariableDeclaration(u.left)?u.left.declarations[0]?.id:u.left;f&&m&&gs(m,xl(f),g),await c(u.body,g);return}for(let f of k.VISITOR_KEYS[u.type]??[]){let g=u[f];for(let m of Array.isArray(g)?g:[g])k.isNode(m)&&await c(m,d)}}};await c(n.body,t);let l=Il(r);return!o&&i===1&&l.length===1?Sn(l[0]):null}async function eR(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 _e(o,t);if(i)return i}return null}async function _e(e,t){if(k.isIdentifier(e))return El(e.name,t);if(k.isMemberExpression(e)||k.isOptionalMemberExpression(e)){let n=k.isMemberExpression(e)?Dm(e,{file:t.file}):null;if(n)return ag(n);let r=await tR(e,t);if(!r)return null;let o=uR(e);return Ro(r,o,!1)}if(k.isAwaitExpression(e))return k.isExpression(e.argument)?_e(e.argument,t):null;if((k.isCallExpression(e)||k.isOptionalCallExpression(e))&&(k.isMemberExpression(e.callee)||k.isOptionalMemberExpression(e.callee))&&!e.callee.computed&&k.isIdentifier(e.callee.property)&&["trim","trimStart","trimEnd"].includes(e.callee.property.name)&&e.arguments.length===0&&k.isExpression(e.callee.object))return kr(await _e(e.callee.object,t));if(k.isCallExpression(e))return ig(e,t);if(k.isObjectExpression(e)){let n=await sg(e,t);return Object.keys(n).length>0?ys(n,t.file):null}if(k.isArrayExpression(e)){let n={};for(let[r,o]of e.elements.entries()){if(!k.isExpression(o))continue;let i=await _e(o,t);i&&(n[String(r)]=i)}return Object.keys(n).length?ys(n,t.file):null}if(k.isConditionalExpression(e)){let n=await _e(e.consequent,t),r=await _e(e.alternate,t);return kr(Hm(n,r))}if(k.isLogicalExpression(e)){let n=await _e(e.left,t),r=await _e(e.right,t);return kr(Hm(n,r))}return k.isTSAsExpression(e)||k.isTSSatisfiesExpression(e)||k.isTSNonNullExpression(e)||k.isTypeCastExpression(e)||k.isParenthesizedExpression(e)?_e(e.expression,t):null}async function tR(e,t){let n=e;for(;k.isMemberExpression(n)||k.isOptionalMemberExpression(n);)n=n.object;return k.isExpression(n)?_e(n,t):null}async function ig(e,t){let n=e.arguments[0],r=k.isExpression(n)?fs(n,t):null,o=Lm(r!==null&&!k.isStringLiteral(n)?{...e,arguments:[k.stringLiteral(r),...e.arguments.slice(1)]}:e,{file:t.file,imports:t.analysis.imports});if(o){if((o.operation==="getByUrl"||o.operation==="getByUrlStrict")&&k.isExpression(n)){let g=bn(n,t);g?.startsWith("/")&&(o.endpointPattern=Er(g))}return ag(o)}if(At(e.callee)==="Promise.all"&&k.isArrayExpression(n))return _e(n,t);if(Bm(e)){let g=e.arguments[0];if(g&&k.isExpression(g))return kr(await _e(g,t))}let i=await nR(e,t);if(i)return i;let s=Mm(e,{file:t.file});if(s)return{sourceKind:s.sourceKind,sourceType:"api-field",endpointPattern:s.endpointPattern,valuePath:s.valuePath,confidence:s.confidence,readonly:!0,evidence:s.evidence};let a=await iR(e,t);if(a)return a;let c=await sR(e,t);if(c)return c;let l=await aR(e,t);if(l)return l;let u=await cR(e,t);if(u)return u;let d=[];for(let g of e.arguments)if(k.isExpression(g)){let m=await _e(g,t);m&&d.push(m)}let f=Il(d);return f.length===1?kr(f[0]):null}async function nR(e,t){let n=At(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=oR(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(k.isIdentifier(s)){let a=await Cr(s.name,t);if(a)return(await Un(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!k.isObjectExpression(r))return ps(t.file,`${n} without static options`);let o=rR(r,"queryFn");if(!o)return ps(t.file,`${n} without queryFn`);if(k.isIdentifier(o)){let i=await Cr(o.name,t);return i?(await Un(i.node,[],i.context)).returnSource:ps(t.file,`${n} queryFn unresolved`)}return k.isArrowFunctionExpression(o)||k.isFunctionExpression(o)?(await Un(o,[],t)).returnSource:k.isCallExpression(o)?ig(o,t):null}function rR(e,t){for(let n of e.properties){if(!k.isObjectProperty(n)||!k.isExpression(n.value))continue;if(vl(n)===t)return n.value}return null}function oR(e,t,n){return k.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 iR(e,t){if(!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property))return null;let n=e.callee.property.name;if(!["map","filter","slice","sort","toSorted"].includes(n))return null;let r=k.isExpression(e.callee.object)?await _e(e.callee.object,t):null;if(!r)return null;if(n!=="map")return Sn(r);let o=e.arguments[0];if(k.isIdentifier(o)){let i=await Cr(o.name,t);if(!i)return Sn(r);let s=await Un(i.node,[r],i.context);return{...Sn(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(k.isArrowFunctionExpression(o)||k.isFunctionExpression(o)){let i=await Un(o,[r],t);return{...Sn(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return Sn(r)}async function sR(e,t){return!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property,{name:"json"})||!k.isExpression(e.callee.object)?null:_e(e.callee.object,t)}async function aR(e,t){return!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property,{name:"then"})||!k.isExpression(e.callee.object)?null:kr(await _e(e.callee.object,t))}async function cR(e,t){if(!k.isIdentifier(e.callee))return null;let n=await Cr(e.callee.name,t);if(!n)return null;let r=[];for(let i of e.arguments){if(!k.isExpression(i)){r.push(ps(t.file,`unsupported argument for ${e.callee.name}`));continue}let s=await _e(i,t);r.push(s)}return(await Un(n.node,r,n.context,{arguments:e.arguments,context:t})).returnSource}async function Cr(e,t,n=new Set){let r=t.paramArguments.get(e);if(r&&!n.has(r.expression)){if(n.add(r.expression),bl(r.expression))return{node:r.expression,context:r.context};if(k.isIdentifier(r.expression))return Cr(r.expression.name,r.context,n)}let o=t.analysis.functions.get(e);if(o)return{node:o,context:t};let i=t.analysis.imports.get(e);if(!i||t.importDepth>=t.options.maxImportDepth)return null;let s=await fg(i,t);if(!s)return null;let a=Rr(s,t,{importDepth:t.importDepth+1}),c=pg(i,s);return c?{node:c,context:a}:Cr(i.importedName,a)}async function Un(e,t,n,r){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let o=Rr(n.analysis,n,{functionDepth:n.functionDepth+1}),i=n.analysis.functionParents.get(e),s=n;for(;s&&(s.analysis!==n.analysis||s.scopeFunction!==i);)s=s.lexicalContext;o.lexicalContext=s,o.paramSources=new Map,o.paramArguments=new Map,o.recordCollections=void 0,o.scopeVariables=n.analysis.functionVariables.get(e),o.scopeFunction=e,e.params.forEach((d,f)=>{for(let y of En(d))o.paramSources.delete(y),o.paramArguments.delete(y);let g=k.isAssignmentPattern(d)?d.left:d,m=r?.arguments[f];k.isIdentifier(g)&&k.isExpression(m)&&r&&o.paramArguments.set(g.name,{expression:m,context:r.context});let h=t[f];h&&gs(d,xl(h),o)});let a=lR(e,o),c=null,l,u=!1;for(let d of a){let f=Rr(n.analysis,o);if(f.recordCollections=await Um(e,d,m=>_e(m,o)),k.isObjectExpression(d)){l={...l??{},...await sg(d,f)},c=c??ys(l,n.file);continue}let g=await _e(d,f);if(g){if(!c){c=g;continue}let m=kl(c,g);if(!m){u=!0,c=null;continue}c=m}}return{returnSource:u?null:c,...l?{objectReturnMap:l}:{}}}function gs(e,t,n){if(k.isIdentifier(e)){n.paramSources.set(e.name,We(t));return}if(k.isAssignmentPattern(e)){gs(e.left,t,n);return}if(k.isObjectPattern(e))for(let r of e.properties){if(!k.isObjectProperty(r)||r.computed||!k.isIdentifier(r.key))continue;let o=Ro(t,[{kind:"property",name:r.key.name}],!0),i=k.isAssignmentPattern(r.value)?r.value.left:r.value;o&&gs(i,o,n)}}function lR(e,t){if(k.isArrowFunctionExpression(e)&&k.isExpression(e.body))return[e.body];let n=[],r=e.body;if(!k.isBlockStatement(r))return n;let o=i=>{if(k.isFunction(i)&&i!==e)return;if(k.isReturnStatement(i)){i.argument&&k.isExpression(i.argument)&&n.push(i.argument);return}if(k.isIfStatement(i)){let a=vr(i.test,{imports:new Map([...t.analysis.imports].filter(([c])=>!Ir(c,t))),functions:t.analysis.functions});if(a!==void 0){a?o(i.consequent):i.alternate&&o(i.alternate);return}}let s=k.VISITOR_KEYS[i.type];for(let a of s??[]){let c=i[a];if(Array.isArray(c))for(let l of c)k.isNode(l)&&o(l);else k.isNode(c)&&o(c)}};return o(r),n}async function sg(e,t){let n={};for(let r of e.properties){if(!k.isObjectProperty(r))continue;let o=vl(r);if(!o||!k.isExpression(r.value))continue;let i=await _e(r.value,t);i&&(n[o]=i)}return n}function vl(e){return k.isIdentifier(e.key)&&!e.computed?e.key.name:k.isStringLiteral(e.key)?e.key.value:null}function uR(e){let t=[],n=e;for(;k.isMemberExpression(n)||k.isOptionalMemberExpression(n);){let r=n.property;n.computed?k.isStringLiteral(r)?t.unshift({kind:"property",name:r.value}):k.isNumericLiteral(r)&&t.unshift({kind:"index",index:r.value}):k.isIdentifier(r)&&t.unshift({kind:"property",name:r.name}),n=n.object}return k.isIdentifier(n),t}function Ro(e,t,n){if(t.length===0)return We(e);let r=t[0],o=r?.kind==="property"?r.name:r?String(r.index):null;if(e.fieldMap&&o!==null){let s=e.fieldMap[o];return s?Ro(s,t.slice(1),n):null}let i=We(e);if(i.sourceType==="cms-field"){let s=t.filter(a=>a.kind==="property").map(a=>a.name);return s[0]==="data"&&s[1]==="items"?(i.valuePath=Co(i.valuePath,"data.items[]"),i.cmsFieldRoot=!1,i):s[0]==="fields"?(i.fieldPath=Co(i.fieldPath,s.slice(1).join(".")),i.cmsFieldRoot=!0,i):i.cmsFieldRoot||n||i.fieldMap?(i.fieldPath=Co(i.fieldPath,s.join(".")),i):(i.valuePath=Co(i.valuePath,Wm(t)),i)}return i.valuePath=Co(i.valuePath,Wm(t)),i}function Wm(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function Co(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function ag(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 Sn(e){let t=We(e);return t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function xl(e){let t=We(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&(t.cmsFieldRoot=!1),t}function kr(e){return e?{...We(e),confidence:e.confidence==="unknown"?"unknown":"safe-derived",evidence:[...e.evidence,{file:e.evidence[0]?.file??"unknown",reason:"safe derived expression"}]}:null}function Hm(e,t){return e?t?kl(e,t):We(e):t?We(t):null}function kl(e,t){if(hs(e)!==hs(t))return null;let n=ug(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function Il(e){let t=new Map;for(let n of e){let r=hs(n),o=t.get(r);t.set(r,o?kl(o,n):We(n))}return[...t.values()]}function hs(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,hs(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 ys(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 ps(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function xs(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 cg(e){let t=[...e].sort(lg),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 dR(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 lg(e,t){return Gm(e.targetKind)-Gm(t.targetKind)||ug(e.confidence,t.confidence)||Ym(e.sourceKind)-Ym(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function Gm(e){return{"repeat-region":0,"conditional-region":1,text:2,richtext:3,attribute:4,"component-prop":5}[e]}function Ym(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function ug(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=Zm.get(n)?.get(e),i=o?.source===t?o.ast:KC(t,{sourceType:"module",plugins:["jsx","typescript"]}),s={file:e,source:t,ast:i,variables:new Map,functions:new Map,imports:new Map,stateSetters:new Map,stateSetterCandidates:new Map,jsxElementsByRange:new Map,functionVariables:new WeakMap,functionParents:new WeakMap},a=[],c=[];k.traverse(i,{enter(d){switch(k.isFunction(d)&&(s.functionParents.set(d,a.at(-1)??null),a.push(d)),d.type){case"CallExpression":c.push(d);break;case"JSXElement":{let f=d.loc;if(!f)return;let g=Sl({startLine:f.start.line,startColumn:f.start.column,endLine:f.end.line,endColumn:f.end.column});s.jsxElementsByRange.has(g)||s.jsxElementsByRange.set(g,d);break}case"ImportDeclaration":{let f=d.source.value;for(let g of d.specifiers)k.isImportSpecifier(g)&&k.isIdentifier(g.local)?s.imports.set(g.local.name,{source:f,importedName:k.isIdentifier(g.imported)?g.imported.name:g.imported.value,localName:g.local.name,isDefault:!1}):k.isImportDefaultSpecifier(g)&&s.imports.set(g.local.name,{source:f,importedName:"default",localName:g.local.name,isDefault:!0});break}case"FunctionDeclaration":{d.id?.name&&s.functions.set(d.id.name,d);break}case"VariableDeclarator":{let f=a.at(-1),g=f&&(k.isFunctionDeclaration(f)||k.isFunctionExpression(f)||k.isArrowFunctionExpression(f))?f:null,m=g?s.functionVariables.get(g)??new Map:s.variables;g&&!s.functionVariables.has(g)&&s.functionVariables.set(g,m);for(let[h,y]of ms(d.id,k.isExpression(d.init)?d.init:null))m.set(h,y);if(k.isArrayPattern(d.id)&&k.isCallExpression(d.init)&&At(d.init.callee)==="useState"){let[h,y]=d.id.elements;k.isIdentifier(h)&&k.isIdentifier(y)&&s.stateSetters.set(h.name,y.name)}k.isIdentifier(d.id)&&bl(d.init)&&s.functions.set(d.id.name,d.init);break}case"ExportNamedDeclaration":{let f=d.declaration,g=d.source?.value;if(g)for(let m of d.specifiers){if(!k.isExportSpecifier(m))continue;let h=k.isIdentifier(m.exported)?m.exported.name:m.exported.value,y=m.local.name;s.imports.set(h,{source:g,importedName:y,localName:h,isDefault:y==="default"})}if(k.isFunctionDeclaration(f)&&f.id?.name&&s.functions.set(f.id.name,f),k.isVariableDeclaration(f))for(let m of f.declarations)k.isIdentifier(m.id)&&bl(m.init)&&s.functions.set(m.id.name,m.init);break}case"ExportDefaultDeclaration":{let f=d.declaration;if((k.isFunctionDeclaration(f)||k.isFunctionExpression(f)||k.isArrowFunctionExpression(f))&&s.functions.set("default",f),k.isIdentifier(f)){let g=s.functions.get(f.name);g&&s.functions.set("default",g)}break}}},exit(d){k.isFunction(d)&&a.pop()}});let l=new Set(s.stateSetters.values()),u=(d,f)=>{let g=s.stateSetterCandidates.get(d)??[];g.push(f),s.stateSetterCandidates.set(d,g)};if(l.size>0)for(let d of c){let f=k.isIdentifier(d.callee)?d.callee.name:null;f&&l.has(f)&&k.isExpression(d.arguments[0])&&u(f,d.arguments[0]);let g=new Set;for(let m of d.arguments)k.isIdentifier(m)&&m.name!==f&&l.has(m.name)&&g.add(m.name);for(let m of g)u(m,d)}return n.set(e,s),s}function ms(e,t){return k.isIdentifier(e)?[[e.name,t]]:k.isAssignmentPattern(e)?ms(e.left,t):k.isArrayPattern(e)?e.elements.flatMap((n,r)=>n&&!k.isRestElement(n)?ms(n,t?k.memberExpression(t,k.numericLiteral(r),!0):null):[]):k.isObjectPattern(e)?e.properties.flatMap(n=>{if(!k.isObjectProperty(n)||n.computed)return[];let r=vl(n);return r?ms(n.value,t?k.memberExpression(t,k.stringLiteral(r),!0):null):[]}):[]}function En(e){return!e||k.isVoidPattern(e)?[]:k.isIdentifier(e)?[e.name]:k.isObjectPattern(e)?e.properties.flatMap(t=>k.isObjectProperty(t)?En(t.value):En(t.argument)):k.isArrayPattern(e)?e.elements.flatMap(t=>t?En(k.isRestElement(t)?t.argument:t):[]):k.isAssignmentPattern(e)?En(e.left):k.isRestElement(e)?En(e.argument):[]}function bl(e){return k.isFunctionExpression(e)||k.isArrowFunctionExpression(e)}function dg(e,t){let n=Rl(e,t);return n?e.functionVariables.get(n):void 0}function Rl(e,t){return e.functions.get(t)??e.functions.get("default")}async function fg(e,t){let n=await mg(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return Cl(n,r,t.fileCache)}function pg(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function mg(e,t,n){return It(t)?Cn(e,t,n):null}function Rr(e,t,n={}){return{file:e.file,analysis:e,readFile:t.readFile,exists:t.exists,fileCache:t.fileCache,options:t.options,variableCache:new Map,functionDepth:n.functionDepth??t.functionDepth,importDepth:n.importDepth??t.importDepth,paramSources:new Map(t.paramSources),paramArguments:e===t.analysis?new Map(t.paramArguments):new Map,resolvingVariables:new Set,resolvingComponentProps:t.resolvingComponentProps,scopeVariables:e===t.analysis?t.scopeVariables:void 0,scopeFunction:e===t.analysis?t.scopeFunction:void 0,lexicalContext:e===t.analysis?t.lexicalContext:void 0,recordCollections:e===t.analysis?t.recordCollections:void 0}}function fR(e){return e?We(e):null}function We(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,We(n)]))}:{}}}import*as Nl from"@babel/parser";import wl from"@babel/traverse";import*as ee from"@babel/types";import{classifySiteEditPropertyName as pR}from"@vcp-dev/contracts";var Pl=typeof wl=="function"?wl:wl.default;function Al(e){let t=pR(e.propertyName);if(t.owner!=="generic")return pt("invalid-property",t.diagnostic?.message??`Property '${e.propertyName}' is not a generic property`);let n=e.selectionRef;if(!n)return pt("missing-selection-ref","A repeat property target requires a complete selection reference");if(n.key!==e.element.identity.key)return pt("selection-mismatch","Selection reference does not identify the requested element");if(n.instanceIndex===void 0)return pt("missing-instance-index","A repeat property target requires an instance index");let r;try{r=Nl.parse(e.source,{sourceType:"module",plugins:["typescript","jsx"]})}catch(y){return pt("repeat-not-found",`Unable to parse repeat source: ${y instanceof Error?y.message:String(y)}`)}let o=mR(r,e.element.sourceRange);if(!o)return pt("repeat-not-found","The selected element is not inside a supported map repeat");if(!ee.isIdentifier(o.callback.params[0]))return pt("unsupported-callback","Repeat property materialization requires an identifier callback item");let i=gR(r,o.collection,e.file,e.sources);if(!i)return pt("collection-not-found","The repeat collection is not a visible local static array");let{array:s,locator:a,sourceFile:c}=i,l=[],u=[];for(let[y,b]of s.elements.entries()){if(!b||!ee.isObjectExpression(b)||!Sg(b))return pt("unsafe-collection","Repeat materialization requires an array of local static objects without spreads");let S=[{kind:"index",index:y}];l.push(S),u.push({kind:"value",root:a.root,path:S})}let d=u.length;if(n.instanceCount!==void 0&&n.instanceCount!==d)return pt("count-mismatch",`Selection reports ${n.instanceCount} instances but the source collection has ${d}`);let f=n.instanceIndex;if(f>=d)return pt("index-out-of-range",`Selected repeat instance ${f} is outside the source collection`);let g=s.elements[f];if(!g||!ee.isObjectExpression(g))return pt("unsafe-collection","Selected repeat item is not an object");let m=ER(e.element,e.propertyName),h=bR(g,e.propertyName);return h?{ok:!0,sourceFile:c,templateFile:e.file,collectionLocator:a,parentObjectLocators:u,selectedParentObjectLocator:u[f],sourceItemIndex:f,sourceItemPath:l[f],collectionIndexMap:Array.from({length:d},(y,b)=>b),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:SR(g,e.propertyName),...m?{property:m}:{},selectionRef:n}:pt("unsafe-property-source",`Property '${e.propertyName}' has a dynamic or unsupported source in the repeat item`)}function mR(e,t){let n=[];return Pl(e,{CallExpression(r){let o=gg(r.node);o&&yg(o.callback,t)&&n.push({...o,span:hg(r.node)})},OptionalCallExpression(r){let o=gg(r.node);o&&yg(o.callback,t)&&n.push({...o,span:hg(r.node)})}}),n.sort((r,o)=>r.span-o.span),n[0]??null}function gg(e){let t=e.callee;if(!ee.isMemberExpression(t)&&!ee.isOptionalMemberExpression(t)||t.computed||!ee.isIdentifier(t.property)||t.property.name!=="map"||!ee.isExpression(t.object))return null;let n=e.arguments[0];return!n||!ee.isExpression(n)||!ee.isArrowFunctionExpression(n)&&!ee.isFunctionExpression(n)?null:{collection:t.object,callback:n}}function gR(e,t,n,r){let o=wo(t);if(o&&ee.isArrayExpression(o))return{array:o,locator:{kind:"value",root:{kind:"expression",sourceRange:vg(o)}},sourceFile:n};if(!ee.isIdentifier(t))return null;let i=[];if(Pl(e,{VariableDeclarator(s){ee.isIdentifier(s.node.id)&&s.node.id.name===t.name&&s.node.init&&i.push(s.node)}}),i.length===1){let s=wo(i[0].init);return!s||!ee.isArrayExpression(s)?null:{array:s,locator:{kind:"value",root:{kind:"binding",name:t.name}},sourceFile:n}}return hR(e,t.name,n,r)}function hR(e,t,n,r){if(!r)return null;for(let o of e.program.body){if(!ee.isImportDeclaration(o))continue;let i=o.specifiers.find(f=>f.local.name===t);if(!i||!ee.isStringLiteral(o.source)||!ee.isImportSpecifier(i))continue;let s=xR(n,o.source.value,r);if(!s)return null;let a=ee.isIdentifier(i.imported)?i.imported.name:i.imported.value,c=r.get(s);if(c===void 0)return null;let l;try{l=Nl.parse(c,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}let u=yR(l,a),d=u?wo(u):null;return!d||!ee.isArrayExpression(d)?null:{array:d,locator:{kind:"value",root:{kind:"binding",name:a}},sourceFile:s}}return null}function yR(e,t){let n=null;return Pl(e,{VariableDeclarator(r){n||!ee.isIdentifier(r.node.id)||r.node.id.name!==t||!r.node.init||!ee.isExpression(r.node.init)||(n=r.node.init)}}),n}function xR(e,t,n){let r=In(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 wo(e){return ee.isParenthesizedExpression(e)?wo(e.expression):ee.isTSAsExpression(e)?bg(e.typeAnnotation)?wo(e.expression):null:ee.isTSSatisfiesExpression(e)?null:e}function bg(e){return ee.isTSTypeReference(e)&&ee.isIdentifier(e.typeName)&&e.typeName.name==="const"}function Sg(e){return e.properties.every(t=>!ee.isObjectProperty(t)||t.computed||!ee.isExpression(t.value)?!1:Ss(t.value))}function Ss(e){if(ee.isTSAsExpression(e)&&bg(e.typeAnnotation))return Ss(e.expression);if(ee.isTSSatisfiesExpression(e))return!1;if(ee.isArrayExpression(e))return e.elements.every(n=>!n||ee.isSpreadElement(n)||!ee.isExpression(n)?!1:Ss(n));if(ee.isObjectExpression(e))return Sg(e);let t=Bt(e);return t.status==="resolved"||t.status==="undefined"}function bR(e,t){let n=e.properties.filter(o=>ee.isObjectProperty(o)&&Eg(o.key)===t);if(n.length>1)return null;let r=n[0];return r?ee.isExpression(r.value)?Ss(r.value)?"static":ee.isIdentifier(r.value)||ee.isMemberExpression(r.value)?"binding":null:null:"missing"}function SR(e,t){let n=e.properties.filter(o=>ee.isObjectProperty(o)&&Eg(o.key)===t);if(n.length>1)return{status:"unresolved"};let r=n[0];return!r||!ee.isExpression(r.value)?{status:"undefined"}:Bt(r.value)}function ER(e,t){let n=e.attributes?.filter(r=>r.name===t)??[];return n.length===1?n[0]:void 0}function Eg(e){return ee.isIdentifier(e)?e.name:ee.isStringLiteral(e)?e.value:ee.isNumericLiteral(e)?String(e.value):null}function vg(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 hg(e){return e.start==null||e.end==null?Number.MAX_SAFE_INTEGER:e.end-e.start}function yg(e,t){let n=vg(e);return xg(n.startLine,n.startColumn,t.startLine,t.startColumn)<=0&&xg(n.endLine,n.endColumn,t.endLine,t.endColumn)>=0}function xg(e,t,n,r){return e===n?t-r:e-n}function pt(e,t){return{ok:!1,errorCode:e,reason:t}}import{classifySiteEditPropertyName as iw}from"@vcp-dev/contracts";import*as ne from"@babel/types";import Fo from"node:path";import*as j from"@babel/types";import*as Ng from"@babel/parser";import Tl from"@babel/traverse";import*as ae from"@babel/types";function vs(e,t){let n=[],r=e;for(;ae.isMemberExpression(r);){if(r.computed)if(ae.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(ae.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!ae.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!ae.isIdentifier(r)||r.name!==t?null:n}function kg(e){if(ae.isIdentifier(e))return{base:e.name,path:[]};if(!ae.isMemberExpression(e))return null;let t=[],n=e;for(;ae.isMemberExpression(n);){if(n.computed)if(ae.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(ae.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!ae.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return ae.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 Jt=Symbol("not-closed-literal");function Es(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:Jt;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":return Es(e.expression);case"ArrayExpression":{let t=[];for(let n of e.elements){if(!n||ae.isSpreadElement(n))return Jt;let r=Es(n);if(r===Jt)return Jt;t.push(r)}return t}case"ObjectExpression":{let t={};for(let n of e.properties){if(!ae.isObjectProperty(n)||n.computed||n.shorthand||!ae.isExpression(n.value))return Jt;let r=ae.isIdentifier(n.key)?n.key.name:ae.isStringLiteral(n.key)?n.key.value:null;if(!r)return Jt;let o=Es(n.value);if(o===Jt)return Jt;t[r]=o}return t}default:return Jt}}function Ig(e){let{resolveBindingTarget:t}=e;async function n(i,s,a,c,l,u,d){let f=Es(i);if(f!==Jt)return f;if(!ae.isTemplateLiteral(i)){if(ae.isTSAsExpression(i)||ae.isTSSatisfiesExpression(i)||ae.isTSNonNullExpression(i))return await n(i.expression,s,a,c,l,u,d);if(ae.isIdentifier(i)){let g=s.getBinding(i.name);if(!g)return;let m=await t({currentFile:a,binding:g,readFile:c,exists:l,fileCache:u,visited:d});return m?.kind==="static"?m.value:void 0}if(ae.isArrayExpression(i)){let g=[];for(let m of i.elements){if(!m||ae.isSpreadElement(m))return;let h=await r(m,s,a,c,l,u,d);if(h===void 0)return;g.push(h)}return g}if(ae.isObjectExpression(i)){let g={};for(let m of i.properties){if(!ae.isObjectProperty(m)||m.computed)return;let h=null;if(ae.isIdentifier(m.key)?h=m.key.name:ae.isStringLiteral(m.key)&&(h=m.key.value),!h)return;if(m.shorthand){if(!ae.isIdentifier(m.value))return;let b=await r(m.value,s,a,c,l,u,d);if(b===void 0)return;g[h]=b;continue}if(!ae.isExpression(m.value))return;let y=await r(m.value,s,a,c,l,u,d);y!==void 0&&(g[h]=y)}return g}if(ae.isMemberExpression(i)){let g=await o(i,s,a,c,l,u,d);if(!g)return;let m=s.getBinding(g.base);if(!m)return;let h=await t({currentFile:a,binding:m,readFile:c,exists:l,fileCache:u,visited:d});return!h||h.kind!=="static"?void 0:Qe(h.value,g.path)}}}async function r(i,s,a,c,l,u,d){if(!ae.isSpreadElement(i))return await n(i,s,a,c,l,u,d)}async function o(i,s,a,c,l,u,d){if(ae.isIdentifier(i))return{base:i.name,path:[]};if(!ae.isMemberExpression(i))return null;let f=[],g=i;for(;ae.isMemberExpression(g);){if(g.computed){let m=g.property;if(ae.isNumericLiteral(m))f.unshift({kind:"index",index:m.value});else if(ae.isStringLiteral(m))f.unshift({kind:"property",name:m.value});else{let h=ae.isExpression(m)?await n(m,s,a,c,l,u,d):void 0;if(typeof h=="string")f.unshift({kind:"property",name:h});else if(Number.isInteger(h))f.unshift({kind:"index",index:h});else return null}}else{if(!ae.isIdentifier(g.property))return null;f.unshift({kind:"property",name:g.property.name})}g=g.object}return ae.isIdentifier(g)?{base:g.name,path:f}:null}return{normalizeExpressionWithScope:o,evaluateStaticExpression:n}}var Pg=typeof Tl=="function"?Tl:Tl.default,Cg=new WeakMap;function Ag(e){try{return Ng.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function ks(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=Ag(n);return e.set(t,{source:n,ast:o}),o}function Is(e,t){return Fl(No(e).expressionRanges,t,!1)}function Tg(e,t){return No(e).exactExpressions.get(Fg(t))??null}function Cs(e,t){return Fl(No(e).jsxRanges,t,!0)}function No(e){let t=Cg.get(e);if(t)return t;let n={expressions:[],expressionRanges:[],jsxRanges:[],exactExpressions:new Map};return Pg(e,{Expression(r){let o=r;n.expressions.push(o);let i=Rg(o,n.expressions.length-1);if(!i)return;n.expressionRanges.push(i);let s=Fg(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=Rg(r,n.jsxRanges.length);o&&n.jsxRanges.push(o)}}),n.expressionRanges.sort(wg),n.jsxRanges.sort(wg),Cg.set(e,n),n}function Rg(e,t){let n=Po(e.node);return n?{path:e,range:n,traversalIndex:t,span:(e.node.end??0)-(e.node.start??0)}:null}function Fg(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}function wg(e,t){return e.range.startLine-t.range.startLine||e.range.startColumn-t.range.startColumn||e.traversalIndex-t.traversalIndex}function Fl(e,t,n,r){let o=0,i=e.length;for(;o<i;){let c=o+Math.floor((i-o)/2),l=e[c].range;l.startLine<t.startLine||l.startLine===t.startLine&&l.startColumn<t.startColumn?o=c+1:i=c}let s=null,a=n?1/0:-1;for(let c=o;c<e.length;c++){let l=e[c],u=l.range;if(u.startLine>t.endLine||u.startLine===t.endLine&&u.startColumn>t.endColumn)break;if(u.endLine>t.endLine||u.endLine===t.endLine&&u.endColumn>t.endColumn||r&&!r(l.path))continue;((n?l.span<a:l.span>a)||l.span===a&&(!s||l.traversalIndex>s.traversalIndex))&&(s=l,a=l.span)}return s?.path??null}function Po(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 wr(e,t){if(t)return _l(e,t);let n=kg(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function _l(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Ao(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of No(e).expressions){if(_l(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function _g(e,t,n,r){return Fl(No(e).expressionRanges,r,!0,o=>_l(o.node,t)===n)}function Nr(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function To(e){let t=null;if(Pg(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}async function Tt(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=Ag(o),s={source:o,ast:i};return n.set(e,s),s}function vR(e){return j.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:j.isMemberExpression(e.callee)&&j.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function kR(e){if(!j.isNewExpression(e)||!j.isIdentifier(e.callee,{name:"Proxy"})||e.arguments.length!==2||!j.isIdentifier(e.arguments[0])||!j.isObjectExpression(e.arguments[1])||e.arguments[1].properties.length!==1)return null;let[t]=e.arguments[1].properties;if(!j.isObjectMethod(t)||t.kind!=="method"||t.computed||t.async||t.generator||!j.isIdentifier(t.key,{name:"get"})||t.params.length!==3||!t.params.every(j.isIdentifier)||t.body.body.length!==2)return null;let[n,r,o]=t.params,[i,s]=t.body.body;if(j.isIfStatement(i)&&j.isBlockStatement(i.consequent)&&i.consequent.body.length!==1)return null;let a=j.isIfStatement(i)?i.test:null,c=a&&j.isLogicalExpression(a,{operator:"&&"})?a.right:null,l=j.isIfStatement(i)?j.isBlockStatement(i.consequent)?i.consequent.body[0]:i.consequent:null,u=j.isReturnStatement(s)?s.argument:null;return!a||!j.isLogicalExpression(a,{operator:"&&"})||!j.isBinaryExpression(a.left,{operator:"==="})||!j.isUnaryExpression(a.left.left,{operator:"typeof"})||!j.isIdentifier(a.left.left.argument,{name:r.name})||!j.isStringLiteral(a.left.right,{value:"string"})||!j.isUnaryExpression(c,{operator:"!"})||!j.isBinaryExpression(c.argument,{operator:"in"})||!j.isIdentifier(c.argument.left,{name:r.name})||!j.isIdentifier(c.argument.right,{name:n.name})||!j.isReturnStatement(l)||!j.isIfStatement(i)||i.alternate||!j.isCallExpression(u)||!j.isMemberExpression(u.callee)||!j.isIdentifier(u.callee.object,{name:"Reflect"})||!j.isIdentifier(u.callee.property,{name:"get"})||u.arguments.length!==3||!j.isIdentifier(u.arguments[0],{name:n.name})||!j.isIdentifier(u.arguments[1],{name:r.name})||!j.isIdentifier(u.arguments[2],{name:o.name})?null:e.arguments[0].name}function IR(e){let t=e.getFunctionParent();if(!t)return null;if(t.isFunctionDeclaration()){let s=t.node.id?.name;if(!s)return null;let a=t.parentPath?.isExportDefaultDeclaration()?"default":(t.parentPath?.isExportNamedDeclaration(),s);return{componentName:s,exportName:a}}if(!t.isArrowFunctionExpression()&&!t.isFunctionExpression())return null;let n=t.parentPath;if(!n?.isVariableDeclarator()||!j.isIdentifier(n.node.id))return null;let r=n.node.id.name,o=n.parentPath,i=o?.parentPath?.isExportDefaultDeclaration()?"default":(o?.parentPath?.isExportNamedDeclaration(),r);return{componentName:r,exportName:i}}function Mg(e,t){let n=IR(e.path);if(!n)return null;let r=fr(e,t);return r?{...n,...r}:null}function Og(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}function Ml(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 Ol(e,t){for(let n of e.program.body){if(t==="default"&&j.isExportDefaultDeclaration(n))return j.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:(j.isFunctionDeclaration(n.declaration)||j.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if(j.isExportNamedDeclaration(n)){if(n.declaration){if(j.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if(j.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if((j.isFunctionDeclaration(n.declaration)||j.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if((j.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&j.isExportSpecifier(r))return n.source?{kind:"re-export",name:r.local.name,source:n.source.value}:{kind:"local-binding",name:r.local.name}}}return null}function Lg(e){let{resolveExternalExpression:t,resolveCollectionCallTarget:n,evaluateStaticExpression:r,resolveSourceInfoProvenance:o,buildExpressionSourceInfo:i}=e;async function s(h){let{currentFile:y,binding:b,readFile:S,exists:v,fileCache:C,visited:P}=h,F=`${y}::${b.kind}::${b.identifier.name}`;if(P.has(F))return null;P.add(F);try{let R=await a({currentFile:y,binding:b,readFile:S,exists:v,fileCache:C,visited:P});if(R)return R;if(b.path.isImportSpecifier()||b.path.isImportDefaultSpecifier())return await g({currentFile:y,binding:b,readFile:S,exists:v,graph:h.graph,externalSourceResolvers:h.externalSourceResolvers,externalAdapters:h.externalAdapters,fileCache:C,visited:P});if(b.kind==="param")return null;if(b.path.isVariableDeclarator()){let N=b.path.node.init;if(!N||!j.isExpression(N))return null;let T=kR(N);if(T&&!b.path.scope.getBinding("Proxy")&&!b.path.scope.getBinding("Reflect")){let W=b.path.scope.getBinding(T),oe=W?await s({...h,binding:W}):null;if(oe?.kind==="static"&&oe.value!==null&&!Array.isArray(oe.value)&&typeof oe.value=="object")return oe}let L=b.path.get("init");if(L&&!Array.isArray(L)&&L.isExpression()){let W=await t({currentFile:y,expressionPath:L,readFile:S,exists:v,graph:h.graph,externalSourceResolvers:h.externalSourceResolvers,externalAdapters:h.externalAdapters,functionCallContracts:h.functionCallContracts,fileCache:C,visited:P});if(W)return W;if(L.isCallExpression()){let oe=await n({currentFile:y,callPath:L,readFile:S,exists:v,graph:h.graph,externalSourceResolvers:h.externalSourceResolvers,externalAdapters:h.externalAdapters,functionCallContracts:h.functionCallContracts,fileCache:C,visited:P});if(oe)return oe}}let q=await r(N,b.path.scope,y,S,v,C,P);return q===void 0?null:{kind:"static",file:y,root:{kind:"binding",name:b.identifier.name},value:q,sourceKind:"binding"}}if(b.path.isIdentifier()&&b.path.parentPath?.isExportDefaultDeclaration()){let N=b.path.parentPath.node.declaration;if(!j.isExpression(N))return null;let T=await r(N,b.path.scope,y,S,v,C,P);return T===void 0?null:{kind:"static",file:y,root:{kind:"binding",name:b.identifier.name},value:T,sourceKind:"binding"}}return null}finally{P.delete(F)}}async function a(h){let{currentFile:y,binding:b,readFile:S,exists:v,fileCache:C,visited:P}=h;if(!b.path.isVariableDeclarator()||!b.path.get("id").isArrayPattern())return null;let F=b.path,R=F.node.init;if(!R||!j.isCallExpression(R))return null;let N=vR(R);if(!N||!j.isArrayPattern(F.node.id)||F.node.id.elements.findIndex(oe=>j.isIdentifier(oe)&&oe.name===b.identifier.name)!==0)return null;let L=N==="useReducer"?1:0,q=R.arguments[L];if(!q||!j.isExpression(q))return null;let W=await r(q,F.scope,y,S,v,C,P);return W===void 0?null:{kind:"static",file:y,root:{kind:"hook-state",name:b.identifier.name,hook:N},value:W,sourceKind:"binding"}}async function c(h){let y=h.expressionPath.scope.getBinding(h.sourceInfo.base);if(!y||!y.constant||y.kind!=="param"||!h.graph)return null;let b=Mg(y,h.sourceInfo);if(!b)return null;let S=[...h.graph.elements.values()].filter(C=>Og(C,h.currentFile,b.componentName,b.exportName));if(!S.length)return null;let v=[];for(let C of S){if(C.sourceFile!==S[0].sourceFile||C.componentName!==S[0].componentName||C.attributeSpreads?.length)return null;let P=await Tt(C.sourceFile,h.readFile,h.fileCache),F=P.ast?Cs(P.ast,C.sourceRange):null;if(!F)return null;let R=F.parentPath;for(;R&&!R.isFunction();){if(R.isJSXElement()){let D=R.node.openingElement.name;if(!j.isJSXIdentifier(D)||!/^[a-z]/.test(D.name))return null}else if(!R.isJSXFragment()&&!R.isReturnStatement()&&!R.isBlockStatement())return null;R=R.parentPath}if(!R)return null;let N=F.get("openingElement").get("attributes").filter(D=>D.isJSXAttribute()&&j.isJSXIdentifier(D.node.name,{name:b.propName}));if(N.length!==1)return null;let T=N[0];if(!T?.isJSXAttribute())return null;let L=T.get("value"),q=L.isJSXExpressionContainer()?L.get("expression"):L;if(!q.isExpression())return null;let W=await r(q.node,q.scope,C.sourceFile,h.readFile,h.exists,h.fileCache,h.visited),oe=W===void 0?void 0:Qe(W,b.remainingPath);if(oe===void 0)return null;v.push(oe)}return v}async function l(h){let y=Mg(h.binding,h.sourceInfo);if(!y||!h.graph)return null;let b=["component-prop",h.currentFile,h.binding.identifier.start??h.binding.path.node.start??-1,y.componentName,y.propName].join(":");if(h.visited.has(b))return null;h.visited.add(b);try{return await u(h,y,h.graph)}finally{h.visited.delete(b)}}async function u(h,y,b){let S=[...b.elements.values()].filter(T=>Og(T,h.currentFile,y.componentName,y.exportName));if(S.length!==1)return null;let v=S[0],C=v.attributes?.find(T=>T.name===y.propName);if(C&&!C.source){let T=await d({caller:v,propName:y.propName,remainingPath:y.remainingPath,readFile:h.readFile,fileCache:h.fileCache});if(T)return Ml(T,{componentName:y.componentName,propName:y.propName,file:v.sourceFile})}if(!C?.source){let T=await f({caller:v,propName:y.propName,remainingPath:y.remainingPath,readFile:h.readFile,exists:h.exists,graph:h.graph,externalSourceResolvers:h.externalSourceResolvers,externalAdapters:h.externalAdapters,functionCallContracts:h.functionCallContracts,fileCache:h.fileCache,visited:h.visited});if(T)return Ml(T,{componentName:y.componentName,propName:y.propName,file:v.sourceFile});let L=Fp(h.binding,y.componentName,y.propName);if(!L||L.propName!==y.propName)return null;let q=await r(L.expressionPath.node,L.expressionPath.scope,h.currentFile,h.readFile,h.exists,h.fileCache,h.visited);if(q===void 0)return null;let W=y.remainingPath;return W.length>0&&Qe(q,W)===void 0?null:{kind:"value",file:h.currentFile,root:{kind:"binding",name:y.propName},path:W,sourceKind:"binding",semanticKind:"component-prop",displayExpression:L.displayPath,chainPrefix:[{kind:"component-prop",file:h.currentFile,displayName:L.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let P=await Tt(v.sourceFile,h.readFile,h.fileCache);if(!P.ast)return null;let F=_g(P.ast,P.source,C.source.expression,C.sourceRange)??Ao(P.ast,P.source,C.source.expression);if(!F)return null;let R={...C.source,expression:Nr(C.source.expression,y.remainingPath),path:[...C.source.path,...y.remainingPath]},N=await o({currentFile:v.sourceFile,expressionPath:F,sourceInfo:R,readFile:h.readFile,exists:h.exists,graph:h.graph,externalSourceResolvers:h.externalSourceResolvers,externalAdapters:h.externalAdapters,functionCallContracts:h.functionCallContracts,fileCache:h.fileCache,visited:h.visited});return N?Ml(N.kind==="external"?N:{...N,displayExpression:R.expression},{componentName:y.componentName,propName:y.propName,file:v.sourceFile}):null}async function d(h){let y=await Tt(h.caller.sourceFile,h.readFile,h.fileCache);if(!y.ast)return null;let b=Cs(y.ast,h.caller.sourceRange);if(!b)return null;let S=b.get("openingElement").get("attributes").find(F=>F.isJSXAttribute()&&F.node.name.type==="JSXIdentifier"&&F.node.name.name===h.propName);if(!S?.isJSXAttribute())return null;let v=S.get("value"),C=v.isStringLiteral()?v:v.isJSXExpressionContainer()?v.get("expression"):null;if(!C?.isExpression())return null;let P=Po(C.node);return P?{kind:"value",file:h.caller.sourceFile,root:{kind:"expression",sourceRange:P},path:h.remainingPath,sourceKind:"binding",semanticKind:"component-prop",displayExpression:h.propName,editMode:"upstream",diagnostics:[]}:null}async function f(h){let y=await Tt(h.caller.sourceFile,h.readFile,h.fileCache);if(!y.ast)return null;let b=Cs(y.ast,h.caller.sourceRange);if(!b)return null;let S=b.get("openingElement");for(let v of S.get("attributes")){if(!v.isJSXSpreadAttribute())continue;let C=v.get("argument");if(!C.isExpression())continue;let P=await i({expression:C.node,scope:C.scope,source:y.source,currentFile:h.caller.sourceFile,readFile:h.readFile,exists:h.exists,fileCache:h.fileCache,visited:h.visited});if(!P)continue;let F=[{kind:"property",name:h.propName},...h.remainingPath],R={...P,expression:Nr(P.expression,F),path:[...P.path,...F]},N=await o({currentFile:h.caller.sourceFile,expressionPath:C,sourceInfo:R,readFile:h.readFile,exists:h.exists,graph:h.graph,externalSourceResolvers:h.externalSourceResolvers,externalAdapters:h.externalAdapters,functionCallContracts:h.functionCallContracts,fileCache:h.fileCache,visited:h.visited});if(N)return N.kind==="external"?N:{...N,displayExpression:R.expression}}return null}async function g(h){let{currentFile:y,binding:b,readFile:S,exists:v,fileCache:C,visited:P}=h,F=b.path.parentPath;if(!F||!F.isImportDeclaration())return null;let R=F.node.source.value;if(typeof R!="string")return null;let N=await Cn(y,R,v);if(!N)return null;if(b.path.isImportDefaultSpecifier()){let D=await Tt(N,S,C),Z=D.ast?Ol(D.ast,"default"):null,fe=await m({file:N,exportName:"default",readFile:S,exists:v,graph:h.graph,externalSourceResolvers:h.externalSourceResolvers,externalAdapters:h.externalAdapters,functionCallContracts:h.functionCallContracts,fileCache:C,visited:P});return!fe||fe.kind!=="static"?null:{kind:"static",file:Z?.kind==="default-expression"?fe.file:N,root:Z?.kind==="default-expression"?fe.root:{kind:"default-export"},value:fe.value,sourceKind:"imported-binding"}}if(!b.path.isImportSpecifier())return null;let T=b.path.node.imported,L=j.isIdentifier(T)?T.name:T.value,q=await Tt(N,S,C),W=q.ast?Ol(q.ast,L):null,oe=await m({file:N,exportName:L,readFile:S,exists:v,graph:h.graph,externalSourceResolvers:h.externalSourceResolvers,externalAdapters:h.externalAdapters,functionCallContracts:h.functionCallContracts,fileCache:C,visited:P});return oe?oe.kind==="external"?oe:{kind:"static",file:W?.kind==="re-export"?oe.file:N,root:W?.kind==="re-export"||oe.root.kind==="binding"&&oe.root.name!==W?.name?oe.root:{kind:"named-export",name:L},value:oe.value,sourceKind:"imported-binding"}:null}async function m(h){let{file:y,exportName:b,readFile:S,exists:v,fileCache:C,visited:P}=h,F=`export::${y}::${b}`;if(!P.has(F)){P.add(F);try{let R=await Tt(y,S,C);if(!R.ast)return;let N=Ol(R.ast,b);if(!N)return;if(N.kind==="default-expression"){let W=N.expression;if(!W||!j.isIdentifier(W))return;let oe=To(R.ast).getBinding(W.name);return oe?await s({currentFile:y,binding:oe,readFile:S,exists:v,graph:h.graph,externalSourceResolvers:h.externalSourceResolvers,externalAdapters:h.externalAdapters,functionCallContracts:h.functionCallContracts,fileCache:C,visited:P})??void 0:void 0}if(N.kind==="re-export"){if(!N.source||!N.name)return;let W=await Cn(y,N.source,v);return W?m({...h,file:W,exportName:N.name}):void 0}let T=N.name;if(!T)return;let L=To(R.ast).getBinding(T);return L?await s({currentFile:y,binding:L,readFile:S,exists:v,graph:h.graph,externalSourceResolvers:h.externalSourceResolvers,externalAdapters:h.externalAdapters,functionCallContracts:h.functionCallContracts,fileCache:C,visited:P})??void 0:void 0}finally{P.delete(F)}}}return{resolveExportValue:m,resolveComponentPropBinding:l,resolveComponentPropValues:c,resolveBindingTarget:s}}import*as Y from"@babel/types";function Dl(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=Nt(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!CR(s,r)?null:{callPath:s,basePath:i}}function CR(e,t){let n=e.node.callee;return!Y.isMemberExpression(n)||!Y.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}function $g(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:Qi(r,t)}function Dg(e,t){return e?Y.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}function Bg(e,t,n,r,o){let i=Y.isExpression(e.body)?e.body:e.body.body.find(a=>Y.isReturnStatement(a))?.argument;if(!i||!Y.isExpression(i))return;let s=Ll(i,t,n,r,o);return typeof s=="number"?s:void 0}function Ll(e,t,n,r,o){if(Y.isNumericLiteral(e)||Y.isStringLiteral(e)||Y.isBooleanLiteral(e))return e.value;if(Y.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(Y.isMemberExpression(e)){let i=vs(e,t);if(i)return Qe(r,i);let s=vs(e,n);return s?Qe(o,s):void 0}if(Y.isBinaryExpression(e)&&e.operator==="-"){let i=Y.isExpression(e.left)?Ll(e.left,t,n,r,o):void 0,s=Y.isExpression(e.right)?Ll(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function RR(e){if(Y.isExpression(e.body))return e.body;for(let t of e.body.body)if(Y.isReturnStatement(t)&&t.argument&&Y.isExpression(t.argument))return t.argument;return null}function wR(e,t,n){let r=Jn(e,t,n);return typeof r=="boolean"?r:void 0}function Jn(e,t,n){if(Y.isStringLiteral(e)||Y.isNumericLiteral(e)||Y.isBooleanLiteral(e))return e.value;if(Y.isNullLiteral(e))return null;if(Y.isIdentifier(e))return e.name===t?n:void 0;if(Y.isMemberExpression(e)){let r=vs(e,t);return r?Qe(n,r):void 0}if(Y.isUnaryExpression(e)&&e.operator==="!"){let r=Jn(e.argument,t,n);return r===void 0?void 0:!r}if(Y.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(Y.isBinaryExpression(e)){let r=Y.isExpression(e.left)?Jn(e.left,t,n):void 0,o=Y.isExpression(e.right)?Jn(e.right,t,n):void 0;if(r===void 0||o===void 0)return;switch(e.operator){case"===":return r===o;case"!==":return r!==o;case"==":return r==o;case"!=":return r!=o;default:return}}}function Vg(e){let t=[],n=e;for(;Y.isMemberExpression(n)||Y.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(Y.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(Y.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(Y.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(Y.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return Y.isIdentifier(n)?{base:n.name,segments:t}:null}function Kg(e){return e.some(t=>t.kind==="dynamic")}function jg(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}function Ug(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 NR(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 Jg(e){let{resolveBindingTarget:t,evaluateStaticExpression:n,buildExpressionSourceInfo:r,resolveSourceInfoProvenance:o,resolveComponentPropValues:i}=e;async function s(m){let{currentFile:h,callPath:y,readFile:b,exists:S,fileCache:v,visited:C}=m,P=y.node.callee;if(!Y.isMemberExpression(P)||!Y.isIdentifier(P.property)||P.property.name!=="map")return null;let F=y.get("callee");if(!F.isMemberExpression())return null;let R=F.get("object");if(Array.isArray(R)||!R.isExpression())return null;let N=await a({currentFile:h,expressionPath:R,readFile:b,exists:S,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:v,visited:C});return!N||!Array.isArray(N.value)||N.value.length===0?null:N}async function a(m){let{currentFile:h,expressionPath:y,readFile:b,exists:S,fileCache:v,visited:C}=m;if(y.isIdentifier()){let P=y.scope.getBinding(y.node.name);if(!P)return null;let F=await t({currentFile:h,binding:P,readFile:b,exists:S,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:v,visited:C});return F?.kind==="static"?F:null}if(y.isCallExpression())return l({currentFile:h,callPath:y,readFile:b,exists:S,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:v,visited:C});if(y.isTSAsExpression()||y.isTSSatisfiesExpression()||y.isTSNonNullExpression()){let P=y.get("expression");if(!Array.isArray(P)&&P.isExpression())return a({...m,expressionPath:P})}if(y.isArrayExpression()){let P=Po(y.node);if(!P)return null;let F=await n(y.node,y.scope,h,b,S,v,C);return Array.isArray(F)?{kind:"static",file:h,root:{kind:"expression",sourceRange:P},value:F,sourceKind:"binding"}:null}if(y.isMemberExpression()){let P=await r({expression:y.node,scope:y.scope,currentFile:h,readFile:b,exists:S,fileCache:v,visited:C});if(!P)return null;let F=await o({currentFile:h,expressionPath:y,sourceInfo:P,readFile:b,exists:S,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:v,visited:C});if(!F||F.kind==="external")return null;let R=await c({currentFile:h,expressionPath:y,provenance:F,readFile:b,exists:S,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:v,visited:C});if(!R||R.kind!=="static")return null;if(F.collectionPathMap?.length){let T=NR(R.value,F.collectionPathMap);if(T)return{kind:"static",file:F.file,root:F.root,value:T.value,sourceKind:F.sourceKind,collectionPathMap:T.collectionPathMap}}let N=Qe(R.value,F.path);return Array.isArray(N)?{kind:"static",file:F.file,root:F.root,value:N,sourceKind:F.sourceKind,pathPrefix:F.path,collectionIndexMap:F.collectionIndexMap,collectionPathMap:F.collectionPathMap}:null}return null}async function c(m){let{provenance:h}=m;if(h.root.kind==="binding"){let v=m.expressionPath.scope.getBinding(h.root.name);if(!v&&h.file!==m.currentFile){let C=await Tt(h.file,m.readFile,m.fileCache);v=C.ast?To(C.ast).getBinding(h.root.name):void 0}return v?await t({currentFile:h.file,binding:v,readFile:m.readFile,exists:m.exists,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:m.fileCache,visited:m.visited}):null}if(h.root.kind!=="expression")return null;let y=await Tt(h.file,m.readFile,m.fileCache);if(!y.ast)return null;let b=Tg(y.ast,h.root.sourceRange);if(!b)return null;let S=await n(b.node,b.scope,h.file,m.readFile,m.exists,m.fileCache,m.visited);return S===void 0?null:{kind:"static",file:h.file,root:h.root,value:S,sourceKind:h.sourceKind}}async function l(m){return await u(m)??await d(m)??await f(m)}async function u(m){let{callPath:h}=m,y=h.node.callee;if(!Y.isMemberExpression(y)||!Y.isIdentifier(y.property)||y.property.name!=="filter")return null;let b=h.get("callee");if(!b.isMemberExpression())return null;let S=b.get("object");if(Array.isArray(S)||!S.isExpression())return null;let v=await a({currentFile:m.currentFile,expressionPath:S,readFile:m.readFile,exists:m.exists,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:m.fileCache,visited:m.visited});if(!v||!Array.isArray(v.value))return null;let[C]=h.node.arguments;if(!Y.isArrowFunctionExpression(C)&&!Y.isFunctionExpression(C))return null;let P=C.params[0];if(!Y.isIdentifier(P))return null;let F=RR(C);if(!F)return null;let R=[],N=[],T=[];for(let[L,q]of v.value.entries()){let W=wR(F,P.name,q);if(typeof W!="boolean")return null;if(W){R.push(q),N.push(v.collectionIndexMap?.[L]??L);let oe=v.collectionPathMap?.[L];oe&&T.push(oe)}}return{...v,value:R,pathPrefix:v.pathPrefix,collectionIndexMap:N,...T.length>0?{collectionPathMap:T}:{}}}async function d(m){let{callPath:h}=m,y=h.node.callee;if(!Y.isMemberExpression(y)||!Y.isIdentifier(y.property)||y.property.name!=="slice")return null;let b=h.get("callee");if(!b.isMemberExpression())return null;let S=b.get("object");if(Array.isArray(S)||!S.isExpression())return null;let v=await a({currentFile:m.currentFile,expressionPath:S,readFile:m.readFile,exists:m.exists,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:m.fileCache,visited:m.visited});if(!v||!Array.isArray(v.value))return null;let[C,P]=h.node.arguments,F=Dg(C,0),R=Dg(P,v.value.length);if(F===null||R===null)return null;let N=Math.max(0,F<0?v.value.length+F:F),T=Math.max(0,R<0?v.value.length+R:R),L=v.value.map((W,oe)=>v.collectionIndexMap?.[oe]??oe).slice(N,T),q=v.collectionPathMap?.slice(N,T);return{...v,value:v.value.slice(N,T),pathPrefix:v.pathPrefix,collectionIndexMap:L,...q?{collectionPathMap:q}:{}}}async function f(m){let{callPath:h}=m,y=h.node.callee;if(!Y.isMemberExpression(y)||!Y.isIdentifier(y.property)||y.property.name!=="sort"&&y.property.name!=="toSorted")return null;let b=h.get("callee");if(!b.isMemberExpression())return null;let S=b.get("object");if(Array.isArray(S)||!S.isExpression())return null;let v=await a({currentFile:m.currentFile,expressionPath:S,readFile:m.readFile,exists:m.exists,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:m.fileCache,visited:m.visited});if(!v||!Array.isArray(v.value))return null;let[C]=h.node.arguments;if(!Y.isArrowFunctionExpression(C)&&!Y.isFunctionExpression(C))return null;let[P,F]=C.params;if(!Y.isIdentifier(P)||!Y.isIdentifier(F))return null;let R=v.value.map((T,L)=>({value:T,sourceIndex:v.collectionIndexMap?.[L]??L,originalIndex:L})),N=[...R];for(let T of R)for(let L of R)if(Bg(C,P.name,F.name,T.value,L.value)===void 0)return null;return N.sort((T,L)=>{let q=Bg(C,P.name,F.name,T.value,L.value)??0;return q===0?T.originalIndex-L.originalIndex:q}),{...v,value:N.map(T=>T.value),pathPrefix:v.pathPrefix,collectionIndexMap:N.map(T=>T.sourceIndex),...v.collectionPathMap?{collectionPathMap:N.map(T=>v.collectionPathMap?.[T.originalIndex]).filter(T=>!!T)}:{}}}async function g(m){let h=null,y=!1,b,S=[];for(let C of m.segments){if(C.kind!=="dynamic")continue;let P=await r({expression:C.expression,scope:m.expressionPath.scope,source:m.fileCache.get(m.currentFile)?.source,currentFile:m.currentFile,readFile:m.readFile,exists:m.exists,fileCache:m.fileCache,visited:m.visited});if(!P)return null;let F=Dl(m.expressionPath,P.base),R;if(F){y=!0;let N=await s({currentFile:m.currentFile,callPath:F.callPath,readFile:m.readFile,exists:m.exists,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:m.fileCache,visited:m.visited});if(!N||!Array.isArray(N.value))return null;R=N.value.map((T,L)=>{let q=Qe(N.value,[{kind:"index",index:L},...F.basePath,...P.path]);return jg(q)}),b??=N.collectionIndexMap}else{let N=await i({...m,sourceInfo:P});if(!N)return null;R=N.map(jg)}if(R.some(N=>N===null)||h!==null&&h!==R.length)return null;h=R.length,S.push(R)}if(h===null||h===0)return null;let v=[];for(let C=0;C<h;C+=1){let P=[...m.rootPath],F=0;for(let R of m.segments){if(R.kind==="dynamic"){let N=S[F]?.[C];if(!N)return null;P.push(N),F+=1;continue}P.push({...R})}v.push(P)}return{sourceKind:y||h>1?"repeat-template":"binding",...b?{collectionIndexMap:b}:{},collectionPathMap:v}}return{resolveRepeatCollectionTarget:s,resolveCollectionCallTarget:l,resolveDynamicMemberPathMap:g}}var{normalizeExpressionWithScope:PR,evaluateStaticExpression:Rs}=Ig({resolveBindingTarget:e=>ws(e)}),{resolveRepeatCollectionTarget:AR,resolveCollectionCallTarget:TR,resolveDynamicMemberPathMap:FR}=Jg({resolveBindingTarget:e=>ws(e),evaluateStaticExpression:Rs,buildExpressionSourceInfo:Xt,resolveSourceInfoProvenance:vt,resolveComponentPropValues:e=>OR(e)}),{resolveExportValue:_R,resolveComponentPropBinding:MR,resolveComponentPropValues:OR,resolveBindingTarget:ws}=Lg({resolveExternalExpression:Jl,resolveCollectionCallTarget:TR,evaluateStaticExpression:Rs,resolveSourceInfoProvenance:vt,buildExpressionSourceInfo:Xt});function qg(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}var Xg=new WeakMap;function LR(e){let t=Xg.get(e);return t||(t=new WeakMap,Xg.set(e,t)),t}function zg(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 eh(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=ks(s,t,n);if(!a)return null;let c=Is(a,r.sourceRange);if(!c)return null;let l=await Xt({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!l){let f=await Hl({currentFile:t,expressionPath:c,readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:new Set});return f?$l(f,wr(c.node,n)):null}let u=new Set,d=await ow({currentFile:t,expressionPath:c,segment:{...r,source:l},readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:u});return d?$l(d,l.expression):null}async function Pr(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=ks(i,t,n);if(!s)return null;let a=e.sourceRange?Is(s,e.sourceRange):e.expression!==void 0?Ao(s,n,e.expression):null;if(!a)return null;let c=Ns(a);if(!c.isIdentifier()&&!c.isMemberExpression())return null;let l=new Set,u=await Xt({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:l}),d=u?await vt({currentFile:t,expressionPath:c,sourceInfo:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:l}):await ch({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 $l(d,e.expression??wr(c.node,n))}async function Ul(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=ks(i,t,n);if(!s)return mt("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?DR({file:t,source:n,ast:s,segment:e.target.segment,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:a}):BR({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}async function Xt(e){if(ne.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!ne.isMemberExpression(e.expression))return null;let t=await PR(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:wr(e.expression,e.source),base:t.base,path:t.path}:null}function $l(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 DR(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=Is(r,o.sourceRange),u=l?await Xt({expression:l.node,scope:l.scope,source:n,currentFile:t,readFile:i,exists:s,fileCache:a,visited:c}):null;if(!u){if(!l||l.isStringLiteral()||l.isTemplateLiteral()&&l.node.expressions.length===0)return Wg(t,o.value);let f=await Hl({currentFile:t,expressionPath:l,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});return f?f.kind==="external"?Qg(t,f):Kl(t,wr(l.node,n),f):jR({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return mt("unsupported-expression","Unable to locate text expression for provenance resolution");let d=await vt({currentFile:t,expressionPath:l,sourceInfo:u,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});if(!d){let f=Vl(l.node);if(f)return mt(f.code,f.message);let g=l.scope.getBinding(u.base);if(g?.path.isVariableDeclarator()){let m=Vl(g.path.node.init);if(m)return mt(m.code,m.message)}return g?.path.isVariableDeclarator()&&ne.isCallExpression(g.path.node.init)?$R("unsupported-expression",ih(g.path.node.init,e.functionCallContracts)):mt("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return d.kind==="external"?Qg(t,d):Kl(t,u.expression,d)}async function BR(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return mt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=Ao(r,n,o.conditionExpression);if(!l)return mt("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await vt({currentFile:t,expressionPath:l,sourceInfo:o.conditionSource,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});if(!u)return mt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(u.kind==="external")return mt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let d=Kl(t,o.conditionExpression,u);return d.finalSource?{...d,finalSource:{...d.finalSource,kind:"conditional-branch",displayPath:o.conditionExpression},chain:[...d.chain,{kind:"conditional-branch",file:u.file,displayName:o.conditionExpression,canEditHere:!0}]}:d}function Wg(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 jR(e){let t=await nh(e);if(t.length===0)return mt("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(VR(e.expression))return th(t);if(oh(e.expression))return mt("unsupported-expression","i18n helpers require a static message id string");if(ne.isMemberExpression(e.expression)&&e.expression.computed&&!ne.isNumericLiteral(e.expression.property)&&!ne.isStringLiteral(e.expression.property))return mt("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return mt(n.code,n.message)}function mt(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function $R(e,t){return th([{code:e,message:t}])}function th(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function VR(e){return ne.isCallExpression(e)||ne.isConditionalExpression(e)||ne.isLogicalExpression(e)||ne.isBinaryExpression(e)}function _o(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 nh(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=Vl(t);if(l)return[l];if(ne.isCallExpression(t))return[{code:"unsupported-expression",message:ih(t,c)}];if(ne.isMemberExpression(t)&&t.computed){let u=t.property;if(!ne.isNumericLiteral(u)&&!ne.isStringLiteral(u)){if(!ne.isExpression(u))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let f=await Rs(u,n,r,o,i,s,a);if(typeof f!="string"&&!Number.isInteger(f))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}]}}return ne.isBinaryExpression(t)?_o([...await Bl(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):ne.isLogicalExpression(t)?_o([...await Bl(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"}]):ne.isConditionalExpression(t)?_o([...await Bl(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 Vl(e){return oh(e)?Hg("i18n helpers require a static message id string"):zR(e)?Hg("CMS helpers require static entry id and field path string arguments"):null}async function Bl(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await nh({...t,expression:o}));return r}function KR(e,t){let n=(t??[]).filter(r=>r.sourceType===e.sourceType&&(r.capabilities===void 0||r.capabilities.includes("write-text")));if(e.adapterId){let r=n.find(o=>o.adapterId===e.adapterId);if(r)return{adapterId:r.adapterId,editMode:"proxy",diagnostics:[]}}else if(n.length>0)return{adapterId:n[0]?.adapterId,editMode:"proxy",diagnostics:[]};return{adapterId:void 0,editMode:"readonly",diagnostics:[UR(e.sourceType)]}}async function Jl(e){for(let n of YR){if(!Gg(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return Zg(Yg(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(!Gg(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return Zg(Yg(r),e.externalAdapters)}return null}function UR(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function JR(e){return{code:"external-source-readonly",message:e}}function Hg(e){return{code:"unsupported-expression",message:e}}function Xl(e){return!e||!ne.isCallExpression(e)?null:ne.isIdentifier(e.callee)?e.callee.name:ne.isMemberExpression(e.callee)&&!e.callee.computed&&ne.isIdentifier(e.callee.object)&&ne.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function Gg(e,t){if(!t||t.length===0)return!0;let n=Xl(e.node);return n?t.includes(n):!1}function Yg(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:_o(e.diagnostics??[])}:{match:e,diagnostics:[]}}function Zg(e,t){let n=KR(e.match,t);return{kind:"external",file:e.match.file,sourceType:e.match.sourceType,sourceId:e.match.sourceId,adapterId:e.match.adapterId??n.adapterId,displayPath:e.match.displayPath,editMode:e.editMode==="readonly"?"readonly":n.editMode,diagnostics:_o([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function XR(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!ne.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!ne.isStringLiteral(n)||!ne.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 zR(e){return!!e&&ne.isCallExpression(e)&&ne.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!ne.isStringLiteral(e.arguments[0])||!ne.isStringLiteral(e.arguments[1]))}function rh(e){if(!(!e||!ne.isCallExpression(e))){if(ne.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&ne.isStringLiteral(t)?t.value:null}if(ne.isMemberExpression(e.callee)&&!e.callee.computed&&ne.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&ne.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!ne.isObjectExpression(t))return null;for(let n of t.properties)if(ne.isObjectProperty(n)&&!n.computed&&(ne.isIdentifier(n.key)&&n.key.name==="id"||ne.isStringLiteral(n.key)&&n.key.value==="id")&&ne.isStringLiteral(n.value))return n.value.value;return null}}}function oh(e){return rh(e)===null}async function WR(e,t,n){let r=new Set,o=Fo.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=Fo.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"]:[Fo.posix.join(i,"locales"),Fo.posix.join(i,"messages")];for(let a of s){let c=Fo.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function HR(e){let t=rh(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await WR(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function GR(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!ne.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!ne.isExpression(n))return null;let o=await Rs(n,e.expressionPath.scope,e.currentFile,e.readFile,e.exists,e.fileCache,e.visited);if(typeof o!="string"||o.length===0)return null;let i={sourceType:"api-field",sourceId:o,file:`api://${o}`,displayPath:o};return r?{match:i,editMode:"readonly",diagnostics:[JR("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var YR=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>XR(e)},{helperNames:["apiField"],resolve:e=>GR(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>HR({currentFile:e,expressionPath:t,exists:n})}];function zl(e){return{...e,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Derived display values are readonly because no identity-preserving write target exists"}]}}function Qg(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 Kl(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=rw(n),s;n.semanticKind?s=n.semanticKind:i?s="config-entry":n.sourceKind==="repeat-template"?s="repeat-template":n.path.length===0?s=n.sourceKind==="imported-binding"?"imported-binding":"binding":s=o?"array-item":"object-field";let a=n.displayExpression??t,c=[...n.chainPrefix??[]];return n.sourceKind==="binding"?c.push({kind:"binding",file:n.file,displayName:n.root.kind==="binding"?n.root.name:a,canEditHere:n.editMode!=="readonly"}):n.sourceKind==="imported-binding"?c.push({kind:"imported-binding",file:n.file,displayName:n.root.kind==="named-export"?n.root.name:"default",canEditHere:n.editMode!=="readonly"}):n.sourceKind==="repeat-template"&&c.push({kind:"repeat-template",file:n.file,displayName:t,canEditHere:n.editMode!=="readonly"}),n.path.length>0&&n.sourceKind!=="repeat-template"&&c.push({kind:o?"array-item":"object-field",file:n.file,displayName:a,canEditHere:n.editMode!=="readonly"}),i&&c.push({kind:"config-entry",file:n.file,displayName:i.displayPath,canEditHere:n.editMode!=="readonly"}),{finalSource:{kind:s,file:n.file,locator:r,root:n.root,path:n.path,displayPath:a,externalSource:i?{sourceType:"config-entry",sourceId:i.sourceId}:void 0},chain:n.editMode==="readonly"?c.map(l=>({...l,canEditHere:!1})):c,confidence:n.sourceKind==="repeat-template"?"safe-derived":"exact",editMode:n.editMode??(n.file===e?"direct":"proxy"),diagnostics:n.diagnostics??[]}}var ZR=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function Wl(e,t){let n=[...ZR,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function ih(e,t){let n=e.callee;return ne.isIdentifier(n)&&Wl(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 Hl(e){let t=await Jl(e);if(t)return t;let n=await sh({...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 Xt({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 vt({...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 tw(e)}async function sh(e){let t=await Ft({...e,allowComposed:!1});if(t?.kind!=="source")return null;let n=Ns(e.expressionPath);return n.isIdentifier()||n.isMemberExpression()?t.provenance:zl(t.provenance)}async function Ft(e){let t=Ns(e.expressionPath),n=ew(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 Xt({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 vt({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 Xt({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 vt({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 Ft({...e,expressionPath:r,allowComposed:!0}),a=await Ft({...e,expressionPath:o,allowComposed:!1}),c=await Ft({...e,expressionPath:i,allowComposed:!1});return jl(s,a,c)}if(t.isCallExpression())return QR({...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 Ft({...e,expressionPath:r,allowComposed:!0}),s=await Ft({...e,expressionPath:o,allowComposed:!0});return jl(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 Ft({...e,expressionPath:r,allowComposed:!0}),s=await Ft({...e,expressionPath:o,allowComposed:!0});return jl(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:Ft({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function Ns(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 QR(e){let t=Xl(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:Ft({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(ne.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:Ft({...e,expressionPath:o,allowComposed:!1})}}return null}function jl(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!qR(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function qR(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 ew(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function tw(e){if(!e.expressionPath.isCallExpression())return null;let t=Xl(e.expressionPath.node);if(!t)return null;let n=Wl(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 ah({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?zl(i):null}async function ah(e){let t=await Jl({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 Xt({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 vt({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 Hl({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 nw(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!ne.isCallExpression(t))return null;let n=t.callee;if(!ne.isIdentifier(n))return null;let r=Wl(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 ah({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?zl(a):null}function rw(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=Nr(t,e.path);return{sourceId:o,displayPath:o}}async function ow(e){let t=e.segment.source;return t?vt({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 vt(e){let t=e.sourceInfo,n=Dl(e.expressionPath,t.base);if(n){let l=await AR({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=$g(n.callPath,[...n.basePath,...t.path]);return go(h)?zg(e.currentFile,h.sourceId,h.displayPath):null}let u=Ug(l,[...n.basePath,...t.path]),d=l.collectionIndexMap?.[0]??0,f=[...l.pathPrefix??[],{kind:"index",index:d},...n.basePath,...t.path],g=[{kind:"index",index:0},...n.basePath,...t.path];return Qe(l.value,g)===void 0?null:{kind:"value",file:l.file,root:l.root,path:u?.[0]??f,sourceKind:"repeat-template",collectionIndexMap:l.collectionIndexMap,...u?{collectionPathMap:u}:{}}}let r=e.expressionPath.scope.getBinding(t.base);if(!r)return null;if(r.path.isImportNamespaceSpecifier()){let l=t.path[0],u=r.path.parentPath;if(!l||l.kind!=="property"||!u?.isImportDeclaration())return null;let d=await Cn(e.currentFile,u.node.source.value,e.exists);if(!d)return null;let f=await _R({file:d,exportName:l.name,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(!f||f.kind==="external")return null;let g=t.path.slice(1);return Qe(f.value,g)===void 0?null:{kind:"value",file:f.file,root:f.root,path:g,sourceKind:"imported-binding",collectionIndexMap:f.collectionIndexMap}}let o=Ap(r);if(o){let l=o.expressionPath,u=await Xt({expression:l.node,scope:l.scope,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(u){let d=await vt({...e,expressionPath:l,sourceInfo:{...u,expression:Nr(u.expression,t.path),path:[...u.path,...t.path]}});if(d)return d}else if(r.constant){let d=`dynamic-alias:${e.currentFile}:${l.node.start}`;if(e.visited.has(d))return null;e.visited.add(d);try{let f=await ch({...e,expressionPath:Ns(l),memberSuffix:t.path});if(f?.kind==="value")return f}finally{e.visited.delete(d)}}if(t.path.length===0){let d=await sh({currentFile:e.currentFile,expressionPath:l,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(d)return d}}if(r.kind==="param")return MR({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 nw({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=Yi(r,t.path,LR(e.fileCache));if(go(s))return zg(e.currentFile,s.sourceId,s.displayPath);let a=await ws({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 ch(e){let t=Vg(e.expressionPath.node);if(!t||!Kg(t.segments))return null;let n=await vt({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 FR({...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 ws({...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:r.sourceKind,displayExpression:wr(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:o}}async function lh(e){let t=iw(e.propertyName);if(t.owner==="blocked")return vn(t.owner,t.diagnostic);if(t.owner==="class-name-source"||t.owner==="style")return vn(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 vn("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 aw(e,l)});o.sort((l,u)=>l.order-u.order);let s=o.at(-1);if(!s)return{status:"missing",owner:"generic"};if(o.filter(l=>l.kind==="spread"&&l.order>s.order).some(l=>!l.target))return vn("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}:vn("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?vn("generic",{code:"remove-exposes-spread",message:`Removing '${e.propertyName}' would expose an earlier spread source`}):sw(e,s.attribute)}async function sw(e,t){if(t.resolution&&t.resolution.status!=="resolved"&&!t.source){let r=await Pr({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}}:vn("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 Pr({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"?vn("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 aw(e,t){let n=t.source?.expression;if(!n)return;let r=await Pr({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:cw(r,e.propertyName)}}function cw(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 vn(e,t){return{status:"blocked",owner:e,...t?{diagnostic:t}:{}}}function uh(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(Xn(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=>fw(a,r.componentName)),s=i.length===1?i[0].identity.key:null;return o.keys.set(r.componentName,s),s};return r=>lw({...r,graph:e},n)}function lw(e,t){let{key:n,element:r,graph:o,provenances:i}=e,s=dw(n,r,o,t),a=s?.tag??(Xn(r.tag)?r.tag:r.componentName),c=s?.identity.key??t(r,o)??n,l=mw(s),u=gw(n,r,o,i,s),d=uw(n,r,o,i,c);return{componentName:a,instanceKey:c,templateOwner:pw(s??r,a),...l.length>0?{variantKeys:l}:{},...u.length>0?{slotKeys:u}:{},editableStrategy:d,impactScope:hw(d),alternativeStrategies:yw(d)}}function uw(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return Gl(e,n)?"instance":!Xn(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function dw(e,t,n,r){if(Xn(t.tag))return t;let o=Gl(e,n);if(o)return o;let i=r(t,n);return i?n.elements.get(i)??null:null}function fw(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function pw(e,t){return Xn(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function mw(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 gw(e,t,n,r,o){let i=new Set,s=Gl(e,n);s&&o?.identity.key===s.identity.key&&i.add("children");for(let a of r.values()){let c=a?.chain.find(u=>u.kind==="component-prop");if(!c)continue;let l=c.displayName.split(".").pop();l&&i.add(l)}return i.size===0&&Xn(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function Gl(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(Xn(r.tag))return r;n=r.parentKey}return null}function Xn(e){return/^[A-Z]/.test(e)}function hw(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function yw(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}function ph(e){let t=e.isRepeat??(e.graph?Rw(e.element,e.graph):!1),n=e.propertyProvenance??new Map,r=e.repeatTargets??new Map,o=Cw(e.element.attributes??[]),i=[...r.values()].some(u=>u.ok),s=o.map(u=>xw({attribute:u,element:e.element,isRepeat:t,selectionRef:e.selectionRef,provenance:n.get(u.name),repeatTarget:r.get(u.name)})),a=(e.element.attributeSpreads?.length??0)>0,c=(e.element.attributeSpreads??[]).slice().sort((u,d)=>u.order-d.order).map(u=>({raw:u.raw,sourceRange:ww(u.sourceRange,e.source),order:u.order,diagnostics:u.source?[]:[{code:"unsupported-spread-source",message:"The spread source cannot be resolved safely, so property ownership is conservative."}]})),l=t&&e.selectionRef?.instanceIndex!==void 0&&i;return{documentVersion:e.documentVersion,...e.selectionRef?{selectionRef:e.selectionRef}:{},items:s,spreads:c,creation:t?{selection:l?"materialize":"unsupported",template:"unsupported"}:{selection:a?"unsupported":"direct",template:a?"unsupported":"direct"}}}function xw(e){let{attribute:t,provenance:n,repeatTarget:r}=e,o=e.selectionRef?.instanceIndex!==void 0&&r?.ok===!0?r:null,i=bw(t,n,e.isRepeat),s=["selection","template"].map(y=>({scope:y,result:is({state:n,scope:y,operation:"set",selectionRef:e.selectionRef,isRepeat:e.isRepeat,repeatTarget:r})})),a=s.find(({result:y})=>y.ok)?.result,c=a?.ok?a.target:void 0,l=c?.kind==="value-binding"&&o&&(JSON.stringify(c.locator.root)!==JSON.stringify(o.selectedParentObjectLocator.root)||JSON.stringify(c.locator.path??[])!==JSON.stringify([...o.selectedParentObjectLocator.path??[],{kind:"property",name:t.name}]))?null:o,u=Sw(t,n,l,e.isRepeat),d=c?kw(c,e.element,t.name):void 0,f=s.filter(({result:y})=>y.ok).map(({scope:y})=>y),g=f.length>0?vw(n,o,e.element):"unsupported",m=o?"repeat-item":e.isRepeat?"repeat-template":"node",h=Iw(t,n,r);if(f.length===0&&h.length===0){let y=s.find(({result:b})=>!b.ok)?.result;y&&!y.ok&&h.push({code:y.code,message:y.reason})}return{name:t.name,source:i,resolution:u,editMode:g,sourceScope:m,allowedWriteScopes:f,...d?{effectiveWriteTarget:d}:{},diagnostics:h}}function bw(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 Sw(e,t,n,r){return n?dh(n.selectedResolution):t?.status==="blocked"?{status:"unresolved"}:r&&t?.status==="binding"?{status:"unresolved"}:dh(Ew(e))}function Ew(e){return e.resolution?e.resolution:e.syntaxKind==="boolean-shorthand"?{status:"resolved",value:!0}:e.resolvedValue!==void 0?{status:"resolved",value:e.resolvedValue}:e.source?{status:"unresolved"}:{status:"resolved",value:e.value}}function dh(e){return!e||e.status==="unresolved"?{status:"unresolved"}:e.status==="undefined"?{status:"undefined"}:{status:"resolved",value:e.value}}function vw(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 kw(e,t,n){return e.kind==="repeat-property"?{kind:"value-path",file:e.target.sourceFile,isProxy:e.target.sourceFile!==t.sourceFile,displayPath:fh({...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:fh(e.locator)}:{kind:"jsx-node",file:t.sourceFile,isProxy:!1,displayPath:t.componentName+" > "+n}}function Iw(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 Cw(e){let t=new Set;return e.filter(n=>t.has(n.name)?!1:(t.add(n.name),!0))}function Rw(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 fh(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 ww(e,t){if(!t)return{start:e.startColumn,end:e.endColumn};let n=t.split(`
5
+ `),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 Nw(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var Pw=160;function mh(e,t,n,r={}){let o=ir(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 gh(e,t,n,r,o,i,s,a,c,l,u){let d=ir(t),f=t.elements.get(e),g=n.nodes.get(e),m=r.get(e);if(!f||!g||!m)throw new Error(`Node not found: ${e}`);let h=Sh(f.textSegments,s),y=Eh(e,t,f,m,h),b=h?_w(h):void 0,S=Mw(i,h),v=f.textSegments.map(R=>({index:R.index,value:R.value,editable:vh(R,m,s?.get(R.index)??null),source:o.get(R.index)??null})),C=xh(f,t),P=f.childKeys.map(R=>{let N=t.elements.get(R);return N?{key:R,tag:N.tag,label:N.tag}:null}).filter(R=>R!==null),F=[];if(f.parentKey){let R=t.elements.get(f.parentKey);if(R)for(let N of R.childKeys){if(N===e)continue;let T=t.elements.get(N);T&&F.push({key:N,tag:T.tag,label:T.tag})}}return{composition:d,key:e,tag:f.tag,componentName:f.componentName,sourceFile:f.sourceFile,sourceLocator:yh(f),label:f.tag,capabilities:y,writeTarget:i,effectiveWriteTarget:S,provenanceChain:b,componentSemantic:c,styleSource:l,conditional:a,...u?{dynamicData:u}:{},textSegments:v,boundaryKind:f.boundaryKind,isOpaque:f.isOpaque,ancestors:C,children:P,siblings:F}}function hh(e,t,n,r,o,i,s,a){let c=ir(t),l=t.elements.get(e),u=n.nodes.get(e),d=r.get(e);if(!l||!u||!d)throw new Error(`Node not found: ${e}`);let f=Sh(l.textSegments,i),g=Aw(l);return{composition:c,key:e,tag:l.tag,...g?{linkSourceKind:g}:{},componentName:l.componentName,sourceFile:l.sourceFile,sourceLocator:yh(l),label:l.tag,capabilities:Eh(e,t,l,d,f),provenanceChain:f?{editMode:f.editMode,diagnostics:f.diagnostics.map(m=>({code:m.code,message:m.message}))}:void 0,...s?{dynamicData:s}:{},...a?{properties:a}:{},textSegments:l.textSegments.map(m=>{let h=o.get(m.index);return{index:m.index,editable:vh(m,d,i?.get(m.index)??null),source:h?{kind:h.kind}:null}}),boundaryKind:l.boundaryKind,isOpaque:l.isOpaque,ancestors:xh(l,t)}}function Aw(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 yh(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:Tw(e.sourceRange),structuralPath:e.identity.structuralPath,...Fw(e.textSegments)}}function xh(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 Tw(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function Fw(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,Pw)}:{}}function bh(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 Sh(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function Eh(e,t,n,r,o){let i=n.identity.structuralPath.includes("#repeat:"),s=t.regions.some(u=>u.kind==="repeat-region"&&u.childKeys.includes(e)),a=o?.diagnostics.find(u=>u.code==="missing-adapter"||u.code==="external-source-readonly")?.code,c=r.canUpdateText?{mode:o?.editMode??"direct",reasonCode:a??(o?.editMode==="upstream"?"component-prop":o?.finalSource?.kind==="repeat-template"?"repeat-item-data":void 0)}:{mode:"unsupported",reasonCode:"capability-denied"},l=r.canUpdateText&&kh(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 vh(e,t,n){return!e.editable||!t.canUpdateText?!1:n?kh(n.editMode):!0}function kh(e){return e==="direct"||e==="proxy"||e==="upstream"}function _w(e){return{finalSource:e.finalSource?{kind:e.finalSource.kind,file:e.finalSource.file,displayPath:e.finalSource.displayPath,externalSource:e.finalSource.externalSource}:null,chain:e.chain.map(t=>({kind:t.kind,file:t.file,displayName:t.displayName,canEditHere:t.canEditHere})),confidence:e.confidence,editMode:e.editMode,diagnostics:e.diagnostics.map(t=>({code:t.code,message:t.message}))}}function Mw(e,t){return t?.finalSource?t.finalSource.kind==="jsx-literal"?{kind:"jsx-node",file:e.file,isProxy:e.isProxy}:t.finalSource.kind==="config-entry"&&t.finalSource.locator?{kind:"value-path",file:t.finalSource.file,isProxy:t.finalSource.file!==e.file,displayPath:t.finalSource.displayPath}:Nw(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 Yl=["set-class-name-source","apply-style-draft"];function Ih(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:Yl,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:Yl,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:Yl}}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}),Rh(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function Rh(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}),Rh(s,t,n,r,o))}}import wh from"node:path";function Ql(){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=Bw(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 Ps(e){let t=()=>Ow(e);return e.mutex?e.mutex.runExclusive(t):t()}async function Ow(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=Lw(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 Zl({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 Zl({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 Zl({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 Nh("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return Nh("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 Lw(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 Zl(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:Dw(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 Nh(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function Dw(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 Bw(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)||wh.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=wh.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 jw=50,$w=8*1024*1024;function _h(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??jw),s=Math.max(0,t.maxUndoBytes??$w);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:u,redo:d};async function a(R){let N=[...R.steps].sort((D,Z)=>D.order-Z.order),T=N.filter(D=>D.type!=="invoke-external-adapter");if(T.length!==N.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let L=new Set(T.map(D=>D.file)),q=await S(L),W=new Map(q.map(D=>[D.file,D.exists===!1?"":D.content])),oe;for(let D of T){let Z=Fh(D,W.get(D.file)??"");if(!Z.ok)return{ok:!1,errorCode:Z.errorCode,reason:Z.reason};W.set(D.file,Z.source),oe=Z.selectionRef??oe}return{ok:!0,filePlan:{operationId:R.operationId,kind:"source-edit",target:R.target,documentVersion:R.documentVersion,conflictPolicy:"compare-and-swap",edits:[...W].map(([D,Z])=>({operation:"upsert",file:D,content:Z,baseContentHash:q.find(fe=>fe.file===D)?.sha256??null}))},...oe?{selectionRef:oe}:{}}}async function c(R){let N=[...R.steps].sort((fe,ct)=>fe.order-ct.order),T=N.filter(fe=>fe.type!=="invoke-external-adapter"),L=N.filter(fe=>fe.type==="invoke-external-adapter"),q=new Set(T.map(fe=>fe.file));if(T.length>0&&L.length>0)return{ok:!1,operationId:R.operationId,errorCode:"unsupported-operation",reason:"Mixed local file rewrites and external adapter writes require an explicit compensation contract.",rolledBack:!1};if(T.length===0)return y(R,L);let W=await S(q),oe=new Map;for(let fe of W)oe.set(fe.file,fe.exists===!1?"":fe.content);let D;for(let fe of T){let ct=oe.get(fe.file)??"",rt=Fh(fe,ct);if(!rt.ok)return{ok:!1,operationId:R.operationId,errorCode:rt.errorCode,reason:rt.reason,rolledBack:!1};oe.set(fe.file,rt.source),rt.selectionRef&&(D=rt.selectionRef)}let Z=await C([...oe].map(([fe,ct])=>({file:fe,content:ct,exists:!0,version:0,sha256:Re(ct)})),W);return Z.ok===!1?{ok:!1,operationId:R.operationId,errorCode:Z.rolledBack?"writeback-failed":"rollback-failed",reason:Z.reason,rolledBack:Z.rolledBack}:(n.push({operationId:R.operationId,preSnapshots:W,postSnapshots:Z.snapshots,plan:R}),f(),r.length=0,{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:Math.max(...Z.snapshots.map(fe=>fe.version)),affectedFiles:[...q],...D?{selectionRef:D}:{}})}async function l(R){let N=new Set(R.edits.map(Z=>Z.file)),T=await S(N),L=b(R,T);if(L)return{ok:!1,operationId:R.operationId,errorCode:"stale-version",reason:L.reason,affectedFiles:[L.file],rolledBack:!1};let q=new Map(T.map(Z=>[Z.file,Z])),W=R.edits.find(Z=>Z.operation==="create-only"&&q.get(Z.file)?.exists!==!1);if(W)return{ok:!1,operationId:R.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${W.file}`,affectedFiles:[W.file],rolledBack:!1};let oe=R.edits.map(Z=>Z.operation==="delete"?{file:Z.file,content:"",exists:!1,version:0}:{file:Z.file,content:Z.content,exists:!0,version:0,sha256:Re(Z.content)}),D=await C(oe,T,new Set(R.edits.filter(Z=>Z.operation==="create-only").map(Z=>Z.file)));return D.ok===!1?{ok:!1,operationId:R.operationId,errorCode:D.rolledBack?"writeback-failed":"rollback-failed",reason:D.reason,rolledBack:D.rolledBack}:(n.push({operationId:R.operationId,preSnapshots:T,postSnapshots:D.snapshots,plan:{operationId:R.operationId,kind:R.kind,target:R.target,documentVersion:R.documentVersion,steps:[],preSnapshots:T}}),f(),r.length=0,{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:Math.max(...D.snapshots.map(Z=>Z.version)),affectedFiles:[...N]})}async function u(){let R=n.at(-1);if(!R)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let N=await C(R.preSnapshots,R.postSnapshots);return N.ok===!1?{ok:!1,operationId:R.operationId,errorCode:N.rolledBack?"writeback-failed":"rollback-failed",reason:N.reason,rolledBack:N.rolledBack}:(n.pop(),r.push(R),{ok:!0,operationId:R.operationId,kind:R.plan.kind,target:R.plan.target,resultVersion:Math.max(...N.snapshots.map(T=>T.version)),affectedFiles:R.preSnapshots.map(T=>T.file)})}async function d(){let R=r.at(-1);if(!R)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let N=await C(R.postSnapshots,R.preSnapshots);return N.ok===!1?{ok:!1,operationId:R.operationId,errorCode:N.rolledBack?"writeback-failed":"rollback-failed",reason:N.reason,rolledBack:N.rolledBack}:(r.pop(),n.push(R),f(),{ok:!0,operationId:R.operationId,kind:R.plan.kind,target:R.plan.target,resultVersion:Math.max(...N.snapshots.map(T=>T.version)),affectedFiles:R.postSnapshots.map(T=>T.file)})}function f(){for(;n.length>i;)n.shift();for(;n.length>0&&g()>s;)n.shift()}function g(){return n.reduce((R,N)=>R+m(N),0)}function m(R){return h(R.preSnapshots)+h(R.postSnapshots)}function h(R){return R.reduce((N,T)=>N+T.file.length+T.content.length,0)}async function y(R,N){let T=[];for(let L of N){let q=L.capability??"write-text",W=o.find(D=>D.sourceType===L.sourceType&&(L.adapterId===void 0||D.adapterId===L.adapterId)&&(D.capabilities===void 0||D.capabilities.includes(q)));if(!W)return{ok:!1,operationId:R.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${L.sourceType}`,rolledBack:!1};let oe=await W.execute(L);if(!oe.ok)return{ok:!1,operationId:R.operationId,errorCode:"writeback-failed",reason:oe.reason??`External adapter failed for ${L.sourceType}`,rolledBack:!1};T.push(L.file)}return{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:0,affectedFiles:T}}function b(R,N){if(R.conflictPolicy!=="compare-and-swap")return null;let T=new Map(N.map(L=>[L.file,L]));for(let L of R.edits){if(L.operation==="create-only")continue;if(L.baseContentHash===void 0)return{file:L.file,reason:`Source file ${L.file} is missing baseContentHash. Reopen the file before saving.`};let q=T.get(L.file),W=L.baseContentHash;if(W===null){if(q?.exists!==!1)return{file:L.file,reason:`Source file ${L.file} was created or changed before save.`};continue}if(!W)return{file:L.file,reason:`Source file ${L.file} is missing baseContentHash. Reopen the file before saving.`};if(q?.exists===!1||q?.sha256!==W)return{file:L.file,reason:`Source file ${L.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function S(R){let N=[];for(let T of R)N.push(await v(T));return N}async function v(R){if(!await e.exists(R))return{file:R,content:"",version:0,exists:!1};let T=Math.max(1,e.getVersion(R)),L=await e.readFile(R);return{file:R,content:L,version:T,exists:!0,sha256:Re(L)}}async function C(R,N,T=new Set){let L=[];try{for(let q of R){if(T.has(q.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive(q.file,q.content)}else await P(q);let W=e.bumpVersion(q.file);L.push(q.file),q.version=W}}catch(q){let W=await F(N.filter(D=>L.includes(D.file)));if(W.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${W.failedFiles.join(", ")}: ${Th(q)}`,rolledBack:!1,instanceConflict:Ah(q)};let oe=Ah(q);return{ok:!1,reason:`${oe?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${Th(q)}`,rolledBack:!0,instanceConflict:oe}}return{ok:!0,snapshots:R.map(Vw)}}async function P(R){if(R.exists===!1){await e.deleteFile(R.file);return}await e.writeFile(R.file,R.content)}async function F(R){let N=[];for(let T of R)try{await P(T),e.bumpVersion(T.file)}catch{N.push(T.file)}return N.length===0?{ok:!0}:{ok:!1,failedFiles:N}}}function Ah(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function Vw(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:Re(e.content)}:{}}}function Th(e){return e instanceof Error?e.message:String(e)}function Fh(e,t){switch(e.type){case"invoke-external-adapter":return{ok:!1,reason:"External adapter steps must be executed asynchronously",errorCode:"unsupported-operation"};case"add-import":return He(rr({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return He(or({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return He(qn({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return He(er({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return He(si({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return He(Kr({source:t,locator:e.locator,next:e.value}));case"update-array-item":return He(Kr({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return He(pi({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return He(ci({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return He(mi({source:t,locator:e.locator,index:e.index}));case"move-array-item":return He(gi({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return He(tr({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return He(li({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 Kw(e,t);case"set-property-changes":return He(ui({source:t,locator:e.locator,changes:e.changes}));case"set-link-target":return He(di({source:t,locator:e.locator,link:e.link,changes:e.changes}));case"set-property-binding":return He(fi({source:t,locator:e.locator,name:e.name,object:e.object,property:e.property}));case"upsert-object-property":return He(yi({source:t,objectLocator:e.locator,name:e.name,value:e.value}));default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function Kw(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!_d(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!==Re(t))return{ok:!1,reason:"The source file changed before className save.",errorCode:"stale-version"};if(n.oldAttrRange){if(t.slice(n.oldAttrRange.start,n.oldAttrRange.end)!==n.oldAttrRaw)return{ok:!1,reason:"The className attribute changed before save.",errorCode:"stale-version"}}else if(n.oldAttrRaw!==null)return{ok:!1,reason:"The className attribute range no longer matches.",errorCode:"stale-version"};return{ok:!0,source:Fd({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function He(e){if(e.ok)return{ok:!0,source:e.source,...e.selectionRef?{selectionRef:e.selectionRef}:{}};switch(e.diagnostic.code){case"locator-miss":return{ok:!1,reason:e.diagnostic.message,errorCode:"locator-miss"};case"unsupported-syntax":case"binding-not-found":case"export-not-found":case"property-not-found":case"array-index-out-of-range":case"directive-conflict":case"metadata-shape-unsupported":return{ok:!1,reason:e.diagnostic.message,errorCode:"unsupported-operation"};case"invalid-parent-child-relation":case"self-closing-element":return{ok:!1,reason:e.diagnostic.message,errorCode:"invalid-target"};case"parse-failed":case"printer-failed":return{ok:!1,reason:e.diagnostic.message,errorCode:"ast-error"};default:return{ok:!1,reason:e.diagnostic.message,errorCode:"writeback-failed"}}}import{computeSiteEditCompositionKey as As,SiteEditCompositionContextSchema as Uw,SiteEditCompositionSelectorSchema as Jw}from"@vcp-dev/contracts";var qe=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="SiteEditCompositionError"}};function Mh(e,t){throw new qe("INVALID_COMPOSITION",e,{value:t})}function Ts(e){let t=Uw.safeParse(e);return t.success?t.data:Mh("Invalid SiteEditCompositionContext.",e)}function Oh(e){let t=[],n=new Map,r=new Map;for(let l of e.compositions){let u=Ts(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new qe("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=As(u);if(n.has(d))throw new qe("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u});let f=r.get(l.entryFile);if(f)throw new qe("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:f});let g={context:u,entryFile:l.entryFile,key:d};t.push(g),n.set(d,g),r.set(l.entryFile,d)}if(t.length===0)throw new qe("INVALID_COMPOSITION","At least one composition must be registered.");let o=new Map;for(let l of e.initialDocumentVersions??[]){let u=Ts(l?.composition);if(!Number.isInteger(l?.version)||(l?.version??-1)<0)throw new qe("INVALID_INITIAL_DOCUMENT_VERSION","Initial document version must be a non-negative integer.",{context:u,version:l?.version});let d=As(u);if(!n.has(d))throw new qe("UNKNOWN_COMPOSITION","Initial document version references an unregistered composition.",{context:u,key:d});if(o.has(d))throw new qe("DUPLICATE_COMPOSITION","Initial document versions must contain each composition at most once.",{context:u,key:d});o.set(d,l.version)}function i(l){let u=Jw.safeParse(l);if(!u.success)return Mh("Invalid SiteEditCompositionSelector.",l);let d=t.filter(({context:f})=>f.routeId===u.data.routeId&&(u.data.templateId===void 0?f.effectiveTemplateId===void 0:f.effectiveTemplateId===u.data.templateId));if(d.length===1)return d[0];throw d.length>1?new qe("AMBIGUOUS_COMPOSITION","The composition selector matches multiple registered contexts.",{selector:u.data}):new qe("UNKNOWN_COMPOSITION","The composition selector is not registered.",{selector:u.data})}function s(l){let u=Ts(l),d=As(u),f=n.get(d);if(!f)throw new qe("UNKNOWN_COMPOSITION","The composition context is not registered.",{context:u,key:d});return f}function a(l){let u=Ts(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new qe("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=As(u),f=n.get(d);if(f){if(f.entryFile===l.entryFile)return f;throw new qe("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u})}let g=[...n.values()].find(h=>h.entryFile===l.entryFile);if(g)throw new qe("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:g.context});let m={context:u,entryFile:l.entryFile,key:d};return t.push(m),n.set(d,m),m}function c(l){let u=n.get(l);if(!u)return;n.delete(l);let d=t.findIndex(f=>f.key===l);return d>=0&&t.splice(d,1),o.delete(l),u}return{entries:t,byKey:n,initialVersions:o,register:a,unregister:c,resolveSelector:i,resolveContext:s,getByKey:l=>n.get(l),routeIds:()=>[...new Set(t.map(({context:l})=>l.routeId))]}}function ql(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 Lh(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 Xw,stripSiteEditRepeatInstanceKeys as Dh}from"@vcp-dev/contracts";function Bh(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=Dh(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 zw(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 Fs(e){return e?.map(t=>({...t}))}function eu(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=Fs(e.collectionPathMap?.[t])??Fs(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:Fs(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>Fs(o)??[])}}function jh(e,t,n){let r=new Set;for(let g of t.regions)if(g.kind==="repeat-region")for(let m of g.childKeys)r.add(m);if(r.size===0)return e;let o=new Map(e.entries.map(g=>[g.key,g])),i=[],s=new Map,a=(g,m)=>Xw(g,m),c=(g,m,h)=>{let y=o.get(g);if(!y)return a(g,h);let b=a(g,h),S={...y,key:b,parentKey:m,childKeys:[]};return i.push(S),S.childKeys=y.childKeys.flatMap(v=>l(v,h,b)),b},l=(g,m,h)=>{if(!r.has(g))return[c(g,h,m)];let y=d(g,m),b=[];for(let S=0;S<y;S+=1)b.push(c(g,h,[...m,S]));return b},u=Array.from(new Set([...e.rootKeys,...e.entries.filter(g=>g.parentKey===null).map(g=>g.key)]));for(let g of u){if(!r.has(g)){c(g,null,[]);continue}let m=d(g,[]);for(let h=0;h<m;h+=1)c(g,null,[h])}return{...e,rootKeys:[...e.rootKeys],entries:i};function d(g,m){let h=new Set;for(let y of f(g)){let b=n.get(y);if(b){for(let S of[...b.textTargets.values(),...b.elementPropertyTargets.values()])if(!(S?.kind!=="value-binding"||S.sourceKind!=="repeat-template"))for(let v of Ww(S))v.length<=m.length||Hw(v,m)&&h.add(v[m.length])}}return h.size>0?h.size:zw(n.get(g))}function f(g){let m=s.get(g);if(m)return m;let h=[g],y=o.get(g);for(let b of y?.childKeys??[])h.push(...f(b));return s.set(g,h),h}}function $h(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function Vh(e,t,n,r){let o=r?.repeatOccurrenceIndexByKey.get(t);if(o!==void 0)return o;if(!e)return null;let i=0;for(let s of e.entries)if((Dh(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function Ww(e){return e.collectionPathMap?.length?e.collectionPathMap.map(t=>t.filter(n=>n.kind==="index").map(n=>n.index)):e.collectionIndexMap?.length?e.collectionIndexMap.map(t=>[t]):[]}function Hw(e,t){if(t.length>e.length)return!1;for(let n=0;n<t.length;n+=1)if(e[n]!==t[n])return!1;return!0}function Kh(e,t,n,r){if(!n)return{...e,key:t};let o=r??new Map(n.entries.map(u=>[u.key,u])),i=o.get(t);if(!i)return{...e,key:t};let s=[],a=i.parentKey;for(;a;){let u=o.get(a);if(!u)break;s.push({key:u.key,tag:u.tag,label:u.label}),a=u.parentKey}s.reverse();let c=i.childKeys.map(u=>o.get(u)).filter(u=>u!==void 0).map(u=>({key:u.key,tag:u.tag,label:u.label})),l=i.parentKey===null?[]:(o.get(i.parentKey)?.childKeys??[]).filter(u=>u!==i.key).map(u=>o.get(u)).filter(u=>u!==void 0).map(u=>({key:u.key,tag:u.tag,label:u.label}));return{...e,key:i.key,ancestors:s,children:c,siblings:l}}function Uh(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 Jh(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function Gw(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var Mo=class extends Error{constructor(t){let n=t.map(Jh);super(Gw(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function Xh(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof Mo?{routeId:e,message:n,diagnostics:t.diagnostics.map(Jh)}:{routeId:e,message:n}}function tu(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function nu(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function Oo(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function zh(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function _s(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 Wh(e){let{journal:t,index:n,observedFileDigests:r}=e;if(r.length!==t.files.length)return"ambiguous";let o=t.files.every((l,u)=>l.preDigest===r[u]),i=t.files.every((l,u)=>l.postDigest===r[u]),s=t.historyTransition,a=n.digest===s.expectedIndexDigest,c=n.digest===s.publishedIndexDigest&&n.cursor===s.publishedCursor&&n.currentId===s.publishedCurrentId;return o&&a?"safely-uncommitted":i&&c?"durably-committed":"ambiguous"}var rN=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,oN=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],Hh=32,Os=256;function iN(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var Gh={maxEntries:50,maxBytes:8*1024*1024};function sN(){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 bi(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 aN(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 cN(){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>Gh.maxEntries||lN(e)>Gh.maxBytes;)e.shift()}}function lN(e){return e.reduce((t,n)=>t+uN(n),0)}function uN(e){return Yh(e.preSnapshots)+Yh(e.postSnapshots)+dN(e.provenance)}function dN(e){return e?new TextEncoder().encode(JSON.stringify(e)).byteLength:0}function Yh(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function Zh(e,t){return{key:Zw(e),composition:e,routeId:e.routeId,entryFile:t,graph:null,topology:null,capabilities:null,document:null,pageComposition:null,pageCompositionProjection:null,documentIndex:null,pagePlacementByKey:null,pagePlacementUnitByKey:null,pageUnitByKey:null,pagePlacementsByUnitKey:null,dependencyFiles:new Set([t]),detailProjections:null,fileVersions:new Map,styleContext:null}}var Ls=class extends Error{constructor(t){super(t.reason),this.result=t}},zn=class extends Error{constructor(t){super(tu(t)),this.failedRoutes=t}};function Qh(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=at(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(at(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}function fN(e,t,n){if(!n)return;let r=at(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 pN=/\.(?:[cm]?[jt]sx?)$/i,mN=/\.json$/i,gN=/\.(?:css|scss|sass)$/i,hN=/\.mdx$/i,yN=/\.ya?ml$/i;function xN(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 bN(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function SN(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=oy(await e.listFiles(i)),a=new Map(s.files.map(l=>[l.path,l]));for(let[l,u]of n)if(EN(l,i.roots??[])){if(!u.exists){a.delete(l);continue}a.set(l,{path:l,sizeBytes:Buffer.byteLength(u.content,"utf8")})}let c=[...a.values()].sort((l,u)=>l.path.localeCompare(u.path));return s.truncated?{files:c,truncated:s.truncated}:c},getVersion(i){return e.getVersion(i)},bumpVersion(i){return e.getVersion(i)}}}function EN(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function oy(e){return Array.isArray(e)?{files:e}:e}function vN(e){if(!qw(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!==tN||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=Qw(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(pN.test(e.path)){let t=Mt({source:e.content,profile:wn({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(mN.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${tt(t)}`,details:{path:e.path}}}if(gN.test(e.path)){let t=qh({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(hN.test(e.path)){let t=qh({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(yN.test(e.path))try{nN(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${tt(t)}`,details:{path:e.path}}}return{ok:!0}}function qh({content:e,path:t,profile:n}){let r=[],o=null,i=!1,s=!1,a=!1,c=!1,l=!0;for(let d=0;d<e.length;d+=1){let f=e[d]??"",g=e[d+1]??"";if(n==="mdx"&&l&&e.startsWith("```",d)){c=!c;let m=e.indexOf(`
8
6
  `,d);if(m===-1){l=!0;break}d=m,l=!0;continue}if(c){l=f===`
9
7
  `||f==="\r";continue}if(s){f==="*"&&g==="/"&&(s=!1,d+=1),l=f===`
10
8
  `||f==="\r";continue}if(a){f===`
11
9
  `||f==="\r"?(a=!1,l=!0):l=!1;continue}if(o){if(i)i=!1;else if(f==="\\")i=!0;else if(f===o)o=null;else if(n==="css"&&(f===`
12
10
  `||f==="\r"))return Ar(t,`Unterminated string literal in ${t}.`);l=f===`
13
11
  `||f==="\r";continue}if(f==="/"&&g==="*"){s=!0,d+=1,l=!1;continue}if(n==="mdx"&&f==="/"&&g==="/"){a=!0,d+=1,l=!1;continue}if(f==="'"||f==='"'||n==="mdx"&&f==="`"){o=f,l=!1;continue}if(f==="{"||f==="("||f==="["){r.push({char:f,offset:d}),l=!1;continue}if(f==="}"||f===")"||f==="]"){let m=f==="}"?"{":f===")"?"(":"[",h=r.pop();if(!h||h.char!==m)return Ar(t,`Unexpected closing token "${f}" in ${t}.`);l=!1;continue}l=f===`
14
- `||f==="\r"}if(s)return Ar(t,`Unterminated block comment in ${t}.`);if(o)return Ar(t,`Unterminated string literal in ${t}.`);if(c)return Ar(t,`Unterminated MDX code fence in ${t}.`);let u=r.at(-1);return u?Ar(t,`Unclosed token "${u.char}" in ${t}.`):{ok:!0}}function Ar(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function js(e){let t="idle",n=e.fileSystem??bN(),r=Md(),o=Bh({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?Cf(e.historyStore):EN()),u=Lh(n,{externalAdapters:e.externalAdapters}),d=new Map,f=Xd(Ds),g=new Set,m=0,h=e.historyStore?.recoveryRequired??!1,y=Ql(),x=P();function E(p){return(Ls.isAbsolute(p)?Ls.relative(e.projectRoot,p):p).replace(/\\/g,"/").replace(/^\.\//,"")}function v(p,S){let b=Ls.posix.dirname(p),w=S.replace(/\.(?:tsx?|jsx?)$/i,""),A=Ls.posix.relative(b,w);return A.startsWith(".")?A:`./${A}`}function C(p,S){return p.startLine===S.startLine&&p.startColumn===S.startColumn&&p.endLine===S.endLine&&p.endColumn===S.endColumn}async function P(){let p=e.historyStore;if(p)try{let S=await p.readTransactionJournal();if(!S)return;let b=await p.readIndex(),w=await Promise.all(S.files.map(async M=>await n.exists(M.path)?Re(await n.readFile(M.path)):null));if(Yh({journal:S,index:b,observedFileDigests:w})!=="ambiguous"){await p.clearTransactionJournal(S.transactionId);let M=await p.readStatus();M.recoveryRequired||(await p.cleanupTmp(),M=await p.readStatus()),h=M.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: ${tt(S)}`).catch(()=>{})}}function F(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let p of o.entries){let S=ey(p.context,p.entryFile);i.set(p.key,S),R(S,S.dependencyFiles)}function R(p,S){let b=new Set(S);N(p),p.dependencyFiles=b;for(let w of p.dependencyFiles){let A=s.get(w);A||(A=new Set,s.set(w,A)),A.add(p.key)}}function N(p){for(let S of p.dependencyFiles){let b=s.get(S);b&&(b.delete(p.key),b.size===0&&s.delete(S))}p.dependencyFiles.clear()}function T(p){let S=new Set;for(let b of p)for(let w of s.get(b)??[])S.add(w);return S}function L(p){for(let S of p)if(!s.has(S))return!1;return!0}async function q(p,S,b,w,A,M){let _=new Map,$=ph(p),G=nh(A.values()),U=tg(A.values()),B=typeof M.exists=="function"?te=>M.exists(te):async()=>!1;for(let[te,ie]of p.elements){let xe=S.nodes.get(te);if(!xe)continue;let he=b.get(ie.sourceFile)??w.get(ie.sourceFile),Ce=new Map,Fe=new Map,O=new Map,J=[];for(let Ae of ie.textSegments){if(!he){Ce.set(Ae.index,null);continue}let Tr=await rh({file:ie.sourceFile,source:he,segment:Ae,readFile:lt=>M.readFile(lt),exists:B,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:lt,adapterId:kn,capabilities:Ys})=>({sourceType:lt,adapterId:kn,capabilities:Ys})),functionCallContracts:e.functionCallContracts,fileCache:G}),et=await Ul({file:ie.sourceFile,source:he,target:{kind:"text-segment",segment:Ae},readFile:lt=>M.readFile(lt),exists:B,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:lt,adapterId:kn,capabilities:Ys})=>({sourceType:lt,adapterId:kn,capabilities:Ys})),functionCallContracts:e.functionCallContracts,fileCache:G}),gt=TN(Tr);Ce.set(Ae.index,gt),Fe.set(Ae.index,Tr),O.set(Ae.index,et),J.push({editable:Ae.editable,source:gt})}let le=new Map,ye=new Map;if(he)for(let Ae of ie.attributes??[]){let Tr=await Pr({file:ie.sourceFile,source:he,sourceRange:Ae.sourceRange,expression:Ae.source?.expression??Ae.value,sourceInfo:Ae.source,readFile:gt=>M.readFile(gt),exists:B,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:gt,adapterId:lt,capabilities:kn})=>({sourceType:gt,adapterId:lt,capabilities:kn})),functionCallContracts:e.functionCallContracts,fileCache:G}),et=await fh({element:ie,file:ie.sourceFile,source:he,propertyName:Ae.name,readFile:gt=>M.readFile(gt),exists:B,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:gt,adapterId:lt,capabilities:kn})=>({sourceType:gt,adapterId:lt,capabilities:kn})),functionCallContracts:e.functionCallContracts,fileCache:G});ye.set(Ae.name,et),le.set(Ae.name,Tr)}let ve=vh(FN(xe.writeTarget),J),Te=$({key:te,element:ie,provenances:O}),nn=wh(ie),Ge=he?await ng({element:ie,graph:p,file:ie.sourceFile,source:he,readFile:Ae=>M.readFile(Ae),exists:B,fileCache:U}):void 0,zt=p.regions.find(Ae=>Ae.kind==="conditional-region"&&Ae.childKeys.includes(te)),ku,Gs=zt?.sourceCandidates?.[0];if(he&&zt&&Gs?.kind==="conditional-branch"){let Ae=await Ul({file:ie.sourceFile,source:he,target:{kind:"conditional-branch",candidate:Gs},readFile:et=>M.readFile(et),exists:B,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:et,adapterId:gt,capabilities:lt})=>({sourceType:et,adapterId:gt,capabilities:lt})),functionCallContracts:e.functionCallContracts,fileCache:G});ku={currentBranch:zt.childKeys.indexOf(te)<=0?"then":"else",availableBranches:zt.childKeys.length>1?["then","else"]:["then"],conditionExpression:Gs.conditionExpression,provenance:{finalSource:Ae.finalSource?{kind:Ae.finalSource.kind,file:Ae.finalSource.file,displayPath:Ae.finalSource.displayPath}:null,chain:Ae.chain.map(et=>({kind:et.kind,file:et.file,displayName:et.displayName,canEditHere:et.canEditHere})),confidence:Ae.confidence,editMode:Ae.editMode,diagnostics:Ae.diagnostics.map(et=>({code:et.code,message:et.message}))}}}_.set(te,{textSources:Ce,textTargets:Fe,elementPropertyTargets:le,propertyProvenances:ye,isRepeat:ZN(te,p),provenances:O,writeTarget:ve,componentSemantic:Te,styleSource:nn,conditional:ku,dynamicData:Ge})}return _}function W(p){return typeof n.getVersion=="function"?n.getVersion(p):0}function oe(p,S){let b=o.initialVersions.get(p.key)??0;for(let w of S.values())b=Math.max(b,w);return Math.max(b,p.graph?.version??0)}function D(p){return i.get(p)?.graph?.version??o.initialVersions.get(p)??0}function Z(p){try{return D(o.resolveSelector(p.composition).key)}catch{return 0}}async function fe(p,S,b=n,w={}){let A=await Jd(p,S,M=>b.readFile(M),M=>b.exists(M),{additionalEntries:await rt(p,b),...w});if(A.diagnostics.length>0)throw new Oo(A.diagnostics);return w.validationOnly||f.remember(A.parsedModules.values()),A}async function ct(p,S,b={}){let w=i.get(p);if(!w)return null;let A=b.sourceCache??nu(d,[]),M=b.fileSystem??ql(n),{graph:_,allSources:$,parsedModules:G,entryModule:U}=await fe(w.entryFile,S,M,{version:w.graph?.version??1}),B=new Map;for(let Ge of $.keys())B.set(Ge,W(Ge));let te=Math.max(oe(w,B),b.minimumVersion??0);b.changed&&te<=(w.graph?.version??0)&&(te=(w.graph?.version??0)+1),_.version=te;for(let[Ge,zt]of $)Os(A,Ge,zt,Ds);let ie=await uy(w.composition,w.entryFile,$,A,M);_.routeId=w.routeId,_.composition=w.composition;let xe=Nh(_),he=Pd(xe,_),Ce=await q(_,xe,$,A,G,M),Fe=py(_,he,Ce),O=fy(Ce),J=Kh(yh(_,xe,he,{canUpdateTextByKey:Fe,dynamicDataSummaryByKey:O}),_,Ce),le=cp({route:w.routeId,composition:w.composition,entryFile:w.entryFile,version:te,source:S,ast:U?.ast}),ye=lp(le);le.ok&&DN(J,_,le.projection,G);let ve={...J,composition:w.composition,...ie?{styleContext:ie}:{},pageComposition:ye},Te=new Set([w.entryFile,...$.keys()]);if(ie){Te.add(ie.entryCss.path);for(let Ge of ie.stylesheets)Te.add(Ge.path)}let nn={...w,dependencyFiles:Te,graph:_,topology:xe,capabilities:he,document:ve,pageComposition:ye,pageCompositionProjection:le.projection,pagePlacementByKey:le.ok?le.projection.placementByKey:null,pagePlacementUnitByKey:le.ok?le.projection.placementUnitByKey:null,pageUnitByKey:le.ok?le.projection.unitByKey:null,pagePlacementsByUnitKey:le.ok?le.projection.placementsByUnitKey:null,documentIndex:Vh(ve),detailProjections:Ce,fileVersions:B,styleContext:ie};if(b.publish===!1)return nn;for(let Ge of Te){let zt=$.get(Ge)??A.get(Ge);zt!==void 0&&(Os(d,Ge,zt,Ds),g.delete(Ge))}return R(w,Te),Object.assign(w,nn),w}async function rt(p,S=n){let b=[];for(let w of XN(p))typeof S.exists=="function"&&await S.exists(w)&&b.push({file:w,source:await S.readFile(w)});return b}async function uy(p,S,b,w,A){let M=[];for(let[B,te]of b){if(ru(B)){M.push(B);continue}for(let ie of WN(te)){let xe=sy(B,ie);xe&&M.push(xe)}}if(!M.length){for(let B of zN(S))if(await A.exists(B)){M.push(B);break}}let _=new Map,$=YN(M).slice(0,Zh);for(;$.length>0&&_.size<Zh;){let B=$.shift();if(_.has(B)||!ru(B))continue;let te=await dy(B,w,A);if(te!==null){_.set(B,{path:B,content:te});for(let ie of HN(te)){let xe=sy(B,ie);xe&&!_.has(xe)&&!$.includes(xe)&&$.push(xe)}}}let G=[..._.values()].map(B=>({...B,hash:Re(B.content)})),U=G[0];return U?{composition:p,revision:Re(JSON.stringify(G.map(({path:B,hash:te})=>({path:B,hash:te})))),entryCss:U,stylesheets:G.slice(1)}:null}async function dy(p,S,b){let w=S.get(p);if(w!==void 0)return w;if(!await b.exists(p))return null;let A=await b.readFile(p);return Os(S,p,A,Ds),A}function fy(p){let S=new Map;for(let[b,w]of p)w.dynamicData?.bindings.length&&S.set(b,dg(w.dynamicData.bindings));return S}function py(p,S,b){let w=new Map;for(let[A,M]of p.elements){if(!S.get(A)?.canUpdateText){w.set(A,!1);continue}let $=b.get(A),G=M.textSegments.some(U=>{if(!U.editable)return!1;let B=$?.provenances.get(U.index)??null;return!B||my(B)});w.set(A,G)}return w}function my(p){return p.editMode==="direct"||p.editMode==="proxy"||p.editMode==="upstream"}async function jo(p,S={}){let b=[...new Set(p)],w=S.affectedCompositionKeys!==void 0,A=w?new Set(S.affectedCompositionKeys):T(b);if(!w&&(A.size===0||!L(b)))for(let U of i.values())iu(U,b)&&A.add(U.key);let M=!w&&A.size===0&&b.some(iy),_=S.publish===!1?nu(d,b):void 0,$={rebuiltRoutes:[],failedRoutes:[],...S.publish===!1?{candidateRouteStates:[],candidateSourceCache:_}:{}},G=ql(n);for(let U of i.values())if(!(S.excludedCompositionKeys?.has(U.key)||!(A.has(U.key)||M)))try{let te=!!U.graph,ie=await G.readFile(U.entryFile),xe=await ct(U.key,ie,{...S,fileSystem:G,..._?{sourceCache:_}:{}});xe?.graph&&($.rebuiltRoutes.push({documentChanged:te,composition:U.composition,routeId:U.routeId,version:xe.graph.version}),$.candidateRouteStates?.push({composition:U.composition,key:U.key,routeId:U.routeId,state:xe}))}catch(te){$.failedRoutes.push({...Hh(U.routeId,te),composition:U.composition})}return $}function Hn(p){let S=[...new Set(p)],b=T(S);if(b.size>0&&L(S))return[...b];for(let w of i.values())iu(w,S)&&b.add(w.key);return[...b]}function gy(p){let S=new Set(Hn(p));return o.entries.filter(b=>S.has(b.key)).map(b=>b.context)}function hy(p){return[...new Set(Hn(p))].sort((b,w)=>b<w?-1:b>w?1:0).map(b=>o.getByKey(b)?.context).filter(b=>b!==void 0)}function yy(p,S){let b=new Set(Hn(S)),w=p.provenance?.affectedCompositions??[];if(w.length===0)return b;if([...new Set(w.map(M=>o.resolveContext(M).key))].some(M=>!b.has(M)))throw new Error("History provenance does not match the affected composition index.");return b}function xy(p,S){let b=p.composition??p.provenance?.initiatingComposition;if(b){let M=o.resolveContext(b);return{context:M.context,key:M.key}}let w=[...new Set(Hn(S))];if(w.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${w.length}).`);let A=o.getByKey(w[0]);if(!A)throw new Error("Legacy history entry references an unknown affected composition.");return{context:A.context,key:A.key}}function Us(p,S){r.emit({type:"operation-completed",composition:p.composition,result:p});for(let{composition:b,version:w}of S.rebuiltRoutes)r.emit({type:"document-changed",composition:b,version:w});for(let{composition:b,message:w}of S.failedRoutes)r.emit({type:"graph-error",composition:b,message:w})}function iu(p,S){return S.some(b=>p.dependencyFiles.has(b)||p.entryFile===b||p.graph?.fileIndex.has(b))}function su(p){for(let S of p)a.add(S);c||F()||(c=(async()=>{t="building";let S=!1;try{for(;a.size>0;){if(F())return;await by(),await y.runExclusive(async()=>{if(m>0||F())return;let b=[...a];a.clear();let w=await au(b);if(w.length===0)return;let A=Hn(w);for(let $ of A){let G=i.get($)?.composition;G&&r.emit({type:"graph-invalidated",composition:G})}let{rebuiltRoutes:M,failedRoutes:_}=await jo(w,{changed:!0});for(let{documentChanged:$,composition:G,version:U}of M)r.emit({type:"graph-ready",composition:G,version:U}),$&&r.emit({type:"document-changed",composition:G,version:U});for(let{composition:$,message:G}of _)S=!0,r.emit({type:"graph-error",composition:$,message:G})})}}finally{c=null,t!=="disposed"&&(t=!S&&[...i.values()].some(b=>b.graph)?"ready":"idle"),a.size>0&&su([])}})())}async function by(){for(;m>0;)await new Promise(p=>setTimeout(p,0))}async function au(p){let S=[];for(let b of new Set(p)){let w=d.get(b);if(w===void 0){if(g.has(b)&&!await n.exists(b))continue;g.delete(b),S.push(b);continue}try{await n.readFile(b)!==w&&(g.delete(b),S.push(b))}catch(A){if(!LN(A))try{if(await n.exists(b))continue}catch{continue}g.add(b),S.push(b)}}return S}function cu(p){Gh(d,p);for(let S of p)S.exists===!1?g.add(S.file):g.delete(S.file)}function lu(p){g.clear();for(let S of p)g.add(S)}async function uu(p){let S=await au(p);if(S.length===0)return;let b=Hn(S);for(let M of b){let _=i.get(M)?.composition;_&&r.emit({type:"graph-invalidated",composition:_})}let{rebuiltRoutes:w,failedRoutes:A}=await jo(S,{changed:!0});for(let{documentChanged:M,composition:_,version:$}of w)r.emit({type:"graph-ready",composition:_,version:$}),M&&r.emit({type:"document-changed",composition:_,version:$});for(let{composition:M,message:_}of A)r.emit({type:"graph-error",composition:M,message:_})}async function Sy(p,S){let b=Zn(p,S);if(!b?.graph)return;let w=at(p)??p,A=b.graph.elements.get(w);A&&await uu([A.sourceFile])}async function du(p){let S=new Set;if(p.target.kind==="node"){let b=Zn(p.target.key,p.composition),w=at(p.target.key)??p.target.key,A=b?.graph?.elements.get(w);A&&S.add(A.sourceFile)}else if(p.target.kind==="route"){let b=i.get(o.resolveSelector(p.target.composition).key);b&&S.add(b.entryFile)}else if(p.target.kind==="page-unit"){let b=i.get(o.resolveSelector(p.target.composition).key);b&&S.add(b.entryFile)}else if(p.target.kind==="source-file")S.add(p.target.path);else if(p.target.kind==="source-batch")for(let b of p.target.paths)S.add(b);if(p.params.kind==="move-node"&&!("kind"in p.params.target)){let b=[p.params.target.parentKey,...p.params.target.relation==="before"||p.params.target.relation==="after"?[p.params.target.anchorKey]:[]];for(let w of b){let A=Zn(w,p.composition),M=at(w)??w,_=A?.graph?.elements.get(M);_&&S.add(_.sourceFile)}}await uu(S)}async function Ey(p){if(p.params.kind!=="source-edit")return Js(p,"invalid-params","source-edit requires source-edit params");for(let S of p.params.edits){let b=ON(S);if(!b.ok)return Js(p,b.errorCode,b.message,b.details)}m+=1;try{let S=await Ry(p.params.edits);if(!S.ok)return Js(p,S.errorCode,S.message,S.details);await du(p);let b={operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:p.params.conflictPolicy,edits:p.params.edits.map(w=>w.operation==="delete"?{operation:"delete",file:w.path,baseContentHash:w.baseContentHash??null}:{operation:"upsert",file:w.path,baseContentHash:w.baseContentHash??null,content:w.content})};return await Yn({request:p,filePlan:b})}catch(S){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Z(p),error:{code:V.INTERNAL_ERROR,message:tt(S)}}}finally{m-=1}}async function vy(p){if(p.target.kind!=="project"||p.params.kind!=="insert-page-resource")return pe(p,V.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");m+=1;try{let S=await Uo({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:[...p.params.artifact.components.flatMap(w=>w.materialization.files.map(A=>({path:A.pathTemplate,content:A.content}))),...p.params.artifact.pages.flatMap(w=>w.materialization.files.map(A=>({path:A.pathTemplate,content:A.content})))],exists:w=>n.exists(w),readFile:w=>n.readFile(w)});if(!S.ok)return pe(p,V.MATERIALIZATION_REJECTED,S.message);let b=await lc({artifact:p.params.artifact,exists:w=>n.exists(w)});return b.ok?await Yn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:"overwrite",edits:b.files},output:{kind:"insert-page-resource",package_instance_id:b.packageInstanceId,pages:b.pages},historyPolicy:"none"}):pe(p,b.code==="MATERIALIZATION_CONFLICT"?V.MATERIALIZATION_CONFLICT:V.MATERIALIZATION_REJECTED,b.message,b.path?{path:b.path}:void 0)}catch(S){return pe(p,V.INTERNAL_ERROR,tt(S))}finally{m-=1}}async function ky(p){if(p.target.kind!=="project"||p.params.kind!=="delete-page-source")return pe(p,V.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return pe(p,V.PLAN_FAILED,"Complete project file listing is required for page deletion.");m+=1;try{let S=ay(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(S.truncated)return pe(p,V.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:S.truncated.reasons});let b=S.files.filter(({path:_})=>/\.(?:tsx?|jsx?)$/.test(_)),w=Object.fromEntries(await Promise.all(b.map(async({path:_})=>[_,await n.readFile(_)]))),A=Fp({expectedUrlPath:p.params.expectedUrlPath,files:w});if(!A.ok)return pe(p,A.code==="HOME_PAGE_LOCKED"?V.HOME_PAGE_LOCKED:A.code==="ROUTE_NOT_FOUND"?V.ROUTE_NOT_FOUND:V.PLAN_FAILED,A.message);let M=await Promise.all(A.edits.map(async _=>({..._,baseContentHash:Re(await n.readFile(_.file))})));return Yn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:M},output:{kind:"delete-page-source",deleted_files:A.deletedFiles,updated_files:A.updatedFiles,preserved_shared_files:A.preservedSharedFiles,warnings:A.warnings},historyPolicy:"none"})}catch(S){return pe(p,V.INTERNAL_ERROR,tt(S))}finally{m-=1}}async function Iy(p,S){if(p.kind!=="insert-child"&&p.kind!=="replace-node")return pe(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 pe(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 pe(p,V.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(p.params.position.documentVersion!==p.documentVersion)return pe(p,V.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.")}let b=S.document,w=S.pageCompositionProjection;if(!b||b.pageComposition?.status!=="supported"||!w||w.status!=="supported")return pe(p,V.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==b.version||w.documentVersion!==b.version)return pe(p,V.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${b.version}).`);let A=p.params.node.kind==="component-call"?p.params.node.materialization:void 0;if(!A)return pe(p,V.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let M=p.params.kind==="insert-child"?p.params.position:null,_=await Uo({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:A.files.map(U=>({path:U.pathTemplate,content:U.content})),exists:U=>n.exists(U),readFile:U=>n.readFile(U)});if(!_.ok)return pe(p,V.MATERIALIZATION_REJECTED,_.message);let $=await SN(n,Object.keys(A.projectDependencies??{})),G=await zf({manifest:A,generatedRoot:"components/site/generated",controlledFiles:A.files.map(U=>({pathTemplate:U.pathTemplate})),exists:U=>n.exists(U),availableHostDependencies:$,commit:async U=>{let B=await n.readFile(S.entryFile),te=S.document,ie=S.pageCompositionProjection;if(!te||te.pageComposition?.status!=="supported"||te.version!==p.documentVersion||!ie||ie.status!=="supported"||ie.documentVersion!==te.version)return{ok:!0,data:pe(p,V.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let xe=U.entry.path,he=_y(U.instanceName),Ce,Fe=[];if(p.params.kind==="insert-child"){if(!M||!("kind"in M)||M.kind!=="page-composition")return{ok:!0,data:pe(p,V.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.")};let ye=hc({routeId:S.routeId,entryFile:S.entryFile,currentDocumentVersion:te.version,expectedDocumentVersion:p.documentVersion,source:B,projection:ie,placementKey:M.placementKey,component:{source:xe,exportName:U.entry.export.kind==="default"?"default":U.entry.export.name,localName:he}});if(!ye.ok)return{ok:!0,data:pe(p,Hs(ye.error.code),ye.error.message,{diagnostics:ye.error.diagnostics})};let ve=ye.plan.rewriteStep,Te;switch(ve.kind){case"insert-root-expression":Te=Xi({source:B,locator:ve.locator,expectedSourceHash:ve.sourceHash,action:{kind:"insert",jsx:ve.node.jsx,placement:ve.placement,replaceOriginal:ve.replaceOriginal}});break;case"insert-child":Te=er({source:B,locator:ve.parentLocator,node:ve.node,placement:ve.placement,...ve.anchorLocator?{anchorLocator:ve.anchorLocator}:{}});break;default:Te={ok:!1,source:B,diagnostic:{code:"unsupported-syntax",message:`Unsupported route composition rewrite: ${String(ve)}`}}}if(!Te.ok)return{ok:!0,data:pe(p,V.AST_PARSE_ERROR,Te.diagnostic.message)};Ce=Te.source}else{let ye=yc({routeId:S.routeId,composition:S.composition,entryFile:S.entryFile,currentDocumentVersion:te.version,expectedDocumentVersion:p.documentVersion,source:B,projection:ie,placementUnitKey:p.target.placementUnitKey,operation:"replace-node"});if(!ye.ok)return{ok:!0,data:pe(p,Hs(ye.error.code),ye.error.message,{diagnostics:ye.error.diagnostics})};let ve=ye.plan.rewriteStep,Te;switch(ve.kind){case"replace-root-expression":Te=Xi({source:B,locator:ve.locator,expectedSourceHash:ve.sourceHash,action:{kind:"replace",jsx:`<${he} />`}});break;case"replace-node":Te=ci({source:B,locator:ve.locator,node:{jsx:`<${he} />`}});break;default:Te={ok:!1,source:B,diagnostic:{message:`Unsupported page-unit replacement rewrite: ${ve.kind}`}}}if(!Te.ok)return{ok:!0,data:pe(p,V.AST_PARSE_ERROR,Te.diagnostic.message)};let nn=await fu({routeState:S,placementUnitKey:p.target.placementUnitKey,source:B,mutatedSource:Te.source});Ce=nn.source,Fe=await Promise.all(nn.files.map(async Ge=>({operation:"delete",file:Ge,baseContentHash:Re(await n.readFile(Ge))})))}let O=rr({source:Ce,moduleSpecifier:v(S.entryFile,xe),imports:U.entry.export.kind==="default"?[{kind:"default",local:he}]:[{kind:"named",imported:U.entry.export.name,local:he}]});if(!O.ok)return{ok:!0,data:pe(p,V.AST_PARSE_ERROR,O.diagnostic.message)};let J=U.files.map(ye=>({operation:"create-only",file:ye.path,content:ye.content})),le=[{operation:"upsert",file:S.entryFile,content:O.source,baseContentHash:Re(B)},...J,...Fe];m+=1;try{let ye=await Yn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:S.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:le}});return!ye.ok&&ye.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:ye.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:ye}}finally{m-=1}}});return G.ok?G.data:pe(p,G.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?V.MATERIALIZATION_CONFLICT:V.MATERIALIZATION_REJECTED,G.error.message,{materializationCode:G.error.code})}async function Cy(p,S){if(p.kind!=="move-node"&&p.kind!=="remove-node")return pe(p,V.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let b=S.document,w=S.pageCompositionProjection;if(!b||b.pageComposition?.status!=="supported"||!w||w.status!=="supported")return pe(p,V.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==b.version||w.documentVersion!==b.version)return pe(p,V.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${b.version}).`);let A=await n.readFile(S.entryFile),M=yc({routeId:S.routeId,composition:S.composition,entryFile:S.entryFile,currentDocumentVersion:b.version,expectedDocumentVersion:p.documentVersion,source:A,projection:w,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(!M.ok)return pe(p,Hs(M.error.code),M.error.message,{diagnostics:M.error.diagnostics});let _=M.plan.rewriteStep,$;switch(_.kind){case"move-node":$=tr({source:A,locator:_.locator,targetParentLocator:_.targetParentLocator,placement:_.placement,..._.anchorLocator?{anchorLocator:_.anchorLocator}:{}});break;case"remove-node":$=qn({source:A,locator:_.locator});break;case"remove-root-expression":$=Xi({source:A,locator:_.locator,expectedSourceHash:_.sourceHash,action:{kind:"remove"}});break;default:$={ok:!1,source:A,diagnostic:{message:`Unsupported page-unit mutation rewrite: ${_.kind}`}}}if(!$.ok)return pe(p,V.AST_PARSE_ERROR,$.diagnostic.message);let G=$.source,U=[];if(p.kind==="remove-node"){let te=await fu({routeState:S,placementUnitKey:p.target.placementUnitKey,source:A,mutatedSource:G});G=te.source,U=await Promise.all(te.files.map(async ie=>({operation:"delete",file:ie,baseContentHash:Re(await n.readFile(ie))})))}let B=[{operation:"upsert",file:S.entryFile,content:G,baseContentHash:Re(A)},...U];m+=1;try{return await Yn({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{m-=1}}async function fu(p){let S={source:p.mutatedSource,files:[]},b=p.routeState.graph,w=p.routeState.pageCompositionProjection;if(!b||!w||w.status!=="supported"||!n.listFiles)return S;let M=w.placementUnitByKey.get(p.placementUnitKey)?.sourceRange;if(!M)return S;let _=[...b.elements.values()].find(O=>O.sourceFile===p.routeState.entryFile&&O.importedFrom&&C(O.sourceRange,M));if(!_?.importedFrom||!_.exportName)return S;let $=E(_.importedFrom),G="components/site/generated/";if(!$.startsWith(G))return S;let U=$.slice(G.length).split("/")[0];if(!U||!/-[0-9a-f]{8}$/i.test(U))return S;let B=`${G}${U}`;if([...b.elements.values()].filter(O=>O.sourceFile===p.routeState.entryFile&&E(O.importedFrom??"")===$).length!==1)return S;let ie=await n.listFiles({maxFiles:5e3,maxDepth:32}),xe=Array.isArray(ie)?ie:ie.files;if(!Array.isArray(ie)&&ie.truncated)return S;let he=xe.map(({path:O})=>O).filter(O=>O===B||O.startsWith(`${B}/`));if(he.length===0||!he.includes($))return S;for(let{path:O}of xe)if(!(O===p.routeState.entryFile||O===B||O.startsWith(`${B}/`)))try{if((await n.readFile(O)).includes(U))return S}catch{return S}let Ce=v(p.routeState.entryFile,$),Fe=or({source:p.mutatedSource,moduleSpecifier:Ce,imports:_.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:_.exportName}]});return Fe.ok?Fe.source.includes(U)?{source:Fe.source,files:[]}:{source:Fe.source,files:he.sort((O,J)=>O.localeCompare(J))}:S}async function Ry(p){if(n.getFileInfo){for(let _ of p)if(await n.exists(_.path)&&await n.getFileInfo(_.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${_.path}`,details:{path:_.path}}}for(let _ of p){if(_.operation!=="upsert"||!/^(?:src\/)?app\/globals\.css$/i.test(_.path))continue;let $=await n.exists(_.path)?await da(n,_.path):null;if($?.ok){let G=lN($.content,_.content);if(!G.ok)return{ok:!1,errorCode:"invalid-params",message:G.message,details:{path:_.path,code:G.code}}}}let S=wy(p);if(S.length===0)return{ok:!0};let b=_N(n,p),w=new Map,A=(_,$)=>{let G=w.get(_);if(G?.source===$)return G.result;let U=Wt(_,$);return w.set(_,{source:$,result:U}),U},M;try{M=await jh(S,async _=>{let $=i.get(_);return $?[...(await fe($.entryFile,await b.readFile($.entryFile),b,{validationOnly:!0,parseModule:A,validatedImports:f.getImports})).parsedModules.values()]:[]})}catch(_){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${tt(_)}`,details:{compositionKeys:S}}}for(let _ of M)f.remember(_);return{ok:!0}}function wy(p){return p.map(b=>b.path).some(iy)?[...i.keys()]:[]}function Js(p,S,b,w){let A=Do(S);return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Z(p),error:{code:A,message:b,...w?{details:w}:{}}}}async function Xs(p){let S=[];for(let b of new Set(p))S.push(await Ny(b));return S}async function Ny(p){if(!(typeof n.exists=="function"?await n.exists(p):!0))return{file:p,content:"",version:Math.max(0,W(p)),exists:!1};let b=await n.readFile(p);return{file:p,content:b,version:Math.max(1,W(p)),exists:!0,sha256:Re(b)}}async function pu(p,S,b,w){if(!e.historyStore)return null;let A=new Map(S.map($=>[$.file,$])),M=new Map(b.map($=>[$.file,$])),_=[...new Set([...A.keys(),...M.keys()])].sort().map($=>{let G=A.get($),U=M.get($);return{path:$,preDigest:G?.exists===!1||!G?null:Re(G.content),postDigest:U?.exists===!1||!U?null:Re(U.content)}});return{schemaVersion:2,transactionId:`${p}:${w.expectedIndexDigest}`,operationId:p,phase:"prepared",historyTransition:w,files:_}}async function mu(p){return!p||!e.historyStore||await e.historyStore.writeTransactionJournal(p),p}async function Gn(p){p&&e.historyStore&&await e.historyStore.clearTransactionJournal(p.transactionId)}async function zs(p,S){let b=[];try{for(let w of p)await gu(w),typeof n.bumpVersion=="function"&&n.bumpVersion(w.file),b.push(w.file)}catch(w){let A=await Py(S.filter(M=>b.includes(M.file)));return A.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${tt(w)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${A.failedFiles.join(", ")}: ${tt(w)}`,rolledBack:!1}}return{ok:!0,snapshots:p.map(Ay)}}async function gu(p){if(p.exists===!1){await n.deleteFile(p.file);return}await n.writeFile(p.file,p.content)}async function Py(p){let S=[];for(let b of p)try{await gu(b),typeof n.bumpVersion=="function"&&n.bumpVersion(b.file)}catch{S.push(b.file)}return S.length===0?{ok:!0}:{ok:!1,failedFiles:S}}function Ay(p){let S=p.exists!==!1;return{file:p.file,content:S?p.content:"",version:p.version,exists:S,...S?{sha256:Re(p.content)}:{}}}async function Yn(p){return y.runExclusive(()=>Ty(p))}async function Ty(p){let S=p.filePlan.edits.map(O=>O.file),b=o.resolveSelector(p.request.composition),w=b.context,A=p.historyPolicy==="none"?void 0:{initiatingComposition:w,affectedCompositions:hy(S)},M=await Xs(S),_=new Map(M.filter(O=>O.exists!==!1).map(O=>[O.file,O.content])),$=yu(),G=new Map(d),U=new Set(g),B=new Set([...i.values()].filter(O=>p.filePlan.edits.some(J=>J.operation==="delete"&&J.file===O.entryFile)).map(O=>O.key)),te=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:Re(O.content)}),ie={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})},xe=null,he=!1,Ce=await Ts({overlay:_,exists:O=>n.exists(O),plan:ie,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:M,postSnapshots:te,...p.selectionRef?{selectionRef:p.selectionRef}:{},...p.output?{output:p.output}:{},...A?{provenance:A}:{}}),J=O?.historyTransition?O.historyTransition:e.historyStore?xN(await e.historyStore.readIndex()):null;if(e.historyStore&&!J)throw new Error("Durable history did not provide an exact index transition.");return xe=await pu(p.request.id,M,te,J),xe=await mu(xe),{history:O,historyTransition:J}},reverify:async()=>{},writeCandidate:async()=>{let O=await u.executeFilePlan(p.filePlan);if(!O.ok)throw new Bs(O);return{postSnapshots:await Xs(O.affectedFiles),affectedFiles:O.affectedFiles,internalResultVersion:O.resultVersion}},validateCandidate:async({candidate:O,receipt:J})=>{let le=await jo(J.affectedFiles,{changed:!0,minimumVersion:J.internalResultVersion,publish:!1,excludedCompositionKeys:B});if(le.failedRoutes.length>0)throw new zn(le.failedRoutes);let ye=bu($,le.candidateRouteStates??[]),ve=xu(ye,b.key);return{...O,rebuild:le,routeSnapshots:ye,resultVersion:ve,...ty(p.selectionRef,ye.map(Te=>Te.state.document))?{selectionRef:ty(p.selectionRef,ye.map(Te=>Te.state.document))}:{}}},publishCandidate:async({candidate:O,history:J,receipt:le})=>{J?.history&&(await l.publishPrepared(J.history),he=!0);let ye=O.resultVersion??le.internalResultVersion;return{composition:w,requestId:p.request.id,kind:p.request.kind,target:p.request.target,ok:!0,resultVersion:ye,affectedFiles:le.affectedFiles,fileChanges:le.postSnapshots.map(ve=>({path:ve.file,operation:ve.exists===!1?"delete":"upsert"})),...p.output?{output:p.output}:{},...O.selectionRef?{selectionRef:O.selectionRef}:{}}},swapCandidate:({candidate:O,receipt:J})=>{O.routeSnapshots&&$o(O.routeSnapshots),O.rebuild?.candidateSourceCache&&Lo(d,O.rebuild.candidateSourceCache),cu(J.postSnapshots)},finalizeCandidate:async()=>{await Gn(xe);for(let O of B)i.delete(O)},emitCommitted:({candidate:O,published:J})=>{Us(J,O.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:O,receipt:J})=>{if(he)throw new Error("history was published before transaction finalization failed");if(J){let le=await zs(M,J.postSnapshots);if(!le.ok)throw new Error(le.reason)}$o($),Lo(d,G),lu(U),O?.history&&await l.discardPrepared?.(O.history),await Gn(xe)}});if(Ce.ok)return Ce.published;if(Ce.stage==="precheck"||Ce.stage==="build")try{await Gn(xe)}catch(O){let J=await Vo(tt(O));return pe(p.request,J,"Unable to clear an uncommitted transaction journal.")}if(Ce.recoveryRequired){let O=await Vo(Ce.reason);return pe(p.request,O===V.RECOVERY_PERSIST_FAILED?O:V.ROLLBACK_FAILED,Ce.reason)}let Fe=Ce.error;return Fe instanceof Bs?{...pe(p.request,Do(Fe.result.errorCode),Fe.result.reason),...Fe.result.affectedFiles?{affectedFiles:Fe.result.affectedFiles}:{}}:Fe instanceof zn?pe(p.request,V.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${tu(Fe.failedRoutes)}`,{failedRoutes:Fe.failedRoutes}):pe(p.request,Eu(Ce.stage),tt(Fe))}async function hu(p){return y.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 b=S.entry,w=p==="undo"?b.preSnapshots:b.postSnapshots,A=p==="undo"?b.postSnapshots:b.preSnapshots,M=w.map(J=>J.file),{context:_,key:$}=xy(b,M),G=await Xs(M),U=new Map(G.filter(J=>J.exists!==!1).map(J=>[J.file,J.content])),B=D($),te=yu(),ie=new Map(d),xe=new Set(g),he=null,Ce=!1,Fe,O=await Ts({overlay:U,plan:{operationId:`${p}:${b.operationId}`,intents:w.map(J=>J.exists===!1?{kind:"delete",path:J.file}:{kind:"upsert",path:J.file,content:J.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(he=await pu(`${p}:${b.operationId}`,G,w,S.historyTransition),he=await mu(he),S),reverify:async()=>{},writeCandidate:async()=>{let J=await zs(w,A);if(!J.ok)throw new Error(J.reason);return{snapshots:J.snapshots}},validateCandidate:async({candidate:J})=>{Fe=yy(b,M);let le=await jo(M,{changed:!0,minimumVersion:B+1,publish:!1,affectedCompositionKeys:Fe});if(le.failedRoutes.length>0)throw new zn(le.failedRoutes);let ye=bu(te,le.candidateRouteStates??[]),ve=xu(ye,$);return{...J,rebuild:le,routeSnapshots:ye,resultVersion:ve}},publishCandidate:async({candidate:J,history:le,receipt:ye})=>{if(!le)throw new Error("history cursor intent is missing");await l.publishPrepared(le),Ce=!0;let ve=J.resultVersion??B+1;return{composition:_,requestId:p,kind:b.kind,target:b.target,ok:!0,resultVersion:ve,affectedFiles:M,fileChanges:ye.snapshots.map(Te=>({path:Te.file,operation:Te.exists===!1?"delete":"upsert"})),...b.output?{output:b.output}:{}}},swapCandidate:({candidate:J,receipt:le})=>{J.routeSnapshots&&$o(J.routeSnapshots),J.rebuild?.candidateSourceCache&&Lo(d,J.rebuild.candidateSourceCache),cu(le.snapshots)},finalizeCandidate:async()=>{await Gn(he)},emitCommitted:({candidate:J,published:le})=>Us(le,J.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:J,receipt:le})=>{if(Ce)throw new Error("history cursor was published before transaction finalization failed");if(le){let ye=await zs(A,le.snapshots);if(!ye.ok)throw new Error(ye.reason)}$o(te),Lo(d,ie),lu(xe),J&&await l.discardPrepared?.(J),await Gn(he)}});if(O.ok)return O.published;if(O.stage==="precheck"||O.stage==="build")try{await Gn(he)}catch(J){let le=await Vo(tt(J));return{composition:_,requestId:p,kind:b.kind,target:b.target,ok:!1,resultVersion:B,error:{code:le,message:"Unable to clear an uncommitted transaction journal."}}}if(O.recoveryRequired){let J=await Vo(O.reason);return{composition:_,requestId:p,kind:b.kind,target:b.target,ok:!1,resultVersion:B,affectedFiles:M,error:{code:J===V.RECOVERY_PERSIST_FAILED?J:V.ROLLBACK_FAILED,message:O.reason}}}return{composition:_,requestId:p,kind:b.kind,target:b.target,ok:!1,resultVersion:B,affectedFiles:M,error:{code:O.error instanceof zn?V.ROUTE_REBUILD_FAILED:Eu(O.stage),message:tt(O.error),...O.error instanceof zn?{details:{failedRoutes:O.error.failedRoutes}}:{}}}}function yu(){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 xu(p,S){return p.find(w=>w.key===S)?.state.graph?.version??o.initialVersions.get(S)??0}function bu(p,S){let b=new Map(p.map(w=>[w.key,w]));for(let w of S)b.set(w.key,w);return[...b.values()]}function $o(p){for(let S of i.values())N(S);for(let S of p){let b={...S.state,dependencyFiles:new Set(S.state.dependencyFiles),fileVersions:new Map(S.state.fileVersions)};i.set(S.key,b),R(b,b.dependencyFiles)}}async function Ws(p){let S=i.get(p);if(!S)throw new Error(`Composition not found: ${p}`);if(S.graph)return;let b=await n.readFile(S.entryFile);await ct(p,b)}function Zn(p,S){let b=i.get(o.resolveSelector(S).key)??null;return!b||!Su(b,p)?null:b}function Su(p,S){if(p.documentIndex?.entriesByKey.has(S)||p.graph?.elements.has(S))return!0;let b=at(S);return b&&b!==S?p.graph?.elements.has(b)===!0:!1}function pe(p,S,b,w){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Z(p),error:{code:S,message:b,...w?{details:w}:{}}}}function Eu(p){return p==="validate"?V.ROUTE_REBUILD_FAILED:p==="publish"?V.HISTORY_COMMIT_FAILED:V.WRITE_IO_ERROR}async function Vo(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 _y(p){let b=p.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(w=>w.charAt(0).toUpperCase()+w.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return b?`Prefab${b}`:"GeneratedPrefab"}function Hs(p){return p==="VERSION_STALE"?V.VERSION_STALE:p==="CROSS_PAGE_MOVE_UNSUPPORTED"?V.CROSS_PAGE_MOVE_UNSUPPORTED:V.UNSUPPORTED_OPERATION}async function vu(p){if(p.target.kind==="route"){let b=i.get(o.resolveSelector(p.target.composition).key)??null;return b?(b.graph||await Ws(b.key),b):pe(p,V.ROUTE_NOT_FOUND,"Composition not found for route target.")}if(p.target.kind==="page-unit"){let b=i.get(o.resolveSelector(p.target.composition).key)??null;return b?(b.graph||await Ws(b.key),b):pe(p,V.ROUTE_NOT_FOUND,"Composition not found for page-unit target.")}if(p.target.kind!=="node")return pe(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 Ws(S.key),Su(S,p.target.key)?S:pe(p,V.NODE_NOT_FOUND,`Target key not found: ${p.target.key}`)):pe(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(),d.clear(),f.clear(),g.clear()},registerComposition(p,S){let b=o.register({context:p,entryFile:S}),w=i.get(b.key);if(w?.entryFile===S)return;w&&N(w);let A=ey(b.context,S);i.set(b.key,A),R(A,A.dependencyFiles),r.emit({type:"graph-invalidated",composition:b.context})},unregisterComposition(p){let S=o.resolveSelector(p),b=i.get(S.key);b&&(N(b),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),b=i.get(S.key);if(!b)throw new Error(`Composition not registered: ${S.key}`);if(b.graph)t="ready";else{t="building";try{let w=await n.readFile(b.entryFile);await ct(S.key,w),t="ready",r.emit({type:"graph-ready",composition:S.context,version:i.get(S.key)?.graph?.version??0})}catch(w){throw t="idle",r.emit({type:"graph-error",composition:S.context,message:tt(w)}),w}}},getDocument(p){let S=o.resolveSelector(p),b=i.get(S.key);if(!b)throw new Error(`Composition not registered: ${S.key}`);if(!b.document)throw new Error(`Composition not built: ${S.key}`);return b.document},async getHistoryStatus(){await x;let p=await l.getStatus?.();return p?{...p,recoveryRequired:h}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:h}},getObjectEditContext(p,S,b){let w=Zn(p,S),A=at(p)??p;if(w?.graph&&w.topology&&w.capabilities&&w.detailProjections){let M=w.detailProjections.get(A);if(M){let _=w.graph.elements.get(A);if(!_)throw new Error(`Key not found: ${p}`);let $=CN(p,A,b),G=new Map;if(M.isRepeat&&$?.instanceIndex!==void 0)for(let te of _.attributes??[])G.set(te.name,Al({file:_.sourceFile,source:d.get(_.sourceFile)??"",element:_,propertyName:te.name,selectionRef:$,graph:w.graph,sources:d}));let U=hh({element:_,graph:w.graph,source:d.get(_.sourceFile),documentVersion:w.graph.version,selectionRef:b,isRepeat:M.isRepeat,propertyProvenance:M.propertyProvenances,repeatTargets:G}),B=bh(A,w.graph,w.topology,w.capabilities,M.textSources,M.provenances,M.dynamicData,U);return p===A?B:zh(B,p,w.document??null,w.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getRenderDetail(p,S){let b=Zn(p,S),w=at(p)??p;if(b?.graph&&b.topology&&b.capabilities&&b.detailProjections){let A=b.detailProjections.get(w);if(A){let M=xh(w,b.graph,b.topology,b.capabilities,A.textSources,A.writeTarget,A.provenances,A.conditional,A.componentSemantic,A.styleSource,A.dynamicData);return p===w?M:Xh(M,p,b.document??null,b.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getClassNameSource(p,S){let b=Zn(p,S),w=at(p)??p;if(!b?.graph)throw new Error(`Key not found: ${p}`);let A=b.graph.elements.get(w);if(!A)throw new Error(`Key not found: ${p}`);let M=d.get(A.sourceFile);if(M===void 0)throw new Error(`Source not loaded: ${A.sourceFile}`);return Aa({key:w,route:{composition:b.composition,routeId:b.routeId,graph:b.graph,source:M}})},refreshSourceForKey:Sy,async execute(p){if(await x,h)return pe(p,V.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(p.kind==="source-edit")return Ey(p);if(p.kind==="insert-page-resource")return vy(p);if(p.kind==="delete-page-source")return ky(p);let S=await vu(p);if("ok"in S)return S;await du(p);let b=await vu(p);if("ok"in b)return b;let w=b;if(p.target.kind==="page-unit"){let B=p;return p.kind==="insert-child"||p.kind==="replace-node"?Iy(B,w):p.kind==="move-node"||p.kind==="remove-node"?Cy(B,w):pe(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 M=p.params,_=p.target.kind==="node"?p.target.key:null;if(M.kind==="move-node"&&"kind"in M.target&&M.target.kind==="source-sibling"){let B=M.target,te=_?w.document?.entries.find(J=>J.key===_):null,ie=w.document?.entries.find(J=>J.key===B.anchorKey),xe=te?.pageCompositionActionScope,he=xe?.kind==="source-siblings"?xe.siblingKeys:null,Ce=he?.indexOf(te?.key??"")??-1,Fe=he?.indexOf(B.anchorKey)??-1,O=B.relation==="before"?Ce-1:Ce+1;if(!te||!ie||!he||Ce<0||Fe!==O||ie.pageCompositionActionScope?.kind!=="source-siblings"||ie.pageCompositionActionScope.siblingKeys.length!==he.length||ie.pageCompositionActionScope.siblingKeys.some((J,le)=>J!==he[le])||!te.operationSummary.canMove)return pe(p,V.INVALID_TARGET,"Source sibling move is unavailable because the current source sibling scope or adjacent anchor no longer matches.")}if(!w.graph||!w.topology||!w.capabilities)return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Z(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 $=UN(w,w.graph,w.capabilities,d,i),G=await new fs($).plan(p);if(!G.ok)return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Z(p),error:{code:Do(G.errorCode),message:G.reason}};let U=G.plan;if(U.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:Z(p),affectedFiles:[]}:{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Z(p),error:{code:V.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};m+=1;try{if(U.steps.some(te=>te.type==="invoke-external-adapter")){let te=await u.execute(U);if(!te.ok)return pe(p,Do(te.errorCode),te.reason);let ie={composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!0,resultVersion:Math.max(Z(p),te.resultVersion),affectedFiles:te.affectedFiles,...te.selectionRef?{selectionRef:te.selectionRef}:{}};return Us(ie,{rebuiltRoutes:[],failedRoutes:[]}),ie}let B=await u.prepareRewritePlan(U);return B.ok?await Yn({request:p,filePlan:B.filePlan,...B.selectionRef?{selectionRef:B.selectionRef}:{}}):pe(p,Do(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:Z(p),error:{code:V.INTERNAL_ERROR,message:tt(B)}}}finally{m-=1}},async undo(p){if(await x,h)return{composition:o.entries[0].context,requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:D(o.entries[0].key),error:{code:V.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};m+=1;try{return await hu("undo")}finally{m-=1}},async redo(p){if(await x,h)return{composition:o.entries[0].context,requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:D(o.entries[0].key),error:{code:V.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};m+=1;try{return await hu("redo")}finally{m-=1}},notifyFileChanged(p){su([p])},getAffectedCompositions(p){return gy(p)},subscribe(p){return r.subscribe(p)}}}function LN(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function DN(e,t,n,r){let o=new Map,i=new Map,s=(d,f,g)=>{let m=d.get(f)??new Set,h=m.size;return m.add(g),d.set(f,m),m.size!==h},a=(d,f)=>{if(!d.importedFrom)return!1;if(d.exportName==="default")return s(i,d.importedFrom,f);let g=s(o,`${d.importedFrom}#${d.tag}`,f);return d.exportName&&d.exportName!==d.tag&&(g=s(o,`${d.importedFrom}#${d.exportName}`,f)||g),g},c=d=>o.get(`${d.sourceFile}#${d.componentName}`)??i.get(d.sourceFile);for(let d of t.elements.values()){if(d.sourceFile!==n.entryFile||!d.importedFrom||!/^[A-Z]/.test(d.tag))continue;let f=n.placements.find(m=>m.members.some(h=>h.sourceRange!==null&&Bo(d.sourceRange,h.sourceRange)));if(!f)continue;let g=f.placementUnitKey;a(d,g)}let l=!0;for(;l;){l=!1;for(let d of t.elements.values()){if(d.sourceFile===n.entryFile||!d.importedFrom||!/^[A-Z]/.test(d.tag))continue;let f=c(d);if(f)for(let g of f)l=a(d,g)||l}}let u=n.placements.find(d=>d.placementKey===n.container.placementKey&&d.relation==="append");for(let d of e.entries){let f=at(d.key)??d.key,g=t.elements.get(d.key)??t.elements.get(f);if(!g)continue;if(g.sourceFile===n.entryFile){if(n.container.sourceRange&&Bo(g.sourceRange,n.container.sourceRange)&&u){d.pageCompositionUnitKey=u.placementUnitKey;continue}let y=n.placements.find(x=>x.members.some(E=>E.sourceRange!==null&&(Bo(g.sourceRange,E.sourceRange)||KN(E.sourceRange,g.sourceRange))));if(y){d.pageCompositionUnitKey=y.placementUnitKey;continue}}let m=o.get(`${g.sourceFile}#${g.componentName}`);if(m){m.size===1&&(d.pageCompositionUnitKey=m.values().next().value);continue}let h=i.get(g.sourceFile);h?.size===1&&(d.pageCompositionUnitKey=h.values().next().value)}BN(e,t,n,r)}function BN(e,t,n,r){let o=new Map(e.entries.map(f=>[f.key,f])),i=e.entries.filter(f=>{let g=f.pageCompositionUnitKey;return g?f.parentKey?o.get(f.parentKey)?.pageCompositionUnitKey!==g:!0:!1}),s=new Map,a=(f,g)=>{s.set(f,Math.min(2,(s.get(f)??0)+g))},c=f=>n.placements.some(g=>g.members.some(m=>m.sourceRange!==null&&Bo(f.sourceRange,m.sourceRange)));for(let f of t.elements.values())f.sourceFile!==n.entryFile||!f.importedFrom||!/^[A-Z]/.test(f.tag)||!c(f)||a(`${f.importedFrom}#${f.exportName??f.tag}`,1);let l=[...t.elements.values()].flatMap(f=>f.sourceFile!==n.entryFile&&f.importedFrom&&/^[A-Z]/.test(f.tag)?[{owner:`${f.sourceFile}#${f.componentName}`,ownerDefault:`${f.sourceFile}#default`,target:`${f.importedFrom}#${f.exportName??f.tag}`}]:[]);for(let f=0;f<=l.length;f+=1){let g=!1;for(let m of l){let h=s.get(m.owner)??s.get(m.ownerDefault)??0;if(!h)continue;let y=s.get(m.target)??0,x=Math.min(2,y+h);x!==y&&(s.set(m.target,x),g=!0)}if(!g)break}let u=f=>s.get(`${f.sourceFile}#${f.componentName}`)??s.get(`${f.sourceFile}#default`)??0;for(let f of i){f.pageCompositionActionScope={kind:"unavailable"};let g=t.elements.get(f.key);f.pageCompositionUnitKey&&g?.sourceFile===n.entryFile&&(f.pageCompositionActionScope={kind:"route-unit"})}let d=new Map;for(let f of i){let g=t.elements.get(f.key);if(!g||g.sourceFile===n.entryFile||f.key!==(at(f.key)??f.key))continue;let m=r.get(g.sourceFile);if(!m)continue;let h=ue(m.ast,{kind:"jsx-node",strategy:"source-range",sourceRange:g.sourceRange});if(!h.ok||!h.match.path.isJSXElement())continue;let y=h.match.path,x=y.parentPath;if(!x||!x.isJSXFragment()&&!(x.isJSXElement()&&Le(x))){u(g)===1&&ry(y)&&(f.pageCompositionActionScope={kind:"route-unit"});continue}if(!ry(x))continue;let E=d.get(x.node)??[];E.push({entry:f,element:g,parentPath:x}),d.set(x.node,E)}for(let f of d.values()){let g=f[0];if(!g)continue;let m=g.entry.pageCompositionUnitKey,h=[],y=!!(m&&u(g.element)===1);for(let E of g.parentPath.node.children){if(jN(E))continue;if(!$N(E)){y=!1;break}let v=[...t.elements.values()].find(P=>P.sourceFile===g.element.sourceFile&&P.componentName===g.element.componentName&&Bo(P.sourceRange,VN(E))),C=v?o.get(v.identity.key):null;if(!v||!C||C.parentKey||C.pageCompositionUnitKey!==m||u(v)!==1){y=!1;break}h.push(C)}if(!y||h.length!==f.length||f.some(({entry:E})=>!h.some(v=>v.key===E.key)))continue;if(h.length===1){h[0].pageCompositionActionScope={kind:"route-unit"};continue}if(h.length<2)continue;let x=h.map(E=>E.key);for(let E of h)E.pageCompositionActionScope={kind:"source-siblings",siblingKeys:x}}}function ry(e){let t=e.parentPath;return!!(t?.isReturnStatement?.()||t?.isArrowFunctionExpression?.()&&t.node.body===e.node)}function jN(e){return!!(e&&typeof e=="object"&&e.type==="JSXText"&&!(e.value??"").trim())}function $N(e){return!!(e&&typeof e=="object"&&e.type==="JSXElement")}function VN(e){return{startLine:e.loc?.start.line??-1,startColumn:e.loc?.start.column??-1,endLine:e.loc?.end.line??-1,endColumn:e.loc?.end.column??-1}}function Bo(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function KN(e,t){return oy(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&oy(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function oy(e,t,n,r){return e!==n?e-n:t-r}function UN(e,t,n,r,o){let i=new Map,s=new Map,a=(u,d)=>{if(s.has(u))return;s.set(u,d);let f=t.elements.get(u);for(let g of f?.childKeys??[])a(g,d)};for(let u of t.regions)if(u.kind==="repeat-region")for(let d of u.childKeys)i.set(d,u.ownerKey),a(d,u.ownerKey);return{getNode(u){let d=c(u),f=t.elements.get(d.baseKey);return f?l(u,f):null},getChildNodes(u){let d=c(u),g=e.documentIndex?.entriesByKey.get(u)?.childKeys;if(g)return g.map(h=>{let y=at(h)??h,x=t.elements.get(y);return x?l(h,x):null}).filter(h=>h!==null);let m=t.elements.get(d.baseKey);return m?m.childKeys.map(h=>{let y=t.elements.get(h);return y?l(h,y):null}).filter(h=>h!==null):[]},getKnownSourceFiles(){return[...r.entries()].map(([u,d])=>({file:u,content:d}))},getRouteEntryFiles(){return[...o.values()].map(u=>u.entryFile)},getCapability(u){let d=c(u),f=n.get(d.baseKey);return f?{...f,key:u,constraints:f.constraints.map(g=>({...g})),...f.editModes?{editModes:{...f.editModes}}:{}}:{composition:e.composition,key:u,canUpdateText:!1,canRemove:!1,canInsertChild:!1,canMove:!1,constraints:[]}},getFileContent(u){return r.get(u)??""},getFileVersion(u){return Math.max(e.fileVersions.get(u)??0,t.version)},getRouteEntryFile(u){return e.routeId===u?e.entryFile:null},getComponentSemantic(u){let d=c(u);return e.detailProjections?.get(d.baseKey)?.componentSemantic??null},getClassNameSource(u){let d=c(u),f=t.elements.get(d.baseKey),g=f?r.get(f.sourceFile):void 0;return!f||g===void 0?null:Aa({key:d.baseKey,route:{composition:e.composition,routeId:e.routeId,graph:t,source:g}})},getEditableTextSegmentIndex(u){let d=c(u),g=e.detailProjections?.get(d.baseKey)?.textTargets.keys()?.next();return g&&!g.done?g.value:null},async getTextWriteTarget(u,d){let f=c(u);return eu(e.detailProjections?.get(f.baseKey)?.textTargets.get(d)??null,f.repeatIndex)},async getElementPropertyWriteTarget(u,d){let f=c(u);return eu(e.detailProjections?.get(f.baseKey)?.elementPropertyTargets.get(d)??null,f.repeatIndex)},getPropertyState(u,d,f){let g=c(u),m=t.elements.get(g.baseKey);if(!m)return null;let y=e.detailProjections?.get(g.baseKey)?.propertyProvenances.get(d);if(y)return y;let x=m.attributes?.find(E=>E.name===d);return x?x.source?{status:"blocked",owner:"generic",diagnostic:{code:"unsupported-property-source",message:`Property '${d}' has an unresolved value source`}}:{status:"direct",owner:"generic",attribute:x,target:{kind:"jsx-attribute",file:m.sourceFile,sourceRange:x.sourceRange}}:(m.attributeSpreads?.length??0)>0?{status:"blocked",owner:"generic",diagnostic:{code:"ambiguous-property-source",message:`A spread may provide or override property '${d}'`}}:{status:"missing",owner:"generic"}},getRepeatPropertyTarget(u,d,f){let g=c(u),m=t.elements.get(g.baseKey);if(!m)return{ok:!1,errorCode:"repeat-not-found",reason:`Node not found: ${u}`};let h=f?{...f,key:g.baseKey}:g.repeatIndex!==null?{key:g.baseKey,instanceIndex:g.repeatIndex}:void 0;return Al({file:m.sourceFile,source:r.get(m.sourceFile)??"",element:m,propertyName:d,selectionRef:h,graph:t,sources:r})},getTextProvenance(u,d){let f=c(u);return e.detailProjections?.get(f.baseKey)?.provenances.get(d)??null}};function c(u){let d=pN(u);return d?{baseKey:d.baseKey,repeatIndex:Jh(e.document??null,u,d.baseKey,e.documentIndex)??Uh(d)}:{baseKey:u,repeatIndex:null}}function l(u,d){let f=at(u)??u,g=e.documentIndex?.entriesByKey.get(u);return{key:u,file:d.sourceFile,component:d.componentName,tag:d.tag,structuralPath:d.identity.structuralPath,sourceRange:d.sourceRange,parentKey:g?.parentKey??d.parentKey??void 0,isRepeatRegion:d.boundaryKind==="repeat-region"||s.has(f),isBoundary:!1,importedFrom:d.importedFrom,exportName:d.exportName,isRepeatItemRoot:i.has(f),repeatOwnerKey:i.get(f)??s.get(f),attributes:d.attributes?.map(m=>({name:m.name,value:m.value,source:m.source?{expression:m.source.expression,base:m.source.base,path:m.source.path.map(h=>({...h}))}:null,resolvedValue:m.resolvedValue}))}}}var JN={"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 Do(e){return JN[e]}function tt(e){return e instanceof Error&&e.message?e.message:String(e)}function iy(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function XN(e){let t=Wn(e);if(!hN.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=>yN.map(a=>`${s}/${a}`))}function zN(e){let n=Wn(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function WN(e){return cy(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function HN(e){return cy(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function cy(e,t){let n=[];for(let r of e.matchAll(t)){let o=ly(r[1]??"");o&&n.push(o)}return n}function sy(e,t){let n=ly(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?Wn(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?Wn(`${GN(e)}/${n}`):n.startsWith("/")?Wn(n.slice(1)):ru(n)?Wn(n):null}function ly(e){return e.split(/[?#]/,1)[0]?.trim()??""}function ru(e){return/\.css$/i.test(e)}function GN(e){let t=Wn(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function YN(e){return Array.from(new Set(e))}function Wn(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 ZN(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 $s=class{constructor(t){this.options=t,this.fileSystem=new _r(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}getDocument(t){return Go(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 Yo(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return qo(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}getSourceFile(t){return ei(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}resolveSourceLocation(t){return ti(t,this.engine.getRenderDetail(t.key,t.composition))}async planOperation(t){let n=qN.safeParse(t);if(!n.success)return{result:Ho(t,n.error.issues.map(i=>i.message))};let r=new _r(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:An(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let c=eP.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(l=>tP(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 js({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=Zo(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 tP(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:Re(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:Re(e.before)},fullContent:e.after}}function nP(e){return new $s(e)}import{SiteEditOperationRequestSchema as iP}from"@vcp-dev/contracts";import _t from"node:fs/promises";import nt from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as rP,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as oP}from"@vcp-dev/contracts";var Vs=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=js({...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 qo(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.engine.getCompositionEntryFiles()})}getSourceFile(t){return ei(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.engine.getCompositionEntryFiles()})}resolveSourceLocation(t){return ti(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 _t.readFile(nt.join(n,r),"utf8")},async readFileBytes(r){return _t.readFile(nt.join(n,r))},async getFileInfo(r){let o=nt.join(n,...r.split("/"));try{let i=await _t.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await Si(nt.join(n,r),o)},async createExclusive(r,o){let i=nt.join(n,r);await _t.mkdir(nt.dirname(i),{recursive:!0});let s=await _t.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await _t.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await _t.rm(nt.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=nt.join(n,i),a=nt.dirname(nt.join(n,o));for(;a!==s&&a.startsWith(`${s}${nt.sep}`);){try{await _t.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=nt.dirname(a);continue}break}a=nt.dirname(a)}},async exists(r){try{return await _t.access(nt.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...oP,...rP],i=[],s=new Set,a=new Set,c=0;for(let d of o)await u(d,i,1);let l=i.sort((d,f)=>d.path.localeCompare(f.path));return a.size>0?{files:l,truncated:{reasons:[...a]}}:{files:l};async function u(d,f,g){if(r.maxDepth!==void 0&&g>r.maxDepth){a.add("max-depth");return}let m=nt.join(n,...d.split("/")),h;try{h=await _t.lstat(m)}catch{return}if(h.isSymbolicLink())return;if(h.isFile()){let x=h.ino>0?`${String(h.dev)}:${String(h.ino)}`:null;if(x&&s.has(x))return;if(r.maxFiles!==void 0&&f.length>=r.maxFiles){a.add("max-files");return}if(r.maxTotalBytes!==void 0&&c+h.size>r.maxTotalBytes){a.add("max-total-bytes");return}x&&s.add(x),f.push({path:d,sizeBytes:h.size}),c+=h.size;return}if(!h.isDirectory())return;if(r.maxFiles!==void 0&&f.length>=r.maxFiles){a.add("max-files");return}let y=await _t.readdir(m,{withFileTypes:!0});for(let x of y)x.isSymbolicLink()||await u(`${d}/${x.name}`,f,g+1)}},getVersion(r){return t.get(r)??1},bumpVersion(r){let o=(t.get(r)??1)+1;return t.set(r,o),o}}}};function ou(e){return new Vs(e)}var Ks=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=ou({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=Zo(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:Go(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:Yo(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=iP.safeParse(r);if(!o.success)return Ho(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:An(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:An(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:An(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 sP(e){return new Ks(e)}export{ce as FileHistoryStoreError,ao as PageTemplateManagedSourceError,Ks as PreviewFileSystemSiteEditEngineRuntime,Pf as SITE_EDIT_RAW_COLOR_LITERAL_RE,$s as SnapshotSiteEditEngineRuntime,Uo as checkComponentI18nHostCompatibility,Sp as computeManagedPageTemplatePaths,sP as createPreviewSiteEditEngineRuntime,nP as createSiteEditEngineRuntime,yp as decodePageTemplateKey,Ac as encodePageTemplateId,rx as instrumentSiteEditRuntimeAttributes,Ep as isManagedPageTemplateSourcePath,of as openFileHistoryStore,Vy as parseSourceModule,Ky as resolveImportBase,tI as resolveManagedPageTemplateComposition,Hi as scanManagedPageTemplateCandidates,kp as scanSiteEditCompositionsFromFiles,eo as scanSiteEditThemeStyleViolations};
12
+ `||f==="\r"}if(s)return Ar(t,`Unterminated block comment in ${t}.`);if(o)return Ar(t,`Unterminated string literal in ${t}.`);if(c)return Ar(t,`Unterminated MDX code fence in ${t}.`);let u=r.at(-1);return u?Ar(t,`Unclosed token "${u.char}" in ${t}.`):{ok:!0}}function Ar(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function Ds(e){let t="idle",n=e.fileSystem??sN(),r=Md(),o=Oh({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?Cf(e.historyStore):cN()),u=_h(n,{externalAdapters:e.externalAdapters}),d=new Map,f=Xd(Os),g=new Set,m=0,h=e.historyStore?.recoveryRequired??!1,y=Ql(),b=P();function S(p){return(Ms.isAbsolute(p)?Ms.relative(e.projectRoot,p):p).replace(/\\/g,"/").replace(/^\.\//,"")}function v(p,E){let x=Ms.posix.dirname(p),w=E.replace(/\.(?:tsx?|jsx?)$/i,""),A=Ms.posix.relative(x,w);return A.startsWith(".")?A:`./${A}`}function C(p,E){return p.startLine===E.startLine&&p.startColumn===E.startColumn&&p.endLine===E.endLine&&p.endColumn===E.endColumn}async function P(){let p=e.historyStore;if(p)try{let E=await p.readTransactionJournal();if(!E)return;let x=await p.readIndex(),w=await Promise.all(E.files.map(async M=>await n.exists(M.path)?Re(await n.readFile(M.path)):null));if(Wh({journal:E,index:x,observedFileDigests:w})!=="ambiguous"){await p.clearTransactionJournal(E.transactionId);let M=await p.readStatus();M.recoveryRequired||(await p.cleanupTmp(),M=await p.readStatus()),h=M.recoveryRequired;return}await p.markRecoveryRequired(`Ambiguous transaction journal ${E.transactionId} at phase ${E.phase}`),h=!0}catch(E){h=!0,await p.markRecoveryRequired(`Transaction journal recovery failed: ${tt(E)}`).catch(()=>{})}}function F(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let p of o.entries){let E=Zh(p.context,p.entryFile);i.set(p.key,E),R(E,E.dependencyFiles)}function R(p,E){let x=new Set(E);N(p),p.dependencyFiles=x;for(let w of p.dependencyFiles){let A=s.get(w);A||(A=new Set,s.set(w,A)),A.add(p.key)}}function N(p){for(let E of p.dependencyFiles){let x=s.get(E);x&&(x.delete(p.key),x.size===0&&s.delete(E))}p.dependencyFiles.clear()}function T(p){let E=new Set;for(let x of p)for(let w of s.get(x)??[])E.add(w);return E}function L(p){for(let E of p)if(!s.has(E))return!1;return!0}async function q(p,E,x,w,A,M){let _=new Map,$=uh(p),G=qg(A.values()),U=Qm(A.values()),B=typeof M.exists=="function"?te=>M.exists(te):async()=>!1;for(let[te,ie]of p.elements){let xe=E.nodes.get(te);if(!xe)continue;let he=x.get(ie.sourceFile)??w.get(ie.sourceFile),Ce=new Map,Fe=new Map,O=new Map,J=[];for(let Ae of ie.textSegments){if(!he){Ce.set(Ae.index,null);continue}let Tr=await eh({file:ie.sourceFile,source:he,segment:Ae,readFile:lt=>M.readFile(lt),exists:B,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:lt,adapterId:kn,capabilities:Gs})=>({sourceType:lt,adapterId:kn,capabilities:Gs})),functionCallContracts:e.functionCallContracts,fileCache:G}),et=await Ul({file:ie.sourceFile,source:he,target:{kind:"text-segment",segment:Ae},readFile:lt=>M.readFile(lt),exists:B,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:lt,adapterId:kn,capabilities:Gs})=>({sourceType:lt,adapterId:kn,capabilities:Gs})),functionCallContracts:e.functionCallContracts,fileCache:G}),gt=xN(Tr);Ce.set(Ae.index,gt),Fe.set(Ae.index,Tr),O.set(Ae.index,et),J.push({editable:Ae.editable,source:gt})}let le=new Map,ye=new Map;if(he)for(let Ae of ie.attributes??[]){let Tr=await Pr({file:ie.sourceFile,source:he,sourceRange:Ae.sourceRange,expression:Ae.source?.expression??Ae.value,sourceInfo:Ae.source,readFile:gt=>M.readFile(gt),exists:B,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:gt,adapterId:lt,capabilities:kn})=>({sourceType:gt,adapterId:lt,capabilities:kn})),functionCallContracts:e.functionCallContracts,fileCache:G}),et=await lh({element:ie,file:ie.sourceFile,source:he,propertyName:Ae.name,readFile:gt=>M.readFile(gt),exists:B,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:gt,adapterId:lt,capabilities:kn})=>({sourceType:gt,adapterId:lt,capabilities:kn})),functionCallContracts:e.functionCallContracts,fileCache:G});ye.set(Ae.name,et),le.set(Ae.name,Tr)}let ve=bh(bN(xe.writeTarget),J),Te=$({key:te,element:ie,provenances:O}),nn=Ih(ie),Ge=he?await qm({element:ie,graph:p,file:ie.sourceFile,source:he,readFile:Ae=>M.readFile(Ae),exists:B,fileCache:U}):void 0,zt=p.regions.find(Ae=>Ae.kind==="conditional-region"&&Ae.childKeys.includes(te)),ku,Hs=zt?.sourceCandidates?.[0];if(he&&zt&&Hs?.kind==="conditional-branch"){let Ae=await Ul({file:ie.sourceFile,source:he,target:{kind:"conditional-branch",candidate:Hs},readFile:et=>M.readFile(et),exists:B,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:et,adapterId:gt,capabilities:lt})=>({sourceType:et,adapterId:gt,capabilities:lt})),functionCallContracts:e.functionCallContracts,fileCache:G});ku={currentBranch:zt.childKeys.indexOf(te)<=0?"then":"else",availableBranches:zt.childKeys.length>1?["then","else"]:["then"],conditionExpression:Hs.conditionExpression,provenance:{finalSource:Ae.finalSource?{kind:Ae.finalSource.kind,file:Ae.finalSource.file,displayPath:Ae.finalSource.displayPath}:null,chain:Ae.chain.map(et=>({kind:et.kind,file:et.file,displayName:et.displayName,canEditHere:et.canEditHere})),confidence:Ae.confidence,editMode:Ae.editMode,diagnostics:Ae.diagnostics.map(et=>({code:et.code,message:et.message}))}}}_.set(te,{textSources:Ce,textTargets:Fe,elementPropertyTargets:le,propertyProvenances:ye,isRepeat:BN(te,p),provenances:O,writeTarget:ve,componentSemantic:Te,styleSource:nn,conditional:ku,dynamicData:Ge})}return _}function W(p){return typeof n.getVersion=="function"?n.getVersion(p):0}function oe(p,E){let x=o.initialVersions.get(p.key)??0;for(let w of E.values())x=Math.max(x,w);return Math.max(x,p.graph?.version??0)}function D(p){return i.get(p)?.graph?.version??o.initialVersions.get(p)??0}function Z(p){try{return D(o.resolveSelector(p.composition).key)}catch{return 0}}async function fe(p,E,x=n,w={}){let A=await Jd(p,E,M=>x.readFile(M),M=>x.exists(M),{additionalEntries:await rt(p,x),...w});if(A.diagnostics.length>0)throw new Mo(A.diagnostics);return w.validationOnly||f.remember(A.parsedModules.values()),A}async function ct(p,E,x={}){let w=i.get(p);if(!w)return null;let A=x.sourceCache??nu(d,[]),M=x.fileSystem??ql(n),{graph:_,allSources:$,parsedModules:G,entryModule:U}=await fe(w.entryFile,E,M,{version:w.graph?.version??1}),B=new Map;for(let Ge of $.keys())B.set(Ge,W(Ge));let te=Math.max(oe(w,B),x.minimumVersion??0);x.changed&&te<=(w.graph?.version??0)&&(te=(w.graph?.version??0)+1),_.version=te;for(let[Ge,zt]of $)_s(A,Ge,zt,Os);let ie=await uy(w.composition,w.entryFile,$,A,M);_.routeId=w.routeId,_.composition=w.composition;let xe=Ch(_),he=Pd(xe,_),Ce=await q(_,xe,$,A,G,M),Fe=py(_,he,Ce),O=fy(Ce),J=jh(mh(_,xe,he,{canUpdateTextByKey:Fe,dynamicDataSummaryByKey:O}),_,Ce),le=ip({route:w.routeId,composition:w.composition,entryFile:w.entryFile,version:te,source:E,ast:U?.ast}),ye=sp(le);le.ok&&IN(J,_,le.projection,G);let ve={...J,composition:w.composition,...ie?{styleContext:ie}:{},pageComposition:ye},Te=new Set([w.entryFile,...$.keys()]);if(ie){Te.add(ie.entryCss.path);for(let Ge of ie.stylesheets)Te.add(Ge.path)}let nn={...w,dependencyFiles:Te,graph:_,topology:xe,capabilities:he,document:ve,pageComposition:ye,pageCompositionProjection:le.projection,pagePlacementByKey:le.ok?le.projection.placementByKey:null,pagePlacementUnitByKey:le.ok?le.projection.placementUnitByKey:null,pageUnitByKey:le.ok?le.projection.unitByKey:null,pagePlacementsByUnitKey:le.ok?le.projection.placementsByUnitKey:null,documentIndex:Bh(ve),detailProjections:Ce,fileVersions:B,styleContext:ie};if(x.publish===!1)return nn;for(let Ge of Te){let zt=$.get(Ge)??A.get(Ge);zt!==void 0&&(_s(d,Ge,zt,Os),g.delete(Ge))}return R(w,Te),Object.assign(w,nn),w}async function rt(p,E=n){let x=[];for(let w of FN(p))typeof E.exists=="function"&&await E.exists(w)&&x.push({file:w,source:await E.readFile(w)});return x}async function uy(p,E,x,w,A){let M=[];for(let[B,te]of x){if(ru(B)){M.push(B);continue}for(let ie of MN(te)){let xe=ry(B,ie);xe&&M.push(xe)}}if(!M.length){for(let B of _N(E))if(await A.exists(B)){M.push(B);break}}let _=new Map,$=DN(M).slice(0,Hh);for(;$.length>0&&_.size<Hh;){let B=$.shift();if(_.has(B)||!ru(B))continue;let te=await dy(B,w,A);if(te!==null){_.set(B,{path:B,content:te});for(let ie of ON(te)){let xe=ry(B,ie);xe&&!_.has(xe)&&!$.includes(xe)&&$.push(xe)}}}let G=[..._.values()].map(B=>({...B,hash:Re(B.content)})),U=G[0];return U?{composition:p,revision:Re(JSON.stringify(G.map(({path:B,hash:te})=>({path:B,hash:te})))),entryCss:U,stylesheets:G.slice(1)}:null}async function dy(p,E,x){let w=E.get(p);if(w!==void 0)return w;if(!await x.exists(p))return null;let A=await x.readFile(p);return _s(E,p,A,Os),A}function fy(p){let E=new Map;for(let[x,w]of p)w.dynamicData?.bindings.length&&E.set(x,cg(w.dynamicData.bindings));return E}function py(p,E,x){let w=new Map;for(let[A,M]of p.elements){if(!E.get(A)?.canUpdateText){w.set(A,!1);continue}let $=x.get(A),G=M.textSegments.some(U=>{if(!U.editable)return!1;let B=$?.provenances.get(U.index)??null;return!B||my(B)});w.set(A,G)}return w}function my(p){return p.editMode==="direct"||p.editMode==="proxy"||p.editMode==="upstream"}async function Bo(p,E={}){let x=[...new Set(p)],w=E.affectedCompositionKeys!==void 0,A=w?new Set(E.affectedCompositionKeys):T(x);if(!w&&(A.size===0||!L(x)))for(let U of i.values())iu(U,x)&&A.add(U.key);let M=!w&&A.size===0&&x.some(ny),_=E.publish===!1?nu(d,x):void 0,$={rebuiltRoutes:[],failedRoutes:[],...E.publish===!1?{candidateRouteStates:[],candidateSourceCache:_}:{}},G=ql(n);for(let U of i.values())if(!(E.excludedCompositionKeys?.has(U.key)||!(A.has(U.key)||M)))try{let te=!!U.graph,ie=await G.readFile(U.entryFile),xe=await ct(U.key,ie,{...E,fileSystem:G,..._?{sourceCache:_}:{}});xe?.graph&&($.rebuiltRoutes.push({documentChanged:te,composition:U.composition,routeId:U.routeId,version:xe.graph.version}),$.candidateRouteStates?.push({composition:U.composition,key:U.key,routeId:U.routeId,state:xe}))}catch(te){$.failedRoutes.push({...Xh(U.routeId,te),composition:U.composition})}return $}function Hn(p){let E=[...new Set(p)],x=T(E);if(x.size>0&&L(E))return[...x];for(let w of i.values())iu(w,E)&&x.add(w.key);return[...x]}function gy(p){let E=new Set(Hn(p));return o.entries.filter(x=>E.has(x.key)).map(x=>x.context)}function hy(p){return[...new Set(Hn(p))].sort((x,w)=>x<w?-1:x>w?1:0).map(x=>o.getByKey(x)?.context).filter(x=>x!==void 0)}function yy(p,E){let x=new Set(Hn(E)),w=p.provenance?.affectedCompositions??[];if(w.length===0)return x;if([...new Set(w.map(M=>o.resolveContext(M).key))].some(M=>!x.has(M)))throw new Error("History provenance does not match the affected composition index.");return x}function xy(p,E){let x=p.composition??p.provenance?.initiatingComposition;if(x){let M=o.resolveContext(x);return{context:M.context,key:M.key}}let w=[...new Set(Hn(E))];if(w.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${w.length}).`);let A=o.getByKey(w[0]);if(!A)throw new Error("Legacy history entry references an unknown affected composition.");return{context:A.context,key:A.key}}function Ks(p,E){r.emit({type:"operation-completed",composition:p.composition,result:p});for(let{composition:x,version:w}of E.rebuiltRoutes)r.emit({type:"document-changed",composition:x,version:w});for(let{composition:x,message:w}of E.failedRoutes)r.emit({type:"graph-error",composition:x,message:w})}function iu(p,E){return E.some(x=>p.dependencyFiles.has(x)||p.entryFile===x||p.graph?.fileIndex.has(x))}function su(p){for(let E of p)a.add(E);c||F()||(c=(async()=>{t="building";let E=!1;try{for(;a.size>0;){if(F())return;await by(),await y.runExclusive(async()=>{if(m>0||F())return;let x=[...a];a.clear();let w=await au(x);if(w.length===0)return;let A=Hn(w);for(let $ of A){let G=i.get($)?.composition;G&&r.emit({type:"graph-invalidated",composition:G})}let{rebuiltRoutes:M,failedRoutes:_}=await Bo(w,{changed:!0});for(let{documentChanged:$,composition:G,version:U}of M)r.emit({type:"graph-ready",composition:G,version:U}),$&&r.emit({type:"document-changed",composition:G,version:U});for(let{composition:$,message:G}of _)E=!0,r.emit({type:"graph-error",composition:$,message:G})})}}finally{c=null,t!=="disposed"&&(t=!E&&[...i.values()].some(x=>x.graph)?"ready":"idle"),a.size>0&&su([])}})())}async function by(){for(;m>0;)await new Promise(p=>setTimeout(p,0))}async function au(p){let E=[];for(let x of new Set(p)){let w=d.get(x);if(w===void 0){if(g.has(x)&&!await n.exists(x))continue;g.delete(x),E.push(x);continue}try{await n.readFile(x)!==w&&(g.delete(x),E.push(x))}catch(A){if(!kN(A))try{if(await n.exists(x))continue}catch{continue}g.add(x),E.push(x)}}return E}function cu(p){zh(d,p);for(let E of p)E.exists===!1?g.add(E.file):g.delete(E.file)}function lu(p){g.clear();for(let E of p)g.add(E)}async function uu(p){let E=await au(p);if(E.length===0)return;let x=Hn(E);for(let M of x){let _=i.get(M)?.composition;_&&r.emit({type:"graph-invalidated",composition:_})}let{rebuiltRoutes:w,failedRoutes:A}=await Bo(E,{changed:!0});for(let{documentChanged:M,composition:_,version:$}of w)r.emit({type:"graph-ready",composition:_,version:$}),M&&r.emit({type:"document-changed",composition:_,version:$});for(let{composition:M,message:_}of A)r.emit({type:"graph-error",composition:M,message:_})}async function Sy(p,E){let x=Zn(p,E);if(!x?.graph)return;let w=at(p)??p,A=x.graph.elements.get(w);A&&await uu([A.sourceFile])}async function du(p){let E=new Set;if(p.target.kind==="node"){let x=Zn(p.target.key,p.composition),w=at(p.target.key)??p.target.key,A=x?.graph?.elements.get(w);A&&E.add(A.sourceFile)}else if(p.target.kind==="route"){let x=i.get(o.resolveSelector(p.target.composition).key);x&&E.add(x.entryFile)}else if(p.target.kind==="page-unit"){let x=i.get(o.resolveSelector(p.target.composition).key);x&&E.add(x.entryFile)}else if(p.target.kind==="source-file")E.add(p.target.path);else if(p.target.kind==="source-batch")for(let x of p.target.paths)E.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 w of x){let A=Zn(w,p.composition),M=at(w)??w,_=A?.graph?.elements.get(M);_&&E.add(_.sourceFile)}}await uu(E)}async function Ey(p){if(p.params.kind!=="source-edit")return Us(p,"invalid-params","source-edit requires source-edit params");for(let E of p.params.edits){let x=vN(E);if(!x.ok)return Us(p,x.errorCode,x.message,x.details)}m+=1;try{let E=await Ry(p.params.edits);if(!E.ok)return Us(p,E.errorCode,E.message,E.details);await du(p);let x={operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:p.params.conflictPolicy,edits:p.params.edits.map(w=>w.operation==="delete"?{operation:"delete",file:w.path,baseContentHash:w.baseContentHash??null}:{operation:"upsert",file:w.path,baseContentHash:w.baseContentHash??null,content:w.content})};return await Yn({request:p,filePlan:x})}catch(E){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Z(p),error:{code:V.INTERNAL_ERROR,message:tt(E)}}}finally{m-=1}}async function vy(p){if(p.target.kind!=="project"||p.params.kind!=="insert-page-resource")return pe(p,V.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");m+=1;try{let E=await Ko({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:[...p.params.artifact.components.flatMap(w=>w.materialization.files.map(A=>({path:A.pathTemplate,content:A.content}))),...p.params.artifact.pages.flatMap(w=>w.materialization.files.map(A=>({path:A.pathTemplate,content:A.content})))],exists:w=>n.exists(w),readFile:w=>n.readFile(w)});if(!E.ok)return pe(p,V.MATERIALIZATION_REJECTED,E.message);let x=await cc({artifact:p.params.artifact,exists:w=>n.exists(w)});return x.ok?await Yn({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"}):pe(p,x.code==="MATERIALIZATION_CONFLICT"?V.MATERIALIZATION_CONFLICT:V.MATERIALIZATION_REJECTED,x.message,x.path?{path:x.path}:void 0)}catch(E){return pe(p,V.INTERNAL_ERROR,tt(E))}finally{m-=1}}async function ky(p){if(p.target.kind!=="project"||p.params.kind!=="delete-page-source")return pe(p,V.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return pe(p,V.PLAN_FAILED,"Complete project file listing is required for page deletion.");m+=1;try{let E=oy(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(E.truncated)return pe(p,V.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:E.truncated.reasons});let x=E.files.filter(({path:_})=>/\.(?:tsx?|jsx?)$/.test(_)),w=Object.fromEntries(await Promise.all(x.map(async({path:_})=>[_,await n.readFile(_)]))),A=Pp({expectedUrlPath:p.params.expectedUrlPath,files:w});if(!A.ok)return pe(p,A.code==="HOME_PAGE_LOCKED"?V.HOME_PAGE_LOCKED:A.code==="ROUTE_NOT_FOUND"?V.ROUTE_NOT_FOUND:V.PLAN_FAILED,A.message);let M=await Promise.all(A.edits.map(async _=>({..._,baseContentHash:Re(await n.readFile(_.file))})));return Yn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:M},output:{kind:"delete-page-source",deleted_files:A.deletedFiles,updated_files:A.updatedFiles,preserved_shared_files:A.preservedSharedFiles,warnings:A.warnings},historyPolicy:"none"})}catch(E){return pe(p,V.INTERNAL_ERROR,tt(E))}finally{m-=1}}async function Iy(p,E){if(p.kind!=="insert-child"&&p.kind!=="replace-node")return pe(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 pe(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 pe(p,V.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(p.params.position.documentVersion!==p.documentVersion)return pe(p,V.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.")}let x=E.document,w=E.pageCompositionProjection;if(!x||x.pageComposition?.status!=="supported"||!w||w.status!=="supported")return pe(p,V.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==x.version||w.documentVersion!==x.version)return pe(p,V.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${x.version}).`);let A=p.params.node.kind==="component-call"?p.params.node.materialization:void 0;if(!A)return pe(p,V.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let M=p.params.kind==="insert-child"?p.params.position:null,_=await Ko({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:A.files.map(U=>({path:U.pathTemplate,content:U.content})),exists:U=>n.exists(U),readFile:U=>n.readFile(U)});if(!_.ok)return pe(p,V.MATERIALIZATION_REJECTED,_.message);let $=await aN(n,Object.keys(A.projectDependencies??{})),G=await Uf({manifest:A,generatedRoot:"components/site/generated",controlledFiles:A.files.map(U=>({pathTemplate:U.pathTemplate})),exists:U=>n.exists(U),availableHostDependencies:$,commit:async U=>{let B=await n.readFile(E.entryFile),te=E.document,ie=E.pageCompositionProjection;if(!te||te.pageComposition?.status!=="supported"||te.version!==p.documentVersion||!ie||ie.status!=="supported"||ie.documentVersion!==te.version)return{ok:!0,data:pe(p,V.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let xe=U.entry.path,he=_y(U.instanceName),Ce,Fe=[];if(p.params.kind==="insert-child"){if(!M||!("kind"in M)||M.kind!=="page-composition")return{ok:!0,data:pe(p,V.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.")};let ye=gc({routeId:E.routeId,entryFile:E.entryFile,currentDocumentVersion:te.version,expectedDocumentVersion:p.documentVersion,source:B,projection:ie,placementKey:M.placementKey,component:{source:xe,exportName:U.entry.export.kind==="default"?"default":U.entry.export.name,localName:he}});if(!ye.ok)return{ok:!0,data:pe(p,Ws(ye.error.code),ye.error.message,{diagnostics:ye.error.diagnostics})};let ve=ye.plan.rewriteStep,Te;switch(ve.kind){case"insert-root-expression":Te=Ui({source:B,locator:ve.locator,expectedSourceHash:ve.sourceHash,action:{kind:"insert",jsx:ve.node.jsx,placement:ve.placement,replaceOriginal:ve.replaceOriginal}});break;case"insert-child":Te=er({source:B,locator:ve.parentLocator,node:ve.node,placement:ve.placement,...ve.anchorLocator?{anchorLocator:ve.anchorLocator}:{}});break;default:Te={ok:!1,source:B,diagnostic:{code:"unsupported-syntax",message:`Unsupported route composition rewrite: ${String(ve)}`}}}if(!Te.ok)return{ok:!0,data:pe(p,V.AST_PARSE_ERROR,Te.diagnostic.message)};Ce=Te.source}else{let ye=hc({routeId:E.routeId,composition:E.composition,entryFile:E.entryFile,currentDocumentVersion:te.version,expectedDocumentVersion:p.documentVersion,source:B,projection:ie,placementUnitKey:p.target.placementUnitKey,operation:"replace-node"});if(!ye.ok)return{ok:!0,data:pe(p,Ws(ye.error.code),ye.error.message,{diagnostics:ye.error.diagnostics})};let ve=ye.plan.rewriteStep,Te;switch(ve.kind){case"replace-root-expression":Te=Ui({source:B,locator:ve.locator,expectedSourceHash:ve.sourceHash,action:{kind:"replace",jsx:`<${he} />`}});break;case"replace-node":Te=ai({source:B,locator:ve.locator,node:{jsx:`<${he} />`}});break;default:Te={ok:!1,source:B,diagnostic:{message:`Unsupported page-unit replacement rewrite: ${ve.kind}`}}}if(!Te.ok)return{ok:!0,data:pe(p,V.AST_PARSE_ERROR,Te.diagnostic.message)};let nn=await fu({routeState:E,placementUnitKey:p.target.placementUnitKey,source:B,mutatedSource:Te.source});Ce=nn.source,Fe=await Promise.all(nn.files.map(async Ge=>({operation:"delete",file:Ge,baseContentHash:Re(await n.readFile(Ge))})))}let O=rr({source:Ce,moduleSpecifier:v(E.entryFile,xe),imports:U.entry.export.kind==="default"?[{kind:"default",local:he}]:[{kind:"named",imported:U.entry.export.name,local:he}]});if(!O.ok)return{ok:!0,data:pe(p,V.AST_PARSE_ERROR,O.diagnostic.message)};let J=U.files.map(ye=>({operation:"create-only",file:ye.path,content:ye.content})),le=[{operation:"upsert",file:E.entryFile,content:O.source,baseContentHash:Re(B)},...J,...Fe];m+=1;try{let ye=await Yn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:E.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:le}});return!ye.ok&&ye.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:ye.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:ye}}finally{m-=1}}});return G.ok?G.data:pe(p,G.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?V.MATERIALIZATION_CONFLICT:V.MATERIALIZATION_REJECTED,G.error.message,{materializationCode:G.error.code})}async function Cy(p,E){if(p.kind!=="move-node"&&p.kind!=="remove-node")return pe(p,V.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let x=E.document,w=E.pageCompositionProjection;if(!x||x.pageComposition?.status!=="supported"||!w||w.status!=="supported")return pe(p,V.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==x.version||w.documentVersion!==x.version)return pe(p,V.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${x.version}).`);let A=await n.readFile(E.entryFile),M=hc({routeId:E.routeId,composition:E.composition,entryFile:E.entryFile,currentDocumentVersion:x.version,expectedDocumentVersion:p.documentVersion,source:A,projection:w,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(!M.ok)return pe(p,Ws(M.error.code),M.error.message,{diagnostics:M.error.diagnostics});let _=M.plan.rewriteStep,$;switch(_.kind){case"move-node":$=tr({source:A,locator:_.locator,targetParentLocator:_.targetParentLocator,placement:_.placement,..._.anchorLocator?{anchorLocator:_.anchorLocator}:{}});break;case"remove-node":$=qn({source:A,locator:_.locator});break;case"remove-root-expression":$=Ui({source:A,locator:_.locator,expectedSourceHash:_.sourceHash,action:{kind:"remove"}});break;default:$={ok:!1,source:A,diagnostic:{message:`Unsupported page-unit mutation rewrite: ${_.kind}`}}}if(!$.ok)return pe(p,V.AST_PARSE_ERROR,$.diagnostic.message);let G=$.source,U=[];if(p.kind==="remove-node"){let te=await fu({routeState:E,placementUnitKey:p.target.placementUnitKey,source:A,mutatedSource:G});G=te.source,U=await Promise.all(te.files.map(async ie=>({operation:"delete",file:ie,baseContentHash:Re(await n.readFile(ie))})))}let B=[{operation:"upsert",file:E.entryFile,content:G,baseContentHash:Re(A)},...U];m+=1;try{return await Yn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:E.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:B}})}finally{m-=1}}async function fu(p){let E={source:p.mutatedSource,files:[]},x=p.routeState.graph,w=p.routeState.pageCompositionProjection;if(!x||!w||w.status!=="supported"||!n.listFiles)return E;let M=w.placementUnitByKey.get(p.placementUnitKey)?.sourceRange;if(!M)return E;let _=[...x.elements.values()].find(O=>O.sourceFile===p.routeState.entryFile&&O.importedFrom&&C(O.sourceRange,M));if(!_?.importedFrom||!_.exportName)return E;let $=S(_.importedFrom),G="components/site/generated/";if(!$.startsWith(G))return E;let U=$.slice(G.length).split("/")[0];if(!U||!/-[0-9a-f]{8}$/i.test(U))return E;let B=`${G}${U}`;if([...x.elements.values()].filter(O=>O.sourceFile===p.routeState.entryFile&&S(O.importedFrom??"")===$).length!==1)return E;let ie=await n.listFiles({maxFiles:5e3,maxDepth:32}),xe=Array.isArray(ie)?ie:ie.files;if(!Array.isArray(ie)&&ie.truncated)return E;let he=xe.map(({path:O})=>O).filter(O=>O===B||O.startsWith(`${B}/`));if(he.length===0||!he.includes($))return E;for(let{path:O}of xe)if(!(O===p.routeState.entryFile||O===B||O.startsWith(`${B}/`)))try{if((await n.readFile(O)).includes(U))return E}catch{return E}let Ce=v(p.routeState.entryFile,$),Fe=or({source:p.mutatedSource,moduleSpecifier:Ce,imports:_.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:_.exportName}]});return Fe.ok?Fe.source.includes(U)?{source:Fe.source,files:[]}:{source:Fe.source,files:he.sort((O,J)=>O.localeCompare(J))}:E}async function Ry(p){if(n.getFileInfo){for(let _ of p)if(await n.exists(_.path)&&await n.getFileInfo(_.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${_.path}`,details:{path:_.path}}}for(let _ of p){if(_.operation!=="upsert"||!/^(?:src\/)?app\/globals\.css$/i.test(_.path))continue;let $=await n.exists(_.path)?await ua(n,_.path):null;if($?.ok){let G=Yw($.content,_.content);if(!G.ok)return{ok:!1,errorCode:"invalid-params",message:G.message,details:{path:_.path,code:G.code}}}}let E=wy(p);if(E.length===0)return{ok:!0};let x=SN(n,p),w=new Map,A=(_,$)=>{let G=w.get(_);if(G?.source===$)return G.result;let U=Wt(_,$);return w.set(_,{source:$,result:U}),U},M;try{M=await Lh(E,async _=>{let $=i.get(_);return $?[...(await fe($.entryFile,await x.readFile($.entryFile),x,{validationOnly:!0,parseModule:A,validatedImports:f.getImports})).parsedModules.values()]:[]})}catch(_){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${tt(_)}`,details:{compositionKeys:E}}}for(let _ of M)f.remember(_);return{ok:!0}}function wy(p){return p.map(x=>x.path).some(ny)?[...i.keys()]:[]}function Us(p,E,x,w){let A=Lo(E);return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Z(p),error:{code:A,message:x,...w?{details:w}:{}}}}async function Js(p){let E=[];for(let x of new Set(p))E.push(await Ny(x));return E}async function Ny(p){if(!(typeof n.exists=="function"?await n.exists(p):!0))return{file:p,content:"",version:Math.max(0,W(p)),exists:!1};let x=await n.readFile(p);return{file:p,content:x,version:Math.max(1,W(p)),exists:!0,sha256:Re(x)}}async function pu(p,E,x,w){if(!e.historyStore)return null;let A=new Map(E.map($=>[$.file,$])),M=new Map(x.map($=>[$.file,$])),_=[...new Set([...A.keys(),...M.keys()])].sort().map($=>{let G=A.get($),U=M.get($);return{path:$,preDigest:G?.exists===!1||!G?null:Re(G.content),postDigest:U?.exists===!1||!U?null:Re(U.content)}});return{schemaVersion:2,transactionId:`${p}:${w.expectedIndexDigest}`,operationId:p,phase:"prepared",historyTransition:w,files:_}}async function mu(p){return!p||!e.historyStore||await e.historyStore.writeTransactionJournal(p),p}async function Gn(p){p&&e.historyStore&&await e.historyStore.clearTransactionJournal(p.transactionId)}async function Xs(p,E){let x=[];try{for(let w of p)await gu(w),typeof n.bumpVersion=="function"&&n.bumpVersion(w.file),x.push(w.file)}catch(w){let A=await Py(E.filter(M=>x.includes(M.file)));return A.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${tt(w)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${A.failedFiles.join(", ")}: ${tt(w)}`,rolledBack:!1}}return{ok:!0,snapshots:p.map(Ay)}}async function gu(p){if(p.exists===!1){await n.deleteFile(p.file);return}await n.writeFile(p.file,p.content)}async function Py(p){let E=[];for(let x of p)try{await gu(x),typeof n.bumpVersion=="function"&&n.bumpVersion(x.file)}catch{E.push(x.file)}return E.length===0?{ok:!0}:{ok:!1,failedFiles:E}}function Ay(p){let E=p.exists!==!1;return{file:p.file,content:E?p.content:"",version:p.version,exists:E,...E?{sha256:Re(p.content)}:{}}}async function Yn(p){return y.runExclusive(()=>Ty(p))}async function Ty(p){let E=p.filePlan.edits.map(O=>O.file),x=o.resolveSelector(p.request.composition),w=x.context,A=p.historyPolicy==="none"?void 0:{initiatingComposition:w,affectedCompositions:hy(E)},M=await Js(E),_=new Map(M.filter(O=>O.exists!==!1).map(O=>[O.file,O.content])),$=yu(),G=new Map(d),U=new Set(g),B=new Set([...i.values()].filter(O=>p.filePlan.edits.some(J=>J.operation==="delete"&&J.file===O.entryFile)).map(O=>O.key)),te=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:Re(O.content)}),ie={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})},xe=null,he=!1,Ce=await Ps({overlay:_,exists:O=>n.exists(O),plan:ie,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:M,postSnapshots:te,...p.selectionRef?{selectionRef:p.selectionRef}:{},...p.output?{output:p.output}:{},...A?{provenance:A}:{}}),J=O?.historyTransition?O.historyTransition:e.historyStore?iN(await e.historyStore.readIndex()):null;if(e.historyStore&&!J)throw new Error("Durable history did not provide an exact index transition.");return xe=await pu(p.request.id,M,te,J),xe=await mu(xe),{history:O,historyTransition:J}},reverify:async()=>{},writeCandidate:async()=>{let O=await u.executeFilePlan(p.filePlan);if(!O.ok)throw new Ls(O);return{postSnapshots:await Js(O.affectedFiles),affectedFiles:O.affectedFiles,internalResultVersion:O.resultVersion}},validateCandidate:async({candidate:O,receipt:J})=>{let le=await Bo(J.affectedFiles,{changed:!0,minimumVersion:J.internalResultVersion,publish:!1,excludedCompositionKeys:B});if(le.failedRoutes.length>0)throw new zn(le.failedRoutes);let ye=bu($,le.candidateRouteStates??[]),ve=xu(ye,x.key);return{...O,rebuild:le,routeSnapshots:ye,resultVersion:ve,...Qh(p.selectionRef,ye.map(Te=>Te.state.document))?{selectionRef:Qh(p.selectionRef,ye.map(Te=>Te.state.document))}:{}}},publishCandidate:async({candidate:O,history:J,receipt:le})=>{J?.history&&(await l.publishPrepared(J.history),he=!0);let ye=O.resultVersion??le.internalResultVersion;return{composition:w,requestId:p.request.id,kind:p.request.kind,target:p.request.target,ok:!0,resultVersion:ye,affectedFiles:le.affectedFiles,fileChanges:le.postSnapshots.map(ve=>({path:ve.file,operation:ve.exists===!1?"delete":"upsert"})),...p.output?{output:p.output}:{},...O.selectionRef?{selectionRef:O.selectionRef}:{}}},swapCandidate:({candidate:O,receipt:J})=>{O.routeSnapshots&&jo(O.routeSnapshots),O.rebuild?.candidateSourceCache&&Oo(d,O.rebuild.candidateSourceCache),cu(J.postSnapshots)},finalizeCandidate:async()=>{await Gn(xe);for(let O of B)i.delete(O)},emitCommitted:({candidate:O,published:J})=>{Ks(J,O.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:O,receipt:J})=>{if(he)throw new Error("history was published before transaction finalization failed");if(J){let le=await Xs(M,J.postSnapshots);if(!le.ok)throw new Error(le.reason)}jo($),Oo(d,G),lu(U),O?.history&&await l.discardPrepared?.(O.history),await Gn(xe)}});if(Ce.ok)return Ce.published;if(Ce.stage==="precheck"||Ce.stage==="build")try{await Gn(xe)}catch(O){let J=await $o(tt(O));return pe(p.request,J,"Unable to clear an uncommitted transaction journal.")}if(Ce.recoveryRequired){let O=await $o(Ce.reason);return pe(p.request,O===V.RECOVERY_PERSIST_FAILED?O:V.ROLLBACK_FAILED,Ce.reason)}let Fe=Ce.error;return Fe instanceof Ls?{...pe(p.request,Lo(Fe.result.errorCode),Fe.result.reason),...Fe.result.affectedFiles?{affectedFiles:Fe.result.affectedFiles}:{}}:Fe instanceof zn?pe(p.request,V.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${tu(Fe.failedRoutes)}`,{failedRoutes:Fe.failedRoutes}):pe(p.request,Eu(Ce.stage),tt(Fe))}async function hu(p){return y.runExclusive(async()=>{let E=p==="undo"?await l.prepareUndo():await l.prepareRedo();return E?Fy(p,E):{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,E){let x=E.entry,w=p==="undo"?x.preSnapshots:x.postSnapshots,A=p==="undo"?x.postSnapshots:x.preSnapshots,M=w.map(J=>J.file),{context:_,key:$}=xy(x,M),G=await Js(M),U=new Map(G.filter(J=>J.exists!==!1).map(J=>[J.file,J.content])),B=D($),te=yu(),ie=new Map(d),xe=new Set(g),he=null,Ce=!1,Fe,O=await Ps({overlay:U,plan:{operationId:`${p}:${x.operationId}`,intents:w.map(J=>J.exists===!1?{kind:"delete",path:J.file}:{kind:"upsert",path:J.file,content:J.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(he=await pu(`${p}:${x.operationId}`,G,w,E.historyTransition),he=await mu(he),E),reverify:async()=>{},writeCandidate:async()=>{let J=await Xs(w,A);if(!J.ok)throw new Error(J.reason);return{snapshots:J.snapshots}},validateCandidate:async({candidate:J})=>{Fe=yy(x,M);let le=await Bo(M,{changed:!0,minimumVersion:B+1,publish:!1,affectedCompositionKeys:Fe});if(le.failedRoutes.length>0)throw new zn(le.failedRoutes);let ye=bu(te,le.candidateRouteStates??[]),ve=xu(ye,$);return{...J,rebuild:le,routeSnapshots:ye,resultVersion:ve}},publishCandidate:async({candidate:J,history:le,receipt:ye})=>{if(!le)throw new Error("history cursor intent is missing");await l.publishPrepared(le),Ce=!0;let ve=J.resultVersion??B+1;return{composition:_,requestId:p,kind:x.kind,target:x.target,ok:!0,resultVersion:ve,affectedFiles:M,fileChanges:ye.snapshots.map(Te=>({path:Te.file,operation:Te.exists===!1?"delete":"upsert"})),...x.output?{output:x.output}:{}}},swapCandidate:({candidate:J,receipt:le})=>{J.routeSnapshots&&jo(J.routeSnapshots),J.rebuild?.candidateSourceCache&&Oo(d,J.rebuild.candidateSourceCache),cu(le.snapshots)},finalizeCandidate:async()=>{await Gn(he)},emitCommitted:({candidate:J,published:le})=>Ks(le,J.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:J,receipt:le})=>{if(Ce)throw new Error("history cursor was published before transaction finalization failed");if(le){let ye=await Xs(A,le.snapshots);if(!ye.ok)throw new Error(ye.reason)}jo(te),Oo(d,ie),lu(xe),J&&await l.discardPrepared?.(J),await Gn(he)}});if(O.ok)return O.published;if(O.stage==="precheck"||O.stage==="build")try{await Gn(he)}catch(J){let le=await $o(tt(J));return{composition:_,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:B,error:{code:le,message:"Unable to clear an uncommitted transaction journal."}}}if(O.recoveryRequired){let J=await $o(O.reason);return{composition:_,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:B,affectedFiles:M,error:{code:J===V.RECOVERY_PERSIST_FAILED?J:V.ROLLBACK_FAILED,message:O.reason}}}return{composition:_,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:B,affectedFiles:M,error:{code:O.error instanceof zn?V.ROUTE_REBUILD_FAILED:Eu(O.stage),message:tt(O.error),...O.error instanceof zn?{details:{failedRoutes:O.error.failedRoutes}}:{}}}}function yu(){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 xu(p,E){return p.find(w=>w.key===E)?.state.graph?.version??o.initialVersions.get(E)??0}function bu(p,E){let x=new Map(p.map(w=>[w.key,w]));for(let w of E)x.set(w.key,w);return[...x.values()]}function jo(p){for(let E of i.values())N(E);for(let E of p){let x={...E.state,dependencyFiles:new Set(E.state.dependencyFiles),fileVersions:new Map(E.state.fileVersions)};i.set(E.key,x),R(x,x.dependencyFiles)}}async function zs(p){let E=i.get(p);if(!E)throw new Error(`Composition not found: ${p}`);if(E.graph)return;let x=await n.readFile(E.entryFile);await ct(p,x)}function Zn(p,E){let x=i.get(o.resolveSelector(E).key)??null;return!x||!Su(x,p)?null:x}function Su(p,E){if(p.documentIndex?.entriesByKey.has(E)||p.graph?.elements.has(E))return!0;let x=at(E);return x&&x!==E?p.graph?.elements.has(x)===!0:!1}function pe(p,E,x,w){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Z(p),error:{code:E,message:x,...w?{details:w}:{}}}}function Eu(p){return p==="validate"?V.ROUTE_REBUILD_FAILED:p==="publish"?V.HISTORY_COMMIT_FAILED:V.WRITE_IO_ERROR}async function $o(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 _y(p){let x=p.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(w=>w.charAt(0).toUpperCase()+w.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return x?`Prefab${x}`:"GeneratedPrefab"}function Ws(p){return p==="VERSION_STALE"?V.VERSION_STALE:p==="CROSS_PAGE_MOVE_UNSUPPORTED"?V.CROSS_PAGE_MOVE_UNSUPPORTED:V.UNSUPPORTED_OPERATION}async function vu(p){if(p.target.kind==="route"){let x=i.get(o.resolveSelector(p.target.composition).key)??null;return x?(x.graph||await zs(x.key),x):pe(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 zs(x.key),x):pe(p,V.ROUTE_NOT_FOUND,"Composition not found for page-unit target.")}if(p.target.kind!=="node")return pe(p,V.UNSUPPORTED_OPERATION,`${p.kind} source target execution is not implemented yet.`);let E=i.get(o.resolveSelector(p.composition).key)??null;return E?(E.graph||await zs(E.key),Su(E,p.target.key)?E:pe(p,V.NODE_NOT_FOUND,`Target key not found: ${p.target.key}`)):pe(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(),d.clear(),f.clear(),g.clear()},registerComposition(p,E){let x=o.register({context:p,entryFile:E}),w=i.get(x.key);if(w?.entryFile===E)return;w&&N(w);let A=Zh(x.context,E);i.set(x.key,A),R(A,A.dependencyFiles),r.emit({type:"graph-invalidated",composition:x.context})},unregisterComposition(p){let E=o.resolveSelector(p),x=i.get(E.key);x&&(N(x),i.delete(E.key),o.unregister(E.key),i.size===0&&(t="idle"),r.emit({type:"graph-invalidated",composition:E.context}))},getCompositionEntryFiles(){return[...i.values()].map(p=>p.entryFile)},getCompositionContext(p){return o.resolveSelector(p).context},async initializeComposition(p){let E=o.resolveSelector(p),x=i.get(E.key);if(!x)throw new Error(`Composition not registered: ${E.key}`);if(x.graph)t="ready";else{t="building";try{let w=await n.readFile(x.entryFile);await ct(E.key,w),t="ready",r.emit({type:"graph-ready",composition:E.context,version:i.get(E.key)?.graph?.version??0})}catch(w){throw t="idle",r.emit({type:"graph-error",composition:E.context,message:tt(w)}),w}}},getDocument(p){let E=o.resolveSelector(p),x=i.get(E.key);if(!x)throw new Error(`Composition not registered: ${E.key}`);if(!x.document)throw new Error(`Composition not built: ${E.key}`);return x.document},async getHistoryStatus(){await b;let p=await l.getStatus?.();return p?{...p,recoveryRequired:h}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:h}},getObjectEditContext(p,E,x){let w=Zn(p,E),A=at(p)??p;if(w?.graph&&w.topology&&w.capabilities&&w.detailProjections){let M=w.detailProjections.get(A);if(M){let _=w.graph.elements.get(A);if(!_)throw new Error(`Key not found: ${p}`);let $=fN(p,A,x),G=new Map;if(M.isRepeat&&$?.instanceIndex!==void 0)for(let te of _.attributes??[])G.set(te.name,Al({file:_.sourceFile,source:d.get(_.sourceFile)??"",element:_,propertyName:te.name,selectionRef:$,graph:w.graph,sources:d}));let U=ph({element:_,graph:w.graph,source:d.get(_.sourceFile),documentVersion:w.graph.version,selectionRef:x,isRepeat:M.isRepeat,propertyProvenance:M.propertyProvenances,repeatTargets:G}),B=hh(A,w.graph,w.topology,w.capabilities,M.textSources,M.provenances,M.dynamicData,U);return p===A?B:Uh(B,p,w.document??null,w.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getRenderDetail(p,E){let x=Zn(p,E),w=at(p)??p;if(x?.graph&&x.topology&&x.capabilities&&x.detailProjections){let A=x.detailProjections.get(w);if(A){let M=gh(w,x.graph,x.topology,x.capabilities,A.textSources,A.writeTarget,A.provenances,A.conditional,A.componentSemantic,A.styleSource,A.dynamicData);return p===w?M:Kh(M,p,x.document??null,x.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getClassNameSource(p,E){let x=Zn(p,E),w=at(p)??p;if(!x?.graph)throw new Error(`Key not found: ${p}`);let A=x.graph.elements.get(w);if(!A)throw new Error(`Key not found: ${p}`);let M=d.get(A.sourceFile);if(M===void 0)throw new Error(`Source not loaded: ${A.sourceFile}`);return Pa({key:w,route:{composition:x.composition,routeId:x.routeId,graph:x.graph,source:M}})},refreshSourceForKey:Sy,async execute(p){if(await b,h)return pe(p,V.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(p.kind==="source-edit")return Ey(p);if(p.kind==="insert-page-resource")return vy(p);if(p.kind==="delete-page-source")return ky(p);let E=await vu(p);if("ok"in E)return E;await du(p);let x=await vu(p);if("ok"in x)return x;let w=x;if(p.target.kind==="page-unit"){let B=p;return p.kind==="insert-child"||p.kind==="replace-node"?Iy(B,w):p.kind==="move-node"||p.kind==="remove-node"?Cy(B,w):pe(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 M=p.params,_=p.target.kind==="node"?p.target.key:null;if(M.kind==="move-node"&&"kind"in M.target&&M.target.kind==="source-sibling"){let B=M.target,te=_?w.document?.entries.find(J=>J.key===_):null,ie=w.document?.entries.find(J=>J.key===B.anchorKey),xe=te?.pageCompositionActionScope,he=xe?.kind==="source-siblings"?xe.siblingKeys:null,Ce=he?.indexOf(te?.key??"")??-1,Fe=he?.indexOf(B.anchorKey)??-1,O=B.relation==="before"?Ce-1:Ce+1;if(!te||!ie||!he||Ce<0||Fe!==O||ie.pageCompositionActionScope?.kind!=="source-siblings"||ie.pageCompositionActionScope.siblingKeys.length!==he.length||ie.pageCompositionActionScope.siblingKeys.some((J,le)=>J!==he[le])||!te.operationSummary.canMove)return pe(p,V.INVALID_TARGET,"Source sibling move is unavailable because the current source sibling scope or adjacent anchor no longer matches.")}if(!w.graph||!w.topology||!w.capabilities)return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Z(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 $=AN(w,w.graph,w.capabilities,d,i),G=await new us($).plan(p);if(!G.ok)return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Z(p),error:{code:Lo(G.errorCode),message:G.reason}};let U=G.plan;if(U.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:Z(p),affectedFiles:[]}:{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Z(p),error:{code:V.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};m+=1;try{if(U.steps.some(te=>te.type==="invoke-external-adapter")){let te=await u.execute(U);if(!te.ok)return pe(p,Lo(te.errorCode),te.reason);let ie={composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!0,resultVersion:Math.max(Z(p),te.resultVersion),affectedFiles:te.affectedFiles,...te.selectionRef?{selectionRef:te.selectionRef}:{}};return Ks(ie,{rebuiltRoutes:[],failedRoutes:[]}),ie}let B=await u.prepareRewritePlan(U);return B.ok?await Yn({request:p,filePlan:B.filePlan,...B.selectionRef?{selectionRef:B.selectionRef}:{}}):pe(p,Lo(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:Z(p),error:{code:V.INTERNAL_ERROR,message:tt(B)}}}finally{m-=1}},async undo(p){if(await b,h)return{composition:o.entries[0].context,requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:D(o.entries[0].key),error:{code:V.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};m+=1;try{return await hu("undo")}finally{m-=1}},async redo(p){if(await b,h)return{composition:o.entries[0].context,requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:D(o.entries[0].key),error:{code:V.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};m+=1;try{return await hu("redo")}finally{m-=1}},notifyFileChanged(p){su([p])},getAffectedCompositions(p){return gy(p)},subscribe(p){return r.subscribe(p)}}}function kN(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function IN(e,t,n,r){let o=new Map,i=new Map,s=(d,f,g)=>{let m=d.get(f)??new Set,h=m.size;return m.add(g),d.set(f,m),m.size!==h},a=(d,f)=>{if(!d.importedFrom)return!1;if(d.exportName==="default")return s(i,d.importedFrom,f);let g=s(o,`${d.importedFrom}#${d.tag}`,f);return d.exportName&&d.exportName!==d.tag&&(g=s(o,`${d.importedFrom}#${d.exportName}`,f)||g),g},c=d=>o.get(`${d.sourceFile}#${d.componentName}`)??i.get(d.sourceFile);for(let d of t.elements.values()){if(d.sourceFile!==n.entryFile||!d.importedFrom||!/^[A-Z]/.test(d.tag))continue;let f=n.placements.find(m=>m.members.some(h=>h.sourceRange!==null&&Do(d.sourceRange,h.sourceRange)));if(!f)continue;let g=f.placementUnitKey;a(d,g)}let l=!0;for(;l;){l=!1;for(let d of t.elements.values()){if(d.sourceFile===n.entryFile||!d.importedFrom||!/^[A-Z]/.test(d.tag))continue;let f=c(d);if(f)for(let g of f)l=a(d,g)||l}}let u=n.placements.find(d=>d.placementKey===n.container.placementKey&&d.relation==="append");for(let d of e.entries){let f=at(d.key)??d.key,g=t.elements.get(d.key)??t.elements.get(f);if(!g)continue;if(g.sourceFile===n.entryFile){if(n.container.sourceRange&&Do(g.sourceRange,n.container.sourceRange)&&u){d.pageCompositionUnitKey=u.placementUnitKey;continue}let y=n.placements.find(b=>b.members.some(S=>S.sourceRange!==null&&(Do(g.sourceRange,S.sourceRange)||PN(S.sourceRange,g.sourceRange))));if(y){d.pageCompositionUnitKey=y.placementUnitKey;continue}}let m=o.get(`${g.sourceFile}#${g.componentName}`);if(m){m.size===1&&(d.pageCompositionUnitKey=m.values().next().value);continue}let h=i.get(g.sourceFile);h?.size===1&&(d.pageCompositionUnitKey=h.values().next().value)}CN(e,t,n,r)}function CN(e,t,n,r){let o=new Map(e.entries.map(f=>[f.key,f])),i=e.entries.filter(f=>{let g=f.pageCompositionUnitKey;return g?f.parentKey?o.get(f.parentKey)?.pageCompositionUnitKey!==g:!0:!1}),s=new Map,a=(f,g)=>{s.set(f,Math.min(2,(s.get(f)??0)+g))},c=f=>n.placements.some(g=>g.members.some(m=>m.sourceRange!==null&&Do(f.sourceRange,m.sourceRange)));for(let f of t.elements.values())f.sourceFile!==n.entryFile||!f.importedFrom||!/^[A-Z]/.test(f.tag)||!c(f)||a(`${f.importedFrom}#${f.exportName??f.tag}`,1);let l=[...t.elements.values()].flatMap(f=>f.sourceFile!==n.entryFile&&f.importedFrom&&/^[A-Z]/.test(f.tag)?[{owner:`${f.sourceFile}#${f.componentName}`,ownerDefault:`${f.sourceFile}#default`,target:`${f.importedFrom}#${f.exportName??f.tag}`}]:[]);for(let f=0;f<=l.length;f+=1){let g=!1;for(let m of l){let h=s.get(m.owner)??s.get(m.ownerDefault)??0;if(!h)continue;let y=s.get(m.target)??0,b=Math.min(2,y+h);b!==y&&(s.set(m.target,b),g=!0)}if(!g)break}let u=f=>s.get(`${f.sourceFile}#${f.componentName}`)??s.get(`${f.sourceFile}#default`)??0;for(let f of i){f.pageCompositionActionScope={kind:"unavailable"};let g=t.elements.get(f.key);f.pageCompositionUnitKey&&g?.sourceFile===n.entryFile&&(f.pageCompositionActionScope={kind:"route-unit"})}let d=new Map;for(let f of i){let g=t.elements.get(f.key);if(!g||g.sourceFile===n.entryFile||f.key!==(at(f.key)??f.key))continue;let m=r.get(g.sourceFile);if(!m)continue;let h=ue(m.ast,{kind:"jsx-node",strategy:"source-range",sourceRange:g.sourceRange});if(!h.ok||!h.match.path.isJSXElement())continue;let y=h.match.path,b=y.parentPath;if(!b||!b.isJSXFragment()&&!(b.isJSXElement()&&Oe(b))){u(g)===1&&ey(y)&&(f.pageCompositionActionScope={kind:"route-unit"});continue}if(!ey(b))continue;let S=d.get(b.node)??[];S.push({entry:f,element:g,parentPath:b}),d.set(b.node,S)}for(let f of d.values()){let g=f[0];if(!g)continue;let m=g.entry.pageCompositionUnitKey,h=[],y=!!(m&&u(g.element)===1);for(let S of g.parentPath.node.children){if(RN(S))continue;if(!wN(S)){y=!1;break}let v=[...t.elements.values()].find(P=>P.sourceFile===g.element.sourceFile&&P.componentName===g.element.componentName&&Do(P.sourceRange,NN(S))),C=v?o.get(v.identity.key):null;if(!v||!C||C.parentKey||C.pageCompositionUnitKey!==m||u(v)!==1){y=!1;break}h.push(C)}if(!y||h.length!==f.length||f.some(({entry:S})=>!h.some(v=>v.key===S.key)))continue;if(h.length===1){h[0].pageCompositionActionScope={kind:"route-unit"};continue}if(h.length<2)continue;let b=h.map(S=>S.key);for(let S of h)S.pageCompositionActionScope={kind:"source-siblings",siblingKeys:b}}}function ey(e){let t=e.parentPath;return!!(t?.isReturnStatement?.()||t?.isArrowFunctionExpression?.()&&t.node.body===e.node)}function RN(e){return!!(e&&typeof e=="object"&&e.type==="JSXText"&&!(e.value??"").trim())}function wN(e){return!!(e&&typeof e=="object"&&e.type==="JSXElement")}function NN(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 Do(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function PN(e,t){return ty(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&ty(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function ty(e,t,n,r){return e!==n?e-n:t-r}function AN(e,t,n,r,o){let i=new Map,s=new Map,a=(u,d)=>{if(s.has(u))return;s.set(u,d);let f=t.elements.get(u);for(let g of f?.childKeys??[])a(g,d)};for(let u of t.regions)if(u.kind==="repeat-region")for(let d of u.childKeys)i.set(d,u.ownerKey),a(d,u.ownerKey);return{getNode(u){let d=c(u),f=t.elements.get(d.baseKey);return f?l(u,f):null},getChildNodes(u){let d=c(u),g=e.documentIndex?.entriesByKey.get(u)?.childKeys;if(g)return g.map(h=>{let y=at(h)??h,b=t.elements.get(y);return b?l(h,b):null}).filter(h=>h!==null);let m=t.elements.get(d.baseKey);return m?m.childKeys.map(h=>{let y=t.elements.get(h);return y?l(h,y):null}).filter(h=>h!==null):[]},getKnownSourceFiles(){return[...r.entries()].map(([u,d])=>({file:u,content:d}))},getRouteEntryFiles(){return[...o.values()].map(u=>u.entryFile)},getCapability(u){let d=c(u),f=n.get(d.baseKey);return f?{...f,key:u,constraints:f.constraints.map(g=>({...g})),...f.editModes?{editModes:{...f.editModes}}:{}}:{composition:e.composition,key:u,canUpdateText:!1,canRemove:!1,canInsertChild:!1,canMove:!1,constraints:[]}},getFileContent(u){return r.get(u)??""},getFileVersion(u){return Math.max(e.fileVersions.get(u)??0,t.version)},getRouteEntryFile(u){return e.routeId===u?e.entryFile:null},getComponentSemantic(u){let d=c(u);return e.detailProjections?.get(d.baseKey)?.componentSemantic??null},getClassNameSource(u){let d=c(u),f=t.elements.get(d.baseKey),g=f?r.get(f.sourceFile):void 0;return!f||g===void 0?null:Pa({key:d.baseKey,route:{composition:e.composition,routeId:e.routeId,graph:t,source:g}})},getEditableTextSegmentIndex(u){let d=c(u),g=e.detailProjections?.get(d.baseKey)?.textTargets.keys()?.next();return g&&!g.done?g.value:null},async getTextWriteTarget(u,d){let f=c(u);return eu(e.detailProjections?.get(f.baseKey)?.textTargets.get(d)??null,f.repeatIndex)},async getElementPropertyWriteTarget(u,d){let f=c(u);return eu(e.detailProjections?.get(f.baseKey)?.elementPropertyTargets.get(d)??null,f.repeatIndex)},getPropertyState(u,d,f){let g=c(u),m=t.elements.get(g.baseKey);if(!m)return null;let y=e.detailProjections?.get(g.baseKey)?.propertyProvenances.get(d);if(y)return y;let b=m.attributes?.find(S=>S.name===d);return b?b.source?{status:"blocked",owner:"generic",diagnostic:{code:"unsupported-property-source",message:`Property '${d}' has an unresolved value source`}}:{status:"direct",owner:"generic",attribute:b,target:{kind:"jsx-attribute",file:m.sourceFile,sourceRange:b.sourceRange}}:(m.attributeSpreads?.length??0)>0?{status:"blocked",owner:"generic",diagnostic:{code:"ambiguous-property-source",message:`A spread may provide or override property '${d}'`}}:{status:"missing",owner:"generic"}},getRepeatPropertyTarget(u,d,f){let g=c(u),m=t.elements.get(g.baseKey);if(!m)return{ok:!1,errorCode:"repeat-not-found",reason:`Node not found: ${u}`};let h=f?{...f,key:g.baseKey}:g.repeatIndex!==null?{key:g.baseKey,instanceIndex:g.repeatIndex}:void 0;return Al({file:m.sourceFile,source:r.get(m.sourceFile)??"",element:m,propertyName:d,selectionRef:h,graph:t,sources:r})},getTextProvenance(u,d){let f=c(u);return e.detailProjections?.get(f.baseKey)?.provenances.get(d)??null}};function c(u){let d=eN(u);return d?{baseKey:d.baseKey,repeatIndex:Vh(e.document??null,u,d.baseKey,e.documentIndex)??$h(d)}:{baseKey:u,repeatIndex:null}}function l(u,d){let f=at(u)??u,g=e.documentIndex?.entriesByKey.get(u);return{key:u,file:d.sourceFile,component:d.componentName,tag:d.tag,structuralPath:d.identity.structuralPath,sourceRange:d.sourceRange,parentKey:g?.parentKey??d.parentKey??void 0,isRepeatRegion:d.boundaryKind==="repeat-region"||s.has(f),isBoundary:!1,importedFrom:d.importedFrom,exportName:d.exportName,isRepeatItemRoot:i.has(f),repeatOwnerKey:i.get(f)??s.get(f),attributes:d.attributes?.map(m=>({name:m.name,value:m.value,source:m.source?{expression:m.source.expression,base:m.source.base,path:m.source.path.map(h=>({...h}))}:null,resolvedValue:m.resolvedValue}))}}}var TN={"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 Lo(e){return TN[e]}function tt(e){return e instanceof Error&&e.message?e.message:String(e)}function ny(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function FN(e){let t=Wn(e);if(!rN.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=>oN.map(a=>`${s}/${a}`))}function _N(e){let n=Wn(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function MN(e){return iy(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function ON(e){return iy(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function iy(e,t){let n=[];for(let r of e.matchAll(t)){let o=sy(r[1]??"");o&&n.push(o)}return n}function ry(e,t){let n=sy(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?Wn(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?Wn(`${LN(e)}/${n}`):n.startsWith("/")?Wn(n.slice(1)):ru(n)?Wn(n):null}function sy(e){return e.split(/[?#]/,1)[0]?.trim()??""}function ru(e){return/\.css$/i.test(e)}function LN(e){let t=Wn(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function DN(e){return Array.from(new Set(e))}function Wn(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 BN(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 Bs=class{constructor(t){this.options=t,this.fileSystem=new _r(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}getDocument(t){return Ho(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 Go(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return Qo(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}getSourceFile(t){return qo(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}resolveSourceLocation(t){return ei(t,this.engine.getRenderDetail(t.key,t.composition))}async planOperation(t){let n=$N.safeParse(t);if(!n.success)return{result:Wo(t,n.error.issues.map(i=>i.message))};let r=new _r(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:An(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let c=VN.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(l=>KN(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 Ds({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=Yo(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 KN(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:Re(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:Re(e.before)},fullContent:e.after}}function UN(e){return new Bs(e)}import{SiteEditOperationRequestSchema as zN}from"@vcp-dev/contracts";import _t from"node:fs/promises";import nt from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as JN,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as XN}from"@vcp-dev/contracts";var js=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=Ds({...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 Qo(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.engine.getCompositionEntryFiles()})}getSourceFile(t){return qo(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.engine.getCompositionEntryFiles()})}resolveSourceLocation(t){return ei(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 _t.readFile(nt.join(n,r),"utf8")},async readFileBytes(r){return _t.readFile(nt.join(n,r))},async getFileInfo(r){let o=nt.join(n,...r.split("/"));try{let i=await _t.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await bi(nt.join(n,r),o)},async createExclusive(r,o){let i=nt.join(n,r);await _t.mkdir(nt.dirname(i),{recursive:!0});let s=await _t.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await _t.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await _t.rm(nt.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=nt.join(n,i),a=nt.dirname(nt.join(n,o));for(;a!==s&&a.startsWith(`${s}${nt.sep}`);){try{await _t.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=nt.dirname(a);continue}break}a=nt.dirname(a)}},async exists(r){try{return await _t.access(nt.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...XN,...JN],i=[],s=new Set,a=new Set,c=0;for(let d of o)await u(d,i,1);let l=i.sort((d,f)=>d.path.localeCompare(f.path));return a.size>0?{files:l,truncated:{reasons:[...a]}}:{files:l};async function u(d,f,g){if(r.maxDepth!==void 0&&g>r.maxDepth){a.add("max-depth");return}let m=nt.join(n,...d.split("/")),h;try{h=await _t.lstat(m)}catch{return}if(h.isSymbolicLink())return;if(h.isFile()){let b=h.ino>0?`${String(h.dev)}:${String(h.ino)}`:null;if(b&&s.has(b))return;if(r.maxFiles!==void 0&&f.length>=r.maxFiles){a.add("max-files");return}if(r.maxTotalBytes!==void 0&&c+h.size>r.maxTotalBytes){a.add("max-total-bytes");return}b&&s.add(b),f.push({path:d,sizeBytes:h.size}),c+=h.size;return}if(!h.isDirectory())return;if(r.maxFiles!==void 0&&f.length>=r.maxFiles){a.add("max-files");return}let y=await _t.readdir(m,{withFileTypes:!0});for(let b of y)b.isSymbolicLink()||await u(`${d}/${b.name}`,f,g+1)}},getVersion(r){return t.get(r)??1},bumpVersion(r){let o=(t.get(r)??1)+1;return t.set(r,o),o}}}};function ou(e){return new js(e)}var $s=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=ou({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=Yo(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:Ho(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:Go(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=zN.safeParse(r);if(!o.success)return Wo(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:An(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:An(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:An(n)}}notifyFileChanged(t){this.engine.notifyFileChanged(t)}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}dispose(){this.listeners.clear(),this.engine.dispose()}};function WN(e){return new $s(e)}var cy=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,ly=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,HN=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,GN=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,YN=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,ZN=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,QN=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,qN=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,eP=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,tP=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,nP=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,rP=/\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,oP=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,iP=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function sP(e,t){let n=Vs([...kt(e,HN),...kt(e,GN),...kt(e,YN),...kt(e,t.includeRgbBackgroundImage?ZN:QN),...t.includeExtendedColorFunctions?[...kt(e,qN),...kt(e,eP)]:[]]),r=Vs([...kt(e,tP),...kt(e,nP)]).filter(o=>t.colorMixPolicy==="always"||cy.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...kt(e,rP).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...kt(e,iP).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:Vs(kt(e,ly)),hardCodedSurfaceOccurrences:lP(e),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?aP(e):[]}}function aP(e){return Vs(kt(e,oP))}function kt(e,t){return e.match(new RegExp(t.source,t.flags))??[]}var ay=160,cP=/((?:[a-z][a-z0-9-]*(?:\[[^\]]*\])?:)+)$/;function lP(e){let t=new RegExp(ly.source,"g"),n=[0];for(let s=0;s<e.length;s+=1)e[s]===`
13
+ `&&n.push(s+1);let r=s=>{let a=0,c=n.length-1;for(;a<c;){let l=Math.ceil((a+c)/2);(n[l]??0)<=s?a=l:c=l-1}return a},o=[],i;for(;(i=t.exec(e))!==null;){let s=i[0],a=s.endsWith("/")?s.slice(0,-1):s,c=/^\/(\d+)/.exec(e.slice(i.index+a.length)),l=e.slice(Math.max(0,i.index-64),i.index),u=cP.exec(l),d=r(i.index),f=e.indexOf(`
14
+ `,i.index),g=e.slice(n[d]??0,f===-1?void 0:f).trim();o.push({token:a,variant:u?.[1]??"",alpha:c?Number(c[1]):null,line:d+1,snippet:g.length>ay?`${g.slice(0,ay-1)}\u2026`:g})}return o}function Vs(e){return[...new Set(e)]}export{ce as FileHistoryStoreError,so as PageTemplateManagedSourceError,$s as PreviewFileSystemSiteEditEngineRuntime,cy as SITE_EDIT_RAW_COLOR_LITERAL_RE,Bs as SnapshotSiteEditEngineRuntime,Ko as checkComponentI18nHostCompatibility,yp as computeManagedPageTemplatePaths,WN as createPreviewSiteEditEngineRuntime,UN as createSiteEditEngineRuntime,mp as decodePageTemplateKey,Pc as encodePageTemplateId,rx as instrumentSiteEditRuntimeAttributes,xp as isManagedPageTemplateSourcePath,of as openFileHistoryStore,Vy as parseSourceModule,Ky as resolveImportBase,Vk as resolveManagedPageTemplateComposition,zi as scanManagedPageTemplateCandidates,Sp as scanSiteEditCompositionsFromFiles,sP as scanSiteEditThemeStyleViolations};