@vcp-dev/site-edit-engine 0.6.11 → 0.7.0
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/README.md +5 -2
- package/dist/index.d.ts +2 -0
- package/dist/index.js +11 -11
- package/dist/internal/protocol/capability.d.ts +2 -0
- package/dist/internal/protocol/event.d.ts +8 -4
- package/dist/internal/protocol/operation.d.ts +3 -1
- package/dist/internal/protocol/render.d.ts +4 -1
- package/dist/next-app-router.d.ts +2 -1
- package/dist/next-app-router.js +1 -1
- package/dist/page-template-managed-source.d.ts +59 -0
- package/dist/preview-runtime.d.ts +295 -22
- package/dist/runtime.d.ts +44 -15
- package/dist/types.d.ts +32 -22
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import{SiteEditOperationRequestSchema as ik,SiteEditPatchPlanSchema as sk}from"@vcp-dev/contracts";function jt(e){return{requestId:e.requestId,kind:e.kind,target:e.target,resultVersion:e.resultVersion,affectedFiles:e.affectedFiles,...e.output?{output:e.output}:{},...e.selectionRef?{selectionRef:e.selectionRef}:{}}}function Rr(e,t){return{ok:!1,error:{code:"INVALID_PARAMS",message:t[0]??"Site edit operation request failed contract validation."},data:{requestId:e.id,kind:e.kind,target:e.target,resultVersion:e.documentVersion}}}function Pr(e,t){if(!e.pageComposition)throw new Error("RenderDocument is missing the required Page Composition projection.");return{siteId:t.siteId,snapshotId:t.snapshotId,routeId:e.routeId,version:e.version,entries:e.entries.map(n=>({key:n.key,...n.pageCompositionUnitKey?{pageCompositionUnitKey:n.pageCompositionUnitKey}:{},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 wr(e){return{key:e.key,tag:e.tag,label:e.label,sourceLocator:e.sourceLocator,isOpaque:e.isOpaque,ancestors:e.ancestors,componentName:e.componentName,sourceFile:e.sourceFile,capabilities:Kp(e.capabilities),provenanceChain:e.provenanceChain?{editMode:e.provenanceChain.editMode,diagnostics:e.provenanceChain.diagnostics}:void 0,dynamicData:e.dynamicData,textSegments:e.textSegments.map(t=>({index:t.index,editable:t.editable,sourceKind:t.source?.kind??null})),boundaryKind:e.boundaryKind}}function Ar(e,t){let n=new Date().toISOString();return e.type==="document-changed"?{type:"site-edit.document.changed",siteId:t.siteId,snapshotId:t.snapshotId,routeId:e.routeId,version:e.version,at:n}:e.type==="operation-completed"?{type:"site-edit.operation.completed",siteId:t.siteId,result:jt(e.result),at:n}:e.type==="operation-failed"?{type:"site-edit.operation.failed",siteId:t.siteId,requestId:e.requestId,error:e.error,at:n}:e.type==="capability-changed"?{type:"site-edit.capability.changed",siteId:t.siteId,routeId:"",keys:e.keys,at:n}:null}function Kp(e){return{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{composeSiteEditRepeatInstanceKey as Gb,getSiteEditSourceDeleteProtectionReason as Yb,isSiteEditTextSourcePath as Zb,parseSiteEditRepeatInstanceKey as Qb,SITE_EDIT_SOURCE_DELETE_CAPABILITY as qb,stripSiteEditRepeatInstanceKeys as ze}from"@vcp-dev/contracts";import{parse as eI}from"yaml";import To from"node:path";function On(e,t,n){return`${e}::${t}::${n}`}var M={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"};import di from"@babel/traverse";import*as x from"@babel/types";import{createHash as Wp}from"node:crypto";import*as cc from"@babel/parser";function $t(e,t,n,r){return{code:e,message:t,locatorKind:n,details:r}}function B(e,t,n,r,o){return{ok:!1,source:e,diagnostic:$t(t,n,r,o)}}function ni(e,t,n,r,o){return{ok:!1,source:e,diagnostic:$t(t,n,r,o)}}var Jp={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function it(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:cc.parse(t,{sourceType:"module",plugins:Jp[n]})}}catch(r){return{ok:!1,source:t,diagnostic:$t("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function ri(e,t){return it({source:e,profile:lc(t.kind)})}function oi(e,t){return it({source:e,profile:lc(t)})}function lc(e){return"next-app-entry"}function Bt(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"}import*as uc from"@babel/parser";import*as cn from"@babel/types";import*as Et from"node:path";var ii=[".tsx",".ts",".jsx",".js"],Xp=ii.map(e=>`/index${e}`);function dc(e){let t=null;try{t=uc.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return[]}return ai(t)}function ai(e){let t=[];for(let n of e.program.body)cn.isImportDeclaration(n)&&typeof n.source.value=="string"&&st(n.source.value)&&t.push(n.source.value),cn.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&st(n.source.value)&&t.push(n.source.value),cn.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&st(n.source.value)&&t.push(n.source.value);return si(e.program,t),t}function si(e,t){if(!e||typeof e!="object")return;let n=e;if(n.type==="CallExpression"&&n.callee?.type==="Import"){let r=n.arguments?.[0];r?.type==="StringLiteral"&&typeof r.value=="string"&&st(r.value)&&t.push(r.value)}for(let r of Object.values(n))if(Array.isArray(r))for(let o of r)si(o,t);else r&&typeof r=="object"&&si(r,t)}function st(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function ci(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=Et.dirname(e);return Et.join(n,t).replace(/\\/g,"/")}async function zp(e,t){if(ii.some(n=>e.endsWith(n))&&await t(e))return e;for(let n of ii){let r=`${e}${n}`;if(await t(r))return r}for(let n of Xp){let r=`${e}${n}`;if(await t(r))return r}return null}async function ln(e,t,n){let r=await Tr(e,t,n);return r.ok?r.path:null}async function Tr(e,t,n){let r=ci(e,t);try{if(!Hp(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 zp(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 Hp(e,t,n){if(!st(t)||t.includes("\0")||t.includes("\\")||Et.posix.isAbsolute(n))return!1;let r=Et.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!Et.posix.isAbsolute(e)}var li=(e,t)=>{let n=it({source:t,profile:Bt({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${Wp("sha256").update(t).digest("hex")}`,ast:n.ast,imports:ai(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};var Nr="components/ui";function Ut(e){if(!e)return!1;let t=ui(e);return t===Nr||t.startsWith(`${Nr}/`)||t.includes(`/${Nr}/`)||t.endsWith(`/${Nr}`)}function Dn(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?Ut(e.slice(2)):e.startsWith("./")||e.startsWith("../")?Ut(ui(`${Gp(t)}/${e}`)):Ut(e):!1}function ui(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 Gp(e){let t=ui(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}var Yp=typeof di=="function"?di:di.default;function Te(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 Zp(e){return/^[A-Z]/.test(e)}function yi(e){let t=e.openingElement;return x.isJSXIdentifier(t.name)?t.name.name==="Fragment":x.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function dn(e){return x.isJSXFragment(e)}function mc(e){return x.isJSXIdentifier(e.name)?e.name.name:x.isJSXMemberExpression(e.name)?hc(e.name):x.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function hc(e){return x.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:x.isJSXMemberExpression(e.object)?`${hc(e.object)}.${e.property.name}`:e.property.name}function Qp(e){return e.split(".")[0]??e}function qp(e){let t=e;for(;t;){let n=t.node;if(x.isFunctionDeclaration(n)&&n.id||x.isVariableDeclarator(n)&&x.isIdentifier(n.id))return n.id.name;if(x.isExportDefaultDeclaration(n)){let r=n.declaration;if(x.isFunctionDeclaration(r)&&r.id)return r.id.name;if(x.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function em(){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 tm(e){let t=new Map;for(let n of e.program.body){if(!x.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(x.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(x.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(x.isImportSpecifier(o)){let i=x.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function dt(e,t=[]){if(x.isIdentifier(e))return t.push(e.name),t;if(x.isObjectPattern(e)){for(let n of e.properties)x.isObjectProperty(n)?dt(n.value,t):x.isRestElement(n)&&dt(n.argument,t);return t}if(x.isArrayPattern(e)){for(let n of e.elements)n&&(x.isRestElement(n)?dt(n.argument,t):dt(n,t));return t}return x.isAssignmentPattern(e)?(dt(e.left,t),t):(x.isRestElement(e)&&dt(e.argument,t),t)}function St(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Fr(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 nm(e,t,n){e.set(t,{resolved:!0,value:n})}function xi(e,t){e.set(t,{resolved:!1})}function gc(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 Pe(e,t,n){if(x.isTSAsExpression(e)||x.isTSSatisfiesExpression(e)||x.isTSNonNullExpression(e)||x.isTypeCastExpression(e)||x.isParenthesizedExpression(e))return Pe(e.expression,t,n);if(x.isLogicalExpression(e))return fi([Pe(e.left,t,n),Pe(e.right,t,n)]);if(x.isConditionalExpression(e))return fi([Pe(e.consequent,t,n),Pe(e.alternate,t,n)]);if(x.isTemplateLiteral(e))return fi(e.expressions.filter(x.isExpression).map(i=>Pe(i,t,n)));if(x.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!x.isMemberExpression(e)&&!x.isOptionalMemberExpression(e))return null;let r=[],o=e;for(;x.isMemberExpression(o)||x.isOptionalMemberExpression(o);){if(o.computed)if(x.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(x.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&x.isExpression(o.property)){let i=Kt(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(!x.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return x.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:St(e,t),base:o.name,path:r}:null}function fi(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 Kt(e,t){if(x.isStringLiteral(e)||x.isNumericLiteral(e)||x.isBooleanLiteral(e))return e.value;if(x.isNullLiteral(e))return null;if(x.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(x.isIdentifier(e)){let n=Fr(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(x.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||x.isSpreadElement(r))return;let o=Kt(r,t);if(o===void 0)return;n.push(o)}return n}if(x.isObjectExpression(e)){let n={};for(let r of e.properties){if(!x.isObjectProperty(r)||r.computed||!x.isExpression(r.value))return;let o=null;if(x.isIdentifier(r.key)?o=r.key.name:x.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!x.isIdentifier(r.value))return;let s=Fr(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=Kt(r.value,t);if(i===void 0)return;n[o]=i}return n}if(x.isMemberExpression(e)){let n=Pe(e,"",t);if(!n)return;let r=Fr(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=gc(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(x.isCallExpression(e))return xc(e,t)??void 0}function yc(e,t,n){let r=Pe(e,n,t);if(!r)return x.isMemberExpression(e)||x.isBinaryExpression(e)||x.isLogicalExpression(e)||x.isConditionalExpression(e)||x.isCallExpression(e)?{value:St(e,n),source:null}:null;let o=Fr(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?gc(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 pi(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:em(),parentStack:[],valueScopes:i,importMap:o}}function hi(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of dt(o.id))xi(n,s);if(!x.isIdentifier(o.id)||!o.init||!x.isExpression(o.init))continue;let i=Kt(o.init,t);i!==void 0&&nm(n,o.id.name,i)}}function rm(e){let t=[];for(let n of e){if(x.isVariableDeclaration(n)){t.push(n);continue}x.isExportNamedDeclaration(n)&&n.declaration&&x.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function om(e,t,n){let r=[],o=0;for(let i of e)if(x.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:Te(i),editable:!0,source:null})}else if(x.isJSXExpressionContainer(i)&&x.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:Te(i),editable:!0,source:null});else if(x.isJSXExpressionContainer(i)&&x.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:Te(i),editable:!0,source:null}):r.push({index:o++,value:St(s,n),sourceRange:Te(i),editable:!0,source:Pe(s,n,t)})}else if(x.isJSXExpressionContainer(i)&&x.isExpression(i.expression)){let s=yc(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:Te(i),editable:!0,source:s.source})}return r}function im(e,t,n){let r=[];for(let o of e.attributes)if(!(!x.isJSXAttribute(o)||!x.isJSXIdentifier(o.name))){if(x.isStringLiteral(o.value)){r.push({name:o.name.name,value:o.value.value,sourceRange:Te(o),source:null});continue}if(x.isJSXExpressionContainer(o.value)&&x.isExpression(o.value.expression)){let i=Kt(o.value.expression,t);if(o.name.name==="className"){let a=typeof i=="string"?i:i===void 0?xc(o.value.expression,t):null;if(a){r.push({name:o.name.name,value:a,sourceRange:Te(o),source:null,resolvedValue:a});continue}}let s=yc(o.value.expression,t,n);if(i!==void 0&&typeof i!="string"&&typeof i!="number"){r.push({name:o.name.name,value:fc(i),sourceRange:Te(o),source:Pe(o.value.expression,n,t),resolvedValue:i});continue}if(!s){i!==void 0&&r.push({name:o.name.name,value:fc(i),sourceRange:Te(o),source:Pe(o.value.expression,n,t),resolvedValue:i});continue}r.push({name:o.name.name,value:s.value,sourceRange:Te(o),source:s.source})}}return r}function xc(e,t){let n=un(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function un(e,t){if(x.isStringLiteral(e))return[e.value];if(x.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(x.isNullLiteral(e))return[];if(x.isBooleanLiteral(e))return e.value?null:[];if(x.isIdentifier(e)||x.isMemberExpression(e)){if(x.isIdentifier(e)&&e.name==="undefined")return[];let n=Kt(e,t);return typeof n=="string"?[n]:null}if(x.isConditionalExpression(e)){let n=un(e.consequent,t),r=un(e.alternate,t);return!n||!r?null:[...n,...r]}if(x.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=Kt(e.left,t);return n===!1||n===null?[]:un(e.right,t)}if(x.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||x.isSpreadElement(r))return null;let o=un(r,t);if(!o)return null;n.push(...o)}return n}if(x.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!x.isObjectProperty(r))return null;let o=am(r.key);if(!o)return null;n.push(o)}return n}if(x.isCallExpression(e)){let n=sm(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!x.isExpression(o))return null;let i=un(o,t);if(!i)return null;r.push(...i)}return r}return null}function sm(e){return x.isIdentifier(e)?e.name:x.isMemberExpression(e)&&x.isIdentifier(e.property)?e.property.name:null}function am(e){return x.isIdentifier(e)?e.name:x.isStringLiteral(e)?e.value:null}function cm(e,t){let n=e.attributes.find(r=>x.isJSXAttribute(r)&&x.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!x.isJSXAttribute(n)||!x.isJSXExpressionContainer(n.value)?null:n.value.expression}function lm(e,t){for(let n of t){let r=cm(e,n);if(r)return r}return null}function um(e){return x.isJSXIdentifier(e.name)?e.name.name:null}function fc(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function dm(e){if(!x.isCallExpression(e)&&!x.isOptionalCallExpression(e))return null;let t=e.callee;return!x.isMemberExpression(t)&&!x.isOptionalMemberExpression(t)||!x.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!x.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function mi(e){return x.isArrowFunctionExpression(e)||x.isFunctionExpression(e)}function fm(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function pm(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function pc(e,t,n,r){if(!e||!x.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:St(e,n),collectionSource:Pe(e,n,r)};if(t){let i=t.params[0],s=t.params[1];x.isIdentifier(i)&&(o.itemParamName=i.name),x.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function bt(e,t,n){if(!e)return[];if(x.isJSXElement(e)){if(yi(e))return Lr(e.children,t,n);let r=Or(e,t,n);return r?[r]:[]}return dn(e)?Dr(e,t,n):x.isParenthesizedExpression(e)?bt(e.expression,t,n):x.isExpression(e)?jr(e,t,n):[]}function _r(e,t,n){let r=new Map;for(let o of e.params)for(let i of dt(o))xi(r,i);t.valueScopes.push(r);try{if(!x.isBlockStatement(e.body))return bt(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return Ec(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function Ec(e,t,n){let r=[];for(let o of e){if(x.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];i&&hi([o],t,i);continue}r.push(...gi(o,t,n))}return r}function gi(e,t,n){if(x.isReturnStatement(e))return e.argument?bt(e.argument,t,n):[];if(x.isBlockStatement(e))return Vt(e.body,t,n);if(x.isIfStatement(e)){let r=x.isBlockStatement(e.consequent)?Vt(e.consequent.body,t,n):gi(e.consequent,t,n),o=e.alternate?x.isBlockStatement(e.alternate)?Vt(e.alternate.body,t,n):gi(e.alternate,t,n):[];return[...r,...o]}if(x.isSwitchStatement(e))return Vt(e.cases.flatMap(r=>r.consequent),t,n);if(x.isTryStatement(e)){let r=Vt(e.block.body,t,n);return e.handler&&r.push(...Vt(e.handler.body.body,t,n)),e.finalizer&&r.push(...Vt(e.finalizer.body,t,n)),r}return[]}function Vt(e,t,n){let r=new Map;t.valueScopes.push(r);try{return Ec(e,t,n)}finally{t.valueScopes.pop()}}function Mr(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:Te(r),sourceCandidates:i&&i.length>0?i:void 0})}function mm(e,t,n,r){let o=lm(e.openingElement,["items","dataSource","data"]),i={key:t,tag:mc(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!x.isJSXAttribute(s))continue;let a=um(s);if(!a||!x.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!x.isJSXEmptyExpression(c)){if(fm(a)&&mi(c)){let l=_r(c,n,r),u=pc(o,c,r,n);Mr(n,"repeat-region",t,s,l,u?[u]:void 0);continue}if(pm(a)){let l=mi(c)?_r(c,n,r):bt(c,n,r);Mr(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!x.isJSXExpressionContainer(s)||!mi(s.expression))continue;let a=_r(s.expression,n,r),c=pc(o,s.expression,r,n);Mr(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function Or(e,t,n){let r=mc(e.openingElement);if(r==="Fragment"||yi(e))return Lr(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=Zp(r),a;if(s){let P=t.ordinalTracker.getOrdinal(i,r);a=`component:${r}#${P}`}else{let P=t.ordinalTracker.getOrdinal(i,r);a=`${r}#${P}`}let c=o?t.elements.get(o.key)?.identity.structuralPath:void 0,l=c?`${c}/${a}`:a,u=On(t.file,t.componentName,l),d={file:t.file,component:t.componentName,structuralPath:l,key:u},m=s?"component-boundary":null,p=om(e.children,t,n),h=im(e.openingElement,t,n),E,C,v=!1;if(s){let P=t.importMap.get(r)??t.importMap.get(Qp(r));P&&(E=P.specifier,C=P.exportName,v=Dn(P.specifier,t.file))}let T={identity:d,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:Te(e),parentKey:i,childKeys:[],textSegments:p,attributes:h.length>0?h:void 0,boundaryKind:m,isOpaque:s,...v?{isPublicUiComponent:!0}:{},importedFrom:E,exportName:C};return t.elements.set(u,T),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(u),mm(e,u,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:u,tag:r}),hm(e.children,t,n),t.parentStack.pop()),u}function Dr(e,t,n){return Lr(e.children,t,n)}function Lr(e,t,n){let r=[];for(let o of e)if(x.isJSXElement(o))if(yi(o))r.push(...Lr(o.children,t,n));else{let i=Or(o,t,n);i&&r.push(i)}else dn(o)?r.push(...Dr(o,t,n)):x.isJSXExpressionContainer(o)&&r.push(...jr(o.expression,t,n));return r}function hm(e,t,n){for(let r of e)x.isJSXElement(r)?Or(r,t,n):dn(r)?Dr(r,t,n):x.isJSXExpressionContainer(r)&&jr(r.expression,t,n)}function gm(e){return e==="&&"||e==="||"||e==="??"}function jr(e,t,n){if(x.isJSXEmptyExpression(e))return[];let r=dm(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,c={kind:"repeat-template",collectionExpression:St(r.collection,n),collectionSource:Pe(r.collection,n,t)};if(x.isArrowFunctionExpression(a)||x.isFunctionExpression(a)){let u=a.params[0],d=a.params[1];x.isIdentifier(u)&&(c.itemParamName=u.name),x.isIdentifier(d)&&(c.indexParamName=d.name)}s.push(c);let l={kind:"repeat-region",ownerKey:i?.key??"",childKeys:[],sourceRange:Te(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(l),(x.isArrowFunctionExpression(a)||x.isFunctionExpression(a))&&l.childKeys.push(..._r(a,t,n)),l.childKeys}if(x.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:St(e.test,n),conditionSource:Pe(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Te(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...bt(e.consequent,t,n)),s.childKeys.push(...bt(e.alternate,t,n)),s.childKeys}if(x.isLogicalExpression(e)&&gm(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:St(e.left,n),conditionSource:Pe(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Te(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...bt(e.right,t,n)),s.childKeys}if(x.isParenthesizedExpression(e))return jr(e.expression,t,n);if(x.isJSXElement(e)){let o=Or(e,t,n);return o?[o]:[]}return dn(e)?Dr(e,t,n):[]}function ym(e){let t=e.argument;return t&&(x.isExpression(t)||dn(t))?t:null}function Ln(e,t){let n=[];for(let r of e){if(x.isReturnStatement(r)){let o=ym(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(x.isIfStatement(r)){let o=x.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...Ln(o,r.test)),r.alternate){let i=x.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...Ln(i,r.test))}continue}if(x.isSwitchStatement(r))for(let o of r.cases){let i=o.test?x.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...Ln(o.consequent,i))}}return n}function Sc(e){let{file:t,source:n,ast:r}=e,o=e.imports.map(d=>d.specifier),i=new Map,s=[],a=[],c=new Map,l=tm(r);Yp(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(d){let m=qp(d);if(!m)return;let p=d.node,h=[];if(x.isArrowFunctionExpression(p))x.isExpression(p.body)||dn(p.body)?h=[{argument:p.body,statement:x.returnStatement(x.isExpression(p.body)?p.body:null)}]:x.isBlockStatement(p.body)&&(h=Ln(p.body.body));else{let $=p.body;x.isBlockStatement($)&&(h=Ln($.body))}if(h.length===0){d.skip();return}let E=new Map;hi(rm(r.program.body),pi(t,m,i,s,l,[E]),E);let C=new Map;for(let $ of p.params)for(let re of dt($))xi(C,re);let v=x.isBlockStatement(p.body)?p.body.body:[],T=h[0]?.statement??null;for(let $ of v){if(T&&$===T)break;x.isVariableDeclaration($)&&hi([$],pi(t,m,i,s,l,[E,C]),C)}let P=pi(t,m,i,s,l,[E,C]);for(let $ of h){let re=bt($.argument,P,n);for(let te of re)a.includes(te)||a.push(te);if($.condition){let te={kind:"conditional-branch",conditionExpression:St($.condition,n),conditionSource:Pe($.condition,n,P)};Mr(P,"conditional-region","",$.statement,re,[te])}}d.skip()}});let u=[...i.keys()];return u.length>0&&c.set(t,u),{graph:{routeId:t,rootKeys:a,elements:i,regions:s,fileIndex:c,version:1,diagnostics:[]},localImports:o}}function Ei(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function $r(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function bc(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??li,c=new Map,l=new Map,u=new Map,d=[],m=new Set,p=v=>{let T=`${v.path}\0${v.code}\0${v.message}\0${JSON.stringify(v.details??{})}`;m.has(T)||(m.add(T),d.push(v))},h=[{file:e,source:t,depth:0,diagnosticEntryFile:e,importStack:[]},...(o.additionalEntries??[]).map(v=>({file:v.file,source:v.source,depth:0,diagnosticEntryFile:v.file,importStack:[]}))],E=new Set;for(;h.length>0;){let v=h.shift(),{file:T,source:P,depth:$,diagnosticEntryFile:re,importStack:te}=v;if(E.has(T))continue;E.add(T),c.set(T,P);let A=a(T,P);if(!A.ok){p($r(A.diagnostic,re,te));continue}u.set(T,A.module);let{graph:D,localImports:O}=Sc(A.module);for(let L of D.elements.values())if(L.importedFrom&&st(L.importedFrom)){let ee=L.importedFrom,Z=await Tr(T,ee,r);Z.ok?(L.importedFrom=Z.path,Ut(Z.path)&&(L.isPublicUiComponent=!0)):Dn(ee,T)||p($r(Z.diagnostic,re,Ei(te,T,ee,Z.diagnostic.path)))}if(l.set(T,D),!($>=i))for(let L of O){if(xm(L))continue;let ee=await Tr(T,L,r);if(!ee.ok){Dn(L,T)||p($r(ee.diagnostic,re,Ei(te,T,L,ee.diagnostic.path)));continue}let Z=ee.path;if(E.has(Z)||Ut(Z))continue;let xe=Ei(te,T,L,Z);try{let W=await n(Z);h.push({file:Z,source:W,depth:$+1,diagnosticEntryFile:re,importStack:xe})}catch(W){p($r({path:Z,code:"import-read-failed",message:`Failed to read imported file: ${Z}`,details:{fromFile:T,specifier:L,reason:W instanceof Error?W.message:String(W)}},re,xe))}}}let C=Em(e,l,s,(o.additionalEntries??[]).map(v=>v.file));return C.diagnostics=d,{graph:C,allSources:c,diagnostics:d,parsedModules:u,entryModule:u.get(e)??null}}function xm(e){return/\.(?:css|scss|sass|less)(?:\?.*)?$/i.test(e)}function Em(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 m=s.get(u)??[];s.set(u,[...m,...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 Ic(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}),kc(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function kc(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}),kc(s,t,n,r,o))}}import{isSiteEditRuntimeContainerTag as Sm,isSiteEditRuntimeVoidElementTag as bm}from"@vcp-dev/contracts/site-edit-runtime-capability";function Im(e,t,n){let r=t.nodes.get(e),o=n.elements.get(e);if(!r||!o)return{key:e,canUpdateText:!1,canInsertChild:!1,canMove:!1,canRemove:!1,constraints:[{kind:"opaque-region",message:"Node not found in graph"}]};let i=r.constraints.map(P=>({kind:P.kind,message:P.reason})),s=o.isOpaque,c=r.parentKey===null&&o.componentName==="Page",l=o.tag.toLowerCase(),u=o.tag!==l,d=!u&&bm(l),m=u||Sm(l),p=u&&o.childKeys.length>0&&!o.isPublicUiComponent,h=o.textSegments.length>0&&o.textSegments.some(P=>P.editable);d&&!i.some(P=>P.kind==="void-element")&&i.push({kind:"void-element",message:`Element '${o.tag}' is void: children cannot be inserted`}),!d&&!m&&!i.some(P=>P.kind==="void-element")&&i.push({kind:"void-element",message:`Element '${o.tag}' cannot contain structured children`});let E=h&&!s,C=!o.isPublicUiComponent&&!d&&m&&(!s||p);return{key:e,canUpdateText:E,canInsertChild:C,canMove:!c,canRemove:!c,constraints:i}}function vc(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,Im(r,e,t));return n}import{createHash as Xi}from"node:crypto";import $i from"@babel/traverse";function Si(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 Wh}from"node:crypto";import rl from"node:path";import*as to from"@babel/parser";import Mi from"@babel/generator";import Oi from"@babel/traverse";import*as vt from"@babel/types";import bi from"@babel/traverse";var It=typeof bi=="function"?bi:bi.default,Br=new WeakMap,Cc=new WeakMap;function pt(e,t){let n=ri(e,t);if(!n.ok)return ni(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=oe(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}}:ni(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function oe(e,t){return t.kind==="jsx-node"?Ac(e,t):t.kind==="jsx-attribute"?wm(e,t):t.kind==="value"?Am(e,t):t.kind==="expression"?Tm(e,t):t.kind==="directive"?Nm(e,t):t.kind==="export"?Fm(e,t):{ok:!1,diagnostic:$t("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function Ac(e,t){return t.strategy==="source-range"?km(e,t):vm(e,t)}function km(e,t){let n=null;if(It(e,{JSXElement(o){if(!pn(o.node,t.sourceRange))return;let i=Ee("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!pn(o.node,t.sourceRange))return;let i=Ee("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!pn(o.node,t.sourceRange))return;let i=Ee("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)}}),!n)return be("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!Km(r.path,t.expectedIdentity)?be("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function vm(e,t){if(t.structuralPath===""){let r=Rm(e,t.component);if(r){let o=Pm(r);if(o)return o}}let n=null;return It(e,{JSXElement(r){if($n(r)!==t.component||ki(r)!==t.structuralPath)return;let i=Ee("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if($n(r)!==t.component||ki(r)!==t.structuralPath)return;let i=Ee("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=Cm(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:be("jsx-node","locator-miss","JSX node not found for structural-path locator")}function Cm(e,t,n){let r=null;return It(e,{JSXElement(o){if($n(o)!==t||!pn(o.node,n))return;let i=Ee("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if($n(o)!==t||!pn(o.node,n))return;let i=Ee("jsx-node",o);i&&(r=i,o.stop())}}),r}function Rm(e,t){let n=null;return It(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 Pm(e){if(e.isArrowFunctionExpression()){let t=e.get("body");if(t.isBlockStatement()){let r=t.get("body").find(o=>o.isReturnStatement());if(r){let o=r.get("argument");if((o.isParenthesizedExpression()?o.get("expression"):o).isJSXFragment())return be("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?be("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target"):null}if(e.isFunctionDeclaration()||e.isFunctionExpression()){let t=e.get("body");if(t.isBlockStatement()){let n=t.get("body").find(r=>r.isReturnStatement());if(n){let r=n.get("argument");if((r.isParenthesizedExpression()?r.get("expression"):r).isJSXFragment())return be("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function wm(e,t){let n=Ac(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>Jm(c,t.name));if(!s||!s.isJSXAttribute())return be("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=Ee("jsx-attribute",s);return a?{ok:!0,match:a}:be("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function Am(e,t){let n=_m(e,t);if(!n.ok)return n;let r=Mm(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!ft(r.match.path.node.loc,t.expectedRange)?be("value","locator-miss","Resolved value does not match expected range"):{ok:!0,match:r.match}:r}function Tm(e,t){let n=null;return It(e,{Identifier(r){if(!$m(r))return;let o=Pc(r);if(!o||!wc(o,t))return;let i=Ee("expression",r);i&&(t.expectedRange&&!ft(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=Pc(r);if(!o||!wc(o,t))return;let i=Ee("expression",r);i&&(t.expectedRange&&!ft(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:be("expression","locator-miss","Expression not found")}function Nm(e,t){let n=null;return It(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!ft(i.node.loc,t.expectedRange))return;let s=Ee("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:be("directive","locator-miss",`Directive '${t.value}' not found`)}function Fm(e,t){let n=null;return It(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let c=r.get("declaration");if(c.isFunctionDeclaration()&&c.node.id?.name==="generateMetadata"){let m=Ee("export",c);if(!m||t.expectedRange&&!ft(c.node.loc,t.expectedRange))return;n=m,r.stop();return}if(!c.isVariableDeclaration())return;let l=vi(c,"generateMetadata");if(!l||!l.isVariableDeclarator())return;let u=l.get("init");if(!u.node)return;let d=Ee("export",u);if(!d||t.expectedRange&&!ft(u.node.loc,t.expectedRange))return;n=d,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=vi(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!ft(s.node.loc,t.expectedRange))return;let a=Ee("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=Ee("export",o);i&&(t.expectedRange&&!ft(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:be("export","export-not-found",`Export '${Vm(t)}' not found`)}function _m(e,t){let n=null;return It(e,{Expression(r){if(n||t.root.kind!=="expression"||!pn(r.node,t.root.sourceRange))return;let o=Ee("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 p=r.get("init");if(!p.node)return;let h=Ee("value",p);if(!h)return;n=h,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(p=>p?.type==="Identifier"&&p.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 m=Ee("value",d);m&&(n=m,r.stop())},ExportNamedDeclaration(r){if(n||t.root.kind!=="named-export")return;let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=vi(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=Ee("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=Ee("value",o);i&&(n=i,r.stop())}}),n?{ok:!0,match:n}:be("value",t.root.kind==="named-export"||t.root.kind==="default-export"?"export-not-found":t.root.kind==="expression"?"locator-miss":"binding-not-found","Value root was not found")}function Mm(e,t){let n=Ii(e);for(let o of t){if(n=Ii(n),o.kind==="property"){if(!n.isObjectExpression())return be("value","unsupported-syntax","Property path requires object expression");let a=n.get("properties");if(a.some(l=>!l.isObjectProperty()))return be("value","unsupported-syntax","Spread properties are not supported");let c=a.find(l=>Xm(l,o.name));if(!c||!c.isObjectProperty())return be("value","property-not-found",`Property '${o.name}' not found`);n=c.get("value");continue}if(!n.isArrayExpression())return be("value","unsupported-syntax","Array index path requires array expression");let i=n.get("elements");if(i.some(a=>a.node?.type==="SpreadElement"))return be("value","unsupported-syntax","Spread array elements are not supported");let s=i[o.index];if(!s?.node)return be("value","array-index-out-of-range",`Array index ${o.index} is out of range`);n=s}n=Ii(n);let r=Ee("value",n);return r?{ok:!0,match:r}:be("value","locator-miss","Resolved value has no source range")}function Ii(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function Ee(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 pn(e,t){return ft(e.loc,t)}function ft(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 ki(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!Ur(n.node)){let o=Tc(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${Rc(n,o)}`):t.unshift(`${o}#${Rc(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||jm(n.parentPath))break;n=n.parentPath}return t.join("/")}function Ur(e){let t=e.openingElement.name;return t.type==="JSXIdentifier"?t.name==="Fragment":t.type==="JSXMemberExpression"&&t.property.name==="Fragment"}function Rc(e,t){let n=Om(e);if(!n)return 0;let r=Br.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=Br.get(n.node)?.get(t);if(!i){let s=Br.get(n.node);s||(s=new Map,Br.set(n.node,s)),i=new WeakMap,s.set(t,i)}for(let s of jn(n))if(Tc(s.node.openingElement)===t){if(i.set(s.node,o),s.node===e.node)return o;o++}return i.get(e.node)??0}function Om(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Ur(t.node)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function jn(e){let t=Cc.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(Ur(o.node)){n.push(...jn(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...jn(o));continue}o.isJSXExpressionContainer()&&n.push(...fn(o.get("expression")))}return Cc.set(e.node,n),n}function fn(e){return e.isJSXElement()?Ur(e.node)?jn(e):[e]:e.isJSXFragment()?jn(e):e.isParenthesizedExpression()?fn(e.get("expression")):e.isLogicalExpression()&&Dm(e.node.operator)?fn(e.get("right")):e.isConditionalExpression()?[...fn(e.get("consequent")),...fn(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:fn(t)):[]}function Dm(e){return e==="&&"||e==="||"||e==="??"}function Tc(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?Lm(e.name):null}function Lm(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 $n(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 jm(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function $m(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function Pc(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 wc(e,t){return e.base===t.base&&Bm(e.path,t.path??[])}function Bm(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 Um(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function Vm(e){return e.exportKind==="named"?e.name:e.exportKind}function be(e,t,n,r){return{ok:!1,diagnostic:$t(t,n,e,r)}}function Km(e,t){return $n(e)!==t.component?!1:ki(e)===t.structuralPath}function Jm(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function vi(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function Xm(e,t){return e.isObjectProperty()?Um(e.node)===t:!1}import Ci from"@babel/generator";var zm=typeof Ci=="function"?Ci:Ci.default;function Hm(e){let t=e.split(`
|
|
2
|
-
`),n=[],r=!1;for(let s of t){let a=s.match(/^(\s+)/);if(a){let c=a[1];c.includes(" ")?r=!0:c.length>0&&n.push(c.length)}}if(r&&t.every(a=>{let c=a.match(/^(\s+)/);return!c||c[1].includes(" ")}))return"tab";if(n.length===0)return"2";function o(s,a){return a===0?s:o(a,s%a)}let i=n[0];for(let s=1;s<n.length;s++)i=o(i,n[s]);return i>=4?"4":"2"}function
|
|
3
|
-
`).map(r=>
|
|
4
|
-
`)}function Vr(e){let{ast:t,source:n}=e;try{let r=Hm(n),i=zm(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=Gm(i,r)),{ok:!0,source:i}}catch(r){return B(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}import*as Fc from"@babel/parser";import{arrayExpression as Ym,booleanLiteral as Zm,identifier as Qm,jsxAttribute as qm,jsxExpressionContainer as eh,jsxIdentifier as th,nullLiteral as nh,numericLiteral as rh,objectExpression as oh,objectProperty as ih,stringLiteral as _c}from"@babel/types";function Nc(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 Bn(e,t,n){return{ok:!0,source:t,operation:{type:n.kind,nodeId:n.target,kind:n.kind,target:n.target,beforeSourceHash:Nc(e),afterSourceHash:Nc(t),inverse:n.inverse}}}function de(e,t,n){let r=Vr({ast:e,source:t});return r.ok?Bn(t,r.source,n):r}function Ie(e,t){let n=oi(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function Kr(e,t){return Vr({ast:e,source:t})}function sh(e,t,n){let r=oe(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function Mc(e,t,n){let r=sh(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:B(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function Oc(e,t){let n=oe(e,t);return n.ok?{ok:!0,match:n.match}:n.diagnostic.code==="locator-miss"?{ok:!0,match:null}:{ok:!1,diagnostic:n.diagnostic}}function mn(e){return typeof e=="string"?_c(e):typeof e=="number"?rh(e):typeof e=="boolean"?Zm(e):e===null?nh():Array.isArray(e)?Ym(e.map(t=>mn(t))):oh(Object.entries(e).map(([t,n])=>ih(Qm(t),mn(n))))}function ah(e){return typeof e=="string"?_c(e):eh(mn(e))}function Jr(e,t){return qm(th(e),ah(t))}function Dc(e,t){try{let r=Fc.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:B(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:B(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function Xr(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=Ie(t,"jsx-node");if(!i.ok)return i.result;let s=oe(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let c=ch(s.match.path)[r];if(!c)return B(t,"locator-miss",`Text segment ${r} not found`,"jsx-node");switch(c.kind){case"jsx-text":c.path.node.value=lh(c.path.node.value,o);break;case"string-literal":c.path.node.value=o;break;case"template-literal":{let l=c.quasiIndex;c.path.node.quasis[l].value.raw=o,c.path.node.quasis[l].value.cooked=o;break}}return de(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function ch(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=uh(r.get("expression"));o.length>0&&t.push(...o)}}return t}function lh(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function uh(e){if(e.isStringLiteral())return[{kind:"string-literal",path:e}];if(e.isTemplateLiteral()){let t=[],n=e.node.quasis;for(let r=0;r<n.length;r++)n[r].value.raw.trim().length>0&&t.push({kind:"template-literal",path:e,quasiIndex:r});if(t.length>0)return t}return e.isCallExpression()?[]:[]}import{nullLiteral as Ri}from"@babel/types";function hn(e){let{source:t,locator:n}=e,r=Ie(t,"jsx-node");if(!r.ok)return r.result;let o=oe(r.ast,n);return o.ok?(dh(o.match.path),de(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function dh(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Ri());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Ri());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Ri());return}e.remove()}import{cloneNode as Ih}from"@babel/types";import Pi from"@babel/traverse";import*as V from"@babel/types";var fh=typeof Pi=="function"?Pi:Pi.default;function Ve(e,t,n,r){if(!e.ok)return e;let o=Ue(n);if(!o)return e;let i=ph(t,o,r);return i?{...e,selectionRef:i}:e}function ph(e,t,n){let r=mh(e,t);if(!r)return;let o=n.sourceLocator?Lc(n.sourceLocator):void 0,i=n.targetParentLocator?Lc(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??gh(r)??i?.component??o?.component;if(!(!s||!a))return{key:On(s,a,yh(r))}}function Lc(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function mh(e,t){let n=null;return fh(e,{JSXElement(r){r.node===t&&(n=r,r.stop())}}),n}function Ue(e){if(!e)return null;if(V.isJSXElement(e))return gn(e)?jc(e.children):e;if(V.isJSXFragment(e))return jc(e.children);if(V.isJSXExpressionContainer(e)||V.isParenthesizedExpression(e)||V.isTSAsExpression(e)||V.isTSSatisfiesExpression(e)||V.isTSTypeAssertion(e)||V.isTSNonNullExpression(e))return Ue(e.expression);if(V.isLogicalExpression(e))return Ue(e.right);if(V.isConditionalExpression(e))return Ue(e.consequent)??Ue(e.alternate);if(V.isCallExpression(e)||V.isOptionalCallExpression(e))return Kc(e)?hh(e.arguments[0]):null;if(V.isArrayExpression(e))for(let t of e.elements){if(!t)continue;let n=Ue(t);if(n)return n}return null}function jc(e){for(let t of e){let n=Ue(t);if(n)return n}return null}function hh(e){return!e||!V.isArrowFunctionExpression(e)&&!V.isFunctionExpression(e)?null:V.isBlockStatement(e.body)?Un(e.body.body):Ue(e.body)}function Un(e){for(let t of e){if(V.isReturnStatement(t)){let n=Ue(t.argument);if(n)return n;continue}if(V.isBlockStatement(t)){let n=Un(t.body);if(n)return n;continue}if(V.isIfStatement(t)){let n=$c(t.consequent);if(n)return n;let r=t.alternate?$c(t.alternate):null;if(r)return r;continue}if(V.isSwitchStatement(t))for(let n of t.cases){let r=Un(n.consequent);if(r)return r}}return null}function $c(e){return V.isBlockStatement(e)?Un(e.body):Un([e])}function gh(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(V.isFunctionDeclaration(n))return n.id?.name??"default"}if(t.isVariableDeclarator()&&V.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 Bc=new WeakMap,Uc=new WeakMap,wi=new WeakMap;function yh(e){let t=Bc.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=xh(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return Bc.set(e.node,o),o}function xh(e){let t=Ai(e.node.openingElement.name);return!t||gn(e.node)?null:/^[A-Z]/.test(t)?`component:${t}#${Vc(e,t)}`:`${t}#${Vc(e,t)}`}function Vc(e,t){let n=Eh(e);if(!n)return 0;let r=wi.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=wi.get(n.node);o||(o=new Map,wi.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of Jt(n))if(Ai(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 Eh(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(gn(t.node)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Jt(e){let t=Uc.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(gn(o.node)){n.push(...Jt(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Jt(o));continue}o.isJSXExpressionContainer()&&n.push(...mt(o.get("expression")))}return Uc.set(e.node,n),n}function mt(e){if(e.isJSXElement())return gn(e.node)?Jt(e):[e];if(e.isJSXFragment())return Jt(e);if(e.isParenthesizedExpression())return mt(e.get("expression"));if(e.isLogicalExpression())return mt(e.get("right"));if(e.isConditionalExpression())return[...mt(e.get("consequent")),...mt(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:mt(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&Kc(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?Sh(n):[]}return[]}function Sh(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return gn(t.node)?Jt(t):[t];if(t.isJSXFragment())return Jt(t);if(t.isParenthesizedExpression())return mt(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return mt(t);if(!t.isBlockStatement())return[];for(let n of t.get("body")){if(!n.isReturnStatement())continue;let r=n.get("argument");return r.node?mt(r):[]}return[]}function Kc(e){let t=e.callee;return(V.isMemberExpression(t)||V.isOptionalMemberExpression(t))&&V.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function gn(e){let t=Ai(e.openingElement.name);return t==="Fragment"||t==="React.Fragment"}function Ai(e){return V.isJSXIdentifier(e)?e.name:V.isJSXMemberExpression(e)?Jc(e):V.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function Jc(e){return`${V.isJSXIdentifier(e.object)?e.object.name:Jc(e.object)}.${e.property.name}`}function kt(e,t){if(t.parentPath===e&&t.listKey==="children"&&Xc(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!Xc(n))return null;let r=n;for(;r&&r!==e;){if(!bh(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function Xc(e){return e.isJSXElement()||e.isJSXFragment()}function bh(e){if(e.isJSXFragment())return!0;if(!e.isJSXElement())return!1;let t=e.node.openingElement.name;return t.type==="JSXIdentifier"?t.name==="Fragment":t.type==="JSXMemberExpression"&&t.property.name==="Fragment"}function yn(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=Ie(t,"jsx-node");if(!a.ok)return a.result;let c=oe(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return B(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 P=c.match.path.node;if(!P.closingElement||P.openingElement.selfClosing)return B(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=Dc(t,r.jsx);if(!u.ok)return u.result;let d=Ih(u.node,!0),m=l.node.children,p={...s,targetParentLocator:n},h=P=>s?Ve(P,a.ast,d,p):P;if(o==="append")return m.push(d),h(de(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return m.unshift(d),h(de(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(!i)return B(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let E=oe(a.ast,i);if(!E.ok)return{ok:!1,source:t,diagnostic:E.diagnostic};let C=kt(c.match.path,E.match.path);if(!C)return B(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");l=C;let v=l.node.children,T=v.findIndex(P=>P===E.match.path.node);return T===-1?B(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(v.splice(o==="before"?T:T+1,0,d),h(de(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as zc from"@babel/parser";import{cloneNode as kh}from"@babel/types";function zr(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=Ie(t,"jsx-node");if(!a.ok)return a.result;let c=vh(t,r);if(!c.ok)return c.result;let l=oe(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return B(t,"unsupported-syntax","insert-jsx-expression-child target must be a JSXElement or JSXFragment","jsx-node");if(l.match.path.isJSXElement()){let v=l.match.path.node;if(!v.closingElement||v.openingElement.selfClosing)return B(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=l.match.path,d=null;if(i){let v=oe(a.ast,i);if(!v.ok)return{ok:!1,source:t,diagnostic:v.diagnostic};let T=kt(l.match.path,v.match.path);if(!T)return B(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=T,d=v.match.path.node}else if(o==="before"||o==="after")return B(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=kh(c.node,!0),p=u.node.children,h={...s,targetParentLocator:n},E=v=>s?Ve(v,a.ast,m,h):v;if(o==="append")return p.push(m),E(de(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return p.unshift(m),E(de(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let C=p.findIndex(v=>v===d);return C===-1?B(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(p.splice(o==="before"?C:C+1,0,m),E(de(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function vh(e,t){try{let r=zc.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:B(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:B(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as Ch,nullLiteral as Ti}from"@babel/types";import*as xn from"@babel/types";function En(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=Ie(t,"jsx-node");if(!a.ok)return a.result;let c=oe(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let l=oe(a.ast,r);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return B(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 T=l.match.path.node;if(!T.closingElement||T.openingElement.selfClosing)return B(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let d=null;if(i){let T=oe(a.ast,i);if(!T.ok)return{ok:!1,source:t,diagnostic:T.diagnostic};let P=kt(l.match.path,T.match.path);if(!P)return B(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=P,d=T.match.path}else if(o==="before"||o==="after")return B(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=d&&typeof d.key=="number"?d.key:-1;if(d&&m===-1)return B(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let p=Ch(c.match.path.node,!0);if(!xn.isJSXElement(p)&&!xn.isJSXExpressionContainer(p)&&!xn.isJSXFragment(p))return B(t,"unsupported-syntax","move-node source must resolve to a JSX child","jsx-node");let h=c.match.path.parentPath?.node===u.node&&typeof c.match.path.key=="number"?c.match.path.key:-1;if(d&&c.match.path.parentPath?.node===d.parentPath?.node&&c.match.path.key===d.key)return B(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");Rh(c.match.path);let E=u.node.children,C={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return E.push(p),Ve(Kr(a.ast,t),a.ast,p,C);if(o==="prepend")return E.unshift(p),Ve(Kr(a.ast,t),a.ast,p,C);let v=m-(h!==-1&&h<m?1:0);return E.splice(o==="before"?v:v+1,0,p),Ve(Kr(a.ast,t),a.ast,p,C)}function Rh(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Ti());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Ti());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Ti());return}e.remove()}import*as Hc from"@babel/parser";import{cloneNode as Ph,nullLiteral as Ni}from"@babel/types";function Hr(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,c=Ie(t,"jsx-node");if(!c.ok)return c.result;let l=wh(t,s);if(!l.ok)return l.result;let u=oe(c.ast,n);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};let d=oe(c.ast,r);if(!d.ok)return{ok:!1,source:t,diagnostic:d.diagnostic};if(!d.match.path.isJSXElement()&&!d.match.path.isJSXFragment())return B(t,"unsupported-syntax","move-repeat-template-child target parent must be a JSXElement or JSXFragment","jsx-node");if(d.match.path.isJSXElement()){let P=d.match.path.node;if(!P.closingElement||P.openingElement.selfClosing)return B(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let m=d.match.path,p=null;if(i){let P=oe(c.ast,i);if(!P.ok)return{ok:!1,source:t,diagnostic:P.diagnostic};let $=kt(d.match.path,P.match.path);if(!$)return B(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");m=$,p=P.match.path.node}else if(o==="before"||o==="after")return B(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!u.match.path.isJSXElement())return B(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let h=m.node,E=Ph(l.node,!0);Ah(u.match.path);let C={...a,sourceLocator:n,targetParentLocator:r},v=h.children;if(o==="append")return v.push(E),Ve(de(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,E,C);if(o==="prepend")return v.unshift(E),Ve(de(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,E,C);let T=v.findIndex(P=>P===p);return T===-1?B(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(v.splice(o==="before"?T:T+1,0,E),Ve(de(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,E,C))}function wh(e,t){try{let r=Hc.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:B(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:B(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function Ah(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Ni());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Ni());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Ni());return}e.remove()}function Wr(e){let{source:t,locator:n,props:r}=e,o=Ie(t,"jsx-node");if(!o.ok)return o.result;let i=Mc(o.ast,n,t);if(!i.ok)return i.result;let s=i.match.path.node.openingElement;for(let[a,c]of Object.entries(r)){if(c===void 0)continue;let l={kind:"jsx-attribute",element:n,name:a},u=Oc(o.ast,l);if(u.ok&&u.match!==null){let d=u.match.path.node;d.value=c===""?Jr(a,"").value:Jr(a,c).value}else s.attributes.push(Jr(a,c))}return de(o.ast,t,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}import{getBindingIdentifiers as Th,identifier as Vn,importDeclaration as Nh,importDefaultSpecifier as Fh,importNamespaceSpecifier as _h,importSpecifier as Mh,isImportDefaultSpecifier as Wc,isImportNamespaceSpecifier as Gc,isImportSpecifier as Yc,stringLiteral as Oh}from"@babel/types";function Sn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(C=>!Jh(C));if(o!==-1){let C=r[o],v=C&&typeof C=="object"&&"kind"in C?C.kind:void 0;return B(t,"unsupported-syntax",`Unsupported import spec kind: ${String(v)}`)}let i=Uh(r);if(!i.ok)return B(t,"unsupported-syntax",i.message);let s=Ie(t);if(!s.ok)return s.result;let{ast:a}=s,c=a.program,l=c.body.filter(C=>C.type==="ImportDeclaration"&&C.source.value===n),u=new Set(l.flatMap(C=>C.specifiers.flatMap(v=>{let T=Xh(C,v);return T?[T]:[]}))),d=i.imports.filter(C=>!u.has(nl(C)));if(d.length===0)return Bn(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let m=Vh(c.body),p=d.find(C=>m.has(Fi(C)));if(p)return B(t,"unsupported-syntax",`Import local binding already exists: ${Fi(p)}`);let h=Bh(d);if(h.reduce((C,v)=>C+v.length,0)!==d.length)return B(t,"unsupported-syntax","Unsupported import specifier grouping");for(let C of h){if(!el(Qc(C)))return B(t,"unsupported-syntax","Unsupported import specifier combination");let v=l.find(T=>Dh(T,C));if(v)Lh(v,C);else{let T=Nh(Zc(C),Oh(n));Kh(c.body,T),l.push(T)}}return de(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function Dh(e,t){return e.importKind==="type"?!1:el($h(jh(e),Qc(t)))}function Lh(e,t){let n=!1,r=new Set(e.specifiers.map(o=>_i(o)));for(let o of Zc(t)){let i=_i(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return tl(e.specifiers),{changed:n}}function Zc(e){let t=e.map(n=>{switch(n.kind){case"named":return Mh(n.local?Vn(n.local):Vn(n.imported),Vn(n.imported));case"default":return Fh(Vn(n.local));case"namespace":return _h(Vn(n.local));default:return n}});return tl(t),t}function Qc(e){let t=qc();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 jh(e){let t=qc();for(let n of e.specifiers)Wc(n)?t.defaultLocals.add(n.local.name):Gc(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function qc(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function $h(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function el(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function tl(e){let t=[...e.filter(n=>Wc(n)),...e.filter(n=>Gc(n)),...e.filter(n=>Yc(n))];e.splice(0,e.length,...t)}function Bh(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 Uh(e){let t=new Map,n=new Map;for(let r of e){let o=nl(r);if(t.has(o))continue;let i=Fi(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 Vh(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(Th(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 Kh(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 Jh(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 nl(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 Fi(e){return e.kind==="named"?e.local??e.imported:e.local}function Xh(e,t){return e.importKind==="type"||Yc(t)&&t.importKind==="type"?null:_i(t)}function _i(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 bn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(u=>!Hh(u));if(o!==-1){let u=r[o],d=u&&typeof u=="object"&&"kind"in u?u.kind:void 0;return B(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(d)}`)}let i=Ie(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 Bn(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let l=a.body[c];return r.length===0?(a.body.splice(c,1),de(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(l.specifiers=l.specifiers.filter(u=>!r.some(d=>zh(u,d))),l.specifiers.length===0&&a.body.splice(c,1),de(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function zh(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 Hh(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 Kn(e){let{source:t,locator:n,next:r}=e,o=Qr(t,n);return o.ok?(o.path.replaceWith(mn(r)),de(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function Gr(e){let{source:t,locator:n,index:r,value:o}=e,i=Qr(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(s=>s?.type==="SpreadElement")?B(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>i.path.node.elements.length?B(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,0,mn(o)),de(i.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):B(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function Yr(e){let{source:t,locator:n,index:r}=e,o=Qr(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(i=>i?.type==="SpreadElement")?B(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=o.path.node.elements.length?B(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(o.path.node.elements.splice(r,1),de(o.ast,t,{kind:"remove-array-element",target:"value",inverse:"insert-array-element"})):B(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function Zr(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=Qr(t,n);if(!i.ok)return i.result;if(!i.path.isArrayExpression())return B(t,"unsupported-syntax","Array operations require array expression target","value");if(i.path.node.elements.some(c=>c?.type==="SpreadElement"))return B(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 B(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),de(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function Qr(e,t){let n=Ie(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=oe(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}}}var Gh=typeof Mi=="function"?Mi:Mi.default;function Li(e){let t=ll(e);if(t)return{ok:!1,error:t};let n=e.projection,r=ji(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.containerSourceRange??n.container.sourceRange,i=r.placement;if((n.container.kind==="virtual-route-root"||n.container.kind==="starter-placeholder")&&(n.container.sourceRange===null||n.container.sourceKind==="jsx-element"||n.container.sourceKind==="atomic-expression"||n.container.kind==="starter-placeholder"))return n.container.sourceKind==="atomic-expression"?{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"An indirect page expression does not expose a safe return boundary.",diagnostics:[]}}:{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:i.placementUnitKey,importStep:ol(e),returnStep:{kind:"insert-return",node:{jsx:`<${e.component.localName} />`},placement:i.relation,replaceOriginal:n.container.kind==="starter-placeholder"}}};if(!o)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition does not expose a safe placement boundary.",diagnostics:[]}};let a={kind:"jsx-node",strategy:"source-range",sourceRange:o},c=pt(e.source,a);if(!c.ok||!c.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:c.ok===!1?c.diagnostic.message:"Route page composition anchor could not be resolved.",diagnostics:c.ok?[]:[qr(c.diagnostic)]}};let l=eo(e.source,c.match.node.start??null,c.match.node.end??null);if(Qh(o,n.container.sourceRange)&&n.container.sourceHash&&l!==n.container.sourceHash)return{ok:!1,error:{code:"VERSION_STALE",message:"Route page composition container hash no longer matches the current source.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Route page composition container hash no longer matches the current source."}]}};let u=ol(e);return{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:r.placement.placementUnitKey,parentLocator:a,importStep:u,insertStep:{kind:"insert-child",parentLocator:a,node:{jsx:`<${e.component.localName} />`},placement:r.placement.relation,...r.placement.anchorSourceRange?{anchorLocator:{kind:"jsx-node",strategy:"source-range",sourceRange:r.placement.anchorSourceRange}}:{}}}}}function ol(e){let t=Zh(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 al(e){let t;try{t=to.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]})}catch(i){return{ok:!1,source:e.source,diagnostic:{message:i instanceof Error?i.message:String(i)}}}let n=to.parseExpression(e.jsx,{plugins:["jsx","typescript"]}),r=!1;return(typeof Oi=="function"?Oi:Oi.default)(t,{ExportDefaultDeclaration(i){let s=i.get("declaration"),a=Yh(i,s);if(a){if(a.isArrowFunctionExpression()&&!a.get("body").isBlockStatement()){let c=a.get("body");c.replaceWith(il(c.node,n,e.placement,e.replaceOriginal===!0)),r=!0,i.stop();return}a.traverse({Function(c){c.node!==a.node&&c.skip()},ReturnStatement(c){if(r)return;let l=c.get("argument");l.node&&(l.replaceWith(il(l.node,n,e.placement,e.replaceOriginal===!0)),r=!0,c.stop())}}),r&&i.stop()}}}),r?{ok:!0,source:Gh(t,{}).code}:{ok:!1,source:e.source,diagnostic:{message:"Route default return boundary could not be resolved."}}}function Yh(e,t){if(t.isFunctionDeclaration()||t.isFunctionExpression()||t.isArrowFunctionExpression())return t;if(!t.isIdentifier())return null;let n=e.scope.getBinding(t.node.name);if(!n)return null;let r=n.path;if(r.isFunctionDeclaration()||r.isFunctionExpression())return r;if(r.isVariableDeclarator()){let o=r.get("init");if(o.isArrowFunctionExpression()||o.isFunctionExpression())return o}return null}function il(e,t,n,r){if(vt.isNullLiteral(e)||r)return t;let s=n==="before"||n==="prepend"?[t,e]:[e,t];return vt.jsxFragment(vt.jsxOpeningFragment(),vt.jsxClosingFragment(),s)}function cl(e){let t=ll(e);if(t)return{ok:!1,error:t};let n=e.projection;if(n.container.sourceRange===null)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition does not expose a safe placement boundary.",diagnostics:[]}};let r=ul(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:[]}};let i=Di(o.sourceRange),s=pt(e.source,i);if(!s.ok||!s.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:s.ok===!1?s.diagnostic.message:"Route page composition source anchor could not be resolved.",diagnostics:s.ok?[]:[qr(s.diagnostic)]}};if(eo(e.source,s.match.node.start??null,s.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")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:"remove-node",locator:i}}};if(!e.targetPlacement)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Page-unit move requires a target placement.",diagnostics:[]}};if(e.targetPlacement.routeId!==e.routeId)return{ok:!1,error:{code:"CROSS_PAGE_MOVE_UNSUPPORTED",message:"Page-unit move across routes 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 c=ji(n,e.targetPlacement.placementKey,e.expectedDocumentVersion);if(!c.ok)return{ok:!1,error:{code:c.diagnostic.code==="DOCUMENT_VERSION_STALE"?"VERSION_STALE":"NO_SAFE_PAGE_PLACEMENT",message:c.diagnostic.message,diagnostics:[c.diagnostic]}};let l=c.placement;if(l.placementUnitKey!==e.targetPlacement.placementUnitKey||l.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 u=l.containerSourceRange;if(!u||!l.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 d=Di(u),m=pt(e.source,d);if(!m.ok||!m.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:m.ok===!1?m.diagnostic.message:"Route page composition target container could not be resolved.",diagnostics:m.ok?[]:[qr(m.diagnostic)]}};if(eo(e.source,m.match.node.start??null,m.match.node.end??null)!==l.containerSourceHash)return sl("Route page composition target container hash no longer matches the current source.");if(l.relation==="before"||l.relation==="after"){let h=l.anchorSourceRange,E=l.anchorSourceHash;if(!h||!E)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable anchor boundary.",diagnostics:[]}};let C=Di(h),v=pt(e.source,C);return!v.ok||!v.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:v.ok===!1?v.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:v.ok?[]:[qr(v.diagnostic)]}}:eo(e.source,v.match.node.start??null,v.match.node.end??null)!==E?sl("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:i,targetParentLocator:d,anchorLocator:C,placement:l.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:i,targetParentLocator:d,placement:l.relation}}}}function sl(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function qr(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function ll(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.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 Zh(e,t){let n=rl.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=rl.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Di(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function eo(e,t,n){return t==null||n==null?null:`sha256:${Wh("sha256").update(e.slice(t,n)).digest("hex")}`}function Qh(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 qh=typeof $i=="function"?$i:$i.default;function fl(e){if(!e.ast)return at(e,[_e("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=ag(e.ast);if(!t)return at(e,[_e("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=lg(t);if(n.length===0)return at(e,[_e("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")]);if(n.length>1)return at(e,[_e("MULTIPLE_PAGE_RETURNS","Route default export contains multiple page-level return statements",{returnCount:n.length})]);let r=ug(n[0].argument);if(!r)return at(e,[_e("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})]);if(r.isNullLiteral())return dl(e,t,"virtual-route-root");if(dg(r,t))return at(e,[_e("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(fg(r,t)||pg(r)&&!e.source.includes("DESIGN_PLAN_REPLACE_ME"))return at(e,[_e("UNSUPPORTED_PAGE_SHAPE","Route default export shape does not provide a single safe placement boundary",{reason:"ambiguous-placement"})]);if(r.isJSXFragment()){let i=Rt(r);if(i.unsupported)return at(e,[_e("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);let s=Bi({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-fragment",source:e.source,containerPath:r,members:i.members});return no(e,t,s,{kind:"virtual-route-root",sourceKind:"jsx-fragment"})}if(r.isJSXElement()&&!In(r)){let i=Ki(r),s=Bi({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[i]});return no(e,t,s,{kind:"virtual-route-root",sourceKind:"jsx-element"})}if(r.isJSXElement()){let i=Rt(r);if(i.unsupported)return at(e,[_e("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);let s=i.members;if(hg(e.source,r,s))return dl(e,t,"starter-placeholder");let a=Bi({input:e,containerKind:"jsx-container",sourceKind:"jsx-element",source:e.source,containerPath:r,members:s});return no(e,t,a,{kind:"jsx-container",sourceKind:"jsx-element"})}if(mg(r))return at(e,[_e("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);let o=yg({input:e,source:e.source,expression:r});return no(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"})}function ji(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:_e("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:_e("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function ul(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:_e("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:_e("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function pl(e){return e.ok?eg(e.projection):tg(e.projection)}function eg(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((E,C)=>ml(e,u,E,C,e.container.placementKey)),m=d.filter(({member:E})=>E.isBusinessMember).map(({sourceMember:E})=>rg(l,E,u.independent)),p=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,p.map(({sourceMember:E})=>E)),o.set(l,m);let h=p[0]?.sourceMember.key??l;n.push({key:l,containerKey:h,businessMemberKeys:m.map(E=>E.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,routeId:e.route,placementUnitKey:l.placementUnitKey,relation:l.relation}));return{status:"supported",version:e.version,routeId:e.route,container:ng(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function tg(e){let t=e.diagnostics.map(og);return{status:"unsupported",version:e.version,routeId:e.route,reason:ig(e.diagnostics),diagnostics:t}}function ng(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 ml(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)=>ml(e,t,a,c,i))]}function rg(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function og(e){return{code:sg(e),message:e.message}}function ig(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 sg(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 ag(e){let t=null;return qh(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=cg(o.path);i&&(t=i,n.stop())}}),t}function cg(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 lg(e){if(e.isArrowFunctionExpression()){let r=e.get("body");if(!r.isBlockStatement())return[{argument:r}]}let t=e.get("body");if(!t.isBlockStatement())return[];let n=[];return t.traverse({Function(r){r.node!==e.node&&r.skip()},ReturnStatement(r){n.push({argument:r.get("argument")})}}),n}function ug(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 dg(e,t){if(e.isIdentifier())return ro(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return ro(n.node.name,t)}return!1}function fg(e,t){return e.isConditionalExpression()?Ct(e.get("consequent"),t)||Ct(e.get("alternate"),t):e.isLogicalExpression()?Ct(e.get("left"),t)||Ct(e.get("right"),t):!1}function pg(e){if(!e.isJSXElement()||!In(e))return!1;let t=Rt(e).members;if(t.length!==1)return!1;let n=t[0];return n.kind==="jsx-element"&&!n.isBusinessMember&&n.businessMemberCount>0}function Ct(e,t){if(e.isIdentifier())return ro(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return ro(n.node.name,t)}return e.isConditionalExpression()?Ct(e.get("consequent"),t)||Ct(e.get("alternate"),t):e.isLogicalExpression()?Ct(e.get("left"),t)||Ct(e.get("right"),t):!1}function ro(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 mg(e){return e.isJSXSpreadChild()}function hg(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&Vi(t)}function Vi(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(!Vi(t))return!1;continue}if(t.isJSXElement()&&!Vi(t))return!1}return!0}function Rt(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:Ji(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:Ge(r.node.loc),businessMemberCount:0,parentSourceRange:Ge(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=Rt(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=In(o)?Rt(o):null;n||=i?.unsupported??!1,t.push({...Ki(o,i?.members),sourceRange:Ge(r.node.loc),parentSourceRange:Ge(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:Ji(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:Ge(r.node.loc),businessMemberCount:1,parentSourceRange:Ge(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&hl(r)){let o=Rt(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=In(r)?Rt(r):null;n||=o?.unsupported??!1,t.push({...Ki(r,o?.members),parentSourceRange:Ge(e.node.loc)})}}return{members:t,unsupported:n}}function Ki(e,t){let n=e.isJSXElement()&&In(e)?t??Rt(e).members:[],r=e.isJSXElement()&&!In(e)&&!hl(e);return{memberKey:Ji(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:Ge(e.node.loc),businessMemberCount:r?1:gl(n),parentSourceRange:Ge(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:gg(e)}}function hl(e){if(e.isJSXFragment())return!0;let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name==="Fragment"||t.type==="JSXMemberExpression"&&t.object.type==="JSXIdentifier"&&t.object.name==="React"&&t.property.name==="Fragment"}function In(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name!=="Fragment"&&t.name[0]===t.name[0]?.toLowerCase()}function gg(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 gl(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function oo(e){return e.length===0?0:Math.max(1,gl(e))}function Bi(e){let t=Ge(e.containerPath.node.loc),n=xl(e.source,e.containerPath.node.start,e.containerPath.node.end),r=Ke(e.input,e.containerKind,e.sourceKind,t),o=Ke(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:oo(e.members)<=1,memberCount:oo(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function yg(e){let t=Ge(e.expression.node.loc),n=xl(e.source,e.expression.node.start,e.expression.node.end),r=Ke(e.input,"virtual-route-root","atomic-expression",t),o=Ke(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:Ke(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 no(e,t,n,r){let o=n.containerSourceRange??n.sourceRange,i=xg(e,n,o),s=Si(i),a={status:"supported",route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:El(t),container:{kind:r.kind,placementKey:n.placementKey,placementUnitKey:n.placementUnitKey,version:e.version,isEmptyPage:n.memberCount===0,sourceKind:r.sourceKind,sourceRange:o,sourceHash:n.sourceHash},placements:i,diagnostics:[],placementByKey:new Map,unitByKey:new Map,placementsByUnitKey:new Map,placementUnitByKey:new Map};return Object.defineProperties(a,{placementByKey:{value:s.placementByKey,enumerable:!1},unitByKey:{value:s.unitByKey,enumerable:!1},placementsByUnitKey:{value:s.placementsByUnitKey,enumerable:!1},placementUnitByKey:{value:s.sourcePlacementByUnitKey,enumerable:!1}}),{ok:!0,projection:a}}function xg(e,t,n){if(t.members.length===0)return[t];let r=[],o=(l,u,d,m,p,h,E=n)=>({...t,placementKey:u,placementUnitKey:d,containerKey:t.placementKey,independent:oo(h)<=1,memberCount:oo(h),sourceRange:m,sourceHash:m?Ui(e.source,m):null,relation:l,containerSourceRange:E,containerSourceHash:E?Ui(e.source,E):null,anchorSourceRange:p,anchorSourceHash:p?Ui(e.source,p):null,members:h}),i=t.placementKey,s=t.members.map(l=>Ke(e,i,"placement-unit",l.sourceRange)),a=s[0]??t.placementUnitKey,c=s.at(-1)??t.placementUnitKey;r.push(o("prepend",Ke(e,i,"prepend",n),a,n,null,[]));for(let l of t.members){let u=l.parentSourceRange??n,d=Ke(e,i,"placement-unit",l.sourceRange);r.push(o("before",Ke(e,d,"before",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u)),r.push(o("after",Ke(e,d,"after",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u))}return r.push(o("append",i,c,n,null,[])),r}function dl(e,t,n){let r=Ke(e,n,"empty-container",void 0),o=Ke(e,n,"empty-unit",void 0),i={placementKey:r,placementUnitKey:o,version:e.version,containerKey:r,independent:!0,memberCount:0,sourceRange:null,sourceHash:null,relation:"append",containerSourceRange:null,containerSourceHash:null,anchorSourceRange:null,anchorSourceHash:null,members:[]},s=Si([i]),a={status:"supported",route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:El(t),container:{kind:n,placementKey:r,placementUnitKey:o,version:e.version,isEmptyPage:!0,sourceKind:n==="starter-placeholder"?"starter-placeholder":"jsx-fragment",sourceRange:null,sourceHash:null},placements:[i],diagnostics:[],placementByKey:new Map,unitByKey:new Map,placementsByUnitKey:new Map,placementUnitByKey:new Map};return Object.defineProperties(a,{placementByKey:{value:s.placementByKey,enumerable:!1},unitByKey:{value:s.unitByKey,enumerable:!1},placementsByUnitKey:{value:s.placementsByUnitKey,enumerable:!1},placementUnitByKey:{value:s.sourcePlacementByUnitKey,enumerable:!1}}),{ok:!0,projection:a}}function at(e,t){return{ok:!1,projection:{status:"unsupported",route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,diagnostics:t}}}function _e(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function Ke(e,t,n,r){return yl([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function Ji(e,t,n){return yl(["member",e,String(t??-1),String(n??-1)])}function yl(e){return`pc_${Xi("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function xl(e,t,n){return t==null||n==null?null:`sha256:${Xi("sha256").update(e.slice(t,n)).digest("hex")}`}function Ui(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:${Xi("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function Ge(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function El(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}function Sg(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var bg=160;function Sl(e,t,n,r={}){let o=[];for(let[i,s]of e.elements){let a=n.get(i),c={canUpdateText:r.canUpdateTextByKey?.get(i)??a?.canUpdateText??!1,canInsertChild:a?.canInsertChild??!1,canMove:a?.canMove??!1,canRemove:a?.canRemove??!1};o.push({key:i,tag:s.tag,label:s.tag===s.componentName?s.tag:`${s.tag} (${s.componentName})`,parentKey:s.parentKey,childKeys:[...s.childKeys],operationSummary:c,...r.dynamicDataSummaryByKey?.get(i)?{dynamicDataSummary:r.dynamicDataSummaryByKey.get(i)}:{}})}return{routeId:e.routeId,version:e.version,rootKeys:[...e.rootKeys],entries:o}}function bl(e,t,n,r,o,i,s,a,c,l,u,d,m){let p=t.elements.get(e),h=n.nodes.get(e),E=r.get(e);if(!p||!h||!E)throw new Error(`Node not found: ${e}`);let C=Rl(p.textSegments,s),v=Pl(e,t,p,E,C),T=C?vg(C):void 0,P=Cg(i,C),$=p.textSegments.map(D=>({index:D.index,value:D.value,editable:wl(D,E,s?.get(D.index)??null),source:o.get(D.index)??null})),re=vl(p,t),te=p.childKeys.map(D=>{let O=t.elements.get(D);return O?{key:D,tag:O.tag,label:O.tag}:null}).filter(D=>D!==null),A=[];if(p.parentKey){let D=t.elements.get(p.parentKey);if(D)for(let O of D.childKeys){if(O===e)continue;let L=t.elements.get(O);L&&A.push({key:O,tag:L.tag,label:L.tag})}}return{key:e,tag:p.tag,componentName:p.componentName,sourceFile:p.sourceFile,sourceLocator:kl(p),label:p.tag,capabilities:v,writeTarget:i,effectiveWriteTarget:P,provenanceChain:T,componentSemantic:c,contentModel:l,mediaModel:u,styleSource:d,conditional:a,...m?{dynamicData:m}:{},textSegments:$,boundaryKind:p.boundaryKind,isOpaque:p.isOpaque,ancestors:re,children:te,siblings:A}}function Il(e,t,n,r,o,i,s){let a=t.elements.get(e),c=n.nodes.get(e),l=r.get(e);if(!a||!c||!l)throw new Error(`Node not found: ${e}`);let u=Rl(a.textSegments,i);return{key:e,tag:a.tag,componentName:a.componentName,sourceFile:a.sourceFile,sourceLocator:kl(a),label:a.tag,capabilities:Pl(e,t,a,l,u),provenanceChain:u?{editMode:u.editMode,diagnostics:u.diagnostics.map(d=>({code:d.code,message:d.message}))}:void 0,...s?{dynamicData:s}:{},textSegments:a.textSegments.map(d=>{let m=o.get(d.index);return{index:d.index,editable:wl(d,l,i?.get(d.index)??null),source:m?{kind:m.kind}:null}}),boundaryKind:a.boundaryKind,isOpaque:a.isOpaque,ancestors:vl(a,t)}}function kl(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:Ig(e.sourceRange),structuralPath:e.identity.structuralPath,...kg(e.textSegments)}}function vl(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 Ig(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function kg(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,bg)}:{}}function Cl(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 Rl(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function Pl(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&&Al(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 wl(e,t,n){return!e.editable||!t.canUpdateText?!1:n?Al(n.editMode):!0}function Al(e){return e==="direct"||e==="proxy"||e==="upstream"}function vg(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 Cg(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}:Sg(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}}function Tl(e){let{key:t,element:n,graph:r,provenances:o}=e,i=Pg(t,n,r),s=i?.tag??(Xt(n.tag)?n.tag:n.componentName),a=i?.identity.key??Nl(n,r)??t,c=Tg(i),l=Ng(t,n,r,o,i),u=Rg(t,n,r,o,a);return{componentName:s,instanceKey:a,templateOwner:Ag(i??n,s),...c.length>0?{variantKeys:c}:{},...l.length>0?{slotKeys:l}:{},editableStrategy:u,impactScope:Fg(u),alternativeStrategies:_g(u)}}function Rg(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return zi(e,n)?"instance":!Xt(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function Nl(e,t){if(Xt(e.tag))return e.identity.key;let n=[...t.elements.values()].filter(r=>r.importedFrom===e.sourceFile&&wg(r,e.componentName));return n.length!==1?null:n[0].identity.key}function Pg(e,t,n){if(Xt(t.tag))return t;let r=zi(e,n);if(r)return r;let o=Nl(t,n);return o?n.elements.get(o)??null:null}function wg(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function Ag(e,t){return Xt(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function Tg(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 Ng(e,t,n,r,o){let i=new Set,s=zi(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&&Xt(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function zi(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(Xt(r.tag))return r;n=r.parentKey}return null}function Xt(e){return/^[A-Z]/.test(e)}function Fg(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function _g(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}var Mg=new Set(["markdown","body","content","value","document"]),Fl=[];function Ml(e){if(!(!Lg(e.tag)||!e.attributes))for(let t of e.attributes){if(!Mg.has(t.name))continue;if(Dg(t))return{kind:"markdown",field:t.name,schema:"markdown",valuePath:t.source?.expression,operationBoundary:Fl};let n=Og(t.resolvedValue);if(n==="prosemirror-doc"||n==="node-array")return{kind:"rich-text-json",field:t.name,valuePath:t.source?.expression,schema:n,operationBoundary:Fl};if(n==="unsupported-json-tree")return{kind:"rich-text-json",field:t.name,valuePath:t.source?.expression,schema:"unsupported-json-tree",operationBoundary:[],diagnostics:[{code:"unsupported-schema",field:t.name,message:'Only top-level node arrays and { type: "doc", content: [] } rich-text JSON are editable in stage D'}]}}}function Og(e){if(e){if(Array.isArray(e)&&e.every(t=>_l(t)))return"node-array";if(_l(e)){if(e.type==="doc"&&Array.isArray(e.content))return"prosemirror-doc";if(Array.isArray(e.content)||Array.isArray(e.children))return"unsupported-json-tree"}}}function _l(e){return!Array.isArray(e)&&typeof e=="object"&&e!==null}function Dg(e){return e.name==="markdown"}function Lg(e){return/^[A-Z]/.test(e)}var jg=["src","alt","poster","caption","width","height"];function Ol(e){let t=e.attributes?.filter(i=>jg.includes(i.name))??[];if(t.length===0)return;let n=t.map(i=>i.name),r=Object.fromEntries(t.filter(i=>i.source?.expression).map(i=>[i.name,i.source.expression])),o=Bg(t.map(i=>i.value));return{kind:$g(e.tag,n),sourceType:o,fields:n,editableFields:[],operationBoundary:[],...Object.keys(r).length>0?{valuePaths:r}:{}}}function $g(e,t){return e==="img"?"image":e==="video"||t.includes("poster")?"video":"media"}function Bg(e){return e.some(t=>t.startsWith("cms:"))?"cms-media-field":e.some(t=>/^(\.?\/|\/)/.test(t))?"local-file-reference":"asset-id"}var Hi=["set-class-name-source","apply-style-draft"];function Dl(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:Hi,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element"}]};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:Hi,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:Hi}}import{createHash as Ug}from"node:crypto";var Jn=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 le(e){return`sha256:${Ug("sha256").update(e).digest("hex")}`}function $l(e){let t=e.route.graph.elements.get(e.key);if(!t)return{key:e.key,routeId:e.route.routeId,filePath:"",componentName:"",sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,openingElementRange:{start:0,end:0},version:{documentVersion:e.route.graph.version,contentHash:le(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=Vg(e.route.source,t);if(!n)return{key:e.key,routeId:e.route.routeId,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:le(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Unable to locate JSX element for key ${t.identity.key}`}]};let r=n.openingElement,o=r.attributes.find(c=>c.type==="JSXAttribute"&&c.name.type==="JSXIdentifier"&&c.name.name==="className"),i={key:e.key,routeId:e.route.routeId,filePath:t.sourceFile,componentName:t.componentName,openingElementRange:jl(r),version:{documentVersion:e.route.graph.version,contentHash:le(e.route.source)}};if(!o)return{...i,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element."}]};let s=o.value,a=s?.type==="StringLiteral"?"stringLiteral":"expression";return{...i,sourceKind:a,attrRaw:Ll(e.route.source,o),valueRaw:s?Ll(e.route.source,s):null,attrRange:jl(o),diagnostics:[]}}function Bl(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 Vg(e,t){let n=it({source:e,profile:Bt({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=oe(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:Kg(t.sourceRange)});return!r.ok||r.match.node.type!=="JSXElement"?null:r.match.node}function Ul(e){let t=it({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 Ll(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function jl(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 Kg(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}import*as us from"@babel/parser";import Qi from"@babel/traverse";import*as S from"@babel/types";import*as gt from"node:path";import*as zl from"@babel/parser";import Yi from"@babel/traverse";import*as kn from"@babel/types";import*as H from"@babel/types";function ao(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?io(n,t):null}if(e.isMemberExpression()){let n=Gg(e.node),r=Jg(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?io(o,[...r,...t]):null}return e.isAwaitExpression()||Gi(e.node)?Pt(Zg(e.node),t,"awaited or fetched expression"):null}function Jg(e){let t=[],n=e;for(;H.isMemberExpression(n);){if(n.computed)if(H.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(H.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(H.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return H.isIdentifier(n)?t:null}function io(e,t=[]){let n=Xg(e,t);if(n)return n;let r=zg(e,t);if(r)return r;let o=Hg(e,t);return o||null}function zn(e){return e?.kind==="api-source"}function Xg(e,t){if(e.path.isVariableDeclarator()&&H.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&Wi(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return Pt(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&H.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(c=>H.isObjectProperty(c)&&Jl(c)==="data"&&Xn(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&Wi(a.node))return Pt(e.identifier.name,t,"query hook data binding")}let n=Wg(e);if(!n||Jl(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()||!Wi(i.node)?null:Pt(e.identifier.name,t,"query hook data binding")}function zg(e,t){if(e.path.isVariableDeclarator()&&H.isArrayPattern(e.path.node.id)){let a=e.path.get("init");if(!a?.isCallExpression()||!Kl(a.node))return null;let[c,l]=e.path.node.id.elements;return!H.isIdentifier(c)||c.name!==e.identifier.name||!H.isIdentifier(l)?null:Vl(e,l.name)?Pt(e.identifier.name,t,"state setter is updated by API data"):null}if(!e.path.isIdentifier())return null;let n=e.path.parentPath;if(!n?.isArrayPattern())return null;let r=n.parentPath;if(!r?.isVariableDeclarator())return null;let o=r.get("init");if(!o?.isCallExpression()||!Kl(o.node)||n.node.elements.findIndex(a=>a===e.path.node)!==0)return null;let s=n.node.elements[1];return H.isIdentifier(s)&&Vl(e,s.name)?Pt(e.identifier.name,t,"state setter is updated by API data"):null}function Hg(e,t){let n=e.path.isVariableDeclarator()?e.path:e.path.findParent(o=>o.isVariableDeclarator());if(!n?.isVariableDeclarator())return null;let r=n.get("init");return r?.isExpression()?r.isAwaitExpression()?Pt(e.identifier.name,t,"awaited binding result"):Gi(r.node)?Pt(e.identifier.name,t,"fetch-backed binding result"):null:null}function Wg(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 Xn(e,t){return H.isIdentifier(e)?e.name===t:H.isAssignmentPattern(e)?Xn(e.left,t):H.isObjectPattern(e)?e.properties.some(n=>H.isObjectProperty(n)?Xn(n.value,t):Xn(n.argument,t)):H.isArrayPattern(e)?e.elements.some(n=>!!n&&Xn(H.isRestElement(n)?n.argument:n,t)):!1}function Vl(e,t){let n=!1,r=!1;return e.scope.path.traverse({CallExpression(i){Gi(i.node)&&(n=!0),(Yg(i.node.callee,t)||i.node.arguments.some(s=>H.isIdentifier(s)&&s.name===t))&&(r=!0)}}),n&&r}function Wi(e){let t=co(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function Kl(e){return co(e.callee)==="useState"}function Gi(e){return so(e,t=>H.isCallExpression(t)&&co(t.callee)==="fetch")}function Gg(e){let t=e;for(;H.isMemberExpression(t);)t=t.object;return H.isIdentifier(t)?t.name:null}function Jl(e){return e.computed?null:H.isIdentifier(e.key)?e.key.name:H.isStringLiteral(e.key)?e.key.value:null}function co(e){return H.isIdentifier(e)?e.name:H.isMemberExpression(e)&&H.isIdentifier(e.property)?e.property.name:null}function Yg(e,t){return so(e,n=>H.isIdentifier(n)&&n.name===t)}function so(e,t){if(t(e))return!0;let n=H.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(H.isNode(i)&&so(i,t))return!0;continue}if(H.isNode(o)&&so(o,t))return!0}return!1}function Zg(e){return H.isIdentifier(e)?e.name:H.isCallExpression(e)?co(e.callee)??"api":H.isAwaitExpression(e)?"awaited-api":"api"}function Pt(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:Qg(e,t),reason:n}}function Qg(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var Hl=typeof Yi=="function"?Yi:Yi.default;function Wl(e,t){let n=Yl(e);if(!n)return{allowed:!0};let r=!1;return Hl(n,{CallExpression(o){if(!Zl(o.node,t.sourceRange)||!qg(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||zn(ao(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function Gl(e,t){let n=Yl(e);if(!n)return{allowed:!0};let r=!1;return Hl(n,{JSXExpressionContainer(o){Zl(o.node,t.sourceRange)&&(kn.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 Yl(e){try{return zl.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function qg(e){let t=e.callee;return kn.isMemberExpression(t)&&kn.isIdentifier(t.property)&&t.property.name==="map"}function Zl(e,t){let n=e.loc;return n?Xl({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&Xl({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function Xl(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 se from"@babel/types";function Ql(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 ct(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return zt(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(se.isObjectPattern(n)||se.isArrayPattern(n))return zt(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(ty(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function zt(e,t,n=!1){return se.isIdentifier(e)?e.name===t&&n:se.isObjectPattern(e)?e.properties.some(r=>se.isObjectProperty(r)?zt(r.value,t,n):zt(r.argument,t,n)):se.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=se.isRestElement(r)?r.argument:r;return zt(o,t,n)}):se.isAssignmentPattern(e)?zt(e.left,t,!0):se.isRestElement(e)?zt(e.argument,t,n):!1}function vn(e,t){if(e.path.isObjectPattern()){if(t){let r=Ye(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:ct(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:ct(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=ql(r),i=!1,s=o?o.initBinding&&Zi(o.initBinding)?(i=ct(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=vn(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=Ye(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||ct(e)}}}}let n=oy(e);if(n){let r=ey(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||ct(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=ny(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:ct(e)}}let i=Hn(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:ct(e)}:null}if(Zi(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:ct(e)}}return null}function ey(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=ql(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=Zi(i)?(a=ct(i),[...s]):(()=>{let u=vn(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=Ye(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||ct(t)}:null}function ql(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=iy(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function Zi(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function ty(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function ny(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=Ye(i.node,t);if(a)return a}return null}function eu(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=lo(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=Hn(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=ry(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=Hn(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 lo(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=Hn(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&Ye(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=lo(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=lo(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=lo(r,t);if(o)return o}}return null}function Ye(e,t,n=[]){if(se.isIdentifier(e))return e.name===t?n:null;if(se.isObjectPattern(e)){for(let r of e.properties)if(se.isObjectProperty(r)){let o=Hn(r);if(!o)continue;let i=Ye(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(se.isRestElement(r)){let o=Ye(r.argument,t,n);if(o)return o}}if(se.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=se.isRestElement(o)?o.argument:o,s=Ye(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return se.isAssignmentPattern(e)?Ye(e.left,t,n):null}function ry(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function oy(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 Hn(e){return e.computed?null:se.isIdentifier(e.key)?e.key.name:se.isStringLiteral(e.key)?e.key.value:null}function iy(e){let t=[],n=e;for(;se.isMemberExpression(n);){if(n.computed)if(se.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(se.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(se.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return se.isIdentifier(n)?{base:n.name,path:t}:null}var Ft=typeof Qi=="function"?Qi:Qi.default;function fe(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 Cn(e){return{file:e.file,component:e.component}}function sy(e){return e.target.kind==="node"?e.target.key:null}function ay(e){return"kind"in e}function uo(e){return!ay(e)}function os(e,t){let n=gt.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=gt.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function qi(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=pt(n,fe(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function ds(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 Je(e){try{return us.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function cy(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function ly(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 ce(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function Gt(e,t){let n=ce(e);return!!(n&&Ze(t,n))}function Ze(e,t){return t.start>=e.start&&t.end<=e.end}function gu(e){if(S.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(S.isJSXMemberExpression(e)){let t=e;for(;S.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function uy(e,t){let n=ce(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);if(!a||Gt(a.path.node,n))return;t.scope.getBinding(i)!==a&&r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=gu(i.node.name);s&&o(s,i)}}),[...r].sort()}function tu(e,t,n){let r=Je(e);if(!r)return{ok:!0};let o=oe(r,fe(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=oe(r,fe(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};if(Nu(o.match.path,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let s=uy(o.match.path,i.match.path);return s.length>0?{ok:!1,bindingNames:s}:{ok:!0}}function nu(e,t,n){let r=wt(t,n);return r?ht(e,r):null}function wt(e,t){let n=oe(e,fe(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:ls(e,t)}function ht(e,t){let n=t.findParent(E=>E.isArrowFunctionExpression()||E.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(E=>E===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(!S.isIdentifier(l)||l.name!=="map"||c.computed)return null;let u=a.get("object"),d=ho(e,u.node),m=r.node.params.map(E=>ho(e,E)),p=ce(i.node),h=ce(r.node);return!d||m.some(E=>E.length===0)||!p||!h?null:{callStart:p.start,callEnd:p.end,callbackStart:h.start,callbackEnd:h.end,collectionExpression:d,callbackParams:m,mapOperator:S.isOptionalMemberExpression(c)&&c.optional?"?.map":".map",collectionNeedsParens:hs(u.node),callbackPath:r,collectionPath:u}}function ho(e,t){let n=ce(t);return n?e.slice(n.start,n.end):""}function fo(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function dy(e,t){let n=ce(e.node);return n?fy(t).some(r=>{let o=ce(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function fy(e){let t=e.callbackPath.node.body;return S.isBlockStatement(t)?At(t.body):Nt(t)}function At(e){let t=[];for(let n of e){if(S.isReturnStatement(n)){n.argument&&t.push(...Nt(n.argument));continue}if(S.isBlockStatement(n)){t.push(...At(n.body));continue}if(S.isIfStatement(n)){let r=S.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...At(r)),n.alternate){let o=S.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...At(o))}continue}if(S.isSwitchStatement(n)){for(let r of n.cases)t.push(...At(r.consequent));continue}S.isTryStatement(n)&&(t.push(...At(n.block.body)),n.handler&&t.push(...At(n.handler.body.body)),n.finalizer&&t.push(...At(n.finalizer.body)))}return t}function Nt(e){return S.isJSXElement(e)?py(e)?ru(e.children):[e]:S.isJSXFragment(e)?ru(e.children):S.isParenthesizedExpression(e)||S.isTSAsExpression(e)||S.isTSSatisfiesExpression(e)||S.isTSNonNullExpression(e)||S.isTSTypeAssertion(e)?Nt(e.expression):S.isConditionalExpression(e)?[...Nt(e.consequent),...Nt(e.alternate)]:S.isLogicalExpression(e)&&_u(e.operator)?Nt(e.right):[]}function ru(e){return e.flatMap(t=>S.isJSXElement(t)||S.isJSXFragment(t)?Nt(t):S.isJSXExpressionContainer(t)&&(S.isJSXElement(t.expression)||S.isJSXFragment(t.expression)||S.isConditionalExpression(t.expression)||S.isLogicalExpression(t.expression))?Nt(t.expression):[])}function py(e){let t=e.openingElement.name;return S.isJSXIdentifier(t)?t.name==="Fragment":S.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function my(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function es(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function ou(e,t,n,r={}){if(!r.preserveConditionalBoundary&&Nu(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=ce(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(c=>ms(c)).map(c=>n.callbackPath.scope.getBinding(c)?.path.node).filter(Boolean)),s=new Set,a=(c,l)=>{let u=l.scope.getBinding(c);if(!u||Gt(u.path.node,o)||i.has(u.path.node))return;t.scope.getBinding(c)!==u&&s.add(c)};return e.traverse({ReferencedIdentifier(c){a(c.node.name,c)},JSXOpeningElement(c){let l=gu(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function iu(e,t,n){let r=ce(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>ms(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return fs(e,s=>{let a=s.scope.getBinding(s.node.name);if(!a||Gt(a.path.node,r)||o.has(a.path.node))return;t.scope.getBinding(s.node.name)!==a&&i.add(s.node.name)}),i.size>0?{ok:!1,bindingNames:[...i].sort()}:{ok:!0}}function hy(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>ms(a)).map(a=>e.callbackPath.scope.getBinding(a)?.path.node).filter(Boolean)),r=new Set,o=(a,c)=>{let l=c.scope.getBinding(a);if(!l||n.has(l.path.node))return;t.scope.getBinding(a)!==l&&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(S.isIdentifier(l))o(l.name,c);else{let u=gy(l);u&&o(u,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function gy(e){let t=e;for(;S.isTSQualifiedName(t);)t=t.left;return S.isIdentifier(t)?t.name:null}function yu(e,t){let n=ce(e.node),r=new Set;return fs(e,o=>{let i=o.scope.getBinding(o.node.name);if(!i||n&&Gt(i.path.node,n))return;t.scope.getBinding(o.node.name)!==i&&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 fs(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function yy(e){let t=xy(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=Mu(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=Ny({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=Tu(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?hs(o):!0}}}function xy(e,t,n){let r=Su(e,t);if(bu(e,r),Iu(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 Ft(e,{JSXElement(s){wu(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:ps(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 Ey(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=>Gn(a.file)));if(!t.has(Gn(e.sourceFile))||!t.has(Gn(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(Gn(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=ky(e.sourceAst,e.sourceComponent);if(!n)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without an exported source component identity"};let r=[];for(let a of e.knownSourceFiles){let c=Je(a.content);if(!c)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component because a loaded source file cannot be parsed"};r.push({file:a.file,ast:c})}let o=Sy(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=xu({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!Qe(s.file,e.targetFile)||ps(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}}function Sy(e,t){let n=new Map,r=i=>{let s=Rn(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 by(i,n))o=r(s)||o}return[...n.values()]}function by(e,t){let n=[],r=Iy(e,t);for(let o of e.ast.program.body){if(S.isExportDefaultDeclaration(o)&&S.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=Zn(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(S.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=Qn(e.file,o.source.value);for(let s of o.specifiers){if(S.isExportNamespaceSpecifier(s)){let l=Tt(s.exported);for(let u of t.values())Qe(u.file,i)&&n.push({file:e.file,namespace:is(l,u.namespace),exportName:u.exportName});continue}if(!S.isExportSpecifier(s))continue;let a=Tt(s.local),c=[...t.values()].filter(l=>Qe(l.file,i)&&Ht(l.namespace,a));if(c.length>0){let l=Tt(s.exported);for(let u of c){let d=Zn(u.namespace,a,l);d&&n.push({file:e.file,namespace:d,exportName:u.exportName})}continue}t.has(Rn({file:i,exportName:a}))&&n.push({file:e.file,exportName:Tt(s.exported)})}continue}if(S.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!S.isExportSpecifier(i))continue;let s=Tt(i.local),a=r.get(s)??[];if(a.length>0){let c=Tt(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let u=Zn(l.namespace,s,c);u&&n.push({file:e.file,namespace:u,exportName:l.exportName})}}}continue}if(S.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=Qn(e.file,o.source.value),s=o.exported;if(s){let a=Tt(s);for(let c of t.values())Qe(c.file,i)&&n.push({file:e.file,namespace:is(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())Qe(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function is(e,t){return t?`${e}.${t}`:e}function Ht(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function Zn(e,t,n){return!Ht(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function Iy(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(!S.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=Qn(e.file,i.source.value);for(let a of i.specifiers){if(S.isImportDefaultSpecifier(a)){let c=t.get(Rn({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(u=>Qe(u.file,s)&&Ht(u.namespace,"default"));for(let u of l){let d=Zn(u.namespace,"default",a.local.name);d&&r(a.local.name,{...u,namespace:d})}continue}if(S.isImportSpecifier(a)){let c=Tt(a.imported),l=[...t.values()].filter(d=>Qe(d.file,s)&&Ht(d.namespace,c));for(let d of l)r(a.local.name,d);let u=t.get(Rn({file:s,exportName:c}));u&&r(a.local.name,u);continue}if(S.isImportNamespaceSpecifier(a))for(let c of t.values())Qe(c.file,s)&&r(a.local.name,{...c,namespace:is(a.local.name,c.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(S.isVariableDeclaration(i))for(let s of i.declarations){if(!S.isIdentifier(s.id)||!s.init)continue;let a=Pn(s.init);if(!a||!S.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(Rn));for(let d of c){let m=Zn(d.namespace,a.name,s.id.name),p=m?{...d,namespace:m}:d,h=Rn(p);u.has(h)||(r(s.id.name,p),u.add(h),o=!0)}}}return n}function Rn(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${as(e.file)}#${t}`}function Tt(e){return S.isIdentifier(e)?e.name:e.value}function ky(e,t){for(let n of e.program.body){if(S.isExportDefaultDeclaration(n)){let o=n.declaration;if((S.isFunctionDeclaration(o)||S.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(S.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!S.isExportNamedDeclaration(n))continue;let r=n.declaration;if((S.isFunctionDeclaration(r)||S.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(S.isVariableDeclaration(r)){for(let o of r.declarations)if(S.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!S.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:S.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function xu(e){let t=vy(e),n=[],r=Iu(e.ast,t);return Ft(e.ast,{JSXElement(o){Qe(e.file,e.sourceFile)&&ps(o)===e.sourceComponent||wu(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function Eu(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function Su(e,t){let n=Eu();return Ft(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function vy(e){let t=Eu();return Qe(e.file,e.sourceFile)&&Cy(t,Su(e.ast,e.sourceComponent)),Ft(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=Qn(e.file,o),s=e.componentIdentities.filter(a=>Qe(a.file,i));if(s.length!==0)for(let a of r.specifiers){let c=n.scope.getBinding(a.local.name);if(c){if(S.isImportDefaultSpecifier(a)&&s.some(l=>l.exportName==="default")&&t.localBindings.add(c),S.isImportDefaultSpecifier(a)){let l=s.filter(u=>Ht(u.namespace,"default"));if(l.length>0){let u=t.namespaceMembers.get(c)??new Set;for(let d of l){let m=au(d,"default");m&&u.add(m)}t.namespaceMembers.set(c,u)}continue}if(S.isImportSpecifier(a)){let l=S.isIdentifier(a.imported)?a.imported.name:a.imported.value,u=s.filter(d=>Ht(d.namespace,l));if(u.length>0){let d=t.namespaceMembers.get(c)??new Set;for(let m of u){let p=au(m,l);p&&d.add(p)}t.namespaceMembers.set(c,d);continue}s.some(d=>!d.namespace&&d.exportName===l)&&t.localBindings.add(c);continue}if(S.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)}}}}}),bu(e.ast,t),t}function Cy(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 bu(e,t){Ft(e,{VariableDeclarator(n){if(!n.node.init)return;let r=Pn(n.node.init);if(r){if(S.isIdentifier(n.node.id)){let o=Wt(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&ss(t,i,o);return}if(S.isObjectPattern(n.node.id)){let o=Wt(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&Cu(n.node.id,o.namespaceMembers,t,n)}}}})}function Iu(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return Ft(e,{ReferencedIdentifier(r){if(n){r.stop();return}Ry(r)||!r.isIdentifier()||!ku(r,t)||Py(r,t)||wy(r)||(n=!0,r.stop())}}),n}function Ry(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 ku(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)&&Wt(r.node,t,r)?r:null}function Py(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!su(e,r))return!1;let o=ku(e,t);if(!o)return!1;if(Pn(r.node)===o.node)return!!Wt(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&su(e,a)&&!!Wt(a.node,t,a)}function wy(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function su(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Wt(e,t,n){let r=Pn(e);if(!r)return null;if(S.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(S.isObjectExpression(r))return Ay(r,t,n);let o=Pu(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?vu(s,o.slice(1).join(".")):null}function Ay(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!S.isObjectProperty(i))continue;let s=Ru(i);if(!s||!S.isExpression(i.value)){S.isExpression(i.value)&&(o||=Wt(i.value,t,n)!==null);continue}let a=Wt(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 vu(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 ss(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 Cu(e,t,n,r){for(let o of e.properties){if(S.isRestElement(o)){if(S.isIdentifier(o.argument)){let c=r.scope.getBinding(o.argument.name);c&&ss(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!S.isObjectProperty(o))continue;let i=Ru(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=vu(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=S.isAssignmentPattern(o.value)?o.value.left:o.value;if(S.isIdentifier(a)){let c=r.scope.getBinding(a.name);c&&ss(n,c,s);continue}if(S.isObjectPattern(a)&&s.namespaceMembers.size>0){Cu(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function Ru(e){return e.computed?S.isStringLiteral(e.key)||S.isNumericLiteral(e.key)?String(e.key.value):null:Ty(e.key)}function Ty(e){return S.isIdentifier(e)?e.name:S.isStringLiteral(e)||S.isNumericLiteral(e)?String(e.value):null}function Pn(e){return S.isParenthesizedExpression(e)||S.isTSAsExpression(e)||S.isTSSatisfiesExpression(e)||S.isTSNonNullExpression(e)||S.isTSTypeAssertion(e)?Pn(e.expression):S.isExpression(e)?e:null}function Pu(e){if(S.isIdentifier(e))return[e.name];if((S.isMemberExpression(e)||S.isOptionalMemberExpression(e))&&!e.computed&&S.isIdentifier(e.property)){let t=Pn(e.object),n=t?Pu(t):null;return n?[...n,e.property.name]:null}return null}function au(e,t){if(!Ht(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 wu(e,t){let n=e.node.openingElement.name;if(S.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=Au(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 Au(e){if(S.isJSXIdentifier(e))return[e.name];if(S.isJSXMemberExpression(e)){let t=Au(e.object);return t?[...t,e.property.name]:null}return null}function ps(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()&&S.isIdentifier(n.node.id))return n.node.id.name}return null}function Ny(e){let t=ce(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||Gt(a.path.node,t))return;let c=My(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 u=Dy(e.callSitePath,c.propName,e.source);if(!u.ok){o=u.reason;return}let d=Fy(u.expression,c.remainingPath);if(!d){o="Cannot move prop-backed repeat child because the mapped prop path is not a portable expression";return}let m=yu(u.expressionPath,e.targetParentPath);if(!m.ok){o=m.reason??`Cannot move prop-backed repeat child because the mapped prop source is not visible at the target: ${m.bindingNames.join(", ")}`;return}n.set(`${c.range.start}:${c.range.end}`,{...c.range,text:d});return}e.targetParentPath.scope.getBinding(s.node.name)!==a&&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:Ly(e.source,t,[...n.values()])}}function Fy(e,t){if(t.length===0)return e;let n=Tu(e);if(!n)return null;let r=hs(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=_y(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function _y(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function My(e,t,n){let r=Oy(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=vn(t,o);if(!i)return null;let s=r?.range??ce(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function Oy(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!Gt(n.node,t)||n.node.computed||!S.isIdentifier(n.node.property))return null;let r=ce(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function Dy(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()&&S.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=ho(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 Ly(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 Tu(e){try{let n=us.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=S.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&S.isExpression(r)?r:null}catch{return null}}function jy(e){let t=ce(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||Gt(s.path.node,t))return;let a=cu(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let u=cu(c,e.targetFile,e.targetFile);(!u||u.moduleFile!==a.moduleFile||!$y(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 fs(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 $y(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 cu(e,t,n){let r=By(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=Qn(t,i),a=i.startsWith(".")?os(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=S.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 By(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function Qn(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?gt.normalize(gt.join(gt.dirname(e),t)).replace(/\\/g,"/"):t}function Qe(e,t){return as(e)===as(t)}function as(e){let t=Gn(e);return t.endsWith("/index")?t.slice(0,-6):t}function Gn(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function ms(e){let t=[],n=r=>{if(r){if(S.isIdentifier(r)){t.push(r.name);return}if(S.isObjectPattern(r)){for(let o of r.properties){if(S.isRestElement(o)){n(o.argument);continue}S.isObjectProperty(o)&&n(o.value)}return}if(S.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(S.isAssignmentPattern(r)){n(r.left);return}if(S.isRestElement(r)){n(r.argument);return}S.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function Uy(e){let t=[];for(let n of e.callbackPath.node.params){if(S.isIdentifier(n)){t.push(n.name);continue}if(S.isRestElement(n)&&S.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 Vy(e,t){return{...e,callbackParams:t}}function lu(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function hs(e){return!(S.isIdentifier(e)||S.isThisExpression(e)||S.isMemberExpression(e)||S.isOptionalMemberExpression(e)||S.isCallExpression(e)||S.isOptionalCallExpression(e))}function Nu(e,t){return Fu(e,t).length>0}function ts(e,t){let n=ce(e.node),r=ce(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()&&!Ky(o,n,r)))return!0;o=o.parentPath}return!1}function Ky(e,t,n){let r=ce(e.node.consequent);if(r&&Ze(r,t)&&!Ze(r,n))return!1;let o=e.node.alternate?ce(e.node.alternate):null;return!(o&&Ze(o,t)&&!Ze(o,n))}function Fu(e,t){let n=ce(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=ce(o.node.consequent),a=ce(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()&&_u(o.node.operator)){let s=ce(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 uu(e,t,n,r){let o=Fu(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=ho(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=Jy(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${zy(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function Jy(e,t){return Xy(e.node)?t:`(${t})`}function Xy(e){return S.isIdentifier(e)||S.isThisExpression(e)||S.isSuper(e)||S.isMemberExpression(e)||S.isOptionalMemberExpression(e)||S.isCallExpression(e)||S.isOptionalCallExpression(e)||S.isBooleanLiteral(e)||S.isNumericLiteral(e)||S.isStringLiteral(e)||S.isNullLiteral(e)||S.isUnaryExpression(e)}function _u(e){return e==="&&"||e==="||"||e==="??"}function zy(e){return e.trim().startsWith("<")?e:`(${e})`}function Mu(e,t){let n=ce(e.node),r=ce(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=du(e),i=du(t);if(!o||!i||!Hy(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=Wy(s.node,n);if(a&&!Ze(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=ce(s.node.right);if(a&&Ze(a,n)&&!Ze(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())&&Gy(s)){let a=ce(s.node.body)??ce(s.node);if(a&&!Ze(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 du(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?ce(t.node.argument):null;if(t.isArrowFunctionExpression()&&(S.isJSXElement(t.node.body)||S.isJSXFragment(t.node.body)||S.isConditionalExpression(t.node.body)||S.isLogicalExpression(t.node.body)))return ce(t.node.body);t=t.parentPath}return null}function Hy(e,t){return e.start===t.start&&e.end===t.end}function Wy(e,t){let n=ce(e.consequent);if(n&&Ze(n,t))return n;let r=ce(e.alternate);return r&&Ze(r,t)?r:null}function Gy(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(S.isMemberExpression(n)||S.isOptionalMemberExpression(n))&&S.isIdentifier(n.property)&&n.property.name==="map"&&!n.computed}var Yy={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 po(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=Yy[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 Zy(e,t){for(let n of e.program.body){if(!S.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>S.isImportDefaultSpecifier(o));if(r&&S.isImportDefaultSpecifier(r))return r.local.name}return null}function Qy(e,t,n){for(let r of e.program.body){if(!S.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>S.isImportSpecifier(i)&&(S.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&S.isImportSpecifier(o))return o.local.name}return null}function fu(e){let t=new Set;return Ft(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function pu(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function qy(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=ds(e),o=Je(t);if(n.exportName!=="default"){let a=o?Qy(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?pu(r,fu(o)):r;return{localName:c,importStep:ns(e,c)}}if(!o)return{localName:r,importStep:ns(e,r)};let i=Zy(o,n.source);if(i)return{localName:i};let s=pu(r,fu(o));return{localName:s,importStep:ns(e,s)}}function ex(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??ds(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 tx(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?nx(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function nx(e){return Object.fromEntries(Object.entries(e).filter(t=>cs(t[1])))}function cs(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(cs):typeof e=="object"?Object.values(e).every(cs):!1}function rx(e,t){let n=Je(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=xu({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 ns(e,t=ds(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 mu(e,t){if("kind"in e)return{parentNode:null,anchorNode:null,placement:e.relation};if("parentKey"in e)return{parentNode:t.getNode(e.parentKey),anchorNode:null,placement:e.relation};let n=t.getNode(e.anchorKey);return{parentNode:n?.parentKey?t.getNode(n.parentKey)??n:n,anchorNode:n,placement:e.relation}}function ox(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function Wn(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function gs(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function Yn(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:gs(e,t.slice(0,n)),index:r.index}}return null}function rs(e,t){return e.locator?e.collectionPathMap?.[t]?gs(e.locator,e.collectionPathMap[t]):Yn(e.locator)?sx(e.locator,ax(t,e.collectionIndexMap)):null:null}function ix(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:Ou(o,t)}function Ou(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=Ou(r,t);return o===void 0?void 0:{[n.name]:o}}function mo(e,t,n){return n?.finalSource?.kind==="component-prop"?"Cannot edit prop-backed node structure with a generic node operation":t?.kind==="value-binding"&&t.sourceKind==="repeat-template"&&!e.isRepeatItemRoot?"Cannot edit repeat-backed child node structure with a generic node operation":t?.kind==="value-binding"&&t.file!==e.file&&t.sourceKind!=="repeat-template"?"Cannot edit upstream-bound node structure with a generic node operation":null}function sx(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},gs(e,i)}return null}function ax(e,t){return t?.[e]??e}function hu(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 cx(e,t){return lx(e.root,t.root)&&dx(e.path??[],t.path??[])}function lx(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&&ux(e.sourceRange,t.sourceRange)}}function ux(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function ls(e,t){let n=null;return Ft(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 dx(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 go=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:Wn(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:Wn(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:Wn(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:Wn(t.kind,t.params.kind)};let r=t;if(!uo(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=mu(r.params.position,this.graph);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:Wn(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"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=sy(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.routeId&&n.routeId&&n.params.routeId!==n.routeId?{ok:!1,errorCode:"stale-version",reason:"The className source route changed before save."}: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.buildSetPropsSteps({initialOrder:0,node:r,props:n.params.props,request:n});return i.ok?this.buildPlan(t,n,i.steps,o):i}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.buildSetPropsSteps({initialOrder:s.length,node:r,props:n.params.props,request:n});if(!a.ok)return a;s.push(...a.steps)}return this.buildPlan(t,n,s,i)}async buildSetPropsSteps(t){let{initialOrder:n,node:r,props:o,request:i}=t,s=r.file,a=[],c={};for(let[l,u]of Object.entries(o)){if(u===void 0)continue;let d=await this.graph.getElementPropertyWriteTarget?.(r.key,l),m=r.attributes?.find(p=>p.name===l);if(!(typeof m?.resolvedValue=="string"&&m.resolvedValue===u||m?.source===null&&m.value===u)){if(d?.kind==="external-entry")return{ok:!1,errorCode:"capability-denied",reason:`set-props cannot overwrite readonly external property '${l}'`};if(d?.kind==="value-binding"&&d.locator){let p=d.locator;if(d.sourceKind==="repeat-template"&&typeof i.selectionRef?.instanceIndex=="number"){let h=rs(d,i.selectionRef.instanceIndex);if(!h)return{ok:!1,errorCode:"invalid-params",reason:"set-props could not resolve the selected repeat item"};p=h}a.push({order:n+a.length,file:d.file,type:"update-value",locator:p,value:u});continue}c[l]=u}}return Object.keys(c).length>0&&a.push({order:n+a.length,file:s,type:"set-props",locator:fe(r),props:c}),{ok:!0,steps:a}}buildTextRewriteSteps(t,n,r,o,i){if(o?.kind==="value-binding"&&o.locator){if(o.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let a=rs(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:fe(t),segmentIndex:n,newText:r}]}}coerceTextValueForValueTarget(t,n,r,o="update-text"){let i=this.graph.getFileContent(t),s=Je(i);if(!s)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not inspect the value source`};let a=oe(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!cy(a.match.path))return{ok:!0,value:r};let c=ly(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=rs(o,i);if(!c)return{ok:!1,errorCode:"invalid-params",reason:"update-array-item could not resolve the selected repeat item"};let l=this.coerceTextValueForValueTarget(o.file,c,s,"update-array-item");return l.ok?this.isValueTargetUnchanged(o.file,c,l.value)?{ok:!1,errorCode:"invalid-params",reason:"update-array-item value is unchanged"}:this.buildPlan(t,n,[{order:0,file:o.file,type:"update-array-item",locator:c,value:l.value}],r):l}isValueTargetUnchanged(t,n,r){let o=Je(this.graph.getFileContent(t));if(!o)return!1;let i=oe(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){if(!o.canUpdateText)return{ok:!1,errorCode:"capability-denied",reason:"Cannot update text on this node"};let s=this.buildTextRewriteSteps(r,n.params.segmentIndex,n.params.value,i,n.selectionRef);return s.ok?this.buildPlan(t,n,s.steps,o):s}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 m=Yn(d.locator);if(m)return this.buildPlan(t,n,[{order:0,file:d.file,type:"remove-bound-array-item",locator:m.locator,index:m.index}],o)}return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed node removal requires a writable array target"}}let s=mo(r,i,this.graph.getTextProvenance?.(r.key,0)??null);if(s)return{ok:!1,errorCode:"unsupported-operation",reason:s};let a=this.getRepeatBackedTemplateStructureReason(r);if(a)return{ok:!1,errorCode:"unsupported-operation",reason:a};let c=await this.getUpstreamBackedDescendantReason(r);if(c)return{ok:!1,errorCode:"unsupported-operation",reason:c};let l=[{order:0,file:r.file,type:"remove-node",locator:fe(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||rx(n,t)>1)return null;let r=os(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(!uo(n.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};if(n.params.node.kind==="component-call"&&!n.params.node.component)return{ok:!1,errorCode:"unsupported-operation",reason:"Materialized component insertion requires the materialization transaction planner"};if(!o.canInsertChild)return{ok:!1,errorCode:"capability-denied",reason:"Cannot insert child into this node"};let s=this.graph.getEditableTextSegmentIndex(r.key),a=s!==null?await this.graph.getTextWriteTarget(r.key,s):null,c=mo(r,a,s!==null?this.graph.getTextProvenance?.(r.key,s)??null:null);if(c)return{ok:!1,errorCode:"unsupported-operation",reason:c};let l=await this.getUpstreamBackedDescendantReason(r);if(l)return{ok:!1,errorCode:"unsupported-operation",reason:l};let u=await this.planExternalBackedInsertChild(t,n,r,o,i,a);if(u)return u;let d=await this.planRepeatBackedInsertChild(t,n,r,o);if(d)return d;let m=this.getRepeatBackedTemplateStructureReason(r);if(m)return{ok:!1,errorCode:"unsupported-operation",reason:m};let p=Wl(this.graph.getFileContent(r.file),r);if(!p.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:p.reason??"Cannot insert child into this node"};let h=po(r,n.params.node);if(h)return{ok:!1,errorCode:"unsupported-operation",reason:h};let E=[],C=0,v=n.params.node.kind==="component-call"?qy(n.params.node,this.graph.getFileContent(r.file)):void 0,T=v?.importStep;return T&&E.push({order:C++,file:r.file,type:"add-import",moduleSpecifier:T.moduleSpecifier,imports:T.imports}),E.push({order:C++,file:r.file,type:"insert-child",parentLocator:fe(r),node:{jsx:ex(n.params.node,v?.localName)},placement:n.params.position.relation,anchorLocator:i?fe(i):void 0}),this.buildPlan(t,n,E,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!uo(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:tx(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(!uo(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=Yn(a.locator);if(!c)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let l=ix(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"?hu(0,a.collectionIndexMap):hu(a.collectionIndexMap?.length??c.index+1,a.collectionIndexMap);return this.buildPlan(t,n,[{order:0,file:a.file,type:"insert-bound-array-item",locator:c.locator,index:u,value:l}],o)}async getUpstreamBackedDescendantReason(t){if(!this.graph.getChildNodes)return null;let n=[...this.graph.getChildNodes(t.key)];for(;n.length>0;){let r=n.shift();if(!r)continue;let o=this.graph.getEditableTextSegmentIndex(r.key),i=o!==null?await this.graph.getTextWriteTarget(r.key,o):null,s=mo(r,i,o!==null?this.graph.getTextProvenance?.(r.key,o)??null:null);if(s)return s;n.push(...this.graph.getChildNodes(r.key))}return null}getRepeatBackedTemplateStructureReason(t){if(t.isRepeatItemRoot)return this.isRepeatTemplateRootNode(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:")||this.isInsideMapCallback(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}isRepeatTemplateRootNode(t){let n=Je(this.graph.getFileContent(t.file));if(!n)return t.isRepeatItemRoot===!0;let r=oe(n,fe(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:ls(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=ht(this.graph.getFileContent(t.file),o);return i?dy(o,i):t.isRepeatItemRoot===!0}isInsideMapCallback(t){let n=Je(this.graph.getFileContent(t.file));if(!n)return!1;let r=oe(n,fe(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:ls(n,t);return o?!!o.findParent(i=>{if(!i.isCallExpression()&&!i.isOptionalCallExpression())return!1;let s=i.node.callee;return(S.isMemberExpression(s)||S.isOptionalMemberExpression(s))&&S.isIdentifier(s.property)&&s.property.name==="map"}):!1}planRepeatTemplateInternalMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&this.isRepeatTemplateRootNode(r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=Je(c);if(!l)return null;let u=wt(l,r),d=wt(l,o);if(!u||!d)return null;let m=ht(c,u),p=ht(c,d);if(!fo(m,p))return null;if(a&&(s==="before"||s==="after")){let E=wt(l,a),C=E?ht(c,E):null;if(!fo(m,C))return null}if(ts(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let h=tu(c,r,o);return h.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:fe(r),targetParentLocator:fe(o),placement:s,anchorLocator:a?fe(a):void 0,selectionContext:Cn(o)}],i):{ok:!1,errorCode:"unsupported-operation",reason:h.reason??`Cannot move node because it depends on bindings outside the target scope: ${h.bindingNames.join(", ")}`}}planRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&this.isRepeatTemplateRootNode(r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=Je(c);if(!l)return null;let u=wt(l,r),d=wt(l,o);if(!u||!d)return null;let m=ht(c,u);if(!m)return null;let p=ht(c,d);if(fo(m,p))return null;if(p&&!my(p,m))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")){let P=nu(c,l,a);if(p&&!fo(p,P)||!p&&P)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 P=po(o,{kind:"native-tag",tag:r.tag});if(P)return{ok:!1,errorCode:"unsupported-operation",reason:P}}let h=qi(this.graph,r);if(!h)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(ts(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let E=uu(c,u,d,h);for(let P of E.conditionPaths){let $=iu(P,d,m);if(!$.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${$.bindingNames.join(", ")}`}}let C=ou(u,d,m,{preserveConditionalBoundary:E.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 v=hy(m,d);if(!v.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its callback parameters depend on bindings outside the target scope: ${v.bindingNames.join(", ")}`};let T=m;if(r.component!==o.component){let P=yy({source:c,ast:l,sourceContext:m,sourceNode:r,targetParent:o,targetParentPath:d});if(!P.ok)return{ok:!1,errorCode:"unsupported-operation",reason:P.reason};T=P.context}else{let P=yu(m.collectionPath,d);if(!P.ok)return{ok:!1,errorCode:"unsupported-operation",reason:P.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${P.bindingNames.join(", ")}`}}return this.buildPlan(t,n,[{order:0,file:r.file,type:"move-repeat-template-child",locator:fe(r),targetParentLocator:fe(o),placement:s,anchorLocator:a?fe(a):void 0,repeatExpression:lu(T,E.sourceJsx),selectionContext:Cn(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&this.isRepeatTemplateRootNode(r)||r.file===o.file)return null;let c=this.graph.getFileContent(r.file),l=this.graph.getFileContent(o.file),u=Je(c),d=Je(l);if(!u||!d)return null;let m=Ey({knownSourceFiles:this.graph.getKnownSourceFiles?.(),routeEntryFiles:this.graph.getRouteEntryFiles?.(),sourceAst:u,sourceFile:r.file,targetFile:o.file,sourceComponent:r.component,targetComponent:o.component});if(!m.ok)return{ok:!1,errorCode:"unsupported-operation",reason:m.reason};let p=wt(u,r),h=wt(d,o);if(!p||!h)return null;let E=Mu(m.callSitePath,h);if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:E.reason};let C=ht(c,p);if(!C)return null;if(ht(l,h))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")&&nu(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 O=po(o,{kind:"native-tag",tag:r.tag});if(O)return{ok:!1,errorCode:"unsupported-operation",reason:O}}let T=qi(this.graph,r);if(!T)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(ts(p,h))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let P=uu(c,p,h,T);for(let O of P.conditionPaths){let L=iu(O,h,C);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 $=ou(p,h,C,{preserveConditionalBoundary:P.conditionPaths.length>0});if(!$.ok)return{ok:!1,errorCode:"unsupported-operation",reason:$.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${$.bindingNames.join(", ")}`};let re=jy({sourceFile:r.file,targetFile:o.file,sourceContext:C,targetParentPath:h});if(!re.ok)return{ok:!1,errorCode:"unsupported-operation",reason:re.reason};let te=Uy(C);if(!te.ok)return{ok:!1,errorCode:"unsupported-operation",reason:te.reason};let A=Vy(C,te.callbackParams),D=[{order:0,file:r.file,type:"remove-node",locator:fe(r),removeWhitespace:!0}];for(let O of re.imports)D.push({order:D.length,file:o.file,type:"add-import",moduleSpecifier:O.moduleSpecifier,imports:O.imports});return D.push({order:D.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:fe(o),expression:lu(A,P.sourceJsx),placement:s,anchorLocator:a?fe(a):void 0,selectionContext:Cn(o)}),this.buildPlan(t,n,D,i)}async planMoveNode(t,n,r,o){if(!o.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};let i=mu(n.params.target,this.graph),s=i.parentNode;if(!s)return{ok:!1,errorCode:"locator-miss",reason:`Target parent for request '${n.id}' not found in graph`};if(ox(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 a=await this.graph.getTextWriteTarget(r.key,0);if(a?.kind==="external-entry"){let v=n.params.target.relation,T=i.anchorNode&&(v==="before"||v==="after")?await this.graph.getTextWriteTarget(i.anchorNode.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:"move-node",value:{operation:"move-node",relation:v,anchorSourceId:T?.kind==="external-entry"?T.sourceId:null,parentKey:"parentKey"in n.params.target?n.params.target.parentKey:null}}],o)}let c=r.file!==s.file,l=n.params.target.relation,u=i.anchorNode,d=mo(r,a,this.graph.getTextProvenance?.(r.key,0)??null);if(d&&!es(d))return{ok:!1,errorCode:"unsupported-operation",reason:d};if(r.isRepeatItemRoot&&u?.isRepeatItemRoot&&r.repeatOwnerKey&&r.repeatOwnerKey===u.repeatOwnerKey&&(l==="before"||l==="after")){let v=a,T=await this.graph.getTextWriteTarget(u.key,0);if(v?.kind==="value-binding"&&T?.kind==="value-binding"&&v.locator&&T.locator){let P=Yn(v.locator),$=Yn(T.locator);if(P&&$&&v.file===T.file&&cx(P.locator,$.locator)){let re=P.index,te=$.index,A=l==="before"?te-(re<te?1:0):te+(re<te?0:1);return this.buildPlan(t,n,[{order:0,file:v.file,type:"move-array-item",locator:P.locator,fromIndex:re,toIndex:A}],o)}}}if(r.isRepeatItemRoot&&this.isRepeatTemplateRootNode(r))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed item outside its collection"};let m=this.getRepeatBackedTemplateStructureReason(r),p=es(d)?d:m;if(p&&es(p)){let v=this.planRepeatTemplateInternalMove(t,n,r,s,o,l,u);if(v)return v;let T=this.planRepeatTemplateHoistMove(t,n,r,s,o,l,u);if(T)return T;let P=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,l,u);return P||{ok:!1,errorCode:"unsupported-operation",reason:p}}if(m)return{ok:!1,errorCode:"unsupported-operation",reason:m};let h=await this.getUpstreamBackedDescendantReason(r);if(h)return{ok:!1,errorCode:"unsupported-operation",reason:h};if(r.tag&&r.tag.toLowerCase()===r.tag){let v=po(s,{kind:"native-tag",tag:r.tag});if(v)return{ok:!1,errorCode:"unsupported-operation",reason:v}}if(c)return this.planCrossFileMove(t,n,r,s,o,l,u);let E=tu(this.graph.getFileContent(r.file),r,s);if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:E.reason??`Cannot move node because it depends on bindings outside the target scope: ${E.bindingNames.join(", ")}`};let C=[{order:0,file:r.file,type:"move-node",locator:fe(r),targetParentLocator:fe(s),placement:l,anchorLocator:u?fe(u):void 0,selectionContext:Cn(s)}];return this.buildPlan(t,n,C,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,u=this.graph.getFileContent(r.file),d=qi(this.graph,r)??`<${r.component} />`,m=Gl(u,r);if(!m.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:m.reason??"Cannot move subtree across files"};if(c.push({order:l++,file:r.file,type:"remove-node",locator:fe(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let h=r.tag??r.component,C={moduleSpecifier:os(o.file,r.importedFrom),imports:r.exportName==="default"?[{kind:"default",local:h}]:[{kind:"named",imported:r.exportName,local:h===r.exportName?void 0:h}]};c.push({order:l++,file:o.file,type:"add-import",moduleSpecifier:C.moduleSpecifier,imports:C.imports}),c.push({order:l++,file:o.file,type:"insert-child",parentLocator:fe(o),node:{jsx:d},placement:s,anchorLocator:a?fe(a):void 0,selectionContext:Cn(o)})}else c.push({order:l++,file:o.file,type:"insert-child",parentLocator:fe(o),node:{jsx:d},placement:s,anchorLocator:a?fe(a):void 0,selectionContext:Cn(o)});let p=this.buildRemoveComponentImportStep(r,u);return p&&c.push({...p,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:le(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}}}};import qn from"node:path";import*as zu from"@babel/parser";import ys from"@babel/traverse";import*as b from"@babel/types";var Hu=typeof ys=="function"?ys:ys.default;function Wu(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}var Du=new WeakMap;function Lu(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 Gu(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=As(s,t,n);if(!a)return null;let c=Ts(a,r.sourceRange);if(!c)return null;let l=r.source??await tt({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!l){let p=await Ls({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});if(!p)return null;if(p.kind==="external")return{kind:"external-entry",file:p.file,sourceType:p.sourceType,sourceId:p.sourceId,adapterId:p.adapterId,displayExpression:p.displayPath};let h={kind:"value",root:p.root,path:p.path.length>0?p.path:[]};return{kind:"value-binding",file:p.file,locator:h,root:p.root,path:p.path,displayExpression:p.displayExpression??nr(c.node,n),sourceKind:p.sourceKind,...p.collectionIndexMap?{collectionIndexMap:p.collectionIndexMap}:{},...p.collectionPathMap?{collectionPathMap:p.collectionPathMap}:{}}}let u=new Set,d=await $x({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});if(!d)return null;if(d.kind==="external")return{kind:"external-entry",file:d.file,sourceType:d.sourceType,sourceId:d.sourceId,adapterId:d.adapterId,displayExpression:d.displayPath};let m={kind:"value",root:d.root,path:d.path.length>0?d.path:[]};return{kind:"value-binding",file:d.file,locator:m,root:d.root,path:d.path,displayExpression:d.displayExpression??l.expression,sourceKind:d.sourceKind,...d.collectionIndexMap?{collectionIndexMap:d.collectionIndexMap}:{},...d.collectionPathMap?{collectionPathMap:d.collectionPathMap}:{}}}async function Yu(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=As(i,t,n);if(!s)return null;let a=e.expression!==void 0?(e.sourceRange?ed(s,n,e.expression,e.sourceRange):null)??_s(s,n,e.expression):e.sourceRange?Ts(s,e.sourceRange):null;if(!a)return null;let c=hx(a),l=new Set,u=e.sourceInfo??await tt({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:l}),d=u?await Le({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 qx({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 mx(d,e.expression??nr(c.node,n))}async function ws(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=As(i,t,n);if(!s)return De("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?gx({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}):yx({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}function Zu(e){try{return zu.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function As(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=Zu(n);return e.set(t,{source:n,ast:o}),o}function Ts(e,t){let n=null,r=-1;for(let o of tr(e).expressions){let i=o.node.loc;if(!i||!Ns(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s>=r&&(n=o,r=s)}return n}function fx(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of tr(e).expressions){if(!px(o.node.loc,t))continue;let i=(o.node.end??0)-(o.node.start??0);i<=r&&(n=o,r=i)}return n}function Qu(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of tr(e).jsxElements){let i=o.node.loc;if(!i||!Ns(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s<=r&&(n=o,r=s)}return n}function tr(e){let t=Du.get(e);if(t)return t;let n={expressions:[],jsxElements:[]};return Hu(e,{Expression(r){n.expressions.push(r)},JSXElement(r){n.jsxElements.push(r)}}),Du.set(e,n),n}function px(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 Ns(e,t){let n=ju({line:e.start.line,column:e.start.column},{line:t.startLine,column:t.startColumn}),r=ju({line:e.end.line,column:e.end.column},{line:t.endLine,column:t.endColumn});return n>=0&&r<=0}function qu(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 ju(e,t){return e.line!==t.line?e.line<t.line?-1:1:e.column!==t.column?e.column<t.column?-1:1:0}async function tt(e){if(b.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!b.isMemberExpression(e.expression))return null;let t=await dd(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:nr(e.expression,e.source),base:t.base,path:t.path}:null}function mx(e,t){if(!e)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}:{}}}function hx(e){if(e.isLogicalExpression()&&(e.node.operator==="||"||e.node.operator==="??")){let t=e.get("left");if(!Array.isArray(t)&&t.isExpression())return t}return e}function nr(e,t){if(t)return Fs(e,t);let n=cE(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function Fs(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function _s(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of tr(e).expressions){if(Fs(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function ed(e,t,n,r){let o=null,i=Number.POSITIVE_INFINITY;for(let s of tr(e).expressions){if(Fs(s.node,t)!==n)continue;let a=s.node.loc;if(!a||!Ns(a,r))continue;let c=(s.node.end??0)-(s.node.start??0);c<=i&&(o=s,i=c)}return o}async function gx(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=Ts(r,o.sourceRange),u=o.source??(l?await tt({expression:l.node,scope:l.scope,source:n,currentFile:t,readFile:i,exists:s,fileCache:a,visited:c}):null);if(!u){if(!l)return xx(t,o.value);let m=await Ls({currentFile:t,expressionPath:l,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});return m?m.kind==="external"?Ku(t,m):ks(t,nr(l.node,n),m):Ex({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return De("unsupported-expression","Unable to locate text expression for provenance resolution");let d=await Le({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 m=Is(l.node);if(m)return De(m.code,m.message);let p=l.scope.getBinding(u.base);if(p?.path.isVariableDeclarator()){let h=Is(p.path.node.init);if(h)return De(h.code,h.message)}return p?.path.isVariableDeclarator()&&b.isCallExpression(p.path.node.init)?Sx("unsupported-expression",id(p.path.node.init,e.functionCallContracts)):De("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return d.kind==="external"?Ku(t,d):ks(t,u.expression,d)}async function yx(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return De("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=_s(r,n,o.conditionExpression);if(!l)return De("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await Le({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 De("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(u.kind==="external")return De("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let d=ks(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 xx(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 Ex(e){let t=await nd(e);if(t.length===0)return De("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(bx(e.expression))return td(t);if(od(e.expression))return De("unsupported-expression","i18n helpers require a static message id string");if(b.isMemberExpression(e.expression)&&e.expression.computed&&!b.isNumericLiteral(e.expression.property)&&!b.isStringLiteral(e.expression.property))return De("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return De(n.code,n.message)}function De(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function Sx(e,t){return td([{code:e,message:t}])}function td(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function bx(e){return b.isCallExpression(e)||b.isConditionalExpression(e)||b.isLogicalExpression(e)||b.isBinaryExpression(e)}function er(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 nd(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=Is(t);if(l)return[l];if(b.isCallExpression(t))return[{code:"unsupported-expression",message:id(t,c)}];if(b.isMemberExpression(t)&&t.computed){let u=t.property;if(!b.isNumericLiteral(u)&&!b.isStringLiteral(u)){if(!b.isExpression(u))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let m=await nt(u,n,r,o,i,s,a);if(typeof m!="string"&&!Number.isInteger(m))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}]}}return b.isBinaryExpression(t)?er([...await xs(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):b.isLogicalExpression(t)?er([...await xs(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"}]):b.isConditionalExpression(t)?er([...await xs(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 Is(e){return od(e)?$u("i18n helpers require a static message id string"):Rx(e)?$u("CMS helpers require static entry id and field path string arguments"):null}async function xs(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await nd({...t,expression:o}));return r}function Ix(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:[kx(e.sourceType)]}}async function Ms(e){for(let n of Tx){if(!Bu(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return Vu(Uu(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(!Bu(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return Vu(Uu(r),e.externalAdapters)}return null}function kx(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function vx(e){return{code:"external-source-readonly",message:e}}function $u(e){return{code:"unsupported-expression",message:e}}function Os(e){return!e||!b.isCallExpression(e)?null:b.isIdentifier(e.callee)?e.callee.name:b.isMemberExpression(e.callee)&&!e.callee.computed&&b.isIdentifier(e.callee.object)&&b.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function Bu(e,t){if(!t||t.length===0)return!0;let n=Os(e.node);return n?t.includes(n):!1}function Uu(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:er(e.diagnostics??[])}:{match:e,diagnostics:[]}}function Vu(e,t){let n=Ix(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:er([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function Cx(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!b.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!b.isStringLiteral(n)||!b.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 Rx(e){return!!e&&b.isCallExpression(e)&&b.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!b.isStringLiteral(e.arguments[0])||!b.isStringLiteral(e.arguments[1]))}function rd(e){if(!(!e||!b.isCallExpression(e))){if(b.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&b.isStringLiteral(t)?t.value:null}if(b.isMemberExpression(e.callee)&&!e.callee.computed&&b.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&b.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!b.isObjectExpression(t))return null;for(let n of t.properties)if(b.isObjectProperty(n)&&!n.computed&&(b.isIdentifier(n.key)&&n.key.name==="id"||b.isStringLiteral(n.key)&&n.key.value==="id")&&b.isStringLiteral(n.value))return n.value.value;return null}}}function od(e){return rd(e)===null}async function Px(e,t,n){let r=new Set,o=qn.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=qn.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"]:[qn.posix.join(i,"locales"),qn.posix.join(i,"messages")];for(let a of s){let c=qn.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function wx(e){let t=rd(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await Px(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function Ax(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!b.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!b.isExpression(n))return null;let o=await nt(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:[vx("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var Tx=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>Cx(e)},{helperNames:["apiField"],resolve:e=>Ax(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>wx({currentFile:e,expressionPath:t,exists:n})}];function Ku(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 ks(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=jx(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:!0}):n.sourceKind==="imported-binding"?c.push({kind:"imported-binding",file:n.file,displayName:n.root.kind==="named-export"?n.root.name:"default",canEditHere:!0}):n.sourceKind==="repeat-template"&&c.push({kind:"repeat-template",file:n.file,displayName:t,canEditHere:!0}),n.path.length>0&&n.sourceKind!=="repeat-template"&&c.push({kind:o?"array-item":"object-field",file:n.file,displayName:a,canEditHere:!0}),i&&c.push({kind:"config-entry",file:n.file,displayName:i.displayPath,canEditHere:!0}),{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:c,confidence:n.sourceKind==="repeat-template"?"safe-derived":"exact",editMode:n.editMode??(n.file===e?"direct":"proxy"),diagnostics:n.diagnostics??[]}}var Nx=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function Ds(e,t){let n=[...Nx,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function id(e,t){let n=e.callee;return b.isIdentifier(n)&&Ds(n.name,t)?.purity==="side-effect"?`Helper "${n.name}" is registered as side-effectful and remains readonly`:"Function calls are recognized but remain readonly until a pure-call strategy is registered"}async function Ls(e){let t=await Ms(e);if(t)return t;let n=await sd({...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 tt({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 Le({...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 Dx(e)}async function sd(e){let t=await qe({...e,allowComposed:!1});return t?.kind==="source"?t.provenance:null}async function qe(e){let t=Fx(e.expressionPath),n=Ox(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 tt({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 Le({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 tt({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 Le({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 qe({...e,expressionPath:r,allowComposed:!0}),a=await qe({...e,expressionPath:o,allowComposed:!1}),c=await qe({...e,expressionPath:i,allowComposed:!1});return Es(s,a,c)}if(t.isCallExpression())return _x({...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 qe({...e,expressionPath:r,allowComposed:!0}),s=await qe({...e,expressionPath:o,allowComposed:!0});return Es(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 qe({...e,expressionPath:r,allowComposed:!0}),s=await qe({...e,expressionPath:o,allowComposed:!0});return Es(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:qe({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function Fx(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 _x(e){let t=Os(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:qe({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(b.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:qe({...e,expressionPath:o,allowComposed:!1})}}return null}function Es(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!Mx(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function Mx(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 Ox(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function Dx(e){if(!e.expressionPath.isCallExpression())return null;let t=Os(e.expressionPath.node);if(!t)return null;let n=Ds(t,e.functionCallContracts);if(!n||n.purity!=="pure")return null;let r=n.sourceArgIndex??0,o=e.expressionPath.get(`arguments.${r}`);return!o||Array.isArray(o)||!o.isExpression()?null:await ad({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})}async function ad(e){let t=await Ms({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 tt({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 Le({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 Ls({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 Lx(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!b.isCallExpression(t))return null;let n=t.callee;if(!b.isIdentifier(n))return null;let r=Ds(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}`);return!s||Array.isArray(s)||!s.isExpression()?null:await ad({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})}function jx(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=xo(t,e.path);return{sourceId:o,displayPath:o}}async function $x(e){let t=e.segment.source;return t?Le({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 Le(e){let t=e.sourceInfo,n=cd(e.expressionPath,t.base);if(n){let l=await ld({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 E=Ux(n.callPath,[...n.basePath,...t.path]);return zn(E)?Lu(e.currentFile,E.sourceId,E.displayPath):null}let u=lE(l,[...n.basePath,...t.path]),d=l.collectionIndexMap?.[0]??0,m=[...l.pathPrefix??[],{kind:"index",index:d},...n.basePath,...t.path],p=[{kind:"index",index:0},...n.basePath,...t.path];return et(l.value,p)===void 0?null:{kind:"value",file:l.file,root:l.root,path:u?.[0]??m,sourceKind:"repeat-template",collectionIndexMap:l.collectionIndexMap,...u?{collectionPathMap:u}:{}}}let r=e.expressionPath.scope.getBinding(t.base);if(!r)return null;if(r.path.isImportNamespaceSpecifier()){let l=t.path[0],u=r.path.parentPath;if(!l||l.kind!=="property"||!u?.isImportDeclaration())return null;let d=await ln(e.currentFile,u.node.source.value,e.exists);if(!d)return null;let m=await yo({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(!m||m.kind==="external")return null;let p=t.path.slice(1);return et(m.value,p)===void 0?null:{kind:"value",file:m.file,root:m.root,path:p,sourceKind:"imported-binding",collectionIndexMap:m.collectionIndexMap}}let o=Ql(r);if(o){let l=o.expressionPath,u=await tt({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 Le({...e,expressionPath:l,sourceInfo:{...u,expression:xo(u.expression,t.path),path:[...u.path,...t.path]}});if(d)return d}if(t.path.length===0){let d=await sd({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 oE({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 Lx({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=io(r,t.path);if(zn(s))return Lu(e.currentFile,s.sourceId,s.displayPath);let a=await Zt({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:et(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}function cd(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=Ye(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!Bx(s,r)?null:{callPath:s,basePath:i}}function Bx(e,t){let n=e.node.callee;return!b.isMemberExpression(n)||!b.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}async function ld(e){let{currentFile:t,callPath:n,readFile:r,exists:o,fileCache:i,visited:s}=e,a=n.node.callee;if(!b.isMemberExpression(a)||!b.isIdentifier(a.property)||a.property.name!=="map")return null;let c=n.get("callee");if(!c.isMemberExpression())return null;let l=c.get("object");if(Array.isArray(l)||!l.isExpression())return null;let u=await rr({currentFile:t,expressionPath:l,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});return!u||!Array.isArray(u.value)||u.value.length===0?null:u}function Ux(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:ao(r,t)}async function rr(e){let{currentFile:t,expressionPath:n,readFile:r,exists:o,fileCache:i,visited:s}=e;if(n.isIdentifier()){let a=n.scope.getBinding(n.node.name);if(!a)return null;let c=await Zt({currentFile:t,binding:a,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});return c?.kind==="static"?c:null}if(n.isCallExpression())return ud({currentFile:t,callPath:n,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(n.isTSAsExpression()||n.isTSSatisfiesExpression()||n.isTSNonNullExpression()){let a=n.get("expression");if(!Array.isArray(a)&&a.isExpression())return rr({...e,expressionPath:a})}if(n.isArrayExpression()){let a=qu(n.node);if(!a)return null;let c=await nt(n.node,n.scope,t,r,o,i,s);return Array.isArray(c)?{kind:"static",file:t,root:{kind:"expression",sourceRange:a},value:c,sourceKind:"binding"}:null}if(n.isMemberExpression()){let a=await tt({expression:n.node,scope:n.scope,currentFile:t,readFile:r,exists:o,fileCache:i,visited:s});if(!a)return null;let c=await Le({currentFile:t,expressionPath:n,sourceInfo:a,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(!c||c.kind==="external")return null;let l=await Vx({currentFile:t,expressionPath:n,provenance:c,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(!l||l.kind!=="static")return null;if(c.collectionPathMap?.length){let d=uE(l.value,c.collectionPathMap);if(d)return{kind:"static",file:c.file,root:c.root,value:d.value,sourceKind:c.sourceKind,collectionPathMap:d.collectionPathMap}}let u=et(l.value,c.path);return Array.isArray(u)?{kind:"static",file:c.file,root:c.root,value:u,sourceKind:c.sourceKind,pathPrefix:c.path,collectionIndexMap:c.collectionIndexMap,collectionPathMap:c.collectionPathMap}:null}return null}async function Vx(e){let{provenance:t}=e;if(t.root.kind==="binding"){let i=e.expressionPath.scope.getBinding(t.root.name);if(!i&&t.file!==e.currentFile){let s=await _t(t.file,e.readFile,e.fileCache);i=s.ast?Rs(s.ast).getBinding(t.root.name):void 0}return i?await Zt({currentFile:t.file,binding:i,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}if(t.root.kind!=="expression")return null;let n=await _t(t.file,e.readFile,e.fileCache);if(!n.ast)return null;let r=fx(n.ast,t.root.sourceRange);if(!r)return null;let o=await nt(r.node,r.scope,t.file,e.readFile,e.exists,e.fileCache,e.visited);return o===void 0?null:{kind:"static",file:t.file,root:t.root,value:o,sourceKind:t.sourceKind}}async function ud(e){return await Kx(e)??await Jx(e)??await Xx(e)}async function Kx(e){let{callPath:t}=e,n=t.node.callee;if(!b.isMemberExpression(n)||!b.isIdentifier(n.property)||n.property.name!=="filter")return null;let r=t.get("callee");if(!r.isMemberExpression())return null;let o=r.get("object");if(Array.isArray(o)||!o.isExpression())return null;let i=await rr({currentFile:e.currentFile,expressionPath: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});if(!i||!Array.isArray(i.value))return null;let[s]=t.node.arguments;if(!b.isArrowFunctionExpression(s)&&!b.isFunctionExpression(s))return null;let a=s.params[0];if(!b.isIdentifier(a))return null;let c=zx(s);if(!c)return null;let l=[],u=[],d=[];for(let[m,p]of i.value.entries()){let h=Hx(c,a.name,p);if(typeof h!="boolean")return null;if(h){l.push(p),u.push(i.collectionIndexMap?.[m]??m);let E=i.collectionPathMap?.[m];E&&d.push(E)}}return{...i,value:l,pathPrefix:i.pathPrefix,collectionIndexMap:u,...d.length>0?{collectionPathMap:d}:{}}}async function Jx(e){let{callPath:t}=e,n=t.node.callee;if(!b.isMemberExpression(n)||!b.isIdentifier(n.property)||n.property.name!=="slice")return null;let r=t.get("callee");if(!r.isMemberExpression())return null;let o=r.get("object");if(Array.isArray(o)||!o.isExpression())return null;let i=await rr({currentFile:e.currentFile,expressionPath: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});if(!i||!Array.isArray(i.value))return null;let[s,a]=t.node.arguments,c=Ju(s,0),l=Ju(a,i.value.length);if(c===null||l===null)return null;let u=Math.max(0,c<0?i.value.length+c:c),d=Math.max(0,l<0?i.value.length+l:l),m=i.value.map((h,E)=>i.collectionIndexMap?.[E]??E).slice(u,d),p=i.collectionPathMap?.slice(u,d);return{...i,value:i.value.slice(u,d),pathPrefix:i.pathPrefix,collectionIndexMap:m,...p?{collectionPathMap:p}:{}}}function Ju(e,t){return e?b.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}async function Xx(e){let{callPath:t}=e,n=t.node.callee;if(!b.isMemberExpression(n)||!b.isIdentifier(n.property)||n.property.name!=="sort"&&n.property.name!=="toSorted")return null;let r=t.get("callee");if(!r.isMemberExpression())return null;let o=r.get("object");if(Array.isArray(o)||!o.isExpression())return null;let i=await rr({currentFile:e.currentFile,expressionPath: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});if(!i||!Array.isArray(i.value))return null;let[s]=t.node.arguments;if(!b.isArrowFunctionExpression(s)&&!b.isFunctionExpression(s))return null;let[a,c]=s.params;if(!b.isIdentifier(a)||!b.isIdentifier(c))return null;let l=i.value.map((d,m)=>({value:d,sourceIndex:i.collectionIndexMap?.[m]??m,originalIndex:m})),u=[...l];for(let d of l)for(let m of l)if(Xu(s,a.name,c.name,d.value,m.value)===void 0)return null;return u.sort((d,m)=>{let p=Xu(s,a.name,c.name,d.value,m.value)??0;return p===0?d.originalIndex-m.originalIndex:p}),{...i,value:u.map(d=>d.value),pathPrefix:i.pathPrefix,collectionIndexMap:u.map(d=>d.sourceIndex),...i.collectionPathMap?{collectionPathMap:u.map(d=>i.collectionPathMap?.[d.originalIndex]).filter(d=>!!d)}:{}}}function Xu(e,t,n,r,o){let i=b.isExpression(e.body)?e.body:e.body.body.find(a=>b.isReturnStatement(a))?.argument;if(!i||!b.isExpression(i))return;let s=vs(i,t,n,r,o);return typeof s=="number"?s:void 0}function vs(e,t,n,r,o){if(b.isNumericLiteral(e)||b.isStringLiteral(e)||b.isBooleanLiteral(e))return e.value;if(b.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(b.isMemberExpression(e)){let i=Cs(e,t);if(i)return et(r,i);let s=Cs(e,n);return s?et(o,s):void 0}if(b.isBinaryExpression(e)&&e.operator==="-"){let i=b.isExpression(e.left)?vs(e.left,t,n,r,o):void 0,s=b.isExpression(e.right)?vs(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function zx(e){if(b.isExpression(e.body))return e.body;for(let t of e.body.body)if(b.isReturnStatement(t)&&t.argument&&b.isExpression(t.argument))return t.argument;return null}function Hx(e,t,n){let r=Yt(e,t,n);return typeof r=="boolean"?r:void 0}function Yt(e,t,n){if(b.isStringLiteral(e)||b.isNumericLiteral(e)||b.isBooleanLiteral(e))return e.value;if(b.isNullLiteral(e))return null;if(b.isIdentifier(e))return e.name===t?n:void 0;if(b.isMemberExpression(e)){let r=Cs(e,t);return r?et(n,r):void 0}if(b.isUnaryExpression(e)&&e.operator==="!"){let r=Yt(e.argument,t,n);return r===void 0?void 0:!r}if(b.isLogicalExpression(e)){let r=Yt(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&Yt(e.right,t,n);if(e.operator==="||")return r||Yt(e.right,t,n)}if(b.isBinaryExpression(e)){let r=b.isExpression(e.left)?Yt(e.left,t,n):void 0,o=b.isExpression(e.right)?Yt(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 Cs(e,t){let n=[],r=e;for(;b.isMemberExpression(r);){if(r.computed)if(b.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(b.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!b.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!b.isIdentifier(r)||r.name!==t?null:n}async function Zt(e){let{currentFile:t,binding:n,readFile:r,exists:o,fileCache:i,visited:s}=e,a=`${t}::${n.kind}::${n.identifier.name}`;if(s.has(a))return null;s.add(a);try{let c=await Wx({currentFile:t,binding:n,readFile:r,exists:o,fileCache:i,visited:s});if(c)return c;if(n.path.isImportSpecifier()||n.path.isImportDefaultSpecifier())return await aE({currentFile:t,binding:n,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,fileCache:i,visited:s});if(n.kind==="param")return null;if(n.path.isVariableDeclarator()){let l=n.path.node.init;if(!l||!b.isExpression(l))return null;let u=n.path.get("init");if(u&&!Array.isArray(u)&&u.isExpression()){let m=await Ms({currentFile:t,expressionPath:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(m)return m;if(u.isCallExpression()){let p=await ud({currentFile:t,callPath:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(p)return p}}let d=await nt(l,n.path.scope,t,r,o,i,s);return d===void 0?null:{kind:"static",file:t,root:{kind:"binding",name:n.identifier.name},value:d,sourceKind:"binding"}}if(n.path.isIdentifier()&&n.path.parentPath?.isExportDefaultDeclaration()){let l=n.path.parentPath.node.declaration;if(!b.isExpression(l))return null;let u=await nt(l,n.path.scope,t,r,o,i,s);return u===void 0?null:{kind:"static",file:t,root:{kind:"binding",name:n.identifier.name},value:u,sourceKind:"binding"}}return null}finally{s.delete(a)}}async function Wx(e){let{currentFile:t,binding:n,readFile:r,exists:o,fileCache:i,visited:s}=e;if(!n.path.isVariableDeclarator()||!n.path.get("id").isArrayPattern())return null;let a=n.path,c=a.node.init;if(!c||!b.isCallExpression(c))return null;let l=Gx(c);if(!l||!b.isArrayPattern(a.node.id)||a.node.id.elements.findIndex(h=>b.isIdentifier(h)&&h.name===n.identifier.name)!==0)return null;let d=l==="useReducer"?1:0,m=c.arguments[d];if(!m||!b.isExpression(m))return null;let p=await nt(m,a.scope,t,r,o,i,s);return p===void 0?null:{kind:"static",file:t,root:{kind:"hook-state",name:n.identifier.name,hook:l},value:p,sourceKind:"binding"}}function Gx(e){return b.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:b.isMemberExpression(e.callee)&&b.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function Yx(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()||!b.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 Zx(e,t){let n=Yx(e.path);if(!n)return null;let r=vn(e,t);return r?{...n,...r}:null}function xo(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function Qx(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}async function qx(e){let t=tE(e.expressionPath.node);if(!t||!nE(t.segments))return null;let n=await Le({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 eE({...e,rootPath:n.path,segments:t.segments});return r?{...n,path:r.collectionPathMap[0]??n.path,sourceKind:"repeat-template",displayExpression:nr(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:r.collectionPathMap}:null}async function eE(e){let t=null,n,r=[];for(let i of e.segments){if(i.kind!=="dynamic")continue;let s=await tt({expression:i.expression,scope:e.expressionPath.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(!s)return null;let a=cd(e.expressionPath,s.base);if(!a)return null;let c=await ld({currentFile:e.currentFile,callPath:a.callPath,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(!c||!Array.isArray(c.value))return null;let l=c.value.map((u,d)=>{let m=et(c.value,[{kind:"index",index:d},...a.basePath,...s.path]);return rE(m)});if(l.some(u=>u===null)||t!==null&&t!==l.length)return null;t=l.length,n??=c.collectionIndexMap,r.push(l)}if(t===null||t===0)return null;let o=[];for(let i=0;i<t;i+=1){let s=[...e.rootPath],a=0;for(let c of e.segments){if(c.kind==="dynamic"){let l=r[a]?.[i];if(!l)return null;s.push(l),a+=1;continue}s.push({...c})}o.push(s)}return{...n?{collectionIndexMap:n}:{},collectionPathMap:o}}function tE(e){let t=[],n=e;for(;b.isMemberExpression(n)||b.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(b.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(b.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(b.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(b.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return b.isIdentifier(n)?{base:n.name,segments:t}:null}function nE(e){return e.some(t=>t.kind==="dynamic")}function rE(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}async function oE(e){let t=Zx(e.binding,e.sourceInfo);if(!t||!e.graph)return null;let n=[...e.graph.elements.values()].filter(l=>Qx(l,e.currentFile,t.componentName,t.exportName));if(n.length!==1)return null;let r=n[0],o=r.attributes?.find(l=>l.name===t.propName);if(o&&!o.source){let l=await iE({caller:r,propName:t.propName,remainingPath:t.remainingPath,readFile:e.readFile,fileCache:e.fileCache});if(l)return Ss(l,{componentName:t.componentName,propName:t.propName,file:r.sourceFile})}if(!o?.source){let l=await sE({caller:r,propName:t.propName,remainingPath:t.remainingPath,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(l)return Ss(l,{componentName:t.componentName,propName:t.propName,file:r.sourceFile});let u=eu(e.binding,t.componentName,t.propName);if(!u||u.propName!==t.propName)return null;let d=await nt(u.expressionPath.node,u.expressionPath.scope,e.currentFile,e.readFile,e.exists,e.fileCache,e.visited);if(d===void 0)return null;let m=t.remainingPath;return m.length>0&&et(d,m)===void 0?null:{kind:"value",file:e.currentFile,root:{kind:"binding",name:t.propName},path:m,sourceKind:"binding",semanticKind:"component-prop",displayExpression:u.displayPath,chainPrefix:[{kind:"component-prop",file:e.currentFile,displayName:u.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let i=await _t(r.sourceFile,e.readFile,e.fileCache);if(!i.ast)return null;let s=ed(i.ast,i.source,o.source.expression,o.sourceRange)??_s(i.ast,i.source,o.source.expression);if(!s)return null;let a={...o.source,expression:xo(o.source.expression,t.remainingPath),path:[...o.source.path,...t.remainingPath]},c=await Le({currentFile:r.sourceFile,expressionPath:s,sourceInfo:a,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 c?Ss(c.kind==="external"?c:{...c,displayExpression:a.expression},{componentName:t.componentName,propName:t.propName,file:r.sourceFile}):null}async function iE(e){let t=await _t(e.caller.sourceFile,e.readFile,e.fileCache);if(!t.ast)return null;let n=Qu(t.ast,e.caller.sourceRange);if(!n)return null;let r=n.get("openingElement").get("attributes").find(a=>a.isJSXAttribute()&&a.node.name.type==="JSXIdentifier"&&a.node.name.name===e.propName);if(!r?.isJSXAttribute())return null;let o=r.get("value"),i=o.isStringLiteral()?o:o.isJSXExpressionContainer()?o.get("expression"):null;if(!i?.isExpression())return null;let s=qu(i.node);return s?{kind:"value",file:e.caller.sourceFile,root:{kind:"expression",sourceRange:s},path:e.remainingPath,sourceKind:"binding",semanticKind:"component-prop",displayExpression:e.propName,editMode:"upstream",diagnostics:[]}:null}async function sE(e){let t=await _t(e.caller.sourceFile,e.readFile,e.fileCache);if(!t.ast)return null;let n=Qu(t.ast,e.caller.sourceRange);if(!n)return null;let r=n.get("openingElement");for(let o of r.get("attributes")){if(!o.isJSXSpreadAttribute())continue;let i=o.get("argument");if(!i.isExpression())continue;let s=await tt({expression:i.node,scope:i.scope,source:t.source,currentFile:e.caller.sourceFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(!s)continue;let a=[{kind:"property",name:e.propName},...e.remainingPath],c={...s,expression:xo(s.expression,a),path:[...s.path,...a]},l=await Le({currentFile:e.caller.sourceFile,expressionPath:i,sourceInfo:c,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(l)return l.kind==="external"?l:{...l,displayExpression:c.expression}}return null}function Ss(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"}}async function aE(e){let{currentFile:t,binding:n,readFile:r,exists:o,fileCache:i,visited:s}=e,a=n.path.parentPath;if(!a||!a.isImportDeclaration())return null;let c=a.node.source.value;if(typeof c!="string")return null;let l=await ln(t,c,o);if(!l)return null;if(n.path.isImportDefaultSpecifier()){let E=await _t(l,r,i),C=E.ast?Ps(E.ast,"default"):null,v=await yo({file:l,exportName:"default",readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});return!v||v.kind!=="static"?null:{kind:"static",file:C?.kind==="default-expression"?v.file:l,root:C?.kind==="default-expression"?v.root:{kind:"default-export"},value:v.value,sourceKind:"imported-binding"}}if(!n.path.isImportSpecifier())return null;let u=n.path.node.imported,d=b.isIdentifier(u)?u.name:u.value,m=await _t(l,r,i),p=m.ast?Ps(m.ast,d):null,h=await yo({file:l,exportName:d,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});return h?h.kind==="external"?h:{kind:"static",file:p?.kind==="re-export"?h.file:l,root:p?.kind==="re-export"?h.root:{kind:"named-export",name:d},value:h.value,sourceKind:"imported-binding"}:null}async function yo(e){let{file:t,exportName:n,readFile:r,exists:o,fileCache:i,visited:s}=e,a=`export::${t}::${n}`;if(!s.has(a)){s.add(a);try{let c=await _t(t,r,i);if(!c.ast)return;let l=Ps(c.ast,n);if(!l)return;if(l.kind==="default-expression"){let p=l.expression;if(!p||!b.isIdentifier(p))return;let h=Rs(c.ast).getBinding(p.name);return h?await Zt({currentFile:t,binding:h,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s})??void 0:void 0}if(l.kind==="re-export"){if(!l.source||!l.name)return;let p=await ln(t,l.source,o);return p?yo({...e,file:p,exportName:l.name}):void 0}let u=l.name;if(!u)return;let d=Rs(c.ast).getBinding(u);return d?await Zt({currentFile:t,binding:d,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s})??void 0:void 0}finally{s.delete(a)}}}function Rs(e){let t=null;if(Hu(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}function Ps(e,t){for(let n of e.program.body){if(t==="default"&&b.isExportDefaultDeclaration(n))return b.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:(b.isFunctionDeclaration(n.declaration)||b.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if(b.isExportNamedDeclaration(n)){if(n.declaration){if(b.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if(b.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if((b.isFunctionDeclaration(n.declaration)||b.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if((b.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&b.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}async function nt(e,t,n,r,o,i,s){if(b.isStringLiteral(e)||b.isNumericLiteral(e)||b.isBooleanLiteral(e))return e.value;if(b.isNullLiteral(e))return null;if(b.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(b.isTSAsExpression(e)||b.isTSSatisfiesExpression(e)||b.isTSNonNullExpression(e))return await nt(e.expression,t,n,r,o,i,s);if(b.isIdentifier(e)){let a=t.getBinding(e.name);if(!a)return;let c=await Zt({currentFile:n,binding:a,readFile:r,exists:o,fileCache:i,visited:s});return c?.kind==="static"?c.value:void 0}if(b.isArrayExpression(e)){let a=[];for(let c of e.elements){if(!c||b.isSpreadElement(c))return;let l=await bs(c,t,n,r,o,i,s);if(l===void 0)return;a.push(l)}return a}if(b.isObjectExpression(e)){let a={};for(let c of e.properties){if(!b.isObjectProperty(c)||c.computed)return;let l=null;if(b.isIdentifier(c.key)?l=c.key.name:b.isStringLiteral(c.key)&&(l=c.key.value),!l)return;if(c.shorthand){if(!b.isIdentifier(c.value))return;let d=await bs(c.value,t,n,r,o,i,s);if(d===void 0)return;a[l]=d;continue}if(!b.isExpression(c.value))return;let u=await bs(c.value,t,n,r,o,i,s);u!==void 0&&(a[l]=u)}return a}if(b.isMemberExpression(e)){let a=await dd(e,t,n,r,o,i,s);if(!a)return;let c=t.getBinding(a.base);if(!c)return;let l=await Zt({currentFile:n,binding:c,readFile:r,exists:o,fileCache:i,visited:s});return!l||l.kind!=="static"?void 0:et(l.value,a.path)}}async function bs(e,t,n,r,o,i,s){if(!b.isSpreadElement(e))return await nt(e,t,n,r,o,i,s)}async function dd(e,t,n,r,o,i,s){if(b.isIdentifier(e))return{base:e.name,path:[]};if(!b.isMemberExpression(e))return null;let a=[],c=e;for(;b.isMemberExpression(c);){if(c.computed){let l=c.property;if(b.isNumericLiteral(l))a.unshift({kind:"index",index:l.value});else if(b.isStringLiteral(l))a.unshift({kind:"property",name:l.value});else{let u=b.isExpression(l)?await nt(l,t,n,r,o,i,s):void 0;if(typeof u=="string")a.unshift({kind:"property",name:u});else if(Number.isInteger(u))a.unshift({kind:"index",index:u});else return null}}else{if(!b.isIdentifier(c.property))return null;a.unshift({kind:"property",name:c.property.name})}c=c.object}return b.isIdentifier(c)?{base:c.name,path:a}:null}function cE(e){if(b.isIdentifier(e))return{base:e.name,path:[]};if(!b.isMemberExpression(e))return null;let t=[],n=e;for(;b.isMemberExpression(n);){if(n.computed)if(b.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(b.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!b.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return b.isIdentifier(n)?{base:n.name,path:t}:null}function et(e,t){let n=e;for(let r of t){if(r.kind==="property"){if(n===null||Array.isArray(n)||typeof n!="object"||!(r.name in n))return;n=n[r.name];continue}if(!Array.isArray(n)||r.index<0||r.index>=n.length)return;n=n[r.index]}return n}function lE(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 uE(e,t){let n=[],r=[];for(let o of t){let i=et(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}}async function _t(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=Zu(o),s={source:o,ast:i};return n.set(e,s),s}import Vs from"@babel/generator";import{parse as kE}from"@babel/parser";import Ks from"@babel/traverse";import*as k from"@babel/types";import*as hd from"@babel/types";import js from"@babel/generator";import*as ae from"@babel/types";var dE=typeof js=="function"?js:js.default,fE=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,pE=/^((?:https?:)?\/\/)[^/@\s]+@/i,mE=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function pd(e,t){let n=lt(e.callee);if(!n)return null;if(n==="fetch")return $s(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(fd(r))return $s(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(fd(r))return $s(e.arguments[0],r,t,["ky client contract"])}return null}function $s(e,t,n,r){if(!e||ae.isSpreadElement(e)||ae.isJSXNamespacedName(e))return xE(t,n,r,"missing url argument");let o=or(e);return{sourceKind:yE(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 or(e){if(ae.isStringLiteral(e))return Eo(e.value);if(ae.isTemplateLiteral(e))return Eo(hE(e));if(ae.isBinaryExpression(e)&&e.operator==="+"){let t=or(e.left),n=or(e.right);return!t&&!n?void 0:Eo(`${t??Bs(e.left)}${n??Bs(e.right)}`)}if(ae.isMemberExpression(e)){let t=md(e);if(t)return`env:${t}`}if(!(ae.isCallExpression(e)&<(e.callee)==="new URL")){if(ae.isNewExpression(e)&&ae.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!ae.isSpreadElement(t)?or(t):void 0,o=n&&!ae.isSpreadElement(n)?or(n):void 0;return o&&r?Eo(`${o} + ${r}`):r??o}if(ae.isIdentifier(e))return`:${e.name}`}}function hE(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+=Bs(r))}return t}function Bs(e){if(ae.isIdentifier(e))return`:${e.name}`;if(ae.isMemberExpression(e)){let t=md(e);if(t)return`env:${t}`}return`:${gE(e)}`}function gE(e){return dE(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function Eo(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(pE,"$1<redacted>@").replace(mE,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?fE.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function yE(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 xE(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function fd(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function md(e){return!ae.isMemberExpression(e.object)||!ae.isIdentifier(e.object.object,{name:"process"})||!EE(e.object.property,"env")?null:ae.isIdentifier(e.property)?e.property.name:ae.isStringLiteral(e.property)?e.property.value:null}function EE(e,t){return ae.isIdentifier(e)&&e.name===t}function lt(e){if(ae.isIdentifier(e))return e.name;if(ae.isMemberExpression(e)){let t=lt(e.object),n=ae.isIdentifier(e.property)?e.property.name:ae.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var SE=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),bE=new Set(["getConfig","submit"]);function gd(e,t){let n=IE(lt(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!SE.has(i))return null;let s=Us(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(!bE.has(i))return null;let s=Us(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=Us(e,0)??"/cms/:path";return{sourceKind:"vcp-cms-collection",sourceType:"cms-field",operation:n,endpointPattern:i,confidence:i==="/cms/:path"?"partial":"safe-derived",evidence:[{file:t.file,symbol:n,reason:"VCP CMS fetch helper"}]}}return null}function IE(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 yd(e,t){let n=lt(e);return n==="cms.settings"?{sourceKind:"vcp-cms-settings",sourceType:"cms-field",operation:"settings",endpointPattern:"/settings",confidence:"exact",evidence:[{file:t.file,symbol:n,reason:"VCP CMS settings facade"}]}:n==="cms.navigation"?{sourceKind:"vcp-cms-navigation",sourceType:"cms-field",operation:"navigation",endpointPattern:"/navigation",confidence:"exact",evidence:[{file:t.file,symbol:n,reason:"VCP CMS navigation facade"}]}:null}function xd(e){let t=lt(e.callee);return typeof t=="string"&&t.startsWith("cms.field.")}function Us(e,t){let n=e.arguments[t];return hd.isStringLiteral(n)?n.value:null}var zs=typeof Ks=="function"?Ks:Ks.default,nP=typeof Vs=="function"?Vs:Vs.default,vE={maxFunctionDepth:8,maxImportDepth:6},CE=new Set(["src","href","alt","poster","content","title","aria-label"]);async function vd(e){let t=e.fileCache??new Map,n=Ys(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...vE,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:jd(n,e.element.componentName)};await Cd(e.element.componentName,e.graph,r);let o=[];o.push(...await TE(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await NE(s,e.element,e.graph,r);a&&o.push(Xs(a,"text","children"))}for(let s of e.element.attributes??[]){let a=AE(s);if(!a)continue;let c=await wd(s.source,e.element,e.graph,r);c&&o.push(Xs(c,a,s.name))}let i=zE(o).sort(Dd);return{hasDynamicData:i.length>0,bindings:i}}async function Cd(e,t,n){if(n.importDepth>=n.options.maxImportDepth)return;let r=n.analysis.functions.get(e)??n.analysis.functions.get("default"),o=r?.params[0];if(!r||!o)return;let i=n.analysis.functions.get("default")===r?"default":e,s=[];for(let l of t.elements.values()){if(l.sourceFile===n.file&&l.tag===e){s.push(l);continue}!l.importedFrom||!l.exportName||l.importedFrom===n.file&&l.exportName!==i||(l.importedFrom===n.file||await Rd(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 Pd(l.sourceFile,n);if(!d)continue;let m=Io(d,n,{importDepth:n.importDepth+1});m.paramSources.clear(),m.scopeVariables=jd(d,l.componentName),await Cd(l.componentName,t,m);let p=await RE(l,m);for(let[h,E]of p){if(!E)continue;let C=a.get(h)??[];C.push(E),a.set(h,C)}}finally{n.resolvingComponentProps.delete(u)}}}let c=new Map;for(let[l,u]of a){let d=Md(u);d.length===1&&c.set(l,d[0])}wE(o,c,n)}async function Rd(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 Pd(e,r))?.imports.get(t);if(!s||!st(s.source))return!1;let a=await Ud(e,s.source,r.exists);return a?a===n?!0:Rd(a,s.importedName,n,r,o):!1}async function RE(e,t){let n=new Map;zs(t.analysis.ast,{JSXElement(o){if(PE(o.node,e.sourceRange)){for(let i of o.node.openingElement.attributes)!k.isJSXAttribute(i)||!k.isJSXIdentifier(i.name)||!k.isJSXExpressionContainer(i.value)||!k.isExpression(i.value.expression)||n.set(i.name.name,i.value.expression);o.stop()}}});let r=new Map;for(let[o,i]of n){let s=await ke(i,t);s&&r.set(o,s)}return r}function PE(e,t){return e.loc?.start.line===t.startLine&&e.loc.start.column===t.startColumn&&e.loc.end.line===t.endLine&&e.loc.end.column===t.endColumn}async function Pd(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 Ys(e,r,t.fileCache)}function wE(e,t,n){if(k.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,Gs(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,Ce(o))}}function AE(e){return e.name==="dangerouslySetInnerHTML"?"richtext":CE.has(e.name)?"attribute":null}async function TE(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 Hs(i.collectionSource,n);s&&r.push(Xs(wn(s),"repeat-region",i.collectionExpression))}return r}async function NE(e,t,n,r){return wd(e.source,t,n,r)}async function wd(e,t,n,r){let o=await FE(e,t,n,r);return o||Hs(e,r)}async function FE(e,t,n,r){if(!e)return null;let o=_E(e.base,t,n);if(!o)return null;let i=await Hs(o.collectionSource,r);return i?cr(i,e.path,!0):null}function _E(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 Hs(e,t){if(!e)return null;let n=await Ad(e.base,t);return n?cr(n,e.path,!1):null}async function Ad(e,t){let n=t.paramSources.get(e);if(n)return Ce(n);if(t.variableCache.has(e))return HE(t.variableCache.get(e)??null);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let r=await ME(e,t);if(r)return t.variableCache.set(e,Ce(r)),t.resolvingVariables.delete(e),r;let o=t.scopeVariables?.get(e)??t.analysis.variables.get(e);if(o){let s=await ke(o,t);return t.variableCache.set(e,s?Ce(s):null),t.resolvingVariables.delete(e),s}let i=t.analysis.imports.get(e);if(i&&t.importDepth<t.options.maxImportDepth){let s=await $d(i,t);if(s){let a=Io(s,t,{importDepth:t.importDepth+1}),c=Bd(i,s);if(c){let d=(await Qt(c,[],a)).returnSource;return t.variableCache.set(e,d?Ce(d):null),t.resolvingVariables.delete(e),d}let l=s.variables.get(i.importedName);if(l){let u=await ke(l,a);return t.variableCache.set(e,u?Ce(u):null),t.resolvingVariables.delete(e),u}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}async function ME(e,t){let n=t.analysis.stateSetters.get(e);if(!n)return null;let r=[];zs(t.analysis.ast,{CallExpression(o){if(k.isIdentifier(o.node.callee,{name:n})){let i=o.node.arguments[0];k.isExpression(i)&&r.push(i);return}o.node.arguments.some(i=>k.isIdentifier(i)&&i.name===n)&&r.push(o.node)}});for(let o of r){let i=await ke(o,t);if(i)return i}return null}async function ke(e,t){if(k.isIdentifier(e))return Ad(e.name,t);if(k.isMemberExpression(e)||k.isOptionalMemberExpression(e)){let n=k.isMemberExpression(e)?yd(e,{file:t.file}):null;if(n)return _d(n);let r=await OE(e,t);if(!r)return null;let o=JE(e);return cr(r,o,!1)}if(k.isAwaitExpression(e))return k.isExpression(e.argument)?ke(e.argument,t):null;if(k.isCallExpression(e))return Td(e,t);if(k.isObjectExpression(e)){let n=await Nd(e,t);return Object.keys(n).length>0?Gs(n,t.file):null}if(k.isConditionalExpression(e)){let n=await ke(e.consequent,t),r=await ke(e.alternate,t);return ar(Sd(n,r))}if(k.isLogicalExpression(e)){let n=await ke(e.left,t),r=await ke(e.right,t);return ar(Sd(n,r))}return k.isTSAsExpression(e)||k.isTSSatisfiesExpression(e)||k.isTSNonNullExpression(e)||k.isTypeCastExpression(e)||k.isParenthesizedExpression(e)?ke(e.expression,t):null}async function OE(e,t){let n=e;for(;k.isMemberExpression(n)||k.isOptionalMemberExpression(n);)n=n.object;return k.isExpression(n)?ke(n,t):null}async function Td(e,t){let n=gd(e,{file:t.file,imports:t.analysis.imports});if(n)return _d(n);if(xd(e)){let d=e.arguments[0];if(d&&k.isExpression(d))return ar(await ke(d,t))}let r=await DE(e,t);if(r)return r;let o=pd(e,{file:t.file});if(o)return{sourceKind:o.sourceKind,sourceType:"api-field",endpointPattern:o.endpointPattern,valuePath:o.valuePath,confidence:o.confidence,readonly:!0,evidence:o.evidence};let i=await $E(e,t);if(i)return i;let s=await BE(e,t);if(s)return s;let a=await UE(e,t);if(a)return a;let c=await VE(e,t);if(c)return c;let l=[];for(let d of e.arguments)if(k.isExpression(d)){let m=await ke(d,t);m&&l.push(m)}let u=Md(l);return u.length===1?ar(u[0]):null}async function DE(e,t){let n=lt(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=jE(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(k.isIdentifier(s)){let a=await sr(s.name,t);if(a)return(await Qt(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!k.isObjectExpression(r))return So(t.file,`${n} without static options`);let o=LE(r,"queryFn");if(!o)return So(t.file,`${n} without queryFn`);if(k.isIdentifier(o)){let i=await sr(o.name,t);return i?(await Qt(i.node,[],i.context)).returnSource:So(t.file,`${n} queryFn unresolved`)}return k.isArrowFunctionExpression(o)||k.isFunctionExpression(o)?(await Qt(o,[],t)).returnSource:k.isCallExpression(o)?Td(o,t):null}function LE(e,t){for(let n of e.properties){if(!k.isObjectProperty(n)||!k.isExpression(n.value))continue;if(Fd(n)===t)return n.value}return null}function jE(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 $E(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 ke(e.callee.object,t):null;if(!r)return null;if(n!=="map")return wn(r);let o=e.arguments[0];if(k.isIdentifier(o)){let i=await sr(o.name,t);if(!i)return wn(r);let s=await Qt(i.node,[r],i.context);return{...wn(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(k.isArrowFunctionExpression(o)||k.isFunctionExpression(o)){let i=await Qt(o,[r],t);return{...wn(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return wn(r)}async function BE(e,t){return!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property,{name:"json"})||!k.isExpression(e.callee.object)?null:ke(e.callee.object,t)}async function UE(e,t){return!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property,{name:"then"})||!k.isExpression(e.callee.object)?null:ar(await ke(e.callee.object,t))}async function VE(e,t){if(!k.isIdentifier(e.callee))return null;let n=await sr(e.callee.name,t);if(!n)return null;let r=[];for(let i of e.arguments){if(!k.isExpression(i)){r.push(So(t.file,`unsupported argument for ${e.callee.name}`));continue}let s=await ke(i,t);r.push(s)}return(await Qt(n.node,r,n.context)).returnSource}async function sr(e,t){let n=t.analysis.functions.get(e);if(n)return{node:n,context:t};let r=t.analysis.imports.get(e);if(!r||t.importDepth>=t.options.maxImportDepth)return null;let o=await $d(r,t);if(!o)return null;let i=Io(o,t,{importDepth:t.importDepth+1}),s=Bd(r,o);return s?{node:s,context:i}:sr(r.importedName,i)}async function Qt(e,t,n){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let r=Io(n.analysis,n,{functionDepth:n.functionDepth+1});r.scopeVariables=n.analysis.functionVariables.get(e),e.params.forEach((c,l)=>{let u=t[l];u&&Js(c,XE(u),r)});let o=KE(e),i=null,s,a=!1;for(let c of o){if(k.isObjectExpression(c)){s={...s??{},...await Nd(c,r)},i=i??Gs(s,n.file);continue}let l=await ke(c,r);if(l){if(!i){i=l;continue}let u=Ws(i,l);if(!u){a=!0,i=null;continue}i=u}}return{returnSource:a?null:i,...s?{objectReturnMap:s}:{}}}function Js(e,t,n){if(k.isIdentifier(e)){n.paramSources.set(e.name,Ce(t));return}if(k.isAssignmentPattern(e)){Js(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=cr(t,[{kind:"property",name:r.key.name}],!0),i=k.isAssignmentPattern(r.value)?r.value.left:r.value;Js(i,o,n)}}function KE(e){if(k.isArrowFunctionExpression(e)&&k.isExpression(e.body))return[e.body];let t=[],n=e.body;if(!k.isBlockStatement(n))return t;let r=o=>{if(k.isFunction(o)&&o!==e)return;if(k.isReturnStatement(o)){o.argument&&k.isExpression(o.argument)&&t.push(o.argument);return}let i=k.VISITOR_KEYS[o.type];for(let s of i??[]){let a=o[s];if(Array.isArray(a))for(let c of a)k.isNode(c)&&r(c);else k.isNode(a)&&r(a)}};return r(n),t}async function Nd(e,t){let n={};for(let r of e.properties){if(!k.isObjectProperty(r))continue;let o=Fd(r);if(!o||!k.isExpression(r.value))continue;let i=await ke(r.value,t);i&&(n[o]=i)}return n}function Fd(e){return k.isIdentifier(e.key)&&!e.computed?e.key.name:k.isStringLiteral(e.key)?e.key.value:null}function JE(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 cr(e,t,n){if(t.length===0)return Ce(e);let r=t[0];if(r?.kind==="property"&&e.fieldMap?.[r.name])return cr(e.fieldMap[r.name],t.slice(1),n);let o=Ce(e);if(o.sourceType==="cms-field"){let i=t.filter(s=>s.kind==="property").map(s=>s.name);return i[0]==="data"&&i[1]==="items"?(o.valuePath=ir(o.valuePath,"data.items[]"),o.cmsFieldRoot=!1,o):i[0]==="fields"?(o.fieldPath=ir(o.fieldPath,i.slice(1).join(".")),o.cmsFieldRoot=!0,o):o.cmsFieldRoot||n||o.fieldMap?(o.fieldPath=ir(o.fieldPath,i.join(".")),o):(o.valuePath=ir(o.valuePath,Ed(t)),o)}return o.valuePath=ir(o.valuePath,Ed(t)),o}function Ed(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function ir(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function _d(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 wn(e){let t=Ce(e);return t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function XE(e){let t=Ce(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&(t.cmsFieldRoot=!1),t}function ar(e){return e?{...Ce(e),confidence:e.confidence==="unknown"?"unknown":"safe-derived",evidence:[...e.evidence,{file:e.evidence[0]?.file??"unknown",reason:"safe derived expression"}]}:null}function Sd(e,t){return e?t?Ws(e,t):Ce(e):t?Ce(t):null}function Ws(e,t){if(bo(e)!==bo(t))return null;let n=Ld(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function Md(e){let t=new Map;for(let n of e){let r=bo(n),o=t.get(r);t.set(r,o?Ws(o,n):Ce(n))}return[...t.values()]}function bo(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,bo(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 Gs(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 So(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 Od(e){let t=[...e].sort(Dd),n=t[0];return{hasDynamicData:t.length>0,sourceKinds:[...new Set(t.map(r=>r.sourceKind))],...n?.endpointPattern?{primaryEndpoint:n.endpointPattern}:{},...n?.collection?{primaryCollection:n.collection}:{},...n?.fieldPath?{primaryFieldPath:n.fieldPath}:{}}}function zE(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 Dd(e,t){return bd(e.targetKind)-bd(t.targetKind)||Ld(e.confidence,t.confidence)||Id(e.sourceKind)-Id(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function bd(e){return{"repeat-region":0,text:1,richtext:2,attribute:3,"component-prop":4}[e]}function Id(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function Ld(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function Ys(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=kE(t,{sourceType:"module",plugins:["jsx","typescript"]}),i={file:e,source:t,ast:o,variables:new Map,functions:new Map,imports:new Map,stateSetters:new Map,functionVariables:new WeakMap};return zs(o,{ImportDeclaration(s){let a=s.node.source.value;for(let c of s.node.specifiers)k.isImportSpecifier(c)&&k.isIdentifier(c.local)?i.imports.set(c.local.name,{source:a,importedName:k.isIdentifier(c.imported)?c.imported.name:c.imported.value,localName:c.local.name,isDefault:!1}):k.isImportDefaultSpecifier(c)&&i.imports.set(c.local.name,{source:a,importedName:"default",localName:c.local.name,isDefault:!0})},FunctionDeclaration(s){s.node.id?.name&&i.functions.set(s.node.id.name,s.node)},VariableDeclarator(s){let a=s.getFunctionParent(),c=a&&(k.isFunctionDeclaration(a.node)||k.isFunctionExpression(a.node)||k.isArrowFunctionExpression(a.node))?a.node:null,l=c?i.functionVariables.get(c)??new Map:i.variables;c&&!i.functionVariables.has(c)&&i.functionVariables.set(c,l);for(let u of An(s.node.id))l.set(u,k.isExpression(s.node.init)?s.node.init:null);if(k.isArrayPattern(s.node.id)&&k.isCallExpression(s.node.init)&<(s.node.init.callee)==="useState"){let[u,d]=s.node.id.elements;k.isIdentifier(u)&&k.isIdentifier(d)&&i.stateSetters.set(u.name,d.name)}k.isIdentifier(s.node.id)&&kd(s.node.init)&&i.functions.set(s.node.id.name,s.node.init)},ExportNamedDeclaration(s){let a=s.node.declaration,c=s.node.source?.value;if(c)for(let l of s.node.specifiers){if(!k.isExportSpecifier(l))continue;let u=k.isIdentifier(l.exported)?l.exported.name:l.exported.value,d=l.local.name;i.imports.set(u,{source:c,importedName:d,localName:u,isDefault:d==="default"})}if(k.isFunctionDeclaration(a)&&a.id?.name&&i.functions.set(a.id.name,a),k.isVariableDeclaration(a))for(let l of a.declarations)k.isIdentifier(l.id)&&kd(l.init)&&i.functions.set(l.id.name,l.init)},ExportDefaultDeclaration(s){let a=s.node.declaration;if((k.isFunctionDeclaration(a)||k.isFunctionExpression(a)||k.isArrowFunctionExpression(a))&&i.functions.set("default",a),k.isIdentifier(a)){let c=i.functions.get(a.name);c&&i.functions.set("default",c)}}}),n.set(e,i),i}function An(e){return!e||k.isVoidPattern(e)?[]:k.isIdentifier(e)?[e.name]:k.isObjectPattern(e)?e.properties.flatMap(t=>k.isObjectProperty(t)?An(t.value):An(t.argument)):k.isArrayPattern(e)?e.elements.flatMap(t=>t?An(k.isRestElement(t)?t.argument:t):[]):k.isAssignmentPattern(e)?An(e.left):k.isRestElement(e)?An(e.argument):[]}function kd(e){return k.isFunctionExpression(e)||k.isArrowFunctionExpression(e)}function jd(e,t){let n=e.functions.get(t)??e.functions.get("default");return n?e.functionVariables.get(n):void 0}async function $d(e,t){let n=await Ud(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return Ys(n,r,t.fileCache)}function Bd(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function Ud(e,t,n){return st(t)?ln(e,t,n):null}function Io(e,t,n={}){return{file:e.file,analysis:e,readFile:t.readFile,exists:t.exists,fileCache:t.fileCache,options:t.options,variableCache:new Map,functionDepth:n.functionDepth??t.functionDepth,importDepth:n.importDepth??t.importDepth,paramSources:new Map(t.paramSources),resolvingVariables:new Set,resolvingComponentProps:t.resolvingComponentProps,scopeVariables:e===t.analysis?t.scopeVariables:void 0}}function HE(e){return e?Ce(e):null}function Ce(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,Ce(n)]))}:{}}}var WE=50,GE=8*1024*1024;function Xd(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??WE),s=Math.max(0,t.maxUndoBytes??GE);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:u,redo:d};async function a(A){let D=[...A.steps].sort((W,q)=>W.order-q.order),O=D.filter(W=>W.type!=="invoke-external-adapter");if(O.length!==D.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let L=new Set(O.map(W=>W.file)),ee=await T(L),Z=new Map(ee.map(W=>[W.file,W.exists===!1?"":W.content])),xe;for(let W of O){let q=Jd(W,Z.get(W.file)??"");if(!q.ok)return{ok:!1,errorCode:q.errorCode,reason:q.reason};Z.set(W.file,q.source),xe=q.selectionRef??xe}return{ok:!0,filePlan:{operationId:A.operationId,kind:"source-edit",target:A.target,documentVersion:A.documentVersion,conflictPolicy:"compare-and-swap",edits:[...Z].map(([W,q])=>({operation:"upsert",file:W,content:q,baseContentHash:ee.find(ge=>ge.file===W)?.sha256??null}))},...xe?{selectionRef:xe}:{}}}async function c(A){let D=[...A.steps].sort((ge,xt)=>ge.order-xt.order),O=D.filter(ge=>ge.type!=="invoke-external-adapter"),L=D.filter(ge=>ge.type==="invoke-external-adapter"),ee=new Set(O.map(ge=>ge.file));if(O.length>0&&L.length>0)return{ok:!1,operationId:A.operationId,errorCode:"unsupported-operation",reason:"Mixed local file rewrites and external adapter writes require an explicit compensation contract.",rolledBack:!1};if(O.length===0)return C(A,L);let Z=await T(ee),xe=new Map;for(let ge of Z)xe.set(ge.file,ge.exists===!1?"":ge.content);let W;for(let ge of O){let xt=xe.get(ge.file)??"",ut=Jd(ge,xt);if(!ut.ok)return{ok:!1,operationId:A.operationId,errorCode:ut.errorCode,reason:ut.reason,rolledBack:!1};xe.set(ge.file,ut.source),ut.selectionRef&&(W=ut.selectionRef)}let q=await $([...xe].map(([ge,xt])=>({file:ge,content:xt,exists:!0,version:0,sha256:le(xt)})),Z);return q.ok===!1?{ok:!1,operationId:A.operationId,errorCode:q.rolledBack?"writeback-failed":"rollback-failed",reason:q.reason,rolledBack:q.rolledBack}:(n.push({operationId:A.operationId,preSnapshots:Z,postSnapshots:q.snapshots,plan:A}),m(),r.length=0,{ok:!0,operationId:A.operationId,kind:A.kind,target:A.target,resultVersion:Math.max(...q.snapshots.map(ge=>ge.version)),affectedFiles:[...ee],...W?{selectionRef:W}:{}})}async function l(A){let D=new Set(A.edits.map(q=>q.file)),O=await T(D),L=v(A,O);if(L)return{ok:!1,operationId:A.operationId,errorCode:"stale-version",reason:L.reason,affectedFiles:[L.file],rolledBack:!1};let ee=new Map(O.map(q=>[q.file,q])),Z=A.edits.find(q=>q.operation==="create-only"&&ee.get(q.file)?.exists!==!1);if(Z)return{ok:!1,operationId:A.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${Z.file}`,affectedFiles:[Z.file],rolledBack:!1};let xe=A.edits.map(q=>q.operation==="delete"?{file:q.file,content:"",exists:!1,version:0}:{file:q.file,content:q.content,exists:!0,version:0,sha256:le(q.content)}),W=await $(xe,O,new Set(A.edits.filter(q=>q.operation==="create-only").map(q=>q.file)));return W.ok===!1?{ok:!1,operationId:A.operationId,errorCode:W.rolledBack?"writeback-failed":"rollback-failed",reason:W.reason,rolledBack:W.rolledBack}:(n.push({operationId:A.operationId,preSnapshots:O,postSnapshots:W.snapshots,plan:{operationId:A.operationId,kind:A.kind,target:A.target,documentVersion:A.documentVersion,steps:[],preSnapshots:O}}),m(),r.length=0,{ok:!0,operationId:A.operationId,kind:A.kind,target:A.target,resultVersion:Math.max(...W.snapshots.map(q=>q.version)),affectedFiles:[...D]})}async function u(){let A=n.at(-1);if(!A)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let D=await $(A.preSnapshots,A.postSnapshots);return D.ok===!1?{ok:!1,operationId:A.operationId,errorCode:D.rolledBack?"writeback-failed":"rollback-failed",reason:D.reason,rolledBack:D.rolledBack}:(n.pop(),r.push(A),{ok:!0,operationId:A.operationId,kind:A.plan.kind,target:A.plan.target,resultVersion:Math.max(...D.snapshots.map(O=>O.version)),affectedFiles:A.preSnapshots.map(O=>O.file)})}async function d(){let A=r.at(-1);if(!A)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let D=await $(A.postSnapshots,A.preSnapshots);return D.ok===!1?{ok:!1,operationId:A.operationId,errorCode:D.rolledBack?"writeback-failed":"rollback-failed",reason:D.reason,rolledBack:D.rolledBack}:(r.pop(),n.push(A),m(),{ok:!0,operationId:A.operationId,kind:A.plan.kind,target:A.plan.target,resultVersion:Math.max(...D.snapshots.map(O=>O.version)),affectedFiles:A.postSnapshots.map(O=>O.file)})}function m(){for(;n.length>i;)n.shift();for(;n.length>0&&p()>s;)n.shift()}function p(){return n.reduce((A,D)=>A+h(D),0)}function h(A){return E(A.preSnapshots)+E(A.postSnapshots)}function E(A){return A.reduce((D,O)=>D+O.file.length+O.content.length,0)}async function C(A,D){let O=[];for(let L of D){let ee=L.capability??"write-text",Z=o.find(W=>W.sourceType===L.sourceType&&(L.adapterId===void 0||W.adapterId===L.adapterId)&&(W.capabilities===void 0||W.capabilities.includes(ee)));if(!Z)return{ok:!1,operationId:A.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${L.sourceType}`,rolledBack:!1};let xe=await Z.execute(L);if(!xe.ok)return{ok:!1,operationId:A.operationId,errorCode:"writeback-failed",reason:xe.reason??`External adapter failed for ${L.sourceType}`,rolledBack:!1};O.push(L.file)}return{ok:!0,operationId:A.operationId,kind:A.kind,target:A.target,resultVersion:0,affectedFiles:O}}function v(A,D){if(A.conflictPolicy!=="compare-and-swap")return null;let O=new Map(D.map(L=>[L.file,L]));for(let L of A.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 ee=O.get(L.file),Z=L.baseContentHash;if(Z===null){if(ee?.exists!==!1)return{file:L.file,reason:`Source file ${L.file} was created or changed before save.`};continue}if(!Z)return{file:L.file,reason:`Source file ${L.file} is missing baseContentHash. Reopen the file before saving.`};if(ee?.exists===!1||ee?.sha256!==Z)return{file:L.file,reason:`Source file ${L.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function T(A){let D=[];for(let O of A)D.push(await P(O));return D}async function P(A){if(!await e.exists(A))return{file:A,content:"",version:0,exists:!1};let O=Math.max(1,e.getVersion(A)),L=await e.readFile(A);return{file:A,content:L,version:O,exists:!0,sha256:le(L)}}async function $(A,D,O=new Set){let L=[];try{for(let ee of A){if(O.has(ee.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive(ee.file,ee.content)}else await re(ee);let Z=e.bumpVersion(ee.file);L.push(ee.file),ee.version=Z}}catch(ee){let Z=await te(D.filter(W=>L.includes(W.file)));if(Z.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${Z.failedFiles.join(", ")}: ${Kd(ee)}`,rolledBack:!1,instanceConflict:Vd(ee)};let xe=Vd(ee);return{ok:!1,reason:`${xe?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${Kd(ee)}`,rolledBack:!0,instanceConflict:xe}}return{ok:!0,snapshots:A.map(YE)}}async function re(A){if(A.exists===!1){await e.deleteFile(A.file);return}await e.writeFile(A.file,A.content)}async function te(A){let D=[];for(let O of A)try{await re(O),e.bumpVersion(O.file)}catch{D.push(O.file)}return D.length===0?{ok:!0}:{ok:!1,failedFiles:D}}}function Vd(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function YE(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:le(e.content)}:{}}}function Kd(e){return e instanceof Error?e.message:String(e)}function Jd(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 Me(Sn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return Me(bn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return Me(hn({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return Me(yn({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return Me(Xr({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return Me(Kn({source:t,locator:e.locator,next:e.value}));case"update-array-item":return Me(Kn({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return Me(Gr({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return Me(zr({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return Me(Yr({source:t,locator:e.locator,index:e.index}));case"move-array-item":return Me(Zr({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return Me(En({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return Me(Hr({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 ZE(e,t);case"set-props":{let n=e;return Me(Wr({source:t,locator:n.locator,props:n.props}))}default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function ZE(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!Ul(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!==le(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:Bl({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function Me(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"}}}function zd(){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 QE}from"node:crypto";import ko from"node:fs/promises";import Zs from"node:path";import{setTimeout as qE}from"node:timers/promises";var eS={async mkdir(e,t){await ko.mkdir(e,t)},async writeFile(e,t,n){await ko.writeFile(e,t,n)},async rename(e,t){await ko.rename(e,t)},async rm(e,t){await ko.rm(e,t)}},tS=new Set(["EACCES","EBUSY","EPERM"]),nS=[10,20,40,80,160];async function rS(e,t,n){for(let r of nS)try{await e.rename(t,n);return}catch(o){if(!oS(o))throw o;await qE(r)}await e.rename(t,n)}function oS(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&tS.has(e.code)}async function vo(e,t,n=eS){let r=Zs.dirname(e),o=Zs.basename(e),i=Zs.join(r,`.${o}.${process.pid}.${QE()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await rS(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import{randomBytes as xS}from"node:crypto";import yt from"node:path";import{parse as ES}from"@babel/parser";import SS from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as Ro,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as Wd,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as bS,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as IS,SiteEditMaterializationSchema as kS,parseComponentI18nResourcesJson as vS}from"@vcp-dev/contracts";var Hd=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,iS=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,sS=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,aS=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,cS=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,lS=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,uS=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,dS=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,fS=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,pS=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,mS=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,hS=/\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,gS=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,yS=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function lr(e,t){let n=Co([...Xe(e,sS),...Xe(e,aS),...Xe(e,cS),...Xe(e,t.includeRgbBackgroundImage?lS:uS),...t.includeExtendedColorFunctions?[...Xe(e,dS),...Xe(e,fS)]:[]]),r=Co([...Xe(e,pS),...Xe(e,mS)]).filter(o=>t.colorMixPolicy==="always"||Hd.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...Xe(e,hS).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...Xe(e,yS).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:Co(Xe(e,iS)),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?Co(Xe(e,gS)):[]}}function Xe(e,t){return e.match(new RegExp(t.source,t.flags))??[]}function Co(e){return[...new Set(e)]}var ea="components/site/generated",Gd="{{$INSTANCE}}",Po=5,CS=/^[a-z][a-z0-9-]{0,48}$/,RS=/^[a-f0-9]{8}$/,Yd=/\.tsx?$/,PS=/\.json$/,wS=/\.(?:tsx?|json)$/,AS=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,TS=["react","react/","next","next/","lucide-react","react-i18next","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],Qs=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),qs=SS,NS=typeof qs=="function"?qs:qs.default;function FS(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>Wd)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=KS(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=kS.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=BS(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${ea}.`,path:e.generatedRoot}};if(!nf(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=qd(r.data.files),s=qd(e.controlledFiles);if(!JS(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>Wd)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>bS)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>IS?{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 _S(e){let t=FS(e);if(!t.ok)return t;let n=t.data.generatedRoot,r=nf(e.manifest.instanceBaseName),o=Math.max(1,Math.min(Po,e.maxAttempts??Po));for(let i=0;i<o;i+=1){let s=US(e.instanceNameGenerator?.()??xS(4).toString("hex"));if(!s)return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_INVALID",message:"Static prefab instance suffix must be 8 lowercase hex chars."}};let a=`${r}-${s}`,c=of(n,a),l=MS({manifest:e.manifest,generatedRoot:n,instanceName:a,instanceRoot:c,allowedExternalImports:e.allowedExternalImports??TS});if(!l.ok)return l;if(!await OS(e.exists,c,l.data.files))return{ok:!0,data:l.data}}return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:"Unable to allocate a create-only static prefab instance after repeated conflicts."}}}async function tf(e){let t=Math.max(1,Math.min(Po,e.maxAttempts??Po));for(let n=0;n<t;n+=1){let r=await _S({...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 MS(e){let t=[],n=new Set;for(let i of e.manifest.files){let s=Zd({pathTemplate:i.pathTemplate,generatedRoot:e.generatedRoot,instanceName:e.instanceName,instanceRoot:e.instanceRoot});if(!s.ok)return s;if(n.has(s.data))return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${s.data}`,path:s.data}};n.add(s.data),t.push({kind:"create-only",path:s.data,content:i.content,...i.role?{role:i.role}:{},sourcePathTemplate:i.pathTemplate})}t.sort((i,s)=>i.path.localeCompare(s.path));let r=Zd({pathTemplate:e.manifest.entry.pathTemplate,generatedRoot:e.generatedRoot,instanceName:e.instanceName,instanceRoot:e.instanceRoot});if(!r.ok)return r;if(!t.some(i=>i.path===r.data))return{ok:!1,error:{code:"MATERIALIZATION_ENTRY_INVALID",message:"Entry path must match one of the static prefab files.",path:r.data}};let o=DS(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 OS(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function Zd(e){if(e.pathTemplate.split(Gd).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(Gd,e.instanceName),n=VS(t);return n?of(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||!wS.test(n)||AS.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 DS(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(PS.test(d.path)){if(d.path.endsWith(Ro)){let h=vS(d.content);if(!h.success)return qt("MATERIALIZATION_DATA_UNSUPPORTED",h.error.message,d.path);c.set(d.path,new Set)}else try{JSON.parse(d.content)}catch{return qt("MATERIALIZATION_DATA_UNSUPPORTED","Static prefab JSON file must contain valid JSON.",d.path)}continue}let m;try{m=ES(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 p=lr(d.content,{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0});if(p.hardCodedSurfaceHits.length>0||p.rawColorHits.length>0||p.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,m)}for(let d of e){if(!Yd.test(d.path))continue;let m=s.get(d.path),p=null;if(NS(m,{ImportDeclaration(h){let E=Qd({importer:d.path,source:h.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});if(!E.allowed)p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab imports must resolve within the controlled instance or match the starter allowlist.",file:d.path},h.stop();else if(E.internalPath&&(a.get(d.path).add(E.internalPath),E.internalPath.endsWith(Ro))){let C=LS({importer:d.path,imported:E.internalPath,source:h.node.source.value,ast:m});C.ok?c.get(E.internalPath).add(d.path):(p??=C.error,h.stop())}},ExportAllDeclaration(h){p??={code:"MATERIALIZATION_ENTRY_INVALID",message:"Static prefab files cannot use export-star declarations.",file:d.path},h.stop()},ExportNamedDeclaration(h){if(h.node.source){let E=Qd({importer:d.path,source:h.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});!E.allowed||!E.internalPath?(p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab re-exports must resolve within the controlled instance.",file:d.path},h.stop()):a.get(d.path).add(E.internalPath)}},CallExpression(h){if(h.node.callee.type==="Import"){p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use dynamic import().",file:d.path},h.stop();return}h.node.callee.type==="Identifier"&&h.node.callee.name==="require"&&(p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use require().",file:d.path},h.stop())},NewExpression(h){h.node.callee.type==="Identifier"&&h.node.callee.name==="Function"&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot construct functions dynamically.",file:d.path},h.stop())},MetaProperty(h){h.node.meta.type==="Identifier"&&h.node.meta.name==="import"&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot use import.meta.",file:d.path},h.stop())},MemberExpression(h){let E=ef(h.node);E&&Qs.has(E)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${E}.`,file:d.path},h.stop())},OptionalMemberExpression(h){let E=ef(h.node);E&&Qs.has(E)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${E}.`,file:d.path},h.stop())},Identifier(h){h.isReferencedIdentifier()&&Qs.has(h.node.name)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h.node.name}.`,file:d.path},h.stop())},JSXAttribute(h){h.node.name.type==="JSXIdentifier"&&h.node.name.name==="style"&&(p??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot use inline style attributes.",file:d.path},h.stop())},JSXOpeningElement(h){h.node.name.type==="JSXIdentifier"&&h.node.name.name.toLowerCase()==="style"&&(p??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot declare style elements.",file:d.path},h.stop())}}),p)return{ok:!1,error:p}}if(!Yd.test(n))return qt("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must be a .ts/.tsx source module.",n);let l=s.get(n);if(!l)return qt("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",n);if(!jS(l,r))return qt("MATERIALIZATION_EXPORT_MISSING","Static prefab entry does not declare the manifest export.",n);for(let[d,m]of c)if(m.size!==1)return qt("MATERIALIZATION_IMPORT_FORBIDDEN","Each component .i18n.json file must have exactly one same-name Client Component static importer.",d);return $S(n,a).size!==e.length?qt("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",n):{ok:!0,data:{kind:"static-prefab-materialization",instanceName:"",generatedRoot:ea,instanceRoot:"",entry:{path:"",export:{kind:"default"}},files:[]}}}function Qd(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=yt.posix.normalize(yt.posix.join(yt.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 LS(e){let t=yt.posix.dirname(e.importer),n=yt.posix.dirname(e.imported),r=yt.posix.basename(e.importer).replace(/\.tsx?$/,""),o=yt.posix.basename(e.imported).slice(0,-Ro.length),i=`./${r}${Ro}`;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 jS(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 $S(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 qt(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function BS(e){let t=rf(e);return t===ea?t:null}function US(e){let t=e.trim().toLowerCase();return RS.test(t)?t:null}function nf(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 CS.test(t)?t:null}function rf(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=yt.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function VS(e){let t=rf(e);return!t||t!==e?null:t}function of(...e){return yt.posix.join(...e)}function qd(e){return new Set(e.map(t=>t.pathTemplate))}function KS(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 JS(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function ef(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{randomBytes as XS}from"node:crypto";import wo from"node:path";import{parse as ff}from"@babel/parser";import zS from"@babel/traverse";import*as pf from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as na,PageResourceArtifactSchema as HS,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as WS,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as GS,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as YS,parseComponentI18nResourcesJson as ZS}from"@vcp-dev/contracts";var ra="{{$INSTANCE}}",QS=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,qS=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,oa="components/site/generated",eb=/\.(?:tsx?|json)$/,tb=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,nb=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],rb=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),ta=zS,ob=typeof ta=="function"?ta:ta.default;async function ia(e){let t=HS.safeParse(e.artifact);if(!t.success)return me("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>XS(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=pb(r());if(!i)return me("Random instance suffix must be 8 lowercase hex chars.");let s=`${mb(n.resource_id)}-${i}`,a=new Map,c=new Map,l=[];for(let P of n.pages){let $=P.final_route.slice(1);a.set(P.template_page_id,P.final_route),c.set(P.template_page_id,P.title),l.push({template_page_id:P.template_page_id,title:P.title,final_route:P.final_route,route_file_path:`app/${$}/page.tsx`})}let u=[],d=new Set,m=new Set,p=new Map,h=new Map,E=[],C=new Set(n.pages.flatMap(P=>P.components.map($=>$.component_id)));for(let P of n.components){if(!C.has(P.component_id))continue;let $=sf({materialization:P.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c});if(!$.ok)return $;for(let re of $.files){let te=cf(re,d,u);if(te)return te}m.add($.entry),h.set($.entry,$.entryExport),p.set(P.component_id,$.entry)}for(let[P,$]of n.pages.entries()){let re=l[P],te=sf({materialization:$.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c,pageEntryTarget:re.route_file_path});if(!te.ok)return te;for(let O of te.files){let L=cf(O,d,u);if(L)return L}m.add(te.entry),h.set(te.entry,te.entryExport),E.push({entry:te.entry,declaredComponentIds:new Set($.components.map(O=>O.component_id))});let A=u.find(O=>O.file===re.route_file_path);if(!A)return me("Page materialization entry did not resolve to its final route file.",re.route_file_path);if(lb(A.content,re.route_file_path)!==re.final_route)return me(`Page ${$.template_page_id} requires a static PAGE_SEO.path equal to ${re.final_route}.`,re.route_file_path)}let v=sb(u,m,s,p,E,h);if(!v.ok)return v;for(let P of u)if(await e.exists(P.file))return!P.file.startsWith("app/")&&o>1?ia({...e,randomHex:r,maxAttempts:o-1}):{ok:!1,code:"MATERIALIZATION_CONFLICT",message:`Page resource create-only target already exists: ${P.file}`,path:P.file};let T=ab(u);return T||(u.sort((P,$)=>P.file.localeCompare($.file)),{ok:!0,packageInstanceId:s,pages:l,files:u})}function sf(e){let t=e.materialization.entry.pathTemplate,n=[];for(let o of e.materialization.files){let s=o.pathTemplate===t&&e.pageEntryTarget?e.pageEntryTarget:af(o.pathTemplate,e.packageInstanceId);if(!s)return me("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=ib(o.content,e.packageInstanceId,e.routeByPage,e.titleByPage);if(!a.ok)return a;n.push({operation:"create-only",file:s,content:a.data})}let r=e.pageEntryTarget??af(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 ib(e,t,n,r){let o,i=e.replace(QS,(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(qS,(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(ra,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?me("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function af(e,t){let n=`${oa}/${t}`;if(e.split(ra).length>2)return null;let o=e.replace(ra,t),i=`${oa}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=wo.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!eb.test(a)||tb.test(a)?null:a}function cf(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 sb(e,t,n,r,o,i){let s=new Set(e.map(p=>p.file)),a=`${oa}/${n}`,c=new Map(e.map(p=>[p.file,new Set])),l=new Map;for(let p of e){if(p.file.endsWith(".json")){try{JSON.parse(p.content)}catch{return me("Materialization JSON file must contain valid JSON.",p.file)}if(p.file.endsWith(na)&&!ZS(p.content).success)return me("Materialization component i18n resources are invalid.",p.file);continue}try{let E=ff(p.content,{sourceType:"module",plugins:["jsx","typescript"]});l.set(p.file,E);for(let v of E.program.body)if((v.type==="ImportDeclaration"||v.type==="ExportAllDeclaration"||v.type==="ExportNamedDeclaration"&&v.source)&&v.source){let T=v.source.value,P=db(p.file,T,s,a);if(!P.allowed)return me(`Materialization import is outside the controlled package: ${T}`,p.file);P.internalPath&&c.get(p.file).add(P.internalPath)}let C;if(ob(E,{Identifier(v){v.isReferencedIdentifier()&&rb.has(v.node.name)&&(C??=v.node.name,v.stop())},JSXAttribute(v){v.node.name.type==="JSXIdentifier"&&v.node.name.name==="style"&&(C??="inline style",v.stop())},JSXOpeningElement(v){v.node.name.type==="JSXIdentifier"&&v.node.name.name.toLowerCase()==="style"&&(C??="style element",v.stop())}}),C)return me(`Materialization source uses forbidden capability: ${C}`,p.file)}catch{return me("Materialization source must parse as TS/TSX.",p.file)}let h=lr(p.content,{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0});if(h.hardCodedSurfaceHits.length>0||h.rawColorHits.length>0||h.privateTokenHits.length>0)return me("Materialization source violates the public theme token policy.",p.file)}if([...t].some(p=>!s.has(p)))return me("Materialization entry is outside the controlled package.");for(let p of t)if(p.endsWith(".json"))return me("Materialization JSON files cannot be package entries.");for(let[p,h]of i){let E=l.get(p);if(!E||!cb(E,h))return me("Materialization entry does not declare its contracted export.",p)}let u=new Map([...r].map(([p,h])=>[h,p]));for(let p of o){let h=df(p.entry,c);for(let E of p.declaredComponentIds){let C=r.get(E);if(!C||!h.has(C))return me(`Page entry does not reach declared component: ${E}`,p.entry)}for(let E of h){let C=u.get(E);if(C&&!p.declaredComponentIds.has(C))return me(`Page entry imports undeclared component: ${C}`,p.entry)}}let d=new Set;for(let p of t)for(let h of df(p,c))d.add(h);if(d.size!==e.length)return me("Every materialization file must be reachable from a package entry.");let m=fb(e,l,c);return m||{ok:!0}}function ab(e){if(e.length>WS)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>GS)return me("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>YS?me("Page resource exceeds the aggregate content byte limit."):null}function cb(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 lb(e,t){let n;try{n=ff(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return null}for(let r of n.program.body){let o=r.type==="VariableDeclaration"?r:r.type==="ExportNamedDeclaration"&&r.declaration?.type==="VariableDeclaration"?r.declaration:null;if(o)for(let i of o.declarations){if(i.id.type!=="Identifier"||i.id.name!=="PAGE_SEO")continue;let s=lf(i.init);if(s?.type!=="ObjectExpression")return null;for(let a of s.properties){if(a.type!=="ObjectProperty"||a.computed||!ub(a.key))continue;let c=lf(a.value);return c?.type==="StringLiteral"?c.value:c?.type==="TemplateLiteral"&&c.expressions.length===0?c.quasis[0]?.value.cooked??null:null}return null}}return null}function lf(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&pf.isExpression(t)?t:null}function ub(e){return e.type==="Identifier"&&e.name==="path"||e.type==="StringLiteral"&&e.value==="path"}function db(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=uf(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:nb.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=wo.posix.normalize(wo.posix.join(wo.posix.dirname(e),t)),i=uf(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function uf(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 fb(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(na))continue;let i=o.file.slice(0,-na.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 df(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 pb(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function mb(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{COMPONENT_I18N_FILE_SUFFIX as hb,parseComponentI18nResourcesJson as gb,resolveSiteTextDirection as yb,SiteLocaleSchema as xb}from"@vcp-dev/contracts";var Eb=["i18next","react-i18next"],Sb="components/ui/site-locale-provider.tsx",bb="components/ui/component-i18n-provider.tsx",mf="app/layout.tsx";async function aa(e){let t=e.files.filter(m=>m.path.endsWith(hb));if(t.length===0)return{ok:!0};for(let m of["package.json",mf,Sb,bb])if(!await e.exists(m))return en(`Target snapshot is missing required i18n host file: ${m}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return en("Target snapshot package.json is invalid.")}let r=hf(n)&&hf(n.dependencies)?n.dependencies:{},o=Eb.filter(m=>typeof r[m]!="string"||r[m].trim().length===0);if(o.length>0)return en(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile(mf),s=sa(i,"html","lang"),a=sa(i,"html","dir"),c=sa(i,"SiteLocaleProvider","locale"),l=xb.safeParse(s);if(!l.success||!a||!c||s!==c||a!==yb(l.data))return en("Target snapshot app/layout.tsx must keep html lang/dir and SiteLocaleProvider locale consistent.");if(!i.includes('from "@/components/ui/site-locale-provider"')||!/<SiteLocaleProvider\b/.test(i)||!/<\/SiteLocaleProvider>/.test(i))return en("Target snapshot root layout is not wired to SiteLocaleProvider.");let u=l.data,d=u.split("-")[0];for(let m of t){let p=gb(m.content);if(!p.success)return en(`Component i18n resource is invalid: ${m.path}.`);if(!Object.hasOwn(p.data,u)&&!Object.hasOwn(p.data,d))return en(`Component i18n resource ${m.path} has no locale for ${u} or ${d}.`)}return{ok:!0}}function sa(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 hf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function en(e){return{ok:!1,message:e}}import{parse as yf}from"@babel/parser";import{HOME_PAGE_URL_PATH as Tb}from"@vcp-dev/contracts";import FP from"node:fs";import MP from"node:path";var Ib=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function gf(e){let t=e.map(r=>Ab(r.path)),n=kb(t);return n?t.filter(r=>vb(n,r)).map(r=>({routeId:Cb(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function kb(e){return e.some(r=>r.startsWith("app/"))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function vb(e,t){if(!t.startsWith(`${e}/`))return!1;let n=t.slice(t.lastIndexOf("/")+1);return Ib.test(n)?t.slice(e.length+1,-n.length-1).split("/").filter(Boolean).every(r=>!r.startsWith("_")):!1}function Cb(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(Pb).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function Rb(e){return e.startsWith("(")&&e.endsWith(")")}function Pb(e){return!e||e.startsWith("@")||e.startsWith("_")||Rb(e)?null:wb(e)}function wb(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function Ab(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var Nb="components/site/generated/",ca=[".tsx",".ts",".jsx",".js"];function xf(e){if(e.expectedUrlPath===Tb)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set(gf(Object.keys(e.files).map(d=>({path:d}))).map(d=>d.entryFile)),n=Object.entries(e.files).filter(([d,m])=>t.has(d.replace(/\\/g,"/"))?Fb(m)===e.expectedUrlPath:!1);if(n.length===0)return{ok:!1,code:"ROUTE_NOT_FOUND",message:"No route uniquely matches PAGE_SEO.path."};if(n.length>1)return{ok:!1,code:"ROUTE_AMBIGUOUS",message:"Multiple routes match PAGE_SEO.path."};let[r]=n[0],o=Db(e.files),i=jb(r,o),s=$b(r,i,o),a=[...i].filter(d=>!s.has(d)).sort((d,m)=>d.localeCompare(m)),c=[{operation:"delete",file:r},...[...s].sort((d,m)=>d.localeCompare(m)).map(d=>({operation:"delete",file:d}))],l=[],u=[];for(let[d,m]of Object.entries(e.files))if(d!==r){if(m.includes("NAV_ITEMS")){let p=_b(m,e.expectedUrlPath);p.status==="removed"?(c.push({operation:"upsert",file:d,content:p.source}),l.push(d)):p.status==="unsupported"&&u.push(`unsupported_navigation:${d}`)}m.includes(e.expectedUrlPath)&&!m.includes("NAV_ITEMS")&&u.push(`preserved_link:${d}`)}return{ok:!0,edits:c,deletedFiles:[r,...[...s].sort((d,m)=>d.localeCompare(m))],updatedFiles:l,preservedSharedFiles:a,warnings:u}}function Fb(e){let t;try{t=yf(e,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}for(let n of Mt(t.program.body)){let r=n.type==="ExportNamedDeclaration"?n.declaration:n;if(r?.type==="VariableDeclaration")for(let o of Mt(r.declarations)){let i=o.id;if(i?.type!=="Identifier"||i.name!=="PAGE_SEO")continue;let s=Ef(o.init);if(s?.type!=="ObjectExpression")return null;for(let a of Mt(s.properties)){if(a.type!=="ObjectProperty"||a.computed)continue;let c=a.key,l=a.value;if((c?.name==="path"||c?.value==="path")&&l?.type==="StringLiteral"&&typeof l.value=="string")return l.value}return null}}return null}function _b(e,t){let n=bf(t);if(!n)return{status:"unsupported"};let r;try{r=yf(e,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return{status:"unsupported"}}let o=[];for(let l of Mt(r.program.body)){let u=l.type==="ExportNamedDeclaration"?l.declaration:l;if(u?.type==="VariableDeclaration")for(let d of Mt(u.declarations)){let m=d.id;m?.type==="Identifier"&&m.name==="NAV_ITEMS"&&o.push(d)}}if(o.length===0)return{status:"navigation_not_found"};if(o.length!==1)return{status:"unsupported"};let i=Sf(o[0]?.init);if(!i)return{status:"unsupported"};let s=[],a=l=>{let u=Mt(l.elements);for(let[d,m]of u.entries()){if(Ob(m,n)){let h=u[d+1],E=u[d-1];if(typeof m.start!="number"||typeof m.end!="number")continue;h&&typeof h.start=="number"?s.push({start:m.start,end:h.start}):E&&typeof E.end=="number"?s.push({start:E.end,end:m.end}):s.push({start:m.start,end:m.end});continue}let p=Mb(m);p&&a(p)}};if(a(i),s.length===0)return{status:"not_found"};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}}function Mt(e){return Array.isArray(e)?e:[]}function Ef(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="ParenthesizedExpression";)t=t.expression;return t}function Sf(e){let t=Ef(e);return t?.type==="ArrayExpression"?t:void 0}function Mb(e){if(e.type==="ObjectExpression")for(let t of Mt(e.properties)){if(t.type!=="ObjectProperty"||t.computed)continue;let n=t.key;if((n?.name??n?.value)==="children")return Sf(t.value)}}function bf(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function Ob(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of Mt(e.properties)){if(o.type!=="ObjectProperty"||o.computed)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"&&bf(n??"")===t}function Db(e){let t=new Set(Object.keys(e)),n=new Map;for(let[r,o]of Object.entries(e)){let i=new Set;for(let s of dc(o)){let a=ci(r,s),c=Lb(a,t);c&&i.add(c)}n.set(r,i)}return n}function Lb(e,t){let n=e.replace(/\\/g,"/");return(ca.some(o=>n.endsWith(o))?[n]:[...ca.map(o=>`${n}${o}`),...ca.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function jb(e,t){let n=new Set,r=[...t.get(e)??[]];for(;r.length>0;){let o=r.pop();!o.startsWith(Nb)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function $b(e,t,n){let r=new Set(t),o=!0;for(;o;){o=!1;for(let i of[...r])[...n].some(([a,c])=>a!==e&&!r.has(a)&&c.has(i))&&(r.delete(i),o=!0)}return r}function Rf(e){let t=null,n=new WeakMap;async function r(){return t??=Bb(e),t}return{async prepareAppend(o){let i=await e.readIndex(),s=await e.stageAppend(Cf(o),{durableManifest:!1}),a;try{a=await e.previewStagedAppend(s.entryId,i.digest)}catch(l){throw await e.discardStage(s.stageId),l}let c={kind:"append",entry:o,historyTransition:a};return n.set(c,{expectedDigest:i.digest,stageId:s.stageId,entryId:s.entryId}),c},async prepareUndo(){let i=(await r()).undo.at(-1);if(!i?.historyId)return null;let s=await e.readIndex(),a=s.entryIds.indexOf(i.historyId);if(a<0)throw new Error("undo entry is missing from index");let c=a-1,l=await e.previewCursor(c,s.digest),u={kind:"undo",entry:i,historyTransition:l};return n.set(u,{expectedDigest:s.digest,cursor:c}),u},async prepareRedo(){let i=(await r()).redo.at(-1);if(!i?.historyId)return null;let s=await e.readIndex(),a=s.entryIds.indexOf(i.historyId);if(a<0)throw new Error("redo entry is missing from index");let c=a,l=await e.previewCursor(c,s.digest),u={kind:"redo",entry:i,historyTransition:l};return n.set(u,{expectedDigest:s.digest,cursor:c}),u},async publishPrepared(o){let i=n.get(o);if(!i)throw new Error("history mutation was not prepared");let s=await r();if(o.kind==="append"){if(!i.entryId)throw new Error("staged entry id is missing");let a=await e.publishStagedAppend(i.entryId,i.expectedDigest,i.stageId);If(a,o.historyTransition),o.entry.historyId=i.entryId,s.entryIds=[...a.entryIds],s.cursor=a.cursor,s.undo.push(o.entry),s.redo.length=0}else{if(i.cursor===void 0)throw new Error("prepared cursor is missing");let a=await e.setCursor(i.cursor,i.expectedDigest);if(If(a,o.historyTransition),o.kind==="undo"){if(s.undo.at(-1)!==o.entry)throw new Error("undo state changed before publish");s.undo.pop(),s.redo.push(o.entry)}else{if(s.redo.at(-1)!==o.entry)throw new Error("redo state changed before publish");s.redo.pop(),s.undo.push(o.entry)}s.cursor=i.cursor}n.delete(o)},async discardPrepared(o){let i=n.get(o);if(!i)return;let s=o.historyTransition;if(s){let a=await e.readIndex();if(a.digest===s.publishedIndexDigest&&a.cursor===s.publishedCursor&&a.currentId===s.publishedCurrentId)throw new Error("cannot discard a history mutation whose index was published")}i.stageId&&await e.discardStage(i.stageId),n.delete(o)},async peekUndo(){return(await r()).undo.at(-1)??null},async pushUndo(o){let i=await r(),s=o;if(s.historyId){let l=i.entryIds.indexOf(s.historyId);if(l>=0)try{await e.setCursor(l),i.undo.push(o),i.cursor=l;return}catch(u){throw i.redo.push(o),u}}let a=await e.append(Cf(o)),c=a.currentId;if(!c)throw new Error("history store did not publish an entry");o.historyId=c,i.entryIds=[...a.entryIds],i.cursor=a.cursor,i.undo.push(o),i.redo.length=0},async popUndo(){return(await r()).undo.pop()??null},async peekRedo(){return(await r()).redo.at(-1)??null},async pushRedo(o){let i=await r(),s=o;if(!s.historyId)throw i.undo.push(o),new Error("cannot move an unpersisted history entry to redo");let a=i.entryIds.indexOf(s.historyId);if(a<0)throw i.undo.push(o),new Error("history entry is missing from the durable index");try{await e.setCursor(a-1),i.cursor=a-1,i.redo.push(o)}catch(c){throw i.undo.push(o),c}},async popRedo(){return(await r()).redo.pop()??null},async clearRedo(){(await r()).redo.length=0},async getStatus(){let o=await e.readStatus();return{canUndo:o.canUndo,canRedo:o.canRedo,undoDepth:o.undoDepth,redoDepth:o.redoDepth,recoveryRequired:o.recoveryRequired}},async markRecoveryRequired(o){await e.markRecoveryRequired(o)}}}function If(e,t){if(!t)throw new Error("durable history transition is missing");if(e.digest!==t.publishedIndexDigest||e.cursor!==t.publishedCursor||e.currentId!==t.publishedCurrentId)throw new Error("durable history published an unexpected index state")}async function Bb(e){let t=await e.readIndex(),n=await Promise.all(t.undoIds.map(async o=>kf(e,o))),r=await Promise.all(t.redoIds.map(async o=>kf(e,o)));return{undo:n.reverse(),redo:r.reverse(),entryIds:[...t.entryIds],cursor:t.cursor}}async function kf(e,t){let n=await e.readEntry(t),r=Ub(n);return{historyId:t,operationId:r.operationId,kind:r.kind,target:r.target,...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(Vb(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function Cf(e){let t=[],n=(o,i)=>o.map((s,a)=>{let c={file:s.file,exists:s.exists!==!1,version:s.version,...s.sha256?{sha256:s.sha256}:{}};if(c.exists){let l=`${i}-${a}`;c.blobName=l,t.push({name:l,data:s.content})}return c}),r={operationId:e.operationId,kind:e.kind,target:e.target,...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(r)),blobs:t}}function Ub(e){if(!Kb(e.manifest))throw new Error("durable history manifest is not an object");return e.manifest}function Vb(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function Kb(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import Pf from"node:path";function ua(){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 Af(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=Hb(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 Ao(e){let t=()=>Jb(e);return e.mutex?e.mutex.runExclusive(t):t()}async function Jb(e){let t=await Af(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=Xb(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 la({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 la({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 la({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 wf("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return wf("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 Xb(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 la(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:zb(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 wf(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function zb(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 Hb(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)||Pf.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=Pf.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}}function da(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function Tn(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function Tf(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function fa(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 Nf(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function Wb(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var ur=class extends Error{constructor(t){let n=t.map(Nf);super(Wb(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function Ff(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof ur?{routeId:e,message:n,diagnostics:t.diagnostics.map(Nf)}:{routeId:e,message:n}}function pa(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function _f(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 tI=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,nI=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],Mf=32,Of=256;function rI(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var Df={maxEntries:50,maxBytes:8*1024*1024};function oI(){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 vo(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}}}function iI(){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>Df.maxEntries||sI(e)>Df.maxBytes;)e.shift()}}function sI(e){return e.reduce((t,n)=>t+aI(n),0)}function aI(e){return Lf(e.preSnapshots)+Lf(e.postSnapshots)}function Lf(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function jf(e,t){return{routeId:e,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}}function cI(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=ze(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}}var Fo=class extends Error{constructor(t){super(t.reason),this.result=t}},tn=class extends Error{constructor(t){super(pa(t)),this.failedRoutes=t}};function $f(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=ze(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(ze(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}var lI=/\.(?:[cm]?[jt]sx?)$/i,uI=/\.json$/i,dI=/\.(?:css|scss|sass)$/i,fI=/\.mdx$/i,pI=/\.ya?ml$/i;function mI(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 hI(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function gI(e,t){let n=new Map;for(let r of t)n.set(r.path,r.operation==="delete"?{exists:!1}:{exists:!0,content:r.content});return{async readFile(r){let o=n.get(r);if(o){if(!o.exists)throw new Error(`Source file not found: ${r}`);return o.content}return e.readFile(r)},async writeFile(){throw new Error("Source edit preflight overlay is read-only.")},async deleteFile(){throw new Error("Source edit preflight overlay is read-only.")},async exists(r){let o=n.get(r);return o?o.exists:e.exists(r)},async getFileInfo(r){let o=n.get(r);return o?o.exists?{path:r,sizeBytes:Buffer.byteLength(o.content,"utf8")}:null:e.getFileInfo?.(r)??null},async listFiles(r={}){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let o=Xf(await e.listFiles(r)),i=new Map(o.files.map(a=>[a.path,a]));for(let[a,c]of n)if(yI(a,r.roots??[])){if(!c.exists){i.delete(a);continue}i.set(a,{path:a,sizeBytes:Buffer.byteLength(c.content,"utf8")})}let s=[...i.values()].sort((a,c)=>a.path.localeCompare(c.path));return o.truncated?{files:s,truncated:o.truncated}:s},getVersion(r){return e.getVersion(r)},bumpVersion(r){return e.getVersion(r)}}}function yI(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function Xf(e){return Array.isArray(e)?{files:e}:e}function xI(e){if(!Zb(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!==qb||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=Yb(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(lI.test(e.path)){let t=it({source:e.content,profile:Bt({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(uI.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${Ne(t)}`,details:{path:e.path}}}if(dI.test(e.path)){let t=Bf({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(fI.test(e.path)){let t=Bf({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(pI.test(e.path))try{eI(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${Ne(t)}`,details:{path:e.path}}}return{ok:!0}}function Bf({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 m=e[d]??"",p=e[d+1]??"";if(n==="mdx"&&l&&e.startsWith("```",d)){c=!c;let h=e.indexOf(`
|
|
5
|
-
`,d);if(
|
|
6
|
-
`||
|
|
7
|
-
`||
|
|
8
|
-
`||
|
|
9
|
-
`||
|
|
10
|
-
`||
|
|
11
|
-
`||m==="\r"}if(s)return Nn(t,`Unterminated block comment in ${t}.`);if(o)return Nn(t,`Unterminated string literal in ${t}.`);if(c)return Nn(t,`Unterminated MDX code fence in ${t}.`);let u=r.at(-1);return u?Nn(t,`Unclosed token "${u.char}" in ${t}.`):{ok:!0}}function Nn(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function fr(e){let t="idle",n=e.fileSystem??oI(),r=zd(),o=new Map,i=new Map,s=null,a=new Set,c=null,l=e.history??(e.historyStore?Rf(e.historyStore):iI()),u=Xd(n,{externalAdapters:e.externalAdapters}),d=new Map,m=new Set,p=Math.max(0,e.initialDocumentVersion??0),h=0,E=e.historyStore?.recoveryRequired??!1,C=ua(),v=re();function T(f){return(To.isAbsolute(f)?To.relative(e.projectRoot,f):f).replace(/\\/g,"/").replace(/^\.\//,"")}function P(f,y){let g=To.posix.dirname(f),I=y.replace(/\.(?:tsx?|jsx?)$/i,""),R=To.posix.relative(g,I);return R.startsWith(".")?R:`./${R}`}function $(f,y){return f.startLine===y.startLine&&f.startColumn===y.startColumn&&f.endLine===y.endLine&&f.endColumn===y.endColumn}async function re(){let f=e.historyStore;if(f)try{let y=await f.readTransactionJournal();if(!y)return;let g=await f.readIndex(),I=await Promise.all(y.files.map(async F=>await n.exists(F.path)?le(await n.readFile(F.path)):null));if(_f({journal:y,index:g,observedFileDigests:I})!=="ambiguous"){await f.clearTransactionJournal(y.transactionId);let F=await f.readStatus();F.recoveryRequired||(await f.cleanupTmp(),F=await f.readStatus()),E=F.recoveryRequired;return}await f.markRecoveryRequired(`Ambiguous transaction journal ${y.transactionId} at phase ${y.phase}`),E=!0}catch(y){E=!0,await f.markRecoveryRequired(`Transaction journal recovery failed: ${Ne(y)}`).catch(()=>{})}}function te(){return t==="disposed"}if(e.onEvent&&r.subscribe(e.onEvent),e.routes)for(let f of e.routes){let y=jf(f.routeId,f.entryFile);o.set(f.routeId,y),A(y,y.dependencyFiles)}function A(f,y){let g=new Set(y);D(f),f.dependencyFiles=g;for(let I of f.dependencyFiles){let R=i.get(I);R||(R=new Set,i.set(I,R)),R.add(f.routeId)}}function D(f){for(let y of f.dependencyFiles){let g=i.get(y);g&&(g.delete(f.routeId),g.size===0&&i.delete(y))}f.dependencyFiles.clear()}function O(f){let y=new Set;for(let g of f)for(let I of i.get(g)??[])y.add(I);return y}function L(f){for(let y of f)if(!i.has(y))return!1;return!0}async function ee(f,y,g,I,R){let F=new Map,j=Wu(R.values()),_=new Map,N=typeof n.exists=="function"?J=>n.exists(J):async()=>!1;for(let[J,Y]of f.elements){let ne=y.nodes.get(J);if(!ne)continue;let ie=g.get(Y.sourceFile)??I.get(Y.sourceFile),ue=new Map,X=new Map,w=new Map,U=[];for(let pe of Y.textSegments){if(!ie){ue.set(pe.index,null);continue}let Mn=await Gu({file:Y.sourceFile,source:ie,segment:pe,readFile:We=>n.readFile(We),exists:N,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:We,adapterId:ei,capabilities:ti})=>({sourceType:We,adapterId:ei,capabilities:ti})),functionCallContracts:e.functionCallContracts,fileCache:j}),ve=await ws({file:Y.sourceFile,source:ie,target:{kind:"text-segment",segment:pe},readFile:We=>n.readFile(We),exists:N,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:We,adapterId:ei,capabilities:ti})=>({sourceType:We,adapterId:ei,capabilities:ti})),functionCallContracts:e.functionCallContracts,fileCache:j}),an=mI(Mn);ue.set(pe.index,an),X.set(pe.index,Mn),w.set(pe.index,ve),U.push({editable:pe.editable,source:an})}let G=new Map;if(ie)for(let pe of Y.attributes??[]){let Mn=await Yu({file:Y.sourceFile,source:ie,sourceRange:pe.sourceRange,expression:pe.source?.expression??pe.value,sourceInfo:pe.source,readFile:ve=>n.readFile(ve),exists:N,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:ve,adapterId:an,capabilities:We})=>({sourceType:ve,adapterId:an,capabilities:We})),functionCallContracts:e.functionCallContracts,fileCache:j});G.set(pe.name,Mn)}let we=Cl(hI(ne.writeTarget),U),Re=Tl({key:J,element:Y,graph:f,provenances:w}),Se=Ml(Y),vr=Ol(Y),Cr=Dl(Y),sn=ie?await vd({element:Y,graph:f,file:Y.sourceFile,source:ie,readFile:pe=>n.readFile(pe),exists:N,fileCache:_}):void 0,Lt=f.regions.find(pe=>pe.kind==="conditional-region"&&pe.childKeys.includes(J)),Ae,_n=Lt?.sourceCandidates?.[0];if(ie&&Lt&&_n?.kind==="conditional-branch"){let pe=await ws({file:Y.sourceFile,source:ie,target:{kind:"conditional-branch",candidate:_n},readFile:ve=>n.readFile(ve),exists:N,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:ve,adapterId:an,capabilities:We})=>({sourceType:ve,adapterId:an,capabilities:We})),functionCallContracts:e.functionCallContracts,fileCache:j});Ae={currentBranch:Lt.childKeys.indexOf(J)<=0?"then":"else",availableBranches:Lt.childKeys.length>1?["then","else"]:["then"],conditionExpression:_n.conditionExpression,provenance:{finalSource:pe.finalSource?{kind:pe.finalSource.kind,file:pe.finalSource.file,displayPath:pe.finalSource.displayPath}:null,chain:pe.chain.map(ve=>({kind:ve.kind,file:ve.file,displayName:ve.displayName,canEditHere:ve.canEditHere})),confidence:pe.confidence,editMode:pe.editMode,diagnostics:pe.diagnostics.map(ve=>({code:ve.code,message:ve.message}))}}}F.set(J,{textSources:ue,textTargets:X,elementPropertyTargets:G,provenances:w,writeTarget:we,componentSemantic:Re,contentModel:Se,mediaModel:vr,styleSource:Cr,conditional:Ae,dynamicData:sn})}return F}function Z(f){return typeof n.getVersion=="function"?n.getVersion(f):0}function xe(f,y){let g=1;for(let I of y.values())g=Math.max(g,I);return Math.max(g,f.graph?.version??0)}async function W(f,y,g={}){let I=o.get(f);if(!I)return null;let R=g.sourceCache??da(d,[]),F=await q(I.entryFile),{graph:j,allSources:_,diagnostics:N,parsedModules:J,entryModule:Y}=await bc(I.entryFile,y,Ae=>n.readFile(Ae),typeof n.exists=="function"?Ae=>n.exists(Ae):async()=>!1,{additionalEntries:F,version:I.graph?.version??1});if(N.length>0)throw new ur(N);let ne=new Map;for(let Ae of _.keys())ne.set(Ae,Z(Ae));let ie=Math.max(xe(I,ne),g.minimumVersion??0,p);g.changed&&ie<=(I.graph?.version??0)&&(ie=(I.graph?.version??0)+1),j.version=ie;for(let[Ae,_n]of _)fa(R,Ae,_n,Of);let ue=await ge(I.entryFile,_,R);j.routeId=f;let X=Ic(j),w=vc(X,j),U=await ee(j,X,_,R,J),G=Cp(j,w,U),we=vp(U),Re=TI(Sl(j,X,w,{canUpdateTextByKey:G,dynamicDataSummaryByKey:we}),j,U),Se=fl({route:f,entryFile:I.entryFile,version:ie,source:y,ast:Y?.ast}),vr=pl(Se);Se.ok&&SI(Re,j,Se.projection);let Cr={...Re,...ue?{styleContext:ue}:{},pageComposition:vr},sn=new Set([I.entryFile,..._.keys()]);if(ue){sn.add(ue.entryCss.path);for(let Ae of ue.stylesheets)sn.add(Ae.path)}let Lt={...I,dependencyFiles:sn,graph:j,topology:X,capabilities:w,document:Cr,pageComposition:vr,pageCompositionProjection:Se.projection,pagePlacementByKey:Se.ok?Se.projection.placementByKey:null,pagePlacementUnitByKey:Se.ok?Se.projection.placementUnitByKey:null,pageUnitByKey:Se.ok?Se.projection.unitByKey:null,pagePlacementsByUnitKey:Se.ok?Se.projection.placementsByUnitKey:null,documentIndex:cI(Cr),detailProjections:U,fileVersions:ne,styleContext:ue};if(g.publish===!1)return Lt;Tn(d,R);for(let Ae of R.keys())m.delete(Ae);return p=Math.max(p,ie),A(I,sn),Object.assign(I,Lt),I}async function q(f){let y=[];for(let g of vI(f))typeof n.exists=="function"&&await n.exists(g)&&y.push({file:g,source:await n.readFile(g)});return y}async function ge(f,y,g){let I=[];for(let[N,J]of y){if(ha(N)){I.push(N);continue}for(let Y of RI(J)){let ne=Kf(N,Y);ne&&I.push(ne)}}if(!I.length){for(let N of CI(f))if(await ut(N)){I.push(N);break}}let R=new Map,F=Wf(I).slice(0,Mf);for(;F.length>0&&R.size<Mf;){let N=F.shift();if(R.has(N)||!ha(N))continue;let J=await xt(N,g);if(J!==null){R.set(N,{path:N,content:J});for(let Y of PI(J)){let ne=Kf(N,Y);ne&&!R.has(ne)&&!F.includes(ne)&&F.push(ne)}}}let j=[...R.values()].map(N=>({...N,hash:le(N.content)})),_=j[0];return _?{revision:le(JSON.stringify(j.map(({path:N,hash:J})=>({path:N,hash:J})))),entryCss:_,stylesheets:j.slice(1)}:null}async function xt(f,y){let g=y.get(f);if(g!==void 0)return g;if(!await ut(f))return null;let I=await n.readFile(f);return fa(y,f,I,Of),I}async function ut(f){return typeof n.exists=="function"?n.exists(f):!1}function vp(f){let y=new Map;for(let[g,I]of f)I.dynamicData?.bindings.length&&y.set(g,Od(I.dynamicData.bindings));return y}function Cp(f,y,g){let I=new Map;for(let[R,F]of f.elements){if(!y.get(R)?.canUpdateText){I.set(R,!1);continue}let _=g.get(R),N=F.textSegments.some(J=>{if(!J.editable)return!1;let Y=_?.provenances.get(J.index)??null;return!Y||Rp(Y)});I.set(R,N)}return I}function Rp(f){return f.editMode==="direct"||f.editMode==="proxy"||f.editMode==="upstream"}async function br(f,y={}){let g=[...new Set(f)],I=O(g);if(I.size===0||!L(g))for(let _ of o.values())za(_,g)&&I.add(_.routeId);let R=I.size===0&&g.some(Vf),F=y.publish===!1?da(d,g):void 0,j={rebuiltRoutes:[],failedRoutes:[],...y.publish===!1?{candidateRouteStates:[],candidateSourceCache:F}:{}};for(let _ of o.values())if(!(y.excludedRouteIds?.has(_.routeId)||!(I.has(_.routeId)||R)))try{let J=!!_.graph,Y=await n.readFile(_.entryFile),ne=await W(_.routeId,Y,{...y,...F?{sourceCache:F}:{}});ne?.graph&&(j.rebuiltRoutes.push({documentChanged:J,routeId:_.routeId,version:ne.graph.version}),j.candidateRouteStates?.push({routeId:_.routeId,state:ne}))}catch(J){j.failedRoutes.push(Ff(_.routeId,J))}return j}function Xa(f){let y=[...new Set(f)],g=O(y);if(g.size>0&&L(y))return[...g];for(let I of o.values())za(I,y)&&g.add(I.routeId);return[...g]}function Wo(f,y){r.emit({type:"operation-completed",result:f});for(let{routeId:g,version:I}of y.rebuiltRoutes)r.emit({type:"document-changed",routeId:g,version:I});for(let{routeId:g,message:I}of y.failedRoutes)r.emit({type:"graph-error",routeId:g,message:I})}function za(f,y){return y.some(g=>f.dependencyFiles.has(g)||f.entryFile===g||f.graph?.fileIndex.has(g))}function Ha(f){for(let y of f)a.add(y);c||te()||(c=(async()=>{t="building";let y=!1;try{for(;a.size>0;){if(te())return;await Pp();let g=[...a];a.clear();let I=await Wa(g);if(I.length===0)continue;let R=Xa(I);for(let _ of R)r.emit({type:"graph-invalidated",routeId:_});let{rebuiltRoutes:F,failedRoutes:j}=await br(I,{changed:!0});for(let{documentChanged:_,routeId:N,version:J}of F)r.emit({type:"graph-ready",routeId:N,version:J}),_&&r.emit({type:"document-changed",routeId:N,version:J});for(let{routeId:_,message:N}of j)y=!0,r.emit({type:"graph-error",routeId:_,message:N})}}finally{if(c=null,t!=="disposed"){let g=s?o.get(s):null;t=!y&&g?.graph?"ready":"idle"}a.size>0&&Ha([])}})())}async function Pp(){for(;h>0;)await new Promise(f=>setTimeout(f,0))}async function Wa(f){let y=[];for(let g of new Set(f)){let I=d.get(g);if(I===void 0){if(m.has(g)&&!await n.exists(g))continue;m.delete(g),y.push(g);continue}try{await n.readFile(g)!==I&&(m.delete(g),y.push(g))}catch(R){if(!EI(R))try{if(await n.exists(g))continue}catch{continue}m.add(g),y.push(g)}}return y}function Ga(f){Tf(d,f);for(let y of f)y.exists===!1?m.add(y.file):m.delete(y.file)}function Ya(f){m.clear();for(let y of f)m.add(y)}async function Za(f){let y=await Wa(f);if(y.length===0)return;let g=Xa(y);for(let F of g)r.emit({type:"graph-invalidated",routeId:F});let{rebuiltRoutes:I,failedRoutes:R}=await br(y,{changed:!0});for(let{documentChanged:F,routeId:j,version:_}of I)r.emit({type:"graph-ready",routeId:j,version:_}),F&&r.emit({type:"document-changed",routeId:j,version:_});for(let{routeId:F,message:j}of R)r.emit({type:"graph-error",routeId:F,message:j})}async function wp(f,y){let g=Fn(f,y);if(!g?.graph)return;let I=ze(f)??f,R=g.graph.elements.get(I);R&&await Za([R.sourceFile])}async function Qa(f){let y=new Set;if(f.target.kind==="node"){let g=Fn(f.target.key,f.routeId),I=ze(f.target.key)??f.target.key,R=g?.graph?.elements.get(I);R&&y.add(R.sourceFile)}else if(f.target.kind==="route"){let g=o.get(f.target.routeId);g&&y.add(g.entryFile)}else if(f.target.kind==="page-unit"){let g=o.get(f.target.routeId);g&&y.add(g.entryFile)}else if(f.target.kind==="source-file")y.add(f.target.path);else if(f.target.kind==="source-batch")for(let g of f.target.paths)y.add(g);await Za(y)}async function Ap(f){if(f.params.kind!=="source-edit")return Go(f,"invalid-params","source-edit requires source-edit params");for(let y of f.params.edits){let g=xI(y);if(!g.ok)return Go(f,g.errorCode,g.message,g.details)}h+=1;try{let y=await Op(f.params.edits);if(!y.ok)return Go(f,y.errorCode,y.message,y.details);await Qa(f);let g={operationId:f.id,kind:"source-edit",target:f.target,documentVersion:f.documentVersion,conflictPolicy:f.params.conflictPolicy,edits:f.params.edits.map(I=>I.operation==="delete"?{operation:"delete",file:I.path,baseContentHash:I.baseContentHash??null}:{operation:"upsert",file:I.path,baseContentHash:I.baseContentHash??null,content:I.content})};return await on({request:f,filePlan:g})}catch(y){return{requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:p,error:{code:M.INTERNAL_ERROR,message:Ne(y)}}}finally{h-=1}}async function Tp(f){if(f.target.kind!=="project"||f.params.kind!=="insert-page-resource")return Q(f,M.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");h+=1;try{let y=await aa({files:[...f.params.artifact.components.flatMap(I=>I.materialization.files.map(R=>({path:R.pathTemplate,content:R.content}))),...f.params.artifact.pages.flatMap(I=>I.materialization.files.map(R=>({path:R.pathTemplate,content:R.content})))],exists:I=>n.exists(I),readFile:I=>n.readFile(I)});if(!y.ok)return Q(f,M.MATERIALIZATION_REJECTED,y.message);let g=await ia({artifact:f.params.artifact,exists:I=>n.exists(I)});return g.ok?await on({request:f,filePlan:{operationId:f.id,kind:"source-edit",target:f.target,documentVersion:f.documentVersion,conflictPolicy:"overwrite",edits:g.files},output:{kind:"insert-page-resource",package_instance_id:g.packageInstanceId,pages:g.pages},historyPolicy:"none"}):Q(f,g.code==="MATERIALIZATION_CONFLICT"?M.MATERIALIZATION_CONFLICT:M.MATERIALIZATION_REJECTED,g.message,g.path?{path:g.path}:void 0)}catch(y){return Q(f,M.INTERNAL_ERROR,Ne(y))}finally{h-=1}}async function Np(f){if(f.target.kind!=="project"||f.params.kind!=="delete-page-source")return Q(f,M.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return Q(f,M.PLAN_FAILED,"Complete project file listing is required for page deletion.");h+=1;try{let y=Xf(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(y.truncated)return Q(f,M.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:y.truncated.reasons});let g=y.files.filter(({path:j})=>/\.(?:tsx?|jsx?)$/.test(j)),I=Object.fromEntries(await Promise.all(g.map(async({path:j})=>[j,await n.readFile(j)]))),R=xf({expectedUrlPath:f.params.expectedUrlPath,files:I});if(!R.ok)return Q(f,R.code==="HOME_PAGE_LOCKED"?M.HOME_PAGE_LOCKED:R.code==="ROUTE_NOT_FOUND"?M.ROUTE_NOT_FOUND:M.PLAN_FAILED,R.message);let F=await Promise.all(R.edits.map(async j=>({...j,baseContentHash:le(await n.readFile(j.file))})));return on({request:f,filePlan:{operationId:f.id,kind:"source-edit",target:f.target,documentVersion:f.documentVersion,conflictPolicy:"compare-and-swap",edits:F},output:{kind:"delete-page-source",deleted_files:R.deletedFiles,updated_files:R.updatedFiles,preserved_shared_files:R.preservedSharedFiles,warnings:R.warnings},historyPolicy:"none"})}catch(y){return Q(f,M.INTERNAL_ERROR,Ne(y))}finally{h-=1}}async function Fp(f,y){if(f.kind!=="insert-child"||f.params.kind!=="insert-child")return Q(f,M.UNSUPPORTED_OPERATION,"Only page-unit insert-child is currently supported by the page composition transaction.");if(!("kind"in f.params.position)||f.params.position.kind!=="page-composition")return Q(f,M.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(f.params.position.documentVersion!==f.documentVersion)return Q(f,M.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.");let g=y.document,I=y.pageCompositionProjection;if(!g||g.pageComposition?.status!=="supported"||!I||I.status!=="supported")return Q(f,M.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(f.documentVersion!==g.version||I.documentVersion!==g.version)return Q(f,M.VERSION_STALE,`Document version ${f.documentVersion} is stale (current: ${g.version}).`);let R=f.params.node.kind==="component-call"?f.params.node.materialization:void 0;if(!R)return Q(f,M.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let F=f.params.position,j=await aa({files:R.files.map(N=>({path:N.pathTemplate,content:N.content})),exists:N=>n.exists(N),readFile:N=>n.readFile(N)});if(!j.ok)return Q(f,M.MATERIALIZATION_REJECTED,j.message);let _=await tf({manifest:R,generatedRoot:"components/site/generated",controlledFiles:R.files.map(N=>({pathTemplate:N.pathTemplate})),exists:N=>n.exists(N),commit:async N=>{let J=await n.readFile(y.entryFile),Y=y.document,ne=y.pageCompositionProjection;if(!Y||Y.pageComposition?.status!=="supported"||Y.version!==f.documentVersion||!ne||ne.status!=="supported"||ne.documentVersion!==Y.version)return{ok:!0,data:Q(f,M.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let ie=N.entry.path,ue=Vp(N.instanceName),X=Li({routeId:y.routeId,entryFile:y.entryFile,currentDocumentVersion:Y.version,expectedDocumentVersion:f.documentVersion,source:J,projection:ne,placementKey:F.placementKey,component:{source:ie,exportName:N.entry.export.kind==="default"?"default":N.entry.export.name,localName:ue}});if(!X.ok)return{ok:!0,data:Q(f,sc(X.error.code),X.error.message,{diagnostics:X.error.diagnostics})};let w=X.plan.returnStep?al({source:J,jsx:X.plan.returnStep.node.jsx,placement:X.plan.returnStep.placement,...X.plan.returnStep.replaceOriginal?{replaceOriginal:!0}:{}}):X.plan.insertStep?.parentLocator?yn({source:J,locator:X.plan.insertStep.parentLocator,node:X.plan.insertStep.node,placement:X.plan.insertStep.placement,...X.plan.insertStep.anchorLocator?{anchorLocator:X.plan.insertStep.anchorLocator}:{}}):{ok:!1,source:J,diagnostic:{code:"unsupported-syntax",message:"Route composition rewrite has no insertion step."}};if(!w.ok)return{ok:!0,data:Q(f,M.AST_PARSE_ERROR,w.diagnostic.message)};let U=Sn({source:w.source,moduleSpecifier:X.plan.importStep.moduleSpecifier,imports:X.plan.importStep.imports});if(!U.ok)return{ok:!0,data:Q(f,M.AST_PARSE_ERROR,U.diagnostic.message)};let G=N.files.map(Re=>({operation:"create-only",file:Re.path,content:Re.content})),we=[{operation:"upsert",file:y.entryFile,content:U.source,baseContentHash:le(J)},...G];h+=1;try{let Re=await on({request:f,filePlan:{operationId:f.id,kind:"source-edit",target:{kind:"source-file",path:y.entryFile},documentVersion:f.documentVersion,conflictPolicy:"compare-and-swap",edits:we}});return!Re.ok&&Re.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:Re.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:Re}}finally{h-=1}}});return _.ok?_.data:Q(f,M.VERSION_STALE,_.error.message,{materializationCode:_.error.code})}async function _p(f,y){if(f.kind!=="move-node"&&f.kind!=="remove-node")return Q(f,M.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let g=y.document,I=y.pageCompositionProjection;if(!g||g.pageComposition?.status!=="supported"||!I||I.status!=="supported")return Q(f,M.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(f.documentVersion!==g.version||I.documentVersion!==g.version)return Q(f,M.VERSION_STALE,`Document version ${f.documentVersion} is stale (current: ${g.version}).`);let R=await n.readFile(y.entryFile),F=cl({routeId:y.routeId,entryFile:y.entryFile,currentDocumentVersion:g.version,expectedDocumentVersion:f.documentVersion,source:R,projection:I,placementUnitKey:f.target.placementUnitKey,operation:f.kind,targetPlacement:f.kind==="move-node"&&f.params.kind==="move-node"&&"kind"in f.params.target&&f.params.target.kind==="page-composition"?f.params.target:void 0});if(!F.ok)return Q(f,sc(F.error.code),F.error.message,{diagnostics:F.error.diagnostics});let j=F.plan.rewriteStep.kind==="move-node"?En({source:R,locator:F.plan.rewriteStep.locator,targetParentLocator:F.plan.rewriteStep.targetParentLocator,placement:F.plan.rewriteStep.placement,...F.plan.rewriteStep.anchorLocator?{anchorLocator:F.plan.rewriteStep.anchorLocator}:{}}):hn({source:R,locator:F.plan.rewriteStep.locator});if(!j.ok)return Q(f,M.AST_PARSE_ERROR,j.diagnostic.message);let _=j.source,N=[];if(f.kind==="remove-node"){let Y=await Mp({routeState:y,placementUnitKey:f.target.placementUnitKey,source:R,mutatedSource:_});_=Y.source,N=await Promise.all(Y.files.map(async ne=>({operation:"delete",file:ne,baseContentHash:le(await n.readFile(ne))})))}let J=[{operation:"upsert",file:y.entryFile,content:_,baseContentHash:le(R)},...N];h+=1;try{return await on({request:f,filePlan:{operationId:f.id,kind:"source-edit",target:{kind:"source-file",path:y.entryFile},documentVersion:f.documentVersion,conflictPolicy:"compare-and-swap",edits:J}})}finally{h-=1}}async function Mp(f){let y={source:f.mutatedSource,files:[]},g=f.routeState.graph,I=f.routeState.pageCompositionProjection;if(!g||!I||I.status!=="supported"||!n.listFiles)return y;let F=I.placementUnitByKey.get(f.placementUnitKey)?.sourceRange;if(!F)return y;let j=[...g.elements.values()].find(G=>G.sourceFile===f.routeState.entryFile&&G.importedFrom&&$(G.sourceRange,F));if(!j?.importedFrom||!j.exportName)return y;let _=T(j.importedFrom),N="components/site/generated/";if(!_.startsWith(N))return y;let J=_.slice(N.length).split("/")[0];if(!J||!/-[0-9a-f]{8}$/i.test(J))return y;let Y=`${N}${J}`;if([...g.elements.values()].filter(G=>G.sourceFile===f.routeState.entryFile&&T(G.importedFrom??"")===_).length!==1)return y;let ie=await n.listFiles({maxFiles:5e3,maxDepth:32}),ue=Array.isArray(ie)?ie:ie.files;if(!Array.isArray(ie)&&ie.truncated)return y;let X=ue.map(({path:G})=>G).filter(G=>G===Y||G.startsWith(`${Y}/`));if(X.length===0||!X.includes(_))return y;for(let{path:G}of ue)if(!(G===f.routeState.entryFile||G===Y||G.startsWith(`${Y}/`)))try{if((await n.readFile(G)).includes(J))return y}catch{return y}let w=P(f.routeState.entryFile,_),U=bn({source:f.mutatedSource,moduleSpecifier:w,imports:j.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:j.exportName}]});return U.ok?{source:U.source,files:X.sort((G,we)=>G.localeCompare(we))}:y}async function Op(f){if(n.getFileInfo){for(let R of f)if(await n.exists(R.path)&&await n.getFileInfo(R.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${R.path}`,details:{path:R.path}}}let y=Dp(f);if(y.length===0)return{ok:!0};let g=gI(n,f),I=fr({projectRoot:e.projectRoot,fileSystem:g,routes:[...o.values()].map(R=>({routeId:R.routeId,entryFile:R.entryFile})),externalAdapters:e.externalAdapters,externalSourceResolvers:e.externalSourceResolvers,functionCallContracts:e.functionCallContracts,dev:e.dev});try{for(let R of y)await I.setActiveRoute(R)}catch(R){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${Ne(R)}`,details:{routeIds:y}}}finally{I.dispose()}return{ok:!0}}function Dp(f){return f.map(g=>g.path).some(Vf)?[...o.keys()]:[]}function Go(f,y,g,I){let R=dr(y);return{requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:p,error:{code:R,message:g,...I?{details:I}:{}}}}async function Yo(f){let y=[];for(let g of new Set(f))y.push(await Lp(g));return y}async function Lp(f){if(!(typeof n.exists=="function"?await n.exists(f):!0))return{file:f,content:"",version:Math.max(0,Z(f)),exists:!1};let g=await n.readFile(f);return{file:f,content:g,version:Math.max(1,Z(f)),exists:!0,sha256:le(g)}}async function qa(f,y,g,I){if(!e.historyStore)return null;let R=new Map(y.map(_=>[_.file,_])),F=new Map(g.map(_=>[_.file,_])),j=[...new Set([...R.keys(),...F.keys()])].sort().map(_=>{let N=R.get(_),J=F.get(_);return{path:_,preDigest:N?.exists===!1||!N?null:le(N.content),postDigest:J?.exists===!1||!J?null:le(J.content)}});return{schemaVersion:2,transactionId:`${f}:${I.expectedIndexDigest}`,operationId:f,phase:"prepared",historyTransition:I,files:j}}async function ec(f){return!f||!e.historyStore||await e.historyStore.writeTransactionJournal(f),f}async function rn(f){f&&e.historyStore&&await e.historyStore.clearTransactionJournal(f.transactionId)}async function Zo(f,y){let g=[];try{for(let I of f)await tc(I),typeof n.bumpVersion=="function"&&n.bumpVersion(I.file),g.push(I.file)}catch(I){let R=await jp(y.filter(F=>g.includes(F.file)));return R.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${Ne(I)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${R.failedFiles.join(", ")}: ${Ne(I)}`,rolledBack:!1}}return{ok:!0,snapshots:f.map($p)}}async function tc(f){if(f.exists===!1){await n.deleteFile(f.file);return}await n.writeFile(f.file,f.content)}async function jp(f){let y=[];for(let g of f)try{await tc(g),typeof n.bumpVersion=="function"&&n.bumpVersion(g.file)}catch{y.push(g.file)}return y.length===0?{ok:!0}:{ok:!1,failedFiles:y}}function $p(f){let y=f.exists!==!1;return{file:f.file,content:y?f.content:"",version:f.version,exists:y,...y?{sha256:le(f.content)}:{}}}async function on(f){return C.runExclusive(()=>Bp(f))}async function Bp(f){let y=f.filePlan.edits.map(w=>w.file),g=await Yo(y),I=new Map(g.filter(w=>w.exists!==!1).map(w=>[w.file,w.content])),R=p,F=rc(),j=new Map(d),_=new Set(m),N=new Set([...o.values()].filter(w=>f.filePlan.edits.some(U=>U.operation==="delete"&&U.file===w.entryFile)).map(w=>w.routeId)),J=f.filePlan.edits.map(w=>w.operation==="delete"?{file:w.file,content:"",version:0,exists:!1}:{file:w.file,content:w.content,version:0,exists:!0,sha256:le(w.content)}),Y={operationId:f.filePlan.operationId,intents:f.filePlan.edits.map(w=>w.operation==="delete"?{kind:"delete",path:w.file}:{kind:w.operation==="create-only"?"create-only":"upsert",path:w.file,content:w.content})},ne=null,ie=!1,ue=await Ao({overlay:I,exists:w=>n.exists(w),plan:Y,buildCandidate:async({plan:w})=>({plan:w}),prepareHistory:async()=>{let w=f.historyPolicy==="none"?null:await l.prepareAppend({operationId:f.request.id,kind:f.request.kind,target:f.request.target,preSnapshots:g,postSnapshots:J,...f.selectionRef?{selectionRef:f.selectionRef}:{},...f.output?{output:f.output}:{}}),U=w?.historyTransition?w.historyTransition:e.historyStore?rI(await e.historyStore.readIndex()):null;if(e.historyStore&&!U)throw new Error("Durable history did not provide an exact index transition.");return ne=await qa(f.request.id,g,J,U),ne=await ec(ne),{history:w,historyTransition:U}},reverify:async()=>{},writeCandidate:async()=>{let w=await u.executeFilePlan(f.filePlan);if(!w.ok)throw new Fo(w);return{postSnapshots:await Yo(w.affectedFiles),affectedFiles:w.affectedFiles,internalResultVersion:w.resultVersion}},validateCandidate:async({candidate:w,receipt:U})=>{let G=await br(U.affectedFiles,{changed:!0,minimumVersion:U.internalResultVersion,publish:!1,excludedRouteIds:N});if(G.failedRoutes.length>0)throw new tn(G.failedRoutes);let we=oc(F,G.candidateRouteStates??[]),Re=Math.max(U.internalResultVersion,...G.rebuiltRoutes.map(Se=>Se.version));return{...w,rebuild:G,routeSnapshots:we,resultVersion:Re,...$f(f.selectionRef,we.map(Se=>Se.state.document))?{selectionRef:$f(f.selectionRef,we.map(Se=>Se.state.document))}:{}}},publishCandidate:async({candidate:w,history:U,receipt:G})=>{U?.history&&(await l.publishPrepared(U.history),ie=!0);let we=w.resultVersion??G.internalResultVersion;return{requestId:f.request.id,kind:f.request.kind,target:f.request.target,ok:!0,resultVersion:we,affectedFiles:G.affectedFiles,...f.output?{output:f.output}:{},...w.selectionRef?{selectionRef:w.selectionRef}:{}}},swapCandidate:({candidate:w,receipt:U})=>{w.routeSnapshots&&Ir(w.routeSnapshots),w.rebuild?.candidateSourceCache&&Tn(d,w.rebuild.candidateSourceCache),Ga(U.postSnapshots),p=Math.max(p,w.resultVersion??R)},finalizeCandidate:async()=>{await rn(ne);for(let w of N)o.delete(w)},emitCommitted:({candidate:w,published:U})=>{Wo(U,w.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:w,receipt:U})=>{if(ie)throw new Error("history was published before transaction finalization failed");if(U){let G=await Zo(g,U.postSnapshots);if(!G.ok)throw new Error(G.reason)}Ir(F),Tn(d,j),Ya(_),p=R,w?.history&&await l.discardPrepared?.(w.history),await rn(ne)}});if(ue.ok)return ue.published;if(ue.stage==="precheck"||ue.stage==="build")try{await rn(ne)}catch(w){let U=await kr(Ne(w));return Q(f.request,U,"Unable to clear an uncommitted transaction journal.")}if(ue.recoveryRequired){let w=await kr(ue.reason);return Q(f.request,w===M.RECOVERY_PERSIST_FAILED?w:M.ROLLBACK_FAILED,ue.reason)}let X=ue.error;return X instanceof Fo?{...Q(f.request,dr(X.result.errorCode),X.result.reason),...X.result.affectedFiles?{affectedFiles:X.result.affectedFiles}:{}}:X instanceof tn?Q(f.request,M.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${pa(X.failedRoutes)}`,{failedRoutes:X.failedRoutes}):Q(f.request,ic(ue.stage),Ne(X))}async function nc(f){return C.runExclusive(async()=>{let y=f==="undo"?await l.prepareUndo():await l.prepareRedo();return y?Up(f,y):{requestId:f,kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:p,error:{code:M.INTERNAL_ERROR,message:f==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function Up(f,y){let g=y.entry,I=f==="undo"?g.preSnapshots:g.postSnapshots,R=f==="undo"?g.postSnapshots:g.preSnapshots,F=I.map(w=>w.file),j=await Yo(F),_=new Map(j.filter(w=>w.exists!==!1).map(w=>[w.file,w.content])),N=p,J=rc(),Y=new Map(d),ne=new Set(m),ie=null,ue=!1,X=await Ao({overlay:_,plan:{operationId:`${f}:${g.operationId}`,intents:I.map(w=>w.exists===!1?{kind:"delete",path:w.file}:{kind:"upsert",path:w.file,content:w.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(ie=await qa(`${f}:${g.operationId}`,j,I,y.historyTransition),ie=await ec(ie),y),reverify:async()=>{},writeCandidate:async()=>{let w=await Zo(I,R);if(!w.ok)throw new Error(w.reason);return{snapshots:w.snapshots}},validateCandidate:async({candidate:w})=>{let U=await br(F,{changed:!0,minimumVersion:p+1,publish:!1});if(U.failedRoutes.length>0)throw new tn(U.failedRoutes);let G=oc(J,U.candidateRouteStates??[]),we=Math.max(p+1,...U.rebuiltRoutes.map(Re=>Re.version));return{...w,rebuild:U,routeSnapshots:G,resultVersion:we}},publishCandidate:async({candidate:w,history:U})=>{if(!U)throw new Error("history cursor intent is missing");await l.publishPrepared(U),ue=!0;let G=w.resultVersion??p+1;return{requestId:f,kind:g.kind,target:g.target,ok:!0,resultVersion:G,affectedFiles:F,...g.output?{output:g.output}:{}}},swapCandidate:({candidate:w,receipt:U})=>{w.routeSnapshots&&Ir(w.routeSnapshots),w.rebuild?.candidateSourceCache&&Tn(d,w.rebuild.candidateSourceCache),Ga(U.snapshots),p=Math.max(p,w.resultVersion??N)},finalizeCandidate:async()=>{await rn(ie)},emitCommitted:({candidate:w,published:U})=>Wo(U,w.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:w,receipt:U})=>{if(ue)throw new Error("history cursor was published before transaction finalization failed");if(U){let G=await Zo(R,U.snapshots);if(!G.ok)throw new Error(G.reason)}Ir(J),Tn(d,Y),Ya(ne),p=N,w&&await l.discardPrepared?.(w),await rn(ie)}});if(X.ok)return X.published;if(X.stage==="precheck"||X.stage==="build")try{await rn(ie)}catch(w){let U=await kr(Ne(w));return{requestId:f,kind:g.kind,target:g.target,ok:!1,resultVersion:p,error:{code:U,message:"Unable to clear an uncommitted transaction journal."}}}if(X.recoveryRequired){let w=await kr(X.reason);return{requestId:f,kind:g.kind,target:g.target,ok:!1,resultVersion:p,affectedFiles:F,error:{code:w===M.RECOVERY_PERSIST_FAILED?w:M.ROLLBACK_FAILED,message:X.reason}}}return{requestId:f,kind:g.kind,target:g.target,ok:!1,resultVersion:p,affectedFiles:F,error:{code:X.error instanceof tn?M.ROUTE_REBUILD_FAILED:ic(X.stage),message:Ne(X.error),...X.error instanceof tn?{details:{failedRoutes:X.error.failedRoutes}}:{}}}}function rc(){return[...o.values()].map(f=>({routeId:f.routeId,state:{...f,dependencyFiles:new Set(f.dependencyFiles),fileVersions:new Map(f.fileVersions)}}))}function oc(f,y){let g=new Map(f.map(I=>[I.routeId,I]));for(let I of y)g.set(I.routeId,I);return[...g.values()]}function Ir(f){for(let y of o.values())D(y);for(let y of f){let g={...y.state,dependencyFiles:new Set(y.state.dependencyFiles),fileVersions:new Map(y.state.fileVersions)};o.set(y.routeId,g),A(g,g.dependencyFiles)}}async function Qo(f){let y=o.get(f);if(!y)throw new Error(`Route not found: ${f}`);if(y.graph)return;let g=await n.readFile(y.entryFile);await W(f,g)}function Fn(f,y){if(y){let g=o.get(y)??null;return!g||!qo(g,f)?null:g}for(let g of o.values())if(qo(g,f))return g;return null}function qo(f,y){if(f.documentIndex?.entriesByKey.has(y)||f.graph?.elements.has(y))return!0;let g=ze(y);return g&&g!==y?f.graph?.elements.has(g)===!0:!1}function Q(f,y,g,I){return{requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:p,error:{code:y,message:g,...I?{details:I}:{}}}}function ic(f){return f==="validate"?M.ROUTE_REBUILD_FAILED:f==="publish"?M.HISTORY_COMMIT_FAILED:M.WRITE_IO_ERROR}async function kr(f){if(E=!0,!l.markRecoveryRequired)return M.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(f),M.RECOVERY_REQUIRED}catch{return M.RECOVERY_PERSIST_FAILED}}function Vp(f){let g=f.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(I=>I.charAt(0).toUpperCase()+I.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return g?`Prefab${g}`:"GeneratedPrefab"}function sc(f){return f==="VERSION_STALE"?M.VERSION_STALE:f==="CROSS_PAGE_MOVE_UNSUPPORTED"?M.CROSS_PAGE_MOVE_UNSUPPORTED:M.UNSUPPORTED_OPERATION}async function ac(f){if(f.target.kind==="route"){let g=o.get(f.target.routeId)??null;return g?(g.graph||await Qo(g.routeId),g):Q(f,M.ROUTE_NOT_FOUND,`Route not found: ${f.target.routeId}`)}if(f.target.kind==="page-unit"){let g=o.get(f.target.routeId)??null;return g?(g.graph||await Qo(g.routeId),g):Q(f,M.ROUTE_NOT_FOUND,`Route not found: ${f.target.routeId}`)}if(f.target.kind!=="node")return Q(f,M.UNSUPPORTED_OPERATION,`${f.kind} source target execution is not implemented yet.`);if(!f.routeId)return Q(f,M.INVALID_TARGET,"routeId is required when executing a node target");let y=o.get(f.routeId)??null;return y?(y.graph||await Qo(y.routeId),qo(y,f.target.key)?y:Q(f,M.NODE_NOT_FOUND,`Target key not found: ${f.target.key}`)):Q(f,M.ROUTE_NOT_FOUND,`Route not found: ${f.routeId}`)}return{get status(){return t},dispose(){t="disposed",a.clear(),o.clear(),i.clear(),d.clear(),m.clear(),s=null},registerRoute(f,y){let g=o.get(f);if(g?.entryFile===y)return;g&&D(g);let I=jf(f,y);o.set(f,I),A(I,I.dependencyFiles),r.emit({type:"graph-invalidated",routeId:f})},unregisterRoute(f){let y=o.get(f);y&&(D(y),o.delete(f),s===f&&(s=null,t="idle"),r.emit({type:"graph-invalidated",routeId:f}))},getRouteEntryFiles(){return[...o.values()].map(f=>f.entryFile)},async setActiveRoute(f){let y=o.get(f);if(!y)throw new Error(`Route not found: ${f}`);let g=s===f;if(s=f,!y.graph){t="building";try{let I=await n.readFile(y.entryFile);await W(f,I);let R=o.get(f)?.graph?.version??1;t="ready",r.emit({type:"graph-ready",routeId:f,version:R})}catch(I){throw t="idle",r.emit({type:"graph-error",routeId:f,message:Ne(I)}),I}return}t="ready",g||r.emit({type:"graph-ready",routeId:f,version:y.graph.version})},getDocument(f){let y=o.get(f);if(!y)throw new Error(`Route not found: ${f}`);if(!y.document)throw new Error(`Route not built: ${f}`);return y.document},async getHistoryStatus(){await v;let f=await l.getStatus?.();return f?{...f,recoveryRequired:E}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:E}},getObjectEditContext(f,y){let g=Fn(f,y),I=ze(f)??f;if(g?.graph&&g.topology&&g.capabilities&&g.detailProjections){let R=g.detailProjections.get(I);if(R){let F=Il(I,g.graph,g.topology,g.capabilities,R.textSources,R.provenances,R.dynamicData);return f===I?F:DI(F,f,g.document??null,g.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${f}`)},getRenderDetail(f,y){let g=Fn(f,y),I=ze(f)??f;if(g?.graph&&g.topology&&g.capabilities&&g.detailProjections){let R=g.detailProjections.get(I);if(R){let F=bl(I,g.graph,g.topology,g.capabilities,R.textSources,R.writeTarget,R.provenances,R.conditional,R.componentSemantic,R.contentModel,R.mediaModel,R.styleSource,R.dynamicData);return f===I?F:OI(F,f,g.document??null,g.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${f}`)},getClassNameSource(f,y){let g=Fn(f,y),I=ze(f)??f;if(!g?.graph)throw new Error(`Key not found: ${f}`);let R=g.graph.elements.get(I);if(!R)throw new Error(`Key not found: ${f}`);let F=d.get(R.sourceFile);if(F===void 0)throw new Error(`Source not loaded: ${R.sourceFile}`);return $l({key:I,route:{routeId:g.routeId,graph:g.graph,source:F}})},refreshSourceForKey:wp,async execute(f){if(await v,E)return Q(f,M.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(f.kind==="source-edit")return Ap(f);if(f.kind==="insert-page-resource")return Tp(f);if(f.kind==="delete-page-source")return Np(f);let y=await ac(f);if("ok"in y)return y;await Qa(f);let g=await ac(f);if("ok"in g)return g;let I=g;if(f.target.kind==="page-unit"){let _=f;return f.kind==="insert-child"?Fp(_,I):f.kind==="move-node"||f.kind==="remove-node"?_p(_,I):Q(f,M.UNSUPPORTED_OPERATION,"Only page-unit insert-child, move-node, and remove-node are currently supported by the page composition transaction.")}if(!I.graph||!I.topology||!I.capabilities)return{requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:p,error:{code:f.target.kind==="route"?M.ROUTE_NOT_FOUND:M.NODE_NOT_FOUND,message:f.target.kind==="route"?`Route not ready: ${f.target.routeId}`:f.target.kind==="node"?`Target key not found: ${f.target.key}`:`${f.kind} source target execution is not implemented yet.`}};let R=II(I,I.graph,I.capabilities,d,o),F=await new go(R).plan(f);if(!F.ok)return{requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:p,error:{code:dr(F.errorCode),message:F.reason}};let j=F.plan;if(j.steps.length===0)return f.kind==="set-props"?{requestId:f.id,kind:f.kind,target:f.target,ok:!0,resultVersion:p,affectedFiles:[]}:{requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:p,error:{code:M.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};h+=1;try{if(j.steps.some(N=>N.type==="invoke-external-adapter")){let N=await u.execute(j);if(!N.ok)return Q(f,dr(N.errorCode),N.reason);let J={requestId:f.id,kind:f.kind,target:f.target,ok:!0,resultVersion:Math.max(p,N.resultVersion),affectedFiles:N.affectedFiles,...N.selectionRef?{selectionRef:N.selectionRef}:{}};return Wo(J,{rebuiltRoutes:[],failedRoutes:[]}),J}let _=await u.prepareRewritePlan(j);return _.ok?await on({request:f,filePlan:_.filePlan,..._.selectionRef?{selectionRef:_.selectionRef}:{}}):Q(f,dr(_.errorCode),_.reason)}catch(_){return{requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:p,error:{code:M.INTERNAL_ERROR,message:Ne(_)}}}finally{h-=1}},async undo(f){if(await v,E)return{requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:p,error:{code:M.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};h+=1;try{return await nc("undo")}finally{h-=1}},async redo(f){if(await v,E)return{requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:p,error:{code:M.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};h+=1;try{return await nc("redo")}finally{h-=1}},notifyFileChanged(f){Ha([f])},subscribe(f){return r.subscribe(f)}}}function EI(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function SI(e,t,n){let r=new Map,o=new Map;for(let s of t.elements.values()){if(s.sourceFile!==n.entryFile||!s.importedFrom||!/^[A-Z]/.test(s.tag))continue;let a=n.placements.find(l=>l.members.some(u=>u.sourceRange!==null&&ma(s.sourceRange,u.sourceRange)));if(!a)continue;let c=a.placementUnitKey;if(r.set(`${s.importedFrom}#${s.tag}`,c),s.exportName==="default"){let l=o.get(s.importedFrom)??new Set;l.add(c),o.set(s.importedFrom,l)}s.exportName&&s.exportName!=="default"&&s.exportName!==s.tag&&r.set(`${s.importedFrom}#${s.exportName}`,c)}let i=n.placements.find(s=>s.placementKey===n.container.placementKey&&s.relation==="append");for(let s of e.entries){let a=t.elements.get(s.key);if(!a)continue;if(a.sourceFile===n.entryFile){if(n.container.sourceRange&&ma(a.sourceRange,n.container.sourceRange)&&i){s.pageCompositionUnitKey=i.placementUnitKey;continue}let u=n.placements.find(d=>d.members.some(m=>m.sourceRange!==null&&(ma(a.sourceRange,m.sourceRange)||bI(m.sourceRange,a.sourceRange))));if(u){s.pageCompositionUnitKey=u.placementUnitKey;continue}}let c=r.get(`${a.sourceFile}#${a.componentName}`);if(c){s.pageCompositionUnitKey=c;continue}let l=o.get(a.sourceFile);l?.size===1&&(s.pageCompositionUnitKey=l.values().next().value)}}function ma(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function bI(e,t){return Uf(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&Uf(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function Uf(e,t,n,r){return e!==n?e-n:t-r}function II(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 m=t.elements.get(u);for(let p of m?.childKeys??[])a(p,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),m=t.elements.get(d.baseKey);return m?l(u,m):null},getChildNodes(u){let d=c(u),p=e.documentIndex?.entriesByKey.get(u)?.childKeys;if(p)return p.map(E=>{let C=ze(E)??E,v=t.elements.get(C);return v?l(E,v):null}).filter(E=>E!==null);let h=t.elements.get(d.baseKey);return h?h.childKeys.map(E=>{let C=t.elements.get(E);return C?l(E,C):null}).filter(E=>E!==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),m=n.get(d.baseKey);return m?{...m,key:u,constraints:m.constraints.map(p=>({...p})),...m.editModes?{editModes:{...m.editModes}}:{}}:{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},getEditableTextSegmentIndex(u){let d=c(u),p=e.detailProjections?.get(d.baseKey)?.textTargets.keys()?.next();return p&&!p.done?p.value:null},async getTextWriteTarget(u,d){let m=c(u);return Jf(e.detailProjections?.get(m.baseKey)?.textTargets.get(d)??null,m.repeatIndex)},async getElementPropertyWriteTarget(u,d){let m=c(u);return Jf(e.detailProjections?.get(m.baseKey)?.elementPropertyTargets.get(d)??null,m.repeatIndex)},getTextProvenance(u,d){let m=c(u);return e.detailProjections?.get(m.baseKey)?.provenances.get(d)??null}};function c(u){let d=Qb(u);return d?{baseKey:d.baseKey,repeatIndex:FI(e.document??null,u,d.baseKey,e.documentIndex)??NI(d)}:{baseKey:u,repeatIndex:null}}function l(u,d){let m=ze(u)??u,p=e.documentIndex?.entriesByKey.get(u),h=e.detailProjections?.get(m);return{key:u,file:d.sourceFile,component:d.componentName,tag:d.tag,structuralPath:d.identity.structuralPath,sourceRange:d.sourceRange,parentKey:p?.parentKey??d.parentKey??void 0,isRepeatRegion:d.boundaryKind==="repeat-region"||s.has(m),isBoundary:!1,importedFrom:d.importedFrom,exportName:d.exportName,isRepeatItemRoot:i.has(m),repeatOwnerKey:i.get(m)??s.get(m),contentModel:h?.contentModel,attributes:d.attributes?.map(E=>({name:E.name,value:E.value,source:E.source?{expression:E.source.expression,base:E.source.base,path:E.source.path.map(C=>({...C}))}:null,resolvedValue:E.resolvedValue}))}}}var kI={"stale-version":M.VERSION_STALE,"capability-denied":M.CAPABILITY_REJECTED,"invalid-params":M.INVALID_PARAMS,"locator-miss":M.LOCATOR_FAILED,"route-not-found":M.ROUTE_NOT_FOUND,"unsupported-operation":M.UNSUPPORTED_OPERATION,"invalid-target":M.INVALID_TARGET,"ast-error":M.AST_PARSE_ERROR,"writeback-failed":M.WRITE_IO_ERROR,"rollback-failed":M.RECOVERY_REQUIRED,unknown:M.INTERNAL_ERROR};function dr(e){return kI[e]}function Ne(e){return e instanceof Error&&e.message?e.message:String(e)}function Vf(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function vI(e){let t=nn(e);if(!tI.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=>nI.map(a=>`${s}/${a}`))}function CI(e){let n=nn(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function RI(e){return zf(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function PI(e){return zf(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function zf(e,t){let n=[];for(let r of e.matchAll(t)){let o=Hf(r[1]??"");o&&n.push(o)}return n}function Kf(e,t){let n=Hf(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?nn(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?nn(`${wI(e)}/${n}`):n.startsWith("/")?nn(n.slice(1)):ha(n)?nn(n):null}function Hf(e){return e.split(/[?#]/,1)[0]?.trim()??""}function ha(e){return/\.css$/i.test(e)}function wI(e){let t=nn(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function Wf(e){return Array.from(new Set(e))}function nn(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 AI(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 No(e){return e?.map(t=>({...t}))}function Jf(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=No(e.collectionPathMap?.[t])??No(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:No(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>No(o)??[])}}function TI(e,t,n){let r=new Set;for(let p of t.regions)if(p.kind==="repeat-region")for(let h of p.childKeys)r.add(h);if(r.size===0)return e;let o=new Map(e.entries.map(p=>[p.key,p])),i=[],s=new Map,a=(p,h)=>Gb(p,h),c=(p,h,E)=>{let C=o.get(p);if(!C)return a(p,E);let v=a(p,E),T={...C,key:v,parentKey:h,childKeys:[]};return i.push(T),T.childKeys=C.childKeys.flatMap(P=>l(P,E,v)),v},l=(p,h,E)=>{if(!r.has(p))return[c(p,E,h)];let C=d(p,h),v=[];for(let T=0;T<C;T+=1)v.push(c(p,E,[...h,T]));return v},u=Wf([...e.rootKeys,...e.entries.filter(p=>p.parentKey===null).map(p=>p.key)]);for(let p of u){if(!r.has(p)){c(p,null,[]);continue}let h=d(p,[]);for(let E=0;E<h;E+=1)c(p,null,[E])}return{...e,rootKeys:[...e.rootKeys],entries:i};function d(p,h){let E=new Set;for(let C of m(p)){let v=n.get(C);if(v){for(let T of[...v.textTargets.values(),...v.elementPropertyTargets.values()])if(!(T?.kind!=="value-binding"||T.sourceKind!=="repeat-template"))for(let P of _I(T))P.length<=h.length||MI(P,h)&&E.add(P[h.length])}}return E.size>0?E.size:AI(n.get(p))}function m(p){let h=s.get(p);if(h)return h;let E=[p],C=o.get(p);for(let v of C?.childKeys??[])E.push(...m(v));return s.set(p,E),E}}function NI(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function FI(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((ze(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function _I(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 MI(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 OI(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 DI(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}}import Sa from"node:path";import{TextDecoder as LI}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as Yf,SITE_EDIT_SOURCE_ALLOWED_DIRS as Zf,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as Qf,SiteEditSourceFileResponseSchema as ga,SiteEditSourceLocationSchema as jI,SiteEditSourcePathSchema as _o,SiteEditSourceTreeResponseSchema as $I,isSiteEditTextSourcePath as BI}from"@vcp-dev/contracts";var UI=[...Qf,...Yf,...Zf],ya=2e3,xa=12,Ea=24*1024*1024,Gf=512*1024,VI=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),KI={".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"},JI={".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"},XI=new LI("utf-8",{fatal:!0});async function Mo(e,t={}){let{files:n,truncated:r}=await qI(e,t),o=nk(n.map(i=>i.metadata));return $I.parse({nodes:o,defaultPath:rk(n.map(i=>i.metadata)),totalFiles:n.length,...r?{truncated:r}:{}})}async function Oo(e,t,n={}){let r=_o.parse(t.path),o=await WI(e,r,n);if(!o)throw new Error(`Source file not found: ${r}`);if(ba(r)){let s=tp(r),a=await YI(e,{path:r,sizeBytes:o.sizeBytes,mimeType:s});return ga.parse({path:r,kind:"binary",language:null,sizeBytes:o.sizeBytes,mimeType:s,readonly:!0,...a})}let i=await zI(e,r);return i.ok?ga.parse({path:r,kind:"text",language:np(r),sizeBytes:i.sizeBytes,contentHash:le(i.content),readonly:!1,content:i.content}):ga.parse({path:r,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function zI(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=HI(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 HI(e){if(e.includes(0))return null;try{return XI.decode(e)}catch{return null}}async function WI(e,t,n){if(!ZI(t,n))return null;let r=await GI(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function GI(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=qf(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(ba(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function YI(e,t){if(!VI.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>Gf)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>Gf?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function ZI(e,t){return Qf.some(n=>n===e)||Yf.some(n=>n===e)||Zf.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=_o.safeParse(n);return r.success&&r.data===e})}function Do(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return jI.parse({key:e.key,routeId:e.routeId,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 qf(e){return Array.isArray(e)?{files:e}:e}function QI(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function qI(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=qf(await e.listFiles({roots:ek(t),maxFiles:ya+1,maxDepth:xa,maxTotalBytes:Ea+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=_o.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>xa){o.add("max-depth");continue}if(r.size>=ya){o.add("max-files");break}if(i+a.sizeBytes>Ea){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:tk(l,a.sizeBytes)}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:QI([...o]),maxFiles:ya,maxDepth:xa,maxTotalBytes:Ea}}:{}}}function ek(e){let t=new Set(UI);for(let n of e.routeEntryFiles??[]){let r=_o.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function tk(e,t){return ba(e)?{path:e,kind:"binary",language:null,sizeBytes:t,mimeType:tp(e),readonly:!0}:{path:e,kind:"text",language:np(e),sizeBytes:t,readonly:!1}}function nk(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 ep(t)}function ep(e){return e.map(t=>t.kind==="directory"?{...t,children:ep(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function rk(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 ba(e){return!BI(e)}function tp(e){let t=Sa.posix.extname(e).toLowerCase();return!t&&Sa.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":KI[t]??"application/octet-stream"}function np(e){let t=Sa.posix.extname(e).toLowerCase();return JI[t]??"plaintext"}var Lo=class{constructor(t){this.options=t,this.fileSystem=new Jn(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}async setActiveRoute(t){await this.engine.setActiveRoute(t)}getDocument(t){return Pr(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){return wr(this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(){return Mo(this.fileSystem,{routeEntryFiles:this.options.routes.map(t=>t.entryFile)})}getSourceFile(t){return Oo(this.fileSystem,t,{routeEntryFiles:this.options.routes.map(n=>n.entryFile)})}resolveSourceLocation(t){return Do(t,this.engine.getRenderDetail(t.key,t.routeId))}async planOperation(t){let n=ik.safeParse(t);if(!n.success)return{result:Rr(t,n.error.issues.map(i=>i.message))};let r=new Jn(this.options.files),o=this.createEngine(r,{emitEvents:!1});try{for(let u of this.getPlanningRouteIds(n.data))await o.setActiveRoute(u);let i=this.withInferredNodeRouteId(n.data,o),s=await o.execute(i);if(!s.ok)return{result:{ok:!1,error:{code:s.error?.code??"INTERNAL_ERROR",message:s.error?.message??"Operation failed"},data:{requestId:s.requestId,kind:s.kind,target:s.target,resultVersion:s.resultVersion}}};let a={ok:!0,data:jt(s)},c=r.getChangedFiles();if(c.length===0)return{result:a};let l=sk.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:c.map(u=>ak(u,t.kind==="source-edit")),changedRouteIds:this.getChangedRouteIds(c.map(u=>u.path)),diagnostics:[]});return this.options.onEvent?.({type:"site-edit.operation.planned",siteId:t.siteId,operationId:t.id,baseSnapshotId:t.baseSnapshotId,changedFiles:l.patches.map(u=>u.path),at:new Date().toISOString()}),{result:a,patchPlan:l}}finally{o.dispose()}}dispose(){this.engine.dispose()}getPlanningRouteIds(t){let n=this.getExplicitPlanningRouteId(t);if(n){let r=this.options.routes.find(o=>o.routeId===n);return r?[r.routeId]:this.options.routes.map(o=>o.routeId)}if(t.target.kind==="node"){let r=this.getBuiltRouteIdsForKey(t.target.key);if(r.length>0)return r}return this.options.routes.map(r=>r.routeId)}getExplicitPlanningRouteId(t){if(t.routeId)return t.routeId;if(t.target.kind==="route")return t.target.routeId;if(t.params.kind==="set-class-name-source")return t.params.routeId;if(t.params.kind==="apply-style-draft")return t.params.className?.routeId}getBuiltRouteIdsForKey(t){let n=[];for(let r of this.options.routes)try{this.engine.getRenderDetail(t,r.routeId),n.push(r.routeId)}catch{}return n}withInferredNodeRouteId(t,n){if(t.target.kind!=="node"||t.routeId)return t;let r=this.findRouteIdForNodeTarget(n,t.target.key);return r?{...t,routeId:r}:t}findRouteIdForNodeTarget(t,n){for(let r of this.options.routes)try{if(t.getDocument(r.routeId).entries.some(i=>i.key===n))return r.routeId}catch{}return this.options.routes.length===1?this.options.routes[0]?.routeId:void 0}createEngine(t,n={}){let r=n.emitEvents??!0;return fr({projectRoot:"/snapshot",fileSystem:t,routes:this.options.routes.map(o=>({routeId:o.routeId,entryFile:o.entryFile})),onEvent:r&&this.options.onEvent?o=>{let i=Ar(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,initialDocumentVersion:this.options.initialDocumentVersion})}getChangedRouteIds(t){let n=new Set(t),r=new Set(this.options.routes.map(s=>s.entryFile));if(t.some(s=>!r.has(s)))return this.options.routes.map(s=>s.routeId);let i=this.options.routes.filter(s=>n.has(s.entryFile)).map(s=>s.routeId);return i.length>0?i:this.options.routes.map(s=>s.routeId)}};function ak(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:le(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:le(e.before)},fullContent:e.after}}function ck(e){return new Lo(e)}import{SiteEditOperationRequestSchema as dk}from"@vcp-dev/contracts";import rt from"node:fs/promises";import Fe from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as lk,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as uk}from"@vcp-dev/contracts";var jo=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=fr({...t,fileSystem:this.fileSystem})}get status(){return this.engine.status}registerRoute(t,n){this.engine.registerRoute(t,n)}unregisterRoute(t){this.engine.unregisterRoute(t)}async setActiveRoute(t){await this.engine.setActiveRoute(t)}getDocument(t){return this.engine.getDocument(t)}getHistoryStatus(){return this.engine.getHistoryStatus()}getObjectEditContext(t,n){return this.engine.getObjectEditContext(t,n)}getRenderDetail(t,n){return this.engine.getRenderDetail(t,n)}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(){return Mo(this.fileSystem,{routeEntryFiles:this.engine.getRouteEntryFiles()})}getSourceFile(t){return Oo(this.fileSystem,t,{routeEntryFiles:this.engine.getRouteEntryFiles()})}resolveSourceLocation(t){return Do(t,this.engine.getRenderDetail(t.key,t.routeId))}refreshSourceForKey(t,n){return this.engine.refreshSourceForKey(t,n)}execute(t){return this.engine.execute(t)}undo(t){return this.engine.undo(t)}redo(t){return this.engine.redo(t)}notifyFileChanged(t){this.engine.notifyFileChanged(t)}subscribe(t){return this.engine.subscribe(t)}dispose(){this.engine.dispose()}createFileSystem(){if(this.options.fileSystem)return this.options.fileSystem;let t=new Map,{projectRoot:n}=this.options;return{async readFile(r){return rt.readFile(Fe.join(n,r),"utf8")},async readFileBytes(r){return rt.readFile(Fe.join(n,r))},async getFileInfo(r){let o=Fe.join(n,...r.split("/"));try{let i=await rt.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await vo(Fe.join(n,r),o)},async createExclusive(r,o){let i=Fe.join(n,r);await rt.mkdir(Fe.dirname(i),{recursive:!0});let s=await rt.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await rt.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await rt.rm(Fe.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=Fe.join(n,i),a=Fe.dirname(Fe.join(n,o));for(;a!==s&&a.startsWith(`${s}${Fe.sep}`);){try{await rt.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=Fe.dirname(a);continue}break}a=Fe.dirname(a)}},async exists(r){try{return await rt.access(Fe.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...uk,...lk],i=[],s=new Set,a=new Set,c=0;for(let d of o)await u(d,i,1);let l=i.sort((d,m)=>d.path.localeCompare(m.path));return a.size>0?{files:l,truncated:{reasons:[...a]}}:{files:l};async function u(d,m,p){if(r.maxDepth!==void 0&&p>r.maxDepth){a.add("max-depth");return}let h=Fe.join(n,...d.split("/")),E;try{E=await rt.lstat(h)}catch{return}if(E.isSymbolicLink())return;if(E.isFile()){let v=E.ino>0?`${String(E.dev)}:${String(E.ino)}`:null;if(v&&s.has(v))return;if(r.maxFiles!==void 0&&m.length>=r.maxFiles){a.add("max-files");return}if(r.maxTotalBytes!==void 0&&c+E.size>r.maxTotalBytes){a.add("max-total-bytes");return}v&&s.add(v),m.push({path:d,sizeBytes:E.size}),c+=E.size;return}if(!E.isDirectory())return;if(r.maxFiles!==void 0&&m.length>=r.maxFiles){a.add("max-files");return}let C=await rt.readdir(h,{withFileTypes:!0});for(let v of C)v.isSymbolicLink()||await u(`${d}/${v.name}`,m,p+1)}},getVersion(r){return t.get(r)??1},bumpVersion(r){let o=(t.get(r)??1)+1;return t.set(r,o),o}}}};function Ia(e){return new jo(e)}var $o=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=Ia({projectRoot:t.projectRoot,fileSystem:t.fileSystem,routes:t.routes.map(n=>({routeId:n.routeId,entryFile:n.entryFile})),onEvent:n=>{let r=Ar(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.initialDocumentVersion!==void 0?{initialDocumentVersion:t.initialDocumentVersion}:{},siteId:t.siteId,snapshotId:t.snapshotId})}get status(){return this.engine.status}registerRoute(t,n){this.engine.registerRoute(t,n)}unregisterRoute(t){this.engine.unregisterRoute(t)}async setActiveRoute(t){await this.engine.setActiveRoute(t)}getDocument(t){return{ok:!0,data:Pr(this.engine.getDocument(t),{siteId:this.options.siteId,snapshotId:this.options.snapshotId})}}getInternalDocument(t){return this.engine.getDocument(t)}getStyleContext(t){return{ok:!0,data:this.engine.getDocument(t).styleContext??null}}async getHistoryStatus(){return{ok:!0,data:await this.engine.getHistoryStatus()}}getObjectEditContext(t,n){return{ok:!0,data:wr(this.engine.getObjectEditContext(t,n))}}getClassNameSource(t,n){return{ok:!0,data:this.engine.getClassNameSource(t,n)}}async getSourceTree(){return{ok:!0,data:await this.engine.getSourceTree()}}async getSourceFile(t){return{ok:!0,data:await this.engine.getSourceFile(t)}}resolveSourceLocation(t){return{ok:!0,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=dk.safeParse(r);if(!o.success)return Rr(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,error:{code:s.code,message:s.message},data:{requestId:i.requestId,kind:i.kind,target:i.target,resultVersion:i.resultVersion,...i.affectedFiles?.length?{affectedFiles:i.affectedFiles}:{}}}}return{ok:!0,data:jt(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,error:{code:r.code,message:r.message},data:{requestId:n.requestId,kind:n.kind,target:n.target,resultVersion:n.resultVersion}}}return{ok:!0,data:jt(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,error:{code:r.code,message:r.message},data:{requestId:n.requestId,kind:n.kind,target:n.target,resultVersion:n.resultVersion}}}return{ok:!0,data:jt(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 fk(e){return new $o(e)}import{createHash as pk,randomUUID as Ma}from"node:crypto";import he from"node:fs/promises";import ye from"node:path";var He=1,va=1,mk=2,hk="index.json",gk="recovery.json",yk="transaction-journal.json",xk="document-version.json",Uo={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},K={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"},z=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};async function fp(e,t={}){let n=Fk(e),r=Ok(t.limits),o=ka(n),i=_k(n),s=await Oe(i),a=await Oe(o)||s;a||(await vk(n),await Ck(n)),a||await Dk(n);let c=await je(n),l=new Set(a?(await zo(n)).map(d=>d.stageId):[]);a||await pr(n,c.entryIds);let u=async()=>{if(await Oe(o)||s)throw new z(K.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")};return{rootDir:n,recoveryRequired:a,async readDocumentVersion(){return up(n)},async writeDocumentVersion(d){if(await u(),!Number.isInteger(d)||d<0)throw new z(K.INVALID_SCHEMA,"document version must be a non-negative integer");let m=await up(n);await mr(Ep(n),{schemaVersion:1,version:Math.max(m,d)})},async stageAppend(d,m={}){await u();let p=await op(d,r),h={schemaVersion:va,stageId:Ma(),entryId:p.entryId,blobIds:p.blobs.map(E=>E.digest)};try{await ip(n,p),await bk(n,h,m.durableManifest!==!1)}catch(E){try{await ap(n,h)}catch(C){throw new z(K.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:C})}throw E}return{stageId:h.stageId,entryId:h.entryId,blobIds:h.blobIds}},async discardStage(d){await u(),wa(d);let m=await Ra(n,d);m&&await ap(n,m)},async previewStagedAppend(d,m){return await u(),(await rp(n,r,d,m)).transition},async previewCursor(d,m){await u();let p=await je(n);return Aa(p,m),Ca(d,p.entryIds.length),pp(p,p.entryIds,d)},async publishStagedAppend(d,m,p){if(await u(),Vo(d,"entryId"),p){wa(p);let E=await Ra(n,p);if(!E||E.entryId!==d)throw new z(K.INVALID_SCHEMA,"history stage does not match the published entry")}let h=await rp(n,r,d,m);return lp({rootDir:n,previousDigest:h.current.digest,entryIds:h.entryIds,cursor:h.cursor,afterWrite:async()=>{p?await Ko(n,p):await kk(n,d),await pr(n,h.entryIds)}})},async append(d){await u();let m=await je(n),p=await op(d,r),h=[...m.entryIds];m.cursor<h.length-1&&h.splice(m.cursor+1),h.push(p.entryId);try{await ip(n,p);let E=await mp(n,h,r);return await Da(n,E.entryIds,E.cursor),await pr(n,E.entryIds),je(n)}catch(E){throw await pr(n,m.entryIds),E}},async readEntry(d){return Vo(d,"entryId"),gr(n,d)},async readBlob(d){Vo(d,"blobId");let m=await Ja(n,d),p=await Ot(m,K.NOT_FOUND,"blob");return La(p,d,m),p},async readIndex(){return je(n)},async readStatus(){let d=await je(n);return{canUndo:d.undoIds.length>0,canRedo:d.redoIds.length>0,undoDepth:d.undoIds.length,redoDepth:d.redoIds.length,cursor:d.cursor,recoveryRequired:await Oe(o)||await Oe(i)}},async readUndoRedoIds(){let d=await je(n);return{undoIds:d.undoIds,redoIds:d.redoIds,currentId:d.currentId}},async setCursor(d,m){await u();let p=await je(n);return Aa(p,m),Ca(d,p.entryIds.length),lp({rootDir:n,previousDigest:p.digest,entryIds:p.entryIds,cursor:d})},async markRecoveryRequired(d){await Oe(o)||await mr(ka(n),{schemaVersion:He,reason:Mk(d),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await he.rm(ka(n),{force:!0})},async readTransactionJournal(){return await Oe(i)?Bo(i):null},async writeTransactionJournal(d){await u(),Sp(d);try{await mr(i,d)}catch(p){let h=await Bo(i).catch(()=>null);if(h&&Buffer.from($e(h)).equals(Buffer.from($e(d))))return;throw h?new z(K.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:p}):p}let m=await Bo(i);if(!Buffer.from($e(m)).equals(Buffer.from($e(d))))throw new z(K.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(d){let m=await Oe(i)?await Bo(i):null;if(m&&m.transactionId!==d)throw new z(K.INVALID_SCHEMA,"transaction journal changed concurrently");try{await he.rm(i,{force:!0})}catch(p){if(!await Oe(i))return;throw p}if(await Oe(i))throw new z(K.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await u();for(let m of l)await Ko(n,m),l.delete(m);await Rk(n);let d=await je(n);await pr(n,d.entryIds)}}}async function rp(e,t,n,r){Vo(n,"entryId");let o=await je(e);Aa(o,r);let i=await gr(e,n),s=[...o.entryIds];o.cursor<s.length-1&&s.splice(o.cursor+1),s.push(i.id);let a=await mp(e,s,t);return{current:o,entryIds:a.entryIds,cursor:a.cursor,transition:pp(o,a.entryIds,a.cursor)}}function pp(e,t,n){return Ca(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:Ek(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function Ek(e,t){return Dt($e({schemaVersion:He,entryIds:e,cursor:t}))}function Ca(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new z(K.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function Sk(e){if(!ot(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!Be(e.expectedIndexDigest)||!Be(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!Be(n)?!1:t===-1?n===null:Be(n)}async function op(e,t){if(!e.kind.trim())throw new z(K.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new z(K.INVALID_JSON,"history blob name must not be empty");let l=Nk(c.data),u=Dt(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:He,kind:e.kind,manifest:e.manifest,blobs:r},i=$e({...o}),s=Dt(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new z(K.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function ip(e,t){let n=Ba(e,t.entryId),r={id:t.entryId,...t.entryBody},o=[...t.blobs.map(a=>sp(Ua(e,a.digest),a.bytes,{kind:"blob",digest:a.digest},Ka(e,a.digest))),sp(n,$e(r),{kind:"entry",digest:t.entryId},Va(e,t.entryId))],s=(await Promise.allSettled(o)).find(a=>a.status==="rejected");if(s)throw s.reason}async function sp(e,t,n,r){let o=await Fa(e)??(r?await Fa(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new z(n.kind==="blob"?K.BLOB_CORRUPT:K.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await yp(e,t)}async function mp(e,t,n){let r=[...t],o=r.length-1;for(;;){if((await gp(e,r)).totalBytes<=n.maxSessionBytes&&r.length<=n.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new z(K.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");r.shift(),o-=1}}async function bk(e,t,n){Oa(t);let r=$a(e,t.stageId);if(n){await mr(r,t);return}await Tk(r,t)}async function Ra(e,t){let n=await Fa($a(e,t));if(n===null)return null;let r=yr(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=Oa(r);if(o.stageId!==t)throw new z(K.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function zo(e){let t=[];for(let n of await Xo(ja(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);wa(r);let o=await Ra(e,r);o&&t.push(o)}return t}async function ap(e,t){Oa(t);let n=await je(e),r=(await zo(e)).filter(s=>s.stageId!==t.stageId),o=new Set(n.entryIds),i=new Set;for(let s of n.entryIds){let a=await gr(e,s);for(let c of a.blobs)i.add(c.digest)}for(let s of r){o.add(s.entryId);for(let a of s.blobIds)i.add(a)}o.has(t.entryId)||await cp(Ba(e,t.entryId),Va(e,t.entryId));for(let s of t.blobIds)i.has(s)||await cp(Ua(e,s),Ka(e,s));await Ko(e,t.stageId),await _a(xr(e)),await _a(Er(e))}async function Ko(e,t){await Pa($a(e,t)),await Ik(e)}async function Ik(e){try{await he.rmdir(ja(e))}catch(t){if(Sr(t)||ot(t)&&t.code==="ENOTEMPTY")return;throw t}}async function kk(e,t){for(let n of await zo(e))n.entryId===t&&await Ko(e,n.stageId)}async function Pa(e){if(await he.rm(e,{force:!0}),await Oe(e))throw new z(K.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function cp(e,t){await Pa(e),await Pa(t)}function Oa(e){if(!ot(e)||e.schemaVersion!==va||typeof e.stageId!="string"||!hp(e.stageId)||!Be(e.entryId))throw new z(K.INVALID_SCHEMA,"history stage schema is invalid");let t=xp(e.blobIds,"history stage blobIds");return{schemaVersion:va,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function wa(e){if(!hp(e))throw new z(K.INVALID_PATH,"history stageId must be a UUID")}function hp(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 pr(e,t){let n=new Set(t),r=new Set;for(let c of t){let l=await gr(e,c);for(let u of l.blobs)r.add(u.digest)}for(let c of await zo(e)){n.add(c.entryId);for(let l of c.blobIds)r.add(l)}let o=xr(e),i=await Xo(o);for(let c of i){if(!c.endsWith(".json"))continue;let l=dp(c.slice(0,-5));l&&!n.has(l)&&await Jo(ye.join(o,c))}let s=Er(e),a=await Xo(s);for(let c of a){let l=dp(c);l&&!r.has(l)&&await Jo(ye.join(s,c))}}async function je(e){let t=Ho(e),n=await Ot(t,K.NOT_FOUND,"index"),r=yr(Buffer.from(n).toString("utf8"),"index"),o=Pk(r),i=[...o.entryIds],{totalBytes:s}=await gp(e,i),a=i.slice(0,o.cursor+1).reverse(),c=i.slice(o.cursor+1);return{schemaVersion:He,digest:o.digest,entryIds:i,cursor:o.cursor,currentId:i[o.cursor]??null,undoIds:a,redoIds:c,totalBytes:s}}async function gp(e,t){let n=0,r=new Set,o=Ho(e),i=await Ot(o,K.NOT_FOUND,"index");n+=i.byteLength;for(let s of t){let a=await gr(e,s),c=await bp(e,s),l=await Ot(c,K.NOT_FOUND,"entry");n+=l.byteLength;for(let u of a.blobs){if(r.has(u.digest))continue;r.add(u.digest);let d=await Ja(e,u.digest),m=await Ot(d,K.NOT_FOUND,"blob");La(m,u.digest,d),n+=m.byteLength}}return{totalBytes:n}}async function gr(e,t){let n=await bp(e,t),r=await Ot(n,K.NOT_FOUND,"entry"),o=yr(Buffer.from(r).toString("utf8"),`entry ${t}`),i=wk(o);if(i.id!==t)throw new z(K.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(Dt($e({schemaVersion:i.schemaVersion,kind:i.kind,manifest:i.manifest,blobs:i.blobs}))!==t)throw new z(K.ENTRY_CORRUPT,`entry hash mismatch for ${t}`);for(let a of i.blobs){let c=await Ja(e,a.digest),l=await Ot(c,K.NOT_FOUND,"blob");La(l,a.digest,c)}return i}async function Da(e,t,n){let r={schemaVersion:He,digest:Dt($e({schemaVersion:He,entryIds:t,cursor:n})),entryIds:t,cursor:n};await mr(Ho(e),r)}function Aa(e,t){if(t!==void 0&&e.digest!==t)throw new z(K.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function lp(e){let t=Dt($e({schemaVersion:He,entryIds:e.entryIds,cursor:e.cursor}));try{return await Da(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.(),await je(e.rootDir)}catch(n){let r=await je(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new z(K.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function vk(e){await he.mkdir(e,{recursive:!0}),await he.mkdir(xr(e),{recursive:!0}),await he.mkdir(Er(e),{recursive:!0}),await he.mkdir(hr(e),{recursive:!0})}async function Ck(e){await he.rm(hr(e),{recursive:!0,force:!0}),await he.mkdir(hr(e),{recursive:!0})}async function Rk(e){let t=hr(e);await he.mkdir(t,{recursive:!0});for(let n of await Xo(t))n!=="stages"&&await he.rm(ye.join(t,n),{recursive:!0,force:!0})}function Pk(e){if(!ot(e))throw new z(K.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==He)throw new z(K.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=xp(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new z(K.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!Be(o))throw new z(K.INDEX_CORRUPT,"index digest is invalid");let i=Dt($e({schemaVersion:He,entryIds:t,cursor:r}));if(o!==i)throw new z(K.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:He,digest:o,entryIds:t,cursor:r}}function wk(e){if(!ot(e))throw new z(K.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==He)throw new z(K.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!Be(t))throw new z(K.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new z(K.ENTRY_CORRUPT,"entry kind is invalid");let r=Na(e.manifest,"entry.manifest"),o=Ak(e.blobs);return{id:t,schemaVersion:He,kind:n,manifest:r,blobs:o}}function Ak(e){if(!Array.isArray(e))throw new z(K.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!ot(t))throw new z(K.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new z(K.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!Be(o))throw new z(K.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new z(K.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function mr(e,t){await yp(e,$e(t))}async function Tk(e,t){let n=ye.dirname(e),r=ye.basename(e),o=ye.join(n,`.${r}.${process.pid}.${Ma()}.tmp`);await he.mkdir(n,{recursive:!0});try{await he.writeFile(o,$e(t),{flag:"wx"}),await he.rename(o,e)}finally{await Jo(o)}}async function yp(e,t){let n=ye.dirname(e),r=ye.basename(e),o=ye.join(n,`.${r}.${process.pid}.${Ma()}.tmp`);await he.mkdir(n,{recursive:!0});try{let i=await he.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await he.rename(o,e),await _a(n)}finally{await Jo(o)}}function $e(e){return Buffer.from(JSON.stringify(Ta(e)),"utf8")}function Ta(e){if(Array.isArray(e))return e.map(t=>Ta(t));if(ot(e)){let t={};for(let n of Object.keys(e).sort())t[n]=Ta(e[n]);return t}return e}function yr(e,t){try{return JSON.parse(e)}catch(n){throw new z(K.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function Na(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=>Na(n,t));if(ot(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=Na(o,t);return n}break}throw new z(K.INVALID_JSON,`${t} must be JSON-serializable`)}function xp(e,t){if(!Array.isArray(e))throw new z(K.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!Be(n))throw new z(K.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function Vo(e,t){if(!Be(e))throw new z(K.INVALID_PATH,`${t} must be a sha256 digest`)}function Be(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function Dt(e){return`sha256:${pk("sha256").update(e).digest("hex")}`}function Nk(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function Ot(e,t,n){try{return await he.readFile(e)}catch(r){throw new z(t,`${n} not found: ${e}`,{cause:r})}}async function Fa(e){try{return await he.readFile(e)}catch(t){if(Sr(t))return null;throw t}}function La(e,t,n){if(Dt(e)!==t)throw new z(K.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function Oe(e){try{return await he.access(e),!0}catch(t){if(Sr(t))return!1;throw t}}async function Jo(e){try{await he.rm(e,{force:!0,recursive:!0})}catch{}}async function _a(e){try{let t=await he.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function Xo(e){try{return await he.readdir(e)}catch(t){if(Sr(t))return[];throw t}}function Fk(e){if(typeof e!="string"||e.trim().length===0)throw new z(K.INVALID_ROOT,"history store rootDir must be a non-empty string");return ye.resolve(e)}function Ho(e){return ye.join(e,hk)}function ka(e){return ye.join(e,gk)}function _k(e){return ye.join(e,yk)}function Ep(e){return ye.join(e,xk)}async function up(e){try{let t=await he.readFile(Ep(e),"utf8"),n=yr(t,"document version");if(!ot(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new z(K.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(Sr(t))return 0;throw t}}async function Bo(e){let t=await Ot(e,K.RECOVERY_PENDING,"transaction journal"),n=yr(Buffer.from(t).toString("utf8"),"transaction journal");return Sp(n),n}function Sp(e){if(!ot(e)||e.schemaVersion!==mk||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!Sk(e.historyTransition)||!Array.isArray(e.files))throw new z(K.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!ot(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!Be(t.preDigest)||t.postDigest!==null&&!Be(t.postDigest))throw new z(K.INVALID_SCHEMA,"transaction journal file digest is invalid")}function Mk(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function xr(e){return ye.join(e,"entries")}function Er(e){return ye.join(e,"blobs")}function hr(e){return ye.join(e,"tmp")}function ja(e){return ye.join(hr(e),"stages")}function $a(e,t){return ye.join(ja(e),`${t}.json`)}function Ba(e,t){return ye.join(xr(e),`${kp(t)}.json`)}function Ua(e,t){return ye.join(Er(e),kp(t))}function Va(e,t){return ye.join(xr(e),`${t}.json`)}function Ka(e,t){return ye.join(Er(e),t)}async function bp(e,t){return Ip(Ba(e,t),Va(e,t))}async function Ja(e,t){return Ip(Ua(e,t),Ka(e,t))}async function Ip(e,t){return await Oe(e)?e:await Oe(t)?t:e}function kp(e){return e.slice(7)}function dp(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return Be(t)?t:null}function ot(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Sr(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function Ok(e){return{maxEntries:e?.maxEntries??Uo.maxEntries,maxSessionBytes:e?.maxSessionBytes??Uo.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??Uo.maxEntryBytes}}async function Dk(e){let t=Ho(e);await Oe(t)||await Da(e,[],-1)}export{z as FileHistoryStoreError,$o as PreviewFileSystemSiteEditEngineRuntime,Hd as SITE_EDIT_RAW_COLOR_LITERAL_RE,Lo as SnapshotSiteEditEngineRuntime,fk as createPreviewSiteEditEngineRuntime,ck as createSiteEditEngineRuntime,fp as openFileHistoryStore,lr as scanSiteEditThemeStyleViolations};
|
|
1
|
+
import{SiteEditOperationRequestSchema as lk,SiteEditPatchPlanSchema as uk}from"@vcp-dev/contracts";function Vt(e){return{requestId:e.requestId,kind:e.kind,composition:e.composition,target:e.target,resultVersion:e.resultVersion,affectedFiles:e.affectedFiles,...e.output?{output:e.output}:{},...e.selectionRef?{selectionRef:e.selectionRef}:{}}}function $r(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 Vr(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,...n.pageCompositionUnitKey?{pageCompositionUnitKey:n.pageCompositionUnitKey}:{},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 Ur(e){return{composition:e.composition,key:e.key,tag:e.tag,label:e.label,sourceLocator:e.sourceLocator,isOpaque:e.isOpaque,ancestors:e.ancestors,componentName:e.componentName,sourceFile:e.sourceFile,capabilities:Rm(e.capabilities),provenanceChain:e.provenanceChain?{editMode:e.provenanceChain.editMode,diagnostics:e.provenanceChain.diagnostics}:void 0,dynamicData:e.dynamicData,textSegments:e.textSegments.map(t=>({index:t.index,editable:t.editable,sourceKind:t.source?.kind??null})),boundaryKind:e.boundaryKind}}function Kr(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:Vt(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 Rm(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{computeSiteEditCompositionKey as YI,composeSiteEditRepeatInstanceKey as ZI,getSiteEditSourceDeleteProtectionReason as QI,isSiteEditTextSourcePath as qI,parseSiteEditRepeatInstanceKey as ev,SITE_EDIT_SOURCE_DELETE_CAPABILITY as tv,stripSiteEditRepeatInstanceKeys as Ge}from"@vcp-dev/contracts";import{parse as nv}from"yaml";import Wo from"node:path";function Kn(e,t,n){return`${e}::${t}::${n}`}var O={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"};import Ni from"@babel/traverse";import*as x from"@babel/types";import{createHash as _m}from"node:crypto";import*as Tc from"@babel/parser";function Ut(e,t,n,r){return{code:e,message:t,locatorKind:n,details:r}}function V(e,t,n,r,o){return{ok:!1,source:e,diagnostic:Ut(t,n,r,o)}}function Ei(e,t,n,r,o){return{ok:!1,source:e,diagnostic:Ut(t,n,r,o)}}var wm={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function ct(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:Tc.parse(t,{sourceType:"module",plugins:wm[n]})}}catch(r){return{ok:!1,source:t,diagnostic:Ut("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function Ii(e,t){return ct({source:e,profile:_c(t.kind)})}function vi(e,t){return ct({source:e,profile:_c(t)})}function _c(e){return"next-app-entry"}function Kt(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"}import*as Nm from"@babel/parser";import*as mn from"@babel/types";import*as vt from"node:path";var ki=[".tsx",".ts",".jsx",".js"],Pm=ki.map(e=>`/index${e}`);function Fc(e){let t=[];for(let n of e.program.body)mn.isImportDeclaration(n)&&typeof n.source.value=="string"&<(n.source.value)&&t.push(n.source.value),mn.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&<(n.source.value)&&t.push(n.source.value),mn.isExportAllDeclaration(n)&&typeof n.source.value=="string"&<(n.source.value)&&t.push(n.source.value);return Ci(e.program,t),t}function Ci(e,t){if(!e||typeof e!="object")return;let n=e;if(n.type==="CallExpression"&&n.callee?.type==="Import"){let r=n.arguments?.[0];r?.type==="StringLiteral"&&typeof r.value=="string"&<(r.value)&&t.push(r.value)}for(let r of Object.values(n))if(Array.isArray(r))for(let o of r)Ci(o,t);else r&&typeof r=="object"&&Ci(r,t)}function lt(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function Ri(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=vt.dirname(e);return vt.join(n,t).replace(/\\/g,"/")}async function Am(e,t){if(ki.some(n=>e.endsWith(n))&&await t(e))return e;for(let n of ki){let r=`${e}${n}`;if(await t(r))return r}for(let n of Pm){let r=`${e}${n}`;if(await t(r))return r}return null}async function gn(e,t,n){let r=await Jr(e,t,n);return r.ok?r.path:null}async function Jr(e,t,n){let r=Ri(e,t);try{if(!Tm(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 Am(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 Tm(e,t,n){if(!lt(t)||t.includes("\0")||t.includes("\\")||vt.posix.isAbsolute(n))return!1;let r=vt.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!vt.posix.isAbsolute(e)}var Jn=(e,t)=>{let n=ct({source:t,profile:Kt({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${_m("sha256").update(t).digest("hex")}`,ast:n.ast,imports:Fc(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};var Xr="components/ui";function Jt(e){if(!e)return!1;let t=wi(e);return t===Xr||t.startsWith(`${Xr}/`)||t.includes(`/${Xr}/`)||t.endsWith(`/${Xr}`)}function Xn(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?Jt(e.slice(2)):e.startsWith("./")||e.startsWith("../")?Jt(wi(`${Fm(t)}/${e}`)):Jt(e):!1}function wi(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 Fm(e){let t=wi(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}var Mm=typeof Ni=="function"?Ni:Ni.default;function _e(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 Om(e){return/^[A-Z]/.test(e)}function Mi(e){let t=e.openingElement;return x.isJSXIdentifier(t.name)?t.name.name==="Fragment":x.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function yn(e){return x.isJSXFragment(e)}function Dc(e){return x.isJSXIdentifier(e.name)?e.name.name:x.isJSXMemberExpression(e.name)?Lc(e.name):x.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function Lc(e){return x.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:x.isJSXMemberExpression(e.object)?`${Lc(e.object)}.${e.property.name}`:e.property.name}function Dm(e){return e.split(".")[0]??e}function Lm(e){let t=e;for(;t;){let n=t.node;if(x.isFunctionDeclaration(n)&&n.id||x.isVariableDeclarator(n)&&x.isIdentifier(n.id))return n.id.name;if(x.isExportDefaultDeclaration(n)){let r=n.declaration;if(x.isFunctionDeclaration(r)&&r.id)return r.id.name;if(x.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function Bm(){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 jm(e){let t=new Map;for(let n of e.program.body){if(!x.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(x.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(x.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(x.isImportSpecifier(o)){let i=x.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function mt(e,t=[]){if(x.isIdentifier(e))return t.push(e.name),t;if(x.isObjectPattern(e)){for(let n of e.properties)x.isObjectProperty(n)?mt(n.value,t):x.isRestElement(n)&&mt(n.argument,t);return t}if(x.isArrayPattern(e)){for(let n of e.elements)n&&(x.isRestElement(n)?mt(n.argument,t):mt(n,t));return t}return x.isAssignmentPattern(e)?(mt(e.left,t),t):(x.isRestElement(e)&&mt(e.argument,t),t)}function kt(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function zr(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 $m(e,t,n){e.set(t,{resolved:!0,value:n})}function Oi(e,t){e.set(t,{resolved:!1})}function Bc(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 Ne(e,t,n){if(x.isTSAsExpression(e)||x.isTSSatisfiesExpression(e)||x.isTSNonNullExpression(e)||x.isTypeCastExpression(e)||x.isParenthesizedExpression(e))return Ne(e.expression,t,n);if(x.isLogicalExpression(e))return Pi([Ne(e.left,t,n),Ne(e.right,t,n)]);if(x.isConditionalExpression(e))return Pi([Ne(e.consequent,t,n),Ne(e.alternate,t,n)]);if(x.isTemplateLiteral(e))return Pi(e.expressions.filter(x.isExpression).map(i=>Ne(i,t,n)));if(x.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!x.isMemberExpression(e)&&!x.isOptionalMemberExpression(e))return null;let r=[],o=e;for(;x.isMemberExpression(o)||x.isOptionalMemberExpression(o);){if(o.computed)if(x.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(x.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&x.isExpression(o.property)){let i=zt(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(!x.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return x.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:kt(e,t),base:o.name,path:r}:null}function Pi(e){let t=e.filter(r=>r!==null);if(t.length===0)return null;let n=t[0];return t.some(r=>r.base!==n.base||JSON.stringify(r.path)!==JSON.stringify(n.path))?null:{...n}}function zt(e,t){if(x.isStringLiteral(e)||x.isNumericLiteral(e)||x.isBooleanLiteral(e))return e.value;if(x.isNullLiteral(e))return null;if(x.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(x.isIdentifier(e)){let n=zr(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(x.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||x.isSpreadElement(r))return;let o=zt(r,t);if(o===void 0)return;n.push(o)}return n}if(x.isObjectExpression(e)){let n={};for(let r of e.properties){if(!x.isObjectProperty(r)||r.computed||!x.isExpression(r.value))return;let o=null;if(x.isIdentifier(r.key)?o=r.key.name:x.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!x.isIdentifier(r.value))return;let s=zr(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=zt(r.value,t);if(i===void 0)return;n[o]=i}return n}if(x.isMemberExpression(e)){let n=Ne(e,"",t);if(!n)return;let r=zr(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=Bc(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(x.isCallExpression(e))return $c(e,t)??void 0}function jc(e,t,n){let r=Ne(e,n,t);if(!r)return x.isMemberExpression(e)||x.isBinaryExpression(e)||x.isLogicalExpression(e)||x.isConditionalExpression(e)||x.isCallExpression(e)?{value:kt(e,n),source:null}:null;let o=zr(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?Bc(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 Ai(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:Bm(),parentStack:[],valueScopes:i,importMap:o}}function _i(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of mt(o.id))Oi(n,s);if(!x.isIdentifier(o.id)||!o.init||!x.isExpression(o.init))continue;let i=zt(o.init,t);i!==void 0&&$m(n,o.id.name,i)}}function Vm(e){let t=[];for(let n of e){if(x.isVariableDeclaration(n)){t.push(n);continue}x.isExportNamedDeclaration(n)&&n.declaration&&x.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function Um(e,t,n){let r=[],o=0;for(let i of e)if(x.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:_e(i),editable:!0,source:null})}else if(x.isJSXExpressionContainer(i)&&x.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:_e(i),editable:!0,source:null});else if(x.isJSXExpressionContainer(i)&&x.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:_e(i),editable:!0,source:null}):r.push({index:o++,value:kt(s,n),sourceRange:_e(i),editable:!0,source:Ne(s,n,t)})}else if(x.isJSXExpressionContainer(i)&&x.isExpression(i.expression)){let s=jc(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:_e(i),editable:!0,source:s.source})}return r}function Km(e,t,n){let r=[];for(let o of e.attributes)if(!(!x.isJSXAttribute(o)||!x.isJSXIdentifier(o.name))){if(x.isStringLiteral(o.value)){r.push({name:o.name.name,value:o.value.value,sourceRange:_e(o),source:null});continue}if(x.isJSXExpressionContainer(o.value)&&x.isExpression(o.value.expression)){let i=zt(o.value.expression,t);if(o.name.name==="className"){let a=typeof i=="string"?i:i===void 0?$c(o.value.expression,t):null;if(a){r.push({name:o.name.name,value:a,sourceRange:_e(o),source:null,resolvedValue:a});continue}}let s=jc(o.value.expression,t,n);if(i!==void 0&&typeof i!="string"&&typeof i!="number"){r.push({name:o.name.name,value:Mc(i),sourceRange:_e(o),source:Ne(o.value.expression,n,t),resolvedValue:i});continue}if(!s){i!==void 0&&r.push({name:o.name.name,value:Mc(i),sourceRange:_e(o),source:Ne(o.value.expression,n,t),resolvedValue:i});continue}r.push({name:o.name.name,value:s.value,sourceRange:_e(o),source:s.source})}}return r}function $c(e,t){let n=hn(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function hn(e,t){if(x.isStringLiteral(e))return[e.value];if(x.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(x.isNullLiteral(e))return[];if(x.isBooleanLiteral(e))return e.value?null:[];if(x.isIdentifier(e)||x.isMemberExpression(e)){if(x.isIdentifier(e)&&e.name==="undefined")return[];let n=zt(e,t);return typeof n=="string"?[n]:null}if(x.isConditionalExpression(e)){let n=hn(e.consequent,t),r=hn(e.alternate,t);return!n||!r?null:[...n,...r]}if(x.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=zt(e.left,t);return n===!1||n===null?[]:hn(e.right,t)}if(x.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||x.isSpreadElement(r))return null;let o=hn(r,t);if(!o)return null;n.push(...o)}return n}if(x.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!x.isObjectProperty(r))return null;let o=Xm(r.key);if(!o)return null;n.push(o)}return n}if(x.isCallExpression(e)){let n=Jm(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!x.isExpression(o))return null;let i=hn(o,t);if(!i)return null;r.push(...i)}return r}return null}function Jm(e){return x.isIdentifier(e)?e.name:x.isMemberExpression(e)&&x.isIdentifier(e.property)?e.property.name:null}function Xm(e){return x.isIdentifier(e)?e.name:x.isStringLiteral(e)?e.value:null}function zm(e,t){let n=e.attributes.find(r=>x.isJSXAttribute(r)&&x.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!x.isJSXAttribute(n)||!x.isJSXExpressionContainer(n.value)?null:n.value.expression}function Hm(e,t){for(let n of t){let r=zm(e,n);if(r)return r}return null}function Wm(e){return x.isJSXIdentifier(e.name)?e.name.name:null}function Mc(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function Gm(e){if(!x.isCallExpression(e)&&!x.isOptionalCallExpression(e))return null;let t=e.callee;return!x.isMemberExpression(t)&&!x.isOptionalMemberExpression(t)||!x.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!x.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function Ti(e){return x.isArrowFunctionExpression(e)||x.isFunctionExpression(e)}function Ym(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function Zm(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function Oc(e,t,n,r){if(!e||!x.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:kt(e,n),collectionSource:Ne(e,n,r)};if(t){let i=t.params[0],s=t.params[1];x.isIdentifier(i)&&(o.itemParamName=i.name),x.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function Ct(e,t,n){if(!e)return[];if(x.isJSXElement(e)){if(Mi(e))return Zr(e.children,t,n);let r=Gr(e,t,n);return r?[r]:[]}return yn(e)?Yr(e,t,n):x.isParenthesizedExpression(e)?Ct(e.expression,t,n):x.isExpression(e)?Qr(e,t,n):[]}function Hr(e,t,n){let r=new Map;for(let o of e.params)for(let i of mt(o))Oi(r,i);t.valueScopes.push(r);try{if(!x.isBlockStatement(e.body))return Ct(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return Vc(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function Vc(e,t,n){let r=[];for(let o of e){if(x.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];i&&_i([o],t,i);continue}r.push(...Fi(o,t,n))}return r}function Fi(e,t,n){if(x.isReturnStatement(e))return e.argument?Ct(e.argument,t,n):[];if(x.isBlockStatement(e))return Xt(e.body,t,n);if(x.isIfStatement(e)){let r=x.isBlockStatement(e.consequent)?Xt(e.consequent.body,t,n):Fi(e.consequent,t,n),o=e.alternate?x.isBlockStatement(e.alternate)?Xt(e.alternate.body,t,n):Fi(e.alternate,t,n):[];return[...r,...o]}if(x.isSwitchStatement(e))return Xt(e.cases.flatMap(r=>r.consequent),t,n);if(x.isTryStatement(e)){let r=Xt(e.block.body,t,n);return e.handler&&r.push(...Xt(e.handler.body.body,t,n)),e.finalizer&&r.push(...Xt(e.finalizer.body,t,n)),r}return[]}function Xt(e,t,n){let r=new Map;t.valueScopes.push(r);try{return Vc(e,t,n)}finally{t.valueScopes.pop()}}function Wr(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:_e(r),sourceCandidates:i&&i.length>0?i:void 0})}function Qm(e,t,n,r){let o=Hm(e.openingElement,["items","dataSource","data"]),i={key:t,tag:Dc(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!x.isJSXAttribute(s))continue;let a=Wm(s);if(!a||!x.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!x.isJSXEmptyExpression(c)){if(Ym(a)&&Ti(c)){let l=Hr(c,n,r),u=Oc(o,c,r,n);Wr(n,"repeat-region",t,s,l,u?[u]:void 0);continue}if(Zm(a)){let l=Ti(c)?Hr(c,n,r):Ct(c,n,r);Wr(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!x.isJSXExpressionContainer(s)||!Ti(s.expression))continue;let a=Hr(s.expression,n,r),c=Oc(o,s.expression,r,n);Wr(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function Gr(e,t,n){let r=Dc(e.openingElement);if(r==="Fragment"||Mi(e))return Zr(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=Om(r),a;if(s){let w=t.ordinalTracker.getOrdinal(i,r);a=`component:${r}#${w}`}else{let w=t.ordinalTracker.getOrdinal(i,r);a=`${r}#${w}`}let c=o?t.elements.get(o.key)?.identity.structuralPath:void 0,l=c?`${c}/${a}`:a,u=Kn(t.file,t.componentName,l),d={file:t.file,component:t.componentName,structuralPath:l,key:u},p=s?"component-boundary":null,m=Um(e.children,t,n),g=Km(e.openingElement,t,n),S,C,v=!1;if(s){let w=t.importMap.get(r)??t.importMap.get(Dm(r));w&&(S=w.specifier,C=w.exportName,v=Xn(w.specifier,t.file))}let P={identity:d,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:_e(e),parentKey:i,childKeys:[],textSegments:m,attributes:g.length>0?g:void 0,boundaryKind:p,isOpaque:s,...v?{isPublicUiComponent:!0}:{},importedFrom:S,exportName:C};return t.elements.set(u,P),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(u),Qm(e,u,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:u,tag:r}),qm(e.children,t,n),t.parentStack.pop()),u}function Yr(e,t,n){return Zr(e.children,t,n)}function Zr(e,t,n){let r=[];for(let o of e)if(x.isJSXElement(o))if(Mi(o))r.push(...Zr(o.children,t,n));else{let i=Gr(o,t,n);i&&r.push(i)}else yn(o)?r.push(...Yr(o,t,n)):x.isJSXExpressionContainer(o)&&r.push(...Qr(o.expression,t,n));return r}function qm(e,t,n){for(let r of e)x.isJSXElement(r)?Gr(r,t,n):yn(r)?Yr(r,t,n):x.isJSXExpressionContainer(r)&&Qr(r.expression,t,n)}function eg(e){return e==="&&"||e==="||"||e==="??"}function Qr(e,t,n){if(x.isJSXEmptyExpression(e))return[];let r=Gm(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,c={kind:"repeat-template",collectionExpression:kt(r.collection,n),collectionSource:Ne(r.collection,n,t)};if(x.isArrowFunctionExpression(a)||x.isFunctionExpression(a)){let u=a.params[0],d=a.params[1];x.isIdentifier(u)&&(c.itemParamName=u.name),x.isIdentifier(d)&&(c.indexParamName=d.name)}s.push(c);let l={kind:"repeat-region",ownerKey:i?.key??"",childKeys:[],sourceRange:_e(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(l),(x.isArrowFunctionExpression(a)||x.isFunctionExpression(a))&&l.childKeys.push(...Hr(a,t,n)),l.childKeys}if(x.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:kt(e.test,n),conditionSource:Ne(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:_e(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Ct(e.consequent,t,n)),s.childKeys.push(...Ct(e.alternate,t,n)),s.childKeys}if(x.isLogicalExpression(e)&&eg(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:kt(e.left,n),conditionSource:Ne(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:_e(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Ct(e.right,t,n)),s.childKeys}if(x.isParenthesizedExpression(e))return Qr(e.expression,t,n);if(x.isJSXElement(e)){let o=Gr(e,t,n);return o?[o]:[]}return yn(e)?Yr(e,t,n):[]}function tg(e){let t=e.argument;return t&&(x.isExpression(t)||yn(t))?t:null}function zn(e,t){let n=[];for(let r of e){if(x.isReturnStatement(r)){let o=tg(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(x.isIfStatement(r)){let o=x.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...zn(o,r.test)),r.alternate){let i=x.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...zn(i,r.test))}continue}if(x.isSwitchStatement(r))for(let o of r.cases){let i=o.test?x.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...zn(o.consequent,i))}}return n}function Uc(e){let{file:t,source:n,ast:r}=e,o=e.imports.map(d=>d.specifier),i=new Map,s=[],a=[],c=new Map,l=jm(r);Mm(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(d){let p=Lm(d);if(!p)return;let m=d.node,g=[];if(x.isArrowFunctionExpression(m))x.isExpression(m.body)||yn(m.body)?g=[{argument:m.body,statement:x.returnStatement(x.isExpression(m.body)?m.body:null)}]:x.isBlockStatement(m.body)&&(g=zn(m.body.body));else{let B=m.body;x.isBlockStatement(B)&&(g=zn(B.body))}if(g.length===0){d.skip();return}let S=new Map;_i(Vm(r.program.body),Ai(t,p,i,s,l,[S]),S);let C=new Map;for(let B of m.params)for(let re of mt(B))Oi(C,re);let v=x.isBlockStatement(m.body)?m.body.body:[],P=g[0]?.statement??null;for(let B of v){if(P&&B===P)break;x.isVariableDeclaration(B)&&_i([B],Ai(t,p,i,s,l,[S,C]),C)}let w=Ai(t,p,i,s,l,[S,C]);for(let B of g){let re=Ct(B.argument,w,n);for(let ne of re)a.includes(ne)||a.push(ne);if(B.condition){let ne={kind:"conditional-branch",conditionExpression:kt(B.condition,n),conditionSource:Ne(B.condition,n,w)};Wr(w,"conditional-region","",B.statement,re,[ne])}}d.skip()}});let u=[...i.keys()];return u.length>0&&c.set(t,u),{graph:{routeId:t,rootKeys:a,elements:i,regions:s,fileIndex:c,version:1,diagnostics:[]},localImports:o}}function Di(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function qr(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function Kc(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??Jn,c=new Map,l=new Map,u=new Map,d=[],p=new Set,m=v=>{let P=`${v.path}\0${v.code}\0${v.message}\0${JSON.stringify(v.details??{})}`;p.has(P)||(p.add(P),d.push(v))},g=[{file:e,source:t,depth:0,diagnosticEntryFile:e,importStack:[]},...(o.additionalEntries??[]).map(v=>({file:v.file,source:v.source,depth:0,diagnosticEntryFile:v.file,importStack:[]}))],S=new Set;for(;g.length>0;){let v=g.shift(),{file:P,source:w,depth:B,diagnosticEntryFile:re,importStack:ne}=v;if(S.has(P))continue;S.add(P),c.set(P,w);let N=a(P,w);if(!N.ok){m(qr(N.diagnostic,re,ne));continue}u.set(P,N.module);let{graph:X,localImports:M}=Uc(N.module);for(let D of X.elements.values())if(D.importedFrom&<(D.importedFrom)){let Z=D.importedFrom,te=await Jr(P,Z,r);te.ok?(D.importedFrom=te.path,Jt(te.path)&&(D.isPublicUiComponent=!0)):Xn(Z,P)||m(qr(te.diagnostic,re,Di(ne,P,Z,te.diagnostic.path)))}if(l.set(P,X),!(B>=i))for(let D of M){if(ng(D))continue;let Z=await Jr(P,D,r);if(!Z.ok){Xn(D,P)||m(qr(Z.diagnostic,re,Di(ne,P,D,Z.diagnostic.path)));continue}let te=Z.path;if(S.has(te)||Jt(te))continue;let he=Di(ne,P,D,te);try{let W=await n(te);g.push({file:te,source:W,depth:B+1,diagnosticEntryFile:re,importStack:he})}catch(W){m(qr({path:te,code:"import-read-failed",message:`Failed to read imported file: ${te}`,details:{fromFile:P,specifier:D,reason:W instanceof Error?W.message:String(W)}},re,he))}}}let C=rg(e,l,s,(o.additionalEntries??[]).map(v=>v.file));return C.diagnostics=d,{graph:C,allSources:c,diagnostics:d,parsedModules:u,entryModule:u.get(e)??null}}function ng(e){return/\.(?:css|scss|sass|less)(?:\?.*)?$/i.test(e)}function rg(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 p=s.get(u)??[];s.set(u,[...p,...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 Jc(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}),Xc(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function Xc(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}),Xc(s,t,n,r,o))}}import{isSiteEditRuntimeContainerTag as og,isSiteEditRuntimeVoidElementTag as ig}from"@vcp-dev/contracts/site-edit-runtime-capability";function xn(e){if(!e.composition)throw new Error("Composition unavailable for render source graph.");return e.composition}function sg(e,t,n){let r=xn(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(B=>({kind:B.kind,message:B.reason})),a=i.isOpaque,l=o.parentKey===null&&i.componentName==="Page",u=i.tag.toLowerCase(),d=i.tag!==u,p=!d&&ig(u),m=d||og(u),g=d&&i.childKeys.length>0&&!i.isPublicUiComponent,S=i.textSegments.length>0&&i.textSegments.some(B=>B.editable);p&&!s.some(B=>B.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' is void: children cannot be inserted`}),!p&&!m&&!s.some(B=>B.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' cannot contain structured children`});let C=S&&!a,v=!i.isPublicUiComponent&&!p&&m&&(!a||g);return{composition:r,key:e,canUpdateText:C,canInsertChild:v,canMove:!l,canRemove:!l,constraints:s}}function zc(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,sg(r,e,t));return n}import{createHash as cs}from"node:crypto";import ns from"@babel/traverse";function Li(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 _h}from"node:crypto";import Cl from"node:path";import*as ho from"@babel/parser";import Zi from"@babel/generator";import Qi from"@babel/traverse";import*as Nt from"@babel/types";import Bi from"@babel/traverse";var Rt=typeof Bi=="function"?Bi:Bi.default,eo=new WeakMap,Hc=new WeakMap;function ht(e,t){let n=Ii(e,t);if(!n.ok)return Ei(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=ie(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}}:Ei(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function ie(e,t){return t.kind==="jsx-node"?Zc(e,t):t.kind==="jsx-attribute"?fg(e,t):t.kind==="value"?pg(e,t):t.kind==="expression"?mg(e,t):t.kind==="directive"?gg(e,t):t.kind==="export"?hg(e,t):{ok:!1,diagnostic:Ut("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function Zc(e,t){return t.strategy==="source-range"?ag(e,t):cg(e,t)}function ag(e,t){let n=null;if(Rt(e,{JSXElement(o){if(!bn(o.node,t.sourceRange))return;let i=Ee("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!bn(o.node,t.sourceRange))return;let i=Ee("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!bn(o.node,t.sourceRange))return;let i=Ee("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)}}),!n)return ve("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!wg(r.path,t.expectedIdentity)?ve("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function cg(e,t){if(t.structuralPath===""){let r=ug(e,t.component);if(r){let o=dg(r);if(o)return o}}let n=null;return Rt(e,{JSXElement(r){if(Wn(r)!==t.component||$i(r)!==t.structuralPath)return;let i=Ee("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(Wn(r)!==t.component||$i(r)!==t.structuralPath)return;let i=Ee("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=lg(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:ve("jsx-node","locator-miss","JSX node not found for structural-path locator")}function lg(e,t,n){let r=null;return Rt(e,{JSXElement(o){if(Wn(o)!==t||!bn(o.node,n))return;let i=Ee("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(Wn(o)!==t||!bn(o.node,n))return;let i=Ee("jsx-node",o);i&&(r=i,o.stop())}}),r}function ug(e,t){let n=null;return Rt(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 dg(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 ve("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?ve("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 ve("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function fg(e,t){let n=Zc(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>Ng(c,t.name));if(!s||!s.isJSXAttribute())return ve("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=Ee("jsx-attribute",s);return a?{ok:!0,match:a}:ve("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function pg(e,t){let n=yg(e,t);if(!n.ok)return n;let r=xg(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!gt(r.match.path.node.loc,t.expectedRange)?ve("value","locator-miss","Resolved value does not match expected range"):{ok:!0,match:r.match}:r}function mg(e,t){let n=null;return Rt(e,{Identifier(r){if(!vg(r))return;let o=Gc(r);if(!o||!Yc(o,t))return;let i=Ee("expression",r);i&&(t.expectedRange&&!gt(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=Gc(r);if(!o||!Yc(o,t))return;let i=Ee("expression",r);i&&(t.expectedRange&&!gt(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:ve("expression","locator-miss","Expression not found")}function gg(e,t){let n=null;return Rt(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!gt(i.node.loc,t.expectedRange))return;let s=Ee("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:ve("directive","locator-miss",`Directive '${t.value}' not found`)}function hg(e,t){let n=null;return Rt(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let c=r.get("declaration");if(c.isFunctionDeclaration()&&c.node.id?.name==="generateMetadata"){let p=Ee("export",c);if(!p||t.expectedRange&&!gt(c.node.loc,t.expectedRange))return;n=p,r.stop();return}if(!c.isVariableDeclaration())return;let l=Vi(c,"generateMetadata");if(!l||!l.isVariableDeclarator())return;let u=l.get("init");if(!u.node)return;let d=Ee("export",u);if(!d||t.expectedRange&&!gt(u.node.loc,t.expectedRange))return;n=d,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=Vi(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!gt(s.node.loc,t.expectedRange))return;let a=Ee("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=Ee("export",o);i&&(t.expectedRange&&!gt(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:ve("export","export-not-found",`Export '${Rg(t)}' not found`)}function yg(e,t){let n=null;return Rt(e,{Expression(r){if(n||t.root.kind!=="expression"||!bn(r.node,t.root.sourceRange))return;let o=Ee("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 m=r.get("init");if(!m.node)return;let g=Ee("value",m);if(!g)return;n=g,r.stop();return}if(t.root.kind!=="hook-state")return;let o=t.root,i=r.get("id"),s=r.get("init");if(!i.isArrayPattern()||!s.isCallExpression()||i.node.elements.findIndex(m=>m?.type==="Identifier"&&m.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 p=Ee("value",d);p&&(n=p,r.stop())},ExportNamedDeclaration(r){if(n||t.root.kind!=="named-export")return;let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=Vi(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=Ee("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=Ee("value",o);i&&(n=i,r.stop())}}),n?{ok:!0,match:n}:ve("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 xg(e,t){let n=ji(e);for(let o of t){if(n=ji(n),o.kind==="property"){if(!n.isObjectExpression())return ve("value","unsupported-syntax","Property path requires object expression");let a=n.get("properties");if(a.some(l=>!l.isObjectProperty()))return ve("value","unsupported-syntax","Spread properties are not supported");let c=a.find(l=>Pg(l,o.name));if(!c||!c.isObjectProperty())return ve("value","property-not-found",`Property '${o.name}' not found`);n=c.get("value");continue}if(!n.isArrayExpression())return ve("value","unsupported-syntax","Array index path requires array expression");let i=n.get("elements");if(i.some(a=>a.node?.type==="SpreadElement"))return ve("value","unsupported-syntax","Spread array elements are not supported");let s=i[o.index];if(!s?.node)return ve("value","array-index-out-of-range",`Array index ${o.index} is out of range`);n=s}n=ji(n);let r=Ee("value",n);return r?{ok:!0,match:r}:ve("value","locator-miss","Resolved value has no source range")}function ji(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function Ee(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 bn(e,t){return gt(e.loc,t)}function gt(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 $i(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!to(n.node)){let o=Qc(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${Wc(n,o)}`):t.unshift(`${o}#${Wc(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||Ig(n.parentPath))break;n=n.parentPath}return t.join("/")}function to(e){let t=e.openingElement.name;return t.type==="JSXIdentifier"?t.name==="Fragment":t.type==="JSXMemberExpression"&&t.property.name==="Fragment"}function Wc(e,t){let n=Sg(e);if(!n)return 0;let r=eo.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=eo.get(n.node)?.get(t);if(!i){let s=eo.get(n.node);s||(s=new Map,eo.set(n.node,s)),i=new WeakMap,s.set(t,i)}for(let s of Hn(n))if(Qc(s.node.openingElement)===t){if(i.set(s.node,o),s.node===e.node)return o;o++}return i.get(e.node)??0}function Sg(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(to(t.node)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Hn(e){let t=Hc.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(to(o.node)){n.push(...Hn(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Hn(o));continue}o.isJSXExpressionContainer()&&n.push(...Sn(o.get("expression")))}return Hc.set(e.node,n),n}function Sn(e){return e.isJSXElement()?to(e.node)?Hn(e):[e]:e.isJSXFragment()?Hn(e):e.isParenthesizedExpression()?Sn(e.get("expression")):e.isLogicalExpression()&&bg(e.node.operator)?Sn(e.get("right")):e.isConditionalExpression()?[...Sn(e.get("consequent")),...Sn(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Sn(t)):[]}function bg(e){return e==="&&"||e==="||"||e==="??"}function Qc(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?Eg(e.name):null}function Eg(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 Wn(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 Ig(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function vg(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function Gc(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 Yc(e,t){return e.base===t.base&&kg(e.path,t.path??[])}function kg(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 Cg(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function Rg(e){return e.exportKind==="named"?e.name:e.exportKind}function ve(e,t,n,r){return{ok:!1,diagnostic:Ut(t,n,e,r)}}function wg(e,t){return Wn(e)!==t.component?!1:$i(e)===t.structuralPath}function Ng(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function Vi(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function Pg(e,t){return e.isObjectProperty()?Cg(e.node)===t:!1}import Ui from"@babel/generator";var Ag=typeof Ui=="function"?Ui:Ui.default;function Tg(e){let t=e.split(`
|
|
2
|
+
`),n=[],r=!1;for(let s of t){let a=s.match(/^(\s+)/);if(a){let c=a[1];c.includes(" ")?r=!0:c.length>0&&n.push(c.length)}}if(r&&t.every(a=>{let c=a.match(/^(\s+)/);return!c||c[1].includes(" ")}))return"tab";if(n.length===0)return"2";function o(s,a){return a===0?s:o(a,s%a)}let i=n[0];for(let s=1;s<n.length;s++)i=o(i,n[s]);return i>=4?"4":"2"}function _g(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 Fg(e,t){return e.split(`
|
|
3
|
+
`).map(r=>_g(r,t)).join(`
|
|
4
|
+
`)}function no(e){let{ast:t,source:n}=e;try{let r=Tg(n),i=Ag(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=Fg(i,r)),{ok:!0,source:i}}catch(r){return V(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}import*as el from"@babel/parser";import{arrayExpression as Mg,booleanLiteral as Og,identifier as Dg,jsxAttribute as Lg,jsxExpressionContainer as Bg,jsxIdentifier as jg,nullLiteral as $g,numericLiteral as Vg,objectExpression as Ug,objectProperty as Kg,stringLiteral as tl}from"@babel/types";function qc(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 Gn(e,t,n){return{ok:!0,source:t,operation:{type:n.kind,nodeId:n.target,kind:n.kind,target:n.target,beforeSourceHash:qc(e),afterSourceHash:qc(t),inverse:n.inverse}}}function ue(e,t,n){let r=no({ast:e,source:t});return r.ok?Gn(t,r.source,n):r}function ke(e,t){let n=vi(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function ro(e,t){return no({ast:e,source:t})}function Jg(e,t,n){let r=ie(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function nl(e,t,n){let r=Jg(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:V(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function rl(e,t){let n=ie(e,t);return n.ok?{ok:!0,match:n.match}:n.diagnostic.code==="locator-miss"?{ok:!0,match:null}:{ok:!1,diagnostic:n.diagnostic}}function En(e){return typeof e=="string"?tl(e):typeof e=="number"?Vg(e):typeof e=="boolean"?Og(e):e===null?$g():Array.isArray(e)?Mg(e.map(t=>En(t))):Ug(Object.entries(e).map(([t,n])=>Kg(Dg(t),En(n))))}function Xg(e){return typeof e=="string"?tl(e):Bg(En(e))}function oo(e,t){return Lg(jg(e),Xg(t))}function ol(e,t){try{let r=el.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:V(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:V(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function io(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=ke(t,"jsx-node");if(!i.ok)return i.result;let s=ie(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let c=zg(s.match.path)[r];if(!c)return V(t,"locator-miss",`Text segment ${r} not found`,"jsx-node");switch(c.kind){case"jsx-text":c.path.node.value=Hg(c.path.node.value,o);break;case"string-literal":c.path.node.value=o;break;case"template-literal":{let l=c.quasiIndex;c.path.node.quasis[l].value.raw=o,c.path.node.quasis[l].value.cooked=o;break}}return ue(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function zg(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=Wg(r.get("expression"));o.length>0&&t.push(...o)}}return t}function Hg(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function Wg(e){if(e.isStringLiteral())return[{kind:"string-literal",path:e}];if(e.isTemplateLiteral()){let t=[],n=e.node.quasis;for(let r=0;r<n.length;r++)n[r].value.raw.trim().length>0&&t.push({kind:"template-literal",path:e,quasiIndex:r});if(t.length>0)return t}return e.isCallExpression()?[]:[]}import{nullLiteral as Ki}from"@babel/types";function In(e){let{source:t,locator:n}=e,r=ke(t,"jsx-node");if(!r.ok)return r.result;let o=ie(r.ast,n);return o.ok?(Gg(o.match.path),ue(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function Gg(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Ki());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Ki());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Ki());return}e.remove()}import{cloneNode as sh}from"@babel/types";import Ji from"@babel/traverse";import*as U from"@babel/types";var Yg=typeof Ji=="function"?Ji:Ji.default;function Xe(e,t,n,r){if(!e.ok)return e;let o=Je(n);if(!o)return e;let i=Zg(t,o,r);return i?{...e,selectionRef:i}:e}function Zg(e,t,n){let r=Qg(e,t);if(!r)return;let o=n.sourceLocator?il(n.sourceLocator):void 0,i=n.targetParentLocator?il(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??eh(r)??i?.component??o?.component;if(!(!s||!a))return{key:Kn(s,a,th(r))}}function il(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function Qg(e,t){let n=null;return Yg(e,{JSXElement(r){r.node===t&&(n=r,r.stop())}}),n}function Je(e){if(!e)return null;if(U.isJSXElement(e))return vn(e)?sl(e.children):e;if(U.isJSXFragment(e))return sl(e.children);if(U.isJSXExpressionContainer(e)||U.isParenthesizedExpression(e)||U.isTSAsExpression(e)||U.isTSSatisfiesExpression(e)||U.isTSTypeAssertion(e)||U.isTSNonNullExpression(e))return Je(e.expression);if(U.isLogicalExpression(e))return Je(e.right);if(U.isConditionalExpression(e))return Je(e.consequent)??Je(e.alternate);if(U.isCallExpression(e)||U.isOptionalCallExpression(e))return dl(e)?qg(e.arguments[0]):null;if(U.isArrayExpression(e))for(let t of e.elements){if(!t)continue;let n=Je(t);if(n)return n}return null}function sl(e){for(let t of e){let n=Je(t);if(n)return n}return null}function qg(e){return!e||!U.isArrowFunctionExpression(e)&&!U.isFunctionExpression(e)?null:U.isBlockStatement(e.body)?Yn(e.body.body):Je(e.body)}function Yn(e){for(let t of e){if(U.isReturnStatement(t)){let n=Je(t.argument);if(n)return n;continue}if(U.isBlockStatement(t)){let n=Yn(t.body);if(n)return n;continue}if(U.isIfStatement(t)){let n=al(t.consequent);if(n)return n;let r=t.alternate?al(t.alternate):null;if(r)return r;continue}if(U.isSwitchStatement(t))for(let n of t.cases){let r=Yn(n.consequent);if(r)return r}}return null}function al(e){return U.isBlockStatement(e)?Yn(e.body):Yn([e])}function eh(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(U.isFunctionDeclaration(n))return n.id?.name??"default"}if(t.isVariableDeclarator()&&U.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 cl=new WeakMap,ll=new WeakMap,Xi=new WeakMap;function th(e){let t=cl.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=nh(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return cl.set(e.node,o),o}function nh(e){let t=zi(e.node.openingElement.name);return!t||vn(e.node)?null:/^[A-Z]/.test(t)?`component:${t}#${ul(e,t)}`:`${t}#${ul(e,t)}`}function ul(e,t){let n=rh(e);if(!n)return 0;let r=Xi.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Xi.get(n.node);o||(o=new Map,Xi.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of Ht(n))if(zi(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 rh(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(vn(t.node)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Ht(e){let t=ll.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(vn(o.node)){n.push(...Ht(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Ht(o));continue}o.isJSXExpressionContainer()&&n.push(...yt(o.get("expression")))}return ll.set(e.node,n),n}function yt(e){if(e.isJSXElement())return vn(e.node)?Ht(e):[e];if(e.isJSXFragment())return Ht(e);if(e.isParenthesizedExpression())return yt(e.get("expression"));if(e.isLogicalExpression())return yt(e.get("right"));if(e.isConditionalExpression())return[...yt(e.get("consequent")),...yt(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:yt(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&dl(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?oh(n):[]}return[]}function oh(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return vn(t.node)?Ht(t):[t];if(t.isJSXFragment())return Ht(t);if(t.isParenthesizedExpression())return yt(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return yt(t);if(!t.isBlockStatement())return[];for(let n of t.get("body")){if(!n.isReturnStatement())continue;let r=n.get("argument");return r.node?yt(r):[]}return[]}function dl(e){let t=e.callee;return(U.isMemberExpression(t)||U.isOptionalMemberExpression(t))&&U.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function vn(e){let t=zi(e.openingElement.name);return t==="Fragment"||t==="React.Fragment"}function zi(e){return U.isJSXIdentifier(e)?e.name:U.isJSXMemberExpression(e)?fl(e):U.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function fl(e){return`${U.isJSXIdentifier(e.object)?e.object.name:fl(e.object)}.${e.property.name}`}function wt(e,t){if(t.parentPath===e&&t.listKey==="children"&&pl(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!pl(n))return null;let r=n;for(;r&&r!==e;){if(!ih(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function pl(e){return e.isJSXElement()||e.isJSXFragment()}function ih(e){if(e.isJSXFragment())return!0;if(!e.isJSXElement())return!1;let t=e.node.openingElement.name;return t.type==="JSXIdentifier"?t.name==="Fragment":t.type==="JSXMemberExpression"&&t.property.name==="Fragment"}function kn(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=ke(t,"jsx-node");if(!a.ok)return a.result;let c=ie(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return V(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 w=c.match.path.node;if(!w.closingElement||w.openingElement.selfClosing)return V(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=ol(t,r.jsx);if(!u.ok)return u.result;let d=sh(u.node,!0),p=l.node.children,m={...s,targetParentLocator:n},g=w=>s?Xe(w,a.ast,d,m):w;if(o==="append")return p.push(d),g(ue(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return p.unshift(d),g(ue(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(!i)return V(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let S=ie(a.ast,i);if(!S.ok)return{ok:!1,source:t,diagnostic:S.diagnostic};let C=wt(c.match.path,S.match.path);if(!C)return V(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");l=C;let v=l.node.children,P=v.findIndex(w=>w===S.match.path.node);return P===-1?V(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(v.splice(o==="before"?P:P+1,0,d),g(ue(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as ml from"@babel/parser";import{cloneNode as ah}from"@babel/types";function so(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=ke(t,"jsx-node");if(!a.ok)return a.result;let c=ch(t,r);if(!c.ok)return c.result;let l=ie(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return V(t,"unsupported-syntax","insert-jsx-expression-child target must be a JSXElement or JSXFragment","jsx-node");if(l.match.path.isJSXElement()){let v=l.match.path.node;if(!v.closingElement||v.openingElement.selfClosing)return V(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=l.match.path,d=null;if(i){let v=ie(a.ast,i);if(!v.ok)return{ok:!1,source:t,diagnostic:v.diagnostic};let P=wt(l.match.path,v.match.path);if(!P)return V(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=P,d=v.match.path.node}else if(o==="before"||o==="after")return V(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let p=ah(c.node,!0),m=u.node.children,g={...s,targetParentLocator:n},S=v=>s?Xe(v,a.ast,p,g):v;if(o==="append")return m.push(p),S(ue(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return m.unshift(p),S(ue(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let C=m.findIndex(v=>v===d);return C===-1?V(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(m.splice(o==="before"?C:C+1,0,p),S(ue(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function ch(e,t){try{let r=ml.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:V(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:V(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as lh,nullLiteral as Hi}from"@babel/types";import*as Cn from"@babel/types";function Rn(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=ke(t,"jsx-node");if(!a.ok)return a.result;let c=ie(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let l=ie(a.ast,r);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return V(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 P=l.match.path.node;if(!P.closingElement||P.openingElement.selfClosing)return V(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let d=null;if(i){let P=ie(a.ast,i);if(!P.ok)return{ok:!1,source:t,diagnostic:P.diagnostic};let w=wt(l.match.path,P.match.path);if(!w)return V(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=w,d=P.match.path}else if(o==="before"||o==="after")return V(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let p=d&&typeof d.key=="number"?d.key:-1;if(d&&p===-1)return V(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let m=lh(c.match.path.node,!0);if(!Cn.isJSXElement(m)&&!Cn.isJSXExpressionContainer(m)&&!Cn.isJSXFragment(m))return V(t,"unsupported-syntax","move-node source must resolve to a JSX child","jsx-node");let g=c.match.path.parentPath?.node===u.node&&typeof c.match.path.key=="number"?c.match.path.key:-1;if(d&&c.match.path.parentPath?.node===d.parentPath?.node&&c.match.path.key===d.key)return V(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");uh(c.match.path);let S=u.node.children,C={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return S.push(m),Xe(ro(a.ast,t),a.ast,m,C);if(o==="prepend")return S.unshift(m),Xe(ro(a.ast,t),a.ast,m,C);let v=p-(g!==-1&&g<p?1:0);return S.splice(o==="before"?v:v+1,0,m),Xe(ro(a.ast,t),a.ast,m,C)}function uh(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Hi());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Hi());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Hi());return}e.remove()}import*as gl from"@babel/parser";import{cloneNode as dh,nullLiteral as Wi}from"@babel/types";function ao(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,c=ke(t,"jsx-node");if(!c.ok)return c.result;let l=fh(t,s);if(!l.ok)return l.result;let u=ie(c.ast,n);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};let d=ie(c.ast,r);if(!d.ok)return{ok:!1,source:t,diagnostic:d.diagnostic};if(!d.match.path.isJSXElement()&&!d.match.path.isJSXFragment())return V(t,"unsupported-syntax","move-repeat-template-child target parent must be a JSXElement or JSXFragment","jsx-node");if(d.match.path.isJSXElement()){let w=d.match.path.node;if(!w.closingElement||w.openingElement.selfClosing)return V(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let p=d.match.path,m=null;if(i){let w=ie(c.ast,i);if(!w.ok)return{ok:!1,source:t,diagnostic:w.diagnostic};let B=wt(d.match.path,w.match.path);if(!B)return V(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");p=B,m=w.match.path.node}else if(o==="before"||o==="after")return V(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!u.match.path.isJSXElement())return V(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let g=p.node,S=dh(l.node,!0);ph(u.match.path);let C={...a,sourceLocator:n,targetParentLocator:r},v=g.children;if(o==="append")return v.push(S),Xe(ue(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,S,C);if(o==="prepend")return v.unshift(S),Xe(ue(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,S,C);let P=v.findIndex(w=>w===m);return P===-1?V(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(v.splice(o==="before"?P:P+1,0,S),Xe(ue(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,S,C))}function fh(e,t){try{let r=gl.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:V(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:V(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function ph(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Wi());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Wi());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Wi());return}e.remove()}function co(e){let{source:t,locator:n,props:r}=e,o=ke(t,"jsx-node");if(!o.ok)return o.result;let i=nl(o.ast,n,t);if(!i.ok)return i.result;let s=i.match.path.node.openingElement;for(let[a,c]of Object.entries(r)){if(c===void 0)continue;let l={kind:"jsx-attribute",element:n,name:a},u=rl(o.ast,l);if(u.ok&&u.match!==null){let d=u.match.path.node;d.value=c===""?oo(a,"").value:oo(a,c).value}else s.attributes.push(oo(a,c))}return ue(o.ast,t,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}import{getBindingIdentifiers as mh,identifier as Zn,importDeclaration as gh,importDefaultSpecifier as hh,importNamespaceSpecifier as yh,importSpecifier as xh,isImportDefaultSpecifier as hl,isImportNamespaceSpecifier as yl,isImportSpecifier as xl,stringLiteral as Sh}from"@babel/types";function wn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(C=>!Nh(C));if(o!==-1){let C=r[o],v=C&&typeof C=="object"&&"kind"in C?C.kind:void 0;return V(t,"unsupported-syntax",`Unsupported import spec kind: ${String(v)}`)}let i=Ch(r);if(!i.ok)return V(t,"unsupported-syntax",i.message);let s=ke(t);if(!s.ok)return s.result;let{ast:a}=s,c=a.program,l=c.body.filter(C=>C.type==="ImportDeclaration"&&C.source.value===n),u=new Set(l.flatMap(C=>C.specifiers.flatMap(v=>{let P=Ph(C,v);return P?[P]:[]}))),d=i.imports.filter(C=>!u.has(kl(C)));if(d.length===0)return Gn(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let p=Rh(c.body),m=d.find(C=>p.has(Gi(C)));if(m)return V(t,"unsupported-syntax",`Import local binding already exists: ${Gi(m)}`);let g=kh(d);if(g.reduce((C,v)=>C+v.length,0)!==d.length)return V(t,"unsupported-syntax","Unsupported import specifier grouping");for(let C of g){if(!Il(bl(C)))return V(t,"unsupported-syntax","Unsupported import specifier combination");let v=l.find(P=>bh(P,C));if(v)Eh(v,C);else{let P=gh(Sl(C),Sh(n));wh(c.body,P),l.push(P)}}return ue(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function bh(e,t){return e.importKind==="type"?!1:Il(vh(Ih(e),bl(t)))}function Eh(e,t){let n=!1,r=new Set(e.specifiers.map(o=>Yi(o)));for(let o of Sl(t)){let i=Yi(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return vl(e.specifiers),{changed:n}}function Sl(e){let t=e.map(n=>{switch(n.kind){case"named":return xh(n.local?Zn(n.local):Zn(n.imported),Zn(n.imported));case"default":return hh(Zn(n.local));case"namespace":return yh(Zn(n.local));default:return n}});return vl(t),t}function bl(e){let t=El();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 Ih(e){let t=El();for(let n of e.specifiers)hl(n)?t.defaultLocals.add(n.local.name):yl(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function El(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function vh(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function Il(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function vl(e){let t=[...e.filter(n=>hl(n)),...e.filter(n=>yl(n)),...e.filter(n=>xl(n))];e.splice(0,e.length,...t)}function kh(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 Ch(e){let t=new Map,n=new Map;for(let r of e){let o=kl(r);if(t.has(o))continue;let i=Gi(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 Rh(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(mh(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 wh(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 Nh(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 kl(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 Gi(e){return e.kind==="named"?e.local??e.imported:e.local}function Ph(e,t){return e.importKind==="type"||xl(t)&&t.importKind==="type"?null:Yi(t)}function Yi(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 Nn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(u=>!Th(u));if(o!==-1){let u=r[o],d=u&&typeof u=="object"&&"kind"in u?u.kind:void 0;return V(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(d)}`)}let i=ke(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 Gn(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let l=a.body[c];return r.length===0?(a.body.splice(c,1),ue(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(l.specifiers=l.specifiers.filter(u=>!r.some(d=>Ah(u,d))),l.specifiers.length===0&&a.body.splice(c,1),ue(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function Ah(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 Th(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 Qn(e){let{source:t,locator:n,next:r}=e,o=po(t,n);return o.ok?(o.path.replaceWith(En(r)),ue(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function lo(e){let{source:t,locator:n,index:r,value:o}=e,i=po(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(s=>s?.type==="SpreadElement")?V(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>i.path.node.elements.length?V(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,0,En(o)),ue(i.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):V(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function uo(e){let{source:t,locator:n,index:r}=e,o=po(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(i=>i?.type==="SpreadElement")?V(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=o.path.node.elements.length?V(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(o.path.node.elements.splice(r,1),ue(o.ast,t,{kind:"remove-array-element",target:"value",inverse:"insert-array-element"})):V(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function fo(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=po(t,n);if(!i.ok)return i.result;if(!i.path.isArrayExpression())return V(t,"unsupported-syntax","Array operations require array expression target","value");if(i.path.node.elements.some(c=>c?.type==="SpreadElement"))return V(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 V(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),ue(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function po(e,t){let n=ke(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=ie(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}}}var Fh=typeof Zi=="function"?Zi:Zi.default;function es(e){let t=Tl(e);if(t)return{ok:!1,error:t};let n=e.projection,r=ts(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.containerSourceRange??n.container.sourceRange,i=r.placement;if((n.container.kind==="virtual-route-root"||n.container.kind==="starter-placeholder")&&(n.container.sourceRange===null||n.container.sourceKind==="jsx-element"||n.container.sourceKind==="atomic-expression"||n.container.kind==="starter-placeholder"))return n.container.sourceKind==="atomic-expression"?{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"An indirect page expression does not expose a safe return boundary.",diagnostics:[]}}:{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:i.placementUnitKey,importStep:Rl(e),returnStep:{kind:"insert-return",node:{jsx:`<${e.component.localName} />`},placement:i.relation,replaceOriginal:n.container.kind==="starter-placeholder"}}};if(!o)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition does not expose a safe placement boundary.",diagnostics:[]}};let a={kind:"jsx-node",strategy:"source-range",sourceRange:o},c=ht(e.source,a);if(!c.ok||!c.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:c.ok===!1?c.diagnostic.message:"Route page composition anchor could not be resolved.",diagnostics:c.ok?[]:[mo(c.diagnostic)]}};let l=go(e.source,c.match.node.start??null,c.match.node.end??null);if(Bh(o,n.container.sourceRange)&&n.container.sourceHash&&l!==n.container.sourceHash)return{ok:!1,error:{code:"VERSION_STALE",message:"Route page composition container hash no longer matches the current source.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Route page composition container hash no longer matches the current source."}]}};let u=Rl(e);return{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:r.placement.placementUnitKey,parentLocator:a,importStep:u,insertStep:{kind:"insert-child",parentLocator:a,node:{jsx:`<${e.component.localName} />`},placement:r.placement.relation,...r.placement.anchorSourceRange?{anchorLocator:{kind:"jsx-node",strategy:"source-range",sourceRange:r.placement.anchorSourceRange}}:{}}}}}function Rl(e){let t=Lh(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 Pl(e){let t;try{t=ho.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]})}catch(i){return{ok:!1,source:e.source,diagnostic:{message:i instanceof Error?i.message:String(i)}}}let n=ho.parseExpression(e.jsx,{plugins:["jsx","typescript"]}),r=!1;return(typeof Qi=="function"?Qi:Qi.default)(t,{ExportDefaultDeclaration(i){let s=i.get("declaration"),a=Mh(i,s);if(a){if(a.isArrowFunctionExpression()&&!a.get("body").isBlockStatement()){let c=a.get("body");c.replaceWith(wl(c.node,n,e.placement,e.replaceOriginal===!0)),r=!0,i.stop();return}a.traverse({Function(c){c.node!==a.node&&c.skip()},ReturnStatement(c){if(r)return;let l=c.get("argument");l.node&&(l.replaceWith(wl(l.node,n,e.placement,e.replaceOriginal===!0)),r=!0,c.stop())}}),r&&i.stop()}}}),r?{ok:!0,source:Fh(t,{}).code}:{ok:!1,source:e.source,diagnostic:{message:"Route default return boundary could not be resolved."}}}function Mh(e,t){if(t.isFunctionDeclaration()||t.isFunctionExpression()||t.isArrowFunctionExpression())return t;if(!t.isIdentifier())return null;let n=e.scope.getBinding(t.node.name);if(!n)return null;let r=n.path;if(r.isFunctionDeclaration()||r.isFunctionExpression())return r;if(r.isVariableDeclarator()){let o=r.get("init");if(o.isArrowFunctionExpression()||o.isFunctionExpression())return o}return null}function wl(e,t,n,r){if(Nt.isNullLiteral(e)||r)return t;let s=n==="before"||n==="prepend"?[t,e]:[e,t];return Nt.jsxFragment(Nt.jsxOpeningFragment(),Nt.jsxClosingFragment(),s)}function Al(e){let t=Tl(e);if(t)return{ok:!1,error:t};let n=e.projection;if(n.container.sourceRange===null)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition does not expose a safe placement boundary.",diagnostics:[]}};let r=_l(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:[]}};let i=qi(o.sourceRange),s=ht(e.source,i);if(!s.ok||!s.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:s.ok===!1?s.diagnostic.message:"Route page composition source anchor could not be resolved.",diagnostics:s.ok?[]:[mo(s.diagnostic)]}};if(go(e.source,s.match.node.start??null,s.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")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:"remove-node",locator:i}}};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||!Dh(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 c=ts(n,e.targetPlacement.placementKey,e.expectedDocumentVersion);if(!c.ok)return{ok:!1,error:{code:c.diagnostic.code==="DOCUMENT_VERSION_STALE"?"VERSION_STALE":"NO_SAFE_PAGE_PLACEMENT",message:c.diagnostic.message,diagnostics:[c.diagnostic]}};let l=c.placement;if(l.placementUnitKey!==e.targetPlacement.placementUnitKey||l.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 u=l.containerSourceRange;if(!u||!l.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 d=qi(u),p=ht(e.source,d);if(!p.ok||!p.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:p.ok===!1?p.diagnostic.message:"Route page composition target container could not be resolved.",diagnostics:p.ok?[]:[mo(p.diagnostic)]}};if(go(e.source,p.match.node.start??null,p.match.node.end??null)!==l.containerSourceHash)return Nl("Route page composition target container hash no longer matches the current source.");if(l.relation==="before"||l.relation==="after"){let g=l.anchorSourceRange,S=l.anchorSourceHash;if(!g||!S)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable anchor boundary.",diagnostics:[]}};let C=qi(g),v=ht(e.source,C);return!v.ok||!v.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:v.ok===!1?v.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:v.ok?[]:[mo(v.diagnostic)]}}:go(e.source,v.match.node.start??null,v.match.node.end??null)!==S?Nl("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:i,targetParentLocator:d,anchorLocator:C,placement:l.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:i,targetParentLocator:d,placement:l.relation}}}}function Nl(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function mo(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function Tl(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&&!Oh(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 Oh(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function Dh(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function Lh(e,t){let n=Cl.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Cl.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function qi(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function go(e,t,n){return t==null||n==null?null:`sha256:${_h("sha256").update(e.slice(t,n)).digest("hex")}`}function Bh(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 jh=typeof ns=="function"?ns:ns.default;function Ml(e){if(!e.ast)return ut(e,[Oe("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=Hh(e.ast);if(!t)return ut(e,[Oe("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=Gh(t);if(n.length===0)return ut(e,[Oe("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")]);if(n.length>1)return ut(e,[Oe("MULTIPLE_PAGE_RETURNS","Route default export contains multiple page-level return statements",{returnCount:n.length})]);let r=Yh(n[0].argument);if(!r)return ut(e,[Oe("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})]);if(r.isNullLiteral())return Fl(e,t,"virtual-route-root");if(Zh(r,t))return ut(e,[Oe("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(Qh(r,t)||qh(r)&&!e.source.includes("DESIGN_PLAN_REPLACE_ME"))return ut(e,[Oe("UNSUPPORTED_PAGE_SHAPE","Route default export shape does not provide a single safe placement boundary",{reason:"ambiguous-placement"})]);if(r.isJSXFragment()){let i=At(r);if(i.unsupported)return ut(e,[Oe("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);let s=rs({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-fragment",source:e.source,containerPath:r,members:i.members});return yo(e,t,s,{kind:"virtual-route-root",sourceKind:"jsx-fragment"})}if(r.isJSXElement()&&!Pn(r)){let i=ss(r),s=rs({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[i]});return yo(e,t,s,{kind:"virtual-route-root",sourceKind:"jsx-element"})}if(r.isJSXElement()){let i=At(r);if(i.unsupported)return ut(e,[Oe("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);let s=i.members;if(ty(e.source,r,s))return Fl(e,t,"starter-placeholder");let a=rs({input:e,containerKind:"jsx-container",sourceKind:"jsx-element",source:e.source,containerPath:r,members:s});return yo(e,t,a,{kind:"jsx-container",sourceKind:"jsx-element"})}if(ey(r))return ut(e,[Oe("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);let o=ry({input:e,source:e.source,expression:r});return yo(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"})}function ts(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Oe("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:Oe("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function _l(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Oe("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:Oe("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function Ol(e){return e.ok?$h(e.projection):Vh(e.projection)}function $h(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((S,C)=>Dl(e,u,S,C,e.container.placementKey)),p=d.filter(({member:S})=>S.isBusinessMember).map(({sourceMember:S})=>Kh(l,S,u.independent)),m=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,m.map(({sourceMember:S})=>S)),o.set(l,p);let g=m[0]?.sourceMember.key??l;n.push({key:l,containerKey:g,businessMemberKeys:p.map(S=>S.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:Uh(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function Vh(e){let t=e.diagnostics.map(Jh);return{status:"unsupported",version:e.version,composition:e.composition,reason:Xh(e.diagnostics),diagnostics:t}}function Uh(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 Dl(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)=>Dl(e,t,a,c,i))]}function Kh(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function Jh(e){return{code:zh(e),message:e.message}}function Xh(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 zh(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 Hh(e){let t=null;return jh(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=Wh(o.path);i&&(t=i,n.stop())}}),t}function Wh(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 Gh(e){if(e.isArrowFunctionExpression()){let r=e.get("body");if(!r.isBlockStatement())return[{argument:r}]}let t=e.get("body");if(!t.isBlockStatement())return[];let n=[];return t.traverse({Function(r){r.node!==e.node&&r.skip()},ReturnStatement(r){n.push({argument:r.get("argument")})}}),n}function Yh(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 Zh(e,t){if(e.isIdentifier())return xo(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return xo(n.node.name,t)}return!1}function Qh(e,t){return e.isConditionalExpression()?Pt(e.get("consequent"),t)||Pt(e.get("alternate"),t):e.isLogicalExpression()?Pt(e.get("left"),t)||Pt(e.get("right"),t):!1}function qh(e){if(!e.isJSXElement()||!Pn(e))return!1;let t=At(e).members;if(t.length!==1)return!1;let n=t[0];return n.kind==="jsx-element"&&!n.isBusinessMember&&n.businessMemberCount>0}function Pt(e,t){if(e.isIdentifier())return xo(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return xo(n.node.name,t)}return e.isConditionalExpression()?Pt(e.get("consequent"),t)||Pt(e.get("alternate"),t):e.isLogicalExpression()?Pt(e.get("left"),t)||Pt(e.get("right"),t):!1}function xo(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 ey(e){return e.isJSXSpreadChild()}function ty(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&is(t)}function is(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(!is(t))return!1;continue}if(t.isJSXElement()&&!is(t))return!1}return!0}function At(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:as(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:Qe(r.node.loc),businessMemberCount:0,parentSourceRange:Qe(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=At(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=Pn(o)?At(o):null;n||=i?.unsupported??!1,t.push({...ss(o,i?.members),sourceRange:Qe(r.node.loc),parentSourceRange:Qe(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:as(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:Qe(r.node.loc),businessMemberCount:1,parentSourceRange:Qe(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&Ll(r)){let o=At(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=Pn(r)?At(r):null;n||=o?.unsupported??!1,t.push({...ss(r,o?.members),parentSourceRange:Qe(e.node.loc)})}}return{members:t,unsupported:n}}function ss(e,t){let n=e.isJSXElement()&&Pn(e)?t??At(e).members:[],r=e.isJSXElement()&&!Pn(e)&&!Ll(e);return{memberKey:as(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:Qe(e.node.loc),businessMemberCount:r?1:Bl(n),parentSourceRange:Qe(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:ny(e)}}function Ll(e){if(e.isJSXFragment())return!0;let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name==="Fragment"||t.type==="JSXMemberExpression"&&t.object.type==="JSXIdentifier"&&t.object.name==="React"&&t.property.name==="Fragment"}function Pn(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name!=="Fragment"&&t.name[0]===t.name[0]?.toLowerCase()}function ny(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 Bl(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function So(e){return e.length===0?0:Math.max(1,Bl(e))}function rs(e){let t=Qe(e.containerPath.node.loc),n=$l(e.source,e.containerPath.node.start,e.containerPath.node.end),r=ze(e.input,e.containerKind,e.sourceKind,t),o=ze(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:So(e.members)<=1,memberCount:So(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function ry(e){let t=Qe(e.expression.node.loc),n=$l(e.source,e.expression.node.start,e.expression.node.end),r=ze(e.input,"virtual-route-root","atomic-expression",t),o=ze(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:ze(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 yo(e,t,n,r){let o=n.containerSourceRange??n.sourceRange,i=oy(e,n,o),s=Li(i),a={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Vl(t),container:{kind:r.kind,placementKey:n.placementKey,placementUnitKey:n.placementUnitKey,version:e.version,isEmptyPage:n.memberCount===0,sourceKind:r.sourceKind,sourceRange:o,sourceHash:n.sourceHash},placements:i,diagnostics:[],placementByKey:new Map,unitByKey:new Map,placementsByUnitKey:new Map,placementUnitByKey:new Map};return Object.defineProperties(a,{placementByKey:{value:s.placementByKey,enumerable:!1},unitByKey:{value:s.unitByKey,enumerable:!1},placementsByUnitKey:{value:s.placementsByUnitKey,enumerable:!1},placementUnitByKey:{value:s.sourcePlacementByUnitKey,enumerable:!1}}),{ok:!0,projection:a}}function oy(e,t,n){if(t.members.length===0)return[t];let r=[],o=(l,u,d,p,m,g,S=n)=>({...t,placementKey:u,placementUnitKey:d,containerKey:t.placementKey,independent:So(g)<=1,memberCount:So(g),sourceRange:p,sourceHash:p?os(e.source,p):null,relation:l,containerSourceRange:S,containerSourceHash:S?os(e.source,S):null,anchorSourceRange:m,anchorSourceHash:m?os(e.source,m):null,members:g}),i=t.placementKey,s=t.members.map(l=>ze(e,i,"placement-unit",l.sourceRange)),a=s[0]??t.placementUnitKey,c=s.at(-1)??t.placementUnitKey;r.push(o("prepend",ze(e,i,"prepend",n),a,n,null,[]));for(let l of t.members){let u=l.parentSourceRange??n,d=ze(e,i,"placement-unit",l.sourceRange);r.push(o("before",ze(e,d,"before",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u)),r.push(o("after",ze(e,d,"after",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u))}return r.push(o("append",i,c,n,null,[])),r}function Fl(e,t,n){let r=ze(e,n,"empty-container",void 0),o=ze(e,n,"empty-unit",void 0),i={placementKey:r,placementUnitKey:o,version:e.version,containerKey:r,independent:!0,memberCount:0,sourceRange:null,sourceHash:null,relation:"append",containerSourceRange:null,containerSourceHash:null,anchorSourceRange:null,anchorSourceHash:null,members:[]},s=Li([i]),a={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Vl(t),container:{kind:n,placementKey:r,placementUnitKey:o,version:e.version,isEmptyPage:!0,sourceKind:n==="starter-placeholder"?"starter-placeholder":"jsx-fragment",sourceRange:null,sourceHash:null},placements:[i],diagnostics:[],placementByKey:new Map,unitByKey:new Map,placementsByUnitKey:new Map,placementUnitByKey:new Map};return Object.defineProperties(a,{placementByKey:{value:s.placementByKey,enumerable:!1},unitByKey:{value:s.unitByKey,enumerable:!1},placementsByUnitKey:{value:s.placementsByUnitKey,enumerable:!1},placementUnitByKey:{value:s.sourcePlacementByUnitKey,enumerable:!1}}),{ok:!0,projection:a}}function ut(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 Oe(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function ze(e,t,n,r){return jl([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function as(e,t,n){return jl(["member",e,String(t??-1),String(n??-1)])}function jl(e){return`pc_${cs("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function $l(e,t,n){return t==null||n==null?null:`sha256:${cs("sha256").update(e.slice(t,n)).digest("hex")}`}function os(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:${cs("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function Qe(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function Vl(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}function sy(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var ay=160;function Ul(e,t,n,r={}){let o=xn(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 Kl(e,t,n,r,o,i,s,a,c,l,u,d,p){let m=xn(t),g=t.elements.get(e),S=n.nodes.get(e),C=r.get(e);if(!g||!S||!C)throw new Error(`Node not found: ${e}`);let v=Wl(g.textSegments,s),P=Gl(e,t,g,C,v),w=v?uy(v):void 0,B=dy(i,v),re=g.textSegments.map(M=>({index:M.index,value:M.value,editable:Yl(M,C,s?.get(M.index)??null),source:o.get(M.index)??null})),ne=zl(g,t),N=g.childKeys.map(M=>{let D=t.elements.get(M);return D?{key:M,tag:D.tag,label:D.tag}:null}).filter(M=>M!==null),X=[];if(g.parentKey){let M=t.elements.get(g.parentKey);if(M)for(let D of M.childKeys){if(D===e)continue;let Z=t.elements.get(D);Z&&X.push({key:D,tag:Z.tag,label:Z.tag})}}return{composition:m,key:e,tag:g.tag,componentName:g.componentName,sourceFile:g.sourceFile,sourceLocator:Xl(g),label:g.tag,capabilities:P,writeTarget:i,effectiveWriteTarget:B,provenanceChain:w,componentSemantic:c,contentModel:l,mediaModel:u,styleSource:d,conditional:a,...p?{dynamicData:p}:{},textSegments:re,boundaryKind:g.boundaryKind,isOpaque:g.isOpaque,ancestors:ne,children:N,siblings:X}}function Jl(e,t,n,r,o,i,s){let a=xn(t),c=t.elements.get(e),l=n.nodes.get(e),u=r.get(e);if(!c||!l||!u)throw new Error(`Node not found: ${e}`);let d=Wl(c.textSegments,i);return{composition:a,key:e,tag:c.tag,componentName:c.componentName,sourceFile:c.sourceFile,sourceLocator:Xl(c),label:c.tag,capabilities:Gl(e,t,c,u,d),provenanceChain:d?{editMode:d.editMode,diagnostics:d.diagnostics.map(p=>({code:p.code,message:p.message}))}:void 0,...s?{dynamicData:s}:{},textSegments:c.textSegments.map(p=>{let m=o.get(p.index);return{index:p.index,editable:Yl(p,u,i?.get(p.index)??null),source:m?{kind:m.kind}:null}}),boundaryKind:c.boundaryKind,isOpaque:c.isOpaque,ancestors:zl(c,t)}}function Xl(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:cy(e.sourceRange),structuralPath:e.identity.structuralPath,...ly(e.textSegments)}}function zl(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 cy(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function ly(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,ay)}:{}}function Hl(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 Wl(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function Gl(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&&Zl(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 Yl(e,t,n){return!e.editable||!t.canUpdateText?!1:n?Zl(n.editMode):!0}function Zl(e){return e==="direct"||e==="proxy"||e==="upstream"}function uy(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 dy(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}:sy(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}}function Ql(e){let{key:t,element:n,graph:r,provenances:o}=e,i=py(t,n,r),s=i?.tag??(Wt(n.tag)?n.tag:n.componentName),a=i?.identity.key??ql(n,r)??t,c=hy(i),l=yy(t,n,r,o,i),u=fy(t,n,r,o,a);return{componentName:s,instanceKey:a,templateOwner:gy(i??n,s),...c.length>0?{variantKeys:c}:{},...l.length>0?{slotKeys:l}:{},editableStrategy:u,impactScope:xy(u),alternativeStrategies:Sy(u)}}function fy(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return ls(e,n)?"instance":!Wt(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function ql(e,t){if(Wt(e.tag))return e.identity.key;let n=[...t.elements.values()].filter(r=>r.importedFrom===e.sourceFile&&my(r,e.componentName));return n.length!==1?null:n[0].identity.key}function py(e,t,n){if(Wt(t.tag))return t;let r=ls(e,n);if(r)return r;let o=ql(t,n);return o?n.elements.get(o)??null:null}function my(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function gy(e,t){return Wt(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function hy(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 yy(e,t,n,r,o){let i=new Set,s=ls(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&&Wt(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function ls(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(Wt(r.tag))return r;n=r.parentKey}return null}function Wt(e){return/^[A-Z]/.test(e)}function xy(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function Sy(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}var by=new Set(["markdown","body","content","value","document"]),eu=[];function nu(e){if(!(!vy(e.tag)||!e.attributes))for(let t of e.attributes){if(!by.has(t.name))continue;if(Iy(t))return{kind:"markdown",field:t.name,schema:"markdown",valuePath:t.source?.expression,operationBoundary:eu};let n=Ey(t.resolvedValue);if(n==="prosemirror-doc"||n==="node-array")return{kind:"rich-text-json",field:t.name,valuePath:t.source?.expression,schema:n,operationBoundary:eu};if(n==="unsupported-json-tree")return{kind:"rich-text-json",field:t.name,valuePath:t.source?.expression,schema:"unsupported-json-tree",operationBoundary:[],diagnostics:[{code:"unsupported-schema",field:t.name,message:'Only top-level node arrays and { type: "doc", content: [] } rich-text JSON are editable in stage D'}]}}}function Ey(e){if(e){if(Array.isArray(e)&&e.every(t=>tu(t)))return"node-array";if(tu(e)){if(e.type==="doc"&&Array.isArray(e.content))return"prosemirror-doc";if(Array.isArray(e.content)||Array.isArray(e.children))return"unsupported-json-tree"}}}function tu(e){return!Array.isArray(e)&&typeof e=="object"&&e!==null}function Iy(e){return e.name==="markdown"}function vy(e){return/^[A-Z]/.test(e)}var ky=["src","alt","poster","caption","width","height"];function ru(e){let t=e.attributes?.filter(i=>ky.includes(i.name))??[];if(t.length===0)return;let n=t.map(i=>i.name),r=Object.fromEntries(t.filter(i=>i.source?.expression).map(i=>[i.name,i.source.expression])),o=Ry(t.map(i=>i.value));return{kind:Cy(e.tag,n),sourceType:o,fields:n,editableFields:[],operationBoundary:[],...Object.keys(r).length>0?{valuePaths:r}:{}}}function Cy(e,t){return e==="img"?"image":e==="video"||t.includes("poster")?"video":"media"}function Ry(e){return e.some(t=>t.startsWith("cms:"))?"cms-media-field":e.some(t=>/^(\.?\/|\/)/.test(t))?"local-file-reference":"asset-id"}var us=["set-class-name-source","apply-style-draft"];function ou(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:us,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element"}]};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:us,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:us}}import{createHash as wy}from"node:crypto";var qn=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 le(e){return`sha256:${wy("sha256").update(e).digest("hex")}`}function au(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:le(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=Ny(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:le(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Unable to locate JSX element for key ${t.identity.key}`}]};let r=n.openingElement,o=r.attributes.find(c=>c.type==="JSXAttribute"&&c.name.type==="JSXIdentifier"&&c.name.name==="className"),i={key:e.key,composition:e.route.composition,filePath:t.sourceFile,componentName:t.componentName,openingElementRange:su(r),version:{documentVersion:e.route.graph.version,contentHash:le(e.route.source)}};if(!o)return{...i,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element."}]};let s=o.value,a=s?.type==="StringLiteral"?"stringLiteral":"expression";return{...i,sourceKind:a,attrRaw:iu(e.route.source,o),valueRaw:s?iu(e.route.source,s):null,attrRange:su(o),diagnostics:[]}}function cu(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 Ny(e,t){let n=ct({source:e,profile:Kt({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=ie(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:Py(t.sourceRange)});return!r.ok||r.match.node.type!=="JSXElement"?null:r.match.node}function lu(e){let t=ct({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 iu(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function su(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 Py(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}import*as ws from"@babel/parser";import gs from"@babel/traverse";import*as b from"@babel/types";import*as St from"node:path";import*as mu from"@babel/parser";import ps from"@babel/traverse";import*as An from"@babel/types";import*as G from"@babel/types";function Io(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?bo(n,t):null}if(e.isMemberExpression()){let n=Oy(e.node),r=Ay(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?bo(o,[...r,...t]):null}return e.isAwaitExpression()||fs(e.node)?Tt(Ly(e.node),t,"awaited or fetched expression"):null}function Ay(e){let t=[],n=e;for(;G.isMemberExpression(n);){if(n.computed)if(G.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(G.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(G.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return G.isIdentifier(n)?t:null}function bo(e,t=[]){let n=Ty(e,t);if(n)return n;let r=_y(e,t);if(r)return r;let o=Fy(e,t);return o||null}function tr(e){return e?.kind==="api-source"}function Ty(e,t){if(e.path.isVariableDeclarator()&&G.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&ds(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return Tt(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&G.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(c=>G.isObjectProperty(c)&&fu(c)==="data"&&er(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&ds(a.node))return Tt(e.identifier.name,t,"query hook data binding")}let n=My(e);if(!n||fu(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()||!ds(i.node)?null:Tt(e.identifier.name,t,"query hook data binding")}function _y(e,t){if(e.path.isVariableDeclarator()&&G.isArrayPattern(e.path.node.id)){let a=e.path.get("init");if(!a?.isCallExpression()||!du(a.node))return null;let[c,l]=e.path.node.id.elements;return!G.isIdentifier(c)||c.name!==e.identifier.name||!G.isIdentifier(l)?null:uu(e,l.name)?Tt(e.identifier.name,t,"state setter is updated by API data"):null}if(!e.path.isIdentifier())return null;let n=e.path.parentPath;if(!n?.isArrayPattern())return null;let r=n.parentPath;if(!r?.isVariableDeclarator())return null;let o=r.get("init");if(!o?.isCallExpression()||!du(o.node)||n.node.elements.findIndex(a=>a===e.path.node)!==0)return null;let s=n.node.elements[1];return G.isIdentifier(s)&&uu(e,s.name)?Tt(e.identifier.name,t,"state setter is updated by API data"):null}function Fy(e,t){let n=e.path.isVariableDeclarator()?e.path:e.path.findParent(o=>o.isVariableDeclarator());if(!n?.isVariableDeclarator())return null;let r=n.get("init");return r?.isExpression()?r.isAwaitExpression()?Tt(e.identifier.name,t,"awaited binding result"):fs(r.node)?Tt(e.identifier.name,t,"fetch-backed binding result"):null:null}function My(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 er(e,t){return G.isIdentifier(e)?e.name===t:G.isAssignmentPattern(e)?er(e.left,t):G.isObjectPattern(e)?e.properties.some(n=>G.isObjectProperty(n)?er(n.value,t):er(n.argument,t)):G.isArrayPattern(e)?e.elements.some(n=>!!n&&er(G.isRestElement(n)?n.argument:n,t)):!1}function uu(e,t){let n=!1,r=!1;return e.scope.path.traverse({CallExpression(i){fs(i.node)&&(n=!0),(Dy(i.node.callee,t)||i.node.arguments.some(s=>G.isIdentifier(s)&&s.name===t))&&(r=!0)}}),n&&r}function ds(e){let t=vo(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function du(e){return vo(e.callee)==="useState"}function fs(e){return Eo(e,t=>G.isCallExpression(t)&&vo(t.callee)==="fetch")}function Oy(e){let t=e;for(;G.isMemberExpression(t);)t=t.object;return G.isIdentifier(t)?t.name:null}function fu(e){return e.computed?null:G.isIdentifier(e.key)?e.key.name:G.isStringLiteral(e.key)?e.key.value:null}function vo(e){return G.isIdentifier(e)?e.name:G.isMemberExpression(e)&&G.isIdentifier(e.property)?e.property.name:null}function Dy(e,t){return Eo(e,n=>G.isIdentifier(n)&&n.name===t)}function Eo(e,t){if(t(e))return!0;let n=G.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(G.isNode(i)&&Eo(i,t))return!0;continue}if(G.isNode(o)&&Eo(o,t))return!0}return!1}function Ly(e){return G.isIdentifier(e)?e.name:G.isCallExpression(e)?vo(e.callee)??"api":G.isAwaitExpression(e)?"awaited-api":"api"}function Tt(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:By(e,t),reason:n}}function By(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var gu=typeof ps=="function"?ps:ps.default;function hu(e,t){let n=xu(e);if(!n)return{allowed:!0};let r=!1;return gu(n,{CallExpression(o){if(!Su(o.node,t.sourceRange)||!jy(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||tr(Io(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function yu(e,t){let n=xu(e);if(!n)return{allowed:!0};let r=!1;return gu(n,{JSXExpressionContainer(o){Su(o.node,t.sourceRange)&&(An.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 xu(e){try{return mu.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function jy(e){let t=e.callee;return An.isMemberExpression(t)&&An.isIdentifier(t.property)&&t.property.name==="map"}function Su(e,t){let n=e.loc;return n?pu({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&pu({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function pu(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 se from"@babel/types";function bu(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 dt(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return Gt(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(se.isObjectPattern(n)||se.isArrayPattern(n))return Gt(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(Vy(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function Gt(e,t,n=!1){return se.isIdentifier(e)?e.name===t&&n:se.isObjectPattern(e)?e.properties.some(r=>se.isObjectProperty(r)?Gt(r.value,t,n):Gt(r.argument,t,n)):se.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=se.isRestElement(r)?r.argument:r;return Gt(o,t,n)}):se.isAssignmentPattern(e)?Gt(e.left,t,!0):se.isRestElement(e)?Gt(e.argument,t,n):!1}function Tn(e,t){if(e.path.isObjectPattern()){if(t){let r=qe(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:dt(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:dt(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=Eu(r),i=!1,s=o?o.initBinding&&ms(o.initBinding)?(i=dt(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=Tn(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=qe(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||dt(e)}}}}let n=Jy(e);if(n){let r=$y(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||dt(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=Uy(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:dt(e)}}let i=nr(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:dt(e)}:null}if(ms(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:dt(e)}}return null}function $y(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=Eu(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=ms(i)?(a=dt(i),[...s]):(()=>{let u=Tn(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=qe(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||dt(t)}:null}function Eu(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=Xy(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function ms(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function Vy(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Uy(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=qe(i.node,t);if(a)return a}return null}function Iu(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=ko(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=nr(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=Ky(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=nr(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 ko(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=nr(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&qe(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=ko(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=ko(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=ko(r,t);if(o)return o}}return null}function qe(e,t,n=[]){if(se.isIdentifier(e))return e.name===t?n:null;if(se.isObjectPattern(e)){for(let r of e.properties)if(se.isObjectProperty(r)){let o=nr(r);if(!o)continue;let i=qe(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(se.isRestElement(r)){let o=qe(r.argument,t,n);if(o)return o}}if(se.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=se.isRestElement(o)?o.argument:o,s=qe(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return se.isAssignmentPattern(e)?qe(e.left,t,n):null}function Ky(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function Jy(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 nr(e){return e.computed?null:se.isIdentifier(e.key)?e.key.name:se.isStringLiteral(e.key)?e.key.value:null}function Xy(e){let t=[],n=e;for(;se.isMemberExpression(n);){if(n.computed)if(se.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(se.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(se.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return se.isIdentifier(n)?{base:n.name,path:t}:null}var Dt=typeof gs=="function"?gs:gs.default;function de(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 _n(e){return{file:e.file,component:e.component}}function zy(e){return e.target.kind==="node"?e.target.key:null}function Hy(e){return"kind"in e}function Co(e){return!Hy(e)}function Es(e,t){let n=St.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=St.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function hs(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=ht(n,de(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function Ns(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 He(e){try{return ws.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Wy(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function Gy(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 ce(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function Qt(e,t){let n=ce(e);return!!(n&&et(t,n))}function et(e,t){return t.start>=e.start&&t.end<=e.end}function Bu(e){if(b.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(b.isJSXMemberExpression(e)){let t=e;for(;b.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function Yy(e,t){let n=ce(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);if(!a||Qt(a.path.node,n))return;t.scope.getBinding(i)!==a&&r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=Bu(i.node.name);s&&o(s,i)}}),[...r].sort()}function vu(e,t,n){let r=He(e);if(!r)return{ok:!0};let o=ie(r,de(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=ie(r,de(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};if(qu(o.match.path,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let s=Yy(o.match.path,i.match.path);return s.length>0?{ok:!1,bindingNames:s}:{ok:!0}}function ku(e,t,n){let r=_t(t,n);return r?xt(e,r):null}function _t(e,t){let n=ie(e,de(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:Rs(e,t)}function xt(e,t){let n=t.findParent(S=>S.isArrowFunctionExpression()||S.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(S=>S===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(!b.isIdentifier(l)||l.name!=="map"||c.computed)return null;let u=a.get("object"),d=Po(e,u.node),p=r.node.params.map(S=>Po(e,S)),m=ce(i.node),g=ce(r.node);return!d||p.some(S=>S.length===0)||!m||!g?null:{callStart:m.start,callEnd:m.end,callbackStart:g.start,callbackEnd:g.end,collectionExpression:d,callbackParams:p,mapOperator:b.isOptionalMemberExpression(c)&&c.optional?"?.map":".map",collectionNeedsParens:_s(u.node),callbackPath:r,collectionPath:u}}function Po(e,t){let n=ce(t);return n?e.slice(n.start,n.end):""}function Ro(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function Zy(e,t){let n=ce(e.node);return n?Qy(t).some(r=>{let o=ce(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function Qy(e){let t=e.callbackPath.node.body;return b.isBlockStatement(t)?Ft(t.body):Ot(t)}function Ft(e){let t=[];for(let n of e){if(b.isReturnStatement(n)){n.argument&&t.push(...Ot(n.argument));continue}if(b.isBlockStatement(n)){t.push(...Ft(n.body));continue}if(b.isIfStatement(n)){let r=b.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...Ft(r)),n.alternate){let o=b.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...Ft(o))}continue}if(b.isSwitchStatement(n)){for(let r of n.cases)t.push(...Ft(r.consequent));continue}b.isTryStatement(n)&&(t.push(...Ft(n.block.body)),n.handler&&t.push(...Ft(n.handler.body.body)),n.finalizer&&t.push(...Ft(n.finalizer.body)))}return t}function Ot(e){return b.isJSXElement(e)?qy(e)?Cu(e.children):[e]:b.isJSXFragment(e)?Cu(e.children):b.isParenthesizedExpression(e)||b.isTSAsExpression(e)||b.isTSSatisfiesExpression(e)||b.isTSNonNullExpression(e)||b.isTSTypeAssertion(e)?Ot(e.expression):b.isConditionalExpression(e)?[...Ot(e.consequent),...Ot(e.alternate)]:b.isLogicalExpression(e)&&td(e.operator)?Ot(e.right):[]}function Cu(e){return e.flatMap(t=>b.isJSXElement(t)||b.isJSXFragment(t)?Ot(t):b.isJSXExpressionContainer(t)&&(b.isJSXElement(t.expression)||b.isJSXFragment(t.expression)||b.isConditionalExpression(t.expression)||b.isLogicalExpression(t.expression))?Ot(t.expression):[])}function qy(e){let t=e.openingElement.name;return b.isJSXIdentifier(t)?t.name==="Fragment":b.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function ex(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function ys(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function Ru(e,t,n,r={}){if(!r.preserveConditionalBoundary&&qu(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=ce(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(c=>Ts(c)).map(c=>n.callbackPath.scope.getBinding(c)?.path.node).filter(Boolean)),s=new Set,a=(c,l)=>{let u=l.scope.getBinding(c);if(!u||Qt(u.path.node,o)||i.has(u.path.node))return;t.scope.getBinding(c)!==u&&s.add(c)};return e.traverse({ReferencedIdentifier(c){a(c.node.name,c)},JSXOpeningElement(c){let l=Bu(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function wu(e,t,n){let r=ce(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>Ts(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return Ps(e,s=>{let a=s.scope.getBinding(s.node.name);if(!a||Qt(a.path.node,r)||o.has(a.path.node))return;t.scope.getBinding(s.node.name)!==a&&i.add(s.node.name)}),i.size>0?{ok:!1,bindingNames:[...i].sort()}:{ok:!0}}function tx(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>Ts(a)).map(a=>e.callbackPath.scope.getBinding(a)?.path.node).filter(Boolean)),r=new Set,o=(a,c)=>{let l=c.scope.getBinding(a);if(!l||n.has(l.path.node))return;t.scope.getBinding(a)!==l&&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(b.isIdentifier(l))o(l.name,c);else{let u=nx(l);u&&o(u,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function nx(e){let t=e;for(;b.isTSQualifiedName(t);)t=t.left;return b.isIdentifier(t)?t.name:null}function ju(e,t){let n=ce(e.node),r=new Set;return Ps(e,o=>{let i=o.scope.getBinding(o.node.name);if(!i||n&&Qt(i.path.node,n))return;t.scope.getBinding(o.node.name)!==i&&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 Ps(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function rx(e){let t=ox(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=nd(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=yx({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=Qu(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?_s(o):!0}}}function ox(e,t,n){let r=Uu(e,t);if(Ku(e,r),Ju(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 Dt(e,{JSXElement(s){Yu(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:As(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 ix(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=>or(a.file)));if(!t.has(or(e.sourceFile))||!t.has(or(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(or(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=lx(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=He(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=sx(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=$u({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!tt(s.file,e.targetFile)||As(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}}function sx(e,t){let n=new Map,r=i=>{let s=Fn(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 ax(i,n))o=r(s)||o}return[...n.values()]}function ax(e,t){let n=[],r=cx(e,t);for(let o of e.ast.program.body){if(b.isExportDefaultDeclaration(o)&&b.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=sr(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(b.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=ar(e.file,o.source.value);for(let s of o.specifiers){if(b.isExportNamespaceSpecifier(s)){let l=Mt(s.exported);for(let u of t.values())tt(u.file,i)&&n.push({file:e.file,namespace:Is(l,u.namespace),exportName:u.exportName});continue}if(!b.isExportSpecifier(s))continue;let a=Mt(s.local),c=[...t.values()].filter(l=>tt(l.file,i)&&Yt(l.namespace,a));if(c.length>0){let l=Mt(s.exported);for(let u of c){let d=sr(u.namespace,a,l);d&&n.push({file:e.file,namespace:d,exportName:u.exportName})}continue}t.has(Fn({file:i,exportName:a}))&&n.push({file:e.file,exportName:Mt(s.exported)})}continue}if(b.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!b.isExportSpecifier(i))continue;let s=Mt(i.local),a=r.get(s)??[];if(a.length>0){let c=Mt(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let u=sr(l.namespace,s,c);u&&n.push({file:e.file,namespace:u,exportName:l.exportName})}}}continue}if(b.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=ar(e.file,o.source.value),s=o.exported;if(s){let a=Mt(s);for(let c of t.values())tt(c.file,i)&&n.push({file:e.file,namespace:Is(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())tt(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function Is(e,t){return t?`${e}.${t}`:e}function Yt(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function sr(e,t,n){return!Yt(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function cx(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(!b.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=ar(e.file,i.source.value);for(let a of i.specifiers){if(b.isImportDefaultSpecifier(a)){let c=t.get(Fn({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(u=>tt(u.file,s)&&Yt(u.namespace,"default"));for(let u of l){let d=sr(u.namespace,"default",a.local.name);d&&r(a.local.name,{...u,namespace:d})}continue}if(b.isImportSpecifier(a)){let c=Mt(a.imported),l=[...t.values()].filter(d=>tt(d.file,s)&&Yt(d.namespace,c));for(let d of l)r(a.local.name,d);let u=t.get(Fn({file:s,exportName:c}));u&&r(a.local.name,u);continue}if(b.isImportNamespaceSpecifier(a))for(let c of t.values())tt(c.file,s)&&r(a.local.name,{...c,namespace:Is(a.local.name,c.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(b.isVariableDeclaration(i))for(let s of i.declarations){if(!b.isIdentifier(s.id)||!s.init)continue;let a=Mn(s.init);if(!a||!b.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(Fn));for(let d of c){let p=sr(d.namespace,a.name,s.id.name),m=p?{...d,namespace:p}:d,g=Fn(m);u.has(g)||(r(s.id.name,m),u.add(g),o=!0)}}}return n}function Fn(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${ks(e.file)}#${t}`}function Mt(e){return b.isIdentifier(e)?e.name:e.value}function lx(e,t){for(let n of e.program.body){if(b.isExportDefaultDeclaration(n)){let o=n.declaration;if((b.isFunctionDeclaration(o)||b.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(b.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!b.isExportNamedDeclaration(n))continue;let r=n.declaration;if((b.isFunctionDeclaration(r)||b.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(b.isVariableDeclaration(r)){for(let o of r.declarations)if(b.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!b.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:b.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function $u(e){let t=ux(e),n=[],r=Ju(e.ast,t);return Dt(e.ast,{JSXElement(o){tt(e.file,e.sourceFile)&&As(o)===e.sourceComponent||Yu(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function Vu(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function Uu(e,t){let n=Vu();return Dt(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function ux(e){let t=Vu();return tt(e.file,e.sourceFile)&&dx(t,Uu(e.ast,e.sourceComponent)),Dt(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=ar(e.file,o),s=e.componentIdentities.filter(a=>tt(a.file,i));if(s.length!==0)for(let a of r.specifiers){let c=n.scope.getBinding(a.local.name);if(c){if(b.isImportDefaultSpecifier(a)&&s.some(l=>l.exportName==="default")&&t.localBindings.add(c),b.isImportDefaultSpecifier(a)){let l=s.filter(u=>Yt(u.namespace,"default"));if(l.length>0){let u=t.namespaceMembers.get(c)??new Set;for(let d of l){let p=Pu(d,"default");p&&u.add(p)}t.namespaceMembers.set(c,u)}continue}if(b.isImportSpecifier(a)){let l=b.isIdentifier(a.imported)?a.imported.name:a.imported.value,u=s.filter(d=>Yt(d.namespace,l));if(u.length>0){let d=t.namespaceMembers.get(c)??new Set;for(let p of u){let m=Pu(p,l);m&&d.add(m)}t.namespaceMembers.set(c,d);continue}s.some(d=>!d.namespace&&d.exportName===l)&&t.localBindings.add(c);continue}if(b.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)}}}}}),Ku(e.ast,t),t}function dx(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 Ku(e,t){Dt(e,{VariableDeclarator(n){if(!n.node.init)return;let r=Mn(n.node.init);if(r){if(b.isIdentifier(n.node.id)){let o=Zt(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&vs(t,i,o);return}if(b.isObjectPattern(n.node.id)){let o=Zt(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&Hu(n.node.id,o.namespaceMembers,t,n)}}}})}function Ju(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return Dt(e,{ReferencedIdentifier(r){if(n){r.stop();return}fx(r)||!r.isIdentifier()||!Xu(r,t)||px(r,t)||mx(r)||(n=!0,r.stop())}}),n}function fx(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 Xu(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)&&Zt(r.node,t,r)?r:null}function px(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!Nu(e,r))return!1;let o=Xu(e,t);if(!o)return!1;if(Mn(r.node)===o.node)return!!Zt(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&Nu(e,a)&&!!Zt(a.node,t,a)}function mx(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function Nu(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Zt(e,t,n){let r=Mn(e);if(!r)return null;if(b.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(b.isObjectExpression(r))return gx(r,t,n);let o=Gu(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?zu(s,o.slice(1).join(".")):null}function gx(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!b.isObjectProperty(i))continue;let s=Wu(i);if(!s||!b.isExpression(i.value)){b.isExpression(i.value)&&(o||=Zt(i.value,t,n)!==null);continue}let a=Zt(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 zu(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 vs(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 Hu(e,t,n,r){for(let o of e.properties){if(b.isRestElement(o)){if(b.isIdentifier(o.argument)){let c=r.scope.getBinding(o.argument.name);c&&vs(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!b.isObjectProperty(o))continue;let i=Wu(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=zu(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=b.isAssignmentPattern(o.value)?o.value.left:o.value;if(b.isIdentifier(a)){let c=r.scope.getBinding(a.name);c&&vs(n,c,s);continue}if(b.isObjectPattern(a)&&s.namespaceMembers.size>0){Hu(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function Wu(e){return e.computed?b.isStringLiteral(e.key)||b.isNumericLiteral(e.key)?String(e.key.value):null:hx(e.key)}function hx(e){return b.isIdentifier(e)?e.name:b.isStringLiteral(e)||b.isNumericLiteral(e)?String(e.value):null}function Mn(e){return b.isParenthesizedExpression(e)||b.isTSAsExpression(e)||b.isTSSatisfiesExpression(e)||b.isTSNonNullExpression(e)||b.isTSTypeAssertion(e)?Mn(e.expression):b.isExpression(e)?e:null}function Gu(e){if(b.isIdentifier(e))return[e.name];if((b.isMemberExpression(e)||b.isOptionalMemberExpression(e))&&!e.computed&&b.isIdentifier(e.property)){let t=Mn(e.object),n=t?Gu(t):null;return n?[...n,e.property.name]:null}return null}function Pu(e,t){if(!Yt(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 Yu(e,t){let n=e.node.openingElement.name;if(b.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=Zu(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 Zu(e){if(b.isJSXIdentifier(e))return[e.name];if(b.isJSXMemberExpression(e)){let t=Zu(e.object);return t?[...t,e.property.name]:null}return null}function As(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()&&b.isIdentifier(n.node.id))return n.node.id.name}return null}function yx(e){let t=ce(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||Qt(a.path.node,t))return;let c=bx(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 u=Ix(e.callSitePath,c.propName,e.source);if(!u.ok){o=u.reason;return}let d=xx(u.expression,c.remainingPath);if(!d){o="Cannot move prop-backed repeat child because the mapped prop path is not a portable expression";return}let p=ju(u.expressionPath,e.targetParentPath);if(!p.ok){o=p.reason??`Cannot move prop-backed repeat child because the mapped prop source is not visible at the target: ${p.bindingNames.join(", ")}`;return}n.set(`${c.range.start}:${c.range.end}`,{...c.range,text:d});return}e.targetParentPath.scope.getBinding(s.node.name)!==a&&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:vx(e.source,t,[...n.values()])}}function xx(e,t){if(t.length===0)return e;let n=Qu(e);if(!n)return null;let r=_s(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=Sx(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function Sx(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function bx(e,t,n){let r=Ex(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=Tn(t,o);if(!i)return null;let s=r?.range??ce(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function Ex(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!Qt(n.node,t)||n.node.computed||!b.isIdentifier(n.node.property))return null;let r=ce(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function Ix(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()&&b.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=Po(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 vx(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 Qu(e){try{let n=ws.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=b.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&b.isExpression(r)?r:null}catch{return null}}function kx(e){let t=ce(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||Qt(s.path.node,t))return;let a=Au(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let u=Au(c,e.targetFile,e.targetFile);(!u||u.moduleFile!==a.moduleFile||!Cx(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 Ps(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 Cx(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 Au(e,t,n){let r=Rx(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=ar(t,i),a=i.startsWith(".")?Es(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=b.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 Rx(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function ar(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?St.normalize(St.join(St.dirname(e),t)).replace(/\\/g,"/"):t}function tt(e,t){return ks(e)===ks(t)}function ks(e){let t=or(e);return t.endsWith("/index")?t.slice(0,-6):t}function or(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function Ts(e){let t=[],n=r=>{if(r){if(b.isIdentifier(r)){t.push(r.name);return}if(b.isObjectPattern(r)){for(let o of r.properties){if(b.isRestElement(o)){n(o.argument);continue}b.isObjectProperty(o)&&n(o.value)}return}if(b.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(b.isAssignmentPattern(r)){n(r.left);return}if(b.isRestElement(r)){n(r.argument);return}b.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function wx(e){let t=[];for(let n of e.callbackPath.node.params){if(b.isIdentifier(n)){t.push(n.name);continue}if(b.isRestElement(n)&&b.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 Nx(e,t){return{...e,callbackParams:t}}function Tu(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function _s(e){return!(b.isIdentifier(e)||b.isThisExpression(e)||b.isMemberExpression(e)||b.isOptionalMemberExpression(e)||b.isCallExpression(e)||b.isOptionalCallExpression(e))}function qu(e,t){return ed(e,t).length>0}function xs(e,t){let n=ce(e.node),r=ce(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()&&!Px(o,n,r)))return!0;o=o.parentPath}return!1}function Px(e,t,n){let r=ce(e.node.consequent);if(r&&et(r,t)&&!et(r,n))return!1;let o=e.node.alternate?ce(e.node.alternate):null;return!(o&&et(o,t)&&!et(o,n))}function ed(e,t){let n=ce(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=ce(o.node.consequent),a=ce(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()&&td(o.node.operator)){let s=ce(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 _u(e,t,n,r){let o=ed(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=Po(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=Ax(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${_x(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function Ax(e,t){return Tx(e.node)?t:`(${t})`}function Tx(e){return b.isIdentifier(e)||b.isThisExpression(e)||b.isSuper(e)||b.isMemberExpression(e)||b.isOptionalMemberExpression(e)||b.isCallExpression(e)||b.isOptionalCallExpression(e)||b.isBooleanLiteral(e)||b.isNumericLiteral(e)||b.isStringLiteral(e)||b.isNullLiteral(e)||b.isUnaryExpression(e)}function td(e){return e==="&&"||e==="||"||e==="??"}function _x(e){return e.trim().startsWith("<")?e:`(${e})`}function nd(e,t){let n=ce(e.node),r=ce(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=Fu(e),i=Fu(t);if(!o||!i||!Fx(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=Mx(s.node,n);if(a&&!et(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=ce(s.node.right);if(a&&et(a,n)&&!et(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())&&Ox(s)){let a=ce(s.node.body)??ce(s.node);if(a&&!et(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 Fu(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?ce(t.node.argument):null;if(t.isArrowFunctionExpression()&&(b.isJSXElement(t.node.body)||b.isJSXFragment(t.node.body)||b.isConditionalExpression(t.node.body)||b.isLogicalExpression(t.node.body)))return ce(t.node.body);t=t.parentPath}return null}function Fx(e,t){return e.start===t.start&&e.end===t.end}function Mx(e,t){let n=ce(e.consequent);if(n&&et(n,t))return n;let r=ce(e.alternate);return r&&et(r,t)?r:null}function Ox(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(b.isMemberExpression(n)||b.isOptionalMemberExpression(n))&&b.isIdentifier(n.property)&&n.property.name==="map"&&!n.computed}var Dx={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 wo(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=Dx[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 Lx(e,t){for(let n of e.program.body){if(!b.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>b.isImportDefaultSpecifier(o));if(r&&b.isImportDefaultSpecifier(r))return r.local.name}return null}function Bx(e,t,n){for(let r of e.program.body){if(!b.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>b.isImportSpecifier(i)&&(b.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&b.isImportSpecifier(o))return o.local.name}return null}function Mu(e){let t=new Set;return Dt(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function Ou(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function jx(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=Ns(e),o=He(t);if(n.exportName!=="default"){let a=o?Bx(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?Ou(r,Mu(o)):r;return{localName:c,importStep:Ss(e,c)}}if(!o)return{localName:r,importStep:Ss(e,r)};let i=Lx(o,n.source);if(i)return{localName:i};let s=Ou(r,Mu(o));return{localName:s,importStep:Ss(e,s)}}function $x(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??Ns(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 Vx(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?Ux(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function Ux(e){return Object.fromEntries(Object.entries(e).filter(t=>Cs(t[1])))}function Cs(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(Cs):typeof e=="object"?Object.values(e).every(Cs):!1}function Kx(e,t){let n=He(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=$u({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 Ss(e,t=Ns(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 Du(e,t){if("kind"in e)return{parentNode:null,anchorNode:null,placement:e.relation};if("parentKey"in e)return{parentNode:t.getNode(e.parentKey),anchorNode:null,placement:e.relation};let n=t.getNode(e.anchorKey);return{parentNode:n?.parentKey?t.getNode(n.parentKey)??n:n,anchorNode:n,placement:e.relation}}function Jx(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function rr(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function Fs(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function ir(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:Fs(e,t.slice(0,n)),index:r.index}}return null}function bs(e,t){return e.locator?e.collectionPathMap?.[t]?Fs(e.locator,e.collectionPathMap[t]):ir(e.locator)?zx(e.locator,Hx(t,e.collectionIndexMap)):null:null}function Xx(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:rd(o,t)}function rd(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=rd(r,t);return o===void 0?void 0:{[n.name]:o}}function No(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 zx(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},Fs(e,i)}return null}function Hx(e,t){return t?.[e]??e}function Lu(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 Wx(e,t){return Gx(e.root,t.root)&&Zx(e.path??[],t.path??[])}function Gx(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&&Yx(e.sourceRange,t.sourceRange)}}function Yx(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function Rs(e,t){let n=null;return Dt(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 Zx(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 Ao=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:rr(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:rr(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:rr(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:rr(t.kind,t.params.kind)};let r=t;if(!Co(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=Du(r.params.position,this.graph);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:rr(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"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=zy(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.buildSetPropsSteps({initialOrder:0,node:r,props:n.params.props,request:n});return i.ok?this.buildPlan(t,n,i.steps,o):i}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.buildSetPropsSteps({initialOrder:s.length,node:r,props:n.params.props,request:n});if(!a.ok)return a;s.push(...a.steps)}return this.buildPlan(t,n,s,i)}async buildSetPropsSteps(t){let{initialOrder:n,node:r,props:o,request:i}=t,s=r.file,a=[],c={};for(let[l,u]of Object.entries(o)){if(u===void 0)continue;let d=await this.graph.getElementPropertyWriteTarget?.(r.key,l),p=r.attributes?.find(m=>m.name===l);if(!(typeof p?.resolvedValue=="string"&&p.resolvedValue===u||p?.source===null&&p.value===u)){if(d?.kind==="external-entry")return{ok:!1,errorCode:"capability-denied",reason:`set-props cannot overwrite readonly external property '${l}'`};if(d?.kind==="value-binding"&&d.locator){let m=d.locator;if(d.sourceKind==="repeat-template"&&typeof i.selectionRef?.instanceIndex=="number"){let g=bs(d,i.selectionRef.instanceIndex);if(!g)return{ok:!1,errorCode:"invalid-params",reason:"set-props could not resolve the selected repeat item"};m=g}a.push({order:n+a.length,file:d.file,type:"update-value",locator:m,value:u});continue}c[l]=u}}return Object.keys(c).length>0&&a.push({order:n+a.length,file:s,type:"set-props",locator:de(r),props:c}),{ok:!0,steps:a}}buildTextRewriteSteps(t,n,r,o,i){if(o?.kind==="value-binding"&&o.locator){if(o.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let a=bs(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:de(t),segmentIndex:n,newText:r}]}}coerceTextValueForValueTarget(t,n,r,o="update-text"){let i=this.graph.getFileContent(t),s=He(i);if(!s)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not inspect the value source`};let a=ie(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!Wy(a.match.path))return{ok:!0,value:r};let c=Gy(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=bs(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=He(this.graph.getFileContent(t));if(!o)return!1;let i=ie(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){if(!o.canUpdateText)return{ok:!1,errorCode:"capability-denied",reason:"Cannot update text on this node"};let s=this.buildTextRewriteSteps(r,n.params.segmentIndex,n.params.value,i,n.selectionRef);return s.ok?this.buildPlan(t,n,s.steps,o):s}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 p=ir(d.locator);if(p)return this.buildPlan(t,n,[{order:0,file:d.file,type:"remove-bound-array-item",locator:p.locator,index:p.index}],o)}return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed node removal requires a writable array target"}}let s=No(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:de(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||Kx(n,t)>1)return null;let r=Es(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(!Co(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=No(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 p=this.getRepeatBackedTemplateStructureReason(r);if(p)return{ok:!1,errorCode:"unsupported-operation",reason:p};let m=hu(this.graph.getFileContent(r.file),r);if(!m.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:m.reason??"Cannot insert child into this node"};let g=wo(r,n.params.node);if(g)return{ok:!1,errorCode:"unsupported-operation",reason:g};let S=[],C=0,v=n.params.node.kind==="component-call"?jx(n.params.node,this.graph.getFileContent(r.file)):void 0,P=v?.importStep;return P&&S.push({order:C++,file:r.file,type:"add-import",moduleSpecifier:P.moduleSpecifier,imports:P.imports}),S.push({order:C++,file:r.file,type:"insert-child",parentLocator:de(r),node:{jsx:$x(n.params.node,v?.localName)},placement:n.params.position.relation,anchorLocator:i?de(i):void 0}),this.buildPlan(t,n,S,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!Co(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:Vx(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(!Co(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=ir(a.locator);if(!c)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let l=Xx(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"?Lu(0,a.collectionIndexMap):Lu(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=No(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 this.isRepeatTemplateRootNode(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:")||this.isInsideMapCallback(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}isRepeatTemplateRootNode(t){let n=He(this.graph.getFileContent(t.file));if(!n)return t.isRepeatItemRoot===!0;let r=ie(n,de(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:Rs(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=xt(this.graph.getFileContent(t.file),o);return i?Zy(o,i):t.isRepeatItemRoot===!0}isInsideMapCallback(t){let n=He(this.graph.getFileContent(t.file));if(!n)return!1;let r=ie(n,de(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:Rs(n,t);return o?!!o.findParent(i=>{if(!i.isCallExpression()&&!i.isOptionalCallExpression())return!1;let s=i.node.callee;return(b.isMemberExpression(s)||b.isOptionalMemberExpression(s))&&b.isIdentifier(s.property)&&s.property.name==="map"}):!1}planRepeatTemplateInternalMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&this.isRepeatTemplateRootNode(r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=He(c);if(!l)return null;let u=_t(l,r),d=_t(l,o);if(!u||!d)return null;let p=xt(c,u),m=xt(c,d);if(!Ro(p,m))return null;if(a&&(s==="before"||s==="after")){let S=_t(l,a),C=S?xt(c,S):null;if(!Ro(p,C))return null}if(xs(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let g=vu(c,r,o);return g.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:de(r),targetParentLocator:de(o),placement:s,anchorLocator:a?de(a):void 0,selectionContext:_n(o)}],i):{ok:!1,errorCode:"unsupported-operation",reason:g.reason??`Cannot move node because it depends on bindings outside the target scope: ${g.bindingNames.join(", ")}`}}planRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&this.isRepeatTemplateRootNode(r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=He(c);if(!l)return null;let u=_t(l,r),d=_t(l,o);if(!u||!d)return null;let p=xt(c,u);if(!p)return null;let m=xt(c,d);if(Ro(p,m))return null;if(m&&!ex(m,p))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")){let w=ku(c,l,a);if(m&&!Ro(m,w)||!m&&w)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 w=wo(o,{kind:"native-tag",tag:r.tag});if(w)return{ok:!1,errorCode:"unsupported-operation",reason:w}}let g=hs(this.graph,r);if(!g)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(xs(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let S=_u(c,u,d,g);for(let w of S.conditionPaths){let B=wu(w,d,p);if(!B.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${B.bindingNames.join(", ")}`}}let C=Ru(u,d,p,{preserveConditionalBoundary:S.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 v=tx(p,d);if(!v.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its callback parameters depend on bindings outside the target scope: ${v.bindingNames.join(", ")}`};let P=p;if(r.component!==o.component){let w=rx({source:c,ast:l,sourceContext:p,sourceNode:r,targetParent:o,targetParentPath:d});if(!w.ok)return{ok:!1,errorCode:"unsupported-operation",reason:w.reason};P=w.context}else{let w=ju(p.collectionPath,d);if(!w.ok)return{ok:!1,errorCode:"unsupported-operation",reason:w.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${w.bindingNames.join(", ")}`}}return this.buildPlan(t,n,[{order:0,file:r.file,type:"move-repeat-template-child",locator:de(r),targetParentLocator:de(o),placement:s,anchorLocator:a?de(a):void 0,repeatExpression:Tu(P,S.sourceJsx),selectionContext:_n(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&this.isRepeatTemplateRootNode(r)||r.file===o.file)return null;let c=this.graph.getFileContent(r.file),l=this.graph.getFileContent(o.file),u=He(c),d=He(l);if(!u||!d)return null;let p=ix({knownSourceFiles:this.graph.getKnownSourceFiles?.(),routeEntryFiles:this.graph.getRouteEntryFiles?.(),sourceAst:u,sourceFile:r.file,targetFile:o.file,sourceComponent:r.component,targetComponent:o.component});if(!p.ok)return{ok:!1,errorCode:"unsupported-operation",reason:p.reason};let m=_t(u,r),g=_t(d,o);if(!m||!g)return null;let S=nd(p.callSitePath,g);if(!S.ok)return{ok:!1,errorCode:"unsupported-operation",reason:S.reason};let C=xt(c,m);if(!C)return null;if(xt(l,g))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")&&ku(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 M=wo(o,{kind:"native-tag",tag:r.tag});if(M)return{ok:!1,errorCode:"unsupported-operation",reason:M}}let P=hs(this.graph,r);if(!P)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(xs(m,g))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let w=_u(c,m,g,P);for(let M of w.conditionPaths){let D=wu(M,g,C);if(!D.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${D.bindingNames.join(", ")}`}}let B=Ru(m,g,C,{preserveConditionalBoundary:w.conditionPaths.length>0});if(!B.ok)return{ok:!1,errorCode:"unsupported-operation",reason:B.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${B.bindingNames.join(", ")}`};let re=kx({sourceFile:r.file,targetFile:o.file,sourceContext:C,targetParentPath:g});if(!re.ok)return{ok:!1,errorCode:"unsupported-operation",reason:re.reason};let ne=wx(C);if(!ne.ok)return{ok:!1,errorCode:"unsupported-operation",reason:ne.reason};let N=Nx(C,ne.callbackParams),X=[{order:0,file:r.file,type:"remove-node",locator:de(r),removeWhitespace:!0}];for(let M of re.imports)X.push({order:X.length,file:o.file,type:"add-import",moduleSpecifier:M.moduleSpecifier,imports:M.imports});return X.push({order:X.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:de(o),expression:Tu(N,w.sourceJsx),placement:s,anchorLocator:a?de(a):void 0,selectionContext:_n(o)}),this.buildPlan(t,n,X,i)}async planMoveNode(t,n,r,o){if(!o.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};let i=Du(n.params.target,this.graph),s=i.parentNode;if(!s)return{ok:!1,errorCode:"locator-miss",reason:`Target parent for request '${n.id}' not found in graph`};if(Jx(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 a=await this.graph.getTextWriteTarget(r.key,0);if(a?.kind==="external-entry"){let v=n.params.target.relation,P=i.anchorNode&&(v==="before"||v==="after")?await this.graph.getTextWriteTarget(i.anchorNode.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:"move-node",value:{operation:"move-node",relation:v,anchorSourceId:P?.kind==="external-entry"?P.sourceId:null,parentKey:"parentKey"in n.params.target?n.params.target.parentKey:null}}],o)}let c=r.file!==s.file,l=n.params.target.relation,u=i.anchorNode,d=No(r,a,this.graph.getTextProvenance?.(r.key,0)??null);if(d&&!ys(d))return{ok:!1,errorCode:"unsupported-operation",reason:d};if(r.isRepeatItemRoot&&u?.isRepeatItemRoot&&r.repeatOwnerKey&&r.repeatOwnerKey===u.repeatOwnerKey&&(l==="before"||l==="after")){let v=a,P=await this.graph.getTextWriteTarget(u.key,0);if(v?.kind==="value-binding"&&P?.kind==="value-binding"&&v.locator&&P.locator){let w=ir(v.locator),B=ir(P.locator);if(w&&B&&v.file===P.file&&Wx(w.locator,B.locator)){let re=w.index,ne=B.index,N=l==="before"?ne-(re<ne?1:0):ne+(re<ne?0:1);return this.buildPlan(t,n,[{order:0,file:v.file,type:"move-array-item",locator:w.locator,fromIndex:re,toIndex:N}],o)}}}if(r.isRepeatItemRoot&&this.isRepeatTemplateRootNode(r))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed item outside its collection"};let p=this.getRepeatBackedTemplateStructureReason(r),m=ys(d)?d:p;if(m&&ys(m)){let v=this.planRepeatTemplateInternalMove(t,n,r,s,o,l,u);if(v)return v;let P=this.planRepeatTemplateHoistMove(t,n,r,s,o,l,u);if(P)return P;let w=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,l,u);return w||{ok:!1,errorCode:"unsupported-operation",reason:m}}if(p)return{ok:!1,errorCode:"unsupported-operation",reason:p};let g=await this.getUpstreamBackedDescendantReason(r);if(g)return{ok:!1,errorCode:"unsupported-operation",reason:g};if(r.tag&&r.tag.toLowerCase()===r.tag){let v=wo(s,{kind:"native-tag",tag:r.tag});if(v)return{ok:!1,errorCode:"unsupported-operation",reason:v}}if(c)return this.planCrossFileMove(t,n,r,s,o,l,u);let S=vu(this.graph.getFileContent(r.file),r,s);if(!S.ok)return{ok:!1,errorCode:"unsupported-operation",reason:S.reason??`Cannot move node because it depends on bindings outside the target scope: ${S.bindingNames.join(", ")}`};let C=[{order:0,file:r.file,type:"move-node",locator:de(r),targetParentLocator:de(s),placement:l,anchorLocator:u?de(u):void 0,selectionContext:_n(s)}];return this.buildPlan(t,n,C,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,u=this.graph.getFileContent(r.file),d=hs(this.graph,r)??`<${r.component} />`,p=yu(u,r);if(!p.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:p.reason??"Cannot move subtree across files"};if(c.push({order:l++,file:r.file,type:"remove-node",locator:de(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let g=r.tag??r.component,C={moduleSpecifier:Es(o.file,r.importedFrom),imports:r.exportName==="default"?[{kind:"default",local:g}]:[{kind:"named",imported:r.exportName,local:g===r.exportName?void 0:g}]};c.push({order:l++,file:o.file,type:"add-import",moduleSpecifier:C.moduleSpecifier,imports:C.imports}),c.push({order:l++,file:o.file,type:"insert-child",parentLocator:de(o),node:{jsx:d},placement:s,anchorLocator:a?de(a):void 0,selectionContext:_n(o)})}else c.push({order:l++,file:o.file,type:"insert-child",parentLocator:de(o),node:{jsx:d},placement:s,anchorLocator:a?de(a):void 0,selectionContext:_n(o)});let m=this.buildRemoveComponentImportStep(r,u);return m&&c.push({...m,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:le(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}}}};import cr from"node:path";import*as md from"@babel/parser";import Ms from"@babel/traverse";import*as E from"@babel/types";var gd=typeof Ms=="function"?Ms:Ms.default;function hd(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}var od=new WeakMap;function id(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 yd(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=zs(s,t,n);if(!a)return null;let c=Hs(a,r.sourceRange);if(!c)return null;let l=r.source??await ot({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!l){let m=await ea({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});if(!m)return null;if(m.kind==="external")return{kind:"external-entry",file:m.file,sourceType:m.sourceType,sourceId:m.sourceId,adapterId:m.adapterId,displayExpression:m.displayPath};let g={kind:"value",root:m.root,path:m.path.length>0?m.path:[]};return{kind:"value-binding",file:m.file,locator:g,root:m.root,path:m.path,displayExpression:m.displayExpression??dr(c.node,n),sourceKind:m.sourceKind,...m.collectionIndexMap?{collectionIndexMap:m.collectionIndexMap}:{},...m.collectionPathMap?{collectionPathMap:m.collectionPathMap}:{}}}let u=new Set,d=await CS({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});if(!d)return null;if(d.kind==="external")return{kind:"external-entry",file:d.file,sourceType:d.sourceType,sourceId:d.sourceId,adapterId:d.adapterId,displayExpression:d.displayPath};let p={kind:"value",root:d.root,path:d.path.length>0?d.path:[]};return{kind:"value-binding",file:d.file,locator:p,root:d.root,path:d.path,displayExpression:d.displayExpression??l.expression,sourceKind:d.sourceKind,...d.collectionIndexMap?{collectionIndexMap:d.collectionIndexMap}:{},...d.collectionPathMap?{collectionPathMap:d.collectionPathMap}:{}}}async function xd(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=zs(i,t,n);if(!s)return null;let a=e.expression!==void 0?(e.sourceRange?Id(s,n,e.expression,e.sourceRange):null)??Ys(s,n,e.expression):e.sourceRange?Hs(s,e.sourceRange):null;if(!a)return null;let c=tS(a),l=new Set,u=e.sourceInfo??await ot({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:l}),d=u?await je({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 jS({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 eS(d,e.expression??dr(c.node,n))}async function Xs(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=zs(i,t,n);if(!s)return Be("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?nS({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}):rS({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}function Sd(e){try{return md.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function zs(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=Sd(n);return e.set(t,{source:n,ast:o}),o}function Hs(e,t){let n=null,r=-1;for(let o of ur(e).expressions){let i=o.node.loc;if(!i||!Ws(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s>=r&&(n=o,r=s)}return n}function Qx(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of ur(e).expressions){if(!qx(o.node.loc,t))continue;let i=(o.node.end??0)-(o.node.start??0);i<=r&&(n=o,r=i)}return n}function bd(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of ur(e).jsxElements){let i=o.node.loc;if(!i||!Ws(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s<=r&&(n=o,r=s)}return n}function ur(e){let t=od.get(e);if(t)return t;let n={expressions:[],jsxElements:[]};return gd(e,{Expression(r){n.expressions.push(r)},JSXElement(r){n.jsxElements.push(r)}}),od.set(e,n),n}function qx(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 Ws(e,t){let n=sd({line:e.start.line,column:e.start.column},{line:t.startLine,column:t.startColumn}),r=sd({line:e.end.line,column:e.end.column},{line:t.endLine,column:t.endColumn});return n>=0&&r<=0}function Ed(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 sd(e,t){return e.line!==t.line?e.line<t.line?-1:1:e.column!==t.column?e.column<t.column?-1:1:0}async function ot(e){if(E.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!E.isMemberExpression(e.expression))return null;let t=await Fd(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:dr(e.expression,e.source),base:t.base,path:t.path}:null}function eS(e,t){if(!e)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}:{}}}function tS(e){if(e.isLogicalExpression()&&(e.node.operator==="||"||e.node.operator==="??")){let t=e.get("left");if(!Array.isArray(t)&&t.isExpression())return t}return e}function dr(e,t){if(t)return Gs(e,t);let n=WS(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function Gs(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Ys(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of ur(e).expressions){if(Gs(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function Id(e,t,n,r){let o=null,i=Number.POSITIVE_INFINITY;for(let s of ur(e).expressions){if(Gs(s.node,t)!==n)continue;let a=s.node.loc;if(!a||!Ws(a,r))continue;let c=(s.node.end??0)-(s.node.start??0);c<=i&&(o=s,i=c)}return o}async function nS(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=Hs(r,o.sourceRange),u=o.source??(l?await ot({expression:l.node,scope:l.scope,source:n,currentFile:t,readFile:i,exists:s,fileCache:a,visited:c}):null);if(!u){if(!l)return oS(t,o.value);let p=await ea({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 p?p.kind==="external"?dd(t,p):$s(t,dr(l.node,n),p):iS({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return Be("unsupported-expression","Unable to locate text expression for provenance resolution");let d=await je({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 p=js(l.node);if(p)return Be(p.code,p.message);let m=l.scope.getBinding(u.base);if(m?.path.isVariableDeclarator()){let g=js(m.path.node.init);if(g)return Be(g.code,g.message)}return m?.path.isVariableDeclarator()&&E.isCallExpression(m.path.node.init)?sS("unsupported-expression",wd(m.path.node.init,e.functionCallContracts)):Be("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return d.kind==="external"?dd(t,d):$s(t,u.expression,d)}async function rS(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return Be("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=Ys(r,n,o.conditionExpression);if(!l)return Be("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await je({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 Be("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(u.kind==="external")return Be("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let d=$s(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 oS(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 iS(e){let t=await kd(e);if(t.length===0)return Be("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(aS(e.expression))return vd(t);if(Rd(e.expression))return Be("unsupported-expression","i18n helpers require a static message id string");if(E.isMemberExpression(e.expression)&&e.expression.computed&&!E.isNumericLiteral(e.expression.property)&&!E.isStringLiteral(e.expression.property))return Be("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return Be(n.code,n.message)}function Be(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function sS(e,t){return vd([{code:e,message:t}])}function vd(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function aS(e){return E.isCallExpression(e)||E.isConditionalExpression(e)||E.isLogicalExpression(e)||E.isBinaryExpression(e)}function lr(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 kd(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=js(t);if(l)return[l];if(E.isCallExpression(t))return[{code:"unsupported-expression",message:wd(t,c)}];if(E.isMemberExpression(t)&&t.computed){let u=t.property;if(!E.isNumericLiteral(u)&&!E.isStringLiteral(u)){if(!E.isExpression(u))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let p=await it(u,n,r,o,i,s,a);if(typeof p!="string"&&!Number.isInteger(p))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}]}}return E.isBinaryExpression(t)?lr([...await Os(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):E.isLogicalExpression(t)?lr([...await Os(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"}]):E.isConditionalExpression(t)?lr([...await Os(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 js(e){return Rd(e)?ad("i18n helpers require a static message id string"):fS(e)?ad("CMS helpers require static entry id and field path string arguments"):null}async function Os(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await kd({...t,expression:o}));return r}function cS(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:[lS(e.sourceType)]}}async function Zs(e){for(let n of hS){if(!cd(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return ud(ld(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(!cd(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return ud(ld(r),e.externalAdapters)}return null}function lS(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function uS(e){return{code:"external-source-readonly",message:e}}function ad(e){return{code:"unsupported-expression",message:e}}function Qs(e){return!e||!E.isCallExpression(e)?null:E.isIdentifier(e.callee)?e.callee.name:E.isMemberExpression(e.callee)&&!e.callee.computed&&E.isIdentifier(e.callee.object)&&E.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function cd(e,t){if(!t||t.length===0)return!0;let n=Qs(e.node);return n?t.includes(n):!1}function ld(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:lr(e.diagnostics??[])}:{match:e,diagnostics:[]}}function ud(e,t){let n=cS(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:lr([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function dS(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!E.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!E.isStringLiteral(n)||!E.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 fS(e){return!!e&&E.isCallExpression(e)&&E.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!E.isStringLiteral(e.arguments[0])||!E.isStringLiteral(e.arguments[1]))}function Cd(e){if(!(!e||!E.isCallExpression(e))){if(E.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&E.isStringLiteral(t)?t.value:null}if(E.isMemberExpression(e.callee)&&!e.callee.computed&&E.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&E.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!E.isObjectExpression(t))return null;for(let n of t.properties)if(E.isObjectProperty(n)&&!n.computed&&(E.isIdentifier(n.key)&&n.key.name==="id"||E.isStringLiteral(n.key)&&n.key.value==="id")&&E.isStringLiteral(n.value))return n.value.value;return null}}}function Rd(e){return Cd(e)===null}async function pS(e,t,n){let r=new Set,o=cr.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=cr.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"]:[cr.posix.join(i,"locales"),cr.posix.join(i,"messages")];for(let a of s){let c=cr.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function mS(e){let t=Cd(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await pS(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function gS(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!E.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!E.isExpression(n))return null;let o=await it(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:[uS("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var hS=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>dS(e)},{helperNames:["apiField"],resolve:e=>gS(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>mS({currentFile:e,expressionPath:t,exists:n})}];function dd(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 $s(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=kS(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:!0}):n.sourceKind==="imported-binding"?c.push({kind:"imported-binding",file:n.file,displayName:n.root.kind==="named-export"?n.root.name:"default",canEditHere:!0}):n.sourceKind==="repeat-template"&&c.push({kind:"repeat-template",file:n.file,displayName:t,canEditHere:!0}),n.path.length>0&&n.sourceKind!=="repeat-template"&&c.push({kind:o?"array-item":"object-field",file:n.file,displayName:a,canEditHere:!0}),i&&c.push({kind:"config-entry",file:n.file,displayName:i.displayPath,canEditHere:!0}),{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:c,confidence:n.sourceKind==="repeat-template"?"safe-derived":"exact",editMode:n.editMode??(n.file===e?"direct":"proxy"),diagnostics:n.diagnostics??[]}}var yS=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function qs(e,t){let n=[...yS,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function wd(e,t){let n=e.callee;return E.isIdentifier(n)&&qs(n.name,t)?.purity==="side-effect"?`Helper "${n.name}" is registered as side-effectful and remains readonly`:"Function calls are recognized but remain readonly until a pure-call strategy is registered"}async function ea(e){let t=await Zs(e);if(t)return t;let n=await Nd({...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 ot({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 je({...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 IS(e)}async function Nd(e){let t=await nt({...e,allowComposed:!1});return t?.kind==="source"?t.provenance:null}async function nt(e){let t=xS(e.expressionPath),n=ES(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 ot({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 je({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 ot({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 je({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 nt({...e,expressionPath:r,allowComposed:!0}),a=await nt({...e,expressionPath:o,allowComposed:!1}),c=await nt({...e,expressionPath:i,allowComposed:!1});return Ds(s,a,c)}if(t.isCallExpression())return SS({...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 nt({...e,expressionPath:r,allowComposed:!0}),s=await nt({...e,expressionPath:o,allowComposed:!0});return Ds(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 nt({...e,expressionPath:r,allowComposed:!0}),s=await nt({...e,expressionPath:o,allowComposed:!0});return Ds(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:nt({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function xS(e){let t=e;for(;t.isParenthesizedExpression()||t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression()||t.isTSTypeAssertion();){let n=t.get("expression");if(Array.isArray(n)||!n.isExpression())return t;t=n}return t}async function SS(e){let t=Qs(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:nt({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(E.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:nt({...e,expressionPath:o,allowComposed:!1})}}return null}function Ds(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!bS(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function bS(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 ES(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function IS(e){if(!e.expressionPath.isCallExpression())return null;let t=Qs(e.expressionPath.node);if(!t)return null;let n=qs(t,e.functionCallContracts);if(!n||n.purity!=="pure")return null;let r=n.sourceArgIndex??0,o=e.expressionPath.get(`arguments.${r}`);return!o||Array.isArray(o)||!o.isExpression()?null:await Pd({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})}async function Pd(e){let t=await Zs({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 ot({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 je({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 ea({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 vS(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!E.isCallExpression(t))return null;let n=t.callee;if(!E.isIdentifier(n))return null;let r=qs(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}`);return!s||Array.isArray(s)||!s.isExpression()?null:await Pd({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})}function kS(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=_o(t,e.path);return{sourceId:o,displayPath:o}}async function CS(e){let t=e.segment.source;return t?je({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 je(e){let t=e.sourceInfo,n=Ad(e.expressionPath,t.base);if(n){let l=await Td({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 S=wS(n.callPath,[...n.basePath,...t.path]);return tr(S)?id(e.currentFile,S.sourceId,S.displayPath):null}let u=GS(l,[...n.basePath,...t.path]),d=l.collectionIndexMap?.[0]??0,p=[...l.pathPrefix??[],{kind:"index",index:d},...n.basePath,...t.path],m=[{kind:"index",index:0},...n.basePath,...t.path];return rt(l.value,m)===void 0?null:{kind:"value",file:l.file,root:l.root,path:u?.[0]??p,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 gn(e.currentFile,u.node.source.value,e.exists);if(!d)return null;let p=await To({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(!p||p.kind==="external")return null;let m=t.path.slice(1);return rt(p.value,m)===void 0?null:{kind:"value",file:p.file,root:p.root,path:m,sourceKind:"imported-binding",collectionIndexMap:p.collectionIndexMap}}let o=bu(r);if(o){let l=o.expressionPath,u=await ot({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 je({...e,expressionPath:l,sourceInfo:{...u,expression:_o(u.expression,t.path),path:[...u.path,...t.path]}});if(d)return d}if(t.path.length===0){let d=await Nd({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 JS({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 vS({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=bo(r,t.path);if(tr(s))return id(e.currentFile,s.sourceId,s.displayPath);let a=await en({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:rt(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}function Ad(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=qe(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!RS(s,r)?null:{callPath:s,basePath:i}}function RS(e,t){let n=e.node.callee;return!E.isMemberExpression(n)||!E.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}async function Td(e){let{currentFile:t,callPath:n,readFile:r,exists:o,fileCache:i,visited:s}=e,a=n.node.callee;if(!E.isMemberExpression(a)||!E.isIdentifier(a.property)||a.property.name!=="map")return null;let c=n.get("callee");if(!c.isMemberExpression())return null;let l=c.get("object");if(Array.isArray(l)||!l.isExpression())return null;let u=await fr({currentFile:t,expressionPath:l,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});return!u||!Array.isArray(u.value)||u.value.length===0?null:u}function wS(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:Io(r,t)}async function fr(e){let{currentFile:t,expressionPath:n,readFile:r,exists:o,fileCache:i,visited:s}=e;if(n.isIdentifier()){let a=n.scope.getBinding(n.node.name);if(!a)return null;let c=await en({currentFile:t,binding:a,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});return c?.kind==="static"?c:null}if(n.isCallExpression())return _d({currentFile:t,callPath:n,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(n.isTSAsExpression()||n.isTSSatisfiesExpression()||n.isTSNonNullExpression()){let a=n.get("expression");if(!Array.isArray(a)&&a.isExpression())return fr({...e,expressionPath:a})}if(n.isArrayExpression()){let a=Ed(n.node);if(!a)return null;let c=await it(n.node,n.scope,t,r,o,i,s);return Array.isArray(c)?{kind:"static",file:t,root:{kind:"expression",sourceRange:a},value:c,sourceKind:"binding"}:null}if(n.isMemberExpression()){let a=await ot({expression:n.node,scope:n.scope,currentFile:t,readFile:r,exists:o,fileCache:i,visited:s});if(!a)return null;let c=await je({currentFile:t,expressionPath:n,sourceInfo:a,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(!c||c.kind==="external")return null;let l=await NS({currentFile:t,expressionPath:n,provenance:c,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(!l||l.kind!=="static")return null;if(c.collectionPathMap?.length){let d=YS(l.value,c.collectionPathMap);if(d)return{kind:"static",file:c.file,root:c.root,value:d.value,sourceKind:c.sourceKind,collectionPathMap:d.collectionPathMap}}let u=rt(l.value,c.path);return Array.isArray(u)?{kind:"static",file:c.file,root:c.root,value:u,sourceKind:c.sourceKind,pathPrefix:c.path,collectionIndexMap:c.collectionIndexMap,collectionPathMap:c.collectionPathMap}:null}return null}async function NS(e){let{provenance:t}=e;if(t.root.kind==="binding"){let i=e.expressionPath.scope.getBinding(t.root.name);if(!i&&t.file!==e.currentFile){let s=await Lt(t.file,e.readFile,e.fileCache);i=s.ast?Ks(s.ast).getBinding(t.root.name):void 0}return i?await en({currentFile:t.file,binding:i,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}if(t.root.kind!=="expression")return null;let n=await Lt(t.file,e.readFile,e.fileCache);if(!n.ast)return null;let r=Qx(n.ast,t.root.sourceRange);if(!r)return null;let o=await it(r.node,r.scope,t.file,e.readFile,e.exists,e.fileCache,e.visited);return o===void 0?null:{kind:"static",file:t.file,root:t.root,value:o,sourceKind:t.sourceKind}}async function _d(e){return await PS(e)??await AS(e)??await TS(e)}async function PS(e){let{callPath:t}=e,n=t.node.callee;if(!E.isMemberExpression(n)||!E.isIdentifier(n.property)||n.property.name!=="filter")return null;let r=t.get("callee");if(!r.isMemberExpression())return null;let o=r.get("object");if(Array.isArray(o)||!o.isExpression())return null;let i=await fr({currentFile:e.currentFile,expressionPath: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});if(!i||!Array.isArray(i.value))return null;let[s]=t.node.arguments;if(!E.isArrowFunctionExpression(s)&&!E.isFunctionExpression(s))return null;let a=s.params[0];if(!E.isIdentifier(a))return null;let c=_S(s);if(!c)return null;let l=[],u=[],d=[];for(let[p,m]of i.value.entries()){let g=FS(c,a.name,m);if(typeof g!="boolean")return null;if(g){l.push(m),u.push(i.collectionIndexMap?.[p]??p);let S=i.collectionPathMap?.[p];S&&d.push(S)}}return{...i,value:l,pathPrefix:i.pathPrefix,collectionIndexMap:u,...d.length>0?{collectionPathMap:d}:{}}}async function AS(e){let{callPath:t}=e,n=t.node.callee;if(!E.isMemberExpression(n)||!E.isIdentifier(n.property)||n.property.name!=="slice")return null;let r=t.get("callee");if(!r.isMemberExpression())return null;let o=r.get("object");if(Array.isArray(o)||!o.isExpression())return null;let i=await fr({currentFile:e.currentFile,expressionPath: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});if(!i||!Array.isArray(i.value))return null;let[s,a]=t.node.arguments,c=fd(s,0),l=fd(a,i.value.length);if(c===null||l===null)return null;let u=Math.max(0,c<0?i.value.length+c:c),d=Math.max(0,l<0?i.value.length+l:l),p=i.value.map((g,S)=>i.collectionIndexMap?.[S]??S).slice(u,d),m=i.collectionPathMap?.slice(u,d);return{...i,value:i.value.slice(u,d),pathPrefix:i.pathPrefix,collectionIndexMap:p,...m?{collectionPathMap:m}:{}}}function fd(e,t){return e?E.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}async function TS(e){let{callPath:t}=e,n=t.node.callee;if(!E.isMemberExpression(n)||!E.isIdentifier(n.property)||n.property.name!=="sort"&&n.property.name!=="toSorted")return null;let r=t.get("callee");if(!r.isMemberExpression())return null;let o=r.get("object");if(Array.isArray(o)||!o.isExpression())return null;let i=await fr({currentFile:e.currentFile,expressionPath: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});if(!i||!Array.isArray(i.value))return null;let[s]=t.node.arguments;if(!E.isArrowFunctionExpression(s)&&!E.isFunctionExpression(s))return null;let[a,c]=s.params;if(!E.isIdentifier(a)||!E.isIdentifier(c))return null;let l=i.value.map((d,p)=>({value:d,sourceIndex:i.collectionIndexMap?.[p]??p,originalIndex:p})),u=[...l];for(let d of l)for(let p of l)if(pd(s,a.name,c.name,d.value,p.value)===void 0)return null;return u.sort((d,p)=>{let m=pd(s,a.name,c.name,d.value,p.value)??0;return m===0?d.originalIndex-p.originalIndex:m}),{...i,value:u.map(d=>d.value),pathPrefix:i.pathPrefix,collectionIndexMap:u.map(d=>d.sourceIndex),...i.collectionPathMap?{collectionPathMap:u.map(d=>i.collectionPathMap?.[d.originalIndex]).filter(d=>!!d)}:{}}}function pd(e,t,n,r,o){let i=E.isExpression(e.body)?e.body:e.body.body.find(a=>E.isReturnStatement(a))?.argument;if(!i||!E.isExpression(i))return;let s=Vs(i,t,n,r,o);return typeof s=="number"?s:void 0}function Vs(e,t,n,r,o){if(E.isNumericLiteral(e)||E.isStringLiteral(e)||E.isBooleanLiteral(e))return e.value;if(E.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(E.isMemberExpression(e)){let i=Us(e,t);if(i)return rt(r,i);let s=Us(e,n);return s?rt(o,s):void 0}if(E.isBinaryExpression(e)&&e.operator==="-"){let i=E.isExpression(e.left)?Vs(e.left,t,n,r,o):void 0,s=E.isExpression(e.right)?Vs(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function _S(e){if(E.isExpression(e.body))return e.body;for(let t of e.body.body)if(E.isReturnStatement(t)&&t.argument&&E.isExpression(t.argument))return t.argument;return null}function FS(e,t,n){let r=qt(e,t,n);return typeof r=="boolean"?r:void 0}function qt(e,t,n){if(E.isStringLiteral(e)||E.isNumericLiteral(e)||E.isBooleanLiteral(e))return e.value;if(E.isNullLiteral(e))return null;if(E.isIdentifier(e))return e.name===t?n:void 0;if(E.isMemberExpression(e)){let r=Us(e,t);return r?rt(n,r):void 0}if(E.isUnaryExpression(e)&&e.operator==="!"){let r=qt(e.argument,t,n);return r===void 0?void 0:!r}if(E.isLogicalExpression(e)){let r=qt(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&qt(e.right,t,n);if(e.operator==="||")return r||qt(e.right,t,n)}if(E.isBinaryExpression(e)){let r=E.isExpression(e.left)?qt(e.left,t,n):void 0,o=E.isExpression(e.right)?qt(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 Us(e,t){let n=[],r=e;for(;E.isMemberExpression(r);){if(r.computed)if(E.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(E.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!E.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!E.isIdentifier(r)||r.name!==t?null:n}async function en(e){let{currentFile:t,binding:n,readFile:r,exists:o,fileCache:i,visited:s}=e,a=`${t}::${n.kind}::${n.identifier.name}`;if(s.has(a))return null;s.add(a);try{let c=await MS({currentFile:t,binding:n,readFile:r,exists:o,fileCache:i,visited:s});if(c)return c;if(n.path.isImportSpecifier()||n.path.isImportDefaultSpecifier())return await HS({currentFile:t,binding:n,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,fileCache:i,visited:s});if(n.kind==="param")return null;if(n.path.isVariableDeclarator()){let l=n.path.node.init;if(!l||!E.isExpression(l))return null;let u=n.path.get("init");if(u&&!Array.isArray(u)&&u.isExpression()){let p=await Zs({currentFile:t,expressionPath:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(p)return p;if(u.isCallExpression()){let m=await _d({currentFile:t,callPath:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(m)return m}}let d=await it(l,n.path.scope,t,r,o,i,s);return d===void 0?null:{kind:"static",file:t,root:{kind:"binding",name:n.identifier.name},value:d,sourceKind:"binding"}}if(n.path.isIdentifier()&&n.path.parentPath?.isExportDefaultDeclaration()){let l=n.path.parentPath.node.declaration;if(!E.isExpression(l))return null;let u=await it(l,n.path.scope,t,r,o,i,s);return u===void 0?null:{kind:"static",file:t,root:{kind:"binding",name:n.identifier.name},value:u,sourceKind:"binding"}}return null}finally{s.delete(a)}}async function MS(e){let{currentFile:t,binding:n,readFile:r,exists:o,fileCache:i,visited:s}=e;if(!n.path.isVariableDeclarator()||!n.path.get("id").isArrayPattern())return null;let a=n.path,c=a.node.init;if(!c||!E.isCallExpression(c))return null;let l=OS(c);if(!l||!E.isArrayPattern(a.node.id)||a.node.id.elements.findIndex(g=>E.isIdentifier(g)&&g.name===n.identifier.name)!==0)return null;let d=l==="useReducer"?1:0,p=c.arguments[d];if(!p||!E.isExpression(p))return null;let m=await it(p,a.scope,t,r,o,i,s);return m===void 0?null:{kind:"static",file:t,root:{kind:"hook-state",name:n.identifier.name,hook:l},value:m,sourceKind:"binding"}}function OS(e){return E.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:E.isMemberExpression(e.callee)&&E.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function DS(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()||!E.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 LS(e,t){let n=DS(e.path);if(!n)return null;let r=Tn(e,t);return r?{...n,...r}:null}function _o(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function BS(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}async function jS(e){let t=VS(e.expressionPath.node);if(!t||!US(t.segments))return null;let n=await je({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 $S({...e,rootPath:n.path,segments:t.segments});return r?{...n,path:r.collectionPathMap[0]??n.path,sourceKind:"repeat-template",displayExpression:dr(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:r.collectionPathMap}:null}async function $S(e){let t=null,n,r=[];for(let i of e.segments){if(i.kind!=="dynamic")continue;let s=await ot({expression:i.expression,scope:e.expressionPath.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(!s)return null;let a=Ad(e.expressionPath,s.base);if(!a)return null;let c=await Td({currentFile:e.currentFile,callPath:a.callPath,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(!c||!Array.isArray(c.value))return null;let l=c.value.map((u,d)=>{let p=rt(c.value,[{kind:"index",index:d},...a.basePath,...s.path]);return KS(p)});if(l.some(u=>u===null)||t!==null&&t!==l.length)return null;t=l.length,n??=c.collectionIndexMap,r.push(l)}if(t===null||t===0)return null;let o=[];for(let i=0;i<t;i+=1){let s=[...e.rootPath],a=0;for(let c of e.segments){if(c.kind==="dynamic"){let l=r[a]?.[i];if(!l)return null;s.push(l),a+=1;continue}s.push({...c})}o.push(s)}return{...n?{collectionIndexMap:n}:{},collectionPathMap:o}}function VS(e){let t=[],n=e;for(;E.isMemberExpression(n)||E.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(E.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(E.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(E.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(E.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return E.isIdentifier(n)?{base:n.name,segments:t}:null}function US(e){return e.some(t=>t.kind==="dynamic")}function KS(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}async function JS(e){let t=LS(e.binding,e.sourceInfo);if(!t||!e.graph)return null;let n=[...e.graph.elements.values()].filter(l=>BS(l,e.currentFile,t.componentName,t.exportName));if(n.length!==1)return null;let r=n[0],o=r.attributes?.find(l=>l.name===t.propName);if(o&&!o.source){let l=await XS({caller:r,propName:t.propName,remainingPath:t.remainingPath,readFile:e.readFile,fileCache:e.fileCache});if(l)return Ls(l,{componentName:t.componentName,propName:t.propName,file:r.sourceFile})}if(!o?.source){let l=await zS({caller:r,propName:t.propName,remainingPath:t.remainingPath,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(l)return Ls(l,{componentName:t.componentName,propName:t.propName,file:r.sourceFile});let u=Iu(e.binding,t.componentName,t.propName);if(!u||u.propName!==t.propName)return null;let d=await it(u.expressionPath.node,u.expressionPath.scope,e.currentFile,e.readFile,e.exists,e.fileCache,e.visited);if(d===void 0)return null;let p=t.remainingPath;return p.length>0&&rt(d,p)===void 0?null:{kind:"value",file:e.currentFile,root:{kind:"binding",name:t.propName},path:p,sourceKind:"binding",semanticKind:"component-prop",displayExpression:u.displayPath,chainPrefix:[{kind:"component-prop",file:e.currentFile,displayName:u.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let i=await Lt(r.sourceFile,e.readFile,e.fileCache);if(!i.ast)return null;let s=Id(i.ast,i.source,o.source.expression,o.sourceRange)??Ys(i.ast,i.source,o.source.expression);if(!s)return null;let a={...o.source,expression:_o(o.source.expression,t.remainingPath),path:[...o.source.path,...t.remainingPath]},c=await je({currentFile:r.sourceFile,expressionPath:s,sourceInfo:a,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 c?Ls(c.kind==="external"?c:{...c,displayExpression:a.expression},{componentName:t.componentName,propName:t.propName,file:r.sourceFile}):null}async function XS(e){let t=await Lt(e.caller.sourceFile,e.readFile,e.fileCache);if(!t.ast)return null;let n=bd(t.ast,e.caller.sourceRange);if(!n)return null;let r=n.get("openingElement").get("attributes").find(a=>a.isJSXAttribute()&&a.node.name.type==="JSXIdentifier"&&a.node.name.name===e.propName);if(!r?.isJSXAttribute())return null;let o=r.get("value"),i=o.isStringLiteral()?o:o.isJSXExpressionContainer()?o.get("expression"):null;if(!i?.isExpression())return null;let s=Ed(i.node);return s?{kind:"value",file:e.caller.sourceFile,root:{kind:"expression",sourceRange:s},path:e.remainingPath,sourceKind:"binding",semanticKind:"component-prop",displayExpression:e.propName,editMode:"upstream",diagnostics:[]}:null}async function zS(e){let t=await Lt(e.caller.sourceFile,e.readFile,e.fileCache);if(!t.ast)return null;let n=bd(t.ast,e.caller.sourceRange);if(!n)return null;let r=n.get("openingElement");for(let o of r.get("attributes")){if(!o.isJSXSpreadAttribute())continue;let i=o.get("argument");if(!i.isExpression())continue;let s=await ot({expression:i.node,scope:i.scope,source:t.source,currentFile:e.caller.sourceFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(!s)continue;let a=[{kind:"property",name:e.propName},...e.remainingPath],c={...s,expression:_o(s.expression,a),path:[...s.path,...a]},l=await je({currentFile:e.caller.sourceFile,expressionPath:i,sourceInfo:c,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(l)return l.kind==="external"?l:{...l,displayExpression:c.expression}}return null}function Ls(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"}}async function HS(e){let{currentFile:t,binding:n,readFile:r,exists:o,fileCache:i,visited:s}=e,a=n.path.parentPath;if(!a||!a.isImportDeclaration())return null;let c=a.node.source.value;if(typeof c!="string")return null;let l=await gn(t,c,o);if(!l)return null;if(n.path.isImportDefaultSpecifier()){let S=await Lt(l,r,i),C=S.ast?Js(S.ast,"default"):null,v=await To({file:l,exportName:"default",readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});return!v||v.kind!=="static"?null:{kind:"static",file:C?.kind==="default-expression"?v.file:l,root:C?.kind==="default-expression"?v.root:{kind:"default-export"},value:v.value,sourceKind:"imported-binding"}}if(!n.path.isImportSpecifier())return null;let u=n.path.node.imported,d=E.isIdentifier(u)?u.name:u.value,p=await Lt(l,r,i),m=p.ast?Js(p.ast,d):null,g=await To({file:l,exportName:d,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});return g?g.kind==="external"?g:{kind:"static",file:m?.kind==="re-export"?g.file:l,root:m?.kind==="re-export"?g.root:{kind:"named-export",name:d},value:g.value,sourceKind:"imported-binding"}:null}async function To(e){let{file:t,exportName:n,readFile:r,exists:o,fileCache:i,visited:s}=e,a=`export::${t}::${n}`;if(!s.has(a)){s.add(a);try{let c=await Lt(t,r,i);if(!c.ast)return;let l=Js(c.ast,n);if(!l)return;if(l.kind==="default-expression"){let m=l.expression;if(!m||!E.isIdentifier(m))return;let g=Ks(c.ast).getBinding(m.name);return g?await en({currentFile:t,binding:g,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s})??void 0:void 0}if(l.kind==="re-export"){if(!l.source||!l.name)return;let m=await gn(t,l.source,o);return m?To({...e,file:m,exportName:l.name}):void 0}let u=l.name;if(!u)return;let d=Ks(c.ast).getBinding(u);return d?await en({currentFile:t,binding:d,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s})??void 0:void 0}finally{s.delete(a)}}}function Ks(e){let t=null;if(gd(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}function Js(e,t){for(let n of e.program.body){if(t==="default"&&E.isExportDefaultDeclaration(n))return E.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:(E.isFunctionDeclaration(n.declaration)||E.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if(E.isExportNamedDeclaration(n)){if(n.declaration){if(E.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if(E.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if((E.isFunctionDeclaration(n.declaration)||E.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if((E.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&E.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}async function it(e,t,n,r,o,i,s){if(E.isStringLiteral(e)||E.isNumericLiteral(e)||E.isBooleanLiteral(e))return e.value;if(E.isNullLiteral(e))return null;if(E.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(E.isTSAsExpression(e)||E.isTSSatisfiesExpression(e)||E.isTSNonNullExpression(e))return await it(e.expression,t,n,r,o,i,s);if(E.isIdentifier(e)){let a=t.getBinding(e.name);if(!a)return;let c=await en({currentFile:n,binding:a,readFile:r,exists:o,fileCache:i,visited:s});return c?.kind==="static"?c.value:void 0}if(E.isArrayExpression(e)){let a=[];for(let c of e.elements){if(!c||E.isSpreadElement(c))return;let l=await Bs(c,t,n,r,o,i,s);if(l===void 0)return;a.push(l)}return a}if(E.isObjectExpression(e)){let a={};for(let c of e.properties){if(!E.isObjectProperty(c)||c.computed)return;let l=null;if(E.isIdentifier(c.key)?l=c.key.name:E.isStringLiteral(c.key)&&(l=c.key.value),!l)return;if(c.shorthand){if(!E.isIdentifier(c.value))return;let d=await Bs(c.value,t,n,r,o,i,s);if(d===void 0)return;a[l]=d;continue}if(!E.isExpression(c.value))return;let u=await Bs(c.value,t,n,r,o,i,s);u!==void 0&&(a[l]=u)}return a}if(E.isMemberExpression(e)){let a=await Fd(e,t,n,r,o,i,s);if(!a)return;let c=t.getBinding(a.base);if(!c)return;let l=await en({currentFile:n,binding:c,readFile:r,exists:o,fileCache:i,visited:s});return!l||l.kind!=="static"?void 0:rt(l.value,a.path)}}async function Bs(e,t,n,r,o,i,s){if(!E.isSpreadElement(e))return await it(e,t,n,r,o,i,s)}async function Fd(e,t,n,r,o,i,s){if(E.isIdentifier(e))return{base:e.name,path:[]};if(!E.isMemberExpression(e))return null;let a=[],c=e;for(;E.isMemberExpression(c);){if(c.computed){let l=c.property;if(E.isNumericLiteral(l))a.unshift({kind:"index",index:l.value});else if(E.isStringLiteral(l))a.unshift({kind:"property",name:l.value});else{let u=E.isExpression(l)?await it(l,t,n,r,o,i,s):void 0;if(typeof u=="string")a.unshift({kind:"property",name:u});else if(Number.isInteger(u))a.unshift({kind:"index",index:u});else return null}}else{if(!E.isIdentifier(c.property))return null;a.unshift({kind:"property",name:c.property.name})}c=c.object}return E.isIdentifier(c)?{base:c.name,path:a}:null}function WS(e){if(E.isIdentifier(e))return{base:e.name,path:[]};if(!E.isMemberExpression(e))return null;let t=[],n=e;for(;E.isMemberExpression(n);){if(n.computed)if(E.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(E.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!E.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return E.isIdentifier(n)?{base:n.name,path:t}:null}function rt(e,t){let n=e;for(let r of t){if(r.kind==="property"){if(n===null||Array.isArray(n)||typeof n!="object"||!(r.name in n))return;n=n[r.name];continue}if(!Array.isArray(n)||r.index<0||r.index>=n.length)return;n=n[r.index]}return n}function GS(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 YS(e,t){let n=[],r=[];for(let o of t){let i=rt(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}}async function Lt(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=Sd(o),s={source:o,ast:i};return n.set(e,s),s}import ia from"@babel/generator";import{parse as lb}from"@babel/parser";import sa from"@babel/traverse";import*as k from"@babel/types";import*as Ld from"@babel/types";import ta from"@babel/generator";import*as ae from"@babel/types";var ZS=typeof ta=="function"?ta:ta.default,QS=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,qS=/^((?:https?:)?\/\/)[^/@\s]+@/i,eb=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function Od(e,t){let n=ft(e.callee);if(!n)return null;if(n==="fetch")return na(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(Md(r))return na(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(Md(r))return na(e.arguments[0],r,t,["ky client contract"])}return null}function na(e,t,n,r){if(!e||ae.isSpreadElement(e)||ae.isJSXNamespacedName(e))return ob(t,n,r,"missing url argument");let o=pr(e);return{sourceKind:rb(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 pr(e){if(ae.isStringLiteral(e))return Fo(e.value);if(ae.isTemplateLiteral(e))return Fo(tb(e));if(ae.isBinaryExpression(e)&&e.operator==="+"){let t=pr(e.left),n=pr(e.right);return!t&&!n?void 0:Fo(`${t??ra(e.left)}${n??ra(e.right)}`)}if(ae.isMemberExpression(e)){let t=Dd(e);if(t)return`env:${t}`}if(!(ae.isCallExpression(e)&&ft(e.callee)==="new URL")){if(ae.isNewExpression(e)&&ae.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!ae.isSpreadElement(t)?pr(t):void 0,o=n&&!ae.isSpreadElement(n)?pr(n):void 0;return o&&r?Fo(`${o} + ${r}`):r??o}if(ae.isIdentifier(e))return`:${e.name}`}}function tb(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+=ra(r))}return t}function ra(e){if(ae.isIdentifier(e))return`:${e.name}`;if(ae.isMemberExpression(e)){let t=Dd(e);if(t)return`env:${t}`}return`:${nb(e)}`}function nb(e){return ZS(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function Fo(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(qS,"$1<redacted>@").replace(eb,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?QS.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function rb(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 ob(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function Md(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function Dd(e){return!ae.isMemberExpression(e.object)||!ae.isIdentifier(e.object.object,{name:"process"})||!ib(e.object.property,"env")?null:ae.isIdentifier(e.property)?e.property.name:ae.isStringLiteral(e.property)?e.property.value:null}function ib(e,t){return ae.isIdentifier(e)&&e.name===t}function ft(e){if(ae.isIdentifier(e))return e.name;if(ae.isMemberExpression(e)){let t=ft(e.object),n=ae.isIdentifier(e.property)?e.property.name:ae.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var sb=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),ab=new Set(["getConfig","submit"]);function Bd(e,t){let n=cb(ft(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!sb.has(i))return null;let s=oa(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(!ab.has(i))return null;let s=oa(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=oa(e,0)??"/cms/:path";return{sourceKind:"vcp-cms-collection",sourceType:"cms-field",operation:n,endpointPattern:i,confidence:i==="/cms/:path"?"partial":"safe-derived",evidence:[{file:t.file,symbol:n,reason:"VCP CMS fetch helper"}]}}return null}function cb(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 jd(e,t){let n=ft(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 $d(e){let t=ft(e.callee);return typeof t=="string"&&t.startsWith("cms.field.")}function oa(e,t){let n=e.arguments[t];return Ld.isStringLiteral(n)?n.value:null}var la=typeof sa=="function"?sa:sa.default,vN=typeof ia=="function"?ia:ia.default,ub={maxFunctionDepth:8,maxImportDepth:6},db=new Set(["src","href","alt","poster","content","title","aria-label"]);async function zd(e){let t=e.fileCache??new Map,n=pa(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...ub,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:af(n,e.element.componentName)};await Hd(e.element.componentName,e.graph,r);let o=[];o.push(...await hb(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await yb(s,e.element,e.graph,r);a&&o.push(ca(a,"text","children"))}for(let s of e.element.attributes??[]){let a=gb(s);if(!a)continue;let c=await Yd(s.source,e.element,e.graph,r);c&&o.push(ca(c,a,s.name))}let i=_b(o).sort(of);return{hasDynamicData:i.length>0,bindings:i}}async function Hd(e,t,n){if(n.importDepth>=n.options.maxImportDepth)return;let r=n.analysis.functions.get(e)??n.analysis.functions.get("default"),o=r?.params[0];if(!r||!o)return;let i=n.analysis.functions.get("default")===r?"default":e,s=[];for(let l of t.elements.values()){if(l.sourceFile===n.file&&l.tag===e){s.push(l);continue}!l.importedFrom||!l.exportName||l.importedFrom===n.file&&l.exportName!==i||(l.importedFrom===n.file||await Wd(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 Gd(l.sourceFile,n);if(!d)continue;let p=Do(d,n,{importDepth:n.importDepth+1});p.paramSources.clear(),p.scopeVariables=af(d,l.componentName),await Hd(l.componentName,t,p);let m=await fb(l,p);for(let[g,S]of m){if(!S)continue;let C=a.get(g)??[];C.push(S),a.set(g,C)}}finally{n.resolvingComponentProps.delete(u)}}}let c=new Map;for(let[l,u]of a){let d=nf(u);d.length===1&&c.set(l,d[0])}mb(o,c,n)}async function Wd(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 Gd(e,r))?.imports.get(t);if(!s||!lt(s.source))return!1;let a=await uf(e,s.source,r.exists);return a?a===n?!0:Wd(a,s.importedName,n,r,o):!1}async function fb(e,t){let n=new Map;la(t.analysis.ast,{JSXElement(o){if(pb(o.node,e.sourceRange)){for(let i of o.node.openingElement.attributes)!k.isJSXAttribute(i)||!k.isJSXIdentifier(i.name)||!k.isJSXExpressionContainer(i.value)||!k.isExpression(i.value.expression)||n.set(i.name.name,i.value.expression);o.stop()}}});let r=new Map;for(let[o,i]of n){let s=await Ce(i,t);s&&r.set(o,s)}return r}function pb(e,t){return e.loc?.start.line===t.startLine&&e.loc.start.column===t.startColumn&&e.loc.end.line===t.endLine&&e.loc.end.column===t.endColumn}async function Gd(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 pa(e,r,t.fileCache)}function mb(e,t,n){if(k.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,fa(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 gb(e){return e.name==="dangerouslySetInnerHTML"?"richtext":db.has(e.name)?"attribute":null}async function hb(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 ua(i.collectionSource,n);s&&r.push(ca(On(s),"repeat-region",i.collectionExpression))}return r}async function yb(e,t,n,r){return Yd(e.source,t,n,r)}async function Yd(e,t,n,r){let o=await xb(e,t,n,r);return o||ua(e,r)}async function xb(e,t,n,r){if(!e)return null;let o=Sb(e.base,t,n);if(!o)return null;let i=await ua(o.collectionSource,r);return i?yr(i,e.path,!0):null}function Sb(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 ua(e,t){if(!e)return null;let n=await Zd(e.base,t);return n?yr(n,e.path,!1):null}async function Zd(e,t){let n=t.paramSources.get(e);if(n)return we(n);if(t.variableCache.has(e))return Fb(t.variableCache.get(e)??null);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let r=await bb(e,t);if(r)return t.variableCache.set(e,we(r)),t.resolvingVariables.delete(e),r;let o=t.scopeVariables?.get(e)??t.analysis.variables.get(e);if(o){let s=await Ce(o,t);return t.variableCache.set(e,s?we(s):null),t.resolvingVariables.delete(e),s}let i=t.analysis.imports.get(e);if(i&&t.importDepth<t.options.maxImportDepth){let s=await cf(i,t);if(s){let a=Do(s,t,{importDepth:t.importDepth+1}),c=lf(i,s);if(c){let d=(await tn(c,[],a)).returnSource;return t.variableCache.set(e,d?we(d):null),t.resolvingVariables.delete(e),d}let l=s.variables.get(i.importedName);if(l){let u=await Ce(l,a);return t.variableCache.set(e,u?we(u):null),t.resolvingVariables.delete(e),u}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}async function bb(e,t){let n=t.analysis.stateSetters.get(e);if(!n)return null;let r=[];la(t.analysis.ast,{CallExpression(o){if(k.isIdentifier(o.node.callee,{name:n})){let i=o.node.arguments[0];k.isExpression(i)&&r.push(i);return}o.node.arguments.some(i=>k.isIdentifier(i)&&i.name===n)&&r.push(o.node)}});for(let o of r){let i=await Ce(o,t);if(i)return i}return null}async function Ce(e,t){if(k.isIdentifier(e))return Zd(e.name,t);if(k.isMemberExpression(e)||k.isOptionalMemberExpression(e)){let n=k.isMemberExpression(e)?jd(e,{file:t.file}):null;if(n)return tf(n);let r=await Eb(e,t);if(!r)return null;let o=Ab(e);return yr(r,o,!1)}if(k.isAwaitExpression(e))return k.isExpression(e.argument)?Ce(e.argument,t):null;if(k.isCallExpression(e))return Qd(e,t);if(k.isObjectExpression(e)){let n=await qd(e,t);return Object.keys(n).length>0?fa(n,t.file):null}if(k.isConditionalExpression(e)){let n=await Ce(e.consequent,t),r=await Ce(e.alternate,t);return hr(Ud(n,r))}if(k.isLogicalExpression(e)){let n=await Ce(e.left,t),r=await Ce(e.right,t);return hr(Ud(n,r))}return k.isTSAsExpression(e)||k.isTSSatisfiesExpression(e)||k.isTSNonNullExpression(e)||k.isTypeCastExpression(e)||k.isParenthesizedExpression(e)?Ce(e.expression,t):null}async function Eb(e,t){let n=e;for(;k.isMemberExpression(n)||k.isOptionalMemberExpression(n);)n=n.object;return k.isExpression(n)?Ce(n,t):null}async function Qd(e,t){let n=Bd(e,{file:t.file,imports:t.analysis.imports});if(n)return tf(n);if($d(e)){let d=e.arguments[0];if(d&&k.isExpression(d))return hr(await Ce(d,t))}let r=await Ib(e,t);if(r)return r;let o=Od(e,{file:t.file});if(o)return{sourceKind:o.sourceKind,sourceType:"api-field",endpointPattern:o.endpointPattern,valuePath:o.valuePath,confidence:o.confidence,readonly:!0,evidence:o.evidence};let i=await Cb(e,t);if(i)return i;let s=await Rb(e,t);if(s)return s;let a=await wb(e,t);if(a)return a;let c=await Nb(e,t);if(c)return c;let l=[];for(let d of e.arguments)if(k.isExpression(d)){let p=await Ce(d,t);p&&l.push(p)}let u=nf(l);return u.length===1?hr(u[0]):null}async function Ib(e,t){let n=ft(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=kb(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(k.isIdentifier(s)){let a=await gr(s.name,t);if(a)return(await tn(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!k.isObjectExpression(r))return Mo(t.file,`${n} without static options`);let o=vb(r,"queryFn");if(!o)return Mo(t.file,`${n} without queryFn`);if(k.isIdentifier(o)){let i=await gr(o.name,t);return i?(await tn(i.node,[],i.context)).returnSource:Mo(t.file,`${n} queryFn unresolved`)}return k.isArrowFunctionExpression(o)||k.isFunctionExpression(o)?(await tn(o,[],t)).returnSource:k.isCallExpression(o)?Qd(o,t):null}function vb(e,t){for(let n of e.properties){if(!k.isObjectProperty(n)||!k.isExpression(n.value))continue;if(ef(n)===t)return n.value}return null}function kb(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 Cb(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 Ce(e.callee.object,t):null;if(!r)return null;if(n!=="map")return On(r);let o=e.arguments[0];if(k.isIdentifier(o)){let i=await gr(o.name,t);if(!i)return On(r);let s=await tn(i.node,[r],i.context);return{...On(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(k.isArrowFunctionExpression(o)||k.isFunctionExpression(o)){let i=await tn(o,[r],t);return{...On(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return On(r)}async function Rb(e,t){return!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property,{name:"json"})||!k.isExpression(e.callee.object)?null:Ce(e.callee.object,t)}async function wb(e,t){return!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property,{name:"then"})||!k.isExpression(e.callee.object)?null:hr(await Ce(e.callee.object,t))}async function Nb(e,t){if(!k.isIdentifier(e.callee))return null;let n=await gr(e.callee.name,t);if(!n)return null;let r=[];for(let i of e.arguments){if(!k.isExpression(i)){r.push(Mo(t.file,`unsupported argument for ${e.callee.name}`));continue}let s=await Ce(i,t);r.push(s)}return(await tn(n.node,r,n.context)).returnSource}async function gr(e,t){let n=t.analysis.functions.get(e);if(n)return{node:n,context:t};let r=t.analysis.imports.get(e);if(!r||t.importDepth>=t.options.maxImportDepth)return null;let o=await cf(r,t);if(!o)return null;let i=Do(o,t,{importDepth:t.importDepth+1}),s=lf(r,o);return s?{node:s,context:i}:gr(r.importedName,i)}async function tn(e,t,n){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let r=Do(n.analysis,n,{functionDepth:n.functionDepth+1});r.scopeVariables=n.analysis.functionVariables.get(e),e.params.forEach((c,l)=>{let u=t[l];u&&aa(c,Tb(u),r)});let o=Pb(e),i=null,s,a=!1;for(let c of o){if(k.isObjectExpression(c)){s={...s??{},...await qd(c,r)},i=i??fa(s,n.file);continue}let l=await Ce(c,r);if(l){if(!i){i=l;continue}let u=da(i,l);if(!u){a=!0,i=null;continue}i=u}}return{returnSource:a?null:i,...s?{objectReturnMap:s}:{}}}function aa(e,t,n){if(k.isIdentifier(e)){n.paramSources.set(e.name,we(t));return}if(k.isAssignmentPattern(e)){aa(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=yr(t,[{kind:"property",name:r.key.name}],!0),i=k.isAssignmentPattern(r.value)?r.value.left:r.value;aa(i,o,n)}}function Pb(e){if(k.isArrowFunctionExpression(e)&&k.isExpression(e.body))return[e.body];let t=[],n=e.body;if(!k.isBlockStatement(n))return t;let r=o=>{if(k.isFunction(o)&&o!==e)return;if(k.isReturnStatement(o)){o.argument&&k.isExpression(o.argument)&&t.push(o.argument);return}let i=k.VISITOR_KEYS[o.type];for(let s of i??[]){let a=o[s];if(Array.isArray(a))for(let c of a)k.isNode(c)&&r(c);else k.isNode(a)&&r(a)}};return r(n),t}async function qd(e,t){let n={};for(let r of e.properties){if(!k.isObjectProperty(r))continue;let o=ef(r);if(!o||!k.isExpression(r.value))continue;let i=await Ce(r.value,t);i&&(n[o]=i)}return n}function ef(e){return k.isIdentifier(e.key)&&!e.computed?e.key.name:k.isStringLiteral(e.key)?e.key.value:null}function Ab(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 yr(e,t,n){if(t.length===0)return we(e);let r=t[0];if(r?.kind==="property"&&e.fieldMap?.[r.name])return yr(e.fieldMap[r.name],t.slice(1),n);let o=we(e);if(o.sourceType==="cms-field"){let i=t.filter(s=>s.kind==="property").map(s=>s.name);return i[0]==="data"&&i[1]==="items"?(o.valuePath=mr(o.valuePath,"data.items[]"),o.cmsFieldRoot=!1,o):i[0]==="fields"?(o.fieldPath=mr(o.fieldPath,i.slice(1).join(".")),o.cmsFieldRoot=!0,o):o.cmsFieldRoot||n||o.fieldMap?(o.fieldPath=mr(o.fieldPath,i.join(".")),o):(o.valuePath=mr(o.valuePath,Vd(t)),o)}return o.valuePath=mr(o.valuePath,Vd(t)),o}function Vd(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function mr(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function tf(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 On(e){let t=we(e);return t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function Tb(e){let t=we(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&(t.cmsFieldRoot=!1),t}function hr(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 Ud(e,t){return e?t?da(e,t):we(e):t?we(t):null}function da(e,t){if(Oo(e)!==Oo(t))return null;let n=sf(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function nf(e){let t=new Map;for(let n of e){let r=Oo(n),o=t.get(r);t.set(r,o?da(o,n):we(n))}return[...t.values()]}function Oo(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,Oo(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 fa(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 Mo(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function ca(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 rf(e){let t=[...e].sort(of),n=t[0];return{hasDynamicData:t.length>0,sourceKinds:[...new Set(t.map(r=>r.sourceKind))],...n?.endpointPattern?{primaryEndpoint:n.endpointPattern}:{},...n?.collection?{primaryCollection:n.collection}:{},...n?.fieldPath?{primaryFieldPath:n.fieldPath}:{}}}function _b(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 of(e,t){return Kd(e.targetKind)-Kd(t.targetKind)||sf(e.confidence,t.confidence)||Jd(e.sourceKind)-Jd(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function Kd(e){return{"repeat-region":0,text:1,richtext:2,attribute:3,"component-prop":4}[e]}function Jd(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function sf(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function pa(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=lb(t,{sourceType:"module",plugins:["jsx","typescript"]}),i={file:e,source:t,ast:o,variables:new Map,functions:new Map,imports:new Map,stateSetters:new Map,functionVariables:new WeakMap};return la(o,{ImportDeclaration(s){let a=s.node.source.value;for(let c of s.node.specifiers)k.isImportSpecifier(c)&&k.isIdentifier(c.local)?i.imports.set(c.local.name,{source:a,importedName:k.isIdentifier(c.imported)?c.imported.name:c.imported.value,localName:c.local.name,isDefault:!1}):k.isImportDefaultSpecifier(c)&&i.imports.set(c.local.name,{source:a,importedName:"default",localName:c.local.name,isDefault:!0})},FunctionDeclaration(s){s.node.id?.name&&i.functions.set(s.node.id.name,s.node)},VariableDeclarator(s){let a=s.getFunctionParent(),c=a&&(k.isFunctionDeclaration(a.node)||k.isFunctionExpression(a.node)||k.isArrowFunctionExpression(a.node))?a.node:null,l=c?i.functionVariables.get(c)??new Map:i.variables;c&&!i.functionVariables.has(c)&&i.functionVariables.set(c,l);for(let u of Dn(s.node.id))l.set(u,k.isExpression(s.node.init)?s.node.init:null);if(k.isArrayPattern(s.node.id)&&k.isCallExpression(s.node.init)&&ft(s.node.init.callee)==="useState"){let[u,d]=s.node.id.elements;k.isIdentifier(u)&&k.isIdentifier(d)&&i.stateSetters.set(u.name,d.name)}k.isIdentifier(s.node.id)&&Xd(s.node.init)&&i.functions.set(s.node.id.name,s.node.init)},ExportNamedDeclaration(s){let a=s.node.declaration,c=s.node.source?.value;if(c)for(let l of s.node.specifiers){if(!k.isExportSpecifier(l))continue;let u=k.isIdentifier(l.exported)?l.exported.name:l.exported.value,d=l.local.name;i.imports.set(u,{source:c,importedName:d,localName:u,isDefault:d==="default"})}if(k.isFunctionDeclaration(a)&&a.id?.name&&i.functions.set(a.id.name,a),k.isVariableDeclaration(a))for(let l of a.declarations)k.isIdentifier(l.id)&&Xd(l.init)&&i.functions.set(l.id.name,l.init)},ExportDefaultDeclaration(s){let a=s.node.declaration;if((k.isFunctionDeclaration(a)||k.isFunctionExpression(a)||k.isArrowFunctionExpression(a))&&i.functions.set("default",a),k.isIdentifier(a)){let c=i.functions.get(a.name);c&&i.functions.set("default",c)}}}),n.set(e,i),i}function Dn(e){return!e||k.isVoidPattern(e)?[]:k.isIdentifier(e)?[e.name]:k.isObjectPattern(e)?e.properties.flatMap(t=>k.isObjectProperty(t)?Dn(t.value):Dn(t.argument)):k.isArrayPattern(e)?e.elements.flatMap(t=>t?Dn(k.isRestElement(t)?t.argument:t):[]):k.isAssignmentPattern(e)?Dn(e.left):k.isRestElement(e)?Dn(e.argument):[]}function Xd(e){return k.isFunctionExpression(e)||k.isArrowFunctionExpression(e)}function af(e,t){let n=e.functions.get(t)??e.functions.get("default");return n?e.functionVariables.get(n):void 0}async function cf(e,t){let n=await uf(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return pa(n,r,t.fileCache)}function lf(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function uf(e,t,n){return lt(t)?gn(e,t,n):null}function Do(e,t,n={}){return{file:e.file,analysis:e,readFile:t.readFile,exists:t.exists,fileCache:t.fileCache,options:t.options,variableCache:new Map,functionDepth:n.functionDepth??t.functionDepth,importDepth:n.importDepth??t.importDepth,paramSources:new Map(t.paramSources),resolvingVariables:new Set,resolvingComponentProps:t.resolvingComponentProps,scopeVariables:e===t.analysis?t.scopeVariables:void 0}}function Fb(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)]))}:{}}}var Mb=50,Ob=8*1024*1024;function mf(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??Mb),s=Math.max(0,t.maxUndoBytes??Ob);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:u,redo:d};async function a(N){let X=[...N.steps].sort((W,q)=>W.order-q.order),M=X.filter(W=>W.type!=="invoke-external-adapter");if(M.length!==X.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let D=new Set(M.map(W=>W.file)),Z=await P(D),te=new Map(Z.map(W=>[W.file,W.exists===!1?"":W.content])),he;for(let W of M){let q=pf(W,te.get(W.file)??"");if(!q.ok)return{ok:!1,errorCode:q.errorCode,reason:q.reason};te.set(W.file,q.source),he=q.selectionRef??he}return{ok:!0,filePlan:{operationId:N.operationId,kind:"source-edit",target:N.target,documentVersion:N.documentVersion,conflictPolicy:"compare-and-swap",edits:[...te].map(([W,q])=>({operation:"upsert",file:W,content:q,baseContentHash:Z.find(xe=>xe.file===W)?.sha256??null}))},...he?{selectionRef:he}:{}}}async function c(N){let X=[...N.steps].sort((xe,Et)=>xe.order-Et.order),M=X.filter(xe=>xe.type!=="invoke-external-adapter"),D=X.filter(xe=>xe.type==="invoke-external-adapter"),Z=new Set(M.map(xe=>xe.file));if(M.length>0&&D.length>0)return{ok:!1,operationId:N.operationId,errorCode:"unsupported-operation",reason:"Mixed local file rewrites and external adapter writes require an explicit compensation contract.",rolledBack:!1};if(M.length===0)return C(N,D);let te=await P(Z),he=new Map;for(let xe of te)he.set(xe.file,xe.exists===!1?"":xe.content);let W;for(let xe of M){let Et=he.get(xe.file)??"",It=pf(xe,Et);if(!It.ok)return{ok:!1,operationId:N.operationId,errorCode:It.errorCode,reason:It.reason,rolledBack:!1};he.set(xe.file,It.source),It.selectionRef&&(W=It.selectionRef)}let q=await B([...he].map(([xe,Et])=>({file:xe,content:Et,exists:!0,version:0,sha256:le(Et)})),te);return q.ok===!1?{ok:!1,operationId:N.operationId,errorCode:q.rolledBack?"writeback-failed":"rollback-failed",reason:q.reason,rolledBack:q.rolledBack}:(n.push({operationId:N.operationId,preSnapshots:te,postSnapshots:q.snapshots,plan:N}),p(),r.length=0,{ok:!0,operationId:N.operationId,kind:N.kind,target:N.target,resultVersion:Math.max(...q.snapshots.map(xe=>xe.version)),affectedFiles:[...Z],...W?{selectionRef:W}:{}})}async function l(N){let X=new Set(N.edits.map(q=>q.file)),M=await P(X),D=v(N,M);if(D)return{ok:!1,operationId:N.operationId,errorCode:"stale-version",reason:D.reason,affectedFiles:[D.file],rolledBack:!1};let Z=new Map(M.map(q=>[q.file,q])),te=N.edits.find(q=>q.operation==="create-only"&&Z.get(q.file)?.exists!==!1);if(te)return{ok:!1,operationId:N.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${te.file}`,affectedFiles:[te.file],rolledBack:!1};let he=N.edits.map(q=>q.operation==="delete"?{file:q.file,content:"",exists:!1,version:0}:{file:q.file,content:q.content,exists:!0,version:0,sha256:le(q.content)}),W=await B(he,M,new Set(N.edits.filter(q=>q.operation==="create-only").map(q=>q.file)));return W.ok===!1?{ok:!1,operationId:N.operationId,errorCode:W.rolledBack?"writeback-failed":"rollback-failed",reason:W.reason,rolledBack:W.rolledBack}:(n.push({operationId:N.operationId,preSnapshots:M,postSnapshots:W.snapshots,plan:{operationId:N.operationId,kind:N.kind,target:N.target,documentVersion:N.documentVersion,steps:[],preSnapshots:M}}),p(),r.length=0,{ok:!0,operationId:N.operationId,kind:N.kind,target:N.target,resultVersion:Math.max(...W.snapshots.map(q=>q.version)),affectedFiles:[...X]})}async function u(){let N=n.at(-1);if(!N)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let X=await B(N.preSnapshots,N.postSnapshots);return X.ok===!1?{ok:!1,operationId:N.operationId,errorCode:X.rolledBack?"writeback-failed":"rollback-failed",reason:X.reason,rolledBack:X.rolledBack}:(n.pop(),r.push(N),{ok:!0,operationId:N.operationId,kind:N.plan.kind,target:N.plan.target,resultVersion:Math.max(...X.snapshots.map(M=>M.version)),affectedFiles:N.preSnapshots.map(M=>M.file)})}async function d(){let N=r.at(-1);if(!N)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let X=await B(N.postSnapshots,N.preSnapshots);return X.ok===!1?{ok:!1,operationId:N.operationId,errorCode:X.rolledBack?"writeback-failed":"rollback-failed",reason:X.reason,rolledBack:X.rolledBack}:(r.pop(),n.push(N),p(),{ok:!0,operationId:N.operationId,kind:N.plan.kind,target:N.plan.target,resultVersion:Math.max(...X.snapshots.map(M=>M.version)),affectedFiles:N.postSnapshots.map(M=>M.file)})}function p(){for(;n.length>i;)n.shift();for(;n.length>0&&m()>s;)n.shift()}function m(){return n.reduce((N,X)=>N+g(X),0)}function g(N){return S(N.preSnapshots)+S(N.postSnapshots)}function S(N){return N.reduce((X,M)=>X+M.file.length+M.content.length,0)}async function C(N,X){let M=[];for(let D of X){let Z=D.capability??"write-text",te=o.find(W=>W.sourceType===D.sourceType&&(D.adapterId===void 0||W.adapterId===D.adapterId)&&(W.capabilities===void 0||W.capabilities.includes(Z)));if(!te)return{ok:!1,operationId:N.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${D.sourceType}`,rolledBack:!1};let he=await te.execute(D);if(!he.ok)return{ok:!1,operationId:N.operationId,errorCode:"writeback-failed",reason:he.reason??`External adapter failed for ${D.sourceType}`,rolledBack:!1};M.push(D.file)}return{ok:!0,operationId:N.operationId,kind:N.kind,target:N.target,resultVersion:0,affectedFiles:M}}function v(N,X){if(N.conflictPolicy!=="compare-and-swap")return null;let M=new Map(X.map(D=>[D.file,D]));for(let D of N.edits){if(D.operation==="create-only")continue;if(D.baseContentHash===void 0)return{file:D.file,reason:`Source file ${D.file} is missing baseContentHash. Reopen the file before saving.`};let Z=M.get(D.file),te=D.baseContentHash;if(te===null){if(Z?.exists!==!1)return{file:D.file,reason:`Source file ${D.file} was created or changed before save.`};continue}if(!te)return{file:D.file,reason:`Source file ${D.file} is missing baseContentHash. Reopen the file before saving.`};if(Z?.exists===!1||Z?.sha256!==te)return{file:D.file,reason:`Source file ${D.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function P(N){let X=[];for(let M of N)X.push(await w(M));return X}async function w(N){if(!await e.exists(N))return{file:N,content:"",version:0,exists:!1};let M=Math.max(1,e.getVersion(N)),D=await e.readFile(N);return{file:N,content:D,version:M,exists:!0,sha256:le(D)}}async function B(N,X,M=new Set){let D=[];try{for(let Z of N){if(M.has(Z.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive(Z.file,Z.content)}else await re(Z);let te=e.bumpVersion(Z.file);D.push(Z.file),Z.version=te}}catch(Z){let te=await ne(X.filter(W=>D.includes(W.file)));if(te.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${te.failedFiles.join(", ")}: ${ff(Z)}`,rolledBack:!1,instanceConflict:df(Z)};let he=df(Z);return{ok:!1,reason:`${he?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${ff(Z)}`,rolledBack:!0,instanceConflict:he}}return{ok:!0,snapshots:N.map(Db)}}async function re(N){if(N.exists===!1){await e.deleteFile(N.file);return}await e.writeFile(N.file,N.content)}async function ne(N){let X=[];for(let M of N)try{await re(M),e.bumpVersion(M.file)}catch{X.push(M.file)}return X.length===0?{ok:!0}:{ok:!1,failedFiles:X}}}function df(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function Db(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:le(e.content)}:{}}}function ff(e){return e instanceof Error?e.message:String(e)}function pf(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 De(wn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return De(Nn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return De(In({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return De(kn({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return De(io({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return De(Qn({source:t,locator:e.locator,next:e.value}));case"update-array-item":return De(Qn({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return De(lo({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return De(so({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return De(uo({source:t,locator:e.locator,index:e.index}));case"move-array-item":return De(fo({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return De(Rn({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return De(ao({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 Lb(e,t);case"set-props":{let n=e;return De(co({source:t,locator:n.locator,props:n.props}))}default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function Lb(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!lu(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!==le(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:cu({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function De(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"}}}function gf(){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 Bb}from"node:crypto";import Lo from"node:fs/promises";import ma from"node:path";import{setTimeout as jb}from"node:timers/promises";var $b={async mkdir(e,t){await Lo.mkdir(e,t)},async writeFile(e,t,n){await Lo.writeFile(e,t,n)},async rename(e,t){await Lo.rename(e,t)},async rm(e,t){await Lo.rm(e,t)}},Vb=new Set(["EACCES","EBUSY","EPERM"]),Ub=[10,20,40,80,160];async function Kb(e,t,n){for(let r of Ub)try{await e.rename(t,n);return}catch(o){if(!Jb(o))throw o;await jb(r)}await e.rename(t,n)}function Jb(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&Vb.has(e.code)}async function Bo(e,t,n=$b){let r=ma.dirname(e),o=ma.basename(e),i=ma.join(r,`.${o}.${process.pid}.${Bb()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await Kb(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import{randomBytes as oE}from"node:crypto";import bt from"node:path";import{parse as iE}from"@babel/parser";import sE from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as $o,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as yf,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as aE,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as cE,SiteEditMaterializationSchema as lE,parseComponentI18nResourcesJson as uE}from"@vcp-dev/contracts";var hf=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,Xb=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,zb=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,Hb=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,Wb=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,Gb=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,Yb=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,Zb=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,Qb=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,qb=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,eE=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,tE=/\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,nE=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,rE=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function xr(e,t){let n=jo([...We(e,zb),...We(e,Hb),...We(e,Wb),...We(e,t.includeRgbBackgroundImage?Gb:Yb),...t.includeExtendedColorFunctions?[...We(e,Zb),...We(e,Qb)]:[]]),r=jo([...We(e,qb),...We(e,eE)]).filter(o=>t.colorMixPolicy==="always"||hf.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...We(e,tE).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...We(e,rE).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:jo(We(e,Xb)),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?jo(We(e,nE)):[]}}function We(e,t){return e.match(new RegExp(t.source,t.flags))??[]}function jo(e){return[...new Set(e)]}var ya="components/site/generated",xf="{{$INSTANCE}}",Vo=5,dE=/^[a-z][a-z0-9-]{0,48}$/,fE=/^[a-f0-9]{8}$/,Sf=/\.tsx?$/,pE=/\.json$/,mE=/\.(?:tsx?|json)$/,gE=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,hE=["react","react/","next","next/","lucide-react","react-i18next","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],ga=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),ha=sE,yE=typeof ha=="function"?ha:ha.default;function xE(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>yf)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=PE(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=lE.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=RE(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${ya}.`,path:e.generatedRoot}};if(!Cf(r.data.instanceBaseName))return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_INVALID",message:"Static prefab instanceBaseName must contain at least one safe word.",path:r.data.instanceBaseName}};let i=If(r.data.files),s=If(e.controlledFiles);if(!AE(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>yf)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>aE)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>cE?{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 SE(e){let t=xE(e);if(!t.ok)return t;let n=t.data.generatedRoot,r=Cf(e.manifest.instanceBaseName),o=Math.max(1,Math.min(Vo,e.maxAttempts??Vo));for(let i=0;i<o;i+=1){let s=wE(e.instanceNameGenerator?.()??oE(4).toString("hex"));if(!s)return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_INVALID",message:"Static prefab instance suffix must be 8 lowercase hex chars."}};let a=`${r}-${s}`,c=wf(n,a),l=bE({manifest:e.manifest,generatedRoot:n,instanceName:a,instanceRoot:c,allowedExternalImports:e.allowedExternalImports??hE});if(!l.ok)return l;if(!await EE(e.exists,c,l.data.files))return{ok:!0,data:l.data}}return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:"Unable to allocate a create-only static prefab instance after repeated conflicts."}}}async function kf(e){let t=Math.max(1,Math.min(Vo,e.maxAttempts??Vo));for(let n=0;n<t;n+=1){let r=await SE({...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 bE(e){let t=[],n=new Set;for(let i of e.manifest.files){let s=bf({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=bf({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=IE(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 EE(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function bf(e){if(e.pathTemplate.split(xf).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(xf,e.instanceName),n=NE(t);return n?wf(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||!mE.test(n)||gE.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 IE(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(pE.test(d.path)){if(d.path.endsWith($o)){let g=uE(d.content);if(!g.success)return nn("MATERIALIZATION_DATA_UNSUPPORTED",g.error.message,d.path);c.set(d.path,new Set)}else try{JSON.parse(d.content)}catch{return nn("MATERIALIZATION_DATA_UNSUPPORTED","Static prefab JSON file must contain valid JSON.",d.path)}continue}let p;try{p=iE(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 m=xr(d.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{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,p)}for(let d of e){if(!Sf.test(d.path))continue;let p=s.get(d.path),m=null;if(yE(p,{ImportDeclaration(g){let S=Ef({importer:d.path,source:g.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});if(!S.allowed)m??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab imports must resolve within the controlled instance or match the starter allowlist.",file:d.path},g.stop();else if(S.internalPath&&(a.get(d.path).add(S.internalPath),S.internalPath.endsWith($o))){let C=vE({importer:d.path,imported:S.internalPath,source:g.node.source.value,ast:p});C.ok?c.get(S.internalPath).add(d.path):(m??=C.error,g.stop())}},ExportAllDeclaration(g){m??={code:"MATERIALIZATION_ENTRY_INVALID",message:"Static prefab files cannot use export-star declarations.",file:d.path},g.stop()},ExportNamedDeclaration(g){if(g.node.source){let S=Ef({importer:d.path,source:g.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});!S.allowed||!S.internalPath?(m??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab re-exports must resolve within the controlled instance.",file:d.path},g.stop()):a.get(d.path).add(S.internalPath)}},CallExpression(g){if(g.node.callee.type==="Import"){m??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use dynamic import().",file:d.path},g.stop();return}g.node.callee.type==="Identifier"&&g.node.callee.name==="require"&&(m??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use require().",file:d.path},g.stop())},NewExpression(g){g.node.callee.type==="Identifier"&&g.node.callee.name==="Function"&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot construct functions dynamically.",file:d.path},g.stop())},MetaProperty(g){g.node.meta.type==="Identifier"&&g.node.meta.name==="import"&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot use import.meta.",file:d.path},g.stop())},MemberExpression(g){let S=vf(g.node);S&&ga.has(S)&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${S}.`,file:d.path},g.stop())},OptionalMemberExpression(g){let S=vf(g.node);S&&ga.has(S)&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${S}.`,file:d.path},g.stop())},Identifier(g){g.isReferencedIdentifier()&&ga.has(g.node.name)&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${g.node.name}.`,file:d.path},g.stop())},JSXAttribute(g){g.node.name.type==="JSXIdentifier"&&g.node.name.name==="style"&&(m??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot use inline style attributes.",file:d.path},g.stop())},JSXOpeningElement(g){g.node.name.type==="JSXIdentifier"&&g.node.name.name.toLowerCase()==="style"&&(m??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot declare style elements.",file:d.path},g.stop())}}),m)return{ok:!1,error:m}}if(!Sf.test(n))return nn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must be a .ts/.tsx source module.",n);let l=s.get(n);if(!l)return nn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",n);if(!kE(l,r))return nn("MATERIALIZATION_EXPORT_MISSING","Static prefab entry does not declare the manifest export.",n);for(let[d,p]of c)if(p.size!==1)return nn("MATERIALIZATION_IMPORT_FORBIDDEN","Each component .i18n.json file must have exactly one same-name Client Component static importer.",d);return CE(n,a).size!==e.length?nn("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",n):{ok:!0,data:{kind:"static-prefab-materialization",instanceName:"",generatedRoot:ya,instanceRoot:"",entry:{path:"",export:{kind:"default"}},files:[]}}}function Ef(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=bt.posix.normalize(bt.posix.join(bt.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 vE(e){let t=bt.posix.dirname(e.importer),n=bt.posix.dirname(e.imported),r=bt.posix.basename(e.importer).replace(/\.tsx?$/,""),o=bt.posix.basename(e.imported).slice(0,-$o.length),i=`./${r}${$o}`;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 kE(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 CE(e,t){let n=new Set,r=[e];for(;r.length>0;){let o=r.pop();n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function nn(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function RE(e){let t=Rf(e);return t===ya?t:null}function wE(e){let t=e.trim().toLowerCase();return fE.test(t)?t:null}function Cf(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 dE.test(t)?t:null}function Rf(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=bt.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function NE(e){let t=Rf(e);return!t||t!==e?null:t}function wf(...e){return bt.posix.join(...e)}function If(e){return new Set(e.map(t=>t.pathTemplate))}function PE(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 AE(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function vf(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{randomBytes as TE}from"node:crypto";import Uo from"node:path";import{parse as Mf}from"@babel/parser";import _E from"@babel/traverse";import*as Of from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as Sa,PageResourceArtifactSchema as FE,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as ME,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as OE,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as DE,parseComponentI18nResourcesJson as LE}from"@vcp-dev/contracts";var ba="{{$INSTANCE}}",BE=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,jE=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,Ea="components/site/generated",$E=/\.(?:tsx?|json)$/,VE=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,UE=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],KE=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),xa=_E,JE=typeof xa=="function"?xa:xa.default;async function Ia(e){let t=FE.safeParse(e.artifact);if(!t.success)return pe("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>TE(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=qE(r());if(!i)return pe("Random instance suffix must be 8 lowercase hex chars.");let s=`${eI(n.resource_id)}-${i}`,a=new Map,c=new Map,l=[];for(let w of n.pages){let B=w.final_route.slice(1);a.set(w.template_page_id,w.final_route),c.set(w.template_page_id,w.title),l.push({template_page_id:w.template_page_id,title:w.title,final_route:w.final_route,route_file_path:`app/${B}/page.tsx`})}let u=[],d=new Set,p=new Set,m=new Map,g=new Map,S=[],C=new Set(n.pages.flatMap(w=>w.components.map(B=>B.component_id)));for(let w of n.components){if(!C.has(w.component_id))continue;let B=Nf({materialization:w.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c});if(!B.ok)return B;for(let re of B.files){let ne=Af(re,d,u);if(ne)return ne}p.add(B.entry),g.set(B.entry,B.entryExport),m.set(w.component_id,B.entry)}for(let[w,B]of n.pages.entries()){let re=l[w],ne=Nf({materialization:B.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c,pageEntryTarget:re.route_file_path});if(!ne.ok)return ne;for(let M of ne.files){let D=Af(M,d,u);if(D)return D}p.add(ne.entry),g.set(ne.entry,ne.entryExport),S.push({entry:ne.entry,declaredComponentIds:new Set(B.components.map(M=>M.component_id))});let N=u.find(M=>M.file===re.route_file_path);if(!N)return pe("Page materialization entry did not resolve to its final route file.",re.route_file_path);if(GE(N.content,re.route_file_path)!==re.final_route)return pe(`Page ${B.template_page_id} requires a static PAGE_SEO.path equal to ${re.final_route}.`,re.route_file_path)}let v=zE(u,p,s,m,S,g);if(!v.ok)return v;for(let w of u)if(await e.exists(w.file))return!w.file.startsWith("app/")&&o>1?Ia({...e,randomHex:r,maxAttempts:o-1}):{ok:!1,code:"MATERIALIZATION_CONFLICT",message:`Page resource create-only target already exists: ${w.file}`,path:w.file};let P=HE(u);return P||(u.sort((w,B)=>w.file.localeCompare(B.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 s=o.pathTemplate===t&&e.pageEntryTarget?e.pageEntryTarget:Pf(o.pathTemplate,e.packageInstanceId);if(!s)return pe("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=XE(o.content,e.packageInstanceId,e.routeByPage,e.titleByPage);if(!a.ok)return a;n.push({operation:"create-only",file:s,content:a.data})}let r=e.pageEntryTarget??Pf(t,e.packageInstanceId);return!r||!n.some(o=>o.file===r)?pe("Materialization entry must match one controlled source file.",t):{ok:!0,files:n,entry:r,entryExport:e.materialization.entry.export}}function XE(e,t,n,r){let o,i=e.replace(BE,(c,l)=>{let u=n.get(l);return u||(o=l,c)});if(o)return pe(`Page route placeholder references unknown template page: ${o}`);let s=i.replace(jE,(c,l)=>{let u=r.get(l);return u?JSON.stringify(u):(o=l,c)});if(o)return pe(`Page title placeholder references unknown template page: ${o}`);let a=s.replaceAll(ba,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?pe("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function Pf(e,t){let n=`${Ea}/${t}`;if(e.split(ba).length>2)return null;let o=e.replace(ba,t),i=`${Ea}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=Uo.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!$E.test(a)||VE.test(a)?null:a}function Af(e,t,n){return t.has(e.file)?pe(`Page resource materializations resolve duplicate target: ${e.file}`,e.file):(t.add(e.file),n.push(e),null)}function zE(e,t,n,r,o,i){let s=new Set(e.map(m=>m.file)),a=`${Ea}/${n}`,c=new Map(e.map(m=>[m.file,new Set])),l=new Map;for(let m of e){if(m.file.endsWith(".json")){try{JSON.parse(m.content)}catch{return pe("Materialization JSON file must contain valid JSON.",m.file)}if(m.file.endsWith(Sa)&&!LE(m.content).success)return pe("Materialization component i18n resources are invalid.",m.file);continue}try{let S=Mf(m.content,{sourceType:"module",plugins:["jsx","typescript"]});l.set(m.file,S);for(let v of S.program.body)if((v.type==="ImportDeclaration"||v.type==="ExportAllDeclaration"||v.type==="ExportNamedDeclaration"&&v.source)&&v.source){let P=v.source.value,w=ZE(m.file,P,s,a);if(!w.allowed)return pe(`Materialization import is outside the controlled package: ${P}`,m.file);w.internalPath&&c.get(m.file).add(w.internalPath)}let C;if(JE(S,{Identifier(v){v.isReferencedIdentifier()&&KE.has(v.node.name)&&(C??=v.node.name,v.stop())},JSXAttribute(v){v.node.name.type==="JSXIdentifier"&&v.node.name.name==="style"&&(C??="inline style",v.stop())},JSXOpeningElement(v){v.node.name.type==="JSXIdentifier"&&v.node.name.name.toLowerCase()==="style"&&(C??="style element",v.stop())}}),C)return pe(`Materialization source uses forbidden capability: ${C}`,m.file)}catch{return pe("Materialization source must parse as TS/TSX.",m.file)}let g=xr(m.content,{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0});if(g.hardCodedSurfaceHits.length>0||g.rawColorHits.length>0||g.privateTokenHits.length>0)return pe("Materialization source violates the public theme token policy.",m.file)}if([...t].some(m=>!s.has(m)))return pe("Materialization entry is outside the controlled package.");for(let m of t)if(m.endsWith(".json"))return pe("Materialization JSON files cannot be package entries.");for(let[m,g]of i){let S=l.get(m);if(!S||!WE(S,g))return pe("Materialization entry does not declare its contracted export.",m)}let u=new Map([...r].map(([m,g])=>[g,m]));for(let m of o){let g=Ff(m.entry,c);for(let S of m.declaredComponentIds){let C=r.get(S);if(!C||!g.has(C))return pe(`Page entry does not reach declared component: ${S}`,m.entry)}for(let S of g){let C=u.get(S);if(C&&!m.declaredComponentIds.has(C))return pe(`Page entry imports undeclared component: ${C}`,m.entry)}}let d=new Set;for(let m of t)for(let g of Ff(m,c))d.add(g);if(d.size!==e.length)return pe("Every materialization file must be reachable from a package entry.");let p=QE(e,l,c);return p||{ok:!0}}function HE(e){if(e.length>ME)return pe("Page resource exceeds the aggregate source file limit.");let t=0;for(let n of e){let r=Buffer.byteLength(n.content,"utf8");if(r>OE)return pe("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>DE?pe("Page resource exceeds the aggregate content byte limit."):null}function WE(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 GE(e,t){let n;try{n=Mf(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return null}for(let r of n.program.body){let o=r.type==="VariableDeclaration"?r:r.type==="ExportNamedDeclaration"&&r.declaration?.type==="VariableDeclaration"?r.declaration:null;if(o)for(let i of o.declarations){if(i.id.type!=="Identifier"||i.id.name!=="PAGE_SEO")continue;let s=Tf(i.init);if(s?.type!=="ObjectExpression")return null;for(let a of s.properties){if(a.type!=="ObjectProperty"||a.computed||!YE(a.key))continue;let c=Tf(a.value);return c?.type==="StringLiteral"?c.value:c?.type==="TemplateLiteral"&&c.expressions.length===0?c.quasis[0]?.value.cooked??null:null}return null}}return null}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 YE(e){return e.type==="Identifier"&&e.name==="path"||e.type==="StringLiteral"&&e.value==="path"}function ZE(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=_f(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:UE.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=Uo.posix.normalize(Uo.posix.join(Uo.posix.dirname(e),t)),i=_f(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function _f(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 QE(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(Sa))continue;let i=o.file.slice(0,-Sa.length),s=[`${i}.tsx`,`${i}.ts`].find(u=>r.has(u));if(!s)return pe("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 pe("Component i18n resources must have exactly one same-name Client Component static importer.",s)}return null}function Ff(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 qE(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function eI(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"page-resource"}function pe(e,t){return{ok:!1,code:"MATERIALIZATION_REJECTED",message:e,...t?{path:t}:{}}}import{COMPONENT_I18N_FILE_SUFFIX as tI,parseComponentI18nResourcesJson as nI,resolveSiteTextDirection as rI,SiteLocaleSchema as oI}from"@vcp-dev/contracts";var iI=["i18next","react-i18next"],sI="components/ui/site-locale-provider.tsx",aI="components/ui/component-i18n-provider.tsx",Df="app/layout.tsx";async function ka(e){let t=e.files.filter(p=>p.path.endsWith(tI));if(t.length===0)return{ok:!0};for(let p of["package.json",Df,sI,aI])if(!await e.exists(p))return rn(`Target snapshot is missing required i18n host file: ${p}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return rn("Target snapshot package.json is invalid.")}let r=Lf(n)&&Lf(n.dependencies)?n.dependencies:{},o=iI.filter(p=>typeof r[p]!="string"||r[p].trim().length===0);if(o.length>0)return rn(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile(Df),s=va(i,"html","lang"),a=va(i,"html","dir"),c=va(i,"SiteLocaleProvider","locale"),l=oI.safeParse(s);if(!l.success||!a||!c||s!==c||a!==rI(l.data))return rn("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 rn("Target snapshot root layout is not wired to SiteLocaleProvider.");let u=l.data,d=u.split("-")[0];for(let p of t){let m=nI(p.content);if(!m.success)return rn(`Component i18n resource is invalid: ${p.path}.`);if(!Object.hasOwn(m.data,u)&&!Object.hasOwn(m.data,d))return rn(`Component i18n resource ${p.path} has no locale for ${u} or ${d}.`)}return{ok:!0}}function va(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 Lf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function rn(e){return{ok:!1,message:e}}import{parse as CI}from"@babel/parser";import{HOME_PAGE_URL_PATH as RI}from"@vcp-dev/contracts";import{parse as MP}from"@babel/parser";import{parse as qN}from"@babel/parser";import{FormBlockIdSchema as tP,FormSpecV1Schema as nP}from"@vcp-dev/contracts";var Sr="components/site/generated/forms",rP=`${Sr}/vcp-form-runtime.tsx`,Ko="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",oP=new RegExp(`^${Sr}/form-(${Ko})\\.spec\\.ts$`),iP=new RegExp(`^${Sr}/form-(${Ko})\\.tsx$`),sP=new RegExp(`^@/${Sr}/form-(${Ko})$`),aP=new RegExp(`(?:^|/)${Sr}/form-(${Ko})(?:\\.tsx?)?$`);var cP=Symbol("invalid-literal");import{createHash as dP}from"node:crypto";import{posix as pP}from"node:path";import{parse as gP}from"@babel/parser";import{FormSpecV1Schema as yP}from"@vcp-dev/contracts";var xP=Symbol("dynamic");import{parse as EP}from"@babel/parser";import{parse as cI}from"@babel/parser";var Bf=["page","anchor","external","email","phone","group","file"],lI=["link","cta"],$f=["description","badge","iconKey"],Ca=["label","targetType","href","role","openInNewTab","nofollow","children",...$f],uI=new Set(Ca);function Er(e){return Array.isArray(e)?e:[]}function br(e){let t=e;return t?.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function dI(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function jf(e){let t=e;return t?.type==="BooleanLiteral"&&typeof t.value=="boolean"?t.value:void 0}function Ra(e){let t=[],n;try{n=cI(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 Er(n.program.body)){let s=i.type==="ExportNamedDeclaration"?i.declaration:i;if(s?.type==="VariableDeclaration")for(let a of Er(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 Er(r.elements).forEach((i,s)=>{let a=Vf(i,`NAV_ITEMS[${s}]`,t);a&&o.push(a)}),{items:o,diagnostics:t}}function Vf(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 Er(e.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=dI(l.key);u&&(r[u]=l.value)}let o=br(r.label),i=br(r.targetType);if(!o)return n.push({severity:"fatal",path:`${t}.label`,message:"label must be a static string"}),null;if(!i||!Bf.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${Bf.join("/")}`}),null;r.group!==void 0&&n.push({severity:"warning",code:"leaf-group-field",path:`${t}.group`,message:'unsupported leaf group field ignored; use a canonical targetType: "group" node with children'});let s={label:o,targetType:i};for(let l of $f){if(r[l]===void 0)continue;let u=br(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))uI.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 ${Ca.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=[];Er(r.children.elements).forEach((u,d)=>{let p=Vf(u,`${t}.children[${d}]`,n);p&&l.push(p)}),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=br(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=br(r.role);if(c!==void 0&&(lI.includes(c)?s.role=c:n.push({severity:"warning",path:`${t}.role`,message:"role ignored: not link/cta"})),r.openInNewTab!==void 0){let l=jf(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=jf(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 fI}from"@babel/parser";function Ir(e){return Array.isArray(e)?e:[]}function Uf(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function wa(e,t){let n=Kf(t);if(!n)return{status:"unsupported",source:e};let r;try{r=fI(e,{sourceType:"module",plugins:["typescript","jsx"],tokens:!0})}catch{return{status:"unsupported",source:e}}let o=[];for(let u of Ir(r.program.body)){let d=u.type==="ExportNamedDeclaration"?u.declaration:u;if(d?.type==="VariableDeclaration")for(let p of Ir(d.declarations)){let m=p.id;m?.type==="Identifier"&&m.name==="NAV_ITEMS"&&o.push(p)}}if(o.length===0)return{status:"navigation_not_found",source:e};if(o.length!==1)return{status:"unsupported",source:e};let i=Uf(o[0]?.init);if(!i)return{status:"unsupported",source:e};if(Ra(e).diagnostics.some(({severity:u})=>u==="fatal"))return{status:"unsupported",source:e};let a=[],c=u=>{let d=Ir(u.elements);for(let[p,m]of d.entries()){if(mI(m,n)){let S=d[p+1],C=d[p-1],v=m.start,P=m.end;if(typeof v!="number"||typeof P!="number")continue;S&&typeof S.start=="number"?a.push({start:v,end:S.start}):C&&typeof C.end=="number"?a.push({start:C.end,end:P}):a.push({start:v,end:P});continue}let g=pI(m);g&&c(g)}};if(c(i),a.length===0)return{status:"not_found",source:e};let l=e;for(let u of a.sort((d,p)=>p.start-d.start))l=l.slice(0,u.start)+l.slice(u.end);return{status:"removed",source:l,removedCount:a.length}}function pI(e){if(e.type==="ObjectExpression")for(let t of Ir(e.properties)){if(t.type!=="ObjectProperty")continue;let n=t.key;if((n?.name??n?.value)==="children")return Uf(t.value)}}function Kf(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function mI(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of Ir(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"&&Kf(n??"")===t}import KP from"node:fs";import XP from"node:path";var gI=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function vr(e){let t=e.map(r=>kI(r.path)),n=hI(t);return n?t.filter(r=>xI(n,r)).map(r=>({routeId:SI(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function Jo(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=vI(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function hI(e){return e.some(r=>r.startsWith("app/")&&!yI(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function yI(e){return e.startsWith("app/_vcp/")||e.startsWith("src/app/_vcp/")}function xI(e,t){if(!t.startsWith(`${e}/`))return!1;let n=t.slice(t.lastIndexOf("/")+1);return gI.test(n)?t.slice(e.length+1,-n.length-1).split("/").filter(Boolean).every(r=>!r.startsWith("_")):!1}function SI(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(EI).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function bI(e){return e.startsWith("(")&&e.endsWith(")")}function EI(e){return!e||e.startsWith("@")||e.startsWith("_")||bI(e)?null:II(e)}function II(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function vI(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function kI(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var wI="components/site/generated/",kr=[".tsx",".ts",".jsx",".js"];function Jf(e){if(e.expectedUrlPath===RI)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set(vr(Object.keys(e.files).map(p=>({path:p}))).map(p=>p.entryFile)),n=Object.entries(e.files).filter(([p,m])=>t.has(p.replace(/\\/g,"/"))?NI(m)===e.expectedUrlPath:!1);if(n.length===0)return{ok:!1,code:"ROUTE_NOT_FOUND",message:"No route uniquely matches PAGE_SEO.path."};if(n.length>1)return{ok:!1,code:"ROUTE_AMBIGUOUS",message:"Multiple routes match PAGE_SEO.path."};let[r]=n[0],o=AI(e.files);if(!o.ok)return o.error;let i=o.graph,s=MI(r,i),a=OI(r,s,i),c=[...s].filter(p=>!a.has(p)).sort((p,m)=>p.localeCompare(m)),l=[{operation:"delete",file:r},...[...a].sort((p,m)=>p.localeCompare(m)).map(p=>({operation:"delete",file:p}))],u=[],d=[];for(let[p,m]of Object.entries(e.files))if(p!==r){if(m.includes("NAV_ITEMS")){let g=wa(m,e.expectedUrlPath);g.status==="removed"?(l.push({operation:"upsert",file:p,content:g.source}),u.push(p)):g.status==="unsupported"&&d.push(`unsupported_navigation:${p}`)}m.includes(e.expectedUrlPath)&&!m.includes("NAV_ITEMS")&&d.push(`preserved_link:${p}`)}return{ok:!0,edits:l,deletedFiles:[r,...[...a].sort((p,m)=>p.localeCompare(m))],updatedFiles:u,preservedSharedFiles:c,warnings:d}}function NI(e){let t;try{t=CI(e,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}for(let n of Na(t.program.body)){let r=n.type==="ExportNamedDeclaration"?n.declaration:n;if(r?.type==="VariableDeclaration")for(let o of Na(r.declarations)){let i=o.id;if(i?.type!=="Identifier"||i.name!=="PAGE_SEO")continue;let s=PI(o.init);if(s?.type!=="ObjectExpression")return null;for(let a of Na(s.properties)){if(a.type!=="ObjectProperty"||a.computed)continue;let c=a.key,l=a.value;if((c?.name==="path"||c?.value==="path")&&l?.type==="StringLiteral"&&typeof l.value=="string")return l.value}return null}}return null}function Na(e){return Array.isArray(e)?e:[]}function PI(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="ParenthesizedExpression";)t=t.expression;return t}function AI(e){let t=new Set(Object.keys(e)),n=new Map;for(let[r,o]of Object.entries(e)){if(!TI(r))continue;let i=Jn(r,o);if(!i.ok)return{ok:!1,error:{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:`Page source dependencies could not be proven safe: ${r} (parse-failed).`}};let s=new Set;for(let{specifier:a}of i.module.imports){if(_I(a))continue;let c=Ri(r,a),l=FI(c,t);if(!l)return{ok:!1,error:{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:`Page source dependencies could not be proven safe: ${r} -> ${a} (import-not-found).`}};s.add(l)}n.set(r,s)}return{ok:!0,graph:n}}function TI(e){let t=e.toLowerCase();return kr.some(n=>t.endsWith(n))}function _I(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!kr.some(n=>e.endsWith(n)))}function FI(e,t){let n=e.replace(/\\/g,"/");return(kr.some(o=>n.endsWith(o))?[n]:[...kr.map(o=>`${n}${o}`),...kr.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function MI(e,t){let n=new Set,r=[...t.get(e)??[]];for(;r.length>0;){let o=r.pop();!o.startsWith(wI)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function OI(e,t,n){let r=new Set(t),o=!0;for(;o;){o=!1;for(let i of[...r])[...n].some(([a,c])=>a!==e&&!r.has(a)&&c.has(i))&&(r.delete(i),o=!0)}return r}import{SiteEditHistoryProvenanceSchema as DI}from"@vcp-dev/contracts";var LI={affectedCompositions:[]};function Yf(e){let t=null,n=new WeakMap;async function r(){return t??=BI(e),t}return{async prepareAppend(o){let i=await e.readIndex(),s=await e.stageAppend(Wf(o),{durableManifest:!1}),a;try{a=await e.previewStagedAppend(s.entryId,i.digest)}catch(l){throw await e.discardStage(s.stageId),l}let c={kind:"append",entry:o,historyTransition:a};return n.set(c,{expectedDigest:i.digest,stageId:s.stageId,entryId:s.entryId}),c},async prepareUndo(){let i=(await r()).undo.at(-1);if(!i?.historyId)return null;let s=await e.readIndex(),a=s.entryIds.indexOf(i.historyId);if(a<0)throw new Error("undo entry is missing from index");let c=a-1,l=await e.previewCursor(c,s.digest),u={kind:"undo",entry:i,historyTransition:l};return n.set(u,{expectedDigest:s.digest,cursor:c}),u},async prepareRedo(){let i=(await r()).redo.at(-1);if(!i?.historyId)return null;let s=await e.readIndex(),a=s.entryIds.indexOf(i.historyId);if(a<0)throw new Error("redo entry is missing from index");let c=a,l=await e.previewCursor(c,s.digest),u={kind:"redo",entry:i,historyTransition:l};return n.set(u,{expectedDigest:s.digest,cursor:c}),u},async publishPrepared(o){let i=n.get(o);if(!i)throw new Error("history mutation was not prepared");let s=await r();if(o.kind==="append"){if(!i.entryId)throw new Error("staged entry id is missing");let a=await e.publishStagedAppend(i.entryId,i.expectedDigest,i.stageId);Xf(a,o.historyTransition),o.entry.historyId=i.entryId,s.entryIds=[...a.entryIds],s.cursor=a.cursor,s.undo.push(o.entry),s.redo.length=0}else{if(i.cursor===void 0)throw new Error("prepared cursor is missing");let a=await e.setCursor(i.cursor,i.expectedDigest);if(Xf(a,o.historyTransition),o.kind==="undo"){if(s.undo.at(-1)!==o.entry)throw new Error("undo state changed before publish");s.undo.pop(),s.redo.push(o.entry)}else{if(s.redo.at(-1)!==o.entry)throw new Error("redo state changed before publish");s.redo.pop(),s.undo.push(o.entry)}s.cursor=i.cursor}n.delete(o)},async discardPrepared(o){let i=n.get(o);if(!i)return;let s=o.historyTransition;if(s){let a=await e.readIndex();if(a.digest===s.publishedIndexDigest&&a.cursor===s.publishedCursor&&a.currentId===s.publishedCurrentId)throw new Error("cannot discard a history mutation whose index was published")}i.stageId&&await e.discardStage(i.stageId),n.delete(o)},async peekUndo(){return(await r()).undo.at(-1)??null},async pushUndo(o){let i=await r(),s=o;if(s.historyId){let l=i.entryIds.indexOf(s.historyId);if(l>=0)try{await e.setCursor(l),i.undo.push(o),i.cursor=l;return}catch(u){throw i.redo.push(o),u}}let a=await e.append(Wf(o)),c=a.currentId;if(!c)throw new Error("history store did not publish an entry");o.historyId=c,i.entryIds=[...a.entryIds],i.cursor=a.cursor,i.undo.push(o),i.redo.length=0},async popUndo(){return(await r()).undo.pop()??null},async peekRedo(){return(await r()).redo.at(-1)??null},async pushRedo(o){let i=await r(),s=o;if(!s.historyId)throw i.undo.push(o),new Error("cannot move an unpersisted history entry to redo");let a=i.entryIds.indexOf(s.historyId);if(a<0)throw i.undo.push(o),new Error("history entry is missing from the durable index");try{await e.setCursor(a-1),i.cursor=a-1,i.redo.push(o)}catch(c){throw i.undo.push(o),c}},async popRedo(){return(await r()).redo.pop()??null},async clearRedo(){(await r()).redo.length=0},async getStatus(){let o=await e.readStatus();return{canUndo:o.canUndo,canRedo:o.canRedo,undoDepth:o.undoDepth,redoDepth:o.redoDepth,recoveryRequired:o.recoveryRequired}},async markRecoveryRequired(o){await e.markRecoveryRequired(o)}}}function Xf(e,t){if(!t)throw new Error("durable history transition is missing");if(e.digest!==t.publishedIndexDigest||e.cursor!==t.publishedCursor||e.currentId!==t.publishedCurrentId)throw new Error("durable history published an unexpected index state")}async function BI(e){let t=await e.readIndex(),n=await Promise.all(t.undoIds.map(async o=>zf(e,o))),r=await Promise.all(t.redoIds.map(async o=>zf(e,o)));return{undo:n.reverse(),redo:r.reverse(),entryIds:[...t.entryIds],cursor:t.cursor}}async function zf(e,t){let n=await e.readEntry(t),r=jI(n),o=r.provenance??LI;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 Hf(e,n,r.preSnapshots),postSnapshots:await Hf(e,n,r.postSnapshots)}}async function Hf(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(UI(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function Wf(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=$I(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 jI(e){if(!Qf(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:Zf(t.provenance)}:{},preSnapshots:Gf(t.preSnapshots,"preSnapshots"),postSnapshots:Gf(t.postSnapshots,"postSnapshots")}}function $I(e){if(e.provenance!==void 0)return Zf(e.provenance);if(e.composition)return{initiatingComposition:e.composition,affectedCompositions:[]}}function Zf(e){let t=DI.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 Gf(e,t){return e.map((n,r)=>{if(!Qf(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&&!VI(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 VI(e){return/^sha256:[0-9a-f]{64}$/.test(e)}function UI(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function Qf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import qf from"node:path";function Aa(){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 tp(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=zI(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 Xo(e){let t=()=>KI(e);return e.mutex?e.mutex.runExclusive(t):t()}async function KI(e){let t=await tp(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=JI(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 Pa({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 Pa({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 Pa({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 ep("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return ep("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 JI(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 Pa(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:XI(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 ep(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function XI(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 zI(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)||qf.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=qf.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}}function Ta(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function Ln(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function np(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function _a(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 rp(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function HI(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var Cr=class extends Error{constructor(t){let n=t.map(rp);super(HI(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function op(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof Cr?{routeId:e,message:n,diagnostics:t.diagnostics.map(rp)}:{routeId:e,message:n}}function Fa(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function ip(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"}import{computeSiteEditCompositionKey as zo,SiteEditCompositionContextSchema as WI,SiteEditCompositionSelectorSchema as GI}from"@vcp-dev/contracts";var Pe=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="SiteEditCompositionError"}};function sp(e,t){throw new Pe("INVALID_COMPOSITION",e,{value:t})}function Ho(e){let t=WI.safeParse(e);return t.success?t.data:sp("Invalid SiteEditCompositionContext.",e)}function ap(e){let t=[],n=new Map,r=new Map;for(let l of e.compositions){let u=Ho(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new Pe("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=zo(u);if(n.has(d))throw new Pe("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u});let p=r.get(l.entryFile);if(p)throw new Pe("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:p});let m={context:u,entryFile:l.entryFile,key:d};t.push(m),n.set(d,m),r.set(l.entryFile,d)}if(t.length===0)throw new Pe("INVALID_COMPOSITION","At least one composition must be registered.");let o=new Map;for(let l of e.initialDocumentVersions??[]){let u=Ho(l?.composition);if(!Number.isInteger(l?.version)||(l?.version??-1)<0)throw new Pe("INVALID_INITIAL_DOCUMENT_VERSION","Initial document version must be a non-negative integer.",{context:u,version:l?.version});let d=zo(u);if(!n.has(d))throw new Pe("UNKNOWN_COMPOSITION","Initial document version references an unregistered composition.",{context:u,key:d});if(o.has(d))throw new Pe("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=GI.safeParse(l);if(!u.success)return sp("Invalid SiteEditCompositionSelector.",l);let d=t.filter(({context:p})=>p.routeId===u.data.routeId&&(u.data.templateId===void 0?p.effectiveTemplateId===void 0:p.effectiveTemplateId===u.data.templateId));if(d.length===1)return d[0];throw d.length>1?new Pe("AMBIGUOUS_COMPOSITION","The composition selector matches multiple registered contexts.",{selector:u.data}):new Pe("UNKNOWN_COMPOSITION","The composition selector is not registered.",{selector:u.data})}function s(l){let u=Ho(l),d=zo(u),p=n.get(d);if(!p)throw new Pe("UNKNOWN_COMPOSITION","The composition context is not registered.",{context:u,key:d});return p}function a(l){let u=Ho(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new Pe("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=zo(u),p=n.get(d);if(p){if(p.entryFile===l.entryFile)return p;throw new Pe("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u})}let m=[...n.values()].find(S=>S.entryFile===l.entryFile);if(m)throw new Pe("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:m.context});let g={context:u,entryFile:l.entryFile,key:d};return t.push(g),n.set(d,g),g}function c(l){let u=n.get(l);if(!u)return;n.delete(l);let d=t.findIndex(p=>p.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))]}}var rv=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,ov=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],cp=32,lp=256;function iv(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var up={maxEntries:50,maxBytes:8*1024*1024};function sv(){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 Bo(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}}}function av(){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>up.maxEntries||cv(e)>up.maxBytes;)e.shift()}}function cv(e){return e.reduce((t,n)=>t+lv(n),0)}function lv(e){return dp(e.preSnapshots)+dp(e.postSnapshots)+uv(e.provenance)}function uv(e){return e?new TextEncoder().encode(JSON.stringify(e)).byteLength:0}function dp(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function fp(e,t){return{key:YI(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}}function dv(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=Ge(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}}var Yo=class extends Error{constructor(t){super(t.reason),this.result=t}},on=class extends Error{constructor(t){super(Fa(t)),this.failedRoutes=t}};function pp(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=Ge(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(Ge(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}var fv=/\.(?:[cm]?[jt]sx?)$/i,pv=/\.json$/i,mv=/\.(?:css|scss|sass)$/i,gv=/\.mdx$/i,hv=/\.ya?ml$/i;function yv(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 xv(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function Sv(e,t){let n=new Map;for(let r of t)n.set(r.path,r.operation==="delete"?{exists:!1}:{exists:!0,content:r.content});return{async readFile(r){let o=n.get(r);if(o){if(!o.exists)throw new Error(`Source file not found: ${r}`);return o.content}return e.readFile(r)},async writeFile(){throw new Error("Source edit preflight overlay is read-only.")},async deleteFile(){throw new Error("Source edit preflight overlay is read-only.")},async exists(r){let o=n.get(r);return o?o.exists:e.exists(r)},async getFileInfo(r){let o=n.get(r);return o?o.exists?{path:r,sizeBytes:Buffer.byteLength(o.content,"utf8")}:null:e.getFileInfo?.(r)??null},async listFiles(r={}){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let o=Sp(await e.listFiles(r)),i=new Map(o.files.map(a=>[a.path,a]));for(let[a,c]of n)if(bv(a,r.roots??[])){if(!c.exists){i.delete(a);continue}i.set(a,{path:a,sizeBytes:Buffer.byteLength(c.content,"utf8")})}let s=[...i.values()].sort((a,c)=>a.path.localeCompare(c.path));return o.truncated?{files:s,truncated:o.truncated}:s},getVersion(r){return e.getVersion(r)},bumpVersion(r){return e.getVersion(r)}}}function bv(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function Sp(e){return Array.isArray(e)?{files:e}:e}function Ev(e){if(!qI(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!==tv||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=QI(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(fv.test(e.path)){let t=ct({source:e.content,profile:Kt({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(pv.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${Fe(t)}`,details:{path:e.path}}}if(mv.test(e.path)){let t=mp({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(gv.test(e.path)){let t=mp({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(hv.test(e.path))try{nv(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${Fe(t)}`,details:{path:e.path}}}return{ok:!0}}function mp({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 p=e[d]??"",m=e[d+1]??"";if(n==="mdx"&&l&&e.startsWith("```",d)){c=!c;let g=e.indexOf(`
|
|
5
|
+
`,d);if(g===-1){l=!0;break}d=g,l=!0;continue}if(c){l=p===`
|
|
6
|
+
`||p==="\r";continue}if(s){p==="*"&&m==="/"&&(s=!1,d+=1),l=p===`
|
|
7
|
+
`||p==="\r";continue}if(a){p===`
|
|
8
|
+
`||p==="\r"?(a=!1,l=!0):l=!1;continue}if(o){if(i)i=!1;else if(p==="\\")i=!0;else if(p===o)o=null;else if(n==="css"&&(p===`
|
|
9
|
+
`||p==="\r"))return Bn(t,`Unterminated string literal in ${t}.`);l=p===`
|
|
10
|
+
`||p==="\r";continue}if(p==="/"&&m==="*"){s=!0,d+=1,l=!1;continue}if(n==="mdx"&&p==="/"&&m==="/"){a=!0,d+=1,l=!1;continue}if(p==="'"||p==='"'||n==="mdx"&&p==="`"){o=p,l=!1;continue}if(p==="{"||p==="("||p==="["){r.push({char:p,offset:d}),l=!1;continue}if(p==="}"||p===")"||p==="]"){let g=p==="}"?"{":p===")"?"(":"[",S=r.pop();if(!S||S.char!==g)return Bn(t,`Unexpected closing token "${p}" in ${t}.`);l=!1;continue}l=p===`
|
|
11
|
+
`||p==="\r"}if(s)return Bn(t,`Unterminated block comment in ${t}.`);if(o)return Bn(t,`Unterminated string literal in ${t}.`);if(c)return Bn(t,`Unterminated MDX code fence in ${t}.`);let u=r.at(-1);return u?Bn(t,`Unclosed token "${u.char}" in ${t}.`):{ok:!0}}function Bn(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function wr(e){let t="idle",n=e.fileSystem??sv(),r=gf(),o=ap({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?Yf(e.historyStore):av()),u=mf(n,{externalAdapters:e.externalAdapters}),d=new Map,p=new Set,m=0,g=e.historyStore?.recoveryRequired??!1,S=Aa(),C=B();function v(f){return(Wo.isAbsolute(f)?Wo.relative(e.projectRoot,f):f).replace(/\\/g,"/").replace(/^\.\//,"")}function P(f,y){let h=Wo.posix.dirname(f),I=y.replace(/\.(?:tsx?|jsx?)$/i,""),R=Wo.posix.relative(h,I);return R.startsWith(".")?R:`./${R}`}function w(f,y){return f.startLine===y.startLine&&f.startColumn===y.startColumn&&f.endLine===y.endLine&&f.endColumn===y.endColumn}async function B(){let f=e.historyStore;if(f)try{let y=await f.readTransactionJournal();if(!y)return;let h=await f.readIndex(),I=await Promise.all(y.files.map(async A=>await n.exists(A.path)?le(await n.readFile(A.path)):null));if(ip({journal:y,index:h,observedFileDigests:I})!=="ambiguous"){await f.clearTransactionJournal(y.transactionId);let A=await f.readStatus();A.recoveryRequired||(await f.cleanupTmp(),A=await f.readStatus()),g=A.recoveryRequired;return}await f.markRecoveryRequired(`Ambiguous transaction journal ${y.transactionId} at phase ${y.phase}`),g=!0}catch(y){g=!0,await f.markRecoveryRequired(`Transaction journal recovery failed: ${Fe(y)}`).catch(()=>{})}}function re(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let f of o.entries){let y=fp(f.context,f.entryFile);i.set(f.key,y),ne(y,y.dependencyFiles)}function ne(f,y){let h=new Set(y);N(f),f.dependencyFiles=h;for(let I of f.dependencyFiles){let R=s.get(I);R||(R=new Set,s.set(I,R)),R.add(f.key)}}function N(f){for(let y of f.dependencyFiles){let h=s.get(y);h&&(h.delete(f.key),h.size===0&&s.delete(y))}f.dependencyFiles.clear()}function X(f){let y=new Set;for(let h of f)for(let I of s.get(h)??[])y.add(I);return y}function M(f){for(let y of f)if(!s.has(y))return!1;return!0}async function D(f,y,h,I,R){let A=new Map,F=hd(R.values()),L=new Map,T=typeof n.exists=="function"?$=>n.exists($):async()=>!1;for(let[$,K]of f.elements){let me=y.nodes.get($);if(!me)continue;let Q=h.get(K.sourceFile)??I.get(K.sourceFile),Ie=new Map,Y=new Map,ge=new Map,_=[];for(let fe of K.textSegments){if(!Q){Ie.set(fe.index,null);continue}let Un=await yd({file:K.sourceFile,source:Q,segment:fe,readFile:Ze=>n.readFile(Ze),exists:T,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Ze,adapterId:Si,capabilities:bi})=>({sourceType:Ze,adapterId:Si,capabilities:bi})),functionCallContracts:e.functionCallContracts,fileCache:F}),Re=await Xs({file:K.sourceFile,source:Q,target:{kind:"text-segment",segment:fe},readFile:Ze=>n.readFile(Ze),exists:T,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Ze,adapterId:Si,capabilities:bi})=>({sourceType:Ze,adapterId:Si,capabilities:bi})),functionCallContracts:e.functionCallContracts,fileCache:F}),pn=yv(Un);Ie.set(fe.index,pn),Y.set(fe.index,Un),ge.set(fe.index,Re),_.push({editable:fe.editable,source:pn})}let j=new Map;if(Q)for(let fe of K.attributes??[]){let Un=await xd({file:K.sourceFile,source:Q,sourceRange:fe.sourceRange,expression:fe.source?.expression??fe.value,sourceInfo:fe.source,readFile:Re=>n.readFile(Re),exists:T,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Re,adapterId:pn,capabilities:Ze})=>({sourceType:Re,adapterId:pn,capabilities:Ze})),functionCallContracts:e.functionCallContracts,fileCache:F});j.set(fe.name,Un)}let z=Hl(xv(me.writeTarget),_),oe=Ql({key:$,element:K,graph:f,provenances:ge}),Se=nu(K),Ke=ru(K),dn=ou(K),fn=Q?await zd({element:K,graph:f,file:K.sourceFile,source:Q,readFile:fe=>n.readFile(fe),exists:T,fileCache:L}):void 0,$t=f.regions.find(fe=>fe.kind==="conditional-region"&&fe.childKeys.includes($)),Te,Vn=$t?.sourceCandidates?.[0];if(Q&&$t&&Vn?.kind==="conditional-branch"){let fe=await Xs({file:K.sourceFile,source:Q,target:{kind:"conditional-branch",candidate:Vn},readFile:Re=>n.readFile(Re),exists:T,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Re,adapterId:pn,capabilities:Ze})=>({sourceType:Re,adapterId:pn,capabilities:Ze})),functionCallContracts:e.functionCallContracts,fileCache:F});Te={currentBranch:$t.childKeys.indexOf($)<=0?"then":"else",availableBranches:$t.childKeys.length>1?["then","else"]:["then"],conditionExpression:Vn.conditionExpression,provenance:{finalSource:fe.finalSource?{kind:fe.finalSource.kind,file:fe.finalSource.file,displayPath:fe.finalSource.displayPath}:null,chain:fe.chain.map(Re=>({kind:Re.kind,file:Re.file,displayName:Re.displayName,canEditHere:Re.canEditHere})),confidence:fe.confidence,editMode:fe.editMode,diagnostics:fe.diagnostics.map(Re=>({code:Re.code,message:Re.message}))}}}A.set($,{textSources:Ie,textTargets:Y,elementPropertyTargets:j,provenances:ge,writeTarget:z,componentSemantic:oe,contentModel:Se,mediaModel:Ke,styleSource:dn,conditional:Te,dynamicData:fn})}return A}function Z(f){return typeof n.getVersion=="function"?n.getVersion(f):0}function te(f,y){let h=o.initialVersions.get(f.key)??0;for(let I of y.values())h=Math.max(h,I);return Math.max(h,f.graph?.version??0)}function he(f){return i.get(f)?.graph?.version??o.initialVersions.get(f)??0}function W(f){try{return he(o.resolveSelector(f.composition).key)}catch{return 0}}async function q(f,y,h={}){let I=i.get(f);if(!I)return null;let R=h.sourceCache??Ta(d,[]),A=await xe(I.entryFile),{graph:F,allSources:L,diagnostics:T,parsedModules:$,entryModule:K}=await Kc(I.entryFile,y,Te=>n.readFile(Te),typeof n.exists=="function"?Te=>n.exists(Te):async()=>!1,{additionalEntries:A,version:I.graph?.version??1});if(T.length>0)throw new Cr(T);let me=new Map;for(let Te of L.keys())me.set(Te,Z(Te));let Q=Math.max(te(I,me),h.minimumVersion??0);h.changed&&Q<=(I.graph?.version??0)&&(Q=(I.graph?.version??0)+1),F.version=Q;for(let[Te,Vn]of L)_a(R,Te,Vn,lp);let Ie=await Et(I.composition,I.entryFile,L,R);F.routeId=I.routeId,F.composition=I.composition;let Y=Jc(F),ge=zc(Y,F),_=await D(F,Y,L,R,$),j=om(F,ge,_),z=rm(_),oe=Fv(Ul(F,Y,ge,{canUpdateTextByKey:j,dynamicDataSummaryByKey:z}),F,_),Se=Ml({route:I.routeId,composition:I.composition,entryFile:I.entryFile,version:Q,source:y,ast:K?.ast}),Ke=Ol(Se);Se.ok&&vv(oe,F,Se.projection);let dn={...oe,composition:I.composition,...Ie?{styleContext:Ie}:{},pageComposition:Ke},fn=new Set([I.entryFile,...L.keys()]);if(Ie){fn.add(Ie.entryCss.path);for(let Te of Ie.stylesheets)fn.add(Te.path)}let $t={...I,dependencyFiles:fn,graph:F,topology:Y,capabilities:ge,document:dn,pageComposition:Ke,pageCompositionProjection:Se.projection,pagePlacementByKey:Se.ok?Se.projection.placementByKey:null,pagePlacementUnitByKey:Se.ok?Se.projection.placementUnitByKey:null,pageUnitByKey:Se.ok?Se.projection.unitByKey:null,pagePlacementsByUnitKey:Se.ok?Se.projection.placementsByUnitKey:null,documentIndex:dv(dn),detailProjections:_,fileVersions:me,styleContext:Ie};if(h.publish===!1)return $t;Ln(d,R);for(let Te of R.keys())p.delete(Te);return ne(I,fn),Object.assign(I,$t),I}async function xe(f){let y=[];for(let h of wv(f))typeof n.exists=="function"&&await n.exists(h)&&y.push({file:h,source:await n.readFile(h)});return y}async function Et(f,y,h,I){let R=[];for(let[$,K]of h){if(Oa($)){R.push($);continue}for(let me of Pv(K)){let Q=yp($,me);Q&&R.push(Q)}}if(!R.length){for(let $ of Nv(y))if(await pc($)){R.push($);break}}let A=new Map,F=Ip(R).slice(0,cp);for(;F.length>0&&A.size<cp;){let $=F.shift();if(A.has($)||!Oa($))continue;let K=await It($,I);if(K!==null){A.set($,{path:$,content:K});for(let me of Av(K)){let Q=yp($,me);Q&&!A.has(Q)&&!F.includes(Q)&&F.push(Q)}}}let L=[...A.values()].map($=>({...$,hash:le($.content)})),T=L[0];return T?{composition:f,revision:le(JSON.stringify(L.map(({path:$,hash:K})=>({path:$,hash:K})))),entryCss:T,stylesheets:L.slice(1)}:null}async function It(f,y){let h=y.get(f);if(h!==void 0)return h;if(!await pc(f))return null;let I=await n.readFile(f);return _a(y,f,I,lp),I}async function pc(f){return typeof n.exists=="function"?n.exists(f):!1}function rm(f){let y=new Map;for(let[h,I]of f)I.dynamicData?.bindings.length&&y.set(h,rf(I.dynamicData.bindings));return y}function om(f,y,h){let I=new Map;for(let[R,A]of f.elements){if(!y.get(R)?.canUpdateText){I.set(R,!1);continue}let L=h.get(R),T=A.textSegments.some($=>{if(!$.editable)return!1;let K=L?.provenances.get($.index)??null;return!K||im(K)});I.set(R,T)}return I}function im(f){return f.editMode==="direct"||f.editMode==="proxy"||f.editMode==="upstream"}async function Lr(f,y={}){let h=[...new Set(f)],I=y.affectedCompositionKeys!==void 0,R=I?new Set(y.affectedCompositionKeys):X(h);if(!I&&(R.size===0||!M(h)))for(let T of i.values())mc(T,h)&&R.add(T.key);let A=!I&&R.size===0&&h.some(hp),F=y.publish===!1?Ta(d,h):void 0,L={rebuiltRoutes:[],failedRoutes:[],...y.publish===!1?{candidateRouteStates:[],candidateSourceCache:F}:{}};for(let T of i.values())if(!(y.excludedCompositionKeys?.has(T.key)||!(R.has(T.key)||A)))try{let K=!!T.graph,me=await n.readFile(T.entryFile),Q=await q(T.key,me,{...y,...F?{sourceCache:F}:{}});Q?.graph&&(L.rebuiltRoutes.push({documentChanged:K,composition:T.composition,routeId:T.routeId,version:Q.graph.version}),L.candidateRouteStates?.push({composition:T.composition,key:T.key,routeId:T.routeId,state:Q}))}catch(K){L.failedRoutes.push({...op(T.routeId,K),composition:T.composition})}return L}function cn(f){let y=[...new Set(f)],h=X(y);if(h.size>0&&M(y))return[...h];for(let I of i.values())mc(I,y)&&h.add(I.key);return[...h]}function sm(f){let y=new Set(cn(f));return o.entries.filter(h=>y.has(h.key)).map(h=>h.context)}function am(f){return[...new Set(cn(f))].sort((h,I)=>h<I?-1:h>I?1:0).map(h=>o.getByKey(h)?.context).filter(h=>h!==void 0)}function cm(f,y){let h=new Set(cn(y)),I=f.provenance?.affectedCompositions??[];if(I.length===0)return h;let R=new Set(I.map(A=>o.resolveContext(A).key));if(R.size!==h.size||[...R].some(A=>!h.has(A)))throw new Error("History provenance does not match the affected composition index.");return R}function lm(f,y){let h=f.composition??f.provenance?.initiatingComposition;if(h){let A=o.resolveContext(h);return{context:A.context,key:A.key}}let I=[...new Set(cn(y))];if(I.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${I.length}).`);let R=o.getByKey(I[0]);if(!R)throw new Error("Legacy history entry references an unknown affected composition.");return{context:R.context,key:R.key}}function mi(f,y){r.emit({type:"operation-completed",composition:f.composition,result:f});for(let{composition:h,version:I}of y.rebuiltRoutes)r.emit({type:"document-changed",composition:h,version:I});for(let{composition:h,message:I}of y.failedRoutes)r.emit({type:"graph-error",composition:h,message:I})}function mc(f,y){return y.some(h=>f.dependencyFiles.has(h)||f.entryFile===h||f.graph?.fileIndex.has(h))}function gc(f){for(let y of f)a.add(y);c||re()||(c=(async()=>{t="building";let y=!1;try{for(;a.size>0;){if(re())return;await um();let h=[...a];a.clear();let I=await hc(h);if(I.length===0)continue;let R=cn(I);for(let L of R){let T=i.get(L)?.composition;T&&r.emit({type:"graph-invalidated",composition:T})}let{rebuiltRoutes:A,failedRoutes:F}=await Lr(I,{changed:!0});for(let{documentChanged:L,composition:T,version:$}of A)r.emit({type:"graph-ready",composition:T,version:$}),L&&r.emit({type:"document-changed",composition:T,version:$});for(let{composition:L,message:T}of F)y=!0,r.emit({type:"graph-error",composition:L,message:T})}}finally{c=null,t!=="disposed"&&(t=!y&&[...i.values()].some(h=>h.graph)?"ready":"idle"),a.size>0&&gc([])}})())}async function um(){for(;m>0;)await new Promise(f=>setTimeout(f,0))}async function hc(f){let y=[];for(let h of new Set(f)){let I=d.get(h);if(I===void 0){if(p.has(h)&&!await n.exists(h))continue;p.delete(h),y.push(h);continue}try{await n.readFile(h)!==I&&(p.delete(h),y.push(h))}catch(R){if(!Iv(R))try{if(await n.exists(h))continue}catch{continue}p.add(h),y.push(h)}}return y}function yc(f){np(d,f);for(let y of f)y.exists===!1?p.add(y.file):p.delete(y.file)}function xc(f){p.clear();for(let y of f)p.add(y)}async function Sc(f){let y=await hc(f);if(y.length===0)return;let h=cn(y);for(let A of h){let F=i.get(A)?.composition;F&&r.emit({type:"graph-invalidated",composition:F})}let{rebuiltRoutes:I,failedRoutes:R}=await Lr(y,{changed:!0});for(let{documentChanged:A,composition:F,version:L}of I)r.emit({type:"graph-ready",composition:F,version:L}),A&&r.emit({type:"document-changed",composition:F,version:L});for(let{composition:A,message:F}of R)r.emit({type:"graph-error",composition:A,message:F})}async function dm(f,y){let h=$n(f,y);if(!h?.graph)return;let I=Ge(f)??f,R=h.graph.elements.get(I);R&&await Sc([R.sourceFile])}async function bc(f){let y=new Set;if(f.target.kind==="node"){let h=$n(f.target.key,f.composition),I=Ge(f.target.key)??f.target.key,R=h?.graph?.elements.get(I);R&&y.add(R.sourceFile)}else if(f.target.kind==="route"){let h=i.get(o.resolveSelector(f.target.composition).key);h&&y.add(h.entryFile)}else if(f.target.kind==="page-unit"){let h=i.get(o.resolveSelector(f.target.composition).key);h&&y.add(h.entryFile)}else if(f.target.kind==="source-file")y.add(f.target.path);else if(f.target.kind==="source-batch")for(let h of f.target.paths)y.add(h);await Sc(y)}async function fm(f){if(f.params.kind!=="source-edit")return gi(f,"invalid-params","source-edit requires source-edit params");for(let y of f.params.edits){let h=Ev(y);if(!h.ok)return gi(f,h.errorCode,h.message,h.details)}m+=1;try{let y=await xm(f.params.edits);if(!y.ok)return gi(f,y.errorCode,y.message,y.details);await bc(f);let h={operationId:f.id,kind:"source-edit",target:f.target,documentVersion:f.documentVersion,conflictPolicy:f.params.conflictPolicy,edits:f.params.edits.map(I=>I.operation==="delete"?{operation:"delete",file:I.path,baseContentHash:I.baseContentHash??null}:{operation:"upsert",file:I.path,baseContentHash:I.baseContentHash??null,content:I.content})};return await un({request:f,filePlan:h})}catch(y){return{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:W(f),error:{code:O.INTERNAL_ERROR,message:Fe(y)}}}finally{m-=1}}async function pm(f){if(f.target.kind!=="project"||f.params.kind!=="insert-page-resource")return ee(f,O.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");m+=1;try{let y=await ka({files:[...f.params.artifact.components.flatMap(I=>I.materialization.files.map(R=>({path:R.pathTemplate,content:R.content}))),...f.params.artifact.pages.flatMap(I=>I.materialization.files.map(R=>({path:R.pathTemplate,content:R.content})))],exists:I=>n.exists(I),readFile:I=>n.readFile(I)});if(!y.ok)return ee(f,O.MATERIALIZATION_REJECTED,y.message);let h=await Ia({artifact:f.params.artifact,exists:I=>n.exists(I)});return h.ok?await un({request:f,filePlan:{operationId:f.id,kind:"source-edit",target:f.target,documentVersion:f.documentVersion,conflictPolicy:"overwrite",edits:h.files},output:{kind:"insert-page-resource",package_instance_id:h.packageInstanceId,pages:h.pages},historyPolicy:"none"}):ee(f,h.code==="MATERIALIZATION_CONFLICT"?O.MATERIALIZATION_CONFLICT:O.MATERIALIZATION_REJECTED,h.message,h.path?{path:h.path}:void 0)}catch(y){return ee(f,O.INTERNAL_ERROR,Fe(y))}finally{m-=1}}async function mm(f){if(f.target.kind!=="project"||f.params.kind!=="delete-page-source")return ee(f,O.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return ee(f,O.PLAN_FAILED,"Complete project file listing is required for page deletion.");m+=1;try{let y=Sp(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(y.truncated)return ee(f,O.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:y.truncated.reasons});let h=y.files.filter(({path:F})=>/\.(?:tsx?|jsx?)$/.test(F)),I=Object.fromEntries(await Promise.all(h.map(async({path:F})=>[F,await n.readFile(F)]))),R=Jf({expectedUrlPath:f.params.expectedUrlPath,files:I});if(!R.ok)return ee(f,R.code==="HOME_PAGE_LOCKED"?O.HOME_PAGE_LOCKED:R.code==="ROUTE_NOT_FOUND"?O.ROUTE_NOT_FOUND:O.PLAN_FAILED,R.message);let A=await Promise.all(R.edits.map(async F=>({...F,baseContentHash:le(await n.readFile(F.file))})));return un({request:f,filePlan:{operationId:f.id,kind:"source-edit",target:f.target,documentVersion:f.documentVersion,conflictPolicy:"compare-and-swap",edits:A},output:{kind:"delete-page-source",deleted_files:R.deletedFiles,updated_files:R.updatedFiles,preserved_shared_files:R.preservedSharedFiles,warnings:R.warnings},historyPolicy:"none"})}catch(y){return ee(f,O.INTERNAL_ERROR,Fe(y))}finally{m-=1}}async function gm(f,y){if(f.kind!=="insert-child"||f.params.kind!=="insert-child")return ee(f,O.UNSUPPORTED_OPERATION,"Only page-unit insert-child is currently supported by the page composition transaction.");if(!("kind"in f.params.position)||f.params.position.kind!=="page-composition")return ee(f,O.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(f.params.position.documentVersion!==f.documentVersion)return ee(f,O.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.");let h=y.document,I=y.pageCompositionProjection;if(!h||h.pageComposition?.status!=="supported"||!I||I.status!=="supported")return ee(f,O.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(f.documentVersion!==h.version||I.documentVersion!==h.version)return ee(f,O.VERSION_STALE,`Document version ${f.documentVersion} is stale (current: ${h.version}).`);let R=f.params.node.kind==="component-call"?f.params.node.materialization:void 0;if(!R)return ee(f,O.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let A=f.params.position,F=await ka({files:R.files.map(T=>({path:T.pathTemplate,content:T.content})),exists:T=>n.exists(T),readFile:T=>n.readFile(T)});if(!F.ok)return ee(f,O.MATERIALIZATION_REJECTED,F.message);let L=await kf({manifest:R,generatedRoot:"components/site/generated",controlledFiles:R.files.map(T=>({pathTemplate:T.pathTemplate})),exists:T=>n.exists(T),commit:async T=>{let $=await n.readFile(y.entryFile),K=y.document,me=y.pageCompositionProjection;if(!K||K.pageComposition?.status!=="supported"||K.version!==f.documentVersion||!me||me.status!=="supported"||me.documentVersion!==K.version)return{ok:!0,data:ee(f,O.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let Q=T.entry.path,Ie=Cm(T.instanceName),Y=es({routeId:y.routeId,entryFile:y.entryFile,currentDocumentVersion:K.version,expectedDocumentVersion:f.documentVersion,source:$,projection:me,placementKey:A.placementKey,component:{source:Q,exportName:T.entry.export.kind==="default"?"default":T.entry.export.name,localName:Ie}});if(!Y.ok)return{ok:!0,data:ee(f,Pc(Y.error.code),Y.error.message,{diagnostics:Y.error.diagnostics})};let ge=Y.plan.returnStep?Pl({source:$,jsx:Y.plan.returnStep.node.jsx,placement:Y.plan.returnStep.placement,...Y.plan.returnStep.replaceOriginal?{replaceOriginal:!0}:{}}):Y.plan.insertStep?.parentLocator?kn({source:$,locator:Y.plan.insertStep.parentLocator,node:Y.plan.insertStep.node,placement:Y.plan.insertStep.placement,...Y.plan.insertStep.anchorLocator?{anchorLocator:Y.plan.insertStep.anchorLocator}:{}}):{ok:!1,source:$,diagnostic:{code:"unsupported-syntax",message:"Route composition rewrite has no insertion step."}};if(!ge.ok)return{ok:!0,data:ee(f,O.AST_PARSE_ERROR,ge.diagnostic.message)};let _=wn({source:ge.source,moduleSpecifier:Y.plan.importStep.moduleSpecifier,imports:Y.plan.importStep.imports});if(!_.ok)return{ok:!0,data:ee(f,O.AST_PARSE_ERROR,_.diagnostic.message)};let j=T.files.map(oe=>({operation:"create-only",file:oe.path,content:oe.content})),z=[{operation:"upsert",file:y.entryFile,content:_.source,baseContentHash:le($)},...j];m+=1;try{let oe=await un({request:f,filePlan:{operationId:f.id,kind:"source-edit",target:{kind:"source-file",path:y.entryFile},documentVersion:f.documentVersion,conflictPolicy:"compare-and-swap",edits:z}});return!oe.ok&&oe.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:oe.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:oe}}finally{m-=1}}});return L.ok?L.data:ee(f,O.VERSION_STALE,L.error.message,{materializationCode:L.error.code})}async function hm(f,y){if(f.kind!=="move-node"&&f.kind!=="remove-node")return ee(f,O.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let h=y.document,I=y.pageCompositionProjection;if(!h||h.pageComposition?.status!=="supported"||!I||I.status!=="supported")return ee(f,O.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(f.documentVersion!==h.version||I.documentVersion!==h.version)return ee(f,O.VERSION_STALE,`Document version ${f.documentVersion} is stale (current: ${h.version}).`);let R=await n.readFile(y.entryFile),A=Al({routeId:y.routeId,composition:y.composition,entryFile:y.entryFile,currentDocumentVersion:h.version,expectedDocumentVersion:f.documentVersion,source:R,projection:I,placementUnitKey:f.target.placementUnitKey,operation:f.kind,targetPlacement:f.kind==="move-node"&&f.params.kind==="move-node"&&"kind"in f.params.target&&f.params.target.kind==="page-composition"?f.params.target:void 0});if(!A.ok)return ee(f,Pc(A.error.code),A.error.message,{diagnostics:A.error.diagnostics});let F=A.plan.rewriteStep.kind==="move-node"?Rn({source:R,locator:A.plan.rewriteStep.locator,targetParentLocator:A.plan.rewriteStep.targetParentLocator,placement:A.plan.rewriteStep.placement,...A.plan.rewriteStep.anchorLocator?{anchorLocator:A.plan.rewriteStep.anchorLocator}:{}}):In({source:R,locator:A.plan.rewriteStep.locator});if(!F.ok)return ee(f,O.AST_PARSE_ERROR,F.diagnostic.message);let L=F.source,T=[];if(f.kind==="remove-node"){let K=await ym({routeState:y,placementUnitKey:f.target.placementUnitKey,source:R,mutatedSource:L});L=K.source,T=await Promise.all(K.files.map(async me=>({operation:"delete",file:me,baseContentHash:le(await n.readFile(me))})))}let $=[{operation:"upsert",file:y.entryFile,content:L,baseContentHash:le(R)},...T];m+=1;try{return await un({request:f,filePlan:{operationId:f.id,kind:"source-edit",target:{kind:"source-file",path:y.entryFile},documentVersion:f.documentVersion,conflictPolicy:"compare-and-swap",edits:$}})}finally{m-=1}}async function ym(f){let y={source:f.mutatedSource,files:[]},h=f.routeState.graph,I=f.routeState.pageCompositionProjection;if(!h||!I||I.status!=="supported"||!n.listFiles)return y;let A=I.placementUnitByKey.get(f.placementUnitKey)?.sourceRange;if(!A)return y;let F=[...h.elements.values()].find(j=>j.sourceFile===f.routeState.entryFile&&j.importedFrom&&w(j.sourceRange,A));if(!F?.importedFrom||!F.exportName)return y;let L=v(F.importedFrom),T="components/site/generated/";if(!L.startsWith(T))return y;let $=L.slice(T.length).split("/")[0];if(!$||!/-[0-9a-f]{8}$/i.test($))return y;let K=`${T}${$}`;if([...h.elements.values()].filter(j=>j.sourceFile===f.routeState.entryFile&&v(j.importedFrom??"")===L).length!==1)return y;let Q=await n.listFiles({maxFiles:5e3,maxDepth:32}),Ie=Array.isArray(Q)?Q:Q.files;if(!Array.isArray(Q)&&Q.truncated)return y;let Y=Ie.map(({path:j})=>j).filter(j=>j===K||j.startsWith(`${K}/`));if(Y.length===0||!Y.includes(L))return y;for(let{path:j}of Ie)if(!(j===f.routeState.entryFile||j===K||j.startsWith(`${K}/`)))try{if((await n.readFile(j)).includes($))return y}catch{return y}let ge=P(f.routeState.entryFile,L),_=Nn({source:f.mutatedSource,moduleSpecifier:ge,imports:F.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:F.exportName}]});return _.ok?{source:_.source,files:Y.sort((j,z)=>j.localeCompare(z))}:y}async function xm(f){if(n.getFileInfo){for(let R of f)if(await n.exists(R.path)&&await n.getFileInfo(R.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${R.path}`,details:{path:R.path}}}let y=Sm(f);if(y.length===0)return{ok:!0};let h=Sv(n,f),I=wr({projectRoot:e.projectRoot,fileSystem:h,compositions:[...i.values()].map(R=>({context:R.composition,entryFile:R.entryFile})),externalAdapters:e.externalAdapters,externalSourceResolvers:e.externalSourceResolvers,functionCallContracts:e.functionCallContracts,dev:e.dev});try{for(let R of y){let A=i.get(R)?.composition;if(!A)continue;let F={routeId:A.routeId,...A.effectiveTemplateId!==void 0?{templateId:A.effectiveTemplateId}:{}};await I.initializeComposition(F),I.getDocument(F)}}catch(R){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${Fe(R)}`,details:{compositionKeys:y}}}finally{I.dispose()}return{ok:!0}}function Sm(f){return f.map(h=>h.path).some(hp)?[...i.keys()]:[]}function gi(f,y,h,I){let R=Rr(y);return{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:W(f),error:{code:R,message:h,...I?{details:I}:{}}}}async function hi(f){let y=[];for(let h of new Set(f))y.push(await bm(h));return y}async function bm(f){if(!(typeof n.exists=="function"?await n.exists(f):!0))return{file:f,content:"",version:Math.max(0,Z(f)),exists:!1};let h=await n.readFile(f);return{file:f,content:h,version:Math.max(1,Z(f)),exists:!0,sha256:le(h)}}async function Ec(f,y,h,I){if(!e.historyStore)return null;let R=new Map(y.map(L=>[L.file,L])),A=new Map(h.map(L=>[L.file,L])),F=[...new Set([...R.keys(),...A.keys()])].sort().map(L=>{let T=R.get(L),$=A.get(L);return{path:L,preDigest:T?.exists===!1||!T?null:le(T.content),postDigest:$?.exists===!1||!$?null:le($.content)}});return{schemaVersion:2,transactionId:`${f}:${I.expectedIndexDigest}`,operationId:f,phase:"prepared",historyTransition:I,files:F}}async function Ic(f){return!f||!e.historyStore||await e.historyStore.writeTransactionJournal(f),f}async function ln(f){f&&e.historyStore&&await e.historyStore.clearTransactionJournal(f.transactionId)}async function yi(f,y){let h=[];try{for(let I of f)await vc(I),typeof n.bumpVersion=="function"&&n.bumpVersion(I.file),h.push(I.file)}catch(I){let R=await Em(y.filter(A=>h.includes(A.file)));return R.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${Fe(I)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${R.failedFiles.join(", ")}: ${Fe(I)}`,rolledBack:!1}}return{ok:!0,snapshots:f.map(Im)}}async function vc(f){if(f.exists===!1){await n.deleteFile(f.file);return}await n.writeFile(f.file,f.content)}async function Em(f){let y=[];for(let h of f)try{await vc(h),typeof n.bumpVersion=="function"&&n.bumpVersion(h.file)}catch{y.push(h.file)}return y.length===0?{ok:!0}:{ok:!1,failedFiles:y}}function Im(f){let y=f.exists!==!1;return{file:f.file,content:y?f.content:"",version:f.version,exists:y,...y?{sha256:le(f.content)}:{}}}async function un(f){return S.runExclusive(()=>vm(f))}async function vm(f){let y=f.filePlan.edits.map(_=>_.file),h=o.resolveSelector(f.request.composition).context,I=f.historyPolicy==="none"?void 0:{initiatingComposition:h,affectedCompositions:am(y)},R=await hi(y),A=new Map(R.filter(_=>_.exists!==!1).map(_=>[_.file,_.content])),F=Cc(),L=new Map(d),T=new Set(p),$=new Set([...i.values()].filter(_=>f.filePlan.edits.some(j=>j.operation==="delete"&&j.file===_.entryFile)).map(_=>_.key)),K=f.filePlan.edits.map(_=>_.operation==="delete"?{file:_.file,content:"",version:0,exists:!1}:{file:_.file,content:_.content,version:0,exists:!0,sha256:le(_.content)}),me={operationId:f.filePlan.operationId,intents:f.filePlan.edits.map(_=>_.operation==="delete"?{kind:"delete",path:_.file}:{kind:_.operation==="create-only"?"create-only":"upsert",path:_.file,content:_.content})},Q=null,Ie=!1,Y=await Xo({overlay:A,exists:_=>n.exists(_),plan:me,buildCandidate:async({plan:_})=>({plan:_}),prepareHistory:async()=>{let _=f.historyPolicy==="none"?null:await l.prepareAppend({composition:o.resolveSelector(f.request.composition).context,operationId:f.request.id,kind:f.request.kind,target:f.request.target,preSnapshots:R,postSnapshots:K,...f.selectionRef?{selectionRef:f.selectionRef}:{},...f.output?{output:f.output}:{},...I?{provenance:I}:{}}),j=_?.historyTransition?_.historyTransition:e.historyStore?iv(await e.historyStore.readIndex()):null;if(e.historyStore&&!j)throw new Error("Durable history did not provide an exact index transition.");return Q=await Ec(f.request.id,R,K,j),Q=await Ic(Q),{history:_,historyTransition:j}},reverify:async()=>{},writeCandidate:async()=>{let _=await u.executeFilePlan(f.filePlan);if(!_.ok)throw new Yo(_);return{postSnapshots:await hi(_.affectedFiles),affectedFiles:_.affectedFiles,internalResultVersion:_.resultVersion}},validateCandidate:async({candidate:_,receipt:j})=>{let z=await Lr(j.affectedFiles,{changed:!0,minimumVersion:j.internalResultVersion,publish:!1,excludedCompositionKeys:$});if(z.failedRoutes.length>0)throw new on(z.failedRoutes);let oe=Rc(F,z.candidateRouteStates??[]),Se=Math.max(j.internalResultVersion,...z.rebuiltRoutes.map(Ke=>Ke.version));return{..._,rebuild:z,routeSnapshots:oe,resultVersion:Se,...pp(f.selectionRef,oe.map(Ke=>Ke.state.document))?{selectionRef:pp(f.selectionRef,oe.map(Ke=>Ke.state.document))}:{}}},publishCandidate:async({candidate:_,history:j,receipt:z})=>{j?.history&&(await l.publishPrepared(j.history),Ie=!0);let oe=_.resultVersion??z.internalResultVersion;return{composition:o.resolveSelector(f.request.composition).context,requestId:f.request.id,kind:f.request.kind,target:f.request.target,ok:!0,resultVersion:oe,affectedFiles:z.affectedFiles,...f.output?{output:f.output}:{},..._.selectionRef?{selectionRef:_.selectionRef}:{}}},swapCandidate:({candidate:_,receipt:j})=>{_.routeSnapshots&&Br(_.routeSnapshots),_.rebuild?.candidateSourceCache&&Ln(d,_.rebuild.candidateSourceCache),yc(j.postSnapshots)},finalizeCandidate:async()=>{await ln(Q);for(let _ of $)i.delete(_)},emitCommitted:({candidate:_,published:j})=>{mi(j,_.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:_,receipt:j})=>{if(Ie)throw new Error("history was published before transaction finalization failed");if(j){let z=await yi(R,j.postSnapshots);if(!z.ok)throw new Error(z.reason)}Br(F),Ln(d,L),xc(T),_?.history&&await l.discardPrepared?.(_.history),await ln(Q)}});if(Y.ok)return Y.published;if(Y.stage==="precheck"||Y.stage==="build")try{await ln(Q)}catch(_){let j=await jr(Fe(_));return ee(f.request,j,"Unable to clear an uncommitted transaction journal.")}if(Y.recoveryRequired){let _=await jr(Y.reason);return ee(f.request,_===O.RECOVERY_PERSIST_FAILED?_:O.ROLLBACK_FAILED,Y.reason)}let ge=Y.error;return ge instanceof Yo?{...ee(f.request,Rr(ge.result.errorCode),ge.result.reason),...ge.result.affectedFiles?{affectedFiles:ge.result.affectedFiles}:{}}:ge instanceof on?ee(f.request,O.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${Fa(ge.failedRoutes)}`,{failedRoutes:ge.failedRoutes}):ee(f.request,Nc(Y.stage),Fe(ge))}async function kc(f){return S.runExclusive(async()=>{let y=f==="undo"?await l.prepareUndo():await l.prepareRedo();return y?km(f,y):{composition:o.entries[0].context,requestId:f,kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:o.initialVersions.get(o.entries[0].key)??0,error:{code:O.INTERNAL_ERROR,message:f==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function km(f,y){let h=y.entry,I=f==="undo"?h.preSnapshots:h.postSnapshots,R=f==="undo"?h.postSnapshots:h.preSnapshots,A=I.map(z=>z.file),{context:F,key:L}=lm(h,A),T=await hi(A),$=new Map(T.filter(z=>z.exists!==!1).map(z=>[z.file,z.content])),K=he(L),me=Cc(),Q=new Map(d),Ie=new Set(p),Y=null,ge=!1,_,j=await Xo({overlay:$,plan:{operationId:`${f}:${h.operationId}`,intents:I.map(z=>z.exists===!1?{kind:"delete",path:z.file}:{kind:"upsert",path:z.file,content:z.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(Y=await Ec(`${f}:${h.operationId}`,T,I,y.historyTransition),Y=await Ic(Y),y),reverify:async()=>{},writeCandidate:async()=>{let z=await yi(I,R);if(!z.ok)throw new Error(z.reason);return{snapshots:z.snapshots}},validateCandidate:async({candidate:z})=>{_=cm(h,A);let oe=await Lr(A,{changed:!0,minimumVersion:K+1,publish:!1,affectedCompositionKeys:_});if(oe.failedRoutes.length>0)throw new on(oe.failedRoutes);let Se=Rc(me,oe.candidateRouteStates??[]),Ke=Math.max(K+1,...oe.rebuiltRoutes.map(dn=>dn.version));return{...z,rebuild:oe,routeSnapshots:Se,resultVersion:Ke}},publishCandidate:async({candidate:z,history:oe})=>{if(!oe)throw new Error("history cursor intent is missing");await l.publishPrepared(oe),ge=!0;let Se=z.resultVersion??K+1;return{composition:F,requestId:f,kind:h.kind,target:h.target,ok:!0,resultVersion:Se,affectedFiles:A,...h.output?{output:h.output}:{}}},swapCandidate:({candidate:z,receipt:oe})=>{z.routeSnapshots&&Br(z.routeSnapshots),z.rebuild?.candidateSourceCache&&Ln(d,z.rebuild.candidateSourceCache),yc(oe.snapshots)},finalizeCandidate:async()=>{await ln(Y)},emitCommitted:({candidate:z,published:oe})=>mi(oe,z.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:z,receipt:oe})=>{if(ge)throw new Error("history cursor was published before transaction finalization failed");if(oe){let Se=await yi(R,oe.snapshots);if(!Se.ok)throw new Error(Se.reason)}Br(me),Ln(d,Q),xc(Ie),z&&await l.discardPrepared?.(z),await ln(Y)}});if(j.ok)return j.published;if(j.stage==="precheck"||j.stage==="build")try{await ln(Y)}catch(z){let oe=await jr(Fe(z));return{composition:F,requestId:f,kind:h.kind,target:h.target,ok:!1,resultVersion:K,error:{code:oe,message:"Unable to clear an uncommitted transaction journal."}}}if(j.recoveryRequired){let z=await jr(j.reason);return{composition:F,requestId:f,kind:h.kind,target:h.target,ok:!1,resultVersion:K,affectedFiles:A,error:{code:z===O.RECOVERY_PERSIST_FAILED?z:O.ROLLBACK_FAILED,message:j.reason}}}return{composition:F,requestId:f,kind:h.kind,target:h.target,ok:!1,resultVersion:K,affectedFiles:A,error:{code:j.error instanceof on?O.ROUTE_REBUILD_FAILED:Nc(j.stage),message:Fe(j.error),...j.error instanceof on?{details:{failedRoutes:j.error.failedRoutes}}:{}}}}function Cc(){return[...i.values()].map(f=>({composition:f.composition,key:f.key,routeId:f.routeId,state:{...f,dependencyFiles:new Set(f.dependencyFiles),fileVersions:new Map(f.fileVersions)}}))}function Rc(f,y){let h=new Map(f.map(I=>[I.key,I]));for(let I of y)h.set(I.key,I);return[...h.values()]}function Br(f){for(let y of i.values())N(y);for(let y of f){let h={...y.state,dependencyFiles:new Set(y.state.dependencyFiles),fileVersions:new Map(y.state.fileVersions)};i.set(y.key,h),ne(h,h.dependencyFiles)}}async function xi(f){let y=i.get(f);if(!y)throw new Error(`Composition not found: ${f}`);if(y.graph)return;let h=await n.readFile(y.entryFile);await q(f,h)}function $n(f,y){let h=i.get(o.resolveSelector(y).key)??null;return!h||!wc(h,f)?null:h}function wc(f,y){if(f.documentIndex?.entriesByKey.has(y)||f.graph?.elements.has(y))return!0;let h=Ge(y);return h&&h!==y?f.graph?.elements.has(h)===!0:!1}function ee(f,y,h,I){return{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:W(f),error:{code:y,message:h,...I?{details:I}:{}}}}function Nc(f){return f==="validate"?O.ROUTE_REBUILD_FAILED:f==="publish"?O.HISTORY_COMMIT_FAILED:O.WRITE_IO_ERROR}async function jr(f){if(g=!0,!l.markRecoveryRequired)return O.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(f),O.RECOVERY_REQUIRED}catch{return O.RECOVERY_PERSIST_FAILED}}function Cm(f){let h=f.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(I=>I.charAt(0).toUpperCase()+I.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return h?`Prefab${h}`:"GeneratedPrefab"}function Pc(f){return f==="VERSION_STALE"?O.VERSION_STALE:f==="CROSS_PAGE_MOVE_UNSUPPORTED"?O.CROSS_PAGE_MOVE_UNSUPPORTED:O.UNSUPPORTED_OPERATION}async function Ac(f){if(f.target.kind==="route"){let h=i.get(o.resolveSelector(f.target.composition).key)??null;return h?(h.graph||await xi(h.key),h):ee(f,O.ROUTE_NOT_FOUND,"Composition not found for route target.")}if(f.target.kind==="page-unit"){let h=i.get(o.resolveSelector(f.target.composition).key)??null;return h?(h.graph||await xi(h.key),h):ee(f,O.ROUTE_NOT_FOUND,"Composition not found for page-unit target.")}if(f.target.kind!=="node")return ee(f,O.UNSUPPORTED_OPERATION,`${f.kind} source target execution is not implemented yet.`);let y=i.get(o.resolveSelector(f.composition).key)??null;return y?(y.graph||await xi(y.key),wc(y,f.target.key)?y:ee(f,O.NODE_NOT_FOUND,`Target key not found: ${f.target.key}`)):ee(f,O.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(),p.clear()},registerComposition(f,y){let h=o.register({context:f,entryFile:y}),I=i.get(h.key);if(I?.entryFile===y)return;I&&N(I);let R=fp(h.context,y);i.set(h.key,R),ne(R,R.dependencyFiles),r.emit({type:"graph-invalidated",composition:h.context})},unregisterComposition(f){let y=o.resolveSelector(f),h=i.get(y.key);h&&(N(h),i.delete(y.key),o.unregister(y.key),i.size===0&&(t="idle"),r.emit({type:"graph-invalidated",composition:y.context}))},getCompositionEntryFiles(){return[...i.values()].map(f=>f.entryFile)},getCompositionContext(f){return o.resolveSelector(f).context},async initializeComposition(f){let y=o.resolveSelector(f),h=i.get(y.key);if(!h)throw new Error(`Composition not registered: ${y.key}`);if(h.graph)t="ready";else{t="building";try{let I=await n.readFile(h.entryFile);await q(y.key,I),t="ready",r.emit({type:"graph-ready",composition:y.context,version:i.get(y.key)?.graph?.version??0})}catch(I){throw t="idle",r.emit({type:"graph-error",composition:y.context,message:Fe(I)}),I}}},getDocument(f){let y=o.resolveSelector(f),h=i.get(y.key);if(!h)throw new Error(`Composition not registered: ${y.key}`);if(!h.document)throw new Error(`Composition not built: ${y.key}`);return h.document},async getHistoryStatus(){await C;let f=await l.getStatus?.();return f?{...f,recoveryRequired:g}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:g}},getObjectEditContext(f,y){let h=$n(f,y),I=Ge(f)??f;if(h?.graph&&h.topology&&h.capabilities&&h.detailProjections){let R=h.detailProjections.get(I);if(R){let A=Jl(I,h.graph,h.topology,h.capabilities,R.textSources,R.provenances,R.dynamicData);return f===I?A:jv(A,f,h.document??null,h.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${f}`)},getRenderDetail(f,y){let h=$n(f,y),I=Ge(f)??f;if(h?.graph&&h.topology&&h.capabilities&&h.detailProjections){let R=h.detailProjections.get(I);if(R){let A=Kl(I,h.graph,h.topology,h.capabilities,R.textSources,R.writeTarget,R.provenances,R.conditional,R.componentSemantic,R.contentModel,R.mediaModel,R.styleSource,R.dynamicData);return f===I?A:Bv(A,f,h.document??null,h.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${f}`)},getClassNameSource(f,y){let h=$n(f,y),I=Ge(f)??f;if(!h?.graph)throw new Error(`Key not found: ${f}`);let R=h.graph.elements.get(I);if(!R)throw new Error(`Key not found: ${f}`);let A=d.get(R.sourceFile);if(A===void 0)throw new Error(`Source not loaded: ${R.sourceFile}`);return au({key:I,route:{composition:h.composition,routeId:h.routeId,graph:h.graph,source:A}})},refreshSourceForKey:dm,async execute(f){if(await C,g)return ee(f,O.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(f.kind==="source-edit")return fm(f);if(f.kind==="insert-page-resource")return pm(f);if(f.kind==="delete-page-source")return mm(f);let y=await Ac(f);if("ok"in y)return y;await bc(f);let h=await Ac(f);if("ok"in h)return h;let I=h;if(f.target.kind==="page-unit"){let L=f;return f.kind==="insert-child"?gm(L,I):f.kind==="move-node"||f.kind==="remove-node"?hm(L,I):ee(f,O.UNSUPPORTED_OPERATION,"Only page-unit insert-child, move-node, and remove-node are currently supported by the page composition transaction.")}if(!I.graph||!I.topology||!I.capabilities)return{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:W(f),error:{code:f.target.kind==="route"?O.ROUTE_NOT_FOUND:O.NODE_NOT_FOUND,message:f.target.kind==="route"?"Composition not ready for route target.":f.target.kind==="node"?`Target key not found: ${f.target.key}`:`${f.kind} source target execution is not implemented yet.`}};let R=Cv(I,I.graph,I.capabilities,d,i),A=await new Ao(R).plan(f);if(!A.ok)return{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:W(f),error:{code:Rr(A.errorCode),message:A.reason}};let F=A.plan;if(F.steps.length===0)return f.kind==="set-props"?{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!0,resultVersion:W(f),affectedFiles:[]}:{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:W(f),error:{code:O.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};m+=1;try{if(F.steps.some(T=>T.type==="invoke-external-adapter")){let T=await u.execute(F);if(!T.ok)return ee(f,Rr(T.errorCode),T.reason);let $={composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!0,resultVersion:Math.max(W(f),T.resultVersion),affectedFiles:T.affectedFiles,...T.selectionRef?{selectionRef:T.selectionRef}:{}};return mi($,{rebuiltRoutes:[],failedRoutes:[]}),$}let L=await u.prepareRewritePlan(F);return L.ok?await un({request:f,filePlan:L.filePlan,...L.selectionRef?{selectionRef:L.selectionRef}:{}}):ee(f,Rr(L.errorCode),L.reason)}catch(L){return{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:W(f),error:{code:O.INTERNAL_ERROR,message:Fe(L)}}}finally{m-=1}},async undo(f){if(await C,g)return{composition:o.entries[0].context,requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:he(o.entries[0].key),error:{code:O.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};m+=1;try{return await kc("undo")}finally{m-=1}},async redo(f){if(await C,g)return{composition:o.entries[0].context,requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:he(o.entries[0].key),error:{code:O.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};m+=1;try{return await kc("redo")}finally{m-=1}},notifyFileChanged(f){gc([f])},getAffectedCompositions(f){return sm(f)},subscribe(f){return r.subscribe(f)}}}function Iv(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function vv(e,t,n){let r=new Map,o=new Map;for(let s of t.elements.values()){if(s.sourceFile!==n.entryFile||!s.importedFrom||!/^[A-Z]/.test(s.tag))continue;let a=n.placements.find(l=>l.members.some(u=>u.sourceRange!==null&&Ma(s.sourceRange,u.sourceRange)));if(!a)continue;let c=a.placementUnitKey;if(r.set(`${s.importedFrom}#${s.tag}`,c),s.exportName==="default"){let l=o.get(s.importedFrom)??new Set;l.add(c),o.set(s.importedFrom,l)}s.exportName&&s.exportName!=="default"&&s.exportName!==s.tag&&r.set(`${s.importedFrom}#${s.exportName}`,c)}let i=n.placements.find(s=>s.placementKey===n.container.placementKey&&s.relation==="append");for(let s of e.entries){let a=t.elements.get(s.key);if(!a)continue;if(a.sourceFile===n.entryFile){if(n.container.sourceRange&&Ma(a.sourceRange,n.container.sourceRange)&&i){s.pageCompositionUnitKey=i.placementUnitKey;continue}let u=n.placements.find(d=>d.members.some(p=>p.sourceRange!==null&&(Ma(a.sourceRange,p.sourceRange)||kv(p.sourceRange,a.sourceRange))));if(u){s.pageCompositionUnitKey=u.placementUnitKey;continue}}let c=r.get(`${a.sourceFile}#${a.componentName}`);if(c){s.pageCompositionUnitKey=c;continue}let l=o.get(a.sourceFile);l?.size===1&&(s.pageCompositionUnitKey=l.values().next().value)}}function Ma(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function kv(e,t){return gp(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&gp(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function gp(e,t,n,r){return e!==n?e-n:t-r}function Cv(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 p=t.elements.get(u);for(let m of p?.childKeys??[])a(m,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),p=t.elements.get(d.baseKey);return p?l(u,p):null},getChildNodes(u){let d=c(u),m=e.documentIndex?.entriesByKey.get(u)?.childKeys;if(m)return m.map(S=>{let C=Ge(S)??S,v=t.elements.get(C);return v?l(S,v):null}).filter(S=>S!==null);let g=t.elements.get(d.baseKey);return g?g.childKeys.map(S=>{let C=t.elements.get(S);return C?l(S,C):null}).filter(S=>S!==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),p=n.get(d.baseKey);return p?{...p,key:u,constraints:p.constraints.map(m=>({...m})),...p.editModes?{editModes:{...p.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},getEditableTextSegmentIndex(u){let d=c(u),m=e.detailProjections?.get(d.baseKey)?.textTargets.keys()?.next();return m&&!m.done?m.value:null},async getTextWriteTarget(u,d){let p=c(u);return xp(e.detailProjections?.get(p.baseKey)?.textTargets.get(d)??null,p.repeatIndex)},async getElementPropertyWriteTarget(u,d){let p=c(u);return xp(e.detailProjections?.get(p.baseKey)?.elementPropertyTargets.get(d)??null,p.repeatIndex)},getTextProvenance(u,d){let p=c(u);return e.detailProjections?.get(p.baseKey)?.provenances.get(d)??null}};function c(u){let d=ev(u);return d?{baseKey:d.baseKey,repeatIndex:Ov(e.document??null,u,d.baseKey,e.documentIndex)??Mv(d)}:{baseKey:u,repeatIndex:null}}function l(u,d){let p=Ge(u)??u,m=e.documentIndex?.entriesByKey.get(u),g=e.detailProjections?.get(p);return{key:u,file:d.sourceFile,component:d.componentName,tag:d.tag,structuralPath:d.identity.structuralPath,sourceRange:d.sourceRange,parentKey:m?.parentKey??d.parentKey??void 0,isRepeatRegion:d.boundaryKind==="repeat-region"||s.has(p),isBoundary:!1,importedFrom:d.importedFrom,exportName:d.exportName,isRepeatItemRoot:i.has(p),repeatOwnerKey:i.get(p)??s.get(p),contentModel:g?.contentModel,attributes:d.attributes?.map(S=>({name:S.name,value:S.value,source:S.source?{expression:S.source.expression,base:S.source.base,path:S.source.path.map(C=>({...C}))}:null,resolvedValue:S.resolvedValue}))}}}var Rv={"stale-version":O.VERSION_STALE,"capability-denied":O.CAPABILITY_REJECTED,"invalid-params":O.INVALID_PARAMS,"locator-miss":O.LOCATOR_FAILED,"route-not-found":O.ROUTE_NOT_FOUND,"unsupported-operation":O.UNSUPPORTED_OPERATION,"invalid-target":O.INVALID_TARGET,"ast-error":O.AST_PARSE_ERROR,"writeback-failed":O.WRITE_IO_ERROR,"rollback-failed":O.RECOVERY_REQUIRED,unknown:O.INTERNAL_ERROR};function Rr(e){return Rv[e]}function Fe(e){return e instanceof Error&&e.message?e.message:String(e)}function hp(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function wv(e){let t=sn(e);if(!rv.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=>ov.map(a=>`${s}/${a}`))}function Nv(e){let n=sn(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function Pv(e){return bp(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function Av(e){return bp(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function bp(e,t){let n=[];for(let r of e.matchAll(t)){let o=Ep(r[1]??"");o&&n.push(o)}return n}function yp(e,t){let n=Ep(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?sn(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?sn(`${Tv(e)}/${n}`):n.startsWith("/")?sn(n.slice(1)):Oa(n)?sn(n):null}function Ep(e){return e.split(/[?#]/,1)[0]?.trim()??""}function Oa(e){return/\.css$/i.test(e)}function Tv(e){let t=sn(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function Ip(e){return Array.from(new Set(e))}function sn(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 _v(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 Go(e){return e?.map(t=>({...t}))}function xp(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=Go(e.collectionPathMap?.[t])??Go(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:Go(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>Go(o)??[])}}function Fv(e,t,n){let r=new Set;for(let m of t.regions)if(m.kind==="repeat-region")for(let g of m.childKeys)r.add(g);if(r.size===0)return e;let o=new Map(e.entries.map(m=>[m.key,m])),i=[],s=new Map,a=(m,g)=>ZI(m,g),c=(m,g,S)=>{let C=o.get(m);if(!C)return a(m,S);let v=a(m,S),P={...C,key:v,parentKey:g,childKeys:[]};return i.push(P),P.childKeys=C.childKeys.flatMap(w=>l(w,S,v)),v},l=(m,g,S)=>{if(!r.has(m))return[c(m,S,g)];let C=d(m,g),v=[];for(let P=0;P<C;P+=1)v.push(c(m,S,[...g,P]));return v},u=Ip([...e.rootKeys,...e.entries.filter(m=>m.parentKey===null).map(m=>m.key)]);for(let m of u){if(!r.has(m)){c(m,null,[]);continue}let g=d(m,[]);for(let S=0;S<g;S+=1)c(m,null,[S])}return{...e,rootKeys:[...e.rootKeys],entries:i};function d(m,g){let S=new Set;for(let C of p(m)){let v=n.get(C);if(v){for(let P of[...v.textTargets.values(),...v.elementPropertyTargets.values()])if(!(P?.kind!=="value-binding"||P.sourceKind!=="repeat-template"))for(let w of Dv(P))w.length<=g.length||Lv(w,g)&&S.add(w[g.length])}}return S.size>0?S.size:_v(n.get(m))}function p(m){let g=s.get(m);if(g)return g;let S=[m],C=o.get(m);for(let v of C?.childKeys??[])S.push(...p(v));return s.set(m,S),S}}function Mv(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function Ov(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((Ge(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function Dv(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 Lv(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 Bv(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 jv(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}}import $a from"node:path";import{TextDecoder as $v}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as kp,SITE_EDIT_SOURCE_ALLOWED_DIRS as Cp,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as Rp,SiteEditCompositionContextSchema as Vv,SiteEditSourceFileResponseSchema as Da,SiteEditSourceLocationSchema as Uv,SiteEditSourcePathSchema as Zo,SiteEditSourceTreeResponseSchema as Kv,isSiteEditTextSourcePath as Jv}from"@vcp-dev/contracts";var Xv=[...Rp,...kp,...Cp];function Va(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return Vv.parse(e.composition)}var La=2e3,Ba=12,ja=24*1024*1024,vp=512*1024,zv=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),Hv={".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"},Wv={".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"},Gv=new $v("utf-8",{fatal:!0});async function Qo(e,t={}){let n=Va(t),{files:r,truncated:o}=await rk(e,t),i=sk(r.map(s=>s.metadata));return Kv.parse({composition:n,nodes:i,defaultPath:ak(r.map(s=>s.metadata)),totalFiles:r.length,...o?{truncated:o}:{}})}async function qo(e,t,n={}){let r=Va(n),o=Zo.parse(t.path),i=await Qv(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(Ua(o)){let a=Pp(o),c=await ek(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return Da.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...c})}let s=await Yv(e,o);return s.ok?Da.parse({composition:r,path:o,kind:"text",language:Ap(o),sizeBytes:s.sizeBytes,contentHash:le(s.content),readonly:!1,content:s.content}):Da.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function Yv(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=Zv(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 Zv(e){if(e.includes(0))return null;try{return Gv.decode(e)}catch{return null}}async function Qv(e,t,n){if(!tk(t,n))return null;let r=await qv(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function qv(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=wp(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(Ua(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function ek(e,t){if(!zv.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>vp)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>vp?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function tk(e,t){return Rp.some(n=>n===e)||kp.some(n=>n===e)||Cp.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 Uv.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 wp(e){return Array.isArray(e)?{files:e}:e}function nk(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function rk(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=wp(await e.listFiles({roots:ok(t),maxFiles:La+1,maxDepth:Ba,maxTotalBytes:ja+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>Ba){o.add("max-depth");continue}if(r.size>=La){o.add("max-files");break}if(i+a.sizeBytes>ja){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:ik(l,a.sizeBytes,Va(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:nk([...o]),maxFiles:La,maxDepth:Ba,maxTotalBytes:ja}}:{}}}function ok(e){let t=new Set(Xv);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 ik(e,t,n){return Ua(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:Pp(e),readonly:!0}:{composition:n,path:e,kind:"text",language:Ap(e),sizeBytes:t,readonly:!1}}function sk(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 Np(t)}function Np(e){return e.map(t=>t.kind==="directory"?{...t,children:Np(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function ak(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 Ua(e){return!Jv(e)}function Pp(e){let t=$a.posix.extname(e).toLowerCase();return!t&&$a.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":Hv[t]??"application/octet-stream"}function Ap(e){let t=$a.posix.extname(e).toLowerCase();return Wv[t]??"plaintext"}var ti=class{constructor(t){this.options=t,this.fileSystem=new qn(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}getDocument(t){return Vr(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){return Ur(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=lk.safeParse(t);if(!n.success)return{result:$r(t,n.error.issues.map(i=>i.message))};let r=new qn(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:Vt(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let c=uk.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(l=>dk(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 wr({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=Kr(o,{siteId:this.options.siteId,snapshotId:this.options.snapshotId});i&&this.options.onEvent?.(i)}:void 0,dev:this.options.dev,...this.options.historyStore?{historyStore:this.options.historyStore}:{},...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,...this.options.initialDocumentVersions?{initialDocumentVersions:this.options.initialDocumentVersions}:{}})}};function dk(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:le(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:le(e.before)},fullContent:e.after}}function fk(e){return new ti(e)}import{SiteEditOperationRequestSchema as gk}from"@vcp-dev/contracts";import st from"node:fs/promises";import Me from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as pk,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as mk}from"@vcp-dev/contracts";var ni=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=wr({...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){return 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 st.readFile(Me.join(n,r),"utf8")},async readFileBytes(r){return st.readFile(Me.join(n,r))},async getFileInfo(r){let o=Me.join(n,...r.split("/"));try{let i=await st.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await Bo(Me.join(n,r),o)},async createExclusive(r,o){let i=Me.join(n,r);await st.mkdir(Me.dirname(i),{recursive:!0});let s=await st.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await st.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await st.rm(Me.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=Me.join(n,i),a=Me.dirname(Me.join(n,o));for(;a!==s&&a.startsWith(`${s}${Me.sep}`);){try{await st.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=Me.dirname(a);continue}break}a=Me.dirname(a)}},async exists(r){try{return await st.access(Me.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...mk,...pk],i=[],s=new Set,a=new Set,c=0;for(let d of o)await u(d,i,1);let l=i.sort((d,p)=>d.path.localeCompare(p.path));return a.size>0?{files:l,truncated:{reasons:[...a]}}:{files:l};async function u(d,p,m){if(r.maxDepth!==void 0&&m>r.maxDepth){a.add("max-depth");return}let g=Me.join(n,...d.split("/")),S;try{S=await st.lstat(g)}catch{return}if(S.isSymbolicLink())return;if(S.isFile()){let v=S.ino>0?`${String(S.dev)}:${String(S.ino)}`:null;if(v&&s.has(v))return;if(r.maxFiles!==void 0&&p.length>=r.maxFiles){a.add("max-files");return}if(r.maxTotalBytes!==void 0&&c+S.size>r.maxTotalBytes){a.add("max-total-bytes");return}v&&s.add(v),p.push({path:d,sizeBytes:S.size}),c+=S.size;return}if(!S.isDirectory())return;if(r.maxFiles!==void 0&&p.length>=r.maxFiles){a.add("max-files");return}let C=await st.readdir(g,{withFileTypes:!0});for(let v of C)v.isSymbolicLink()||await u(`${d}/${v.name}`,p,m+1)}},getVersion(r){return t.get(r)??1},bumpVersion(r){let o=(t.get(r)??1)+1;return t.set(r,o),o}}}};function Ka(e){return new ni(e)}var ri=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=Ka({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=Kr(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:Vr(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){return{ok:!0,composition:this.engine.getCompositionContext(n),data:Ur(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=gk.safeParse(r);if(!o.success)return $r(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},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:Vt(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:Vt(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:Vt(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 hk(e){return new ri(e)}import{createHash as yk,randomUUID as tc}from"node:crypto";import ye from"node:fs/promises";import be from"node:path";var Ye=1,Xa=1,xk=2,Sk="index.json",bk="recovery.json",Ek="transaction-journal.json",Ik="document-version.json",ii={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},J={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"},H=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};async function $p(e,t={}){let n=Dk(e),r=jk(t.limits),o=Ja(n),i=Lk(n),s=await Le(i),a=await Le(o)||s;a||(await Nk(n),await Pk(n)),a||await $k(n);let c=await $e(n),l=new Set(a?(await ui(n)).map(d=>d.stageId):[]);a||await Nr(n,c.entryIds);let u=async()=>{if(await Le(o)||s)throw new H(J.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")};return{rootDir:n,recoveryRequired:a,async readDocumentVersion(){return Bp(n)},async writeDocumentVersion(d){if(await u(),!Number.isInteger(d)||d<0)throw new H(J.INVALID_SCHEMA,"document version must be a non-negative integer");let p=await Bp(n);await Pr(Hp(n),{schemaVersion:1,version:Math.max(p,d)})},async stageAppend(d,p={}){await u();let m=await _p(d,r),g={schemaVersion:Xa,stageId:tc(),entryId:m.entryId,blobIds:m.blobs.map(S=>S.digest)};try{await Fp(n,m),await Ck(n,g,p.durableManifest!==!1)}catch(S){try{await Op(n,g)}catch(C){throw new H(J.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:C})}throw S}return{stageId:g.stageId,entryId:g.entryId,blobIds:g.blobIds}},async discardStage(d){await u(),Ga(d);let p=await Ha(n,d);p&&await Op(n,p)},async previewStagedAppend(d,p){return await u(),(await Tp(n,r,d,p)).transition},async previewCursor(d,p){await u();let m=await $e(n);return Ya(m,p),za(d,m.entryIds.length),Vp(m,m.entryIds,d)},async publishStagedAppend(d,p,m){if(await u(),si(d,"entryId"),m){Ga(m);let S=await Ha(n,m);if(!S||S.entryId!==d)throw new H(J.INVALID_SCHEMA,"history stage does not match the published entry")}let g=await Tp(n,r,d,p);return Lp({rootDir:n,previousDigest:g.current.digest,entryIds:g.entryIds,cursor:g.cursor,afterWrite:async()=>{m?await ai(n,m):await wk(n,d),await Nr(n,g.entryIds)}})},async append(d){await u();let p=await $e(n),m=await _p(d,r),g=[...p.entryIds];p.cursor<g.length-1&&g.splice(p.cursor+1),g.push(m.entryId);try{await Fp(n,m);let S=await Up(n,g,r);return await rc(n,S.entryIds,S.cursor),await Nr(n,S.entryIds),$e(n)}catch(S){throw await Nr(n,p.entryIds),S}},async readEntry(d){return si(d,"entryId"),Tr(n,d)},async readBlob(d){si(d,"blobId");let p=await dc(n,d),m=await Bt(p,J.NOT_FOUND,"blob");return oc(m,d,p),m},async readIndex(){return $e(n)},async readStatus(){let d=await $e(n);return{canUndo:d.undoIds.length>0,canRedo:d.redoIds.length>0,undoDepth:d.undoIds.length,redoDepth:d.redoIds.length,cursor:d.cursor,recoveryRequired:await Le(o)||await Le(i)}},async readUndoRedoIds(){let d=await $e(n);return{undoIds:d.undoIds,redoIds:d.redoIds,currentId:d.currentId}},async setCursor(d,p){await u();let m=await $e(n);return Ya(m,p),za(d,m.entryIds.length),Lp({rootDir:n,previousDigest:m.digest,entryIds:m.entryIds,cursor:d})},async markRecoveryRequired(d){await Le(o)||await Pr(Ja(n),{schemaVersion:Ye,reason:Bk(d),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await ye.rm(Ja(n),{force:!0})},async readTransactionJournal(){return await Le(i)?oi(i):null},async writeTransactionJournal(d){await u(),Wp(d);try{await Pr(i,d)}catch(m){let g=await oi(i).catch(()=>null);if(g&&Buffer.from(Ve(g)).equals(Buffer.from(Ve(d))))return;throw g?new H(J.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:m}):m}let p=await oi(i);if(!Buffer.from(Ve(p)).equals(Buffer.from(Ve(d))))throw new H(J.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(d){let p=await Le(i)?await oi(i):null;if(p&&p.transactionId!==d)throw new H(J.INVALID_SCHEMA,"transaction journal changed concurrently");try{await ye.rm(i,{force:!0})}catch(m){if(!await Le(i))return;throw m}if(await Le(i))throw new H(J.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await u();for(let p of l)await ai(n,p),l.delete(p);await Ak(n);let d=await $e(n);await Nr(n,d.entryIds)}}}async function Tp(e,t,n,r){si(n,"entryId");let o=await $e(e);Ya(o,r);let i=await Tr(e,n),s=[...o.entryIds];o.cursor<s.length-1&&s.splice(o.cursor+1),s.push(i.id);let a=await Up(e,s,t);return{current:o,entryIds:a.entryIds,cursor:a.cursor,transition:Vp(o,a.entryIds,a.cursor)}}function Vp(e,t,n){return za(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:vk(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function vk(e,t){return jt(Ve({schemaVersion:Ye,entryIds:e,cursor:t}))}function za(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new H(J.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function kk(e){if(!at(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!Ue(e.expectedIndexDigest)||!Ue(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!Ue(n)?!1:t===-1?n===null:Ue(n)}async function _p(e,t){if(!e.kind.trim())throw new H(J.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new H(J.INVALID_JSON,"history blob name must not be empty");let l=Ok(c.data),u=jt(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:Ye,kind:e.kind,manifest:e.manifest,blobs:r},i=Ve({...o}),s=jt(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new H(J.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function Fp(e,t){let n=ac(e,t.entryId),r={id:t.entryId,...t.entryBody},o=[...t.blobs.map(a=>Mp(cc(e,a.digest),a.bytes,{kind:"blob",digest:a.digest},uc(e,a.digest))),Mp(n,Ve(r),{kind:"entry",digest:t.entryId},lc(e,t.entryId))],s=(await Promise.allSettled(o)).find(a=>a.status==="rejected");if(s)throw s.reason}async function Mp(e,t,n,r){let o=await qa(e)??(r?await qa(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new H(n.kind==="blob"?J.BLOB_CORRUPT:J.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await Xp(e,t)}async function Up(e,t,n){let r=[...t],o=r.length-1;for(;;){if((await Jp(e,r)).totalBytes<=n.maxSessionBytes&&r.length<=n.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new H(J.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");r.shift(),o-=1}}async function Ck(e,t,n){nc(t);let r=sc(e,t.stageId);if(n){await Pr(r,t);return}await Mk(r,t)}async function Ha(e,t){let n=await qa(sc(e,t));if(n===null)return null;let r=_r(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=nc(r);if(o.stageId!==t)throw new H(J.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function ui(e){let t=[];for(let n of await li(ic(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);Ga(r);let o=await Ha(e,r);o&&t.push(o)}return t}async function Op(e,t){nc(t);let n=await $e(e),r=(await ui(e)).filter(s=>s.stageId!==t.stageId),o=new Set(n.entryIds),i=new Set;for(let s of n.entryIds){let a=await Tr(e,s);for(let c of a.blobs)i.add(c.digest)}for(let s of r){o.add(s.entryId);for(let a of s.blobIds)i.add(a)}o.has(t.entryId)||await Dp(ac(e,t.entryId),lc(e,t.entryId));for(let s of t.blobIds)i.has(s)||await Dp(cc(e,s),uc(e,s));await ai(e,t.stageId),await ec(Fr(e)),await ec(Mr(e))}async function ai(e,t){await Wa(sc(e,t)),await Rk(e)}async function Rk(e){try{await ye.rmdir(ic(e))}catch(t){if(Or(t)||at(t)&&t.code==="ENOTEMPTY")return;throw t}}async function wk(e,t){for(let n of await ui(e))n.entryId===t&&await ai(e,n.stageId)}async function Wa(e){if(await ye.rm(e,{force:!0}),await Le(e))throw new H(J.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function Dp(e,t){await Wa(e),await Wa(t)}function nc(e){if(!at(e)||e.schemaVersion!==Xa||typeof e.stageId!="string"||!Kp(e.stageId)||!Ue(e.entryId))throw new H(J.INVALID_SCHEMA,"history stage schema is invalid");let t=zp(e.blobIds,"history stage blobIds");return{schemaVersion:Xa,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function Ga(e){if(!Kp(e))throw new H(J.INVALID_PATH,"history stageId must be a UUID")}function Kp(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 Nr(e,t){let n=new Set(t),r=new Set;for(let c of t){let l=await Tr(e,c);for(let u of l.blobs)r.add(u.digest)}for(let c of await ui(e)){n.add(c.entryId);for(let l of c.blobIds)r.add(l)}let o=Fr(e),i=await li(o);for(let c of i){if(!c.endsWith(".json"))continue;let l=jp(c.slice(0,-5));l&&!n.has(l)&&await ci(be.join(o,c))}let s=Mr(e),a=await li(s);for(let c of a){let l=jp(c);l&&!r.has(l)&&await ci(be.join(s,c))}}async function $e(e){let t=di(e),n=await Bt(t,J.NOT_FOUND,"index"),r=_r(Buffer.from(n).toString("utf8"),"index"),o=Tk(r),i=[...o.entryIds],{totalBytes:s}=await Jp(e,i),a=i.slice(0,o.cursor+1).reverse(),c=i.slice(o.cursor+1);return{schemaVersion:Ye,digest:o.digest,entryIds:i,cursor:o.cursor,currentId:i[o.cursor]??null,undoIds:a,redoIds:c,totalBytes:s}}async function Jp(e,t){let n=0,r=new Set,o=di(e),i=await Bt(o,J.NOT_FOUND,"index");n+=i.byteLength;for(let s of t){let a=await Tr(e,s),c=await Gp(e,s),l=await Bt(c,J.NOT_FOUND,"entry");n+=l.byteLength;for(let u of a.blobs){if(r.has(u.digest))continue;r.add(u.digest);let d=await dc(e,u.digest),p=await Bt(d,J.NOT_FOUND,"blob");oc(p,u.digest,d),n+=p.byteLength}}return{totalBytes:n}}async function Tr(e,t){let n=await Gp(e,t),r=await Bt(n,J.NOT_FOUND,"entry"),o=_r(Buffer.from(r).toString("utf8"),`entry ${t}`),i=_k(o);if(i.id!==t)throw new H(J.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(jt(Ve({schemaVersion:i.schemaVersion,kind:i.kind,manifest:i.manifest,blobs:i.blobs}))!==t)throw new H(J.ENTRY_CORRUPT,`entry hash mismatch for ${t}`);for(let a of i.blobs){let c=await dc(e,a.digest),l=await Bt(c,J.NOT_FOUND,"blob");oc(l,a.digest,c)}return i}async function rc(e,t,n){let r={schemaVersion:Ye,digest:jt(Ve({schemaVersion:Ye,entryIds:t,cursor:n})),entryIds:t,cursor:n};await Pr(di(e),r)}function Ya(e,t){if(t!==void 0&&e.digest!==t)throw new H(J.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function Lp(e){let t=jt(Ve({schemaVersion:Ye,entryIds:e.entryIds,cursor:e.cursor}));try{return await rc(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.(),await $e(e.rootDir)}catch(n){let r=await $e(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new H(J.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function Nk(e){await ye.mkdir(e,{recursive:!0}),await ye.mkdir(Fr(e),{recursive:!0}),await ye.mkdir(Mr(e),{recursive:!0}),await ye.mkdir(Ar(e),{recursive:!0})}async function Pk(e){await ye.rm(Ar(e),{recursive:!0,force:!0}),await ye.mkdir(Ar(e),{recursive:!0})}async function Ak(e){let t=Ar(e);await ye.mkdir(t,{recursive:!0});for(let n of await li(t))n!=="stages"&&await ye.rm(be.join(t,n),{recursive:!0,force:!0})}function Tk(e){if(!at(e))throw new H(J.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==Ye)throw new H(J.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=zp(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new H(J.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!Ue(o))throw new H(J.INDEX_CORRUPT,"index digest is invalid");let i=jt(Ve({schemaVersion:Ye,entryIds:t,cursor:r}));if(o!==i)throw new H(J.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:Ye,digest:o,entryIds:t,cursor:r}}function _k(e){if(!at(e))throw new H(J.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==Ye)throw new H(J.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!Ue(t))throw new H(J.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new H(J.ENTRY_CORRUPT,"entry kind is invalid");let r=Qa(e.manifest,"entry.manifest"),o=Fk(e.blobs);return{id:t,schemaVersion:Ye,kind:n,manifest:r,blobs:o}}function Fk(e){if(!Array.isArray(e))throw new H(J.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!at(t))throw new H(J.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new H(J.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!Ue(o))throw new H(J.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new H(J.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function Pr(e,t){await Xp(e,Ve(t))}async function Mk(e,t){let n=be.dirname(e),r=be.basename(e),o=be.join(n,`.${r}.${process.pid}.${tc()}.tmp`);await ye.mkdir(n,{recursive:!0});try{await ye.writeFile(o,Ve(t),{flag:"wx"}),await ye.rename(o,e)}finally{await ci(o)}}async function Xp(e,t){let n=be.dirname(e),r=be.basename(e),o=be.join(n,`.${r}.${process.pid}.${tc()}.tmp`);await ye.mkdir(n,{recursive:!0});try{let i=await ye.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await ye.rename(o,e),await ec(n)}finally{await ci(o)}}function Ve(e){return Buffer.from(JSON.stringify(Za(e)),"utf8")}function Za(e){if(Array.isArray(e))return e.map(t=>Za(t));if(at(e)){let t={};for(let n of Object.keys(e).sort())t[n]=Za(e[n]);return t}return e}function _r(e,t){try{return JSON.parse(e)}catch(n){throw new H(J.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function Qa(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=>Qa(n,t));if(at(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=Qa(o,t);return n}break}throw new H(J.INVALID_JSON,`${t} must be JSON-serializable`)}function zp(e,t){if(!Array.isArray(e))throw new H(J.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!Ue(n))throw new H(J.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function si(e,t){if(!Ue(e))throw new H(J.INVALID_PATH,`${t} must be a sha256 digest`)}function Ue(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function jt(e){return`sha256:${yk("sha256").update(e).digest("hex")}`}function Ok(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function Bt(e,t,n){try{return await ye.readFile(e)}catch(r){throw new H(t,`${n} not found: ${e}`,{cause:r})}}async function qa(e){try{return await ye.readFile(e)}catch(t){if(Or(t))return null;throw t}}function oc(e,t,n){if(jt(e)!==t)throw new H(J.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function Le(e){try{return await ye.access(e),!0}catch(t){if(Or(t))return!1;throw t}}async function ci(e){try{await ye.rm(e,{force:!0,recursive:!0})}catch{}}async function ec(e){try{let t=await ye.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function li(e){try{return await ye.readdir(e)}catch(t){if(Or(t))return[];throw t}}function Dk(e){if(typeof e!="string"||e.trim().length===0)throw new H(J.INVALID_ROOT,"history store rootDir must be a non-empty string");return be.resolve(e)}function di(e){return be.join(e,Sk)}function Ja(e){return be.join(e,bk)}function Lk(e){return be.join(e,Ek)}function Hp(e){return be.join(e,Ik)}async function Bp(e){try{let t=await ye.readFile(Hp(e),"utf8"),n=_r(t,"document version");if(!at(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new H(J.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(Or(t))return 0;throw t}}async function oi(e){let t=await Bt(e,J.RECOVERY_PENDING,"transaction journal"),n=_r(Buffer.from(t).toString("utf8"),"transaction journal");return Wp(n),n}function Wp(e){if(!at(e)||e.schemaVersion!==xk||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!kk(e.historyTransition)||!Array.isArray(e.files))throw new H(J.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!at(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!Ue(t.preDigest)||t.postDigest!==null&&!Ue(t.postDigest))throw new H(J.INVALID_SCHEMA,"transaction journal file digest is invalid")}function Bk(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function Fr(e){return be.join(e,"entries")}function Mr(e){return be.join(e,"blobs")}function Ar(e){return be.join(e,"tmp")}function ic(e){return be.join(Ar(e),"stages")}function sc(e,t){return be.join(ic(e),`${t}.json`)}function ac(e,t){return be.join(Fr(e),`${Zp(t)}.json`)}function cc(e,t){return be.join(Mr(e),Zp(t))}function lc(e,t){return be.join(Fr(e),`${t}.json`)}function uc(e,t){return be.join(Mr(e),t)}async function Gp(e,t){return Yp(ac(e,t),lc(e,t))}async function dc(e,t){return Yp(cc(e,t),uc(e,t))}async function Yp(e,t){return await Le(e)?e:await Le(t)?t:e}function Zp(e){return e.slice(7)}function jp(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return Ue(t)?t:null}function at(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Or(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function jk(e){return{maxEntries:e?.maxEntries??ii.maxEntries,maxSessionBytes:e?.maxSessionBytes??ii.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??ii.maxEntryBytes}}async function $k(e){let t=di(e);await Le(t)||await rc(e,[],-1)}import{createHash as Vk}from"node:crypto";import{computeSiteEditCompositionKey as qp,ManagedPageTemplateRouteManifestV1Schema as Uk}from"@vcp-dev/contracts";var Kk="app/_vcp/page-templates/runtime.tsx",em=".vcp/page-templates/routes/",Jk="app/_vcp/page-templates/routes/",Ae=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function jn(e){let t=Jo(e);return Vk("sha256").update(t,"utf8").digest("hex").slice(0,16)}function pi(e){return e.replace(/[^A-Za-z0-9_-]/g,"_")}function Dr(e,t){let n=jn(e),r=`${Jk}${n}`,o=pi(t);return{routeRoot:r,manifestFile:`${em}${n}.json`,runtimeFile:Kk,registryFile:`${r}/registry.ts`,templateEntryFile:`${r}/templates/${o}/page.tsx`}}function tm(e){let t=Yk(e),n=new Map;for(let r of t){let o=pi(r),i=n.get(o);if(i!==void 0&&i!==r)throw new Ae("PAGE_TEMPLATE_ID_COLLISION",`Page-template IDs ${JSON.stringify(i)} and ${JSON.stringify(r)} map to the same safe name ${JSON.stringify(o)}.`,{reason:"safe-name-collision",templateId:r,safeName:o});n.set(o,r)}}function fc(e){let t=Jo(e.routeId),n=nm(e.files),r=Dr(t,""),o=n.get(r.manifestFile);if(o===void 0)return null;let i=Wk(t,r.manifestFile,o);return Gk({routeId:t,manifest:i,files:n}),i}function Xk(e){let t=Jo(e.selector.routeId),n=an(e.canonicalEntryFile),r=fc({routeId:t,files:e.files});if(r===null){if(e.selector.templateId!==void 0)throw new Ae("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Page-template selection ${JSON.stringify(e.selector.templateId)} cannot be resolved without a managed manifest for ${JSON.stringify(t)}.`,{reason:"template-selection-without-manifest",routeId:t,templateId:e.selector.templateId});return{mode:"direct",context:{routeId:t},entryFile:n,effectiveEntryFile:n}}if(an(r.canonical_entry_file)!==n)throw new Ae("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Managed page-template manifest for ${JSON.stringify(t)} does not match the supplied canonical entry.`,{reason:"canonical-entry-mismatch",routeId:t,path:r.canonical_entry_file});let o=e.selector.templateId??null,i=(o?r.templates.find(c=>c.template_id===o):void 0)??r.templates.find(c=>c.template_id===r.default_template_id);if(!i)throw new Ae("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Managed page-template manifest for ${JSON.stringify(t)} has no resolvable default template.`,{reason:"default-entry-missing",routeId:t});let a={context:{routeId:t,effectiveTemplateId:i.template_id},entryFile:an(i.entry_file)};return{...a,mode:"delegated",effectiveEntryFile:a.entryFile}}function zk(e){let t=nm(e.files),n=[...t.keys()].map(l=>({path:l})),r=vr(n),o=new Set,i=new Map;for(let l of r){if(o.has(l.routeId))throw new Ae("PAGE_TEMPLATE_ROUTE_AMBIGUOUS",`Multiple canonical page entries resolve to route ${JSON.stringify(l.routeId)}.`,{reason:"duplicate-route-id",routeId:l.routeId,candidates:r.filter(p=>p.routeId===l.routeId).map(p=>p.entryFile)});o.add(l.routeId);let u=jn(l.routeId),d=i.get(u);if(d!==void 0&&d!==l.routeId)throw new Ae("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Page-template route-key collision between ${JSON.stringify(d)} and ${JSON.stringify(l.routeId)}.`,{reason:"route-key-collision",routeId:l.routeId});i.set(u,l.routeId)}let s=new Set(r.map(l=>Dr(l.routeId,"").manifestFile));for(let l of t.keys())if(l.startsWith(em)&&l.endsWith(".json")&&!s.has(l))throw new Ae("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Managed page-template manifest ${JSON.stringify(l)} does not belong to a scanned canonical route.`,{reason:"unknown-manifest",path:l});let a=[];for(let l of r){let u=fc({routeId:l.routeId,files:t});if(u===null){let d={routeId:l.routeId};a.push(Hk(d,l.entryFile));continue}for(let d of[...u.templates].sort(Zk)){let p={routeId:l.routeId,effectiveTemplateId:d.template_id},m={context:p,entryFile:an(d.entry_file)};a.push({key:qp(p),composition:m})}}let c=new Set;for(let{key:l,composition:u}of a){if(c.has(l))throw new Ae("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Duplicate site-edit composition key for ${JSON.stringify(l)}.`,{reason:"duplicate-composition-key",routeId:u.context.routeId});c.add(l)}return a.sort((l,u)=>Qk(l.composition,u.composition)||fi(l.key,u.key)).map(({composition:l})=>l)}function Hk(e,t){return{key:qp(e),composition:{context:e,entryFile:t}}}function nm(e){let t=new Map;if(eC(e)){for(let n of e)Qp(t,n.path,n.content);return t}for(let[n,r]of e)Qp(t,n,r);return t}function Qp(e,t,n){let r=an(t);if(e.has(r))throw new Ae("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Snapshot contains duplicate file path ${JSON.stringify(r)}.`,{reason:"duplicate-file-path",path:r});e.set(r,n)}function Wk(e,t,n){let r;try{r=JSON.parse(n)}catch{throw new Ae("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Managed page-template manifest ${JSON.stringify(t)} is not valid JSON.`,{reason:"invalid-json",routeId:e,path:t})}let o=Uk.safeParse(r);if(!o.success)throw new Ae("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Managed page-template manifest ${JSON.stringify(t)} does not match the known manifest contract.`,{reason:"schema-invalid",routeId:e,path:t,issues:o.error.issues.map(i=>`${i.path.join(".")||"manifest"}: ${i.message}`)});return o.data}function Gk(e){let{routeId:t,manifest:n,files:r}=e,o=Dr(t,""),i=vr([...r.keys()].map(l=>({path:l}))).filter(l=>l.routeId===t);if(n.route_id!==t&&pt(t,"route-id-mismatch",o.manifestFile),n.route_key!==jn(t)&&pt(t,"route-key-mismatch",o.manifestFile),i.length!==1)throw new Ae("PAGE_TEMPLATE_ROUTE_AMBIGUOUS",`Managed page-template route ${JSON.stringify(t)} has ${i.length} canonical entries.`,{reason:i.length===0?"canonical-entry-missing":"duplicate-route-id",routeId:t,candidates:i.map(l=>l.entryFile)});let s=an(n.canonical_entry_file);(s!==i[0].entryFile||!r.has(s))&&pt(t,"canonical-entry-mismatch",s),n.default_template_id!==`vcp-default:${jn(t)}`&&pt(t,"default-template-id-mismatch",o.manifestFile),tm(n.templates);let a=new Set,c=new Set;for(let l of n.templates){let u=Dr(t,l.template_id),d=an(l.entry_file),p=pi(l.template_id);l.safe_name!==p&&pt(t,"safe-name-mismatch",o.manifestFile,{templateId:l.template_id}),a.has(l.safe_name)&&pt(t,"duplicate-safe-name",o.manifestFile,{templateId:l.template_id}),a.add(l.safe_name),c.has(d)&&pt(t,"duplicate-entry-file",o.manifestFile,{templateId:l.template_id}),c.add(d),qk(d,u.routeRoot)||pt(t,"entry-outside-route-root",d,{templateId:l.template_id}),d!==u.templateEntryFile&&pt(t,"entry-path-mismatch",d,{templateId:l.template_id}),r.has(d)||pt(t,"template-entry-missing",d,{templateId:l.template_id})}}function pt(e,t,n,r={}){throw new Ae("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Managed page-template source for ${JSON.stringify(e)} failed validation (${t}).`,{reason:t,routeId:e,path:n,...r})}function Yk(e){return Array.isArray(e)?e.length===0||typeof e[0]=="string"?e:e.map(t=>t.template_id):"rawTemplateIds"in e?e.rawTemplateIds:"templateIds"in e?e.templateIds:[]}function Zk(e,t){return+(t.kind==="default")-+(e.kind==="default")||fi(e.template_id,t.template_id)}function Qk(e,t){let n=fi(e.context.routeId,t.context.routeId);if(n!==0)return n;let r=e.context.effectiveTemplateId,o=t.context.effectiveTemplateId;if(r===void 0)return-1;if(o===void 0)return 1;let s=`vcp-default:${jn(e.context.routeId)}`,a=r===s;return Number(o===s)-Number(a)||fi(r,o)}function fi(e,t){return e<t?-1:e>t?1:0}function qk(e,t){return e.startsWith(`${t}/`)}function an(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function eC(e){return Array.isArray(e)}export{H as FileHistoryStoreError,Ae as PageTemplateManagedSourceError,ri as PreviewFileSystemSiteEditEngineRuntime,hf as SITE_EDIT_RAW_COLOR_LITERAL_RE,ti as SnapshotSiteEditEngineRuntime,tm as assertNoPageTemplateSafeNameCollision,Dr as computeManagedPageTemplatePaths,jn as computePageTemplateRouteKey,pi as computePageTemplateSafeName,hk as createPreviewSiteEditEngineRuntime,fk as createSiteEditEngineRuntime,$p as openFileHistoryStore,fc as parseManagedPageTemplateManifest,Xk as resolveManagedPageTemplateComposition,zk as scanSiteEditCompositionsFromFiles,xr as scanSiteEditThemeStyleViolations};
|