@vcp-dev/site-edit-engine 0.6.6 → 0.6.8

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.
Files changed (2) hide show
  1. package/dist/index.js +3 -3
  2. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
- import{SiteEditOperationRequestSchema as PI,SiteEditPatchPlanSchema as wI}from"@vcp-dev/contracts";function Lt(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 vr(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 Rr(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 Pr(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:Ap(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 wr(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:Lt(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 Ap(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 yb,getSiteEditSourceDeleteProtectionReason as xb,isSiteEditTextSourcePath as Eb,parseSiteEditRepeatInstanceKey as Sb,SITE_EDIT_SOURCE_DELETE_CAPABILITY as bb,stripSiteEditRepeatInstanceKeys as Xe}from"@vcp-dev/contracts";import{parse as Ib}from"yaml";import Ao from"node:path";function _n(e,t,n){return`${e}::${t}::${n}`}var L={NODE_NOT_FOUND:"NODE_NOT_FOUND",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 ai from"@babel/traverse";import*as x from"@babel/types";import{createHash as Dp}from"node:crypto";import*as rc from"@babel/parser";function jt(e,t,n,r){return{code:e,message:t,locatorKind:n,details:r}}function $(e,t,n,r,o){return{ok:!1,source:e,diagnostic:jt(t,n,r,o)}}function ti(e,t,n,r,o){return{ok:!1,source:e,diagnostic:jt(t,n,r,o)}}var Tp={"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:rc.parse(t,{sourceType:"module",plugins:Tp[n]})}}catch(r){return{ok:!1,source:t,diagnostic:jt("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function ni(e,t){return it({source:e,profile:oc(t.kind)})}function ri(e,t){return it({source:e,profile:oc(t)})}function oc(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 Np from"@babel/parser";import*as sn from"@babel/types";import*as Et from"node:path";var oi=[".tsx",".ts",".jsx",".js"],Fp=oi.map(e=>`/index${e}`);function ic(e){let t=[];for(let n of e.program.body)sn.isImportDeclaration(n)&&typeof n.source.value=="string"&&ut(n.source.value)&&t.push(n.source.value),sn.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&ut(n.source.value)&&t.push(n.source.value),sn.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&ut(n.source.value)&&t.push(n.source.value);return t}function ut(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function Mp(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 _p(e,t){if(oi.some(n=>e.endsWith(n))&&await t(e))return e;for(let n of oi){let r=`${e}${n}`;if(await t(r))return r}for(let n of Fp){let r=`${e}${n}`;if(await t(r))return r}return null}async function an(e,t,n){let r=await Ar(e,t,n);return r.ok?r.path:null}async function Ar(e,t,n){let r=Mp(e,t);try{if(!Op(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 _p(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 Op(e,t,n){if(!ut(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 ii=(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:${Dp("sha256").update(t).digest("hex")}`,ast:n.ast,imports:ic(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};var Tr="components/ui";function $t(e){if(!e)return!1;let t=si(e);return t===Tr||t.startsWith(`${Tr}/`)||t.includes(`/${Tr}/`)||t.endsWith(`/${Tr}`)}function On(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?$t(e.slice(2)):e.startsWith("./")||e.startsWith("../")?$t(si(`${Lp(t)}/${e}`)):$t(e):!1}function si(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 Lp(e){let t=si(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}var jp=typeof ai=="function"?ai:ai.default;function we(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 Bp(e){return/^[A-Z]/.test(e)}function pi(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 ln(e){return x.isJSXFragment(e)}function cc(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 $p(e){return e.split(".")[0]??e}function Vp(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 Up(){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 Kp(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 Nr(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 Jp(e,t,n){e.set(t,{resolved:!0,value:n})}function mi(e,t){e.set(t,{resolved:!1})}function uc(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 Re(e,t,n){if(x.isTSAsExpression(e)||x.isTSSatisfiesExpression(e)||x.isTSNonNullExpression(e)||x.isTypeCastExpression(e)||x.isParenthesizedExpression(e))return Re(e.expression,t,n);if(x.isLogicalExpression(e))return ci([Re(e.left,t,n),Re(e.right,t,n)]);if(x.isConditionalExpression(e))return ci([Re(e.consequent,t,n),Re(e.alternate,t,n)]);if(x.isTemplateLiteral(e))return ci(e.expressions.filter(x.isExpression).map(i=>Re(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=Ut(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 ci(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 Ut(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=Nr(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=Ut(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=Nr(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=Ut(r.value,t);if(i===void 0)return;n[o]=i}return n}if(x.isMemberExpression(e)){let n=Re(e,"",t);if(!n)return;let r=Nr(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=uc(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(x.isCallExpression(e))return fc(e,t)??void 0}function dc(e,t,n){let r=Re(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=Nr(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?uc(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 li(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:Up(),parentStack:[],valueScopes:i,importMap:o}}function di(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of dt(o.id))mi(n,s);if(!x.isIdentifier(o.id)||!o.init||!x.isExpression(o.init))continue;let i=Ut(o.init,t);i!==void 0&&Jp(n,o.id.name,i)}}function Xp(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 zp(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:we(i),editable:!0,source:null})}else if(x.isJSXExpressionContainer(i)&&x.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:we(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:we(i),editable:!0,source:null}):r.push({index:o++,value:St(s,n),sourceRange:we(i),editable:!0,source:Re(s,n,t)})}else if(x.isJSXExpressionContainer(i)&&x.isExpression(i.expression)){let s=dc(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:we(i),editable:!0,source:s.source})}return r}function Hp(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:we(o),source:null});continue}if(x.isJSXExpressionContainer(o.value)&&x.isExpression(o.value.expression)){let i=Ut(o.value.expression,t);if(o.name.name==="className"){let a=typeof i=="string"?i:i===void 0?fc(o.value.expression,t):null;if(a){r.push({name:o.name.name,value:a,sourceRange:we(o),source:null,resolvedValue:a});continue}}let s=dc(o.value.expression,t,n);if(i!==void 0&&typeof i!="string"&&typeof i!="number"){r.push({name:o.name.name,value:sc(i),sourceRange:we(o),source:Re(o.value.expression,n,t),resolvedValue:i});continue}if(!s){i!==void 0&&r.push({name:o.name.name,value:sc(i),sourceRange:we(o),source:Re(o.value.expression,n,t),resolvedValue:i});continue}r.push({name:o.name.name,value:s.value,sourceRange:we(o),source:s.source})}}return r}function fc(e,t){let n=cn(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function cn(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=Ut(e,t);return typeof n=="string"?[n]:null}if(x.isConditionalExpression(e)){let n=cn(e.consequent,t),r=cn(e.alternate,t);return!n||!r?null:[...n,...r]}if(x.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=Ut(e.left,t);return n===!1||n===null?[]:cn(e.right,t)}if(x.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||x.isSpreadElement(r))return null;let o=cn(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=Yp(r.key);if(!o)return null;n.push(o)}return n}if(x.isCallExpression(e)){let n=Wp(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=cn(o,t);if(!i)return null;r.push(...i)}return r}return null}function Wp(e){return x.isIdentifier(e)?e.name:x.isMemberExpression(e)&&x.isIdentifier(e.property)?e.property.name:null}function Yp(e){return x.isIdentifier(e)?e.name:x.isStringLiteral(e)?e.value:null}function Gp(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 Zp(e,t){for(let n of t){let r=Gp(e,n);if(r)return r}return null}function Qp(e){return x.isJSXIdentifier(e.name)?e.name.name:null}function sc(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function qp(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 ui(e){return x.isArrowFunctionExpression(e)||x.isFunctionExpression(e)}function em(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function tm(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function ac(e,t,n,r){if(!e||!x.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:St(e,n),collectionSource:Re(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(pi(e))return Dr(e.children,t,n);let r=_r(e,t,n);return r?[r]:[]}return ln(e)?Or(e,t,n):x.isParenthesizedExpression(e)?bt(e.expression,t,n):x.isExpression(e)?Lr(e,t,n):[]}function Fr(e,t,n){let r=new Map;for(let o of e.params)for(let i of dt(o))mi(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 pc(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function pc(e,t,n){let r=[];for(let o of e){if(x.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];i&&di([o],t,i);continue}r.push(...fi(o,t,n))}return r}function fi(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):fi(e.consequent,t,n),o=e.alternate?x.isBlockStatement(e.alternate)?Vt(e.alternate.body,t,n):fi(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 pc(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:we(r),sourceCandidates:i&&i.length>0?i:void 0})}function nm(e,t,n,r){let o=Zp(e.openingElement,["items","dataSource","data"]),i={key:t,tag:cc(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!x.isJSXAttribute(s))continue;let a=Qp(s);if(!a||!x.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!x.isJSXEmptyExpression(c)){if(em(a)&&ui(c)){let l=Fr(c,n,r),u=ac(o,c,r,n);Mr(n,"repeat-region",t,s,l,u?[u]:void 0);continue}if(tm(a)){let l=ui(c)?Fr(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)||!ui(s.expression))continue;let a=Fr(s.expression,n,r),c=ac(o,s.expression,r,n);Mr(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function _r(e,t,n){let r=cc(e.openingElement);if(r==="Fragment"||pi(e))return Dr(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=Bp(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=_n(t.file,t.componentName,l),d={file:t.file,component:t.componentName,structuralPath:l,key:u},m=s?"component-boundary":null,p=zp(e.children,t,n),h=Hp(e.openingElement,t,n),E,v,C=!1;if(s){let w=t.importMap.get(r)??t.importMap.get($p(r));w&&(E=w.specifier,v=w.exportName,C=On(w.specifier,t.file))}let R={identity:d,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:we(e),parentKey:i,childKeys:[],textSegments:p,attributes:h.length>0?h:void 0,boundaryKind:m,isOpaque:s,...C?{isPublicUiComponent:!0}:{},importedFrom:E,exportName:v};return t.elements.set(u,R),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(u),nm(e,u,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:u,tag:r}),rm(e.children,t,n),t.parentStack.pop()),u}function Or(e,t,n){return Dr(e.children,t,n)}function Dr(e,t,n){let r=[];for(let o of e)if(x.isJSXElement(o))if(pi(o))r.push(...Dr(o.children,t,n));else{let i=_r(o,t,n);i&&r.push(i)}else ln(o)?r.push(...Or(o,t,n)):x.isJSXExpressionContainer(o)&&r.push(...Lr(o.expression,t,n));return r}function rm(e,t,n){for(let r of e)x.isJSXElement(r)?_r(r,t,n):ln(r)?Or(r,t,n):x.isJSXExpressionContainer(r)&&Lr(r.expression,t,n)}function om(e){return e==="&&"||e==="||"||e==="??"}function Lr(e,t,n){if(x.isJSXEmptyExpression(e))return[];let r=qp(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:Re(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:we(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(l),(x.isArrowFunctionExpression(a)||x.isFunctionExpression(a))&&l.childKeys.push(...Fr(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:Re(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:we(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)&&om(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:St(e.left,n),conditionSource:Re(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:we(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...bt(e.right,t,n)),s.childKeys}if(x.isParenthesizedExpression(e))return Lr(e.expression,t,n);if(x.isJSXElement(e)){let o=_r(e,t,n);return o?[o]:[]}return ln(e)?Or(e,t,n):[]}function im(e){let t=e.argument;return t&&(x.isExpression(t)||ln(t))?t:null}function Dn(e,t){let n=[];for(let r of e){if(x.isReturnStatement(r)){let o=im(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(...Dn(o,r.test)),r.alternate){let i=x.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...Dn(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(...Dn(o.consequent,i))}}return n}function mc(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=Kp(r);jp(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(d){let m=Vp(d);if(!m)return;let p=d.node,h=[];if(x.isArrowFunctionExpression(p))x.isExpression(p.body)||ln(p.body)?h=[{argument:p.body,statement:x.returnStatement(x.isExpression(p.body)?p.body:null)}]:x.isBlockStatement(p.body)&&(h=Dn(p.body.body));else{let z=p.body;x.isBlockStatement(z)&&(h=Dn(z.body))}if(h.length===0){d.skip();return}let E=new Map;di(Xp(r.program.body),li(t,m,i,s,l,[E]),E);let v=new Map;for(let z of p.params)for(let te of dt(z))mi(v,te);let C=x.isBlockStatement(p.body)?p.body.body:[],R=h[0]?.statement??null;for(let z of C){if(R&&z===R)break;x.isVariableDeclaration(z)&&di([z],li(t,m,i,s,l,[E,v]),v)}let w=li(t,m,i,s,l,[E,v]);for(let z of h){let te=bt(z.argument,w,n);for(let le of te)a.includes(le)||a.push(le);if(z.condition){let le={kind:"conditional-branch",conditionExpression:St(z.condition,n),conditionSource:Re(z.condition,n,w)};Mr(w,"conditional-region","",z.statement,te,[le])}}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 hi(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function jr(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function hc(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??ii,c=new Map,l=new Map,u=new Map,d=[],m=new Set,p=C=>{let R=`${C.path}\0${C.code}\0${C.message}\0${JSON.stringify(C.details??{})}`;m.has(R)||(m.add(R),d.push(C))},h=[{file:e,source:t,depth:0,diagnosticEntryFile:e,importStack:[]},...(o.additionalEntries??[]).map(C=>({file:C.file,source:C.source,depth:0,diagnosticEntryFile:C.file,importStack:[]}))],E=new Set;for(;h.length>0;){let C=h.shift(),{file:R,source:w,depth:z,diagnosticEntryFile:te,importStack:le}=C;if(E.has(R))continue;E.add(R),c.set(R,w);let A=a(R,w);if(!A.ok){p(jr(A.diagnostic,te,le));continue}u.set(R,A.module);let{graph:M,localImports:O}=mc(A.module);for(let j of M.elements.values())if(j.importedFrom&&ut(j.importedFrom)){let ee=j.importedFrom,G=await Ar(R,ee,r);G.ok?(j.importedFrom=G.path,$t(G.path)&&(j.isPublicUiComponent=!0)):On(ee,R)||p(jr(G.diagnostic,te,hi(le,R,ee,G.diagnostic.path)))}if(l.set(R,M),!(z>=i))for(let j of O){if(sm(j))continue;let ee=await Ar(R,j,r);if(!ee.ok){On(j,R)||p(jr(ee.diagnostic,te,hi(le,R,j,ee.diagnostic.path)));continue}let G=ee.path;if(E.has(G)||$t(G))continue;let xe=hi(le,R,j,G);try{let W=await n(G);h.push({file:G,source:W,depth:z+1,diagnosticEntryFile:te,importStack:xe})}catch(W){p(jr({path:G,code:"import-read-failed",message:`Failed to read imported file: ${G}`,details:{fromFile:R,specifier:j,reason:W instanceof Error?W.message:String(W)}},te,xe))}}}let v=am(e,l,s,(o.additionalEntries??[]).map(C=>C.file));return v.diagnostics=d,{graph:v,allSources:c,diagnostics:d,parsedModules:u,entryModule:u.get(e)??null}}function sm(e){return/\.(?:css|scss|sass|less)(?:\?.*)?$/i.test(e)}function am(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 gc(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}),yc(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function yc(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}),yc(s,t,n,r,o))}}import{isSiteEditRuntimeContainerTag as cm,isSiteEditRuntimeVoidElementTag as lm}from"@vcp-dev/contracts/site-edit-runtime-capability";function um(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(w=>({kind:w.kind,message:w.reason})),s=o.isOpaque,c=r.parentKey===null&&o.componentName==="Page",l=o.tag.toLowerCase(),u=o.tag!==l,d=!u&&lm(l),m=u||cm(l),p=u&&o.childKeys.length>0&&!o.isPublicUiComponent,h=o.textSegments.length>0&&o.textSegments.some(w=>w.editable);d&&!i.some(w=>w.kind==="void-element")&&i.push({kind:"void-element",message:`Element '${o.tag}' is void: children cannot be inserted`}),!d&&!m&&!i.some(w=>w.kind==="void-element")&&i.push({kind:"void-element",message:`Element '${o.tag}' cannot contain structured children`});let E=h&&!s,v=!o.isPublicUiComponent&&!d&&m&&(!s||p);return{key:e,canUpdateText:E,canInsertChild:v,canMove:!c,canRemove:!c,constraints:i}}function xc(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,um(r,e,t));return n}import{createHash as Vi}from"node:crypto";import Oi from"@babel/traverse";function gi(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 Dh}from"node:crypto";import Zc from"node:path";import*as eo from"@babel/parser";import Ti from"@babel/generator";import Ni from"@babel/traverse";import*as Ct from"@babel/types";import yi from"@babel/traverse";var It=typeof yi=="function"?yi:yi.default,Br=new WeakMap,Ec=new WeakMap;function pt(e,t){let n=ni(e,t);if(!n.ok)return ti(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=re(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}}:ti(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function re(e,t){return t.kind==="jsx-node"?kc(e,t):t.kind==="jsx-attribute"?gm(e,t):t.kind==="value"?ym(e,t):t.kind==="expression"?xm(e,t):t.kind==="directive"?Em(e,t):t.kind==="export"?Sm(e,t):{ok:!1,diagnostic:jt("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function kc(e,t){return t.strategy==="source-range"?dm(e,t):fm(e,t)}function dm(e,t){let n=null;if(It(e,{JSXElement(o){if(!dn(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(!dn(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(!dn(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&&!Nm(r.path,t.expectedIdentity)?be("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function fm(e,t){if(t.structuralPath===""){let r=mm(e,t.component);if(r){let o=hm(r);if(o)return o}}let n=null;return It(e,{JSXElement(r){if(jn(r)!==t.component||Ei(r)!==t.structuralPath)return;let i=Ee("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(jn(r)!==t.component||Ei(r)!==t.structuralPath)return;let i=Ee("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=pm(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:be("jsx-node","locator-miss","JSX node not found for structural-path locator")}function pm(e,t,n){let r=null;return It(e,{JSXElement(o){if(jn(o)!==t||!dn(o.node,n))return;let i=Ee("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(jn(o)!==t||!dn(o.node,n))return;let i=Ee("jsx-node",o);i&&(r=i,o.stop())}}),r}function mm(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 hm(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 gm(e,t){let n=kc(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>Fm(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 ym(e,t){let n=bm(e,t);if(!n.ok)return n;let r=Im(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 xm(e,t){let n=null;return It(e,{Identifier(r){if(!Pm(r))return;let o=bc(r);if(!o||!Ic(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=bc(r);if(!o||!Ic(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 Em(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 Sm(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=Si(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=Si(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 '${Tm(t)}' not found`)}function bm(e,t){let n=null;return It(e,{Expression(r){if(n||t.root.kind!=="expression"||!dn(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=Si(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 Im(e,t){let n=xi(e);for(let o of t){if(n=xi(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=>Mm(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=xi(n);let r=Ee("value",n);return r?{ok:!0,match:r}:be("value","locator-miss","Resolved value has no source range")}function xi(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 dn(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 Ei(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!$r(n.node)){let o=Cc(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${Sc(n,o)}`):t.unshift(`${o}#${Sc(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||Rm(n.parentPath))break;n=n.parentPath}return t.join("/")}function $r(e){let t=e.openingElement.name;return t.type==="JSXIdentifier"?t.name==="Fragment":t.type==="JSXMemberExpression"&&t.property.name==="Fragment"}function Sc(e,t){let n=km(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 Ln(n))if(Cc(s.node.openingElement)===t){if(i.set(s.node,o),s.node===e.node)return o;o++}return i.get(e.node)??0}function km(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if($r(t.node)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Ln(e){let t=Ec.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($r(o.node)){n.push(...Ln(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Ln(o));continue}o.isJSXExpressionContainer()&&n.push(...un(o.get("expression")))}return Ec.set(e.node,n),n}function un(e){return e.isJSXElement()?$r(e.node)?Ln(e):[e]:e.isJSXFragment()?Ln(e):e.isParenthesizedExpression()?un(e.get("expression")):e.isLogicalExpression()&&Cm(e.node.operator)?un(e.get("right")):e.isConditionalExpression()?[...un(e.get("consequent")),...un(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:un(t)):[]}function Cm(e){return e==="&&"||e==="||"||e==="??"}function Cc(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?vm(e.name):null}function vm(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 jn(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 Rm(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function Pm(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function bc(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 Ic(e,t){return e.base===t.base&&wm(e.path,t.path??[])}function wm(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 Am(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function Tm(e){return e.exportKind==="named"?e.name:e.exportKind}function be(e,t,n,r){return{ok:!1,diagnostic:jt(t,n,e,r)}}function Nm(e,t){return jn(e)!==t.component?!1:Ei(e)===t.structuralPath}function Fm(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function Si(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function Mm(e,t){return e.isObjectProperty()?Am(e.node)===t:!1}import bi from"@babel/generator";var _m=typeof bi=="function"?bi:bi.default;function Om(e){let t=e.split(`
1
+ import{SiteEditOperationRequestSchema as wI,SiteEditPatchPlanSchema as AI}from"@vcp-dev/contracts";function Lt(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 vr(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 Rr(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 Pr(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:Ap(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 wr(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:Lt(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 Ap(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 xb,getSiteEditSourceDeleteProtectionReason as Eb,isSiteEditTextSourcePath as Sb,parseSiteEditRepeatInstanceKey as bb,SITE_EDIT_SOURCE_DELETE_CAPABILITY as Ib,stripSiteEditRepeatInstanceKeys as Xe}from"@vcp-dev/contracts";import{parse as kb}from"yaml";import Ao from"node:path";function _n(e,t,n){return`${e}::${t}::${n}`}var j={NODE_NOT_FOUND:"NODE_NOT_FOUND",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 ai from"@babel/traverse";import*as x from"@babel/types";import{createHash as Dp}from"node:crypto";import*as rc from"@babel/parser";function jt(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:jt(t,n,r,o)}}function ti(e,t,n,r,o){return{ok:!1,source:e,diagnostic:jt(t,n,r,o)}}var Tp={"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:rc.parse(t,{sourceType:"module",plugins:Tp[n]})}}catch(r){return{ok:!1,source:t,diagnostic:jt("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function ni(e,t){return it({source:e,profile:oc(t.kind)})}function ri(e,t){return it({source:e,profile:oc(t)})}function oc(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 Np from"@babel/parser";import*as sn from"@babel/types";import*as Et from"node:path";var oi=[".tsx",".ts",".jsx",".js"],Fp=oi.map(e=>`/index${e}`);function ic(e){let t=[];for(let n of e.program.body)sn.isImportDeclaration(n)&&typeof n.source.value=="string"&&ut(n.source.value)&&t.push(n.source.value),sn.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&ut(n.source.value)&&t.push(n.source.value),sn.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&ut(n.source.value)&&t.push(n.source.value);return t}function ut(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function Mp(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 _p(e,t){if(oi.some(n=>e.endsWith(n))&&await t(e))return e;for(let n of oi){let r=`${e}${n}`;if(await t(r))return r}for(let n of Fp){let r=`${e}${n}`;if(await t(r))return r}return null}async function an(e,t,n){let r=await Ar(e,t,n);return r.ok?r.path:null}async function Ar(e,t,n){let r=Mp(e,t);try{if(!Op(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 _p(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 Op(e,t,n){if(!ut(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 ii=(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:${Dp("sha256").update(t).digest("hex")}`,ast:n.ast,imports:ic(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};var Tr="components/ui";function $t(e){if(!e)return!1;let t=si(e);return t===Tr||t.startsWith(`${Tr}/`)||t.includes(`/${Tr}/`)||t.endsWith(`/${Tr}`)}function On(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?$t(e.slice(2)):e.startsWith("./")||e.startsWith("../")?$t(si(`${Lp(t)}/${e}`)):$t(e):!1}function si(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 Lp(e){let t=si(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}var jp=typeof ai=="function"?ai:ai.default;function we(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 Bp(e){return/^[A-Z]/.test(e)}function pi(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 ln(e){return x.isJSXFragment(e)}function cc(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 $p(e){return e.split(".")[0]??e}function Vp(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 Up(){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 Kp(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 Nr(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 Jp(e,t,n){e.set(t,{resolved:!0,value:n})}function mi(e,t){e.set(t,{resolved:!1})}function uc(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 Re(e,t,n){if(x.isTSAsExpression(e)||x.isTSSatisfiesExpression(e)||x.isTSNonNullExpression(e)||x.isTypeCastExpression(e)||x.isParenthesizedExpression(e))return Re(e.expression,t,n);if(x.isLogicalExpression(e))return ci([Re(e.left,t,n),Re(e.right,t,n)]);if(x.isConditionalExpression(e))return ci([Re(e.consequent,t,n),Re(e.alternate,t,n)]);if(x.isTemplateLiteral(e))return ci(e.expressions.filter(x.isExpression).map(i=>Re(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=Ut(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 ci(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 Ut(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=Nr(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=Ut(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=Nr(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=Ut(r.value,t);if(i===void 0)return;n[o]=i}return n}if(x.isMemberExpression(e)){let n=Re(e,"",t);if(!n)return;let r=Nr(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=uc(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(x.isCallExpression(e))return fc(e,t)??void 0}function dc(e,t,n){let r=Re(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=Nr(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?uc(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 li(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:Up(),parentStack:[],valueScopes:i,importMap:o}}function di(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of dt(o.id))mi(n,s);if(!x.isIdentifier(o.id)||!o.init||!x.isExpression(o.init))continue;let i=Ut(o.init,t);i!==void 0&&Jp(n,o.id.name,i)}}function Xp(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 zp(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:we(i),editable:!0,source:null})}else if(x.isJSXExpressionContainer(i)&&x.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:we(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:we(i),editable:!0,source:null}):r.push({index:o++,value:St(s,n),sourceRange:we(i),editable:!0,source:Re(s,n,t)})}else if(x.isJSXExpressionContainer(i)&&x.isExpression(i.expression)){let s=dc(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:we(i),editable:!0,source:s.source})}return r}function Hp(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:we(o),source:null});continue}if(x.isJSXExpressionContainer(o.value)&&x.isExpression(o.value.expression)){let i=Ut(o.value.expression,t);if(o.name.name==="className"){let a=typeof i=="string"?i:i===void 0?fc(o.value.expression,t):null;if(a){r.push({name:o.name.name,value:a,sourceRange:we(o),source:null,resolvedValue:a});continue}}let s=dc(o.value.expression,t,n);if(i!==void 0&&typeof i!="string"&&typeof i!="number"){r.push({name:o.name.name,value:sc(i),sourceRange:we(o),source:Re(o.value.expression,n,t),resolvedValue:i});continue}if(!s){i!==void 0&&r.push({name:o.name.name,value:sc(i),sourceRange:we(o),source:Re(o.value.expression,n,t),resolvedValue:i});continue}r.push({name:o.name.name,value:s.value,sourceRange:we(o),source:s.source})}}return r}function fc(e,t){let n=cn(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function cn(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=Ut(e,t);return typeof n=="string"?[n]:null}if(x.isConditionalExpression(e)){let n=cn(e.consequent,t),r=cn(e.alternate,t);return!n||!r?null:[...n,...r]}if(x.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=Ut(e.left,t);return n===!1||n===null?[]:cn(e.right,t)}if(x.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||x.isSpreadElement(r))return null;let o=cn(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=Yp(r.key);if(!o)return null;n.push(o)}return n}if(x.isCallExpression(e)){let n=Wp(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=cn(o,t);if(!i)return null;r.push(...i)}return r}return null}function Wp(e){return x.isIdentifier(e)?e.name:x.isMemberExpression(e)&&x.isIdentifier(e.property)?e.property.name:null}function Yp(e){return x.isIdentifier(e)?e.name:x.isStringLiteral(e)?e.value:null}function Gp(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 Zp(e,t){for(let n of t){let r=Gp(e,n);if(r)return r}return null}function Qp(e){return x.isJSXIdentifier(e.name)?e.name.name:null}function sc(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function qp(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 ui(e){return x.isArrowFunctionExpression(e)||x.isFunctionExpression(e)}function em(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function tm(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function ac(e,t,n,r){if(!e||!x.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:St(e,n),collectionSource:Re(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(pi(e))return Dr(e.children,t,n);let r=_r(e,t,n);return r?[r]:[]}return ln(e)?Or(e,t,n):x.isParenthesizedExpression(e)?bt(e.expression,t,n):x.isExpression(e)?Lr(e,t,n):[]}function Fr(e,t,n){let r=new Map;for(let o of e.params)for(let i of dt(o))mi(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 pc(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function pc(e,t,n){let r=[];for(let o of e){if(x.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];i&&di([o],t,i);continue}r.push(...fi(o,t,n))}return r}function fi(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):fi(e.consequent,t,n),o=e.alternate?x.isBlockStatement(e.alternate)?Vt(e.alternate.body,t,n):fi(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 pc(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:we(r),sourceCandidates:i&&i.length>0?i:void 0})}function nm(e,t,n,r){let o=Zp(e.openingElement,["items","dataSource","data"]),i={key:t,tag:cc(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!x.isJSXAttribute(s))continue;let a=Qp(s);if(!a||!x.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!x.isJSXEmptyExpression(c)){if(em(a)&&ui(c)){let l=Fr(c,n,r),u=ac(o,c,r,n);Mr(n,"repeat-region",t,s,l,u?[u]:void 0);continue}if(tm(a)){let l=ui(c)?Fr(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)||!ui(s.expression))continue;let a=Fr(s.expression,n,r),c=ac(o,s.expression,r,n);Mr(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function _r(e,t,n){let r=cc(e.openingElement);if(r==="Fragment"||pi(e))return Dr(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=Bp(r),a;if(s){let R=t.ordinalTracker.getOrdinal(i,r);a=`component:${r}#${R}`}else{let R=t.ordinalTracker.getOrdinal(i,r);a=`${r}#${R}`}let c=o?t.elements.get(o.key)?.identity.structuralPath:void 0,l=c?`${c}/${a}`:a,u=_n(t.file,t.componentName,l),d={file:t.file,component:t.componentName,structuralPath:l,key:u},m=s?"component-boundary":null,p=zp(e.children,t,n),h=Hp(e.openingElement,t,n),E,v,C=!1;if(s){let R=t.importMap.get(r)??t.importMap.get($p(r));R&&(E=R.specifier,v=R.exportName,C=On(R.specifier,t.file))}let A={identity:d,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:we(e),parentKey:i,childKeys:[],textSegments:p,attributes:h.length>0?h:void 0,boundaryKind:m,isOpaque:s,...C?{isPublicUiComponent:!0}:{},importedFrom:E,exportName:v};return t.elements.set(u,A),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(u),nm(e,u,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:u,tag:r}),rm(e.children,t,n),t.parentStack.pop()),u}function Or(e,t,n){return Dr(e.children,t,n)}function Dr(e,t,n){let r=[];for(let o of e)if(x.isJSXElement(o))if(pi(o))r.push(...Dr(o.children,t,n));else{let i=_r(o,t,n);i&&r.push(i)}else ln(o)?r.push(...Or(o,t,n)):x.isJSXExpressionContainer(o)&&r.push(...Lr(o.expression,t,n));return r}function rm(e,t,n){for(let r of e)x.isJSXElement(r)?_r(r,t,n):ln(r)?Or(r,t,n):x.isJSXExpressionContainer(r)&&Lr(r.expression,t,n)}function om(e){return e==="&&"||e==="||"||e==="??"}function Lr(e,t,n){if(x.isJSXEmptyExpression(e))return[];let r=qp(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:Re(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:we(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(l),(x.isArrowFunctionExpression(a)||x.isFunctionExpression(a))&&l.childKeys.push(...Fr(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:Re(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:we(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)&&om(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:St(e.left,n),conditionSource:Re(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:we(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...bt(e.right,t,n)),s.childKeys}if(x.isParenthesizedExpression(e))return Lr(e.expression,t,n);if(x.isJSXElement(e)){let o=_r(e,t,n);return o?[o]:[]}return ln(e)?Or(e,t,n):[]}function im(e){let t=e.argument;return t&&(x.isExpression(t)||ln(t))?t:null}function Dn(e,t){let n=[];for(let r of e){if(x.isReturnStatement(r)){let o=im(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(...Dn(o,r.test)),r.alternate){let i=x.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...Dn(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(...Dn(o.consequent,i))}}return n}function mc(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=Kp(r);jp(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(d){let m=Vp(d);if(!m)return;let p=d.node,h=[];if(x.isArrowFunctionExpression(p))x.isExpression(p.body)||ln(p.body)?h=[{argument:p.body,statement:x.returnStatement(x.isExpression(p.body)?p.body:null)}]:x.isBlockStatement(p.body)&&(h=Dn(p.body.body));else{let B=p.body;x.isBlockStatement(B)&&(h=Dn(B.body))}if(h.length===0){d.skip();return}let E=new Map;di(Xp(r.program.body),li(t,m,i,s,l,[E]),E);let v=new Map;for(let B of p.params)for(let re of dt(B))mi(v,re);let C=x.isBlockStatement(p.body)?p.body.body:[],A=h[0]?.statement??null;for(let B of C){if(A&&B===A)break;x.isVariableDeclaration(B)&&di([B],li(t,m,i,s,l,[E,v]),v)}let R=li(t,m,i,s,l,[E,v]);for(let B of h){let re=bt(B.argument,R,n);for(let te of re)a.includes(te)||a.push(te);if(B.condition){let te={kind:"conditional-branch",conditionExpression:St(B.condition,n),conditionSource:Re(B.condition,n,R)};Mr(R,"conditional-region","",B.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 hi(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function jr(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function hc(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??ii,c=new Map,l=new Map,u=new Map,d=[],m=new Set,p=C=>{let A=`${C.path}\0${C.code}\0${C.message}\0${JSON.stringify(C.details??{})}`;m.has(A)||(m.add(A),d.push(C))},h=[{file:e,source:t,depth:0,diagnosticEntryFile:e,importStack:[]},...(o.additionalEntries??[]).map(C=>({file:C.file,source:C.source,depth:0,diagnosticEntryFile:C.file,importStack:[]}))],E=new Set;for(;h.length>0;){let C=h.shift(),{file:A,source:R,depth:B,diagnosticEntryFile:re,importStack:te}=C;if(E.has(A))continue;E.add(A),c.set(A,R);let w=a(A,R);if(!w.ok){p(jr(w.diagnostic,re,te));continue}u.set(A,w.module);let{graph:_,localImports:M}=mc(w.module);for(let D of _.elements.values())if(D.importedFrom&&ut(D.importedFrom)){let ee=D.importedFrom,G=await Ar(A,ee,r);G.ok?(D.importedFrom=G.path,$t(G.path)&&(D.isPublicUiComponent=!0)):On(ee,A)||p(jr(G.diagnostic,re,hi(te,A,ee,G.diagnostic.path)))}if(l.set(A,_),!(B>=i))for(let D of M){if(sm(D))continue;let ee=await Ar(A,D,r);if(!ee.ok){On(D,A)||p(jr(ee.diagnostic,re,hi(te,A,D,ee.diagnostic.path)));continue}let G=ee.path;if(E.has(G)||$t(G))continue;let xe=hi(te,A,D,G);try{let W=await n(G);h.push({file:G,source:W,depth:B+1,diagnosticEntryFile:re,importStack:xe})}catch(W){p(jr({path:G,code:"import-read-failed",message:`Failed to read imported file: ${G}`,details:{fromFile:A,specifier:D,reason:W instanceof Error?W.message:String(W)}},re,xe))}}}let v=am(e,l,s,(o.additionalEntries??[]).map(C=>C.file));return v.diagnostics=d,{graph:v,allSources:c,diagnostics:d,parsedModules:u,entryModule:u.get(e)??null}}function sm(e){return/\.(?:css|scss|sass|less)(?:\?.*)?$/i.test(e)}function am(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 gc(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}),yc(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function yc(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}),yc(s,t,n,r,o))}}import{isSiteEditRuntimeContainerTag as cm,isSiteEditRuntimeVoidElementTag as lm}from"@vcp-dev/contracts/site-edit-runtime-capability";function um(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(R=>({kind:R.kind,message:R.reason})),s=o.isOpaque,c=r.parentKey===null&&o.componentName==="Page",l=o.tag.toLowerCase(),u=o.tag!==l,d=!u&&lm(l),m=u||cm(l),p=u&&o.childKeys.length>0&&!o.isPublicUiComponent,h=o.textSegments.length>0&&o.textSegments.some(R=>R.editable);d&&!i.some(R=>R.kind==="void-element")&&i.push({kind:"void-element",message:`Element '${o.tag}' is void: children cannot be inserted`}),!d&&!m&&!i.some(R=>R.kind==="void-element")&&i.push({kind:"void-element",message:`Element '${o.tag}' cannot contain structured children`});let E=h&&!s,v=!o.isPublicUiComponent&&!d&&m&&(!s||p);return{key:e,canUpdateText:E,canInsertChild:v,canMove:!c,canRemove:!c,constraints:i}}function xc(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,um(r,e,t));return n}import{createHash as Vi}from"node:crypto";import Oi from"@babel/traverse";function gi(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 Dh}from"node:crypto";import Zc from"node:path";import*as eo from"@babel/parser";import Ti from"@babel/generator";import Ni from"@babel/traverse";import*as Ct from"@babel/types";import yi from"@babel/traverse";var It=typeof yi=="function"?yi:yi.default,Br=new WeakMap,Ec=new WeakMap;function pt(e,t){let n=ni(e,t);if(!n.ok)return ti(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}}:ti(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function oe(e,t){return t.kind==="jsx-node"?kc(e,t):t.kind==="jsx-attribute"?gm(e,t):t.kind==="value"?ym(e,t):t.kind==="expression"?xm(e,t):t.kind==="directive"?Em(e,t):t.kind==="export"?Sm(e,t):{ok:!1,diagnostic:jt("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function kc(e,t){return t.strategy==="source-range"?dm(e,t):fm(e,t)}function dm(e,t){let n=null;if(It(e,{JSXElement(o){if(!dn(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(!dn(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(!dn(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&&!Nm(r.path,t.expectedIdentity)?be("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function fm(e,t){if(t.structuralPath===""){let r=mm(e,t.component);if(r){let o=hm(r);if(o)return o}}let n=null;return It(e,{JSXElement(r){if(jn(r)!==t.component||Ei(r)!==t.structuralPath)return;let i=Ee("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(jn(r)!==t.component||Ei(r)!==t.structuralPath)return;let i=Ee("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=pm(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:be("jsx-node","locator-miss","JSX node not found for structural-path locator")}function pm(e,t,n){let r=null;return It(e,{JSXElement(o){if(jn(o)!==t||!dn(o.node,n))return;let i=Ee("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(jn(o)!==t||!dn(o.node,n))return;let i=Ee("jsx-node",o);i&&(r=i,o.stop())}}),r}function mm(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 hm(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 gm(e,t){let n=kc(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>Fm(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 ym(e,t){let n=bm(e,t);if(!n.ok)return n;let r=Im(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 xm(e,t){let n=null;return It(e,{Identifier(r){if(!Pm(r))return;let o=bc(r);if(!o||!Ic(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=bc(r);if(!o||!Ic(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 Em(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 Sm(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=Si(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=Si(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 '${Tm(t)}' not found`)}function bm(e,t){let n=null;return It(e,{Expression(r){if(n||t.root.kind!=="expression"||!dn(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=Si(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 Im(e,t){let n=xi(e);for(let o of t){if(n=xi(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=>Mm(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=xi(n);let r=Ee("value",n);return r?{ok:!0,match:r}:be("value","locator-miss","Resolved value has no source range")}function xi(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 dn(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 Ei(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!$r(n.node)){let o=Cc(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${Sc(n,o)}`):t.unshift(`${o}#${Sc(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||Rm(n.parentPath))break;n=n.parentPath}return t.join("/")}function $r(e){let t=e.openingElement.name;return t.type==="JSXIdentifier"?t.name==="Fragment":t.type==="JSXMemberExpression"&&t.property.name==="Fragment"}function Sc(e,t){let n=km(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 Ln(n))if(Cc(s.node.openingElement)===t){if(i.set(s.node,o),s.node===e.node)return o;o++}return i.get(e.node)??0}function km(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if($r(t.node)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Ln(e){let t=Ec.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($r(o.node)){n.push(...Ln(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Ln(o));continue}o.isJSXExpressionContainer()&&n.push(...un(o.get("expression")))}return Ec.set(e.node,n),n}function un(e){return e.isJSXElement()?$r(e.node)?Ln(e):[e]:e.isJSXFragment()?Ln(e):e.isParenthesizedExpression()?un(e.get("expression")):e.isLogicalExpression()&&Cm(e.node.operator)?un(e.get("right")):e.isConditionalExpression()?[...un(e.get("consequent")),...un(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:un(t)):[]}function Cm(e){return e==="&&"||e==="||"||e==="??"}function Cc(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?vm(e.name):null}function vm(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 jn(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 Rm(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function Pm(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function bc(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 Ic(e,t){return e.base===t.base&&wm(e.path,t.path??[])}function wm(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 Am(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function Tm(e){return e.exportKind==="named"?e.name:e.exportKind}function be(e,t,n,r){return{ok:!1,diagnostic:jt(t,n,e,r)}}function Nm(e,t){return jn(e)!==t.component?!1:Ei(e)===t.structuralPath}function Fm(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function Si(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function Mm(e,t){return e.isObjectProperty()?Am(e.node)===t:!1}import bi from"@babel/generator";var _m=typeof bi=="function"?bi:bi.default;function Om(e){let t=e.split(`
2
2
  `),n=[],r=!1;for(let s of t){let a=s.match(/^(\s+)/);if(a){let c=a[1];c.includes(" ")?r=!0:c.length>0&&n.push(c.length)}}if(r&&t.every(a=>{let c=a.match(/^(\s+)/);return!c||c[1].includes(" ")}))return"tab";if(n.length===0)return"2";function o(s,a){return a===0?s:o(a,s%a)}let i=n[0];for(let s=1;s<n.length;s++)i=o(i,n[s]);return i>=4?"4":"2"}function Dm(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 Lm(e,t){return e.split(`
3
3
  `).map(r=>Dm(r,t)).join(`
4
- `)}function Vr(e){let{ast:t,source:n}=e;try{let r=Om(n),i=_m(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=Lm(i,r)),{ok:!0,source:i}}catch(r){return $(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}import*as Rc from"@babel/parser";import{arrayExpression as jm,booleanLiteral as Bm,identifier as $m,jsxAttribute as Vm,jsxExpressionContainer as Um,jsxIdentifier as Km,nullLiteral as Jm,numericLiteral as Xm,objectExpression as zm,objectProperty as Hm,stringLiteral as Pc}from"@babel/types";function vc(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:vc(e),afterSourceHash:vc(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=ri(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function Ur(e,t){return Vr({ast:e,source:t})}function Wm(e,t,n){let r=re(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function wc(e,t,n){let r=Wm(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:$(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function Ac(e,t){let n=re(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 fn(e){return typeof e=="string"?Pc(e):typeof e=="number"?Xm(e):typeof e=="boolean"?Bm(e):e===null?Jm():Array.isArray(e)?jm(e.map(t=>fn(t))):zm(Object.entries(e).map(([t,n])=>Hm($m(t),fn(n))))}function Ym(e){return typeof e=="string"?Pc(e):Um(fn(e))}function Kr(e,t){return Vm(Km(e),Ym(t))}function Tc(e,t){try{let r=Rc.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:$(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:$(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function Jr(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=Ie(t,"jsx-node");if(!i.ok)return i.result;let s=re(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let c=Gm(s.match.path)[r];if(!c)return $(t,"locator-miss",`Text segment ${r} not found`,"jsx-node");switch(c.kind){case"jsx-text":c.path.node.value=Zm(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 Gm(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=Qm(r.get("expression"));o.length>0&&t.push(...o)}}return t}function Zm(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function Qm(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 Ii}from"@babel/types";function pn(e){let{source:t,locator:n}=e,r=Ie(t,"jsx-node");if(!r.ok)return r.result;let o=re(r.ast,n);return o.ok?(qm(o.match.path),de(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function qm(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Ii());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Ii());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Ii());return}e.remove()}import{cloneNode as uh}from"@babel/types";import ki from"@babel/traverse";import*as V from"@babel/types";var eh=typeof ki=="function"?ki:ki.default;function Ve(e,t,n,r){if(!e.ok)return e;let o=$e(n);if(!o)return e;let i=th(t,o,r);return i?{...e,selectionRef:i}:e}function th(e,t,n){let r=nh(e,t);if(!r)return;let o=n.sourceLocator?Nc(n.sourceLocator):void 0,i=n.targetParentLocator?Nc(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??oh(r)??i?.component??o?.component;if(!(!s||!a))return{key:_n(s,a,ih(r))}}function Nc(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function nh(e,t){let n=null;return eh(e,{JSXElement(r){r.node===t&&(n=r,r.stop())}}),n}function $e(e){if(!e)return null;if(V.isJSXElement(e))return mn(e)?Fc(e.children):e;if(V.isJSXFragment(e))return Fc(e.children);if(V.isJSXExpressionContainer(e)||V.isParenthesizedExpression(e)||V.isTSAsExpression(e)||V.isTSSatisfiesExpression(e)||V.isTSTypeAssertion(e)||V.isTSNonNullExpression(e))return $e(e.expression);if(V.isLogicalExpression(e))return $e(e.right);if(V.isConditionalExpression(e))return $e(e.consequent)??$e(e.alternate);if(V.isCallExpression(e)||V.isOptionalCallExpression(e))return Lc(e)?rh(e.arguments[0]):null;if(V.isArrayExpression(e))for(let t of e.elements){if(!t)continue;let n=$e(t);if(n)return n}return null}function Fc(e){for(let t of e){let n=$e(t);if(n)return n}return null}function rh(e){return!e||!V.isArrowFunctionExpression(e)&&!V.isFunctionExpression(e)?null:V.isBlockStatement(e.body)?$n(e.body.body):$e(e.body)}function $n(e){for(let t of e){if(V.isReturnStatement(t)){let n=$e(t.argument);if(n)return n;continue}if(V.isBlockStatement(t)){let n=$n(t.body);if(n)return n;continue}if(V.isIfStatement(t)){let n=Mc(t.consequent);if(n)return n;let r=t.alternate?Mc(t.alternate):null;if(r)return r;continue}if(V.isSwitchStatement(t))for(let n of t.cases){let r=$n(n.consequent);if(r)return r}}return null}function Mc(e){return V.isBlockStatement(e)?$n(e.body):$n([e])}function oh(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 _c=new WeakMap,Oc=new WeakMap,Ci=new WeakMap;function ih(e){let t=_c.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=sh(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return _c.set(e.node,o),o}function sh(e){let t=vi(e.node.openingElement.name);return!t||mn(e.node)?null:/^[A-Z]/.test(t)?`component:${t}#${Dc(e,t)}`:`${t}#${Dc(e,t)}`}function Dc(e,t){let n=ah(e);if(!n)return 0;let r=Ci.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Ci.get(n.node);o||(o=new Map,Ci.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of Kt(n))if(vi(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 ah(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(mn(t.node)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Kt(e){let t=Oc.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(mn(o.node)){n.push(...Kt(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Kt(o));continue}o.isJSXExpressionContainer()&&n.push(...mt(o.get("expression")))}return Oc.set(e.node,n),n}function mt(e){if(e.isJSXElement())return mn(e.node)?Kt(e):[e];if(e.isJSXFragment())return Kt(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())&&Lc(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?ch(n):[]}return[]}function ch(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return mn(t.node)?Kt(t):[t];if(t.isJSXFragment())return Kt(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 Lc(e){let t=e.callee;return(V.isMemberExpression(t)||V.isOptionalMemberExpression(t))&&V.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function mn(e){let t=vi(e.openingElement.name);return t==="Fragment"||t==="React.Fragment"}function vi(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"&&Bc(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!Bc(n))return null;let r=n;for(;r&&r!==e;){if(!lh(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function Bc(e){return e.isJSXElement()||e.isJSXFragment()}function lh(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 hn(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=re(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return $(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 $(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=Tc(t,r.jsx);if(!u.ok)return u.result;let d=uh(u.node,!0),m=l.node.children,p={...s,targetParentLocator:n},h=w=>s?Ve(w,a.ast,d,p):w;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 $(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let E=re(a.ast,i);if(!E.ok)return{ok:!1,source:t,diagnostic:E.diagnostic};let v=kt(c.match.path,E.match.path);if(!v)return $(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");l=v;let C=l.node.children,R=C.findIndex(w=>w===E.match.path.node);return R===-1?$(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(C.splice(o==="before"?R:R+1,0,d),h(de(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as $c from"@babel/parser";import{cloneNode as dh}from"@babel/types";function Xr(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=fh(t,r);if(!c.ok)return c.result;let l=re(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return $(t,"unsupported-syntax","insert-jsx-expression-child target must be a JSXElement or JSXFragment","jsx-node");if(l.match.path.isJSXElement()){let C=l.match.path.node;if(!C.closingElement||C.openingElement.selfClosing)return $(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=l.match.path,d=null;if(i){let C=re(a.ast,i);if(!C.ok)return{ok:!1,source:t,diagnostic:C.diagnostic};let R=kt(l.match.path,C.match.path);if(!R)return $(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=R,d=C.match.path.node}else if(o==="before"||o==="after")return $(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=dh(c.node,!0),p=u.node.children,h={...s,targetParentLocator:n},E=C=>s?Ve(C,a.ast,m,h):C;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 v=p.findIndex(C=>C===d);return v===-1?$(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(p.splice(o==="before"?v:v+1,0,m),E(de(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function fh(e,t){try{let r=$c.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:$(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:$(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as ph,nullLiteral as Ri}from"@babel/types";import*as gn from"@babel/types";function yn(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=re(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let l=re(a.ast,r);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return $(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 R=l.match.path.node;if(!R.closingElement||R.openingElement.selfClosing)return $(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let d=null;if(i){let R=re(a.ast,i);if(!R.ok)return{ok:!1,source:t,diagnostic:R.diagnostic};let w=kt(l.match.path,R.match.path);if(!w)return $(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=w,d=R.match.path}else if(o==="before"||o==="after")return $(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=d&&typeof d.key=="number"?d.key:-1;if(d&&m===-1)return $(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let p=ph(c.match.path.node,!0);if(!gn.isJSXElement(p)&&!gn.isJSXExpressionContainer(p)&&!gn.isJSXFragment(p))return $(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 $(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");mh(c.match.path);let E=u.node.children,v={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return E.push(p),Ve(Ur(a.ast,t),a.ast,p,v);if(o==="prepend")return E.unshift(p),Ve(Ur(a.ast,t),a.ast,p,v);let C=m-(h!==-1&&h<m?1:0);return E.splice(o==="before"?C:C+1,0,p),Ve(Ur(a.ast,t),a.ast,p,v)}function mh(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*as Vc from"@babel/parser";import{cloneNode as hh,nullLiteral as Pi}from"@babel/types";function zr(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=gh(t,s);if(!l.ok)return l.result;let u=re(c.ast,n);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};let d=re(c.ast,r);if(!d.ok)return{ok:!1,source:t,diagnostic:d.diagnostic};if(!d.match.path.isJSXElement()&&!d.match.path.isJSXFragment())return $(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 $(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let m=d.match.path,p=null;if(i){let w=re(c.ast,i);if(!w.ok)return{ok:!1,source:t,diagnostic:w.diagnostic};let z=kt(d.match.path,w.match.path);if(!z)return $(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");m=z,p=w.match.path.node}else if(o==="before"||o==="after")return $(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!u.match.path.isJSXElement())return $(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let h=m.node,E=hh(l.node,!0);yh(u.match.path);let v={...a,sourceLocator:n,targetParentLocator:r},C=h.children;if(o==="append")return C.push(E),Ve(de(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,E,v);if(o==="prepend")return C.unshift(E),Ve(de(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,E,v);let R=C.findIndex(w=>w===p);return R===-1?$(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(C.splice(o==="before"?R:R+1,0,E),Ve(de(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,E,v))}function gh(e,t){try{let r=Vc.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:$(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:$(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function yh(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Pi());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Pi());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Pi());return}e.remove()}function Hr(e){let{source:t,locator:n,props:r}=e,o=Ie(t,"jsx-node");if(!o.ok)return o.result;let i=wc(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=Ac(o.ast,l);if(u.ok&&u.match!==null){let d=u.match.path.node;d.value=c===""?Kr(a,"").value:Kr(a,c).value}else s.attributes.push(Kr(a,c))}return de(o.ast,t,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}import{getBindingIdentifiers as xh,identifier as Vn,importDeclaration as Eh,importDefaultSpecifier as Sh,importNamespaceSpecifier as bh,importSpecifier as Ih,isImportDefaultSpecifier as Uc,isImportNamespaceSpecifier as Kc,isImportSpecifier as Jc,stringLiteral as kh}from"@babel/types";function xn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(v=>!Fh(v));if(o!==-1){let v=r[o],C=v&&typeof v=="object"&&"kind"in v?v.kind:void 0;return $(t,"unsupported-syntax",`Unsupported import spec kind: ${String(C)}`)}let i=Ah(r);if(!i.ok)return $(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(v=>v.type==="ImportDeclaration"&&v.source.value===n),u=new Set(l.flatMap(v=>v.specifiers.flatMap(C=>{let R=Mh(v,C);return R?[R]:[]}))),d=i.imports.filter(v=>!u.has(Gc(v)));if(d.length===0)return Bn(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let m=Th(c.body),p=d.find(v=>m.has(wi(v)));if(p)return $(t,"unsupported-syntax",`Import local binding already exists: ${wi(p)}`);let h=wh(d);if(h.reduce((v,C)=>v+C.length,0)!==d.length)return $(t,"unsupported-syntax","Unsupported import specifier grouping");for(let v of h){if(!Wc(zc(v)))return $(t,"unsupported-syntax","Unsupported import specifier combination");let C=l.find(R=>Ch(R,v));if(C)vh(C,v);else{let R=Eh(Xc(v),kh(n));Nh(c.body,R),l.push(R)}}return de(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function Ch(e,t){return e.importKind==="type"?!1:Wc(Ph(Rh(e),zc(t)))}function vh(e,t){let n=!1,r=new Set(e.specifiers.map(o=>Ai(o)));for(let o of Xc(t)){let i=Ai(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return Yc(e.specifiers),{changed:n}}function Xc(e){let t=e.map(n=>{switch(n.kind){case"named":return Ih(n.local?Vn(n.local):Vn(n.imported),Vn(n.imported));case"default":return Sh(Vn(n.local));case"namespace":return bh(Vn(n.local));default:return n}});return Yc(t),t}function zc(e){let t=Hc();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 Rh(e){let t=Hc();for(let n of e.specifiers)Uc(n)?t.defaultLocals.add(n.local.name):Kc(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function Hc(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function Ph(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function Wc(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function Yc(e){let t=[...e.filter(n=>Uc(n)),...e.filter(n=>Kc(n)),...e.filter(n=>Jc(n))];e.splice(0,e.length,...t)}function wh(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 Ah(e){let t=new Map,n=new Map;for(let r of e){let o=Gc(r);if(t.has(o))continue;let i=wi(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 Th(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(xh(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 Nh(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 Fh(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 Gc(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 wi(e){return e.kind==="named"?e.local??e.imported:e.local}function Mh(e,t){return e.importKind==="type"||Jc(t)&&t.importKind==="type"?null:Ai(t)}function Ai(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 En(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(u=>!Oh(u));if(o!==-1){let u=r[o],d=u&&typeof u=="object"&&"kind"in u?u.kind:void 0;return $(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=>_h(u,d))),l.specifiers.length===0&&a.body.splice(c,1),de(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function _h(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 Oh(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 Un(e){let{source:t,locator:n,next:r}=e,o=Zr(t,n);return o.ok?(o.path.replaceWith(fn(r)),de(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function Wr(e){let{source:t,locator:n,index:r,value:o}=e,i=Zr(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(s=>s?.type==="SpreadElement")?$(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>i.path.node.elements.length?$(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,0,fn(o)),de(i.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):$(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function Yr(e){let{source:t,locator:n,index:r}=e,o=Zr(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(i=>i?.type==="SpreadElement")?$(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=o.path.node.elements.length?$(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"})):$(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function Gr(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=Zr(t,n);if(!i.ok)return i.result;if(!i.path.isArrayExpression())return $(t,"unsupported-syntax","Array operations require array expression target","value");if(i.path.node.elements.some(c=>c?.type==="SpreadElement"))return $(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 $(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 Zr(e,t){let n=Ie(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=re(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 Lh=typeof Ti=="function"?Ti:Ti.default;function Mi(e){let t=rl(e);if(t)return{ok:!1,error:t};let n=e.projection,r=_i(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:Qc(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=qr(e.source,c.match.node.start??null,c.match.node.end??null);if($h(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=Qc(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 Qc(e){let t=Bh(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 tl(e){let t;try{t=eo.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=eo.parseExpression(e.jsx,{plugins:["jsx","typescript"]}),r=!1;return(typeof Ni=="function"?Ni:Ni.default)(t,{ExportDefaultDeclaration(i){let s=i.get("declaration"),a=jh(i,s);if(a){if(a.isArrowFunctionExpression()&&!a.get("body").isBlockStatement()){let c=a.get("body");c.replaceWith(qc(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(qc(l.node,n,e.placement,e.replaceOriginal===!0)),r=!0,c.stop())}}),r&&i.stop()}}}),r?{ok:!0,source:Lh(t,{}).code}:{ok:!1,source:e.source,diagnostic:{message:"Route default return boundary could not be resolved."}}}function jh(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 qc(e,t,n,r){if(Ct.isNullLiteral(e)||r)return t;let s=n==="before"||n==="prepend"?[t,e]:[e,t];return Ct.jsxFragment(Ct.jsxOpeningFragment(),Ct.jsxClosingFragment(),s)}function nl(e){let t=rl(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=ol(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=Fi(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(qr(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=_i(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=Fi(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(qr(e.source,m.match.node.start??null,m.match.node.end??null)!==l.containerSourceHash)return el("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 v=Fi(h),C=pt(e.source,v);return!C.ok||!C.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:C.ok===!1?C.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:C.ok?[]:[Qr(C.diagnostic)]}}:qr(e.source,C.match.node.start??null,C.match.node.end??null)!==E?el("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:v,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 el(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 rl(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 Bh(e,t){let n=Zc.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Zc.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Fi(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function qr(e,t,n){return t==null||n==null?null:`sha256:${Dh("sha256").update(e.slice(t,n)).digest("hex")}`}function $h(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 Vh=typeof Oi=="function"?Oi:Oi.default;function sl(e){if(!e.ast)return st(e,[Ne("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=Yh(e.ast);if(!t)return st(e,[Ne("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=Zh(t);if(n.length===0)return st(e,[Ne("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")]);if(n.length>1)return st(e,[Ne("MULTIPLE_PAGE_RETURNS","Route default export contains multiple page-level return statements",{returnCount:n.length})]);let r=Qh(n[0].argument);if(!r)return st(e,[Ne("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})]);if(r.isNullLiteral())return il(e,t,"virtual-route-root");if(qh(r,t))return st(e,[Ne("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(eg(r,t)||tg(r)&&!e.source.includes("DESIGN_PLAN_REPLACE_ME"))return st(e,[Ne("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 st(e,[Ne("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);let s=Di({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-fragment",source:e.source,containerPath:r,members:i.members});return to(e,t,s,{kind:"virtual-route-root",sourceKind:"jsx-fragment"})}if(r.isJSXElement()&&!Sn(r)){let i=Bi(r),s=Di({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[i]});return to(e,t,s,{kind:"virtual-route-root",sourceKind:"jsx-element"})}if(r.isJSXElement()){let i=Rt(r);if(i.unsupported)return st(e,[Ne("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);let s=i.members;if(rg(e.source,r,s))return il(e,t,"starter-placeholder");let a=Di({input:e,containerKind:"jsx-container",sourceKind:"jsx-element",source:e.source,containerPath:r,members:s});return to(e,t,a,{kind:"jsx-container",sourceKind:"jsx-element"})}if(ng(r))return st(e,[Ne("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);let o=ig({input:e,source:e.source,expression:r});return to(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"})}function _i(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Ne("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:Ne("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function ol(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Ne("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:Ne("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function al(e){return e.ok?Uh(e.projection):Kh(e.projection)}function Uh(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,v)=>cl(e,u,E,v,e.container.placementKey)),m=d.filter(({member:E})=>E.isBusinessMember).map(({sourceMember:E})=>Xh(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:Jh(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function Kh(e){let t=e.diagnostics.map(zh);return{status:"unsupported",version:e.version,routeId:e.route,reason:Hh(e.diagnostics),diagnostics:t}}function Jh(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 cl(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)=>cl(e,t,a,c,i))]}function Xh(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function zh(e){return{code:Wh(e),message:e.message}}function Hh(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 Wh(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 Yh(e){let t=null;return Vh(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=Gh(o.path);i&&(t=i,n.stop())}}),t}function Gh(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 Zh(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 Qh(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 qh(e,t){if(e.isIdentifier())return no(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return no(n.node.name,t)}return!1}function eg(e,t){return e.isConditionalExpression()?vt(e.get("consequent"),t)||vt(e.get("alternate"),t):e.isLogicalExpression()?vt(e.get("left"),t)||vt(e.get("right"),t):!1}function tg(e){if(!e.isJSXElement()||!Sn(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 vt(e,t){if(e.isIdentifier())return no(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return no(n.node.name,t)}return e.isConditionalExpression()?vt(e.get("consequent"),t)||vt(e.get("alternate"),t):e.isLogicalExpression()?vt(e.get("left"),t)||vt(e.get("right"),t):!1}function no(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 ng(e){return e.isJSXSpreadChild()}function rg(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&ji(t)}function ji(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(!ji(t))return!1;continue}if(t.isJSXElement()&&!ji(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:$i(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:Ye(r.node.loc),businessMemberCount:0,parentSourceRange:Ye(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=Sn(o)?Rt(o):null;n||=i?.unsupported??!1,t.push({...Bi(o,i?.members),sourceRange:Ye(r.node.loc),parentSourceRange:Ye(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:$i(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:Ye(r.node.loc),businessMemberCount:1,parentSourceRange:Ye(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&ll(r)){let o=Rt(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=Sn(r)?Rt(r):null;n||=o?.unsupported??!1,t.push({...Bi(r,o?.members),parentSourceRange:Ye(e.node.loc)})}}return{members:t,unsupported:n}}function Bi(e,t){let n=e.isJSXElement()&&Sn(e)?t??Rt(e).members:[],r=e.isJSXElement()&&!Sn(e)&&!ll(e);return{memberKey:$i(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:Ye(e.node.loc),businessMemberCount:r?1:ul(n),parentSourceRange:Ye(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:og(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 Sn(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name!=="Fragment"&&t.name[0]===t.name[0]?.toLowerCase()}function og(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 ul(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function ro(e){return e.length===0?0:Math.max(1,ul(e))}function Di(e){let t=Ye(e.containerPath.node.loc),n=fl(e.source,e.containerPath.node.start,e.containerPath.node.end),r=Ue(e.input,e.containerKind,e.sourceKind,t),o=Ue(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:ro(e.members)<=1,memberCount:ro(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function ig(e){let t=Ye(e.expression.node.loc),n=fl(e.source,e.expression.node.start,e.expression.node.end),r=Ue(e.input,"virtual-route-root","atomic-expression",t),o=Ue(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:Ue(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 to(e,t,n,r){let o=n.containerSourceRange??n.sourceRange,i=sg(e,n,o),s=gi(i),a={status:"supported",route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:pl(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 sg(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:ro(h)<=1,memberCount:ro(h),sourceRange:m,sourceHash:m?Li(e.source,m):null,relation:l,containerSourceRange:E,containerSourceHash:E?Li(e.source,E):null,anchorSourceRange:p,anchorSourceHash:p?Li(e.source,p):null,members:h}),i=t.placementKey,s=t.members.map(l=>Ue(e,i,"placement-unit",l.sourceRange)),a=s[0]??t.placementUnitKey,c=s.at(-1)??t.placementUnitKey;r.push(o("prepend",Ue(e,i,"prepend",n),a,n,null,[]));for(let l of t.members){let u=l.parentSourceRange??n,d=Ue(e,i,"placement-unit",l.sourceRange);r.push(o("before",Ue(e,d,"before",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u)),r.push(o("after",Ue(e,d,"after",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u))}return r.push(o("append",i,c,n,null,[])),r}function il(e,t,n){let r=Ue(e,n,"empty-container",void 0),o=Ue(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=gi([i]),a={status:"supported",route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:pl(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 st(e,t){return{ok:!1,projection:{status:"unsupported",route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,diagnostics:t}}}function Ne(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function Ue(e,t,n,r){return dl([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function $i(e,t,n){return dl(["member",e,String(t??-1),String(n??-1)])}function dl(e){return`pc_${Vi("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function fl(e,t,n){return t==null||n==null?null:`sha256:${Vi("sha256").update(e.slice(t,n)).digest("hex")}`}function Li(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:${Vi("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function Ye(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function pl(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 cg(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var lg=160;function ml(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 hl(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 v=Sl(p.textSegments,s),C=bl(e,t,p,E,v),R=v?fg(v):void 0,w=pg(i,v),z=p.textSegments.map(M=>({index:M.index,value:M.value,editable:Il(M,E,s?.get(M.index)??null),source:o.get(M.index)??null})),te=xl(p,t),le=p.childKeys.map(M=>{let O=t.elements.get(M);return O?{key:M,tag:O.tag,label:O.tag}:null}).filter(M=>M!==null),A=[];if(p.parentKey){let M=t.elements.get(p.parentKey);if(M)for(let O of M.childKeys){if(O===e)continue;let j=t.elements.get(O);j&&A.push({key:O,tag:j.tag,label:j.tag})}}return{key:e,tag:p.tag,componentName:p.componentName,sourceFile:p.sourceFile,sourceLocator:yl(p),label:p.tag,capabilities:C,writeTarget:i,effectiveWriteTarget:w,provenanceChain:R,componentSemantic:c,contentModel:l,mediaModel:u,styleSource:d,conditional:a,...m?{dynamicData:m}:{},textSegments:z,boundaryKind:p.boundaryKind,isOpaque:p.isOpaque,ancestors:te,children:le,siblings:A}}function gl(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=Sl(a.textSegments,i);return{key:e,tag:a.tag,componentName:a.componentName,sourceFile:a.sourceFile,sourceLocator:yl(a),label:a.tag,capabilities:bl(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:Il(d,l,i?.get(d.index)??null),source:m?{kind:m.kind}:null}}),boundaryKind:a.boundaryKind,isOpaque:a.isOpaque,ancestors:xl(a,t)}}function yl(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:ug(e.sourceRange),structuralPath:e.identity.structuralPath,...dg(e.textSegments)}}function xl(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 ug(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function dg(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,lg)}:{}}function El(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 Sl(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function bl(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&&kl(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 Il(e,t,n){return!e.editable||!t.canUpdateText?!1:n?kl(n.editMode):!0}function kl(e){return e==="direct"||e==="proxy"||e==="upstream"}function fg(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 pg(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}:cg(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 Cl(e){let{key:t,element:n,graph:r,provenances:o}=e,i=hg(t,n,r),s=i?.tag??(Jt(n.tag)?n.tag:n.componentName),a=i?.identity.key??vl(n,r)??t,c=xg(i),l=Eg(t,n,r,o,i),u=mg(t,n,r,o,a);return{componentName:s,instanceKey:a,templateOwner:yg(i??n,s),...c.length>0?{variantKeys:c}:{},...l.length>0?{slotKeys:l}:{},editableStrategy:u,impactScope:Sg(u),alternativeStrategies:bg(u)}}function mg(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return Ui(e,n)?"instance":!Jt(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function vl(e,t){if(Jt(e.tag))return e.identity.key;let n=[...t.elements.values()].filter(r=>r.importedFrom===e.sourceFile&&gg(r,e.componentName));return n.length!==1?null:n[0].identity.key}function hg(e,t,n){if(Jt(t.tag))return t;let r=Ui(e,n);if(r)return r;let o=vl(t,n);return o?n.elements.get(o)??null:null}function gg(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function yg(e,t){return Jt(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function xg(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 Eg(e,t,n,r,o){let i=new Set,s=Ui(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&&Jt(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function Ui(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(Jt(r.tag))return r;n=r.parentKey}return null}function Jt(e){return/^[A-Z]/.test(e)}function Sg(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function bg(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}var Ig=new Set(["markdown","body","content","value","document"]),Rl=[];function wl(e){if(!(!vg(e.tag)||!e.attributes))for(let t of e.attributes){if(!Ig.has(t.name))continue;if(Cg(t))return{kind:"markdown",field:t.name,schema:"markdown",valuePath:t.source?.expression,operationBoundary:Rl};let n=kg(t.resolvedValue);if(n==="prosemirror-doc"||n==="node-array")return{kind:"rich-text-json",field:t.name,valuePath:t.source?.expression,schema:n,operationBoundary:Rl};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 kg(e){if(e){if(Array.isArray(e)&&e.every(t=>Pl(t)))return"node-array";if(Pl(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 Pl(e){return!Array.isArray(e)&&typeof e=="object"&&e!==null}function Cg(e){return e.name==="markdown"}function vg(e){return/^[A-Z]/.test(e)}var Rg=["src","alt","poster","caption","width","height"];function Al(e){let t=e.attributes?.filter(i=>Rg.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=wg(t.map(i=>i.value));return{kind:Pg(e.tag,n),sourceType:o,fields:n,editableFields:[],operationBoundary:[],...Object.keys(r).length>0?{valuePaths:r}:{}}}function Pg(e,t){return e==="img"?"image":e==="video"||t.includes("poster")?"video":"media"}function wg(e){return e.some(t=>t.startsWith("cms:"))?"cms-media-field":e.some(t=>/^(\.?\/|\/)/.test(t))?"local-file-reference":"asset-id"}var Ki=["set-class-name-source","apply-style-draft"];function Tl(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:Ki,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:Ki,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:Ki}}import{createHash as Ag}from"node:crypto";var Kn=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 ce(e){return`sha256:${Ag("sha256").update(e).digest("hex")}`}function Ml(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:ce(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=Tg(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:ce(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:Fl(r),version:{documentVersion:e.route.graph.version,contentHash:ce(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:Nl(e.route.source,o),valueRaw:s?Nl(e.route.source,s):null,attrRange:Fl(o),diagnostics:[]}}function _l(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 Tg(e,t){let n=it({source:e,profile:Bt({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=re(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:Ng(t.sourceRange)});return!r.ok||r.match.node.type!=="JSXElement"?null:r.match.node}function Ol(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 Nl(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function Fl(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 Ng(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}import*as ss from"@babel/parser";import Wi from"@babel/traverse";import*as S from"@babel/types";import*as gt from"node:path";import*as $l from"@babel/parser";import zi from"@babel/traverse";import*as bn from"@babel/types";import*as H from"@babel/types";function so(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?oo(n,t):null}if(e.isMemberExpression()){let n=Lg(e.node),r=Fg(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?oo(o,[...r,...t]):null}return e.isAwaitExpression()||Xi(e.node)?Pt(Bg(e.node),t,"awaited or fetched expression"):null}function Fg(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 oo(e,t=[]){let n=Mg(e,t);if(n)return n;let r=_g(e,t);if(r)return r;let o=Og(e,t);return o||null}function Xn(e){return e?.kind==="api-source"}function Mg(e,t){if(e.path.isVariableDeclarator()&&H.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&Ji(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"&&Jn(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&Ji(a.node))return Pt(e.identifier.name,t,"query hook data binding")}let n=Dg(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()||!Ji(i.node)?null:Pt(e.identifier.name,t,"query hook data binding")}function _g(e,t){if(e.path.isVariableDeclarator()&&H.isArrayPattern(e.path.node.id)){let a=e.path.get("init");if(!a?.isCallExpression()||!Ll(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:Dl(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()||!Ll(o.node)||n.node.elements.findIndex(a=>a===e.path.node)!==0)return null;let s=n.node.elements[1];return H.isIdentifier(s)&&Dl(e,s.name)?Pt(e.identifier.name,t,"state setter is updated by API data"):null}function Og(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"):Xi(r.node)?Pt(e.identifier.name,t,"fetch-backed binding result"):null:null}function Dg(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 Jn(e,t){return H.isIdentifier(e)?e.name===t:H.isAssignmentPattern(e)?Jn(e.left,t):H.isObjectPattern(e)?e.properties.some(n=>H.isObjectProperty(n)?Jn(n.value,t):Jn(n.argument,t)):H.isArrayPattern(e)?e.elements.some(n=>!!n&&Jn(H.isRestElement(n)?n.argument:n,t)):!1}function Dl(e,t){let n=!1,r=!1;return e.scope.path.traverse({CallExpression(i){Xi(i.node)&&(n=!0),(jg(i.node.callee,t)||i.node.arguments.some(s=>H.isIdentifier(s)&&s.name===t))&&(r=!0)}}),n&&r}function Ji(e){let t=ao(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function Ll(e){return ao(e.callee)==="useState"}function Xi(e){return io(e,t=>H.isCallExpression(t)&&ao(t.callee)==="fetch")}function Lg(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 ao(e){return H.isIdentifier(e)?e.name:H.isMemberExpression(e)&&H.isIdentifier(e.property)?e.property.name:null}function jg(e,t){return io(e,n=>H.isIdentifier(n)&&n.name===t)}function io(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)&&io(i,t))return!0;continue}if(H.isNode(o)&&io(o,t))return!0}return!1}function Bg(e){return H.isIdentifier(e)?e.name:H.isCallExpression(e)?ao(e.callee)??"api":H.isAwaitExpression(e)?"awaited-api":"api"}function Pt(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:$g(e,t),reason:n}}function $g(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var Vl=typeof zi=="function"?zi:zi.default;function Ul(e,t){let n=Jl(e);if(!n)return{allowed:!0};let r=!1;return Vl(n,{CallExpression(o){if(!Xl(o.node,t.sourceRange)||!Vg(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||Xn(so(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function Kl(e,t){let n=Jl(e);if(!n)return{allowed:!0};let r=!1;return Vl(n,{JSXExpressionContainer(o){Xl(o.node,t.sourceRange)&&(bn.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 Jl(e){try{return $l.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Vg(e){let t=e.callee;return bn.isMemberExpression(t)&&bn.isIdentifier(t.property)&&t.property.name==="map"}function Xl(e,t){let n=e.loc;return n?Bl({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&Bl({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function Bl(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 ie from"@babel/types";function zl(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 at(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return Xt(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(ie.isObjectPattern(n)||ie.isArrayPattern(n))return Xt(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(Kg(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function Xt(e,t,n=!1){return ie.isIdentifier(e)?e.name===t&&n:ie.isObjectPattern(e)?e.properties.some(r=>ie.isObjectProperty(r)?Xt(r.value,t,n):Xt(r.argument,t,n)):ie.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=ie.isRestElement(r)?r.argument:r;return Xt(o,t,n)}):ie.isAssignmentPattern(e)?Xt(e.left,t,!0):ie.isRestElement(e)?Xt(e.argument,t,n):!1}function In(e,t){if(e.path.isObjectPattern()){if(t){let r=Ge(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:at(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:at(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=Hl(r),i=!1,s=o?o.initBinding&&Hi(o.initBinding)?(i=at(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=In(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=Ge(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||at(e)}}}}let n=zg(e);if(n){let r=Ug(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||at(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=Jg(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:at(e)}}let i=zn(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:at(e)}:null}if(Hi(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:at(e)}}return null}function Ug(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=Hl(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=Hi(i)?(a=at(i),[...s]):(()=>{let u=In(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=Ge(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||at(t)}:null}function Hl(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=Hg(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function Hi(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function Kg(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Jg(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=Ge(i.node,t);if(a)return a}return null}function Wl(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=co(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=zn(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=Xg(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=zn(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 co(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=zn(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&Ge(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=co(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=co(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=co(r,t);if(o)return o}}return null}function Ge(e,t,n=[]){if(ie.isIdentifier(e))return e.name===t?n:null;if(ie.isObjectPattern(e)){for(let r of e.properties)if(ie.isObjectProperty(r)){let o=zn(r);if(!o)continue;let i=Ge(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(ie.isRestElement(r)){let o=Ge(r.argument,t,n);if(o)return o}}if(ie.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=ie.isRestElement(o)?o.argument:o,s=Ge(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return ie.isAssignmentPattern(e)?Ge(e.left,t,n):null}function Xg(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function zg(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 zn(e){return e.computed?null:ie.isIdentifier(e.key)?e.key.name:ie.isStringLiteral(e.key)?e.key.value:null}function Hg(e){let t=[],n=e;for(;ie.isMemberExpression(n);){if(n.computed)if(ie.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(ie.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(ie.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return ie.isIdentifier(n)?{base:n.name,path:t}:null}var Ft=typeof Wi=="function"?Wi:Wi.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 kn(e){return{file:e.file,component:e.component}}function Wg(e){return e.target.kind==="node"?e.target.key:null}function Yg(e){return"kind"in e}function lo(e){return!Yg(e)}function es(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 Yi(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 as(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 Ke(e){try{return ss.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Gg(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function Zg(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 ae(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function Wt(e,t){let n=ae(e);return!!(n&&Ze(t,n))}function Ze(e,t){return t.start>=e.start&&t.end<=e.end}function uu(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 Qg(e,t){let n=ae(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);if(!a||Wt(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=uu(i.node.name);s&&o(s,i)}}),[...r].sort()}function Yl(e,t,n){let r=Ke(e);if(!r)return{ok:!0};let o=re(r,fe(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=re(r,fe(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};if(vu(o.match.path,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let s=Qg(o.match.path,i.match.path);return s.length>0?{ok:!1,bindingNames:s}:{ok:!0}}function Gl(e,t,n){let r=wt(t,n);return r?ht(e,r):null}function wt(e,t){let n=re(e,fe(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:is(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=mo(e,u.node),m=r.node.params.map(E=>mo(e,E)),p=ae(i.node),h=ae(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:ds(u.node),callbackPath:r,collectionPath:u}}function mo(e,t){let n=ae(t);return n?e.slice(n.start,n.end):""}function uo(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function qg(e,t){let n=ae(e.node);return n?ey(t).some(r=>{let o=ae(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function ey(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)?ty(e)?Zl(e.children):[e]:S.isJSXFragment(e)?Zl(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)&&Pu(e.operator)?Nt(e.right):[]}function Zl(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 ty(e){let t=e.openingElement.name;return S.isJSXIdentifier(t)?t.name==="Fragment":S.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function ny(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function Gi(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function Ql(e,t,n,r={}){if(!r.preserveConditionalBoundary&&vu(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=ae(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(c=>us(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||Wt(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=uu(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function ql(e,t,n){let r=ae(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>us(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return cs(e,s=>{let a=s.scope.getBinding(s.node.name);if(!a||Wt(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 ry(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>us(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=oy(l);u&&o(u,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function oy(e){let t=e;for(;S.isTSQualifiedName(t);)t=t.left;return S.isIdentifier(t)?t.name:null}function du(e,t){let n=ae(e.node),r=new Set;return cs(e,o=>{let i=o.scope.getBinding(o.node.name);if(!i||n&&Wt(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 cs(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function iy(e){let t=sy(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=wu(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=Ey({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=Cu(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?ds(o):!0}}}function sy(e,t,n){let r=mu(e,t);if(hu(e,r),gu(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){Iu(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:ls(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 ay(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=>Wn(a.file)));if(!t.has(Wn(e.sourceFile))||!t.has(Wn(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(Wn(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=dy(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=Ke(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=cy(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=fu({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)||ls(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 cy(e,t){let n=new Map,r=i=>{let s=Cn(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 ly(i,n))o=r(s)||o}return[...n.values()]}function ly(e,t){let n=[],r=uy(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=Gn(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=Zn(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:ts(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)&&zt(l.namespace,a));if(c.length>0){let l=Tt(s.exported);for(let u of c){let d=Gn(u.namespace,a,l);d&&n.push({file:e.file,namespace:d,exportName:u.exportName})}continue}t.has(Cn({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=Gn(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=Zn(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:ts(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 ts(e,t){return t?`${e}.${t}`:e}function zt(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function Gn(e,t,n){return!zt(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function uy(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=Zn(e.file,i.source.value);for(let a of i.specifiers){if(S.isImportDefaultSpecifier(a)){let c=t.get(Cn({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(u=>Qe(u.file,s)&&zt(u.namespace,"default"));for(let u of l){let d=Gn(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)&&zt(d.namespace,c));for(let d of l)r(a.local.name,d);let u=t.get(Cn({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:ts(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=vn(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(Cn));for(let d of c){let m=Gn(d.namespace,a.name,s.id.name),p=m?{...d,namespace:m}:d,h=Cn(p);u.has(h)||(r(s.id.name,p),u.add(h),o=!0)}}}return n}function Cn(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${rs(e.file)}#${t}`}function Tt(e){return S.isIdentifier(e)?e.name:e.value}function dy(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 fu(e){let t=fy(e),n=[],r=gu(e.ast,t);return Ft(e.ast,{JSXElement(o){Qe(e.file,e.sourceFile)&&ls(o)===e.sourceComponent||Iu(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function pu(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function mu(e,t){let n=pu();return Ft(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function fy(e){let t=pu();return Qe(e.file,e.sourceFile)&&py(t,mu(e.ast,e.sourceComponent)),Ft(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=Zn(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=>zt(u.namespace,"default"));if(l.length>0){let u=t.namespaceMembers.get(c)??new Set;for(let d of l){let m=tu(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=>zt(d.namespace,l));if(u.length>0){let d=t.namespaceMembers.get(c)??new Set;for(let m of u){let p=tu(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)}}}}}),hu(e.ast,t),t}function py(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 hu(e,t){Ft(e,{VariableDeclarator(n){if(!n.node.init)return;let r=vn(n.node.init);if(r){if(S.isIdentifier(n.node.id)){let o=Ht(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&ns(t,i,o);return}if(S.isObjectPattern(n.node.id)){let o=Ht(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&Eu(n.node.id,o.namespaceMembers,t,n)}}}})}function gu(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return Ft(e,{ReferencedIdentifier(r){if(n){r.stop();return}my(r)||!r.isIdentifier()||!yu(r,t)||hy(r,t)||gy(r)||(n=!0,r.stop())}}),n}function my(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 yu(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)&&Ht(r.node,t,r)?r:null}function hy(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!eu(e,r))return!1;let o=yu(e,t);if(!o)return!1;if(vn(r.node)===o.node)return!!Ht(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&eu(e,a)&&!!Ht(a.node,t,a)}function gy(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function eu(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Ht(e,t,n){let r=vn(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 yy(r,t,n);let o=bu(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?xu(s,o.slice(1).join(".")):null}function yy(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!S.isObjectProperty(i))continue;let s=Su(i);if(!s||!S.isExpression(i.value)){S.isExpression(i.value)&&(o||=Ht(i.value,t,n)!==null);continue}let a=Ht(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 xu(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 ns(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 Eu(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&&ns(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!S.isObjectProperty(o))continue;let i=Su(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=xu(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&&ns(n,c,s);continue}if(S.isObjectPattern(a)&&s.namespaceMembers.size>0){Eu(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function Su(e){return e.computed?S.isStringLiteral(e.key)||S.isNumericLiteral(e.key)?String(e.key.value):null:xy(e.key)}function xy(e){return S.isIdentifier(e)?e.name:S.isStringLiteral(e)||S.isNumericLiteral(e)?String(e.value):null}function vn(e){return S.isParenthesizedExpression(e)||S.isTSAsExpression(e)||S.isTSSatisfiesExpression(e)||S.isTSNonNullExpression(e)||S.isTSTypeAssertion(e)?vn(e.expression):S.isExpression(e)?e:null}function bu(e){if(S.isIdentifier(e))return[e.name];if((S.isMemberExpression(e)||S.isOptionalMemberExpression(e))&&!e.computed&&S.isIdentifier(e.property)){let t=vn(e.object),n=t?bu(t):null;return n?[...n,e.property.name]:null}return null}function tu(e,t){if(!zt(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 Iu(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=ku(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 ku(e){if(S.isJSXIdentifier(e))return[e.name];if(S.isJSXMemberExpression(e)){let t=ku(e.object);return t?[...t,e.property.name]:null}return null}function ls(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 Ey(e){let t=ae(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||Wt(a.path.node,t))return;let c=Iy(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=Cy(e.callSitePath,c.propName,e.source);if(!u.ok){o=u.reason;return}let d=Sy(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=du(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:vy(e.source,t,[...n.values()])}}function Sy(e,t){if(t.length===0)return e;let n=Cu(e);if(!n)return null;let r=ds(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=by(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function by(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function Iy(e,t,n){let r=ky(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=In(t,o);if(!i)return null;let s=r?.range??ae(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function ky(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!Wt(n.node,t)||n.node.computed||!S.isIdentifier(n.node.property))return null;let r=ae(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function Cy(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=mo(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 vy(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 Cu(e){try{let n=ss.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 Ry(e){let t=ae(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||Wt(s.path.node,t))return;let a=nu(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let u=nu(c,e.targetFile,e.targetFile);(!u||u.moduleFile!==a.moduleFile||!Py(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 cs(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 Py(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 nu(e,t,n){let r=wy(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=Zn(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=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 wy(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function Zn(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 rs(e)===rs(t)}function rs(e){let t=Wn(e);return t.endsWith("/index")?t.slice(0,-6):t}function Wn(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function us(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 Ay(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 Ty(e,t){return{...e,callbackParams:t}}function ru(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function ds(e){return!(S.isIdentifier(e)||S.isThisExpression(e)||S.isMemberExpression(e)||S.isOptionalMemberExpression(e)||S.isCallExpression(e)||S.isOptionalCallExpression(e))}function vu(e,t){return Ru(e,t).length>0}function Zi(e,t){let n=ae(e.node),r=ae(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()&&!Ny(o,n,r)))return!0;o=o.parentPath}return!1}function Ny(e,t,n){let r=ae(e.node.consequent);if(r&&Ze(r,t)&&!Ze(r,n))return!1;let o=e.node.alternate?ae(e.node.alternate):null;return!(o&&Ze(o,t)&&!Ze(o,n))}function Ru(e,t){let n=ae(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=ae(o.node.consequent),a=ae(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()&&Pu(o.node.operator)){let s=ae(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 ou(e,t,n,r){let o=Ru(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=mo(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=Fy(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${_y(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function Fy(e,t){return My(e.node)?t:`(${t})`}function My(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 Pu(e){return e==="&&"||e==="||"||e==="??"}function _y(e){return e.trim().startsWith("<")?e:`(${e})`}function wu(e,t){let n=ae(e.node),r=ae(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=iu(e),i=iu(t);if(!o||!i||!Oy(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=Dy(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=ae(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())&&Ly(s)){let a=ae(s.node.body)??ae(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 iu(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?ae(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 ae(t.node.body);t=t.parentPath}return null}function Oy(e,t){return e.start===t.start&&e.end===t.end}function Dy(e,t){let n=ae(e.consequent);if(n&&Ze(n,t))return n;let r=ae(e.alternate);return r&&Ze(r,t)?r:null}function Ly(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 jy={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 fo(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=jy[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 By(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 $y(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 su(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 au(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function Vy(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=as(e),o=Ke(t);if(n.exportName!=="default"){let a=o?$y(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?au(r,su(o)):r;return{localName:c,importStep:Qi(e,c)}}if(!o)return{localName:r,importStep:Qi(e,r)};let i=By(o,n.source);if(i)return{localName:i};let s=au(r,su(o));return{localName:s,importStep:Qi(e,s)}}function Uy(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??as(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 Ky(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?Jy(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function Jy(e){return Object.fromEntries(Object.entries(e).filter(t=>os(t[1])))}function os(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(os):typeof e=="object"?Object.values(e).every(os):!1}function Xy(e,t){let n=Ke(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=fu({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 Qi(e,t=as(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 cu(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 zy(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function Hn(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 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:fs(e,t.slice(0,n)),index:r.index}}return null}function qi(e,t){return e.locator?e.collectionPathMap?.[t]?fs(e.locator,e.collectionPathMap[t]):Yn(e.locator)?Wy(e.locator,Yy(t,e.collectionIndexMap)):null:null}function Hy(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:Au(o,t)}function Au(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=Au(r,t);return o===void 0?void 0:{[n.name]:o}}function po(e,t,n){return n?.finalSource?.kind==="component-prop"?"Cannot edit prop-backed node structure with a generic node operation":t?.kind==="value-binding"&&t.sourceKind==="repeat-template"&&!e.isRepeatItemRoot?"Cannot edit repeat-backed child node structure with a generic node operation":t?.kind==="value-binding"&&t.file!==e.file&&t.sourceKind!=="repeat-template"?"Cannot edit upstream-bound node structure with a generic node operation":null}function Wy(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 Yy(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 Gy(e,t){return Zy(e.root,t.root)&&qy(e.path??[],t.path??[])}function Zy(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&&Qy(e.sourceRange,t.sourceRange)}}function Qy(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function is(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 qy(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 ho=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:Hn(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:Hn(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:Hn(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:Hn(t.kind,t.params.kind)};let r=t;if(!lo(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=cu(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:Hn(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=Wg(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=qi(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=qi(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=Ke(i);if(!s)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not inspect the value source`};let a=re(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!Gg(a.match.path))return{ok:!0,value:r};let c=Zg(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=qi(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=Ke(this.graph.getFileContent(t));if(!o)return!1;let i=re(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=po(r,i,this.graph.getTextProvenance?.(r.key,0)??null);if(s)return{ok:!1,errorCode:"unsupported-operation",reason:s};let a=this.getRepeatBackedTemplateStructureReason(r);if(a)return{ok:!1,errorCode:"unsupported-operation",reason:a};let c=await this.getUpstreamBackedDescendantReason(r);if(c)return{ok:!1,errorCode:"unsupported-operation",reason:c};let l=[{order:0,file:r.file,type:"remove-node",locator: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||Xy(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(!lo(n.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};if(n.params.node.kind==="component-call"&&!n.params.node.component)return{ok:!1,errorCode:"unsupported-operation",reason:"Materialized component insertion requires the materialization transaction planner"};if(!o.canInsertChild)return{ok:!1,errorCode:"capability-denied",reason:"Cannot insert child into this node"};let s=this.graph.getEditableTextSegmentIndex(r.key),a=s!==null?await this.graph.getTextWriteTarget(r.key,s):null,c=po(r,a,s!==null?this.graph.getTextProvenance?.(r.key,s)??null:null);if(c)return{ok:!1,errorCode:"unsupported-operation",reason:c};let l=await this.getUpstreamBackedDescendantReason(r);if(l)return{ok:!1,errorCode:"unsupported-operation",reason:l};let 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=Ul(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=fo(r,n.params.node);if(h)return{ok:!1,errorCode:"unsupported-operation",reason:h};let E=[],v=0,C=n.params.node.kind==="component-call"?Vy(n.params.node,this.graph.getFileContent(r.file)):void 0,R=C?.importStep;return R&&E.push({order:v++,file:r.file,type:"add-import",moduleSpecifier:R.moduleSpecifier,imports:R.imports}),E.push({order:v++,file:r.file,type:"insert-child",parentLocator:fe(r),node:{jsx:Uy(n.params.node,C?.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(!lo(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:Ky(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(!lo(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=Hy(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=po(r,i,o!==null?this.graph.getTextProvenance?.(r.key,o)??null:null);if(s)return s;n.push(...this.graph.getChildNodes(r.key))}return null}getRepeatBackedTemplateStructureReason(t){if(t.isRepeatItemRoot)return 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=Ke(this.graph.getFileContent(t.file));if(!n)return t.isRepeatItemRoot===!0;let r=re(n,fe(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:is(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=ht(this.graph.getFileContent(t.file),o);return i?qg(o,i):t.isRepeatItemRoot===!0}isInsideMapCallback(t){let n=Ke(this.graph.getFileContent(t.file));if(!n)return!1;let r=re(n,fe(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:is(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=Ke(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(!uo(m,p))return null;if(a&&(s==="before"||s==="after")){let E=wt(l,a),v=E?ht(c,E):null;if(!uo(m,v))return null}if(Zi(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let h=Yl(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:kn(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=Ke(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(uo(m,p))return null;if(p&&!ny(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 w=Gl(c,l,a);if(p&&!uo(p,w)||!p&&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=fo(o,{kind:"native-tag",tag:r.tag});if(w)return{ok:!1,errorCode:"unsupported-operation",reason:w}}let h=Yi(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(Zi(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let E=ou(c,u,d,h);for(let w of E.conditionPaths){let z=ql(w,d,m);if(!z.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${z.bindingNames.join(", ")}`}}let v=Ql(u,d,m,{preserveConditionalBoundary:E.conditionPaths.length>0});if(!v.ok)return{ok:!1,errorCode:"unsupported-operation",reason:v.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${v.bindingNames.join(", ")}`};let C=ry(m,d);if(!C.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its callback parameters depend on bindings outside the target scope: ${C.bindingNames.join(", ")}`};let R=m;if(r.component!==o.component){let w=iy({source:c,ast:l,sourceContext:m,sourceNode:r,targetParent:o,targetParentPath:d});if(!w.ok)return{ok:!1,errorCode:"unsupported-operation",reason:w.reason};R=w.context}else{let w=du(m.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:fe(r),targetParentLocator:fe(o),placement:s,anchorLocator:a?fe(a):void 0,repeatExpression:ru(R,E.sourceJsx),selectionContext:kn(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=Ke(c),d=Ke(l);if(!u||!d)return null;let m=ay({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=wu(m.callSitePath,h);if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:E.reason};let v=ht(c,p);if(!v)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")&&Gl(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=fo(o,{kind:"native-tag",tag:r.tag});if(O)return{ok:!1,errorCode:"unsupported-operation",reason:O}}let R=Yi(this.graph,r);if(!R)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Zi(p,h))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let w=ou(c,p,h,R);for(let O of w.conditionPaths){let j=ql(O,h,v);if(!j.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${j.bindingNames.join(", ")}`}}let z=Ql(p,h,v,{preserveConditionalBoundary:w.conditionPaths.length>0});if(!z.ok)return{ok:!1,errorCode:"unsupported-operation",reason:z.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${z.bindingNames.join(", ")}`};let te=Ry({sourceFile:r.file,targetFile:o.file,sourceContext:v,targetParentPath:h});if(!te.ok)return{ok:!1,errorCode:"unsupported-operation",reason:te.reason};let le=Ay(v);if(!le.ok)return{ok:!1,errorCode:"unsupported-operation",reason:le.reason};let A=Ty(v,le.callbackParams),M=[{order:0,file:r.file,type:"remove-node",locator:fe(r),removeWhitespace:!0}];for(let O of te.imports)M.push({order:M.length,file:o.file,type:"add-import",moduleSpecifier:O.moduleSpecifier,imports:O.imports});return M.push({order:M.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:fe(o),expression:ru(A,w.sourceJsx),placement:s,anchorLocator:a?fe(a):void 0,selectionContext:kn(o)}),this.buildPlan(t,n,M,i)}async planMoveNode(t,n,r,o){if(!o.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};let i=cu(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(zy(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 C=n.params.target.relation,R=i.anchorNode&&(C==="before"||C==="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:C,anchorSourceId:R?.kind==="external-entry"?R.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=po(r,a,this.graph.getTextProvenance?.(r.key,0)??null);if(d&&!Gi(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 C=a,R=await this.graph.getTextWriteTarget(u.key,0);if(C?.kind==="value-binding"&&R?.kind==="value-binding"&&C.locator&&R.locator){let w=Yn(C.locator),z=Yn(R.locator);if(w&&z&&C.file===R.file&&Gy(w.locator,z.locator)){let te=w.index,le=z.index,A=l==="before"?le-(te<le?1:0):le+(te<le?0:1);return this.buildPlan(t,n,[{order:0,file:C.file,type:"move-array-item",locator:w.locator,fromIndex:te,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=Gi(d)?d:m;if(p&&Gi(p)){let C=this.planRepeatTemplateInternalMove(t,n,r,s,o,l,u);if(C)return C;let R=this.planRepeatTemplateHoistMove(t,n,r,s,o,l,u);if(R)return R;let w=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,l,u);return w||{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 C=fo(s,{kind:"native-tag",tag:r.tag});if(C)return{ok:!1,errorCode:"unsupported-operation",reason:C}}if(c)return this.planCrossFileMove(t,n,r,s,o,l,u);let E=Yl(this.graph.getFileContent(r.file),r,s);if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:E.reason??`Cannot move node because it depends on bindings outside the target scope: ${E.bindingNames.join(", ")}`};let v=[{order:0,file:r.file,type:"move-node",locator:fe(r),targetParentLocator:fe(s),placement:l,anchorLocator:u?fe(u):void 0,selectionContext:kn(s)}];return this.buildPlan(t,n,v,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,u=this.graph.getFileContent(r.file),d=Yi(this.graph,r)??`<${r.component} />`,m=Kl(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,v={moduleSpecifier:es(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:v.moduleSpecifier,imports:v.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:kn(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:kn(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:ce(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 $u from"@babel/parser";import ps from"@babel/traverse";import*as b from"@babel/types";var Vu=typeof ps=="function"?ps:ps.default;function Uu(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}var Tu=new WeakMap;function Nu(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 Ku(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=vs(s,t,n);if(!a)return null;let c=Rs(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 Ms({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??tr(c.node,n),sourceKind:p.sourceKind,...p.collectionIndexMap?{collectionIndexMap:p.collectionIndexMap}:{},...p.collectionPathMap?{collectionPathMap:p.collectionPathMap}:{}}}let u=new Set,d=await Px({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 Ju(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=vs(i,t,n);if(!s)return null;let a=e.expression!==void 0?(e.sourceRange?Wu(s,n,e.expression,e.sourceRange):null)??As(s,n,e.expression):e.sourceRange?Rs(s,e.sourceRange):null;if(!a)return null;let c=rx(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 De({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 Vx({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 nx(d,e.expression??tr(c.node,n))}async function Cs(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=vs(i,t,n);if(!s)return Oe("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?ox({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}):ix({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}function Xu(e){try{return $u.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function vs(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=Xu(n);return e.set(t,{source:n,ast:o}),o}function Rs(e,t){let n=null,r=-1;for(let o of er(e).expressions){let i=o.node.loc;if(!i||!Ps(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s>=r&&(n=o,r=s)}return n}function ex(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of er(e).expressions){if(!tx(o.node.loc,t))continue;let i=(o.node.end??0)-(o.node.start??0);i<=r&&(n=o,r=i)}return n}function zu(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of er(e).jsxElements){let i=o.node.loc;if(!i||!Ps(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s<=r&&(n=o,r=s)}return n}function er(e){let t=Tu.get(e);if(t)return t;let n={expressions:[],jsxElements:[]};return Vu(e,{Expression(r){n.expressions.push(r)},JSXElement(r){n.jsxElements.push(r)}}),Tu.set(e,n),n}function tx(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 Ps(e,t){let n=Fu({line:e.start.line,column:e.start.column},{line:t.startLine,column:t.startColumn}),r=Fu({line:e.end.line,column:e.end.column},{line:t.endLine,column:t.endColumn});return n>=0&&r<=0}function Hu(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 Fu(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 id(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:tr(e.expression,e.source),base:t.base,path:t.path}:null}function nx(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 rx(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 tr(e,t){if(t)return ws(e,t);let n=Gx(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function ws(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function As(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of er(e).expressions){if(ws(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function Wu(e,t,n,r){let o=null,i=Number.POSITIVE_INFINITY;for(let s of er(e).expressions){if(ws(s.node,t)!==n)continue;let a=s.node.loc;if(!a||!Ps(a,r))continue;let c=(s.node.end??0)-(s.node.start??0);c<=i&&(o=s,i=c)}return o}async function ox(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=Rs(r,o.sourceRange),u=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 sx(t,o.value);let m=await Ms({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"?Lu(t,m):Es(t,tr(l.node,n),m):ax({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return Oe("unsupported-expression","Unable to locate text expression for provenance resolution");let d=await De({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=xs(l.node);if(m)return Oe(m.code,m.message);let p=l.scope.getBinding(u.base);if(p?.path.isVariableDeclarator()){let h=xs(p.path.node.init);if(h)return Oe(h.code,h.message)}return p?.path.isVariableDeclarator()&&b.isCallExpression(p.path.node.init)?cx("unsupported-expression",qu(p.path.node.init,e.functionCallContracts)):Oe("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return d.kind==="external"?Lu(t,d):Es(t,u.expression,d)}async function ix(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return Oe("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=As(r,n,o.conditionExpression);if(!l)return Oe("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await De({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 Oe("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(u.kind==="external")return Oe("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let d=Es(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 sx(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 ax(e){let t=await Gu(e);if(t.length===0)return Oe("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(lx(e.expression))return Yu(t);if(Qu(e.expression))return Oe("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 Oe("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return Oe(n.code,n.message)}function Oe(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function cx(e,t){return Yu([{code:e,message:t}])}function Yu(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function lx(e){return b.isCallExpression(e)||b.isConditionalExpression(e)||b.isLogicalExpression(e)||b.isBinaryExpression(e)}function qn(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 Gu(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=xs(t);if(l)return[l];if(b.isCallExpression(t))return[{code:"unsupported-expression",message:qu(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)?qn([...await ms(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)?qn([...await ms(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)?qn([...await ms(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 xs(e){return Qu(e)?Mu("i18n helpers require a static message id string"):mx(e)?Mu("CMS helpers require static entry id and field path string arguments"):null}async function ms(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await Gu({...t,expression:o}));return r}function ux(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:[dx(e.sourceType)]}}async function Ts(e){for(let n of xx){if(!_u(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return Du(Ou(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(!_u(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return Du(Ou(r),e.externalAdapters)}return null}function dx(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function fx(e){return{code:"external-source-readonly",message:e}}function Mu(e){return{code:"unsupported-expression",message:e}}function Ns(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 _u(e,t){if(!t||t.length===0)return!0;let n=Ns(e.node);return n?t.includes(n):!1}function Ou(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:qn(e.diagnostics??[])}:{match:e,diagnostics:[]}}function Du(e,t){let n=ux(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:qn([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function px(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 mx(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 Zu(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 Qu(e){return Zu(e)===null}async function hx(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 gx(e){let t=Zu(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await hx(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function yx(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:[fx("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var xx=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>px(e)},{helperNames:["apiField"],resolve:e=>yx(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>gx({currentFile:e,expressionPath:t,exists:n})}];function Lu(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 Es(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=Rx(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 Ex=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function Fs(e,t){let n=[...Ex,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function qu(e,t){let n=e.callee;return b.isIdentifier(n)&&Fs(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 Ms(e){let t=await Ts(e);if(t)return t;let n=await ed({...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 De({...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 Cx(e)}async function ed(e){let t=await qe({...e,allowComposed:!1});return t?.kind==="source"?t.provenance:null}async function qe(e){let t=Sx(e.expressionPath),n=kx(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 De({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 De({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 hs(s,a,c)}if(t.isCallExpression())return bx({...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 hs(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 hs(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 Sx(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 bx(e){let t=Ns(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 hs(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!Ix(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function Ix(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 kx(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function Cx(e){if(!e.expressionPath.isCallExpression())return null;let t=Ns(e.expressionPath.node);if(!t)return null;let n=Fs(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 td({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 td(e){let t=await Ts({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 De({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 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})}async function vx(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=Fs(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 td({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 Rx(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=yo(t,e.path);return{sourceId:o,displayPath:o}}async function Px(e){let t=e.segment.source;return t?De({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 De(e){let t=e.sourceInfo,n=nd(e.expressionPath,t.base);if(n){let l=await rd({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=Ax(n.callPath,[...n.basePath,...t.path]);return Xn(E)?Nu(e.currentFile,E.sourceId,E.displayPath):null}let u=Zx(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 an(e.currentFile,u.node.source.value,e.exists);if(!d)return null;let m=await go({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=zl(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 De({...e,expressionPath:l,sourceInfo:{...u,expression:yo(u.expression,t.path),path:[...u.path,...t.path]}});if(d)return d}if(t.path.length===0){let d=await ed({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 zx({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 vx({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=oo(r,t.path);if(Xn(s))return Nu(e.currentFile,s.sourceId,s.displayPath);let a=await Gt({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 nd(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=Ge(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!wx(s,r)?null:{callPath:s,basePath:i}}function wx(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 rd(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 nr({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 Ax(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:so(r,t)}async function nr(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 Gt({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 od({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 nr({...e,expressionPath:a})}if(n.isArrayExpression()){let a=Hu(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 De({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 Tx({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=Qx(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 Tx(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 Mt(t.file,e.readFile,e.fileCache);i=s.ast?Is(s.ast).getBinding(t.root.name):void 0}return i?await Gt({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 Mt(t.file,e.readFile,e.fileCache);if(!n.ast)return null;let r=ex(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 od(e){return await Nx(e)??await Fx(e)??await Mx(e)}async function Nx(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 nr({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=_x(s);if(!c)return null;let l=[],u=[],d=[];for(let[m,p]of i.value.entries()){let h=Ox(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 Fx(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 nr({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 Mx(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 nr({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(Bu(s,a.name,c.name,d.value,m.value)===void 0)return null;return u.sort((d,m)=>{let p=Bu(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 Bu(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=Ss(i,t,n,r,o);return typeof s=="number"?s:void 0}function Ss(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=bs(e,t);if(i)return et(r,i);let s=bs(e,n);return s?et(o,s):void 0}if(b.isBinaryExpression(e)&&e.operator==="-"){let i=b.isExpression(e.left)?Ss(e.left,t,n,r,o):void 0,s=b.isExpression(e.right)?Ss(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function _x(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 Ox(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=bs(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 bs(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 Gt(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 Dx({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 Yx({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 Ts({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 od({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 Dx(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=Lx(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 Lx(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 jx(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 Bx(e,t){let n=jx(e.path);if(!n)return null;let r=In(e,t);return r?{...n,...r}:null}function yo(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function $x(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}async function Vx(e){let t=Kx(e.expressionPath.node);if(!t||!Jx(t.segments))return null;let n=await De({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 Ux({...e,rootPath:n.path,segments:t.segments});return r?{...n,path:r.collectionPathMap[0]??n.path,sourceKind:"repeat-template",displayExpression:tr(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:r.collectionPathMap}:null}async function Ux(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=nd(e.expressionPath,s.base);if(!a)return null;let c=await rd({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 Xx(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 Kx(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 Jx(e){return e.some(t=>t.kind==="dynamic")}function Xx(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}async function zx(e){let t=Bx(e.binding,e.sourceInfo);if(!t||!e.graph)return null;let n=[...e.graph.elements.values()].filter(l=>$x(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 Hx({caller:r,propName:t.propName,remainingPath:t.remainingPath,readFile:e.readFile,fileCache:e.fileCache});if(l)return gs(l,{componentName:t.componentName,propName:t.propName,file:r.sourceFile})}if(!o?.source){let l=await Wx({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 gs(l,{componentName:t.componentName,propName:t.propName,file:r.sourceFile});let u=Wl(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 Mt(r.sourceFile,e.readFile,e.fileCache);if(!i.ast)return null;let s=Wu(i.ast,i.source,o.source.expression,o.sourceRange)??As(i.ast,i.source,o.source.expression);if(!s)return null;let a={...o.source,expression:yo(o.source.expression,t.remainingPath),path:[...o.source.path,...t.remainingPath]},c=await De({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?gs(c.kind==="external"?c:{...c,displayExpression:a.expression},{componentName:t.componentName,propName:t.propName,file:r.sourceFile}):null}async function Hx(e){let t=await Mt(e.caller.sourceFile,e.readFile,e.fileCache);if(!t.ast)return null;let n=zu(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=Hu(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 Wx(e){let t=await Mt(e.caller.sourceFile,e.readFile,e.fileCache);if(!t.ast)return null;let n=zu(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:yo(s.expression,a),path:[...s.path,...a]},l=await De({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 gs(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 Yx(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 an(t,c,o);if(!l)return null;if(n.path.isImportDefaultSpecifier()){let E=await Mt(l,r,i),v=E.ast?ks(E.ast,"default"):null,C=await go({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!C||C.kind!=="static"?null:{kind:"static",file:v?.kind==="default-expression"?C.file:l,root:v?.kind==="default-expression"?C.root:{kind:"default-export"},value:C.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 Mt(l,r,i),p=m.ast?ks(m.ast,d):null,h=await go({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 go(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 Mt(t,r,i);if(!c.ast)return;let l=ks(c.ast,n);if(!l)return;if(l.kind==="default-expression"){let p=l.expression;if(!p||!b.isIdentifier(p))return;let h=Is(c.ast).getBinding(p.name);return h?await Gt({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 an(t,l.source,o);return p?go({...e,file:p,exportName:l.name}):void 0}let u=l.name;if(!u)return;let d=Is(c.ast).getBinding(u);return d?await Gt({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 Is(e){let t=null;if(Vu(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}function ks(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 Gt({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 ys(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 ys(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 ys(c.value,t,n,r,o,i,s);u!==void 0&&(a[l]=u)}return a}if(b.isMemberExpression(e)){let a=await id(e,t,n,r,o,i,s);if(!a)return;let c=t.getBinding(a.base);if(!c)return;let l=await Gt({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 ys(e,t,n,r,o,i,s){if(!b.isSpreadElement(e))return await nt(e,t,n,r,o,i,s)}async function id(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 Gx(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 Zx(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 Qx(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 Mt(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=Xu(o),s={source:o,ast:i};return n.set(e,s),s}import js from"@babel/generator";import{parse as uE}from"@babel/parser";import Bs from"@babel/traverse";import*as k from"@babel/types";import*as ld from"@babel/types";import _s from"@babel/generator";import*as se from"@babel/types";var qx=typeof _s=="function"?_s:_s.default,eE=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,tE=/^((?:https?:)?\/\/)[^/@\s]+@/i,nE=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function ad(e,t){let n=ct(e.callee);if(!n)return null;if(n==="fetch")return Os(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(sd(r))return Os(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(sd(r))return Os(e.arguments[0],r,t,["ky client contract"])}return null}function Os(e,t,n,r){if(!e||se.isSpreadElement(e)||se.isJSXNamespacedName(e))return sE(t,n,r,"missing url argument");let o=rr(e);return{sourceKind:iE(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 rr(e){if(se.isStringLiteral(e))return xo(e.value);if(se.isTemplateLiteral(e))return xo(rE(e));if(se.isBinaryExpression(e)&&e.operator==="+"){let t=rr(e.left),n=rr(e.right);return!t&&!n?void 0:xo(`${t??Ds(e.left)}${n??Ds(e.right)}`)}if(se.isMemberExpression(e)){let t=cd(e);if(t)return`env:${t}`}if(!(se.isCallExpression(e)&&ct(e.callee)==="new URL")){if(se.isNewExpression(e)&&se.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!se.isSpreadElement(t)?rr(t):void 0,o=n&&!se.isSpreadElement(n)?rr(n):void 0;return o&&r?xo(`${o} + ${r}`):r??o}if(se.isIdentifier(e))return`:${e.name}`}}function rE(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+=Ds(r))}return t}function Ds(e){if(se.isIdentifier(e))return`:${e.name}`;if(se.isMemberExpression(e)){let t=cd(e);if(t)return`env:${t}`}return`:${oE(e)}`}function oE(e){return qx(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function xo(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(tE,"$1<redacted>@").replace(nE,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?eE.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function iE(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 sE(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function sd(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function cd(e){return!se.isMemberExpression(e.object)||!se.isIdentifier(e.object.object,{name:"process"})||!aE(e.object.property,"env")?null:se.isIdentifier(e.property)?e.property.name:se.isStringLiteral(e.property)?e.property.value:null}function aE(e,t){return se.isIdentifier(e)&&e.name===t}function ct(e){if(se.isIdentifier(e))return e.name;if(se.isMemberExpression(e)){let t=ct(e.object),n=se.isIdentifier(e.property)?e.property.name:se.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var cE=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),lE=new Set(["getConfig","submit"]);function ud(e,t){let n=ct(e.callee);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!cE.has(i))return null;let s=Ls(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(!lE.has(i))return null;let s=Ls(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=Ls(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 dd(e,t){let n=ct(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 fd(e){let t=ct(e.callee);return typeof t=="string"&&t.startsWith("cms.field.")}function Ls(e,t){let n=e.arguments[t];return ld.isStringLiteral(n)?n.value:null}var Us=typeof Bs=="function"?Bs:Bs.default,CR=typeof js=="function"?js:js.default,dE={maxFunctionDepth:8,maxImportDepth:6},fE=new Set(["src","href","alt","poster","content","title","aria-label"]);async function xd(e){let t=e.fileCache??new Map,n=zs(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...dE,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:Fd(n,e.element.componentName)};await Ed(e.element.componentName,e.graph,r);let o=[];o.push(...await yE(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await xE(s,e.element,e.graph,r);a&&o.push(Vs(a,"text","children"))}for(let s of e.element.attributes??[]){let a=gE(s);if(!a)continue;let c=await Id(s.source,e.element,e.graph,r);c&&o.push(Vs(c,a,s.name))}let i=ME(o).sort(Td);return{hasDynamicData:i.length>0,bindings:i}}async function Ed(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 Sd(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 bd(l.sourceFile,n);if(!d)continue;let m=bo(d,n,{importDepth:n.importDepth+1});m.paramSources.clear(),m.scopeVariables=Fd(d,l.componentName),await Ed(l.componentName,t,m);let p=await pE(l,m);for(let[h,E]of p){if(!E)continue;let v=a.get(h)??[];v.push(E),a.set(h,v)}}finally{n.resolvingComponentProps.delete(u)}}}let c=new Map;for(let[l,u]of a){let d=wd(u);d.length===1&&c.set(l,d[0])}hE(o,c,n)}async function Sd(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 bd(e,r))?.imports.get(t);if(!s||!ut(s.source))return!1;let a=await Od(e,s.source,r.exists);return a?a===n?!0:Sd(a,s.importedName,n,r,o):!1}async function pE(e,t){let n=new Map;Us(t.analysis.ast,{JSXElement(o){if(mE(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 mE(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 bd(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 zs(e,r,t.fileCache)}function hE(e,t,n){if(k.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,Xs(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,ve(o))}}function gE(e){return e.name==="dangerouslySetInnerHTML"?"richtext":fE.has(e.name)?"attribute":null}async function yE(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 Ks(i.collectionSource,n);s&&r.push(Vs(Rn(s),"repeat-region",i.collectionExpression))}return r}async function xE(e,t,n,r){return Id(e.source,t,n,r)}async function Id(e,t,n,r){let o=await EE(e,t,n,r);return o||Ks(e,r)}async function EE(e,t,n,r){if(!e)return null;let o=SE(e.base,t,n);if(!o)return null;let i=await Ks(o.collectionSource,r);return i?ar(i,e.path,!0):null}function SE(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 Ks(e,t){if(!e)return null;let n=await kd(e.base,t);return n?ar(n,e.path,!1):null}async function kd(e,t){let n=t.paramSources.get(e);if(n)return ve(n);if(t.variableCache.has(e))return _E(t.variableCache.get(e)??null);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let r=await bE(e,t);if(r)return t.variableCache.set(e,ve(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?ve(s):null),t.resolvingVariables.delete(e),s}let i=t.analysis.imports.get(e);if(i&&t.importDepth<t.options.maxImportDepth){let s=await Md(i,t);if(s){let a=bo(s,t,{importDepth:t.importDepth+1}),c=_d(i,s);if(c){let d=(await Zt(c,[],a)).returnSource;return t.variableCache.set(e,d?ve(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?ve(u):null),t.resolvingVariables.delete(e),u}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}async function bE(e,t){let n=t.analysis.stateSetters.get(e);if(!n)return null;let r=[];Us(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 kd(e.name,t);if(k.isMemberExpression(e)||k.isOptionalMemberExpression(e)){let n=k.isMemberExpression(e)?dd(e,{file:t.file}):null;if(n)return Pd(n);let r=await IE(e,t);if(!r)return null;let o=NE(e);return ar(r,o,!1)}if(k.isAwaitExpression(e))return k.isExpression(e.argument)?ke(e.argument,t):null;if(k.isCallExpression(e))return Cd(e,t);if(k.isObjectExpression(e)){let n=await vd(e,t);return Object.keys(n).length>0?Xs(n,t.file):null}if(k.isConditionalExpression(e)){let n=await ke(e.consequent,t),r=await ke(e.alternate,t);return sr(md(n,r))}if(k.isLogicalExpression(e)){let n=await ke(e.left,t),r=await ke(e.right,t);return sr(md(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 IE(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 Cd(e,t){let n=ud(e,{file:t.file});if(n)return Pd(n);if(fd(e)){let d=e.arguments[0];if(d&&k.isExpression(d))return sr(await ke(d,t))}let r=await kE(e,t);if(r)return r;let o=ad(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 RE(e,t);if(i)return i;let s=await PE(e,t);if(s)return s;let a=await wE(e,t);if(a)return a;let c=await AE(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=wd(l);return u.length===1?sr(u[0]):null}async function kE(e,t){let n=ct(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=vE(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(k.isIdentifier(s)){let a=await ir(s.name,t);if(a)return(await Zt(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!k.isObjectExpression(r))return Eo(t.file,`${n} without static options`);let o=CE(r,"queryFn");if(!o)return Eo(t.file,`${n} without queryFn`);if(k.isIdentifier(o)){let i=await ir(o.name,t);return i?(await Zt(i.node,[],i.context)).returnSource:Eo(t.file,`${n} queryFn unresolved`)}return k.isArrowFunctionExpression(o)||k.isFunctionExpression(o)?(await Zt(o,[],t)).returnSource:k.isCallExpression(o)?Cd(o,t):null}function CE(e,t){for(let n of e.properties){if(!k.isObjectProperty(n)||!k.isExpression(n.value))continue;if(Rd(n)===t)return n.value}return null}function vE(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 RE(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 Rn(r);let o=e.arguments[0];if(k.isIdentifier(o)){let i=await ir(o.name,t);if(!i)return Rn(r);let s=await Zt(i.node,[r],i.context);return{...Rn(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(k.isArrowFunctionExpression(o)||k.isFunctionExpression(o)){let i=await Zt(o,[r],t);return{...Rn(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return Rn(r)}async function PE(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 wE(e,t){return!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property,{name:"then"})||!k.isExpression(e.callee.object)?null:sr(await ke(e.callee.object,t))}async function AE(e,t){if(!k.isIdentifier(e.callee))return null;let n=await ir(e.callee.name,t);if(!n)return null;let r=[];for(let i of e.arguments){if(!k.isExpression(i)){r.push(Eo(t.file,`unsupported argument for ${e.callee.name}`));continue}let s=await ke(i,t);r.push(s)}return(await Zt(n.node,r,n.context)).returnSource}async function ir(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 Md(r,t);if(!o)return null;let i=bo(o,t,{importDepth:t.importDepth+1}),s=_d(r,o);return s?{node:s,context:i}:ir(r.importedName,i)}async function Zt(e,t,n){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let r=bo(n.analysis,n,{functionDepth:n.functionDepth+1});r.scopeVariables=n.analysis.functionVariables.get(e),e.params.forEach((c,l)=>{let u=t[l];u&&$s(c,FE(u),r)});let o=TE(e),i=null,s,a=!1;for(let c of o){if(k.isObjectExpression(c)){s={...s??{},...await vd(c,r)},i=i??Xs(s,n.file);continue}let l=await ke(c,r);if(l){if(!i){i=l;continue}let u=Js(i,l);if(!u){a=!0,i=null;continue}i=u}}return{returnSource:a?null:i,...s?{objectReturnMap:s}:{}}}function $s(e,t,n){if(k.isIdentifier(e)){n.paramSources.set(e.name,ve(t));return}if(k.isAssignmentPattern(e)){$s(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=ar(t,[{kind:"property",name:r.key.name}],!0),i=k.isAssignmentPattern(r.value)?r.value.left:r.value;$s(i,o,n)}}function TE(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 vd(e,t){let n={};for(let r of e.properties){if(!k.isObjectProperty(r))continue;let o=Rd(r);if(!o||!k.isExpression(r.value))continue;let i=await ke(r.value,t);i&&(n[o]=i)}return n}function Rd(e){return k.isIdentifier(e.key)&&!e.computed?e.key.name:k.isStringLiteral(e.key)?e.key.value:null}function NE(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 ar(e,t,n){if(t.length===0)return ve(e);let r=t[0];if(r?.kind==="property"&&e.fieldMap?.[r.name])return ar(e.fieldMap[r.name],t.slice(1),n);let o=ve(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=or(o.valuePath,"data.items[]"),o.cmsFieldRoot=!1,o):i[0]==="fields"?(o.fieldPath=or(o.fieldPath,i.slice(1).join(".")),o.cmsFieldRoot=!0,o):o.cmsFieldRoot||n||o.fieldMap?(o.fieldPath=or(o.fieldPath,i.join(".")),o):(o.valuePath=or(o.valuePath,pd(t)),o)}return o.valuePath=or(o.valuePath,pd(t)),o}function pd(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function or(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function Pd(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 Rn(e){let t=ve(e);return t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function FE(e){let t=ve(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&(t.cmsFieldRoot=!1),t}function sr(e){return e?{...ve(e),confidence:e.confidence==="unknown"?"unknown":"safe-derived",evidence:[...e.evidence,{file:e.evidence[0]?.file??"unknown",reason:"safe derived expression"}]}:null}function md(e,t){return e?t?Js(e,t):ve(e):t?ve(t):null}function Js(e,t){if(So(e)!==So(t))return null;let n=Nd(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function wd(e){let t=new Map;for(let n of e){let r=So(n),o=t.get(r);t.set(r,o?Js(o,n):ve(n))}return[...t.values()]}function So(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,So(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 Xs(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 Eo(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function Vs(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 Ad(e){let t=[...e].sort(Td),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 ME(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 Td(e,t){return hd(e.targetKind)-hd(t.targetKind)||Nd(e.confidence,t.confidence)||gd(e.sourceKind)-gd(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function hd(e){return{"repeat-region":0,text:1,richtext:2,attribute:3,"component-prop":4}[e]}function gd(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function Nd(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function zs(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=uE(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 Us(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 Pn(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)&&ct(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)&&yd(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)&&yd(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 Pn(e){return!e||k.isVoidPattern(e)?[]:k.isIdentifier(e)?[e.name]:k.isObjectPattern(e)?e.properties.flatMap(t=>k.isObjectProperty(t)?Pn(t.value):Pn(t.argument)):k.isArrayPattern(e)?e.elements.flatMap(t=>t?Pn(k.isRestElement(t)?t.argument:t):[]):k.isAssignmentPattern(e)?Pn(e.left):k.isRestElement(e)?Pn(e.argument):[]}function yd(e){return k.isFunctionExpression(e)||k.isArrowFunctionExpression(e)}function Fd(e,t){let n=e.functions.get(t)??e.functions.get("default");return n?e.functionVariables.get(n):void 0}async function Md(e,t){let n=await Od(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return zs(n,r,t.fileCache)}function _d(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function Od(e,t,n){return ut(t)?an(e,t,n):null}function bo(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 _E(e){return e?ve(e):null}function ve(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,ve(n)]))}:{}}}var OE=50,DE=8*1024*1024;function Bd(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??OE),s=Math.max(0,t.maxUndoBytes??DE);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:u,redo:d};async function a(A){let M=[...A.steps].sort((W,Q)=>W.order-Q.order),O=M.filter(W=>W.type!=="invoke-external-adapter");if(O.length!==M.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let j=new Set(O.map(W=>W.file)),ee=await R(j),G=new Map(ee.map(W=>[W.file,W.exists===!1?"":W.content])),xe;for(let W of O){let Q=jd(W,G.get(W.file)??"");if(!Q.ok)return{ok:!1,errorCode:Q.errorCode,reason:Q.reason};G.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:[...G].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 M=[...A.steps].sort((ge,xt)=>ge.order-xt.order),O=M.filter(ge=>ge.type!=="invoke-external-adapter"),j=M.filter(ge=>ge.type==="invoke-external-adapter"),ee=new Set(O.map(ge=>ge.file));if(O.length>0&&j.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 v(A,j);let G=await R(ee),xe=new Map;for(let ge of G)xe.set(ge.file,ge.exists===!1?"":ge.content);let W;for(let ge of O){let xt=xe.get(ge.file)??"",lt=jd(ge,xt);if(!lt.ok)return{ok:!1,operationId:A.operationId,errorCode:lt.errorCode,reason:lt.reason,rolledBack:!1};xe.set(ge.file,lt.source),lt.selectionRef&&(W=lt.selectionRef)}let Q=await z([...xe].map(([ge,xt])=>({file:ge,content:xt,exists:!0,version:0,sha256:ce(xt)})),G);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:G,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 M=new Set(A.edits.map(Q=>Q.file)),O=await R(M),j=C(A,O);if(j)return{ok:!1,operationId:A.operationId,errorCode:"stale-version",reason:j.reason,affectedFiles:[j.file],rolledBack:!1};let ee=new Map(O.map(Q=>[Q.file,Q])),G=A.edits.find(Q=>Q.operation==="create-only"&&ee.get(Q.file)?.exists!==!1);if(G)return{ok:!1,operationId:A.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${G.file}`,affectedFiles:[G.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:ce(Q.content)}),W=await z(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:[...M]})}async function u(){let A=n.at(-1);if(!A)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let M=await z(A.preSnapshots,A.postSnapshots);return M.ok===!1?{ok:!1,operationId:A.operationId,errorCode:M.rolledBack?"writeback-failed":"rollback-failed",reason:M.reason,rolledBack:M.rolledBack}:(n.pop(),r.push(A),{ok:!0,operationId:A.operationId,kind:A.plan.kind,target:A.plan.target,resultVersion:Math.max(...M.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 M=await z(A.postSnapshots,A.preSnapshots);return M.ok===!1?{ok:!1,operationId:A.operationId,errorCode:M.rolledBack?"writeback-failed":"rollback-failed",reason:M.reason,rolledBack:M.rolledBack}:(r.pop(),n.push(A),m(),{ok:!0,operationId:A.operationId,kind:A.plan.kind,target:A.plan.target,resultVersion:Math.max(...M.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,M)=>A+h(M),0)}function h(A){return E(A.preSnapshots)+E(A.postSnapshots)}function E(A){return A.reduce((M,O)=>M+O.file.length+O.content.length,0)}async function v(A,M){let O=[];for(let j of M){let ee=j.capability??"write-text",G=o.find(W=>W.sourceType===j.sourceType&&(j.adapterId===void 0||W.adapterId===j.adapterId)&&(W.capabilities===void 0||W.capabilities.includes(ee)));if(!G)return{ok:!1,operationId:A.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${j.sourceType}`,rolledBack:!1};let xe=await G.execute(j);if(!xe.ok)return{ok:!1,operationId:A.operationId,errorCode:"writeback-failed",reason:xe.reason??`External adapter failed for ${j.sourceType}`,rolledBack:!1};O.push(j.file)}return{ok:!0,operationId:A.operationId,kind:A.kind,target:A.target,resultVersion:0,affectedFiles:O}}function C(A,M){if(A.conflictPolicy!=="compare-and-swap")return null;let O=new Map(M.map(j=>[j.file,j]));for(let j of A.edits){if(j.operation==="create-only")continue;if(j.baseContentHash===void 0)return{file:j.file,reason:`Source file ${j.file} is missing baseContentHash. Reopen the file before saving.`};let ee=O.get(j.file),G=j.baseContentHash;if(G===null){if(ee?.exists!==!1)return{file:j.file,reason:`Source file ${j.file} was created or changed before save.`};continue}if(!G)return{file:j.file,reason:`Source file ${j.file} is missing baseContentHash. Reopen the file before saving.`};if(ee?.exists===!1||ee?.sha256!==G)return{file:j.file,reason:`Source file ${j.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function R(A){let M=[];for(let O of A)M.push(await w(O));return M}async function w(A){if(!await e.exists(A))return{file:A,content:"",version:0,exists:!1};let O=Math.max(1,e.getVersion(A)),j=await e.readFile(A);return{file:A,content:j,version:O,exists:!0,sha256:ce(j)}}async function z(A,M,O=new Set){let j=[];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 te(ee);let G=e.bumpVersion(ee.file);j.push(ee.file),ee.version=G}}catch(ee){let G=await le(M.filter(W=>j.includes(W.file)));if(G.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${G.failedFiles.join(", ")}: ${Ld(ee)}`,rolledBack:!1,instanceConflict:Dd(ee)};let xe=Dd(ee);return{ok:!1,reason:`${xe?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${Ld(ee)}`,rolledBack:!0,instanceConflict:xe}}return{ok:!0,snapshots:A.map(LE)}}async function te(A){if(A.exists===!1){await e.deleteFile(A.file);return}await e.writeFile(A.file,A.content)}async function le(A){let M=[];for(let O of A)try{await te(O),e.bumpVersion(O.file)}catch{M.push(O.file)}return M.length===0?{ok:!0}:{ok:!1,failedFiles:M}}}function Dd(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function LE(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:ce(e.content)}:{}}}function Ld(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 Fe(xn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return Fe(En({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return Fe(pn({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return Fe(hn({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return Fe(Jr({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return Fe(Un({source:t,locator:e.locator,next:e.value}));case"update-array-item":return Fe(Un({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return Fe(Wr({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return Fe(Xr({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return Fe(Yr({source:t,locator:e.locator,index:e.index}));case"move-array-item":return Fe(Gr({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return Fe(yn({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return Fe(zr({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 jE(e,t);case"set-props":{let n=e;return Fe(Hr({source:t,locator:n.locator,props:n.props}))}default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function jE(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!Ol(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!==ce(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:_l({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function Fe(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 $d(){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 BE}from"node:crypto";import Io from"node:fs/promises";import Hs from"node:path";import{setTimeout as $E}from"node:timers/promises";var VE={async mkdir(e,t){await Io.mkdir(e,t)},async writeFile(e,t,n){await Io.writeFile(e,t,n)},async rename(e,t){await Io.rename(e,t)},async rm(e,t){await Io.rm(e,t)}},UE=new Set(["EACCES","EBUSY","EPERM"]),KE=[10,20,40,80,160];async function JE(e,t,n){for(let r of KE)try{await e.rename(t,n);return}catch(o){if(!XE(o))throw o;await $E(r)}await e.rename(t,n)}function XE(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&UE.has(e.code)}async function ko(e,t,n=VE){let r=Hs.dirname(e),o=Hs.basename(e),i=Hs.join(r,`.${o}.${process.pid}.${BE()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await JE(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import{randomBytes as iS}from"node:crypto";import yt from"node:path";import{parse as sS}from"@babel/parser";import aS from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as vo,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as Ud,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as cS,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as lS,SiteEditMaterializationSchema as uS,parseComponentI18nResourcesJson as dS}from"@vcp-dev/contracts";var Vd=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,zE=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,HE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,WE=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,YE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,GE=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,ZE=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,QE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,qE=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,eS=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,tS=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,nS=/\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,rS=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,oS=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function cr(e,t){let n=Co([...Je(e,HE),...Je(e,WE),...Je(e,YE),...Je(e,t.includeRgbBackgroundImage?GE:ZE),...t.includeExtendedColorFunctions?[...Je(e,QE),...Je(e,qE)]:[]]),r=Co([...Je(e,eS),...Je(e,tS)]).filter(o=>t.colorMixPolicy==="always"||Vd.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...Je(e,nS).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...Je(e,oS).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:Co(Je(e,zE)),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?Co(Je(e,rS)):[]}}function Je(e,t){return e.match(new RegExp(t.source,t.flags))??[]}function Co(e){return[...new Set(e)]}var Gs="components/site/generated",Kd="{{$INSTANCE}}",Ro=5,fS=/^[a-z][a-z0-9-]{0,48}$/,pS=/^[a-f0-9]{8}$/,Jd=/\.tsx?$/,mS=/\.json$/,hS=/\.(?:tsx?|json)$/,gS=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,yS=["react","react/","next","next/","lucide-react","react-i18next","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],Ws=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Ys=aS,xS=typeof Ys=="function"?Ys:Ys.default;function ES(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>Ud)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=TS(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=uS.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=PS(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${Gs}.`,path:e.generatedRoot}};if(!Gd(r.data.instanceBaseName))return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_INVALID",message:"Static prefab instanceBaseName must contain at least one safe word.",path:r.data.instanceBaseName}};let i=Hd(r.data.files),s=Hd(e.controlledFiles);if(!NS(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>Ud)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let a=0;for(let[c,l]of r.data.files.entries()){let u=Buffer.byteLength(l.content,"utf8");if(u>cS)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>lS?{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 SS(e){let t=ES(e);if(!t.ok)return t;let n=t.data.generatedRoot,r=Gd(e.manifest.instanceBaseName),o=Math.max(1,Math.min(Ro,e.maxAttempts??Ro));for(let i=0;i<o;i+=1){let s=wS(e.instanceNameGenerator?.()??iS(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=Qd(n,a),l=bS({manifest:e.manifest,generatedRoot:n,instanceName:a,instanceRoot:c,allowedExternalImports:e.allowedExternalImports??yS});if(!l.ok)return l;if(!await IS(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 Yd(e){let t=Math.max(1,Math.min(Ro,e.maxAttempts??Ro));for(let n=0;n<t;n+=1){let r=await SS({...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 bS(e){let t=[],n=new Set;for(let i of e.manifest.files){let s=Xd({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=Xd({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=kS(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 IS(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function Xd(e){if(e.pathTemplate.split(Kd).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(Kd,e.instanceName),n=AS(t);return n?Qd(e.generatedRoot,e.instanceName)!==e.instanceRoot?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab instance root normalization failed.",path:e.pathTemplate}}:n!==e.instanceRoot&&!n.startsWith(`${e.instanceRoot}/`)?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab path must stay under components/site/generated/<instance>.",path:n}}:n!==t?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab path template cannot rely on path normalization semantics.",path:e.pathTemplate}}:n===e.instanceRoot||!hS.test(n)||gS.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 kS(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(mS.test(d.path)){if(d.path.endsWith(vo)){let h=dS(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=sS(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=cr(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(!Jd.test(d.path))continue;let m=s.get(d.path),p=null;if(xS(m,{ImportDeclaration(h){let E=zd({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(vo))){let v=CS({importer:d.path,imported:E.internalPath,source:h.node.source.value,ast:m});v.ok?c.get(E.internalPath).add(d.path):(p??=v.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=zd({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=Wd(h.node);E&&Ws.has(E)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${E}.`,file:d.path},h.stop())},OptionalMemberExpression(h){let E=Wd(h.node);E&&Ws.has(E)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${E}.`,file:d.path},h.stop())},Identifier(h){h.isReferencedIdentifier()&&Ws.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(!Jd.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(!vS(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 RS(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:Gs,instanceRoot:"",entry:{path:"",export:{kind:"default"}},files:[]}}}function zd(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 CS(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,-vo.length),i=`./${r}${vo}`;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 vS(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 RS(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 PS(e){let t=Zd(e);return t===Gs?t:null}function wS(e){let t=e.trim().toLowerCase();return pS.test(t)?t:null}function Gd(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 fS.test(t)?t:null}function Zd(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 AS(e){let t=Zd(e);return!t||t!==e?null:t}function Qd(...e){return yt.posix.join(...e)}function Hd(e){return new Set(e.map(t=>t.pathTemplate))}function TS(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 NS(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Wd(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 FS}from"node:crypto";import Po from"node:path";import{parse as sf}from"@babel/parser";import MS from"@babel/traverse";import*as af from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as Qs,PageResourceArtifactSchema as _S,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as OS,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as DS,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as LS,parseComponentI18nResourcesJson as jS}from"@vcp-dev/contracts";var qs="{{$INSTANCE}}",BS=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,ea="components/site/generated",$S=/\.(?:tsx?|json)$/,VS=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,US=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],KS=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Zs=MS,JS=typeof Zs=="function"?Zs:Zs.default;async function ta(e){let t=_S.safeParse(e.artifact);if(!t.success)return me("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>FS(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=qS(r());if(!i)return me("Random instance suffix must be 8 lowercase hex chars.");let s=`${eb(n.resource_id)}-${i}`,a=new Map,c=[];for(let R of n.pages){let w=R.final_route.slice(1);a.set(R.template_page_id,R.final_route),c.push({template_page_id:R.template_page_id,title:R.title,final_route:R.final_route,route_file_path:`app/${w}/page.tsx`})}let l=[],u=new Set,d=new Set,m=new Map,p=new Map,h=[],E=new Set(n.pages.flatMap(R=>R.components.map(w=>w.component_id)));for(let R of n.components){if(!E.has(R.component_id))continue;let w=qd({materialization:R.materialization,packageInstanceId:s,routeByPage:a});if(!w.ok)return w;for(let z of w.files){let te=tf(z,u,l);if(te)return te}d.add(w.entry),p.set(w.entry,w.entryExport),m.set(R.component_id,w.entry)}for(let[R,w]of n.pages.entries()){let z=c[R],te=qd({materialization:w.materialization,packageInstanceId:s,routeByPage:a,pageEntryTarget:z.route_file_path});if(!te.ok)return te;for(let M of te.files){let O=tf(M,u,l);if(O)return O}d.add(te.entry),p.set(te.entry,te.entryExport),h.push({entry:te.entry,declaredComponentIds:new Set(w.components.map(M=>M.component_id))});let le=l.find(M=>M.file===z.route_file_path);if(!le)return me("Page materialization entry did not resolve to its final route file.",z.route_file_path);if(YS(le.content,z.route_file_path)!==z.final_route)return me(`Page ${w.template_page_id} requires a static PAGE_SEO.path equal to ${z.final_route}.`,z.route_file_path)}let v=zS(l,d,s,m,h,p);if(!v.ok)return v;for(let R of l)if(await e.exists(R.file))return!R.file.startsWith("app/")&&o>1?ta({...e,randomHex:r,maxAttempts:o-1}):{ok:!1,code:"MATERIALIZATION_CONFLICT",message:`Page resource create-only target already exists: ${R.file}`,path:R.file};let C=HS(l);return C||(l.sort((R,w)=>R.file.localeCompare(w.file)),{ok:!0,packageInstanceId:s,pages:c,files:l})}function qd(e){let t=e.materialization.entry.pathTemplate,n=[];for(let o of e.materialization.files){let s=o.pathTemplate===t&&e.pageEntryTarget?e.pageEntryTarget:ef(o.pathTemplate,e.packageInstanceId);if(!s)return me("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=XS(o.content,e.packageInstanceId,e.routeByPage);if(!a.ok)return a;n.push({operation:"create-only",file:s,content:a.data})}let r=e.pageEntryTarget??ef(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 XS(e,t,n){let r,o=e.replace(BS,(s,a)=>{let c=n.get(a);return c||(r=a,s)});if(r)return me(`Page route placeholder references unknown template page: ${r}`);let i=o.replaceAll(qs,t);return i.includes("{{$PAGE_ROUTE:")||i.includes("{{$INSTANCE}}")?me("Materialization contains an unresolved placeholder."):{ok:!0,data:i}}function ef(e,t){let n=`${ea}/${t}`;if(e.split(qs).length>2)return null;let o=e.replace(qs,t),i=`${ea}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=Po.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!$S.test(a)||VS.test(a)?null:a}function tf(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 zS(e,t,n,r,o,i){let s=new Set(e.map(p=>p.file)),a=`${ea}/${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(Qs)&&!jS(p.content).success)return me("Materialization component i18n resources are invalid.",p.file);continue}try{let E=sf(p.content,{sourceType:"module",plugins:["jsx","typescript"]});l.set(p.file,E);for(let C of E.program.body)if((C.type==="ImportDeclaration"||C.type==="ExportAllDeclaration"||C.type==="ExportNamedDeclaration"&&C.source)&&C.source){let R=C.source.value,w=ZS(p.file,R,s,a);if(!w.allowed)return me(`Materialization import is outside the controlled package: ${R}`,p.file);w.internalPath&&c.get(p.file).add(w.internalPath)}let v;if(JS(E,{Identifier(C){C.isReferencedIdentifier()&&KS.has(C.node.name)&&(v??=C.node.name,C.stop())},JSXAttribute(C){C.node.name.type==="JSXIdentifier"&&C.node.name.name==="style"&&(v??="inline style",C.stop())},JSXOpeningElement(C){C.node.name.type==="JSXIdentifier"&&C.node.name.name.toLowerCase()==="style"&&(v??="style element",C.stop())}}),v)return me(`Materialization source uses forbidden capability: ${v}`,p.file)}catch{return me("Materialization source must parse as TS/TSX.",p.file)}let h=cr(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||!WS(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=of(p.entry,c);for(let E of p.declaredComponentIds){let v=r.get(E);if(!v||!h.has(v))return me(`Page entry does not reach declared component: ${E}`,p.entry)}for(let E of h){let v=u.get(E);if(v&&!p.declaredComponentIds.has(v))return me(`Page entry imports undeclared component: ${v}`,p.entry)}}let d=new Set;for(let p of t)for(let h of of(p,c))d.add(h);if(d.size!==e.length)return me("Every materialization file must be reachable from a package entry.");let m=QS(e,l,c);return m||{ok:!0}}function HS(e){if(e.length>OS)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>DS)return me("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>LS?me("Page resource exceeds the aggregate content byte limit."):null}function WS(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 YS(e,t){let n;try{n=sf(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=nf(i.init);if(s?.type!=="ObjectExpression")return null;for(let a of s.properties){if(a.type!=="ObjectProperty"||a.computed||!GS(a.key))continue;let c=nf(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 nf(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&af.isExpression(t)?t:null}function GS(e){return e.type==="Identifier"&&e.name==="path"||e.type==="StringLiteral"&&e.value==="path"}function ZS(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=rf(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:US.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=Po.posix.normalize(Po.posix.join(Po.posix.dirname(e),t)),i=rf(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function rf(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 QS(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(Qs))continue;let i=o.file.slice(0,-Qs.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 of(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 qS(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function eb(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 tb,parseComponentI18nResourcesJson as nb,resolveSiteTextDirection as rb,SiteLocaleSchema as ob}from"@vcp-dev/contracts";var ib=["i18next","react-i18next"],sb="components/ui/site-locale-provider.tsx",ab="components/ui/component-i18n-provider.tsx",cf="app/layout.tsx";async function ra(e){let t=e.files.filter(m=>m.path.endsWith(tb));if(t.length===0)return{ok:!0};for(let m of["package.json",cf,sb,ab])if(!await e.exists(m))return qt(`Target snapshot is missing required i18n host file: ${m}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return qt("Target snapshot package.json is invalid.")}let r=lf(n)&&lf(n.dependencies)?n.dependencies:{},o=ib.filter(m=>typeof r[m]!="string"||r[m].trim().length===0);if(o.length>0)return qt(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile(cf),s=na(i,"html","lang"),a=na(i,"html","dir"),c=na(i,"SiteLocaleProvider","locale"),l=ob.safeParse(s);if(!l.success||!a||!c||s!==c||a!==rb(l.data))return qt("Target snapshot app/layout.tsx must keep html lang/dir and SiteLocaleProvider locale consistent.");if(!i.includes('from "@/components/ui/site-locale-provider"')||!/<SiteLocaleProvider\b/.test(i)||!/<\/SiteLocaleProvider>/.test(i))return qt("Target snapshot root layout is not wired to SiteLocaleProvider.");let u=l.data,d=u.split("-")[0];for(let m of t){let p=nb(m.content);if(!p.success)return qt(`Component i18n resource is invalid: ${m.path}.`);if(!Object.hasOwn(p.data,u)&&!Object.hasOwn(p.data,d))return qt(`Component i18n resource ${m.path} has no locale for ${u} or ${d}.`)}return{ok:!0}}function na(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 qt(e){return{ok:!1,message:e}}function mf(e){let t=null,n=new WeakMap;async function r(){return t??=cb(e),t}return{async prepareAppend(o){let i=await e.readIndex(),s=await e.stageAppend(pf(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);uf(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(uf(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(pf(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 uf(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 cb(e){let t=await e.readIndex(),n=await Promise.all(t.undoIds.map(async o=>df(e,o))),r=await Promise.all(t.redoIds.map(async o=>df(e,o)));return{undo:n.reverse(),redo:r.reverse(),entryIds:[...t.entryIds],cursor:t.cursor}}async function df(e,t){let n=await e.readEntry(t),r=lb(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 ff(e,n,r.preSnapshots),postSnapshots:await ff(e,n,r.postSnapshots)}}async function ff(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(ub(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function pf(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 lb(e){if(!db(e.manifest))throw new Error("durable history manifest is not an object");return e.manifest}function ub(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function db(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import hf from"node:path";function ia(){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 yf(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 wo(e){let t=()=>fb(e);return e.mutex?e.mutex.runExclusive(t):t()}async function fb(e){let t=await yf(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=pb(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 oa({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 oa({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 oa({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 gf("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return gf("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 pb(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 oa(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:mb(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 gf(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function mb(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)||hf.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=hf.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 sa(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function wn(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function xf(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function aa(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 Ef(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function gb(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var lr=class extends Error{constructor(t){let n=t.map(Ef);super(gb(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function Sf(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof lr?{routeId:e,message:n,diagnostics:t.diagnostics.map(Ef)}:{routeId:e,message:n}}function ca(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function bf(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 kb=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,Cb=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],If=32,kf=256,Cf={maxEntries:50,maxBytes:8*1024*1024};function vb(){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 ko(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 Rb(){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>Cf.maxEntries||Pb(e)>Cf.maxBytes;)e.shift()}}function Pb(e){return e.reduce((t,n)=>t+wb(n),0)}function wb(e){return vf(e.preSnapshots)+vf(e.postSnapshots)}function vf(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function Rf(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 Ab(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=Xe(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 No=class extends Error{constructor(t){super(t.reason),this.result=t}},en=class extends Error{constructor(t){super(ca(t)),this.failedRoutes=t}};function Pf(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=Xe(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(Xe(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}var Tb=/\.(?:[cm]?[jt]sx?)$/i,Nb=/\.json$/i,Fb=/\.(?:css|scss|sass)$/i,Mb=/\.mdx$/i,_b=/\.ya?ml$/i;function Ob(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 Db(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function Lb(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=Bb(await e.listFiles(r)),i=new Map(o.files.map(a=>[a.path,a]));for(let[a,c]of n)if(jb(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 jb(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function Bb(e){return Array.isArray(e)?{files:e}:e}function $b(e){if(!Eb(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!==bb||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=xb(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(Tb.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(Nb.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${Me(t)}`,details:{path:e.path}}}if(Fb.test(e.path)){let t=wf({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(Mb.test(e.path)){let t=wf({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(_b.test(e.path))try{Ib(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${Me(t)}`,details:{path:e.path}}}return{ok:!0}}function wf({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(`
4
+ `)}function Vr(e){let{ast:t,source:n}=e;try{let r=Om(n),i=_m(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=Lm(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 Rc from"@babel/parser";import{arrayExpression as jm,booleanLiteral as Bm,identifier as $m,jsxAttribute as Vm,jsxExpressionContainer as Um,jsxIdentifier as Km,nullLiteral as Jm,numericLiteral as Xm,objectExpression as zm,objectProperty as Hm,stringLiteral as Pc}from"@babel/types";function vc(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:vc(e),afterSourceHash:vc(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=ri(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function Ur(e,t){return Vr({ast:e,source:t})}function Wm(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 wc(e,t,n){let r=Wm(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 Ac(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 fn(e){return typeof e=="string"?Pc(e):typeof e=="number"?Xm(e):typeof e=="boolean"?Bm(e):e===null?Jm():Array.isArray(e)?jm(e.map(t=>fn(t))):zm(Object.entries(e).map(([t,n])=>Hm($m(t),fn(n))))}function Ym(e){return typeof e=="string"?Pc(e):Um(fn(e))}function Kr(e,t){return Vm(Km(e),Ym(t))}function Tc(e,t){try{let r=Rc.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 Jr(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=Gm(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=Zm(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 Gm(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=Qm(r.get("expression"));o.length>0&&t.push(...o)}}return t}function Zm(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function Qm(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 Ii}from"@babel/types";function pn(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?(qm(o.match.path),de(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function qm(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Ii());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Ii());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Ii());return}e.remove()}import{cloneNode as uh}from"@babel/types";import ki from"@babel/traverse";import*as U from"@babel/types";var eh=typeof ki=="function"?ki:ki.default;function Ve(e,t,n,r){if(!e.ok)return e;let o=$e(n);if(!o)return e;let i=th(t,o,r);return i?{...e,selectionRef:i}:e}function th(e,t,n){let r=nh(e,t);if(!r)return;let o=n.sourceLocator?Nc(n.sourceLocator):void 0,i=n.targetParentLocator?Nc(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??oh(r)??i?.component??o?.component;if(!(!s||!a))return{key:_n(s,a,ih(r))}}function Nc(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function nh(e,t){let n=null;return eh(e,{JSXElement(r){r.node===t&&(n=r,r.stop())}}),n}function $e(e){if(!e)return null;if(U.isJSXElement(e))return mn(e)?Fc(e.children):e;if(U.isJSXFragment(e))return Fc(e.children);if(U.isJSXExpressionContainer(e)||U.isParenthesizedExpression(e)||U.isTSAsExpression(e)||U.isTSSatisfiesExpression(e)||U.isTSTypeAssertion(e)||U.isTSNonNullExpression(e))return $e(e.expression);if(U.isLogicalExpression(e))return $e(e.right);if(U.isConditionalExpression(e))return $e(e.consequent)??$e(e.alternate);if(U.isCallExpression(e)||U.isOptionalCallExpression(e))return Lc(e)?rh(e.arguments[0]):null;if(U.isArrayExpression(e))for(let t of e.elements){if(!t)continue;let n=$e(t);if(n)return n}return null}function Fc(e){for(let t of e){let n=$e(t);if(n)return n}return null}function rh(e){return!e||!U.isArrowFunctionExpression(e)&&!U.isFunctionExpression(e)?null:U.isBlockStatement(e.body)?$n(e.body.body):$e(e.body)}function $n(e){for(let t of e){if(U.isReturnStatement(t)){let n=$e(t.argument);if(n)return n;continue}if(U.isBlockStatement(t)){let n=$n(t.body);if(n)return n;continue}if(U.isIfStatement(t)){let n=Mc(t.consequent);if(n)return n;let r=t.alternate?Mc(t.alternate):null;if(r)return r;continue}if(U.isSwitchStatement(t))for(let n of t.cases){let r=$n(n.consequent);if(r)return r}}return null}function Mc(e){return U.isBlockStatement(e)?$n(e.body):$n([e])}function oh(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 _c=new WeakMap,Oc=new WeakMap,Ci=new WeakMap;function ih(e){let t=_c.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=sh(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return _c.set(e.node,o),o}function sh(e){let t=vi(e.node.openingElement.name);return!t||mn(e.node)?null:/^[A-Z]/.test(t)?`component:${t}#${Dc(e,t)}`:`${t}#${Dc(e,t)}`}function Dc(e,t){let n=ah(e);if(!n)return 0;let r=Ci.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Ci.get(n.node);o||(o=new Map,Ci.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of Kt(n))if(vi(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 ah(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(mn(t.node)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Kt(e){let t=Oc.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(mn(o.node)){n.push(...Kt(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Kt(o));continue}o.isJSXExpressionContainer()&&n.push(...mt(o.get("expression")))}return Oc.set(e.node,n),n}function mt(e){if(e.isJSXElement())return mn(e.node)?Kt(e):[e];if(e.isJSXFragment())return Kt(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())&&Lc(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?ch(n):[]}return[]}function ch(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return mn(t.node)?Kt(t):[t];if(t.isJSXFragment())return Kt(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 Lc(e){let t=e.callee;return(U.isMemberExpression(t)||U.isOptionalMemberExpression(t))&&U.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function mn(e){let t=vi(e.openingElement.name);return t==="Fragment"||t==="React.Fragment"}function vi(e){return U.isJSXIdentifier(e)?e.name:U.isJSXMemberExpression(e)?jc(e):U.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function jc(e){return`${U.isJSXIdentifier(e.object)?e.object.name:jc(e.object)}.${e.property.name}`}function kt(e,t){if(t.parentPath===e&&t.listKey==="children"&&Bc(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!Bc(n))return null;let r=n;for(;r&&r!==e;){if(!lh(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function Bc(e){return e.isJSXElement()||e.isJSXFragment()}function lh(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 hn(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 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 R=c.match.path.node;if(!R.closingElement||R.openingElement.selfClosing)return V(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=Tc(t,r.jsx);if(!u.ok)return u.result;let d=uh(u.node,!0),m=l.node.children,p={...s,targetParentLocator:n},h=R=>s?Ve(R,a.ast,d,p):R;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 V(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 v=kt(c.match.path,E.match.path);if(!v)return V(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");l=v;let C=l.node.children,A=C.findIndex(R=>R===E.match.path.node);return A===-1?V(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(C.splice(o==="before"?A:A+1,0,d),h(de(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as $c from"@babel/parser";import{cloneNode as dh}from"@babel/types";function Xr(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=fh(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 V(t,"unsupported-syntax","insert-jsx-expression-child target must be a JSXElement or JSXFragment","jsx-node");if(l.match.path.isJSXElement()){let C=l.match.path.node;if(!C.closingElement||C.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 C=oe(a.ast,i);if(!C.ok)return{ok:!1,source:t,diagnostic:C.diagnostic};let A=kt(l.match.path,C.match.path);if(!A)return V(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=A,d=C.match.path.node}else if(o==="before"||o==="after")return V(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=dh(c.node,!0),p=u.node.children,h={...s,targetParentLocator:n},E=C=>s?Ve(C,a.ast,m,h):C;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 v=p.findIndex(C=>C===d);return v===-1?V(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(p.splice(o==="before"?v:v+1,0,m),E(de(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function fh(e,t){try{let r=$c.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 ph,nullLiteral as Ri}from"@babel/types";import*as gn from"@babel/types";function yn(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 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 A=l.match.path.node;if(!A.closingElement||A.openingElement.selfClosing)return V(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let d=null;if(i){let A=oe(a.ast,i);if(!A.ok)return{ok:!1,source:t,diagnostic:A.diagnostic};let R=kt(l.match.path,A.match.path);if(!R)return V(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=R,d=A.match.path}else if(o==="before"||o==="after")return V(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=d&&typeof d.key=="number"?d.key:-1;if(d&&m===-1)return V(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let p=ph(c.match.path.node,!0);if(!gn.isJSXElement(p)&&!gn.isJSXExpressionContainer(p)&&!gn.isJSXFragment(p))return V(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 V(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");mh(c.match.path);let E=u.node.children,v={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return E.push(p),Ve(Ur(a.ast,t),a.ast,p,v);if(o==="prepend")return E.unshift(p),Ve(Ur(a.ast,t),a.ast,p,v);let C=m-(h!==-1&&h<m?1:0);return E.splice(o==="before"?C:C+1,0,p),Ve(Ur(a.ast,t),a.ast,p,v)}function mh(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*as Vc from"@babel/parser";import{cloneNode as hh,nullLiteral as Pi}from"@babel/types";function zr(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=gh(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 V(t,"unsupported-syntax","move-repeat-template-child target parent must be a JSXElement or JSXFragment","jsx-node");if(d.match.path.isJSXElement()){let R=d.match.path.node;if(!R.closingElement||R.openingElement.selfClosing)return V(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let m=d.match.path,p=null;if(i){let R=oe(c.ast,i);if(!R.ok)return{ok:!1,source:t,diagnostic:R.diagnostic};let B=kt(d.match.path,R.match.path);if(!B)return V(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");m=B,p=R.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 h=m.node,E=hh(l.node,!0);yh(u.match.path);let v={...a,sourceLocator:n,targetParentLocator:r},C=h.children;if(o==="append")return C.push(E),Ve(de(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,E,v);if(o==="prepend")return C.unshift(E),Ve(de(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,E,v);let A=C.findIndex(R=>R===p);return A===-1?V(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(C.splice(o==="before"?A:A+1,0,E),Ve(de(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,E,v))}function gh(e,t){try{let r=Vc.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 yh(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Pi());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Pi());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Pi());return}e.remove()}function Hr(e){let{source:t,locator:n,props:r}=e,o=Ie(t,"jsx-node");if(!o.ok)return o.result;let i=wc(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=Ac(o.ast,l);if(u.ok&&u.match!==null){let d=u.match.path.node;d.value=c===""?Kr(a,"").value:Kr(a,c).value}else s.attributes.push(Kr(a,c))}return de(o.ast,t,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}import{getBindingIdentifiers as xh,identifier as Vn,importDeclaration as Eh,importDefaultSpecifier as Sh,importNamespaceSpecifier as bh,importSpecifier as Ih,isImportDefaultSpecifier as Uc,isImportNamespaceSpecifier as Kc,isImportSpecifier as Jc,stringLiteral as kh}from"@babel/types";function xn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(v=>!Fh(v));if(o!==-1){let v=r[o],C=v&&typeof v=="object"&&"kind"in v?v.kind:void 0;return V(t,"unsupported-syntax",`Unsupported import spec kind: ${String(C)}`)}let i=Ah(r);if(!i.ok)return V(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(v=>v.type==="ImportDeclaration"&&v.source.value===n),u=new Set(l.flatMap(v=>v.specifiers.flatMap(C=>{let A=Mh(v,C);return A?[A]:[]}))),d=i.imports.filter(v=>!u.has(Gc(v)));if(d.length===0)return Bn(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let m=Th(c.body),p=d.find(v=>m.has(wi(v)));if(p)return V(t,"unsupported-syntax",`Import local binding already exists: ${wi(p)}`);let h=wh(d);if(h.reduce((v,C)=>v+C.length,0)!==d.length)return V(t,"unsupported-syntax","Unsupported import specifier grouping");for(let v of h){if(!Wc(zc(v)))return V(t,"unsupported-syntax","Unsupported import specifier combination");let C=l.find(A=>Ch(A,v));if(C)vh(C,v);else{let A=Eh(Xc(v),kh(n));Nh(c.body,A),l.push(A)}}return de(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function Ch(e,t){return e.importKind==="type"?!1:Wc(Ph(Rh(e),zc(t)))}function vh(e,t){let n=!1,r=new Set(e.specifiers.map(o=>Ai(o)));for(let o of Xc(t)){let i=Ai(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return Yc(e.specifiers),{changed:n}}function Xc(e){let t=e.map(n=>{switch(n.kind){case"named":return Ih(n.local?Vn(n.local):Vn(n.imported),Vn(n.imported));case"default":return Sh(Vn(n.local));case"namespace":return bh(Vn(n.local));default:return n}});return Yc(t),t}function zc(e){let t=Hc();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 Rh(e){let t=Hc();for(let n of e.specifiers)Uc(n)?t.defaultLocals.add(n.local.name):Kc(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function Hc(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function Ph(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function Wc(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function Yc(e){let t=[...e.filter(n=>Uc(n)),...e.filter(n=>Kc(n)),...e.filter(n=>Jc(n))];e.splice(0,e.length,...t)}function wh(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 Ah(e){let t=new Map,n=new Map;for(let r of e){let o=Gc(r);if(t.has(o))continue;let i=wi(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 Th(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(xh(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 Nh(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 Fh(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 Gc(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 wi(e){return e.kind==="named"?e.local??e.imported:e.local}function Mh(e,t){return e.importKind==="type"||Jc(t)&&t.importKind==="type"?null:Ai(t)}function Ai(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 En(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(u=>!Oh(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=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=>_h(u,d))),l.specifiers.length===0&&a.body.splice(c,1),de(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function _h(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 Oh(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 Un(e){let{source:t,locator:n,next:r}=e,o=Zr(t,n);return o.ok?(o.path.replaceWith(fn(r)),de(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function Wr(e){let{source:t,locator:n,index:r,value:o}=e,i=Zr(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,fn(o)),de(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 Yr(e){let{source:t,locator:n,index:r}=e,o=Zr(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),de(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 Gr(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=Zr(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),de(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function Zr(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 Lh=typeof Ti=="function"?Ti:Ti.default;function Mi(e){let t=rl(e);if(t)return{ok:!1,error:t};let n=e.projection,r=_i(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:Qc(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=qr(e.source,c.match.node.start??null,c.match.node.end??null);if($h(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=Qc(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 Qc(e){let t=Bh(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 tl(e){let t;try{t=eo.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=eo.parseExpression(e.jsx,{plugins:["jsx","typescript"]}),r=!1;return(typeof Ni=="function"?Ni:Ni.default)(t,{ExportDefaultDeclaration(i){let s=i.get("declaration"),a=jh(i,s);if(a){if(a.isArrowFunctionExpression()&&!a.get("body").isBlockStatement()){let c=a.get("body");c.replaceWith(qc(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(qc(l.node,n,e.placement,e.replaceOriginal===!0)),r=!0,c.stop())}}),r&&i.stop()}}}),r?{ok:!0,source:Lh(t,{}).code}:{ok:!1,source:e.source,diagnostic:{message:"Route default return boundary could not be resolved."}}}function jh(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 qc(e,t,n,r){if(Ct.isNullLiteral(e)||r)return t;let s=n==="before"||n==="prepend"?[t,e]:[e,t];return Ct.jsxFragment(Ct.jsxOpeningFragment(),Ct.jsxClosingFragment(),s)}function nl(e){let t=rl(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=ol(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=Fi(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(qr(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=_i(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=Fi(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(qr(e.source,m.match.node.start??null,m.match.node.end??null)!==l.containerSourceHash)return el("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 v=Fi(h),C=pt(e.source,v);return!C.ok||!C.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:C.ok===!1?C.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:C.ok?[]:[Qr(C.diagnostic)]}}:qr(e.source,C.match.node.start??null,C.match.node.end??null)!==E?el("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:v,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 el(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 rl(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 Bh(e,t){let n=Zc.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Zc.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Fi(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function qr(e,t,n){return t==null||n==null?null:`sha256:${Dh("sha256").update(e.slice(t,n)).digest("hex")}`}function $h(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 Vh=typeof Oi=="function"?Oi:Oi.default;function sl(e){if(!e.ast)return st(e,[Ne("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=Yh(e.ast);if(!t)return st(e,[Ne("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=Zh(t);if(n.length===0)return st(e,[Ne("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")]);if(n.length>1)return st(e,[Ne("MULTIPLE_PAGE_RETURNS","Route default export contains multiple page-level return statements",{returnCount:n.length})]);let r=Qh(n[0].argument);if(!r)return st(e,[Ne("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})]);if(r.isNullLiteral())return il(e,t,"virtual-route-root");if(qh(r,t))return st(e,[Ne("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(eg(r,t)||tg(r)&&!e.source.includes("DESIGN_PLAN_REPLACE_ME"))return st(e,[Ne("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 st(e,[Ne("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);let s=Di({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-fragment",source:e.source,containerPath:r,members:i.members});return to(e,t,s,{kind:"virtual-route-root",sourceKind:"jsx-fragment"})}if(r.isJSXElement()&&!Sn(r)){let i=Bi(r),s=Di({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[i]});return to(e,t,s,{kind:"virtual-route-root",sourceKind:"jsx-element"})}if(r.isJSXElement()){let i=Rt(r);if(i.unsupported)return st(e,[Ne("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);let s=i.members;if(rg(e.source,r,s))return il(e,t,"starter-placeholder");let a=Di({input:e,containerKind:"jsx-container",sourceKind:"jsx-element",source:e.source,containerPath:r,members:s});return to(e,t,a,{kind:"jsx-container",sourceKind:"jsx-element"})}if(ng(r))return st(e,[Ne("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);let o=ig({input:e,source:e.source,expression:r});return to(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"})}function _i(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Ne("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:Ne("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function ol(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Ne("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:Ne("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function al(e){return e.ok?Uh(e.projection):Kh(e.projection)}function Uh(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,v)=>cl(e,u,E,v,e.container.placementKey)),m=d.filter(({member:E})=>E.isBusinessMember).map(({sourceMember:E})=>Xh(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:Jh(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function Kh(e){let t=e.diagnostics.map(zh);return{status:"unsupported",version:e.version,routeId:e.route,reason:Hh(e.diagnostics),diagnostics:t}}function Jh(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 cl(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)=>cl(e,t,a,c,i))]}function Xh(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function zh(e){return{code:Wh(e),message:e.message}}function Hh(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 Wh(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 Yh(e){let t=null;return Vh(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=Gh(o.path);i&&(t=i,n.stop())}}),t}function Gh(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 Zh(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 Qh(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 qh(e,t){if(e.isIdentifier())return no(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return no(n.node.name,t)}return!1}function eg(e,t){return e.isConditionalExpression()?vt(e.get("consequent"),t)||vt(e.get("alternate"),t):e.isLogicalExpression()?vt(e.get("left"),t)||vt(e.get("right"),t):!1}function tg(e){if(!e.isJSXElement()||!Sn(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 vt(e,t){if(e.isIdentifier())return no(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return no(n.node.name,t)}return e.isConditionalExpression()?vt(e.get("consequent"),t)||vt(e.get("alternate"),t):e.isLogicalExpression()?vt(e.get("left"),t)||vt(e.get("right"),t):!1}function no(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 ng(e){return e.isJSXSpreadChild()}function rg(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&ji(t)}function ji(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(!ji(t))return!1;continue}if(t.isJSXElement()&&!ji(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:$i(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:Ye(r.node.loc),businessMemberCount:0,parentSourceRange:Ye(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=Sn(o)?Rt(o):null;n||=i?.unsupported??!1,t.push({...Bi(o,i?.members),sourceRange:Ye(r.node.loc),parentSourceRange:Ye(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:$i(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:Ye(r.node.loc),businessMemberCount:1,parentSourceRange:Ye(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&ll(r)){let o=Rt(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=Sn(r)?Rt(r):null;n||=o?.unsupported??!1,t.push({...Bi(r,o?.members),parentSourceRange:Ye(e.node.loc)})}}return{members:t,unsupported:n}}function Bi(e,t){let n=e.isJSXElement()&&Sn(e)?t??Rt(e).members:[],r=e.isJSXElement()&&!Sn(e)&&!ll(e);return{memberKey:$i(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:Ye(e.node.loc),businessMemberCount:r?1:ul(n),parentSourceRange:Ye(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:og(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 Sn(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name!=="Fragment"&&t.name[0]===t.name[0]?.toLowerCase()}function og(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 ul(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function ro(e){return e.length===0?0:Math.max(1,ul(e))}function Di(e){let t=Ye(e.containerPath.node.loc),n=fl(e.source,e.containerPath.node.start,e.containerPath.node.end),r=Ue(e.input,e.containerKind,e.sourceKind,t),o=Ue(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:ro(e.members)<=1,memberCount:ro(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function ig(e){let t=Ye(e.expression.node.loc),n=fl(e.source,e.expression.node.start,e.expression.node.end),r=Ue(e.input,"virtual-route-root","atomic-expression",t),o=Ue(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:Ue(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 to(e,t,n,r){let o=n.containerSourceRange??n.sourceRange,i=sg(e,n,o),s=gi(i),a={status:"supported",route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:pl(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 sg(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:ro(h)<=1,memberCount:ro(h),sourceRange:m,sourceHash:m?Li(e.source,m):null,relation:l,containerSourceRange:E,containerSourceHash:E?Li(e.source,E):null,anchorSourceRange:p,anchorSourceHash:p?Li(e.source,p):null,members:h}),i=t.placementKey,s=t.members.map(l=>Ue(e,i,"placement-unit",l.sourceRange)),a=s[0]??t.placementUnitKey,c=s.at(-1)??t.placementUnitKey;r.push(o("prepend",Ue(e,i,"prepend",n),a,n,null,[]));for(let l of t.members){let u=l.parentSourceRange??n,d=Ue(e,i,"placement-unit",l.sourceRange);r.push(o("before",Ue(e,d,"before",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u)),r.push(o("after",Ue(e,d,"after",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u))}return r.push(o("append",i,c,n,null,[])),r}function il(e,t,n){let r=Ue(e,n,"empty-container",void 0),o=Ue(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=gi([i]),a={status:"supported",route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:pl(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 st(e,t){return{ok:!1,projection:{status:"unsupported",route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,diagnostics:t}}}function Ne(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function Ue(e,t,n,r){return dl([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function $i(e,t,n){return dl(["member",e,String(t??-1),String(n??-1)])}function dl(e){return`pc_${Vi("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function fl(e,t,n){return t==null||n==null?null:`sha256:${Vi("sha256").update(e.slice(t,n)).digest("hex")}`}function Li(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:${Vi("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function Ye(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function pl(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 cg(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var lg=160;function ml(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 hl(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 v=Sl(p.textSegments,s),C=bl(e,t,p,E,v),A=v?fg(v):void 0,R=pg(i,v),B=p.textSegments.map(_=>({index:_.index,value:_.value,editable:Il(_,E,s?.get(_.index)??null),source:o.get(_.index)??null})),re=xl(p,t),te=p.childKeys.map(_=>{let M=t.elements.get(_);return M?{key:_,tag:M.tag,label:M.tag}:null}).filter(_=>_!==null),w=[];if(p.parentKey){let _=t.elements.get(p.parentKey);if(_)for(let M of _.childKeys){if(M===e)continue;let D=t.elements.get(M);D&&w.push({key:M,tag:D.tag,label:D.tag})}}return{key:e,tag:p.tag,componentName:p.componentName,sourceFile:p.sourceFile,sourceLocator:yl(p),label:p.tag,capabilities:C,writeTarget:i,effectiveWriteTarget:R,provenanceChain:A,componentSemantic:c,contentModel:l,mediaModel:u,styleSource:d,conditional:a,...m?{dynamicData:m}:{},textSegments:B,boundaryKind:p.boundaryKind,isOpaque:p.isOpaque,ancestors:re,children:te,siblings:w}}function gl(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=Sl(a.textSegments,i);return{key:e,tag:a.tag,componentName:a.componentName,sourceFile:a.sourceFile,sourceLocator:yl(a),label:a.tag,capabilities:bl(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:Il(d,l,i?.get(d.index)??null),source:m?{kind:m.kind}:null}}),boundaryKind:a.boundaryKind,isOpaque:a.isOpaque,ancestors:xl(a,t)}}function yl(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:ug(e.sourceRange),structuralPath:e.identity.structuralPath,...dg(e.textSegments)}}function xl(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 ug(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function dg(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,lg)}:{}}function El(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 Sl(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function bl(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&&kl(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 Il(e,t,n){return!e.editable||!t.canUpdateText?!1:n?kl(n.editMode):!0}function kl(e){return e==="direct"||e==="proxy"||e==="upstream"}function fg(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 pg(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}:cg(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 Cl(e){let{key:t,element:n,graph:r,provenances:o}=e,i=hg(t,n,r),s=i?.tag??(Jt(n.tag)?n.tag:n.componentName),a=i?.identity.key??vl(n,r)??t,c=xg(i),l=Eg(t,n,r,o,i),u=mg(t,n,r,o,a);return{componentName:s,instanceKey:a,templateOwner:yg(i??n,s),...c.length>0?{variantKeys:c}:{},...l.length>0?{slotKeys:l}:{},editableStrategy:u,impactScope:Sg(u),alternativeStrategies:bg(u)}}function mg(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return Ui(e,n)?"instance":!Jt(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function vl(e,t){if(Jt(e.tag))return e.identity.key;let n=[...t.elements.values()].filter(r=>r.importedFrom===e.sourceFile&&gg(r,e.componentName));return n.length!==1?null:n[0].identity.key}function hg(e,t,n){if(Jt(t.tag))return t;let r=Ui(e,n);if(r)return r;let o=vl(t,n);return o?n.elements.get(o)??null:null}function gg(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function yg(e,t){return Jt(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function xg(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 Eg(e,t,n,r,o){let i=new Set,s=Ui(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&&Jt(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function Ui(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(Jt(r.tag))return r;n=r.parentKey}return null}function Jt(e){return/^[A-Z]/.test(e)}function Sg(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function bg(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}var Ig=new Set(["markdown","body","content","value","document"]),Rl=[];function wl(e){if(!(!vg(e.tag)||!e.attributes))for(let t of e.attributes){if(!Ig.has(t.name))continue;if(Cg(t))return{kind:"markdown",field:t.name,schema:"markdown",valuePath:t.source?.expression,operationBoundary:Rl};let n=kg(t.resolvedValue);if(n==="prosemirror-doc"||n==="node-array")return{kind:"rich-text-json",field:t.name,valuePath:t.source?.expression,schema:n,operationBoundary:Rl};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 kg(e){if(e){if(Array.isArray(e)&&e.every(t=>Pl(t)))return"node-array";if(Pl(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 Pl(e){return!Array.isArray(e)&&typeof e=="object"&&e!==null}function Cg(e){return e.name==="markdown"}function vg(e){return/^[A-Z]/.test(e)}var Rg=["src","alt","poster","caption","width","height"];function Al(e){let t=e.attributes?.filter(i=>Rg.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=wg(t.map(i=>i.value));return{kind:Pg(e.tag,n),sourceType:o,fields:n,editableFields:[],operationBoundary:[],...Object.keys(r).length>0?{valuePaths:r}:{}}}function Pg(e,t){return e==="img"?"image":e==="video"||t.includes("poster")?"video":"media"}function wg(e){return e.some(t=>t.startsWith("cms:"))?"cms-media-field":e.some(t=>/^(\.?\/|\/)/.test(t))?"local-file-reference":"asset-id"}var Ki=["set-class-name-source","apply-style-draft"];function Tl(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:Ki,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:Ki,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:Ki}}import{createHash as Ag}from"node:crypto";var Kn=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:${Ag("sha256").update(e).digest("hex")}`}function Ml(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=Tg(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:Fl(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:Nl(e.route.source,o),valueRaw:s?Nl(e.route.source,s):null,attrRange:Fl(o),diagnostics:[]}}function _l(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 Tg(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:Ng(t.sourceRange)});return!r.ok||r.match.node.type!=="JSXElement"?null:r.match.node}function Ol(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 Nl(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function Fl(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 Ng(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}import*as ss from"@babel/parser";import Wi from"@babel/traverse";import*as S from"@babel/types";import*as gt from"node:path";import*as $l from"@babel/parser";import zi from"@babel/traverse";import*as bn from"@babel/types";import*as H from"@babel/types";function so(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?oo(n,t):null}if(e.isMemberExpression()){let n=Lg(e.node),r=Fg(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?oo(o,[...r,...t]):null}return e.isAwaitExpression()||Xi(e.node)?Pt(Bg(e.node),t,"awaited or fetched expression"):null}function Fg(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 oo(e,t=[]){let n=Mg(e,t);if(n)return n;let r=_g(e,t);if(r)return r;let o=Og(e,t);return o||null}function Xn(e){return e?.kind==="api-source"}function Mg(e,t){if(e.path.isVariableDeclarator()&&H.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&Ji(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"&&Jn(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&Ji(a.node))return Pt(e.identifier.name,t,"query hook data binding")}let n=Dg(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()||!Ji(i.node)?null:Pt(e.identifier.name,t,"query hook data binding")}function _g(e,t){if(e.path.isVariableDeclarator()&&H.isArrayPattern(e.path.node.id)){let a=e.path.get("init");if(!a?.isCallExpression()||!Ll(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:Dl(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()||!Ll(o.node)||n.node.elements.findIndex(a=>a===e.path.node)!==0)return null;let s=n.node.elements[1];return H.isIdentifier(s)&&Dl(e,s.name)?Pt(e.identifier.name,t,"state setter is updated by API data"):null}function Og(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"):Xi(r.node)?Pt(e.identifier.name,t,"fetch-backed binding result"):null:null}function Dg(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 Jn(e,t){return H.isIdentifier(e)?e.name===t:H.isAssignmentPattern(e)?Jn(e.left,t):H.isObjectPattern(e)?e.properties.some(n=>H.isObjectProperty(n)?Jn(n.value,t):Jn(n.argument,t)):H.isArrayPattern(e)?e.elements.some(n=>!!n&&Jn(H.isRestElement(n)?n.argument:n,t)):!1}function Dl(e,t){let n=!1,r=!1;return e.scope.path.traverse({CallExpression(i){Xi(i.node)&&(n=!0),(jg(i.node.callee,t)||i.node.arguments.some(s=>H.isIdentifier(s)&&s.name===t))&&(r=!0)}}),n&&r}function Ji(e){let t=ao(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function Ll(e){return ao(e.callee)==="useState"}function Xi(e){return io(e,t=>H.isCallExpression(t)&&ao(t.callee)==="fetch")}function Lg(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 ao(e){return H.isIdentifier(e)?e.name:H.isMemberExpression(e)&&H.isIdentifier(e.property)?e.property.name:null}function jg(e,t){return io(e,n=>H.isIdentifier(n)&&n.name===t)}function io(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)&&io(i,t))return!0;continue}if(H.isNode(o)&&io(o,t))return!0}return!1}function Bg(e){return H.isIdentifier(e)?e.name:H.isCallExpression(e)?ao(e.callee)??"api":H.isAwaitExpression(e)?"awaited-api":"api"}function Pt(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:$g(e,t),reason:n}}function $g(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var Vl=typeof zi=="function"?zi:zi.default;function Ul(e,t){let n=Jl(e);if(!n)return{allowed:!0};let r=!1;return Vl(n,{CallExpression(o){if(!Xl(o.node,t.sourceRange)||!Vg(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||Xn(so(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function Kl(e,t){let n=Jl(e);if(!n)return{allowed:!0};let r=!1;return Vl(n,{JSXExpressionContainer(o){Xl(o.node,t.sourceRange)&&(bn.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 Jl(e){try{return $l.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Vg(e){let t=e.callee;return bn.isMemberExpression(t)&&bn.isIdentifier(t.property)&&t.property.name==="map"}function Xl(e,t){let n=e.loc;return n?Bl({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&Bl({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function Bl(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 zl(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 at(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return Xt(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(se.isObjectPattern(n)||se.isArrayPattern(n))return Xt(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(Kg(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function Xt(e,t,n=!1){return se.isIdentifier(e)?e.name===t&&n:se.isObjectPattern(e)?e.properties.some(r=>se.isObjectProperty(r)?Xt(r.value,t,n):Xt(r.argument,t,n)):se.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=se.isRestElement(r)?r.argument:r;return Xt(o,t,n)}):se.isAssignmentPattern(e)?Xt(e.left,t,!0):se.isRestElement(e)?Xt(e.argument,t,n):!1}function In(e,t){if(e.path.isObjectPattern()){if(t){let r=Ge(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:at(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:at(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=Hl(r),i=!1,s=o?o.initBinding&&Hi(o.initBinding)?(i=at(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=In(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=Ge(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||at(e)}}}}let n=zg(e);if(n){let r=Ug(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||at(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=Jg(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:at(e)}}let i=zn(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:at(e)}:null}if(Hi(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:at(e)}}return null}function Ug(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=Hl(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=Hi(i)?(a=at(i),[...s]):(()=>{let u=In(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=Ge(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||at(t)}:null}function Hl(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=Hg(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function Hi(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function Kg(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Jg(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=Ge(i.node,t);if(a)return a}return null}function Wl(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=co(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=zn(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=Xg(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=zn(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 co(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=zn(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&Ge(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=co(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=co(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=co(r,t);if(o)return o}}return null}function Ge(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=zn(r);if(!o)continue;let i=Ge(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(se.isRestElement(r)){let o=Ge(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=Ge(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return se.isAssignmentPattern(e)?Ge(e.left,t,n):null}function Xg(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function zg(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 zn(e){return e.computed?null:se.isIdentifier(e.key)?e.key.name:se.isStringLiteral(e.key)?e.key.value:null}function Hg(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 Wi=="function"?Wi:Wi.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 kn(e){return{file:e.file,component:e.component}}function Wg(e){return e.target.kind==="node"?e.target.key:null}function Yg(e){return"kind"in e}function lo(e){return!Yg(e)}function es(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 Yi(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 as(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 Ke(e){try{return ss.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Gg(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function Zg(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 Wt(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 uu(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 Qg(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||Wt(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=uu(i.node.name);s&&o(s,i)}}),[...r].sort()}function Yl(e,t,n){let r=Ke(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(vu(o.match.path,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let s=Qg(o.match.path,i.match.path);return s.length>0?{ok:!1,bindingNames:s}:{ok:!0}}function Gl(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:is(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=mo(e,u.node),m=r.node.params.map(E=>mo(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:ds(u.node),callbackPath:r,collectionPath:u}}function mo(e,t){let n=ce(t);return n?e.slice(n.start,n.end):""}function uo(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function qg(e,t){let n=ce(e.node);return n?ey(t).some(r=>{let o=ce(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function ey(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)?ty(e)?Zl(e.children):[e]:S.isJSXFragment(e)?Zl(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)&&Pu(e.operator)?Nt(e.right):[]}function Zl(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 ty(e){let t=e.openingElement.name;return S.isJSXIdentifier(t)?t.name==="Fragment":S.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function ny(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function Gi(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function Ql(e,t,n,r={}){if(!r.preserveConditionalBoundary&&vu(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=>us(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||Wt(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=uu(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function ql(e,t,n){let r=ce(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>us(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return cs(e,s=>{let a=s.scope.getBinding(s.node.name);if(!a||Wt(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 ry(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>us(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=oy(l);u&&o(u,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function oy(e){let t=e;for(;S.isTSQualifiedName(t);)t=t.left;return S.isIdentifier(t)?t.name:null}function du(e,t){let n=ce(e.node),r=new Set;return cs(e,o=>{let i=o.scope.getBinding(o.node.name);if(!i||n&&Wt(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 cs(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function iy(e){let t=sy(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=wu(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=Ey({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=Cu(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?ds(o):!0}}}function sy(e,t,n){let r=mu(e,t);if(hu(e,r),gu(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){Iu(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:ls(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 ay(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=>Wn(a.file)));if(!t.has(Wn(e.sourceFile))||!t.has(Wn(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(Wn(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=dy(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=Ke(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=cy(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=fu({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)||ls(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 cy(e,t){let n=new Map,r=i=>{let s=Cn(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 ly(i,n))o=r(s)||o}return[...n.values()]}function ly(e,t){let n=[],r=uy(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=Gn(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=Zn(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:ts(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)&&zt(l.namespace,a));if(c.length>0){let l=Tt(s.exported);for(let u of c){let d=Gn(u.namespace,a,l);d&&n.push({file:e.file,namespace:d,exportName:u.exportName})}continue}t.has(Cn({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=Gn(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=Zn(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:ts(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 ts(e,t){return t?`${e}.${t}`:e}function zt(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function Gn(e,t,n){return!zt(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function uy(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=Zn(e.file,i.source.value);for(let a of i.specifiers){if(S.isImportDefaultSpecifier(a)){let c=t.get(Cn({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(u=>Qe(u.file,s)&&zt(u.namespace,"default"));for(let u of l){let d=Gn(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)&&zt(d.namespace,c));for(let d of l)r(a.local.name,d);let u=t.get(Cn({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:ts(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=vn(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(Cn));for(let d of c){let m=Gn(d.namespace,a.name,s.id.name),p=m?{...d,namespace:m}:d,h=Cn(p);u.has(h)||(r(s.id.name,p),u.add(h),o=!0)}}}return n}function Cn(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${rs(e.file)}#${t}`}function Tt(e){return S.isIdentifier(e)?e.name:e.value}function dy(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 fu(e){let t=fy(e),n=[],r=gu(e.ast,t);return Ft(e.ast,{JSXElement(o){Qe(e.file,e.sourceFile)&&ls(o)===e.sourceComponent||Iu(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function pu(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function mu(e,t){let n=pu();return Ft(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function fy(e){let t=pu();return Qe(e.file,e.sourceFile)&&py(t,mu(e.ast,e.sourceComponent)),Ft(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=Zn(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=>zt(u.namespace,"default"));if(l.length>0){let u=t.namespaceMembers.get(c)??new Set;for(let d of l){let m=tu(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=>zt(d.namespace,l));if(u.length>0){let d=t.namespaceMembers.get(c)??new Set;for(let m of u){let p=tu(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)}}}}}),hu(e.ast,t),t}function py(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 hu(e,t){Ft(e,{VariableDeclarator(n){if(!n.node.init)return;let r=vn(n.node.init);if(r){if(S.isIdentifier(n.node.id)){let o=Ht(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&ns(t,i,o);return}if(S.isObjectPattern(n.node.id)){let o=Ht(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&Eu(n.node.id,o.namespaceMembers,t,n)}}}})}function gu(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return Ft(e,{ReferencedIdentifier(r){if(n){r.stop();return}my(r)||!r.isIdentifier()||!yu(r,t)||hy(r,t)||gy(r)||(n=!0,r.stop())}}),n}function my(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 yu(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)&&Ht(r.node,t,r)?r:null}function hy(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!eu(e,r))return!1;let o=yu(e,t);if(!o)return!1;if(vn(r.node)===o.node)return!!Ht(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&eu(e,a)&&!!Ht(a.node,t,a)}function gy(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function eu(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Ht(e,t,n){let r=vn(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 yy(r,t,n);let o=bu(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?xu(s,o.slice(1).join(".")):null}function yy(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!S.isObjectProperty(i))continue;let s=Su(i);if(!s||!S.isExpression(i.value)){S.isExpression(i.value)&&(o||=Ht(i.value,t,n)!==null);continue}let a=Ht(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 xu(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 ns(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 Eu(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&&ns(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!S.isObjectProperty(o))continue;let i=Su(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=xu(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&&ns(n,c,s);continue}if(S.isObjectPattern(a)&&s.namespaceMembers.size>0){Eu(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function Su(e){return e.computed?S.isStringLiteral(e.key)||S.isNumericLiteral(e.key)?String(e.key.value):null:xy(e.key)}function xy(e){return S.isIdentifier(e)?e.name:S.isStringLiteral(e)||S.isNumericLiteral(e)?String(e.value):null}function vn(e){return S.isParenthesizedExpression(e)||S.isTSAsExpression(e)||S.isTSSatisfiesExpression(e)||S.isTSNonNullExpression(e)||S.isTSTypeAssertion(e)?vn(e.expression):S.isExpression(e)?e:null}function bu(e){if(S.isIdentifier(e))return[e.name];if((S.isMemberExpression(e)||S.isOptionalMemberExpression(e))&&!e.computed&&S.isIdentifier(e.property)){let t=vn(e.object),n=t?bu(t):null;return n?[...n,e.property.name]:null}return null}function tu(e,t){if(!zt(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 Iu(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=ku(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 ku(e){if(S.isJSXIdentifier(e))return[e.name];if(S.isJSXMemberExpression(e)){let t=ku(e.object);return t?[...t,e.property.name]:null}return null}function ls(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 Ey(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||Wt(a.path.node,t))return;let c=Iy(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=Cy(e.callSitePath,c.propName,e.source);if(!u.ok){o=u.reason;return}let d=Sy(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=du(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:vy(e.source,t,[...n.values()])}}function Sy(e,t){if(t.length===0)return e;let n=Cu(e);if(!n)return null;let r=ds(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=by(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function by(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function Iy(e,t,n){let r=ky(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=In(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 ky(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!Wt(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 Cy(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=mo(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 vy(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 Cu(e){try{let n=ss.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 Ry(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||Wt(s.path.node,t))return;let a=nu(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let u=nu(c,e.targetFile,e.targetFile);(!u||u.moduleFile!==a.moduleFile||!Py(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 cs(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 Py(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 nu(e,t,n){let r=wy(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=Zn(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=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 wy(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function Zn(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 rs(e)===rs(t)}function rs(e){let t=Wn(e);return t.endsWith("/index")?t.slice(0,-6):t}function Wn(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function us(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 Ay(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 Ty(e,t){return{...e,callbackParams:t}}function ru(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function ds(e){return!(S.isIdentifier(e)||S.isThisExpression(e)||S.isMemberExpression(e)||S.isOptionalMemberExpression(e)||S.isCallExpression(e)||S.isOptionalCallExpression(e))}function vu(e,t){return Ru(e,t).length>0}function Zi(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()&&!Ny(o,n,r)))return!0;o=o.parentPath}return!1}function Ny(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 Ru(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()&&Pu(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 ou(e,t,n,r){let o=Ru(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=mo(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=Fy(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${_y(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function Fy(e,t){return My(e.node)?t:`(${t})`}function My(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 Pu(e){return e==="&&"||e==="||"||e==="??"}function _y(e){return e.trim().startsWith("<")?e:`(${e})`}function wu(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=iu(e),i=iu(t);if(!o||!i||!Oy(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=Dy(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())&&Ly(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 iu(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 Oy(e,t){return e.start===t.start&&e.end===t.end}function Dy(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 Ly(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 jy={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 fo(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=jy[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 By(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 $y(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 su(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 au(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function Vy(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=as(e),o=Ke(t);if(n.exportName!=="default"){let a=o?$y(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?au(r,su(o)):r;return{localName:c,importStep:Qi(e,c)}}if(!o)return{localName:r,importStep:Qi(e,r)};let i=By(o,n.source);if(i)return{localName:i};let s=au(r,su(o));return{localName:s,importStep:Qi(e,s)}}function Uy(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??as(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 Ky(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?Jy(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function Jy(e){return Object.fromEntries(Object.entries(e).filter(t=>os(t[1])))}function os(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(os):typeof e=="object"?Object.values(e).every(os):!1}function Xy(e,t){let n=Ke(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=fu({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 Qi(e,t=as(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 cu(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 zy(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function Hn(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 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:fs(e,t.slice(0,n)),index:r.index}}return null}function qi(e,t){return e.locator?e.collectionPathMap?.[t]?fs(e.locator,e.collectionPathMap[t]):Yn(e.locator)?Wy(e.locator,Yy(t,e.collectionIndexMap)):null:null}function Hy(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:Au(o,t)}function Au(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=Au(r,t);return o===void 0?void 0:{[n.name]:o}}function po(e,t,n){return n?.finalSource?.kind==="component-prop"?"Cannot edit prop-backed node structure with a generic node operation":t?.kind==="value-binding"&&t.sourceKind==="repeat-template"&&!e.isRepeatItemRoot?"Cannot edit repeat-backed child node structure with a generic node operation":t?.kind==="value-binding"&&t.file!==e.file&&t.sourceKind!=="repeat-template"?"Cannot edit upstream-bound node structure with a generic node operation":null}function Wy(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 Yy(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 Gy(e,t){return Zy(e.root,t.root)&&qy(e.path??[],t.path??[])}function Zy(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&&Qy(e.sourceRange,t.sourceRange)}}function Qy(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function is(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 qy(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 ho=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:Hn(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:Hn(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:Hn(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:Hn(t.kind,t.params.kind)};let r=t;if(!lo(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=cu(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:Hn(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=Wg(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=qi(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=qi(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=Ke(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(!Gg(a.match.path))return{ok:!0,value:r};let c=Zg(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=qi(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=Ke(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=po(r,i,this.graph.getTextProvenance?.(r.key,0)??null);if(s)return{ok:!1,errorCode:"unsupported-operation",reason:s};let a=this.getRepeatBackedTemplateStructureReason(r);if(a)return{ok:!1,errorCode:"unsupported-operation",reason:a};let c=await this.getUpstreamBackedDescendantReason(r);if(c)return{ok:!1,errorCode:"unsupported-operation",reason:c};let l=[{order:0,file:r.file,type:"remove-node",locator: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||Xy(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(!lo(n.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};if(n.params.node.kind==="component-call"&&!n.params.node.component)return{ok:!1,errorCode:"unsupported-operation",reason:"Materialized component insertion requires the materialization transaction planner"};if(!o.canInsertChild)return{ok:!1,errorCode:"capability-denied",reason:"Cannot insert child into this node"};let s=this.graph.getEditableTextSegmentIndex(r.key),a=s!==null?await this.graph.getTextWriteTarget(r.key,s):null,c=po(r,a,s!==null?this.graph.getTextProvenance?.(r.key,s)??null:null);if(c)return{ok:!1,errorCode:"unsupported-operation",reason:c};let l=await this.getUpstreamBackedDescendantReason(r);if(l)return{ok:!1,errorCode:"unsupported-operation",reason:l};let 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=Ul(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=fo(r,n.params.node);if(h)return{ok:!1,errorCode:"unsupported-operation",reason:h};let E=[],v=0,C=n.params.node.kind==="component-call"?Vy(n.params.node,this.graph.getFileContent(r.file)):void 0,A=C?.importStep;return A&&E.push({order:v++,file:r.file,type:"add-import",moduleSpecifier:A.moduleSpecifier,imports:A.imports}),E.push({order:v++,file:r.file,type:"insert-child",parentLocator:fe(r),node:{jsx:Uy(n.params.node,C?.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(!lo(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:Ky(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(!lo(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=Hy(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=po(r,i,o!==null?this.graph.getTextProvenance?.(r.key,o)??null:null);if(s)return s;n.push(...this.graph.getChildNodes(r.key))}return null}getRepeatBackedTemplateStructureReason(t){if(t.isRepeatItemRoot)return 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=Ke(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:is(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=ht(this.graph.getFileContent(t.file),o);return i?qg(o,i):t.isRepeatItemRoot===!0}isInsideMapCallback(t){let n=Ke(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:is(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=Ke(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(!uo(m,p))return null;if(a&&(s==="before"||s==="after")){let E=wt(l,a),v=E?ht(c,E):null;if(!uo(m,v))return null}if(Zi(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let h=Yl(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:kn(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=Ke(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(uo(m,p))return null;if(p&&!ny(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 R=Gl(c,l,a);if(p&&!uo(p,R)||!p&&R)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 R=fo(o,{kind:"native-tag",tag:r.tag});if(R)return{ok:!1,errorCode:"unsupported-operation",reason:R}}let h=Yi(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(Zi(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let E=ou(c,u,d,h);for(let R of E.conditionPaths){let B=ql(R,d,m);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 v=Ql(u,d,m,{preserveConditionalBoundary:E.conditionPaths.length>0});if(!v.ok)return{ok:!1,errorCode:"unsupported-operation",reason:v.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${v.bindingNames.join(", ")}`};let C=ry(m,d);if(!C.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its callback parameters depend on bindings outside the target scope: ${C.bindingNames.join(", ")}`};let A=m;if(r.component!==o.component){let R=iy({source:c,ast:l,sourceContext:m,sourceNode:r,targetParent:o,targetParentPath:d});if(!R.ok)return{ok:!1,errorCode:"unsupported-operation",reason:R.reason};A=R.context}else{let R=du(m.collectionPath,d);if(!R.ok)return{ok:!1,errorCode:"unsupported-operation",reason:R.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${R.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:ru(A,E.sourceJsx),selectionContext:kn(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=Ke(c),d=Ke(l);if(!u||!d)return null;let m=ay({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=wu(m.callSitePath,h);if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:E.reason};let v=ht(c,p);if(!v)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")&&Gl(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=fo(o,{kind:"native-tag",tag:r.tag});if(M)return{ok:!1,errorCode:"unsupported-operation",reason:M}}let A=Yi(this.graph,r);if(!A)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Zi(p,h))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let R=ou(c,p,h,A);for(let M of R.conditionPaths){let D=ql(M,h,v);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=Ql(p,h,v,{preserveConditionalBoundary:R.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=Ry({sourceFile:r.file,targetFile:o.file,sourceContext:v,targetParentPath:h});if(!re.ok)return{ok:!1,errorCode:"unsupported-operation",reason:re.reason};let te=Ay(v);if(!te.ok)return{ok:!1,errorCode:"unsupported-operation",reason:te.reason};let w=Ty(v,te.callbackParams),_=[{order:0,file:r.file,type:"remove-node",locator:fe(r),removeWhitespace:!0}];for(let M of re.imports)_.push({order:_.length,file:o.file,type:"add-import",moduleSpecifier:M.moduleSpecifier,imports:M.imports});return _.push({order:_.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:fe(o),expression:ru(w,R.sourceJsx),placement:s,anchorLocator:a?fe(a):void 0,selectionContext:kn(o)}),this.buildPlan(t,n,_,i)}async planMoveNode(t,n,r,o){if(!o.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};let i=cu(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(zy(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 C=n.params.target.relation,A=i.anchorNode&&(C==="before"||C==="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:C,anchorSourceId:A?.kind==="external-entry"?A.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=po(r,a,this.graph.getTextProvenance?.(r.key,0)??null);if(d&&!Gi(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 C=a,A=await this.graph.getTextWriteTarget(u.key,0);if(C?.kind==="value-binding"&&A?.kind==="value-binding"&&C.locator&&A.locator){let R=Yn(C.locator),B=Yn(A.locator);if(R&&B&&C.file===A.file&&Gy(R.locator,B.locator)){let re=R.index,te=B.index,w=l==="before"?te-(re<te?1:0):te+(re<te?0:1);return this.buildPlan(t,n,[{order:0,file:C.file,type:"move-array-item",locator:R.locator,fromIndex:re,toIndex:w}],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=Gi(d)?d:m;if(p&&Gi(p)){let C=this.planRepeatTemplateInternalMove(t,n,r,s,o,l,u);if(C)return C;let A=this.planRepeatTemplateHoistMove(t,n,r,s,o,l,u);if(A)return A;let R=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,l,u);return R||{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 C=fo(s,{kind:"native-tag",tag:r.tag});if(C)return{ok:!1,errorCode:"unsupported-operation",reason:C}}if(c)return this.planCrossFileMove(t,n,r,s,o,l,u);let E=Yl(this.graph.getFileContent(r.file),r,s);if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:E.reason??`Cannot move node because it depends on bindings outside the target scope: ${E.bindingNames.join(", ")}`};let v=[{order:0,file:r.file,type:"move-node",locator:fe(r),targetParentLocator:fe(s),placement:l,anchorLocator:u?fe(u):void 0,selectionContext:kn(s)}];return this.buildPlan(t,n,v,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,u=this.graph.getFileContent(r.file),d=Yi(this.graph,r)??`<${r.component} />`,m=Kl(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,v={moduleSpecifier:es(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:v.moduleSpecifier,imports:v.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:kn(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:kn(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 $u from"@babel/parser";import ps from"@babel/traverse";import*as b from"@babel/types";var Vu=typeof ps=="function"?ps:ps.default;function Uu(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}var Tu=new WeakMap;function Nu(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 Ku(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=vs(s,t,n);if(!a)return null;let c=Rs(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 Ms({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??tr(c.node,n),sourceKind:p.sourceKind,...p.collectionIndexMap?{collectionIndexMap:p.collectionIndexMap}:{},...p.collectionPathMap?{collectionPathMap:p.collectionPathMap}:{}}}let u=new Set,d=await Px({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 Ju(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=vs(i,t,n);if(!s)return null;let a=e.expression!==void 0?(e.sourceRange?Wu(s,n,e.expression,e.sourceRange):null)??As(s,n,e.expression):e.sourceRange?Rs(s,e.sourceRange):null;if(!a)return null;let c=rx(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 De({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 Vx({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 nx(d,e.expression??tr(c.node,n))}async function Cs(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=vs(i,t,n);if(!s)return Oe("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?ox({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}):ix({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}function Xu(e){try{return $u.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function vs(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=Xu(n);return e.set(t,{source:n,ast:o}),o}function Rs(e,t){let n=null,r=-1;for(let o of er(e).expressions){let i=o.node.loc;if(!i||!Ps(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s>=r&&(n=o,r=s)}return n}function ex(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of er(e).expressions){if(!tx(o.node.loc,t))continue;let i=(o.node.end??0)-(o.node.start??0);i<=r&&(n=o,r=i)}return n}function zu(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of er(e).jsxElements){let i=o.node.loc;if(!i||!Ps(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s<=r&&(n=o,r=s)}return n}function er(e){let t=Tu.get(e);if(t)return t;let n={expressions:[],jsxElements:[]};return Vu(e,{Expression(r){n.expressions.push(r)},JSXElement(r){n.jsxElements.push(r)}}),Tu.set(e,n),n}function tx(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 Ps(e,t){let n=Fu({line:e.start.line,column:e.start.column},{line:t.startLine,column:t.startColumn}),r=Fu({line:e.end.line,column:e.end.column},{line:t.endLine,column:t.endColumn});return n>=0&&r<=0}function Hu(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 Fu(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 id(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:tr(e.expression,e.source),base:t.base,path:t.path}:null}function nx(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 rx(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 tr(e,t){if(t)return ws(e,t);let n=Gx(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function ws(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function As(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of er(e).expressions){if(ws(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function Wu(e,t,n,r){let o=null,i=Number.POSITIVE_INFINITY;for(let s of er(e).expressions){if(ws(s.node,t)!==n)continue;let a=s.node.loc;if(!a||!Ps(a,r))continue;let c=(s.node.end??0)-(s.node.start??0);c<=i&&(o=s,i=c)}return o}async function ox(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=Rs(r,o.sourceRange),u=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 sx(t,o.value);let m=await Ms({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"?Lu(t,m):Es(t,tr(l.node,n),m):ax({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return Oe("unsupported-expression","Unable to locate text expression for provenance resolution");let d=await De({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=xs(l.node);if(m)return Oe(m.code,m.message);let p=l.scope.getBinding(u.base);if(p?.path.isVariableDeclarator()){let h=xs(p.path.node.init);if(h)return Oe(h.code,h.message)}return p?.path.isVariableDeclarator()&&b.isCallExpression(p.path.node.init)?cx("unsupported-expression",qu(p.path.node.init,e.functionCallContracts)):Oe("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return d.kind==="external"?Lu(t,d):Es(t,u.expression,d)}async function ix(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return Oe("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=As(r,n,o.conditionExpression);if(!l)return Oe("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await De({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 Oe("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(u.kind==="external")return Oe("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let d=Es(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 sx(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 ax(e){let t=await Gu(e);if(t.length===0)return Oe("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(lx(e.expression))return Yu(t);if(Qu(e.expression))return Oe("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 Oe("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return Oe(n.code,n.message)}function Oe(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function cx(e,t){return Yu([{code:e,message:t}])}function Yu(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function lx(e){return b.isCallExpression(e)||b.isConditionalExpression(e)||b.isLogicalExpression(e)||b.isBinaryExpression(e)}function qn(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 Gu(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=xs(t);if(l)return[l];if(b.isCallExpression(t))return[{code:"unsupported-expression",message:qu(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)?qn([...await ms(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)?qn([...await ms(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)?qn([...await ms(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 xs(e){return Qu(e)?Mu("i18n helpers require a static message id string"):mx(e)?Mu("CMS helpers require static entry id and field path string arguments"):null}async function ms(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await Gu({...t,expression:o}));return r}function ux(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:[dx(e.sourceType)]}}async function Ts(e){for(let n of xx){if(!_u(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return Du(Ou(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(!_u(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return Du(Ou(r),e.externalAdapters)}return null}function dx(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function fx(e){return{code:"external-source-readonly",message:e}}function Mu(e){return{code:"unsupported-expression",message:e}}function Ns(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 _u(e,t){if(!t||t.length===0)return!0;let n=Ns(e.node);return n?t.includes(n):!1}function Ou(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:qn(e.diagnostics??[])}:{match:e,diagnostics:[]}}function Du(e,t){let n=ux(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:qn([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function px(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 mx(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 Zu(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 Qu(e){return Zu(e)===null}async function hx(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 gx(e){let t=Zu(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await hx(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function yx(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:[fx("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var xx=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>px(e)},{helperNames:["apiField"],resolve:e=>yx(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>gx({currentFile:e,expressionPath:t,exists:n})}];function Lu(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 Es(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=Rx(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 Ex=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function Fs(e,t){let n=[...Ex,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function qu(e,t){let n=e.callee;return b.isIdentifier(n)&&Fs(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 Ms(e){let t=await Ts(e);if(t)return t;let n=await ed({...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 De({...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 Cx(e)}async function ed(e){let t=await qe({...e,allowComposed:!1});return t?.kind==="source"?t.provenance:null}async function qe(e){let t=Sx(e.expressionPath),n=kx(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 De({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 De({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 hs(s,a,c)}if(t.isCallExpression())return bx({...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 hs(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 hs(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 Sx(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 bx(e){let t=Ns(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 hs(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!Ix(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function Ix(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 kx(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function Cx(e){if(!e.expressionPath.isCallExpression())return null;let t=Ns(e.expressionPath.node);if(!t)return null;let n=Fs(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 td({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 td(e){let t=await Ts({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 De({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 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})}async function vx(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=Fs(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 td({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 Rx(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=yo(t,e.path);return{sourceId:o,displayPath:o}}async function Px(e){let t=e.segment.source;return t?De({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 De(e){let t=e.sourceInfo,n=nd(e.expressionPath,t.base);if(n){let l=await rd({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=Ax(n.callPath,[...n.basePath,...t.path]);return Xn(E)?Nu(e.currentFile,E.sourceId,E.displayPath):null}let u=Zx(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 an(e.currentFile,u.node.source.value,e.exists);if(!d)return null;let m=await go({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=zl(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 De({...e,expressionPath:l,sourceInfo:{...u,expression:yo(u.expression,t.path),path:[...u.path,...t.path]}});if(d)return d}if(t.path.length===0){let d=await ed({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 zx({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 vx({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=oo(r,t.path);if(Xn(s))return Nu(e.currentFile,s.sourceId,s.displayPath);let a=await Gt({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 nd(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=Ge(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!wx(s,r)?null:{callPath:s,basePath:i}}function wx(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 rd(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 nr({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 Ax(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:so(r,t)}async function nr(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 Gt({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 od({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 nr({...e,expressionPath:a})}if(n.isArrayExpression()){let a=Hu(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 De({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 Tx({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=Qx(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 Tx(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 Mt(t.file,e.readFile,e.fileCache);i=s.ast?Is(s.ast).getBinding(t.root.name):void 0}return i?await Gt({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 Mt(t.file,e.readFile,e.fileCache);if(!n.ast)return null;let r=ex(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 od(e){return await Nx(e)??await Fx(e)??await Mx(e)}async function Nx(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 nr({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=_x(s);if(!c)return null;let l=[],u=[],d=[];for(let[m,p]of i.value.entries()){let h=Ox(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 Fx(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 nr({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 Mx(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 nr({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(Bu(s,a.name,c.name,d.value,m.value)===void 0)return null;return u.sort((d,m)=>{let p=Bu(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 Bu(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=Ss(i,t,n,r,o);return typeof s=="number"?s:void 0}function Ss(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=bs(e,t);if(i)return et(r,i);let s=bs(e,n);return s?et(o,s):void 0}if(b.isBinaryExpression(e)&&e.operator==="-"){let i=b.isExpression(e.left)?Ss(e.left,t,n,r,o):void 0,s=b.isExpression(e.right)?Ss(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function _x(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 Ox(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=bs(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 bs(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 Gt(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 Dx({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 Yx({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 Ts({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 od({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 Dx(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=Lx(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 Lx(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 jx(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 Bx(e,t){let n=jx(e.path);if(!n)return null;let r=In(e,t);return r?{...n,...r}:null}function yo(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function $x(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}async function Vx(e){let t=Kx(e.expressionPath.node);if(!t||!Jx(t.segments))return null;let n=await De({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 Ux({...e,rootPath:n.path,segments:t.segments});return r?{...n,path:r.collectionPathMap[0]??n.path,sourceKind:"repeat-template",displayExpression:tr(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:r.collectionPathMap}:null}async function Ux(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=nd(e.expressionPath,s.base);if(!a)return null;let c=await rd({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 Xx(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 Kx(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 Jx(e){return e.some(t=>t.kind==="dynamic")}function Xx(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}async function zx(e){let t=Bx(e.binding,e.sourceInfo);if(!t||!e.graph)return null;let n=[...e.graph.elements.values()].filter(l=>$x(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 Hx({caller:r,propName:t.propName,remainingPath:t.remainingPath,readFile:e.readFile,fileCache:e.fileCache});if(l)return gs(l,{componentName:t.componentName,propName:t.propName,file:r.sourceFile})}if(!o?.source){let l=await Wx({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 gs(l,{componentName:t.componentName,propName:t.propName,file:r.sourceFile});let u=Wl(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 Mt(r.sourceFile,e.readFile,e.fileCache);if(!i.ast)return null;let s=Wu(i.ast,i.source,o.source.expression,o.sourceRange)??As(i.ast,i.source,o.source.expression);if(!s)return null;let a={...o.source,expression:yo(o.source.expression,t.remainingPath),path:[...o.source.path,...t.remainingPath]},c=await De({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?gs(c.kind==="external"?c:{...c,displayExpression:a.expression},{componentName:t.componentName,propName:t.propName,file:r.sourceFile}):null}async function Hx(e){let t=await Mt(e.caller.sourceFile,e.readFile,e.fileCache);if(!t.ast)return null;let n=zu(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=Hu(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 Wx(e){let t=await Mt(e.caller.sourceFile,e.readFile,e.fileCache);if(!t.ast)return null;let n=zu(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:yo(s.expression,a),path:[...s.path,...a]},l=await De({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 gs(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 Yx(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 an(t,c,o);if(!l)return null;if(n.path.isImportDefaultSpecifier()){let E=await Mt(l,r,i),v=E.ast?ks(E.ast,"default"):null,C=await go({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!C||C.kind!=="static"?null:{kind:"static",file:v?.kind==="default-expression"?C.file:l,root:v?.kind==="default-expression"?C.root:{kind:"default-export"},value:C.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 Mt(l,r,i),p=m.ast?ks(m.ast,d):null,h=await go({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 go(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 Mt(t,r,i);if(!c.ast)return;let l=ks(c.ast,n);if(!l)return;if(l.kind==="default-expression"){let p=l.expression;if(!p||!b.isIdentifier(p))return;let h=Is(c.ast).getBinding(p.name);return h?await Gt({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 an(t,l.source,o);return p?go({...e,file:p,exportName:l.name}):void 0}let u=l.name;if(!u)return;let d=Is(c.ast).getBinding(u);return d?await Gt({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 Is(e){let t=null;if(Vu(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}function ks(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 Gt({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 ys(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 ys(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 ys(c.value,t,n,r,o,i,s);u!==void 0&&(a[l]=u)}return a}if(b.isMemberExpression(e)){let a=await id(e,t,n,r,o,i,s);if(!a)return;let c=t.getBinding(a.base);if(!c)return;let l=await Gt({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 ys(e,t,n,r,o,i,s){if(!b.isSpreadElement(e))return await nt(e,t,n,r,o,i,s)}async function id(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 Gx(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 Zx(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 Qx(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 Mt(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=Xu(o),s={source:o,ast:i};return n.set(e,s),s}import js from"@babel/generator";import{parse as uE}from"@babel/parser";import Bs from"@babel/traverse";import*as k from"@babel/types";import*as ld from"@babel/types";import _s from"@babel/generator";import*as ae from"@babel/types";var qx=typeof _s=="function"?_s:_s.default,eE=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,tE=/^((?:https?:)?\/\/)[^/@\s]+@/i,nE=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function ad(e,t){let n=ct(e.callee);if(!n)return null;if(n==="fetch")return Os(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(sd(r))return Os(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(sd(r))return Os(e.arguments[0],r,t,["ky client contract"])}return null}function Os(e,t,n,r){if(!e||ae.isSpreadElement(e)||ae.isJSXNamespacedName(e))return sE(t,n,r,"missing url argument");let o=rr(e);return{sourceKind:iE(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 rr(e){if(ae.isStringLiteral(e))return xo(e.value);if(ae.isTemplateLiteral(e))return xo(rE(e));if(ae.isBinaryExpression(e)&&e.operator==="+"){let t=rr(e.left),n=rr(e.right);return!t&&!n?void 0:xo(`${t??Ds(e.left)}${n??Ds(e.right)}`)}if(ae.isMemberExpression(e)){let t=cd(e);if(t)return`env:${t}`}if(!(ae.isCallExpression(e)&&ct(e.callee)==="new URL")){if(ae.isNewExpression(e)&&ae.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!ae.isSpreadElement(t)?rr(t):void 0,o=n&&!ae.isSpreadElement(n)?rr(n):void 0;return o&&r?xo(`${o} + ${r}`):r??o}if(ae.isIdentifier(e))return`:${e.name}`}}function rE(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+=Ds(r))}return t}function Ds(e){if(ae.isIdentifier(e))return`:${e.name}`;if(ae.isMemberExpression(e)){let t=cd(e);if(t)return`env:${t}`}return`:${oE(e)}`}function oE(e){return qx(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function xo(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(tE,"$1<redacted>@").replace(nE,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?eE.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function iE(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 sE(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function sd(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function cd(e){return!ae.isMemberExpression(e.object)||!ae.isIdentifier(e.object.object,{name:"process"})||!aE(e.object.property,"env")?null:ae.isIdentifier(e.property)?e.property.name:ae.isStringLiteral(e.property)?e.property.value:null}function aE(e,t){return ae.isIdentifier(e)&&e.name===t}function ct(e){if(ae.isIdentifier(e))return e.name;if(ae.isMemberExpression(e)){let t=ct(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 cE=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),lE=new Set(["getConfig","submit"]);function ud(e,t){let n=ct(e.callee);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!cE.has(i))return null;let s=Ls(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(!lE.has(i))return null;let s=Ls(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=Ls(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 dd(e,t){let n=ct(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 fd(e){let t=ct(e.callee);return typeof t=="string"&&t.startsWith("cms.field.")}function Ls(e,t){let n=e.arguments[t];return ld.isStringLiteral(n)?n.value:null}var Us=typeof Bs=="function"?Bs:Bs.default,vR=typeof js=="function"?js:js.default,dE={maxFunctionDepth:8,maxImportDepth:6},fE=new Set(["src","href","alt","poster","content","title","aria-label"]);async function xd(e){let t=e.fileCache??new Map,n=zs(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...dE,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:Fd(n,e.element.componentName)};await Ed(e.element.componentName,e.graph,r);let o=[];o.push(...await yE(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await xE(s,e.element,e.graph,r);a&&o.push(Vs(a,"text","children"))}for(let s of e.element.attributes??[]){let a=gE(s);if(!a)continue;let c=await Id(s.source,e.element,e.graph,r);c&&o.push(Vs(c,a,s.name))}let i=ME(o).sort(Td);return{hasDynamicData:i.length>0,bindings:i}}async function Ed(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 Sd(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 bd(l.sourceFile,n);if(!d)continue;let m=bo(d,n,{importDepth:n.importDepth+1});m.paramSources.clear(),m.scopeVariables=Fd(d,l.componentName),await Ed(l.componentName,t,m);let p=await pE(l,m);for(let[h,E]of p){if(!E)continue;let v=a.get(h)??[];v.push(E),a.set(h,v)}}finally{n.resolvingComponentProps.delete(u)}}}let c=new Map;for(let[l,u]of a){let d=wd(u);d.length===1&&c.set(l,d[0])}hE(o,c,n)}async function Sd(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 bd(e,r))?.imports.get(t);if(!s||!ut(s.source))return!1;let a=await Od(e,s.source,r.exists);return a?a===n?!0:Sd(a,s.importedName,n,r,o):!1}async function pE(e,t){let n=new Map;Us(t.analysis.ast,{JSXElement(o){if(mE(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 mE(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 bd(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 zs(e,r,t.fileCache)}function hE(e,t,n){if(k.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,Xs(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,ve(o))}}function gE(e){return e.name==="dangerouslySetInnerHTML"?"richtext":fE.has(e.name)?"attribute":null}async function yE(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 Ks(i.collectionSource,n);s&&r.push(Vs(Rn(s),"repeat-region",i.collectionExpression))}return r}async function xE(e,t,n,r){return Id(e.source,t,n,r)}async function Id(e,t,n,r){let o=await EE(e,t,n,r);return o||Ks(e,r)}async function EE(e,t,n,r){if(!e)return null;let o=SE(e.base,t,n);if(!o)return null;let i=await Ks(o.collectionSource,r);return i?ar(i,e.path,!0):null}function SE(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 Ks(e,t){if(!e)return null;let n=await kd(e.base,t);return n?ar(n,e.path,!1):null}async function kd(e,t){let n=t.paramSources.get(e);if(n)return ve(n);if(t.variableCache.has(e))return _E(t.variableCache.get(e)??null);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let r=await bE(e,t);if(r)return t.variableCache.set(e,ve(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?ve(s):null),t.resolvingVariables.delete(e),s}let i=t.analysis.imports.get(e);if(i&&t.importDepth<t.options.maxImportDepth){let s=await Md(i,t);if(s){let a=bo(s,t,{importDepth:t.importDepth+1}),c=_d(i,s);if(c){let d=(await Zt(c,[],a)).returnSource;return t.variableCache.set(e,d?ve(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?ve(u):null),t.resolvingVariables.delete(e),u}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}async function bE(e,t){let n=t.analysis.stateSetters.get(e);if(!n)return null;let r=[];Us(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 kd(e.name,t);if(k.isMemberExpression(e)||k.isOptionalMemberExpression(e)){let n=k.isMemberExpression(e)?dd(e,{file:t.file}):null;if(n)return Pd(n);let r=await IE(e,t);if(!r)return null;let o=NE(e);return ar(r,o,!1)}if(k.isAwaitExpression(e))return k.isExpression(e.argument)?ke(e.argument,t):null;if(k.isCallExpression(e))return Cd(e,t);if(k.isObjectExpression(e)){let n=await vd(e,t);return Object.keys(n).length>0?Xs(n,t.file):null}if(k.isConditionalExpression(e)){let n=await ke(e.consequent,t),r=await ke(e.alternate,t);return sr(md(n,r))}if(k.isLogicalExpression(e)){let n=await ke(e.left,t),r=await ke(e.right,t);return sr(md(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 IE(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 Cd(e,t){let n=ud(e,{file:t.file});if(n)return Pd(n);if(fd(e)){let d=e.arguments[0];if(d&&k.isExpression(d))return sr(await ke(d,t))}let r=await kE(e,t);if(r)return r;let o=ad(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 RE(e,t);if(i)return i;let s=await PE(e,t);if(s)return s;let a=await wE(e,t);if(a)return a;let c=await AE(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=wd(l);return u.length===1?sr(u[0]):null}async function kE(e,t){let n=ct(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=vE(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(k.isIdentifier(s)){let a=await ir(s.name,t);if(a)return(await Zt(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!k.isObjectExpression(r))return Eo(t.file,`${n} without static options`);let o=CE(r,"queryFn");if(!o)return Eo(t.file,`${n} without queryFn`);if(k.isIdentifier(o)){let i=await ir(o.name,t);return i?(await Zt(i.node,[],i.context)).returnSource:Eo(t.file,`${n} queryFn unresolved`)}return k.isArrowFunctionExpression(o)||k.isFunctionExpression(o)?(await Zt(o,[],t)).returnSource:k.isCallExpression(o)?Cd(o,t):null}function CE(e,t){for(let n of e.properties){if(!k.isObjectProperty(n)||!k.isExpression(n.value))continue;if(Rd(n)===t)return n.value}return null}function vE(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 RE(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 Rn(r);let o=e.arguments[0];if(k.isIdentifier(o)){let i=await ir(o.name,t);if(!i)return Rn(r);let s=await Zt(i.node,[r],i.context);return{...Rn(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(k.isArrowFunctionExpression(o)||k.isFunctionExpression(o)){let i=await Zt(o,[r],t);return{...Rn(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return Rn(r)}async function PE(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 wE(e,t){return!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property,{name:"then"})||!k.isExpression(e.callee.object)?null:sr(await ke(e.callee.object,t))}async function AE(e,t){if(!k.isIdentifier(e.callee))return null;let n=await ir(e.callee.name,t);if(!n)return null;let r=[];for(let i of e.arguments){if(!k.isExpression(i)){r.push(Eo(t.file,`unsupported argument for ${e.callee.name}`));continue}let s=await ke(i,t);r.push(s)}return(await Zt(n.node,r,n.context)).returnSource}async function ir(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 Md(r,t);if(!o)return null;let i=bo(o,t,{importDepth:t.importDepth+1}),s=_d(r,o);return s?{node:s,context:i}:ir(r.importedName,i)}async function Zt(e,t,n){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let r=bo(n.analysis,n,{functionDepth:n.functionDepth+1});r.scopeVariables=n.analysis.functionVariables.get(e),e.params.forEach((c,l)=>{let u=t[l];u&&$s(c,FE(u),r)});let o=TE(e),i=null,s,a=!1;for(let c of o){if(k.isObjectExpression(c)){s={...s??{},...await vd(c,r)},i=i??Xs(s,n.file);continue}let l=await ke(c,r);if(l){if(!i){i=l;continue}let u=Js(i,l);if(!u){a=!0,i=null;continue}i=u}}return{returnSource:a?null:i,...s?{objectReturnMap:s}:{}}}function $s(e,t,n){if(k.isIdentifier(e)){n.paramSources.set(e.name,ve(t));return}if(k.isAssignmentPattern(e)){$s(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=ar(t,[{kind:"property",name:r.key.name}],!0),i=k.isAssignmentPattern(r.value)?r.value.left:r.value;$s(i,o,n)}}function TE(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 vd(e,t){let n={};for(let r of e.properties){if(!k.isObjectProperty(r))continue;let o=Rd(r);if(!o||!k.isExpression(r.value))continue;let i=await ke(r.value,t);i&&(n[o]=i)}return n}function Rd(e){return k.isIdentifier(e.key)&&!e.computed?e.key.name:k.isStringLiteral(e.key)?e.key.value:null}function NE(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 ar(e,t,n){if(t.length===0)return ve(e);let r=t[0];if(r?.kind==="property"&&e.fieldMap?.[r.name])return ar(e.fieldMap[r.name],t.slice(1),n);let o=ve(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=or(o.valuePath,"data.items[]"),o.cmsFieldRoot=!1,o):i[0]==="fields"?(o.fieldPath=or(o.fieldPath,i.slice(1).join(".")),o.cmsFieldRoot=!0,o):o.cmsFieldRoot||n||o.fieldMap?(o.fieldPath=or(o.fieldPath,i.join(".")),o):(o.valuePath=or(o.valuePath,pd(t)),o)}return o.valuePath=or(o.valuePath,pd(t)),o}function pd(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function or(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function Pd(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 Rn(e){let t=ve(e);return t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function FE(e){let t=ve(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&(t.cmsFieldRoot=!1),t}function sr(e){return e?{...ve(e),confidence:e.confidence==="unknown"?"unknown":"safe-derived",evidence:[...e.evidence,{file:e.evidence[0]?.file??"unknown",reason:"safe derived expression"}]}:null}function md(e,t){return e?t?Js(e,t):ve(e):t?ve(t):null}function Js(e,t){if(So(e)!==So(t))return null;let n=Nd(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function wd(e){let t=new Map;for(let n of e){let r=So(n),o=t.get(r);t.set(r,o?Js(o,n):ve(n))}return[...t.values()]}function So(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,So(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 Xs(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 Eo(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function Vs(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 Ad(e){let t=[...e].sort(Td),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 ME(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 Td(e,t){return hd(e.targetKind)-hd(t.targetKind)||Nd(e.confidence,t.confidence)||gd(e.sourceKind)-gd(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function hd(e){return{"repeat-region":0,text:1,richtext:2,attribute:3,"component-prop":4}[e]}function gd(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function Nd(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function zs(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=uE(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 Us(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 Pn(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)&&ct(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)&&yd(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)&&yd(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 Pn(e){return!e||k.isVoidPattern(e)?[]:k.isIdentifier(e)?[e.name]:k.isObjectPattern(e)?e.properties.flatMap(t=>k.isObjectProperty(t)?Pn(t.value):Pn(t.argument)):k.isArrayPattern(e)?e.elements.flatMap(t=>t?Pn(k.isRestElement(t)?t.argument:t):[]):k.isAssignmentPattern(e)?Pn(e.left):k.isRestElement(e)?Pn(e.argument):[]}function yd(e){return k.isFunctionExpression(e)||k.isArrowFunctionExpression(e)}function Fd(e,t){let n=e.functions.get(t)??e.functions.get("default");return n?e.functionVariables.get(n):void 0}async function Md(e,t){let n=await Od(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return zs(n,r,t.fileCache)}function _d(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function Od(e,t,n){return ut(t)?an(e,t,n):null}function bo(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 _E(e){return e?ve(e):null}function ve(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,ve(n)]))}:{}}}var OE=50,DE=8*1024*1024;function Bd(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??OE),s=Math.max(0,t.maxUndoBytes??DE);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:u,redo:d};async function a(w){let _=[...w.steps].sort((W,Q)=>W.order-Q.order),M=_.filter(W=>W.type!=="invoke-external-adapter");if(M.length!==_.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)),ee=await A(D),G=new Map(ee.map(W=>[W.file,W.exists===!1?"":W.content])),xe;for(let W of M){let Q=jd(W,G.get(W.file)??"");if(!Q.ok)return{ok:!1,errorCode:Q.errorCode,reason:Q.reason};G.set(W.file,Q.source),xe=Q.selectionRef??xe}return{ok:!0,filePlan:{operationId:w.operationId,kind:"source-edit",target:w.target,documentVersion:w.documentVersion,conflictPolicy:"compare-and-swap",edits:[...G].map(([W,Q])=>({operation:"upsert",file:W,content:Q,baseContentHash:ee.find(ge=>ge.file===W)?.sha256??null}))},...xe?{selectionRef:xe}:{}}}async function c(w){let _=[...w.steps].sort((ge,xt)=>ge.order-xt.order),M=_.filter(ge=>ge.type!=="invoke-external-adapter"),D=_.filter(ge=>ge.type==="invoke-external-adapter"),ee=new Set(M.map(ge=>ge.file));if(M.length>0&&D.length>0)return{ok:!1,operationId:w.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 v(w,D);let G=await A(ee),xe=new Map;for(let ge of G)xe.set(ge.file,ge.exists===!1?"":ge.content);let W;for(let ge of M){let xt=xe.get(ge.file)??"",lt=jd(ge,xt);if(!lt.ok)return{ok:!1,operationId:w.operationId,errorCode:lt.errorCode,reason:lt.reason,rolledBack:!1};xe.set(ge.file,lt.source),lt.selectionRef&&(W=lt.selectionRef)}let Q=await B([...xe].map(([ge,xt])=>({file:ge,content:xt,exists:!0,version:0,sha256:le(xt)})),G);return Q.ok===!1?{ok:!1,operationId:w.operationId,errorCode:Q.rolledBack?"writeback-failed":"rollback-failed",reason:Q.reason,rolledBack:Q.rolledBack}:(n.push({operationId:w.operationId,preSnapshots:G,postSnapshots:Q.snapshots,plan:w}),m(),r.length=0,{ok:!0,operationId:w.operationId,kind:w.kind,target:w.target,resultVersion:Math.max(...Q.snapshots.map(ge=>ge.version)),affectedFiles:[...ee],...W?{selectionRef:W}:{}})}async function l(w){let _=new Set(w.edits.map(Q=>Q.file)),M=await A(_),D=C(w,M);if(D)return{ok:!1,operationId:w.operationId,errorCode:"stale-version",reason:D.reason,affectedFiles:[D.file],rolledBack:!1};let ee=new Map(M.map(Q=>[Q.file,Q])),G=w.edits.find(Q=>Q.operation==="create-only"&&ee.get(Q.file)?.exists!==!1);if(G)return{ok:!1,operationId:w.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${G.file}`,affectedFiles:[G.file],rolledBack:!1};let xe=w.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(xe,M,new Set(w.edits.filter(Q=>Q.operation==="create-only").map(Q=>Q.file)));return W.ok===!1?{ok:!1,operationId:w.operationId,errorCode:W.rolledBack?"writeback-failed":"rollback-failed",reason:W.reason,rolledBack:W.rolledBack}:(n.push({operationId:w.operationId,preSnapshots:M,postSnapshots:W.snapshots,plan:{operationId:w.operationId,kind:w.kind,target:w.target,documentVersion:w.documentVersion,steps:[],preSnapshots:M}}),m(),r.length=0,{ok:!0,operationId:w.operationId,kind:w.kind,target:w.target,resultVersion:Math.max(...W.snapshots.map(Q=>Q.version)),affectedFiles:[..._]})}async function u(){let w=n.at(-1);if(!w)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let _=await B(w.preSnapshots,w.postSnapshots);return _.ok===!1?{ok:!1,operationId:w.operationId,errorCode:_.rolledBack?"writeback-failed":"rollback-failed",reason:_.reason,rolledBack:_.rolledBack}:(n.pop(),r.push(w),{ok:!0,operationId:w.operationId,kind:w.plan.kind,target:w.plan.target,resultVersion:Math.max(..._.snapshots.map(M=>M.version)),affectedFiles:w.preSnapshots.map(M=>M.file)})}async function d(){let w=r.at(-1);if(!w)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let _=await B(w.postSnapshots,w.preSnapshots);return _.ok===!1?{ok:!1,operationId:w.operationId,errorCode:_.rolledBack?"writeback-failed":"rollback-failed",reason:_.reason,rolledBack:_.rolledBack}:(r.pop(),n.push(w),m(),{ok:!0,operationId:w.operationId,kind:w.plan.kind,target:w.plan.target,resultVersion:Math.max(..._.snapshots.map(M=>M.version)),affectedFiles:w.postSnapshots.map(M=>M.file)})}function m(){for(;n.length>i;)n.shift();for(;n.length>0&&p()>s;)n.shift()}function p(){return n.reduce((w,_)=>w+h(_),0)}function h(w){return E(w.preSnapshots)+E(w.postSnapshots)}function E(w){return w.reduce((_,M)=>_+M.file.length+M.content.length,0)}async function v(w,_){let M=[];for(let D of _){let ee=D.capability??"write-text",G=o.find(W=>W.sourceType===D.sourceType&&(D.adapterId===void 0||W.adapterId===D.adapterId)&&(W.capabilities===void 0||W.capabilities.includes(ee)));if(!G)return{ok:!1,operationId:w.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${D.sourceType}`,rolledBack:!1};let xe=await G.execute(D);if(!xe.ok)return{ok:!1,operationId:w.operationId,errorCode:"writeback-failed",reason:xe.reason??`External adapter failed for ${D.sourceType}`,rolledBack:!1};M.push(D.file)}return{ok:!0,operationId:w.operationId,kind:w.kind,target:w.target,resultVersion:0,affectedFiles:M}}function C(w,_){if(w.conflictPolicy!=="compare-and-swap")return null;let M=new Map(_.map(D=>[D.file,D]));for(let D of w.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 ee=M.get(D.file),G=D.baseContentHash;if(G===null){if(ee?.exists!==!1)return{file:D.file,reason:`Source file ${D.file} was created or changed before save.`};continue}if(!G)return{file:D.file,reason:`Source file ${D.file} is missing baseContentHash. Reopen the file before saving.`};if(ee?.exists===!1||ee?.sha256!==G)return{file:D.file,reason:`Source file ${D.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function A(w){let _=[];for(let M of w)_.push(await R(M));return _}async function R(w){if(!await e.exists(w))return{file:w,content:"",version:0,exists:!1};let M=Math.max(1,e.getVersion(w)),D=await e.readFile(w);return{file:w,content:D,version:M,exists:!0,sha256:le(D)}}async function B(w,_,M=new Set){let D=[];try{for(let ee of w){if(M.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 G=e.bumpVersion(ee.file);D.push(ee.file),ee.version=G}}catch(ee){let G=await te(_.filter(W=>D.includes(W.file)));if(G.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${G.failedFiles.join(", ")}: ${Ld(ee)}`,rolledBack:!1,instanceConflict:Dd(ee)};let xe=Dd(ee);return{ok:!1,reason:`${xe?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${Ld(ee)}`,rolledBack:!0,instanceConflict:xe}}return{ok:!0,snapshots:w.map(LE)}}async function re(w){if(w.exists===!1){await e.deleteFile(w.file);return}await e.writeFile(w.file,w.content)}async function te(w){let _=[];for(let M of w)try{await re(M),e.bumpVersion(M.file)}catch{_.push(M.file)}return _.length===0?{ok:!0}:{ok:!1,failedFiles:_}}}function Dd(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function LE(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 Ld(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 Fe(xn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return Fe(En({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return Fe(pn({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return Fe(hn({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return Fe(Jr({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return Fe(Un({source:t,locator:e.locator,next:e.value}));case"update-array-item":return Fe(Un({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return Fe(Wr({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return Fe(Xr({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return Fe(Yr({source:t,locator:e.locator,index:e.index}));case"move-array-item":return Fe(Gr({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return Fe(yn({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return Fe(zr({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 jE(e,t);case"set-props":{let n=e;return Fe(Hr({source:t,locator:n.locator,props:n.props}))}default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function jE(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!Ol(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:_l({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function Fe(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 $d(){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 BE}from"node:crypto";import Io from"node:fs/promises";import Hs from"node:path";import{setTimeout as $E}from"node:timers/promises";var VE={async mkdir(e,t){await Io.mkdir(e,t)},async writeFile(e,t,n){await Io.writeFile(e,t,n)},async rename(e,t){await Io.rename(e,t)},async rm(e,t){await Io.rm(e,t)}},UE=new Set(["EACCES","EBUSY","EPERM"]),KE=[10,20,40,80,160];async function JE(e,t,n){for(let r of KE)try{await e.rename(t,n);return}catch(o){if(!XE(o))throw o;await $E(r)}await e.rename(t,n)}function XE(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&UE.has(e.code)}async function ko(e,t,n=VE){let r=Hs.dirname(e),o=Hs.basename(e),i=Hs.join(r,`.${o}.${process.pid}.${BE()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await JE(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import{randomBytes as iS}from"node:crypto";import yt from"node:path";import{parse as sS}from"@babel/parser";import aS from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as vo,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as Ud,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as cS,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as lS,SiteEditMaterializationSchema as uS,parseComponentI18nResourcesJson as dS}from"@vcp-dev/contracts";var Vd=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,zE=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,HE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,WE=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,YE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,GE=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,ZE=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,QE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,qE=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,eS=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,tS=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,nS=/\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,rS=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,oS=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function cr(e,t){let n=Co([...Je(e,HE),...Je(e,WE),...Je(e,YE),...Je(e,t.includeRgbBackgroundImage?GE:ZE),...t.includeExtendedColorFunctions?[...Je(e,QE),...Je(e,qE)]:[]]),r=Co([...Je(e,eS),...Je(e,tS)]).filter(o=>t.colorMixPolicy==="always"||Vd.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...Je(e,nS).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...Je(e,oS).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:Co(Je(e,zE)),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?Co(Je(e,rS)):[]}}function Je(e,t){return e.match(new RegExp(t.source,t.flags))??[]}function Co(e){return[...new Set(e)]}var Gs="components/site/generated",Kd="{{$INSTANCE}}",Ro=5,fS=/^[a-z][a-z0-9-]{0,48}$/,pS=/^[a-f0-9]{8}$/,Jd=/\.tsx?$/,mS=/\.json$/,hS=/\.(?:tsx?|json)$/,gS=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,yS=["react","react/","next","next/","lucide-react","react-i18next","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],Ws=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Ys=aS,xS=typeof Ys=="function"?Ys:Ys.default;function ES(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>Ud)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=TS(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=uS.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=PS(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${Gs}.`,path:e.generatedRoot}};if(!Gd(r.data.instanceBaseName))return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_INVALID",message:"Static prefab instanceBaseName must contain at least one safe word.",path:r.data.instanceBaseName}};let i=Hd(r.data.files),s=Hd(e.controlledFiles);if(!NS(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>Ud)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let a=0;for(let[c,l]of r.data.files.entries()){let u=Buffer.byteLength(l.content,"utf8");if(u>cS)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>lS?{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 SS(e){let t=ES(e);if(!t.ok)return t;let n=t.data.generatedRoot,r=Gd(e.manifest.instanceBaseName),o=Math.max(1,Math.min(Ro,e.maxAttempts??Ro));for(let i=0;i<o;i+=1){let s=wS(e.instanceNameGenerator?.()??iS(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=Qd(n,a),l=bS({manifest:e.manifest,generatedRoot:n,instanceName:a,instanceRoot:c,allowedExternalImports:e.allowedExternalImports??yS});if(!l.ok)return l;if(!await IS(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 Yd(e){let t=Math.max(1,Math.min(Ro,e.maxAttempts??Ro));for(let n=0;n<t;n+=1){let r=await SS({...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 bS(e){let t=[],n=new Set;for(let i of e.manifest.files){let s=Xd({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=Xd({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=kS(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 IS(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function Xd(e){if(e.pathTemplate.split(Kd).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(Kd,e.instanceName),n=AS(t);return n?Qd(e.generatedRoot,e.instanceName)!==e.instanceRoot?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab instance root normalization failed.",path:e.pathTemplate}}:n!==e.instanceRoot&&!n.startsWith(`${e.instanceRoot}/`)?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab path must stay under components/site/generated/<instance>.",path:n}}:n!==t?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab path template cannot rely on path normalization semantics.",path:e.pathTemplate}}:n===e.instanceRoot||!hS.test(n)||gS.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 kS(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(mS.test(d.path)){if(d.path.endsWith(vo)){let h=dS(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=sS(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=cr(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(!Jd.test(d.path))continue;let m=s.get(d.path),p=null;if(xS(m,{ImportDeclaration(h){let E=zd({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(vo))){let v=CS({importer:d.path,imported:E.internalPath,source:h.node.source.value,ast:m});v.ok?c.get(E.internalPath).add(d.path):(p??=v.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=zd({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=Wd(h.node);E&&Ws.has(E)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${E}.`,file:d.path},h.stop())},OptionalMemberExpression(h){let E=Wd(h.node);E&&Ws.has(E)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${E}.`,file:d.path},h.stop())},Identifier(h){h.isReferencedIdentifier()&&Ws.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(!Jd.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(!vS(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 RS(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:Gs,instanceRoot:"",entry:{path:"",export:{kind:"default"}},files:[]}}}function zd(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 CS(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,-vo.length),i=`./${r}${vo}`;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 vS(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 RS(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 PS(e){let t=Zd(e);return t===Gs?t:null}function wS(e){let t=e.trim().toLowerCase();return pS.test(t)?t:null}function Gd(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 fS.test(t)?t:null}function Zd(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 AS(e){let t=Zd(e);return!t||t!==e?null:t}function Qd(...e){return yt.posix.join(...e)}function Hd(e){return new Set(e.map(t=>t.pathTemplate))}function TS(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 NS(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Wd(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 FS}from"node:crypto";import Po from"node:path";import{parse as sf}from"@babel/parser";import MS from"@babel/traverse";import*as af from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as Qs,PageResourceArtifactSchema as _S,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as OS,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as DS,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as LS,parseComponentI18nResourcesJson as jS}from"@vcp-dev/contracts";var qs="{{$INSTANCE}}",BS=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,$S=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,ea="components/site/generated",VS=/\.(?:tsx?|json)$/,US=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,KS=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],JS=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Zs=MS,XS=typeof Zs=="function"?Zs:Zs.default;async function ta(e){let t=_S.safeParse(e.artifact);if(!t.success)return me("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>FS(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=eb(r());if(!i)return me("Random instance suffix must be 8 lowercase hex chars.");let s=`${tb(n.resource_id)}-${i}`,a=new Map,c=new Map,l=[];for(let R of n.pages){let B=R.final_route.slice(1);a.set(R.template_page_id,R.final_route),c.set(R.template_page_id,R.title),l.push({template_page_id:R.template_page_id,title:R.title,final_route:R.final_route,route_file_path:`app/${B}/page.tsx`})}let u=[],d=new Set,m=new Set,p=new Map,h=new Map,E=[],v=new Set(n.pages.flatMap(R=>R.components.map(B=>B.component_id)));for(let R of n.components){if(!v.has(R.component_id))continue;let B=qd({materialization:R.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c});if(!B.ok)return B;for(let re of B.files){let te=tf(re,d,u);if(te)return te}m.add(B.entry),h.set(B.entry,B.entryExport),p.set(R.component_id,B.entry)}for(let[R,B]of n.pages.entries()){let re=l[R],te=qd({materialization:B.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c,pageEntryTarget:re.route_file_path});if(!te.ok)return te;for(let M of te.files){let D=tf(M,d,u);if(D)return D}m.add(te.entry),h.set(te.entry,te.entryExport),E.push({entry:te.entry,declaredComponentIds:new Set(B.components.map(M=>M.component_id))});let w=u.find(M=>M.file===re.route_file_path);if(!w)return me("Page materialization entry did not resolve to its final route file.",re.route_file_path);if(GS(w.content,re.route_file_path)!==re.final_route)return me(`Page ${B.template_page_id} requires a static PAGE_SEO.path equal to ${re.final_route}.`,re.route_file_path)}let C=HS(u,m,s,p,E,h);if(!C.ok)return C;for(let R of u)if(await e.exists(R.file))return!R.file.startsWith("app/")&&o>1?ta({...e,randomHex:r,maxAttempts:o-1}):{ok:!1,code:"MATERIALIZATION_CONFLICT",message:`Page resource create-only target already exists: ${R.file}`,path:R.file};let A=WS(u);return A||(u.sort((R,B)=>R.file.localeCompare(B.file)),{ok:!0,packageInstanceId:s,pages:l,files:u})}function qd(e){let t=e.materialization.entry.pathTemplate,n=[];for(let o of e.materialization.files){let s=o.pathTemplate===t&&e.pageEntryTarget?e.pageEntryTarget:ef(o.pathTemplate,e.packageInstanceId);if(!s)return me("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=zS(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??ef(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 zS(e,t,n,r){let o,i=e.replace(BS,(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($S,(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(qs,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?me("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function ef(e,t){let n=`${ea}/${t}`;if(e.split(qs).length>2)return null;let o=e.replace(qs,t),i=`${ea}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=Po.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!VS.test(a)||US.test(a)?null:a}function tf(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 HS(e,t,n,r,o,i){let s=new Set(e.map(p=>p.file)),a=`${ea}/${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(Qs)&&!jS(p.content).success)return me("Materialization component i18n resources are invalid.",p.file);continue}try{let E=sf(p.content,{sourceType:"module",plugins:["jsx","typescript"]});l.set(p.file,E);for(let C of E.program.body)if((C.type==="ImportDeclaration"||C.type==="ExportAllDeclaration"||C.type==="ExportNamedDeclaration"&&C.source)&&C.source){let A=C.source.value,R=QS(p.file,A,s,a);if(!R.allowed)return me(`Materialization import is outside the controlled package: ${A}`,p.file);R.internalPath&&c.get(p.file).add(R.internalPath)}let v;if(XS(E,{Identifier(C){C.isReferencedIdentifier()&&JS.has(C.node.name)&&(v??=C.node.name,C.stop())},JSXAttribute(C){C.node.name.type==="JSXIdentifier"&&C.node.name.name==="style"&&(v??="inline style",C.stop())},JSXOpeningElement(C){C.node.name.type==="JSXIdentifier"&&C.node.name.name.toLowerCase()==="style"&&(v??="style element",C.stop())}}),v)return me(`Materialization source uses forbidden capability: ${v}`,p.file)}catch{return me("Materialization source must parse as TS/TSX.",p.file)}let h=cr(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||!YS(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=of(p.entry,c);for(let E of p.declaredComponentIds){let v=r.get(E);if(!v||!h.has(v))return me(`Page entry does not reach declared component: ${E}`,p.entry)}for(let E of h){let v=u.get(E);if(v&&!p.declaredComponentIds.has(v))return me(`Page entry imports undeclared component: ${v}`,p.entry)}}let d=new Set;for(let p of t)for(let h of of(p,c))d.add(h);if(d.size!==e.length)return me("Every materialization file must be reachable from a package entry.");let m=qS(e,l,c);return m||{ok:!0}}function WS(e){if(e.length>OS)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>DS)return me("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>LS?me("Page resource exceeds the aggregate content byte limit."):null}function YS(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 GS(e,t){let n;try{n=sf(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=nf(i.init);if(s?.type!=="ObjectExpression")return null;for(let a of s.properties){if(a.type!=="ObjectProperty"||a.computed||!ZS(a.key))continue;let c=nf(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 nf(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&af.isExpression(t)?t:null}function ZS(e){return e.type==="Identifier"&&e.name==="path"||e.type==="StringLiteral"&&e.value==="path"}function QS(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=rf(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:KS.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=Po.posix.normalize(Po.posix.join(Po.posix.dirname(e),t)),i=rf(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function rf(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 qS(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(Qs))continue;let i=o.file.slice(0,-Qs.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 of(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 eb(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function tb(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 nb,parseComponentI18nResourcesJson as rb,resolveSiteTextDirection as ob,SiteLocaleSchema as ib}from"@vcp-dev/contracts";var sb=["i18next","react-i18next"],ab="components/ui/site-locale-provider.tsx",cb="components/ui/component-i18n-provider.tsx",cf="app/layout.tsx";async function ra(e){let t=e.files.filter(m=>m.path.endsWith(nb));if(t.length===0)return{ok:!0};for(let m of["package.json",cf,ab,cb])if(!await e.exists(m))return qt(`Target snapshot is missing required i18n host file: ${m}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return qt("Target snapshot package.json is invalid.")}let r=lf(n)&&lf(n.dependencies)?n.dependencies:{},o=sb.filter(m=>typeof r[m]!="string"||r[m].trim().length===0);if(o.length>0)return qt(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile(cf),s=na(i,"html","lang"),a=na(i,"html","dir"),c=na(i,"SiteLocaleProvider","locale"),l=ib.safeParse(s);if(!l.success||!a||!c||s!==c||a!==ob(l.data))return qt("Target snapshot app/layout.tsx must keep html lang/dir and SiteLocaleProvider locale consistent.");if(!i.includes('from "@/components/ui/site-locale-provider"')||!/<SiteLocaleProvider\b/.test(i)||!/<\/SiteLocaleProvider>/.test(i))return qt("Target snapshot root layout is not wired to SiteLocaleProvider.");let u=l.data,d=u.split("-")[0];for(let m of t){let p=rb(m.content);if(!p.success)return qt(`Component i18n resource is invalid: ${m.path}.`);if(!Object.hasOwn(p.data,u)&&!Object.hasOwn(p.data,d))return qt(`Component i18n resource ${m.path} has no locale for ${u} or ${d}.`)}return{ok:!0}}function na(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 qt(e){return{ok:!1,message:e}}function mf(e){let t=null,n=new WeakMap;async function r(){return t??=lb(e),t}return{async prepareAppend(o){let i=await e.readIndex(),s=await e.stageAppend(pf(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);uf(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(uf(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(pf(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 uf(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 lb(e){let t=await e.readIndex(),n=await Promise.all(t.undoIds.map(async o=>df(e,o))),r=await Promise.all(t.redoIds.map(async o=>df(e,o)));return{undo:n.reverse(),redo:r.reverse(),entryIds:[...t.entryIds],cursor:t.cursor}}async function df(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 ff(e,n,r.preSnapshots),postSnapshots:await ff(e,n,r.postSnapshots)}}async function ff(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(db(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function pf(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(!fb(e.manifest))throw new Error("durable history manifest is not an object");return e.manifest}function db(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function fb(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import hf from"node:path";function ia(){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 yf(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=gb(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 wo(e){let t=()=>pb(e);return e.mutex?e.mutex.runExclusive(t):t()}async function pb(e){let t=await yf(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=mb(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 oa({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 oa({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 oa({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 gf("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return gf("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 mb(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 oa(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:hb(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 gf(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function hb(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 gb(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)||hf.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=hf.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 sa(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function wn(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function xf(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function aa(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 Ef(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function yb(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var lr=class extends Error{constructor(t){let n=t.map(Ef);super(yb(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function Sf(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof lr?{routeId:e,message:n,diagnostics:t.diagnostics.map(Ef)}:{routeId:e,message:n}}function ca(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function bf(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 Cb=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,vb=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],If=32,kf=256,Cf={maxEntries:50,maxBytes:8*1024*1024};function Rb(){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 ko(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 Pb(){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>Cf.maxEntries||wb(e)>Cf.maxBytes;)e.shift()}}function wb(e){return e.reduce((t,n)=>t+Ab(n),0)}function Ab(e){return vf(e.preSnapshots)+vf(e.postSnapshots)}function vf(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function Rf(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 Tb(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=Xe(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 No=class extends Error{constructor(t){super(t.reason),this.result=t}},en=class extends Error{constructor(t){super(ca(t)),this.failedRoutes=t}};function Pf(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=Xe(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(Xe(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}var Nb=/\.(?:[cm]?[jt]sx?)$/i,Fb=/\.json$/i,Mb=/\.(?:css|scss|sass)$/i,_b=/\.mdx$/i,Ob=/\.ya?ml$/i;function Db(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 Lb(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function jb(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=$b(await e.listFiles(r)),i=new Map(o.files.map(a=>[a.path,a]));for(let[a,c]of n)if(Bb(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 Bb(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function $b(e){return Array.isArray(e)?{files:e}:e}function Vb(e){if(!Sb(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!==Ib||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=Eb(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(Nb.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(Fb.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${Me(t)}`,details:{path:e.path}}}if(Mb.test(e.path)){let t=wf({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(_b.test(e.path)){let t=wf({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(Ob.test(e.path))try{kb(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${Me(t)}`,details:{path:e.path}}}return{ok:!0}}function wf({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
5
  `,d);if(h===-1){l=!0;break}d=h,l=!0;continue}if(c){l=m===`
6
6
  `||m==="\r";continue}if(s){m==="*"&&p==="/"&&(s=!1,d+=1),l=m===`
7
7
  `||m==="\r";continue}if(a){m===`
8
8
  `||m==="\r"?(a=!1,l=!0):l=!1;continue}if(o){if(i)i=!1;else if(m==="\\")i=!0;else if(m===o)o=null;else if(n==="css"&&(m===`
9
9
  `||m==="\r"))return An(t,`Unterminated string literal in ${t}.`);l=m===`
10
10
  `||m==="\r";continue}if(m==="/"&&p==="*"){s=!0,d+=1,l=!1;continue}if(n==="mdx"&&m==="/"&&p==="/"){a=!0,d+=1,l=!1;continue}if(m==="'"||m==='"'||n==="mdx"&&m==="`"){o=m,l=!1;continue}if(m==="{"||m==="("||m==="["){r.push({char:m,offset:d}),l=!1;continue}if(m==="}"||m===")"||m==="]"){let h=m==="}"?"{":m===")"?"(":"[",E=r.pop();if(!E||E.char!==h)return An(t,`Unexpected closing token "${m}" in ${t}.`);l=!1;continue}l=m===`
11
- `||m==="\r"}if(s)return An(t,`Unterminated block comment in ${t}.`);if(o)return An(t,`Unterminated string literal in ${t}.`);if(c)return An(t,`Unterminated MDX code fence in ${t}.`);let u=r.at(-1);return u?An(t,`Unclosed token "${u.char}" in ${t}.`):{ok:!0}}function An(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function dr(e){let t="idle",n=e.fileSystem??vb(),r=$d(),o=new Map,i=new Map,s=null,a=new Set,c=null,l=e.history??(e.historyStore?mf(e.historyStore):Rb()),u=Bd(n,{externalAdapters:e.externalAdapters}),d=new Map,m=new Set,p=Math.max(0,e.initialDocumentVersion??0),h=0,E=e.historyStore?.recoveryRequired??!1,v=ia(),C=te();function R(f){return(Ao.isAbsolute(f)?Ao.relative(e.projectRoot,f):f).replace(/\\/g,"/").replace(/^\.\//,"")}function w(f,y){let g=Ao.posix.dirname(f),I=y.replace(/\.(?:tsx?|jsx?)$/i,""),P=Ao.posix.relative(g,I);return P.startsWith(".")?P:`./${P}`}function z(f,y){return f.startLine===y.startLine&&f.startColumn===y.startColumn&&f.endLine===y.endLine&&f.endColumn===y.endColumn}async function te(){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)?ce(await n.readFile(F.path)):null));if(bf({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: ${Me(y)}`).catch(()=>{})}}function le(){return t==="disposed"}if(e.onEvent&&r.subscribe(e.onEvent),e.routes)for(let f of e.routes){let y=Rf(f.routeId,f.entryFile);o.set(f.routeId,y),A(y,y.dependencyFiles)}function A(f,y){let g=new Set(y);M(f),f.dependencyFiles=g;for(let I of f.dependencyFiles){let P=i.get(I);P||(P=new Set,i.set(I,P)),P.add(f.routeId)}}function M(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 j(f){for(let y of f)if(!i.has(y))return!1;return!0}async function ee(f,y,g,I,P){let F=new Map,B=Uu(P.values()),D=new Map,N=typeof n.exists=="function"?K=>n.exists(K):async()=>!1;for(let[K,J]of f.elements){let oe=y.nodes.get(K);if(!oe)continue;let Z=g.get(J.sourceFile)??I.get(J.sourceFile),ue=new Map,T=new Map,_=new Map,Y=[];for(let pe of J.textSegments){if(!Z){ue.set(pe.index,null);continue}let Mn=await Ku({file:J.sourceFile,source:Z,segment:pe,readFile:We=>n.readFile(We),exists:N,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:We,adapterId:qo,capabilities:ei})=>({sourceType:We,adapterId:qo,capabilities:ei})),functionCallContracts:e.functionCallContracts,fileCache:B}),Ce=await Cs({file:J.sourceFile,source:Z,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:qo,capabilities:ei})=>({sourceType:We,adapterId:qo,capabilities:ei})),functionCallContracts:e.functionCallContracts,fileCache:B}),on=Ob(Mn);ue.set(pe.index,on),T.set(pe.index,Mn),_.set(pe.index,Ce),Y.push({editable:pe.editable,source:on})}let q=new Map;if(Z)for(let pe of J.attributes??[]){let Mn=await Ju({file:J.sourceFile,source:Z,sourceRange:pe.sourceRange,expression:pe.source?.expression??pe.value,sourceInfo:pe.source,readFile:Ce=>n.readFile(Ce),exists:N,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Ce,adapterId:on,capabilities:We})=>({sourceType:Ce,adapterId:on,capabilities:We})),functionCallContracts:e.functionCallContracts,fileCache:B});q.set(pe.name,Mn)}let He=El(Db(oe.writeTarget),Y),Se=Cl({key:K,element:J,graph:f,provenances:_}),Te=wl(J),kr=Al(J),Cr=Tl(J),rn=Z?await xd({element:J,graph:f,file:J.sourceFile,source:Z,readFile:pe=>n.readFile(pe),exists:N,fileCache:D}):void 0,Dt=f.regions.find(pe=>pe.kind==="conditional-region"&&pe.childKeys.includes(K)),Pe,Fn=Dt?.sourceCandidates?.[0];if(Z&&Dt&&Fn?.kind==="conditional-branch"){let pe=await Cs({file:J.sourceFile,source:Z,target:{kind:"conditional-branch",candidate:Fn},readFile:Ce=>n.readFile(Ce),exists:N,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Ce,adapterId:on,capabilities:We})=>({sourceType:Ce,adapterId:on,capabilities:We})),functionCallContracts:e.functionCallContracts,fileCache:B});Pe={currentBranch:Dt.childKeys.indexOf(K)<=0?"then":"else",availableBranches:Dt.childKeys.length>1?["then","else"]:["then"],conditionExpression:Fn.conditionExpression,provenance:{finalSource:pe.finalSource?{kind:pe.finalSource.kind,file:pe.finalSource.file,displayPath:pe.finalSource.displayPath}:null,chain:pe.chain.map(Ce=>({kind:Ce.kind,file:Ce.file,displayName:Ce.displayName,canEditHere:Ce.canEditHere})),confidence:pe.confidence,editMode:pe.editMode,diagnostics:pe.diagnostics.map(Ce=>({code:Ce.code,message:Ce.message}))}}}F.set(K,{textSources:ue,textTargets:T,elementPropertyTargets:q,provenances:_,writeTarget:He,componentSemantic:Se,contentModel:Te,mediaModel:kr,styleSource:Cr,conditional:Pe,dynamicData:rn})}return F}function G(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 P=g.sourceCache??sa(d,[]),F=await Q(I.entryFile),{graph:B,allSources:D,diagnostics:N,parsedModules:K,entryModule:J}=await hc(I.entryFile,y,Pe=>n.readFile(Pe),typeof n.exists=="function"?Pe=>n.exists(Pe):async()=>!1,{additionalEntries:F,version:I.graph?.version??1});if(N.length>0)throw new lr(N);let oe=new Map;for(let Pe of D.keys())oe.set(Pe,G(Pe));let Z=Math.max(xe(I,oe),g.minimumVersion??0,p);g.changed&&Z<=(I.graph?.version??0)&&(Z=(I.graph?.version??0)+1),B.version=Z;for(let[Pe,Fn]of D)aa(P,Pe,Fn,kf);let ue=await ge(I.entryFile,D,P);B.routeId=f;let T=gc(B),_=xc(T,B),Y=await ee(B,T,D,P,K),q=fp(B,_,Y),He=dp(Y),Se=Qb(ml(B,T,_,{canUpdateTextByKey:q,dynamicDataSummaryByKey:He}),B,Y),Te=sl({route:f,entryFile:I.entryFile,version:Z,source:y,ast:J?.ast}),kr=al(Te);Te.ok&&Ub(Se,B,Te.projection);let Cr={...Se,...ue?{styleContext:ue}:{},pageComposition:kr},rn=new Set([I.entryFile,...D.keys()]);if(ue){rn.add(ue.entryCss.path);for(let Pe of ue.stylesheets)rn.add(Pe.path)}let Dt={...I,dependencyFiles:rn,graph:B,topology:T,capabilities:_,document:Cr,pageComposition:kr,pageCompositionProjection:Te.projection,pagePlacementByKey:Te.ok?Te.projection.placementByKey:null,pagePlacementUnitByKey:Te.ok?Te.projection.placementUnitByKey:null,pageUnitByKey:Te.ok?Te.projection.unitByKey:null,pagePlacementsByUnitKey:Te.ok?Te.projection.placementsByUnitKey:null,documentIndex:Ab(Cr),detailProjections:Y,fileVersions:oe,styleContext:ue};if(g.publish===!1)return Dt;wn(d,P);for(let Pe of P.keys())m.delete(Pe);return p=Math.max(p,Z),A(I,rn),Object.assign(I,Dt),I}async function Q(f){let y=[];for(let g of zb(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,K]of y){if(ua(N)){I.push(N);continue}for(let J of Wb(K)){let oe=Nf(N,J);oe&&I.push(oe)}}if(!I.length){for(let N of Hb(f))if(await lt(N)){I.push(N);break}}let P=new Map,F=Of(I).slice(0,If);for(;F.length>0&&P.size<If;){let N=F.shift();if(P.has(N)||!ua(N))continue;let K=await xt(N,g);if(K!==null){P.set(N,{path:N,content:K});for(let J of Yb(K)){let oe=Nf(N,J);oe&&!P.has(oe)&&!F.includes(oe)&&F.push(oe)}}}let B=[...P.values()].map(N=>({...N,hash:ce(N.content)})),D=B[0];return D?{revision:ce(JSON.stringify(B.map(({path:N,hash:K})=>({path:N,hash:K})))),entryCss:D,stylesheets:B.slice(1)}:null}async function xt(f,y){let g=y.get(f);if(g!==void 0)return g;if(!await lt(f))return null;let I=await n.readFile(f);return aa(y,f,I,kf),I}async function lt(f){return typeof n.exists=="function"?n.exists(f):!1}function dp(f){let y=new Map;for(let[g,I]of f)I.dynamicData?.bindings.length&&y.set(g,Ad(I.dynamicData.bindings));return y}function fp(f,y,g){let I=new Map;for(let[P,F]of f.elements){if(!y.get(P)?.canUpdateText){I.set(P,!1);continue}let D=g.get(P),N=F.textSegments.some(K=>{if(!K.editable)return!1;let J=D?.provenances.get(K.index)??null;return!J||pp(J)});I.set(P,N)}return I}function pp(f){return f.editMode==="direct"||f.editMode==="proxy"||f.editMode==="upstream"}async function Sr(f,y={}){let g=[...new Set(f)],I=O(g);if(I.size===0||!j(g))for(let D of o.values())Va(D,g)&&I.add(D.routeId);let P=I.size===0&&g.some(Tf),F=y.publish===!1?sa(d,g):void 0,B={rebuiltRoutes:[],failedRoutes:[],...y.publish===!1?{candidateRouteStates:[],candidateSourceCache:F}:{}};for(let D of o.values())if(I.has(D.routeId)||P)try{let K=!!D.graph,J=await n.readFile(D.entryFile),oe=await W(D.routeId,J,{...y,...F?{sourceCache:F}:{}});oe?.graph&&(B.rebuiltRoutes.push({documentChanged:K,routeId:D.routeId,version:oe.graph.version}),B.candidateRouteStates?.push({routeId:D.routeId,state:oe}))}catch(K){B.failedRoutes.push(Sf(D.routeId,K))}return B}function $a(f){let y=[...new Set(f)],g=O(y);if(g.size>0&&j(y))return[...g];for(let I of o.values())Va(I,y)&&g.add(I.routeId);return[...g]}function Ho(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 Va(f,y){return y.some(g=>f.dependencyFiles.has(g)||f.entryFile===g||f.graph?.fileIndex.has(g))}function Ua(f){for(let y of f)a.add(y);c||le()||(c=(async()=>{t="building";let y=!1;try{for(;a.size>0;){if(le())return;await mp();let g=[...a];a.clear();let I=await Ka(g);if(I.length===0)continue;let P=$a(I);for(let D of P)r.emit({type:"graph-invalidated",routeId:D});let{rebuiltRoutes:F,failedRoutes:B}=await Sr(I,{changed:!0});for(let{documentChanged:D,routeId:N,version:K}of F)r.emit({type:"graph-ready",routeId:N,version:K}),D&&r.emit({type:"document-changed",routeId:N,version:K});for(let{routeId:D,message:N}of B)y=!0,r.emit({type:"graph-error",routeId:D,message:N})}}finally{if(c=null,t!=="disposed"){let g=s?o.get(s):null;t=!y&&g?.graph?"ready":"idle"}a.size>0&&Ua([])}})())}async function mp(){for(;h>0;)await new Promise(f=>setTimeout(f,0))}async function Ka(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(P){if(!Vb(P))try{if(await n.exists(g))continue}catch{continue}m.add(g),y.push(g)}}return y}function Ja(f){xf(d,f);for(let y of f)y.exists===!1?m.add(y.file):m.delete(y.file)}function Xa(f){m.clear();for(let y of f)m.add(y)}async function za(f){let y=await Ka(f);if(y.length===0)return;let g=$a(y);for(let F of g)r.emit({type:"graph-invalidated",routeId:F});let{rebuiltRoutes:I,failedRoutes:P}=await Sr(y,{changed:!0});for(let{documentChanged:F,routeId:B,version:D}of I)r.emit({type:"graph-ready",routeId:B,version:D}),F&&r.emit({type:"document-changed",routeId:B,version:D});for(let{routeId:F,message:B}of P)r.emit({type:"graph-error",routeId:F,message:B})}async function hp(f,y){let g=Nn(f,y);if(!g?.graph)return;let I=Xe(f)??f,P=g.graph.elements.get(I);P&&await za([P.sourceFile])}async function Ha(f){let y=new Set;if(f.target.kind==="node"){let g=Nn(f.target.key,f.routeId),I=Xe(f.target.key)??f.target.key,P=g?.graph?.elements.get(I);P&&y.add(P.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 gp(f){if(f.params.kind!=="source-edit")return Wo(f,"invalid-params","source-edit requires source-edit params");for(let y of f.params.edits){let g=$b(y);if(!g.ok)return Wo(f,g.errorCode,g.message,g.details)}h+=1;try{let y=await bp(f.params.edits);if(!y.ok)return Wo(f,y.errorCode,y.message,y.details);await Ha(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 Tn({request:f,filePlan:g})}catch(y){return{requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:p,error:{code:L.INTERNAL_ERROR,message:Me(y)}}}finally{h-=1}}async function yp(f){if(f.target.kind!=="project"||f.params.kind!=="insert-page-resource")return ne(f,L.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");h+=1;try{let y=await ra({files:[...f.params.artifact.components.flatMap(I=>I.materialization.files.map(P=>({path:P.pathTemplate,content:P.content}))),...f.params.artifact.pages.flatMap(I=>I.materialization.files.map(P=>({path:P.pathTemplate,content:P.content})))],exists:I=>n.exists(I),readFile:I=>n.readFile(I)});if(!y.ok)return ne(f,L.MATERIALIZATION_REJECTED,y.message);let g=await ta({artifact:f.params.artifact,exists:I=>n.exists(I)});return g.ok?await Tn({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}}):ne(f,g.code==="MATERIALIZATION_CONFLICT"?L.MATERIALIZATION_CONFLICT:L.MATERIALIZATION_REJECTED,g.message,g.path?{path:g.path}:void 0)}catch(y){return ne(f,L.INTERNAL_ERROR,Me(y))}finally{h-=1}}async function xp(f,y){if(f.kind!=="insert-child"||f.params.kind!=="insert-child")return ne(f,L.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 ne(f,L.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(f.params.position.documentVersion!==f.documentVersion)return ne(f,L.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 ne(f,L.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(f.documentVersion!==g.version||I.documentVersion!==g.version)return ne(f,L.VERSION_STALE,`Document version ${f.documentVersion} is stale (current: ${g.version}).`);let P=f.params.node.kind==="component-call"?f.params.node.materialization:void 0;if(!P)return ne(f,L.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let F=f.params.position,B=await ra({files:P.files.map(N=>({path:N.pathTemplate,content:N.content})),exists:N=>n.exists(N),readFile:N=>n.readFile(N)});if(!B.ok)return ne(f,L.MATERIALIZATION_REJECTED,B.message);let D=await Yd({manifest:P,generatedRoot:"components/site/generated",controlledFiles:P.files.map(N=>({pathTemplate:N.pathTemplate})),exists:N=>n.exists(N),commit:async N=>{let K=await n.readFile(y.entryFile),J=y.document,oe=y.pageCompositionProjection;if(!J||J.pageComposition?.status!=="supported"||J.version!==f.documentVersion||!oe||oe.status!=="supported"||oe.documentVersion!==J.version)return{ok:!0,data:ne(f,L.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let Z=N.entry.path,ue=wp(N.instanceName),T=Mi({routeId:y.routeId,entryFile:y.entryFile,currentDocumentVersion:J.version,expectedDocumentVersion:f.documentVersion,source:K,projection:oe,placementKey:F.placementKey,component:{source:Z,exportName:N.entry.export.kind==="default"?"default":N.entry.export.name,localName:ue}});if(!T.ok)return{ok:!0,data:ne(f,tc(T.error.code),T.error.message,{diagnostics:T.error.diagnostics})};let _=T.plan.returnStep?tl({source:K,jsx:T.plan.returnStep.node.jsx,placement:T.plan.returnStep.placement,...T.plan.returnStep.replaceOriginal?{replaceOriginal:!0}:{}}):T.plan.insertStep?.parentLocator?hn({source:K,locator:T.plan.insertStep.parentLocator,node:T.plan.insertStep.node,placement:T.plan.insertStep.placement,...T.plan.insertStep.anchorLocator?{anchorLocator:T.plan.insertStep.anchorLocator}:{}}):{ok:!1,source:K,diagnostic:{code:"unsupported-syntax",message:"Route composition rewrite has no insertion step."}};if(!_.ok)return{ok:!0,data:ne(f,L.AST_PARSE_ERROR,_.diagnostic.message)};let Y=xn({source:_.source,moduleSpecifier:T.plan.importStep.moduleSpecifier,imports:T.plan.importStep.imports});if(!Y.ok)return{ok:!0,data:ne(f,L.AST_PARSE_ERROR,Y.diagnostic.message)};let q=N.files.map(Se=>({operation:"create-only",file:Se.path,content:Se.content})),He=[{operation:"upsert",file:y.entryFile,content:Y.source,baseContentHash:ce(K)},...q];h+=1;try{let Se=await Tn({request:f,filePlan:{operationId:f.id,kind:"source-edit",target:{kind:"source-file",path:y.entryFile},documentVersion:f.documentVersion,conflictPolicy:"compare-and-swap",edits:He}});return!Se.ok&&Se.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:Se.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:Se}}finally{h-=1}}});return D.ok?D.data:ne(f,L.VERSION_STALE,D.error.message,{materializationCode:D.error.code})}async function Ep(f,y){if(f.kind!=="move-node"&&f.kind!=="remove-node")return ne(f,L.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 ne(f,L.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(f.documentVersion!==g.version||I.documentVersion!==g.version)return ne(f,L.VERSION_STALE,`Document version ${f.documentVersion} is stale (current: ${g.version}).`);let P=await n.readFile(y.entryFile),F=nl({routeId:y.routeId,entryFile:y.entryFile,currentDocumentVersion:g.version,expectedDocumentVersion:f.documentVersion,source:P,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 ne(f,tc(F.error.code),F.error.message,{diagnostics:F.error.diagnostics});let B=F.plan.rewriteStep.kind==="move-node"?yn({source:P,locator:F.plan.rewriteStep.locator,targetParentLocator:F.plan.rewriteStep.targetParentLocator,placement:F.plan.rewriteStep.placement,...F.plan.rewriteStep.anchorLocator?{anchorLocator:F.plan.rewriteStep.anchorLocator}:{}}):pn({source:P,locator:F.plan.rewriteStep.locator});if(!B.ok)return ne(f,L.AST_PARSE_ERROR,B.diagnostic.message);let D=B.source,N=[];if(f.kind==="remove-node"){let J=await Sp({routeState:y,placementUnitKey:f.target.placementUnitKey,source:P,mutatedSource:D});D=J.source,N=await Promise.all(J.files.map(async oe=>({operation:"delete",file:oe,baseContentHash:ce(await n.readFile(oe))})))}let K=[{operation:"upsert",file:y.entryFile,content:D,baseContentHash:ce(P)},...N];h+=1;try{return await Tn({request:f,filePlan:{operationId:f.id,kind:"source-edit",target:{kind:"source-file",path:y.entryFile},documentVersion:f.documentVersion,conflictPolicy:"compare-and-swap",edits:K}})}finally{h-=1}}async function Sp(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 B=[...g.elements.values()].find(q=>q.sourceFile===f.routeState.entryFile&&q.importedFrom&&z(q.sourceRange,F));if(!B?.importedFrom||!B.exportName)return y;let D=R(B.importedFrom),N="components/site/generated/";if(!D.startsWith(N))return y;let K=D.slice(N.length).split("/")[0];if(!K||!/-[0-9a-f]{8}$/i.test(K))return y;let J=`${N}${K}`;if([...g.elements.values()].filter(q=>q.sourceFile===f.routeState.entryFile&&R(q.importedFrom??"")===D).length!==1)return y;let Z=await n.listFiles({maxFiles:5e3,maxDepth:32}),ue=Array.isArray(Z)?Z:Z.files;if(!Array.isArray(Z)&&Z.truncated)return y;let T=ue.map(({path:q})=>q).filter(q=>q===J||q.startsWith(`${J}/`));if(T.length===0||!T.includes(D))return y;for(let{path:q}of ue)if(!(q===f.routeState.entryFile||q===J||q.startsWith(`${J}/`)))try{if((await n.readFile(q)).includes(K))return y}catch{return y}let _=w(f.routeState.entryFile,D),Y=En({source:f.mutatedSource,moduleSpecifier:_,imports:B.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:B.exportName}]});return Y.ok?{source:Y.source,files:T.sort((q,He)=>q.localeCompare(He))}:y}async function bp(f){if(n.getFileInfo){for(let P of f)if(await n.exists(P.path)&&await n.getFileInfo(P.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${P.path}`,details:{path:P.path}}}let y=Ip(f);if(y.length===0)return{ok:!0};let g=Lb(n,f),I=dr({projectRoot:e.projectRoot,fileSystem:g,routes:[...o.values()].map(P=>({routeId:P.routeId,entryFile:P.entryFile})),externalAdapters:e.externalAdapters,externalSourceResolvers:e.externalSourceResolvers,functionCallContracts:e.functionCallContracts,dev:e.dev});try{for(let P of y)await I.setActiveRoute(P)}catch(P){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${Me(P)}`,details:{routeIds:y}}}finally{I.dispose()}return{ok:!0}}function Ip(f){return f.map(g=>g.path).some(Tf)?[...o.keys()]:[]}function Wo(f,y,g,I){let P=ur(y);return{requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:p,error:{code:P,message:g,...I?{details:I}:{}}}}async function Yo(f){let y=[];for(let g of new Set(f))y.push(await kp(g));return y}async function kp(f){if(!(typeof n.exists=="function"?await n.exists(f):!0))return{file:f,content:"",version:Math.max(0,G(f)),exists:!1};let g=await n.readFile(f);return{file:f,content:g,version:Math.max(1,G(f)),exists:!0,sha256:ce(g)}}async function Wa(f,y,g,I){if(!e.historyStore)return null;let P=I.historyTransition;if(!P)throw new Error("Durable history did not provide an exact index transition.");let F=new Map(y.map(N=>[N.file,N])),B=new Map(g.map(N=>[N.file,N])),D=[...new Set([...F.keys(),...B.keys()])].sort().map(N=>{let K=F.get(N),J=B.get(N);return{path:N,preDigest:K?.exists===!1||!K?null:ce(K.content),postDigest:J?.exists===!1||!J?null:ce(J.content)}});return{schemaVersion:2,transactionId:`${f}:${P.expectedIndexDigest}`,operationId:f,phase:"prepared",historyTransition:P,files:D}}async function Ya(f){return!f||!e.historyStore||await e.historyStore.writeTransactionJournal(f),f}async function nn(f){f&&e.historyStore&&await e.historyStore.clearTransactionJournal(f.transactionId)}async function Go(f,y){let g=[];try{for(let I of f)await Ga(I),typeof n.bumpVersion=="function"&&n.bumpVersion(I.file),g.push(I.file)}catch(I){let P=await Cp(y.filter(F=>g.includes(F.file)));return P.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${Me(I)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${P.failedFiles.join(", ")}: ${Me(I)}`,rolledBack:!1}}return{ok:!0,snapshots:f.map(vp)}}async function Ga(f){if(f.exists===!1){await n.deleteFile(f.file);return}await n.writeFile(f.file,f.content)}async function Cp(f){let y=[];for(let g of f)try{await Ga(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 vp(f){let y=f.exists!==!1;return{file:f.file,content:y?f.content:"",version:f.version,exists:y,...y?{sha256:ce(f.content)}:{}}}async function Tn(f){return v.runExclusive(()=>Rp(f))}async function Rp(f){let y=f.filePlan.edits.map(T=>T.file),g=await Yo(y),I=new Map(g.filter(T=>T.exists!==!1).map(T=>[T.file,T.content])),P=p,F=Qa(),B=new Map(d),D=new Set(m),N=f.filePlan.edits.map(T=>T.operation==="delete"?{file:T.file,content:"",version:0,exists:!1}:{file:T.file,content:T.content,version:0,exists:!0,sha256:ce(T.content)}),K={operationId:f.filePlan.operationId,intents:f.filePlan.edits.map(T=>T.operation==="delete"?{kind:"delete",path:T.file}:{kind:T.operation==="create-only"?"create-only":"upsert",path:T.file,content:T.content})},J=null,oe=!1,Z=await wo({overlay:I,exists:T=>n.exists(T),plan:K,buildCandidate:async({plan:T})=>({plan:T}),prepareHistory:async()=>{let T=await l.prepareAppend({operationId:f.request.id,kind:f.request.kind,target:f.request.target,preSnapshots:g,postSnapshots:N,...f.selectionRef?{selectionRef:f.selectionRef}:{},...f.output?{output:f.output}:{}});return J=await Wa(f.request.id,g,N,T),J=await Ya(J),T},reverify:async()=>{},writeCandidate:async()=>{let T=await u.executeFilePlan(f.filePlan);if(!T.ok)throw new No(T);return{postSnapshots:await Yo(T.affectedFiles),affectedFiles:T.affectedFiles,internalResultVersion:T.resultVersion}},validateCandidate:async({candidate:T,receipt:_})=>{let Y=await Sr(_.affectedFiles,{changed:!0,minimumVersion:_.internalResultVersion,publish:!1});if(Y.failedRoutes.length>0)throw new en(Y.failedRoutes);let q=qa(F,Y.candidateRouteStates??[]),He=Math.max(_.internalResultVersion,...Y.rebuiltRoutes.map(Se=>Se.version));return{...T,rebuild:Y,routeSnapshots:q,resultVersion:He,...Pf(f.selectionRef,q.map(Se=>Se.state.document))?{selectionRef:Pf(f.selectionRef,q.map(Se=>Se.state.document))}:{}}},publishCandidate:async({candidate:T,history:_,receipt:Y})=>{if(!_)throw new Error("history intent is missing");await l.publishPrepared(_),oe=!0;let q=T.resultVersion??Y.internalResultVersion;return{requestId:f.request.id,kind:f.request.kind,target:f.request.target,ok:!0,resultVersion:q,affectedFiles:Y.affectedFiles,...f.output?{output:f.output}:{},...T.selectionRef?{selectionRef:T.selectionRef}:{}}},swapCandidate:({candidate:T,receipt:_})=>{T.routeSnapshots&&br(T.routeSnapshots),T.rebuild?.candidateSourceCache&&wn(d,T.rebuild.candidateSourceCache),Ja(_.postSnapshots),p=Math.max(p,T.resultVersion??P)},finalizeCandidate:async()=>{await nn(J)},emitCommitted:({candidate:T,published:_})=>{Ho(_,T.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:T,receipt:_})=>{if(oe)throw new Error("history was published before transaction finalization failed");if(_){let Y=await Go(g,_.postSnapshots);if(!Y.ok)throw new Error(Y.reason)}br(F),wn(d,B),Xa(D),p=P,T&&await l.discardPrepared?.(T),await nn(J)}});if(Z.ok)return Z.published;if(Z.stage==="precheck"||Z.stage==="build")try{await nn(J)}catch(T){let _=await Ir(Me(T));return ne(f.request,_,"Unable to clear an uncommitted transaction journal.")}if(Z.recoveryRequired){let T=await Ir(Z.reason);return ne(f.request,T===L.RECOVERY_PERSIST_FAILED?T:L.ROLLBACK_FAILED,Z.reason)}let ue=Z.error;return ue instanceof No?{...ne(f.request,ur(ue.result.errorCode),ue.result.reason),...ue.result.affectedFiles?{affectedFiles:ue.result.affectedFiles}:{}}:ue instanceof en?ne(f.request,L.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${ca(ue.failedRoutes)}`,{failedRoutes:ue.failedRoutes}):ne(f.request,ec(Z.stage),Me(ue))}async function Za(f){return v.runExclusive(async()=>{let y=f==="undo"?await l.prepareUndo():await l.prepareRedo();return y?Pp(f,y):{requestId:f,kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:p,error:{code:L.INTERNAL_ERROR,message:f==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function Pp(f,y){let g=y.entry,I=f==="undo"?g.preSnapshots:g.postSnapshots,P=f==="undo"?g.postSnapshots:g.preSnapshots,F=I.map(_=>_.file),B=await Yo(F),D=new Map(B.filter(_=>_.exists!==!1).map(_=>[_.file,_.content])),N=p,K=Qa(),J=new Map(d),oe=new Set(m),Z=null,ue=!1,T=await wo({overlay:D,plan:{operationId:`${f}:${g.operationId}`,intents:I.map(_=>_.exists===!1?{kind:"delete",path:_.file}:{kind:"upsert",path:_.file,content:_.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(Z=await Wa(`${f}:${g.operationId}`,B,I,y),Z=await Ya(Z),y),reverify:async()=>{},writeCandidate:async()=>{let _=await Go(I,P);if(!_.ok)throw new Error(_.reason);return{snapshots:_.snapshots}},validateCandidate:async({candidate:_})=>{let Y=await Sr(F,{changed:!0,minimumVersion:p+1,publish:!1});if(Y.failedRoutes.length>0)throw new en(Y.failedRoutes);let q=qa(K,Y.candidateRouteStates??[]),He=Math.max(p+1,...Y.rebuiltRoutes.map(Se=>Se.version));return{..._,rebuild:Y,routeSnapshots:q,resultVersion:He}},publishCandidate:async({candidate:_,history:Y})=>{if(!Y)throw new Error("history cursor intent is missing");await l.publishPrepared(Y),ue=!0;let q=_.resultVersion??p+1;return{requestId:f,kind:g.kind,target:g.target,ok:!0,resultVersion:q,affectedFiles:F,...g.output?{output:g.output}:{}}},swapCandidate:({candidate:_,receipt:Y})=>{_.routeSnapshots&&br(_.routeSnapshots),_.rebuild?.candidateSourceCache&&wn(d,_.rebuild.candidateSourceCache),Ja(Y.snapshots),p=Math.max(p,_.resultVersion??N)},finalizeCandidate:async()=>{await nn(Z)},emitCommitted:({candidate:_,published:Y})=>Ho(Y,_.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:_,receipt:Y})=>{if(ue)throw new Error("history cursor was published before transaction finalization failed");if(Y){let q=await Go(P,Y.snapshots);if(!q.ok)throw new Error(q.reason)}br(K),wn(d,J),Xa(oe),p=N,_&&await l.discardPrepared?.(_),await nn(Z)}});if(T.ok)return T.published;if(T.stage==="precheck"||T.stage==="build")try{await nn(Z)}catch(_){let Y=await Ir(Me(_));return{requestId:f,kind:g.kind,target:g.target,ok:!1,resultVersion:p,error:{code:Y,message:"Unable to clear an uncommitted transaction journal."}}}if(T.recoveryRequired){let _=await Ir(T.reason);return{requestId:f,kind:g.kind,target:g.target,ok:!1,resultVersion:p,affectedFiles:F,error:{code:_===L.RECOVERY_PERSIST_FAILED?_:L.ROLLBACK_FAILED,message:T.reason}}}return{requestId:f,kind:g.kind,target:g.target,ok:!1,resultVersion:p,affectedFiles:F,error:{code:T.error instanceof en?L.ROUTE_REBUILD_FAILED:ec(T.stage),message:Me(T.error),...T.error instanceof en?{details:{failedRoutes:T.error.failedRoutes}}:{}}}}function Qa(){return[...o.values()].map(f=>({routeId:f.routeId,state:{...f,dependencyFiles:new Set(f.dependencyFiles),fileVersions:new Map(f.fileVersions)}}))}function qa(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 br(f){for(let y of o.values())M(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 Zo(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 Nn(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=Xe(y);return g&&g!==y?f.graph?.elements.has(g)===!0:!1}function ne(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 ec(f){return f==="validate"?L.ROUTE_REBUILD_FAILED:f==="publish"?L.HISTORY_COMMIT_FAILED:L.WRITE_IO_ERROR}async function Ir(f){if(E=!0,!l.markRecoveryRequired)return L.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(f),L.RECOVERY_REQUIRED}catch{return L.RECOVERY_PERSIST_FAILED}}function wp(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 tc(f){return f==="VERSION_STALE"?L.VERSION_STALE:f==="CROSS_PAGE_MOVE_UNSUPPORTED"?L.CROSS_PAGE_MOVE_UNSUPPORTED:L.UNSUPPORTED_OPERATION}async function nc(f){if(f.target.kind==="route"){let g=o.get(f.target.routeId)??null;return g?(g.graph||await Zo(g.routeId),g):ne(f,L.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 Zo(g.routeId),g):ne(f,L.ROUTE_NOT_FOUND,`Route not found: ${f.target.routeId}`)}if(f.target.kind!=="node")return ne(f,L.UNSUPPORTED_OPERATION,`${f.kind} source target execution is not implemented yet.`);if(!f.routeId)return ne(f,L.INVALID_TARGET,"routeId is required when executing a node target");let y=o.get(f.routeId)??null;return y?(y.graph||await Zo(y.routeId),Qo(y,f.target.key)?y:ne(f,L.NODE_NOT_FOUND,`Target key not found: ${f.target.key}`)):ne(f,L.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&&M(g);let I=Rf(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&&(M(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 P=o.get(f)?.graph?.version??1;t="ready",r.emit({type:"graph-ready",routeId:f,version:P})}catch(I){throw t="idle",r.emit({type:"graph-error",routeId:f,message:Me(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 C;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=Nn(f,y),I=Xe(f)??f;if(g?.graph&&g.topology&&g.capabilities&&g.detailProjections){let P=g.detailProjections.get(I);if(P){let F=gl(I,g.graph,g.topology,g.capabilities,P.textSources,P.provenances,P.dynamicData);return f===I?F:oI(F,f,g.document??null,g.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${f}`)},getRenderDetail(f,y){let g=Nn(f,y),I=Xe(f)??f;if(g?.graph&&g.topology&&g.capabilities&&g.detailProjections){let P=g.detailProjections.get(I);if(P){let F=hl(I,g.graph,g.topology,g.capabilities,P.textSources,P.writeTarget,P.provenances,P.conditional,P.componentSemantic,P.contentModel,P.mediaModel,P.styleSource,P.dynamicData);return f===I?F:rI(F,f,g.document??null,g.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${f}`)},getClassNameSource(f,y){let g=Nn(f,y),I=Xe(f)??f;if(!g?.graph)throw new Error(`Key not found: ${f}`);let P=g.graph.elements.get(I);if(!P)throw new Error(`Key not found: ${f}`);let F=d.get(P.sourceFile);if(F===void 0)throw new Error(`Source not loaded: ${P.sourceFile}`);return Ml({key:I,route:{routeId:g.routeId,graph:g.graph,source:F}})},refreshSourceForKey:hp,async execute(f){if(await C,E)return ne(f,L.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(f.kind==="source-edit")return gp(f);if(f.kind==="insert-page-resource")return yp(f);let y=await nc(f);if("ok"in y)return y;await Ha(f);let g=await nc(f);if("ok"in g)return g;let I=g;if(f.target.kind==="page-unit"){let D=f;return f.kind==="insert-child"?xp(D,I):f.kind==="move-node"||f.kind==="remove-node"?Ep(D,I):ne(f,L.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"?L.ROUTE_NOT_FOUND:L.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 P=Jb(I,I.graph,I.capabilities,d,o),F=await new ho(P).plan(f);if(!F.ok)return{requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:p,error:{code:ur(F.errorCode),message:F.reason}};let B=F.plan;if(B.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:L.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};h+=1;try{if(B.steps.some(N=>N.type==="invoke-external-adapter")){let N=await u.execute(B);if(!N.ok)return ne(f,ur(N.errorCode),N.reason);let K={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 Ho(K,{rebuiltRoutes:[],failedRoutes:[]}),K}let D=await u.prepareRewritePlan(B);return D.ok?await Tn({request:f,filePlan:D.filePlan,...D.selectionRef?{selectionRef:D.selectionRef}:{}}):ne(f,ur(D.errorCode),D.reason)}catch(D){return{requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:p,error:{code:L.INTERNAL_ERROR,message:Me(D)}}}finally{h-=1}},async undo(f){if(await C,E)return{requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:p,error:{code:L.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};h+=1;try{return await Za("undo")}finally{h-=1}},async redo(f){if(await C,E)return{requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:p,error:{code:L.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};h+=1;try{return await Za("redo")}finally{h-=1}},notifyFileChanged(f){Ua([f])},subscribe(f){return r.subscribe(f)}}}function Vb(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function Ub(e,t,n){let r=new Map;for(let i of t.elements.values()){if(i.sourceFile!==n.entryFile||!i.importedFrom||!/^[A-Z]/.test(i.tag))continue;let s=n.placements.find(c=>c.members.some(l=>l.sourceRange!==null&&la(i.sourceRange,l.sourceRange)));if(!s)continue;let a=s.placementUnitKey;r.set(`${i.importedFrom}#${i.tag}`,a),i.exportName&&i.exportName!==i.tag&&r.set(`${i.importedFrom}#${i.exportName}`,a)}let o=n.placements.find(i=>i.placementKey===n.container.placementKey&&i.relation==="append");for(let i of e.entries){let s=t.elements.get(i.key);if(!s)continue;if(s.sourceFile===n.entryFile){if(n.container.sourceRange&&la(s.sourceRange,n.container.sourceRange)&&o){i.pageCompositionUnitKey=o.placementUnitKey;continue}let c=n.placements.find(l=>l.members.some(u=>u.sourceRange!==null&&(la(s.sourceRange,u.sourceRange)||Kb(u.sourceRange,s.sourceRange))));if(c){i.pageCompositionUnitKey=c.placementUnitKey;continue}}let a=r.get(`${s.sourceFile}#${s.componentName}`);a&&(i.pageCompositionUnitKey=a)}}function la(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function Kb(e,t){return Af(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&Af(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function Af(e,t,n,r){return e!==n?e-n:t-r}function Jb(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 v=Xe(E)??E,C=t.elements.get(v);return C?l(E,C):null}).filter(E=>E!==null);let h=t.elements.get(d.baseKey);return h?h.childKeys.map(E=>{let v=t.elements.get(E);return v?l(E,v):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 Ff(e.detailProjections?.get(m.baseKey)?.textTargets.get(d)??null,m.repeatIndex)},async getElementPropertyWriteTarget(u,d){let m=c(u);return Ff(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=Sb(u);return d?{baseKey:d.baseKey,repeatIndex:eI(e.document??null,u,d.baseKey,e.documentIndex)??qb(d)}:{baseKey:u,repeatIndex:null}}function l(u,d){let m=Xe(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(v=>({...v}))}:null,resolvedValue:E.resolvedValue}))}}}var Xb={"stale-version":L.VERSION_STALE,"capability-denied":L.CAPABILITY_REJECTED,"invalid-params":L.INVALID_PARAMS,"locator-miss":L.LOCATOR_FAILED,"route-not-found":L.ROUTE_NOT_FOUND,"unsupported-operation":L.UNSUPPORTED_OPERATION,"invalid-target":L.INVALID_TARGET,"ast-error":L.AST_PARSE_ERROR,"writeback-failed":L.WRITE_IO_ERROR,"rollback-failed":L.RECOVERY_REQUIRED,unknown:L.INTERNAL_ERROR};function ur(e){return Xb[e]}function Me(e){return e instanceof Error&&e.message?e.message:String(e)}function Tf(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function zb(e){let t=tn(e);if(!kb.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=>Cb.map(a=>`${s}/${a}`))}function Hb(e){let n=tn(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function Wb(e){return Mf(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function Yb(e){return Mf(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function Mf(e,t){let n=[];for(let r of e.matchAll(t)){let o=_f(r[1]??"");o&&n.push(o)}return n}function Nf(e,t){let n=_f(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?tn(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?tn(`${Gb(e)}/${n}`):n.startsWith("/")?tn(n.slice(1)):ua(n)?tn(n):null}function _f(e){return e.split(/[?#]/,1)[0]?.trim()??""}function ua(e){return/\.css$/i.test(e)}function Gb(e){let t=tn(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function Of(e){return Array.from(new Set(e))}function tn(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 Zb(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 To(e){return e?.map(t=>({...t}))}function Ff(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=To(e.collectionPathMap?.[t])??To(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:To(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>To(o)??[])}}function Qb(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)=>yb(p,h),c=(p,h,E)=>{let v=o.get(p);if(!v)return a(p,E);let C=a(p,E),R={...v,key:C,parentKey:h,childKeys:[]};return i.push(R),R.childKeys=v.childKeys.flatMap(w=>l(w,E,C)),C},l=(p,h,E)=>{if(!r.has(p))return[c(p,E,h)];let v=d(p,h),C=[];for(let R=0;R<v;R+=1)C.push(c(p,E,[...h,R]));return C},u=Of([...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 v of m(p)){let C=n.get(v);if(C){for(let R of[...C.textTargets.values(),...C.elementPropertyTargets.values()])if(!(R?.kind!=="value-binding"||R.sourceKind!=="repeat-template"))for(let w of tI(R))w.length<=h.length||nI(w,h)&&E.add(w[h.length])}}return E.size>0?E.size:Zb(n.get(p))}function m(p){let h=s.get(p);if(h)return h;let E=[p],v=o.get(p);for(let C of v?.childKeys??[])E.push(...m(C));return s.set(p,E),E}}function qb(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function eI(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((Xe(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function tI(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 nI(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 rI(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 oI(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 ha from"node:path";import{TextDecoder as iI}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as Lf,SITE_EDIT_SOURCE_ALLOWED_DIRS as jf,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as Bf,SiteEditSourceFileResponseSchema as da,SiteEditSourceLocationSchema as sI,SiteEditSourcePathSchema as Fo,SiteEditSourceTreeResponseSchema as aI,isSiteEditTextSourcePath as cI}from"@vcp-dev/contracts";var lI=[...Bf,...Lf,...jf],fa=2e3,pa=12,ma=24*1024*1024,Df=512*1024,uI=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),dI={".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"},fI={".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"},pI=new iI("utf-8",{fatal:!0});async function Mo(e,t={}){let{files:n,truncated:r}=await bI(e,t),o=CI(n.map(i=>i.metadata));return aI.parse({nodes:o,defaultPath:vI(n.map(i=>i.metadata)),totalFiles:n.length,...r?{truncated:r}:{}})}async function _o(e,t,n={}){let r=Fo.parse(t.path),o=await gI(e,r,n);if(!o)throw new Error(`Source file not found: ${r}`);if(ga(r)){let s=Uf(r),a=await xI(e,{path:r,sizeBytes:o.sizeBytes,mimeType:s});return da.parse({path:r,kind:"binary",language:null,sizeBytes:o.sizeBytes,mimeType:s,readonly:!0,...a})}let i=await mI(e,r);return i.ok?da.parse({path:r,kind:"text",language:Kf(r),sizeBytes:i.sizeBytes,contentHash:ce(i.content),readonly:!1,content:i.content}):da.parse({path:r,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function mI(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 pI.decode(e)}catch{return null}}async function gI(e,t,n){if(!EI(t,n))return null;let r=await yI(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function yI(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=$f(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(ga(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function xI(e,t){if(!uI.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>Df)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>Df?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function EI(e,t){return Bf.some(n=>n===e)||Lf.some(n=>n===e)||jf.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=Fo.safeParse(n);return r.success&&r.data===e})}function Oo(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return sI.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 $f(e){return Array.isArray(e)?{files:e}:e}function SI(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function bI(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=$f(await e.listFiles({roots:II(t),maxFiles:fa+1,maxDepth:pa,maxTotalBytes:ma+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=Fo.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>pa){o.add("max-depth");continue}if(r.size>=fa){o.add("max-files");break}if(i+a.sizeBytes>ma){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:kI(l,a.sizeBytes)}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:SI([...o]),maxFiles:fa,maxDepth:pa,maxTotalBytes:ma}}:{}}}function II(e){let t=new Set(lI);for(let n of e.routeEntryFiles??[]){let r=Fo.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function kI(e,t){return ga(e)?{path:e,kind:"binary",language:null,sizeBytes:t,mimeType:Uf(e),readonly:!0}:{path:e,kind:"text",language:Kf(e),sizeBytes:t,readonly:!1}}function CI(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 Vf(t)}function Vf(e){return e.map(t=>t.kind==="directory"?{...t,children:Vf(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function vI(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 ga(e){return!cI(e)}function Uf(e){let t=ha.posix.extname(e).toLowerCase();return!t&&ha.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":dI[t]??"application/octet-stream"}function Kf(e){let t=ha.posix.extname(e).toLowerCase();return fI[t]??"plaintext"}var Do=class{constructor(t){this.options=t,this.fileSystem=new Kn(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 Rr(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 Pr(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 _o(this.fileSystem,t,{routeEntryFiles:this.options.routes.map(n=>n.entryFile)})}resolveSourceLocation(t){return Oo(t,this.engine.getRenderDetail(t.key,t.routeId))}async planOperation(t){let n=PI.safeParse(t);if(!n.success)return{result:vr(t,n.error.issues.map(i=>i.message))};let r=new Kn(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:Lt(s)},c=r.getChangedFiles();if(c.length===0)return{result:a};let l=wI.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:c.map(u=>AI(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 dr({projectRoot:"/snapshot",fileSystem:t,routes:this.options.routes.map(o=>({routeId:o.routeId,entryFile:o.entryFile})),onEvent:r&&this.options.onEvent?o=>{let i=wr(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})}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 AI(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:ce(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:ce(e.before)},fullContent:e.after}}function TI(e){return new Do(e)}import{SiteEditOperationRequestSchema as MI}from"@vcp-dev/contracts";import rt from"node:fs/promises";import Ae from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as NI,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as FI}from"@vcp-dev/contracts";var Lo=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=dr({...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 _o(this.fileSystem,t,{routeEntryFiles:this.engine.getRouteEntryFiles()})}resolveSourceLocation(t){return Oo(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(Ae.join(n,r),"utf8")},async readFileBytes(r){return rt.readFile(Ae.join(n,r))},async getFileInfo(r){let o=Ae.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 ko(Ae.join(n,r),o)},async createExclusive(r,o){let i=Ae.join(n,r);await rt.mkdir(Ae.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(Ae.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=Ae.join(n,i),a=Ae.dirname(Ae.join(n,o));for(;a!==s&&a.startsWith(`${s}${Ae.sep}`);){try{await rt.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=Ae.dirname(a);continue}break}a=Ae.dirname(a)}},async exists(r){try{return await rt.access(Ae.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...FI,...NI],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=Ae.join(n,...d.split("/")),E;try{E=await rt.lstat(h)}catch{return}if(E.isSymbolicLink())return;if(E.isFile()){let C=E.ino>0?`${String(E.dev)}:${String(E.ino)}`:null;if(C&&s.has(C))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}C&&s.add(C),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 v=await rt.readdir(h,{withFileTypes:!0});for(let C of v)C.isSymbolicLink()||await u(`${d}/${C.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 ya(e){return new Lo(e)}var jo=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=ya({projectRoot:t.projectRoot,fileSystem:t.fileSystem,routes:t.routes.map(n=>({routeId:n.routeId,entryFile:n.entryFile})),onEvent:n=>{let r=wr(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:Rr(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:Pr(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=MI.safeParse(r);if(!o.success)return vr(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:Lt(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:Lt(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:Lt(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 _I(e){return new jo(e)}import{createHash as OI,randomUUID as Aa}from"node:crypto";import he from"node:fs/promises";import ye from"node:path";var ze=1,Ea=1,DI=2,LI="index.json",jI="recovery.json",BI="transaction-journal.json",$I="document-version.json",$o={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},U={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"},X=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 qf(e,t={}){let n=ek(e),r=rk(t.limits),o=xa(n),i=tk(n),s=await _e(i),a=await _e(o)||s;a||(await zI(n),await HI(n)),a||await ok(n);let c=await Le(n),l=new Set(a?(await Xo(n)).map(d=>d.stageId):[]);a||await fr(n,c.entryIds);let u=async()=>{if(await _e(o)||s)throw new X(U.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")};return{rootDir:n,recoveryRequired:a,async readDocumentVersion(){return Zf(n)},async writeDocumentVersion(d){if(await u(),!Number.isInteger(d)||d<0)throw new X(U.INVALID_SCHEMA,"document version must be a non-negative integer");let m=await Zf(n);await pr(sp(n),{schemaVersion:1,version:Math.max(m,d)})},async stageAppend(d,m={}){await u();let p=await Xf(d,r),h={schemaVersion:Ea,stageId:Aa(),entryId:p.entryId,blobIds:p.blobs.map(E=>E.digest)};try{await zf(n,p),await KI(n,h,m.durableManifest!==!1)}catch(E){try{await Wf(n,h)}catch(v){throw new X(U.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:v})}throw E}return{stageId:h.stageId,entryId:h.entryId,blobIds:h.blobIds}},async discardStage(d){await u(),ka(d);let m=await ba(n,d);m&&await Wf(n,m)},async previewStagedAppend(d,m){return await u(),(await Jf(n,r,d,m)).transition},async previewCursor(d,m){await u();let p=await Le(n);return Ca(p,m),Sa(d,p.entryIds.length),ep(p,p.entryIds,d)},async publishStagedAppend(d,m,p){if(await u(),Vo(d,"entryId"),p){ka(p);let E=await ba(n,p);if(!E||E.entryId!==d)throw new X(U.INVALID_SCHEMA,"history stage does not match the published entry")}let h=await Jf(n,r,d,m);return Gf({rootDir:n,previousDigest:h.current.digest,entryIds:h.entryIds,cursor:h.cursor,afterWrite:async()=>{p?await Uo(n,p):await XI(n,d),await fr(n,h.entryIds)}})},async append(d){await u();let m=await Le(n),p=await Xf(d,r),h=[...m.entryIds];m.cursor<h.length-1&&h.splice(m.cursor+1),h.push(p.entryId);try{await zf(n,p);let E=await tp(n,h,r);return await Na(n,E.entryIds,E.cursor),await fr(n,E.entryIds),Le(n)}catch(E){throw await fr(n,m.entryIds),E}},async readEntry(d){return Vo(d,"entryId"),hr(n,d)},async readBlob(d){Vo(d,"blobId");let m=await Ba(n,d),p=await _t(m,U.NOT_FOUND,"blob");return Fa(p,d,m),p},async readIndex(){return Le(n)},async readStatus(){let d=await Le(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 _e(o)||await _e(i)}},async readUndoRedoIds(){let d=await Le(n);return{undoIds:d.undoIds,redoIds:d.redoIds,currentId:d.currentId}},async setCursor(d,m){await u();let p=await Le(n);return Ca(p,m),Sa(d,p.entryIds.length),Gf({rootDir:n,previousDigest:p.digest,entryIds:p.entryIds,cursor:d})},async markRecoveryRequired(d){await _e(o)||await pr(xa(n),{schemaVersion:ze,reason:nk(d),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await he.rm(xa(n),{force:!0})},async readTransactionJournal(){return await _e(i)?Bo(i):null},async writeTransactionJournal(d){await u(),ap(d);try{await pr(i,d)}catch(p){let h=await Bo(i).catch(()=>null);if(h&&Buffer.from(je(h)).equals(Buffer.from(je(d))))return;throw h?new X(U.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:p}):p}let m=await Bo(i);if(!Buffer.from(je(m)).equals(Buffer.from(je(d))))throw new X(U.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(d){let m=await _e(i)?await Bo(i):null;if(m&&m.transactionId!==d)throw new X(U.INVALID_SCHEMA,"transaction journal changed concurrently");try{await he.rm(i,{force:!0})}catch(p){if(!await _e(i))return;throw p}if(await _e(i))throw new X(U.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await u();for(let m of l)await Uo(n,m),l.delete(m);await WI(n);let d=await Le(n);await fr(n,d.entryIds)}}}async function Jf(e,t,n,r){Vo(n,"entryId");let o=await Le(e);Ca(o,r);let i=await hr(e,n),s=[...o.entryIds];o.cursor<s.length-1&&s.splice(o.cursor+1),s.push(i.id);let a=await tp(e,s,t);return{current:o,entryIds:a.entryIds,cursor:a.cursor,transition:ep(o,a.entryIds,a.cursor)}}function ep(e,t,n){return Sa(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:VI(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function VI(e,t){return Ot(je({schemaVersion:ze,entryIds:e,cursor:t}))}function Sa(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new X(U.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function UI(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 Xf(e,t){if(!e.kind.trim())throw new X(U.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new X(U.INVALID_JSON,"history blob name must not be empty");let l=qI(c.data),u=Ot(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:ze,kind:e.kind,manifest:e.manifest,blobs:r},i=je({...o}),s=Ot(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new X(U.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function zf(e,t){let n=Oa(e,t.entryId),r={id:t.entryId,...t.entryBody},o=[...t.blobs.map(a=>Hf(Da(e,a.digest),a.bytes,{kind:"blob",digest:a.digest},ja(e,a.digest))),Hf(n,je(r),{kind:"entry",digest:t.entryId},La(e,t.entryId))],s=(await Promise.allSettled(o)).find(a=>a.status==="rejected");if(s)throw s.reason}async function Hf(e,t,n,r){let o=await Pa(e)??(r?await Pa(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new X(n.kind==="blob"?U.BLOB_CORRUPT:U.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await op(e,t)}async function tp(e,t,n){let r=[...t],o=r.length-1;for(;;){if((await rp(e,r)).totalBytes<=n.maxSessionBytes&&r.length<=n.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new X(U.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");r.shift(),o-=1}}async function KI(e,t,n){Ta(t);let r=_a(e,t.stageId);if(n){await pr(r,t);return}await QI(r,t)}async function ba(e,t){let n=await Pa(_a(e,t));if(n===null)return null;let r=gr(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=Ta(r);if(o.stageId!==t)throw new X(U.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function Xo(e){let t=[];for(let n of await Jo(Ma(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);ka(r);let o=await ba(e,r);o&&t.push(o)}return t}async function Wf(e,t){Ta(t);let n=await Le(e),r=(await Xo(e)).filter(s=>s.stageId!==t.stageId),o=new Set(n.entryIds),i=new Set;for(let s of n.entryIds){let a=await hr(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 Yf(Oa(e,t.entryId),La(e,t.entryId));for(let s of t.blobIds)i.has(s)||await Yf(Da(e,s),ja(e,s));await Uo(e,t.stageId),await wa(yr(e)),await wa(xr(e))}async function Uo(e,t){await Ia(_a(e,t)),await JI(e)}async function JI(e){try{await he.rmdir(Ma(e))}catch(t){if(Er(t)||ot(t)&&t.code==="ENOTEMPTY")return;throw t}}async function XI(e,t){for(let n of await Xo(e))n.entryId===t&&await Uo(e,n.stageId)}async function Ia(e){if(await he.rm(e,{force:!0}),await _e(e))throw new X(U.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function Yf(e,t){await Ia(e),await Ia(t)}function Ta(e){if(!ot(e)||e.schemaVersion!==Ea||typeof e.stageId!="string"||!np(e.stageId)||!Be(e.entryId))throw new X(U.INVALID_SCHEMA,"history stage schema is invalid");let t=ip(e.blobIds,"history stage blobIds");return{schemaVersion:Ea,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function ka(e){if(!np(e))throw new X(U.INVALID_PATH,"history stageId must be a UUID")}function np(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 fr(e,t){let n=new Set(t),r=new Set;for(let c of t){let l=await hr(e,c);for(let u of l.blobs)r.add(u.digest)}for(let c of await Xo(e)){n.add(c.entryId);for(let l of c.blobIds)r.add(l)}let o=yr(e),i=await Jo(o);for(let c of i){if(!c.endsWith(".json"))continue;let l=Qf(c.slice(0,-5));l&&!n.has(l)&&await Ko(ye.join(o,c))}let s=xr(e),a=await Jo(s);for(let c of a){let l=Qf(c);l&&!r.has(l)&&await Ko(ye.join(s,c))}}async function Le(e){let t=zo(e),n=await _t(t,U.NOT_FOUND,"index"),r=gr(Buffer.from(n).toString("utf8"),"index"),o=YI(r),i=[...o.entryIds],{totalBytes:s}=await rp(e,i),a=i.slice(0,o.cursor+1).reverse(),c=i.slice(o.cursor+1);return{schemaVersion:ze,digest:o.digest,entryIds:i,cursor:o.cursor,currentId:i[o.cursor]??null,undoIds:a,redoIds:c,totalBytes:s}}async function rp(e,t){let n=0,r=new Set,o=zo(e),i=await _t(o,U.NOT_FOUND,"index");n+=i.byteLength;for(let s of t){let a=await hr(e,s),c=await cp(e,s),l=await _t(c,U.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 Ba(e,u.digest),m=await _t(d,U.NOT_FOUND,"blob");Fa(m,u.digest,d),n+=m.byteLength}}return{totalBytes:n}}async function hr(e,t){let n=await cp(e,t),r=await _t(n,U.NOT_FOUND,"entry"),o=gr(Buffer.from(r).toString("utf8"),`entry ${t}`),i=GI(o);if(i.id!==t)throw new X(U.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(Ot(je({schemaVersion:i.schemaVersion,kind:i.kind,manifest:i.manifest,blobs:i.blobs}))!==t)throw new X(U.ENTRY_CORRUPT,`entry hash mismatch for ${t}`);for(let a of i.blobs){let c=await Ba(e,a.digest),l=await _t(c,U.NOT_FOUND,"blob");Fa(l,a.digest,c)}return i}async function Na(e,t,n){let r={schemaVersion:ze,digest:Ot(je({schemaVersion:ze,entryIds:t,cursor:n})),entryIds:t,cursor:n};await pr(zo(e),r)}function Ca(e,t){if(t!==void 0&&e.digest!==t)throw new X(U.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function Gf(e){let t=Ot(je({schemaVersion:ze,entryIds:e.entryIds,cursor:e.cursor}));try{return await Na(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.(),await Le(e.rootDir)}catch(n){let r=await Le(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new X(U.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function zI(e){await he.mkdir(e,{recursive:!0}),await he.mkdir(yr(e),{recursive:!0}),await he.mkdir(xr(e),{recursive:!0}),await he.mkdir(mr(e),{recursive:!0})}async function HI(e){await he.rm(mr(e),{recursive:!0,force:!0}),await he.mkdir(mr(e),{recursive:!0})}async function WI(e){let t=mr(e);await he.mkdir(t,{recursive:!0});for(let n of await Jo(t))n!=="stages"&&await he.rm(ye.join(t,n),{recursive:!0,force:!0})}function YI(e){if(!ot(e))throw new X(U.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==ze)throw new X(U.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=ip(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new X(U.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!Be(o))throw new X(U.INDEX_CORRUPT,"index digest is invalid");let i=Ot(je({schemaVersion:ze,entryIds:t,cursor:r}));if(o!==i)throw new X(U.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:ze,digest:o,entryIds:t,cursor:r}}function GI(e){if(!ot(e))throw new X(U.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==ze)throw new X(U.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!Be(t))throw new X(U.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new X(U.ENTRY_CORRUPT,"entry kind is invalid");let r=Ra(e.manifest,"entry.manifest"),o=ZI(e.blobs);return{id:t,schemaVersion:ze,kind:n,manifest:r,blobs:o}}function ZI(e){if(!Array.isArray(e))throw new X(U.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!ot(t))throw new X(U.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new X(U.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!Be(o))throw new X(U.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new X(U.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function pr(e,t){await op(e,je(t))}async function QI(e,t){let n=ye.dirname(e),r=ye.basename(e),o=ye.join(n,`.${r}.${process.pid}.${Aa()}.tmp`);await he.mkdir(n,{recursive:!0});try{await he.writeFile(o,je(t),{flag:"wx"}),await he.rename(o,e)}finally{await Ko(o)}}async function op(e,t){let n=ye.dirname(e),r=ye.basename(e),o=ye.join(n,`.${r}.${process.pid}.${Aa()}.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 wa(n)}finally{await Ko(o)}}function je(e){return Buffer.from(JSON.stringify(va(e)),"utf8")}function va(e){if(Array.isArray(e))return e.map(t=>va(t));if(ot(e)){let t={};for(let n of Object.keys(e).sort())t[n]=va(e[n]);return t}return e}function gr(e,t){try{return JSON.parse(e)}catch(n){throw new X(U.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function Ra(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=>Ra(n,t));if(ot(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=Ra(o,t);return n}break}throw new X(U.INVALID_JSON,`${t} must be JSON-serializable`)}function ip(e,t){if(!Array.isArray(e))throw new X(U.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!Be(n))throw new X(U.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function Vo(e,t){if(!Be(e))throw new X(U.INVALID_PATH,`${t} must be a sha256 digest`)}function Be(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function Ot(e){return`sha256:${OI("sha256").update(e).digest("hex")}`}function qI(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function _t(e,t,n){try{return await he.readFile(e)}catch(r){throw new X(t,`${n} not found: ${e}`,{cause:r})}}async function Pa(e){try{return await he.readFile(e)}catch(t){if(Er(t))return null;throw t}}function Fa(e,t,n){if(Ot(e)!==t)throw new X(U.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function _e(e){try{return await he.access(e),!0}catch(t){if(Er(t))return!1;throw t}}async function Ko(e){try{await he.rm(e,{force:!0,recursive:!0})}catch{}}async function wa(e){try{let t=await he.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function Jo(e){try{return await he.readdir(e)}catch(t){if(Er(t))return[];throw t}}function ek(e){if(typeof e!="string"||e.trim().length===0)throw new X(U.INVALID_ROOT,"history store rootDir must be a non-empty string");return ye.resolve(e)}function zo(e){return ye.join(e,LI)}function xa(e){return ye.join(e,jI)}function tk(e){return ye.join(e,BI)}function sp(e){return ye.join(e,$I)}async function Zf(e){try{let t=await he.readFile(sp(e),"utf8"),n=gr(t,"document version");if(!ot(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new X(U.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(Er(t))return 0;throw t}}async function Bo(e){let t=await _t(e,U.RECOVERY_PENDING,"transaction journal"),n=gr(Buffer.from(t).toString("utf8"),"transaction journal");return ap(n),n}function ap(e){if(!ot(e)||e.schemaVersion!==DI||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!UI(e.historyTransition)||!Array.isArray(e.files))throw new X(U.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 X(U.INVALID_SCHEMA,"transaction journal file digest is invalid")}function nk(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function yr(e){return ye.join(e,"entries")}function xr(e){return ye.join(e,"blobs")}function mr(e){return ye.join(e,"tmp")}function Ma(e){return ye.join(mr(e),"stages")}function _a(e,t){return ye.join(Ma(e),`${t}.json`)}function Oa(e,t){return ye.join(yr(e),`${up(t)}.json`)}function Da(e,t){return ye.join(xr(e),up(t))}function La(e,t){return ye.join(yr(e),`${t}.json`)}function ja(e,t){return ye.join(xr(e),t)}async function cp(e,t){return lp(Oa(e,t),La(e,t))}async function Ba(e,t){return lp(Da(e,t),ja(e,t))}async function lp(e,t){return await _e(e)?e:await _e(t)?t:e}function up(e){return e.slice(7)}function Qf(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 Er(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function rk(e){return{maxEntries:e?.maxEntries??$o.maxEntries,maxSessionBytes:e?.maxSessionBytes??$o.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??$o.maxEntryBytes}}async function ok(e){let t=zo(e);await _e(t)||await Na(e,[],-1)}export{X as FileHistoryStoreError,jo as PreviewFileSystemSiteEditEngineRuntime,Vd as SITE_EDIT_RAW_COLOR_LITERAL_RE,Do as SnapshotSiteEditEngineRuntime,_I as createPreviewSiteEditEngineRuntime,TI as createSiteEditEngineRuntime,qf as openFileHistoryStore,cr as scanSiteEditThemeStyleViolations};
11
+ `||m==="\r"}if(s)return An(t,`Unterminated block comment in ${t}.`);if(o)return An(t,`Unterminated string literal in ${t}.`);if(c)return An(t,`Unterminated MDX code fence in ${t}.`);let u=r.at(-1);return u?An(t,`Unclosed token "${u.char}" in ${t}.`):{ok:!0}}function An(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function dr(e){let t="idle",n=e.fileSystem??Rb(),r=$d(),o=new Map,i=new Map,s=null,a=new Set,c=null,l=e.history??(e.historyStore?mf(e.historyStore):Pb()),u=Bd(n,{externalAdapters:e.externalAdapters}),d=new Map,m=new Set,p=Math.max(0,e.initialDocumentVersion??0),h=0,E=e.historyStore?.recoveryRequired??!1,v=ia(),C=re();function A(f){return(Ao.isAbsolute(f)?Ao.relative(e.projectRoot,f):f).replace(/\\/g,"/").replace(/^\.\//,"")}function R(f,y){let g=Ao.posix.dirname(f),I=y.replace(/\.(?:tsx?|jsx?)$/i,""),P=Ao.posix.relative(g,I);return P.startsWith(".")?P:`./${P}`}function B(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(bf({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: ${Me(y)}`).catch(()=>{})}}function te(){return t==="disposed"}if(e.onEvent&&r.subscribe(e.onEvent),e.routes)for(let f of e.routes){let y=Rf(f.routeId,f.entryFile);o.set(f.routeId,y),w(y,y.dependencyFiles)}function w(f,y){let g=new Set(y);_(f),f.dependencyFiles=g;for(let I of f.dependencyFiles){let P=i.get(I);P||(P=new Set,i.set(I,P)),P.add(f.routeId)}}function _(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 M(f){let y=new Set;for(let g of f)for(let I of i.get(g)??[])y.add(I);return y}function D(f){for(let y of f)if(!i.has(y))return!1;return!0}async function ee(f,y,g,I,P){let F=new Map,$=Uu(P.values()),L=new Map,N=typeof n.exists=="function"?J=>n.exists(J):async()=>!1;for(let[J,X]of f.elements){let ie=y.nodes.get(J);if(!ie)continue;let Z=g.get(X.sourceFile)??I.get(X.sourceFile),ue=new Map,T=new Map,O=new Map,Y=[];for(let pe of X.textSegments){if(!Z){ue.set(pe.index,null);continue}let Mn=await Ku({file:X.sourceFile,source:Z,segment:pe,readFile:We=>n.readFile(We),exists:N,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:We,adapterId:qo,capabilities:ei})=>({sourceType:We,adapterId:qo,capabilities:ei})),functionCallContracts:e.functionCallContracts,fileCache:$}),Ce=await Cs({file:X.sourceFile,source:Z,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:qo,capabilities:ei})=>({sourceType:We,adapterId:qo,capabilities:ei})),functionCallContracts:e.functionCallContracts,fileCache:$}),on=Db(Mn);ue.set(pe.index,on),T.set(pe.index,Mn),O.set(pe.index,Ce),Y.push({editable:pe.editable,source:on})}let q=new Map;if(Z)for(let pe of X.attributes??[]){let Mn=await Ju({file:X.sourceFile,source:Z,sourceRange:pe.sourceRange,expression:pe.source?.expression??pe.value,sourceInfo:pe.source,readFile:Ce=>n.readFile(Ce),exists:N,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Ce,adapterId:on,capabilities:We})=>({sourceType:Ce,adapterId:on,capabilities:We})),functionCallContracts:e.functionCallContracts,fileCache:$});q.set(pe.name,Mn)}let He=El(Lb(ie.writeTarget),Y),Se=Cl({key:J,element:X,graph:f,provenances:O}),Te=wl(X),kr=Al(X),Cr=Tl(X),rn=Z?await xd({element:X,graph:f,file:X.sourceFile,source:Z,readFile:pe=>n.readFile(pe),exists:N,fileCache:L}):void 0,Dt=f.regions.find(pe=>pe.kind==="conditional-region"&&pe.childKeys.includes(J)),Pe,Fn=Dt?.sourceCandidates?.[0];if(Z&&Dt&&Fn?.kind==="conditional-branch"){let pe=await Cs({file:X.sourceFile,source:Z,target:{kind:"conditional-branch",candidate:Fn},readFile:Ce=>n.readFile(Ce),exists:N,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Ce,adapterId:on,capabilities:We})=>({sourceType:Ce,adapterId:on,capabilities:We})),functionCallContracts:e.functionCallContracts,fileCache:$});Pe={currentBranch:Dt.childKeys.indexOf(J)<=0?"then":"else",availableBranches:Dt.childKeys.length>1?["then","else"]:["then"],conditionExpression:Fn.conditionExpression,provenance:{finalSource:pe.finalSource?{kind:pe.finalSource.kind,file:pe.finalSource.file,displayPath:pe.finalSource.displayPath}:null,chain:pe.chain.map(Ce=>({kind:Ce.kind,file:Ce.file,displayName:Ce.displayName,canEditHere:Ce.canEditHere})),confidence:pe.confidence,editMode:pe.editMode,diagnostics:pe.diagnostics.map(Ce=>({code:Ce.code,message:Ce.message}))}}}F.set(J,{textSources:ue,textTargets:T,elementPropertyTargets:q,provenances:O,writeTarget:He,componentSemantic:Se,contentModel:Te,mediaModel:kr,styleSource:Cr,conditional:Pe,dynamicData:rn})}return F}function G(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 P=g.sourceCache??sa(d,[]),F=await Q(I.entryFile),{graph:$,allSources:L,diagnostics:N,parsedModules:J,entryModule:X}=await hc(I.entryFile,y,Pe=>n.readFile(Pe),typeof n.exists=="function"?Pe=>n.exists(Pe):async()=>!1,{additionalEntries:F,version:I.graph?.version??1});if(N.length>0)throw new lr(N);let ie=new Map;for(let Pe of L.keys())ie.set(Pe,G(Pe));let Z=Math.max(xe(I,ie),g.minimumVersion??0,p);g.changed&&Z<=(I.graph?.version??0)&&(Z=(I.graph?.version??0)+1),$.version=Z;for(let[Pe,Fn]of L)aa(P,Pe,Fn,kf);let ue=await ge(I.entryFile,L,P);$.routeId=f;let T=gc($),O=xc(T,$),Y=await ee($,T,L,P,J),q=fp($,O,Y),He=dp(Y),Se=qb(ml($,T,O,{canUpdateTextByKey:q,dynamicDataSummaryByKey:He}),$,Y),Te=sl({route:f,entryFile:I.entryFile,version:Z,source:y,ast:X?.ast}),kr=al(Te);Te.ok&&Kb(Se,$,Te.projection);let Cr={...Se,...ue?{styleContext:ue}:{},pageComposition:kr},rn=new Set([I.entryFile,...L.keys()]);if(ue){rn.add(ue.entryCss.path);for(let Pe of ue.stylesheets)rn.add(Pe.path)}let Dt={...I,dependencyFiles:rn,graph:$,topology:T,capabilities:O,document:Cr,pageComposition:kr,pageCompositionProjection:Te.projection,pagePlacementByKey:Te.ok?Te.projection.placementByKey:null,pagePlacementUnitByKey:Te.ok?Te.projection.placementUnitByKey:null,pageUnitByKey:Te.ok?Te.projection.unitByKey:null,pagePlacementsByUnitKey:Te.ok?Te.projection.placementsByUnitKey:null,documentIndex:Tb(Cr),detailProjections:Y,fileVersions:ie,styleContext:ue};if(g.publish===!1)return Dt;wn(d,P);for(let Pe of P.keys())m.delete(Pe);return p=Math.max(p,Z),w(I,rn),Object.assign(I,Dt),I}async function Q(f){let y=[];for(let g of Hb(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(ua(N)){I.push(N);continue}for(let X of Yb(J)){let ie=Nf(N,X);ie&&I.push(ie)}}if(!I.length){for(let N of Wb(f))if(await lt(N)){I.push(N);break}}let P=new Map,F=Of(I).slice(0,If);for(;F.length>0&&P.size<If;){let N=F.shift();if(P.has(N)||!ua(N))continue;let J=await xt(N,g);if(J!==null){P.set(N,{path:N,content:J});for(let X of Gb(J)){let ie=Nf(N,X);ie&&!P.has(ie)&&!F.includes(ie)&&F.push(ie)}}}let $=[...P.values()].map(N=>({...N,hash:le(N.content)})),L=$[0];return L?{revision:le(JSON.stringify($.map(({path:N,hash:J})=>({path:N,hash:J})))),entryCss:L,stylesheets:$.slice(1)}:null}async function xt(f,y){let g=y.get(f);if(g!==void 0)return g;if(!await lt(f))return null;let I=await n.readFile(f);return aa(y,f,I,kf),I}async function lt(f){return typeof n.exists=="function"?n.exists(f):!1}function dp(f){let y=new Map;for(let[g,I]of f)I.dynamicData?.bindings.length&&y.set(g,Ad(I.dynamicData.bindings));return y}function fp(f,y,g){let I=new Map;for(let[P,F]of f.elements){if(!y.get(P)?.canUpdateText){I.set(P,!1);continue}let L=g.get(P),N=F.textSegments.some(J=>{if(!J.editable)return!1;let X=L?.provenances.get(J.index)??null;return!X||pp(X)});I.set(P,N)}return I}function pp(f){return f.editMode==="direct"||f.editMode==="proxy"||f.editMode==="upstream"}async function Sr(f,y={}){let g=[...new Set(f)],I=M(g);if(I.size===0||!D(g))for(let L of o.values())Va(L,g)&&I.add(L.routeId);let P=I.size===0&&g.some(Tf),F=y.publish===!1?sa(d,g):void 0,$={rebuiltRoutes:[],failedRoutes:[],...y.publish===!1?{candidateRouteStates:[],candidateSourceCache:F}:{}};for(let L of o.values())if(I.has(L.routeId)||P)try{let J=!!L.graph,X=await n.readFile(L.entryFile),ie=await W(L.routeId,X,{...y,...F?{sourceCache:F}:{}});ie?.graph&&($.rebuiltRoutes.push({documentChanged:J,routeId:L.routeId,version:ie.graph.version}),$.candidateRouteStates?.push({routeId:L.routeId,state:ie}))}catch(J){$.failedRoutes.push(Sf(L.routeId,J))}return $}function $a(f){let y=[...new Set(f)],g=M(y);if(g.size>0&&D(y))return[...g];for(let I of o.values())Va(I,y)&&g.add(I.routeId);return[...g]}function Ho(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 Va(f,y){return y.some(g=>f.dependencyFiles.has(g)||f.entryFile===g||f.graph?.fileIndex.has(g))}function Ua(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 mp();let g=[...a];a.clear();let I=await Ka(g);if(I.length===0)continue;let P=$a(I);for(let L of P)r.emit({type:"graph-invalidated",routeId:L});let{rebuiltRoutes:F,failedRoutes:$}=await Sr(I,{changed:!0});for(let{documentChanged:L,routeId:N,version:J}of F)r.emit({type:"graph-ready",routeId:N,version:J}),L&&r.emit({type:"document-changed",routeId:N,version:J});for(let{routeId:L,message:N}of $)y=!0,r.emit({type:"graph-error",routeId:L,message:N})}}finally{if(c=null,t!=="disposed"){let g=s?o.get(s):null;t=!y&&g?.graph?"ready":"idle"}a.size>0&&Ua([])}})())}async function mp(){for(;h>0;)await new Promise(f=>setTimeout(f,0))}async function Ka(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(P){if(!Ub(P))try{if(await n.exists(g))continue}catch{continue}m.add(g),y.push(g)}}return y}function Ja(f){xf(d,f);for(let y of f)y.exists===!1?m.add(y.file):m.delete(y.file)}function Xa(f){m.clear();for(let y of f)m.add(y)}async function za(f){let y=await Ka(f);if(y.length===0)return;let g=$a(y);for(let F of g)r.emit({type:"graph-invalidated",routeId:F});let{rebuiltRoutes:I,failedRoutes:P}=await Sr(y,{changed:!0});for(let{documentChanged:F,routeId:$,version:L}of I)r.emit({type:"graph-ready",routeId:$,version:L}),F&&r.emit({type:"document-changed",routeId:$,version:L});for(let{routeId:F,message:$}of P)r.emit({type:"graph-error",routeId:F,message:$})}async function hp(f,y){let g=Nn(f,y);if(!g?.graph)return;let I=Xe(f)??f,P=g.graph.elements.get(I);P&&await za([P.sourceFile])}async function Ha(f){let y=new Set;if(f.target.kind==="node"){let g=Nn(f.target.key,f.routeId),I=Xe(f.target.key)??f.target.key,P=g?.graph?.elements.get(I);P&&y.add(P.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 gp(f){if(f.params.kind!=="source-edit")return Wo(f,"invalid-params","source-edit requires source-edit params");for(let y of f.params.edits){let g=Vb(y);if(!g.ok)return Wo(f,g.errorCode,g.message,g.details)}h+=1;try{let y=await bp(f.params.edits);if(!y.ok)return Wo(f,y.errorCode,y.message,y.details);await Ha(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 Tn({request:f,filePlan:g})}catch(y){return{requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:p,error:{code:j.INTERNAL_ERROR,message:Me(y)}}}finally{h-=1}}async function yp(f){if(f.target.kind!=="project"||f.params.kind!=="insert-page-resource")return ne(f,j.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");h+=1;try{let y=await ra({files:[...f.params.artifact.components.flatMap(I=>I.materialization.files.map(P=>({path:P.pathTemplate,content:P.content}))),...f.params.artifact.pages.flatMap(I=>I.materialization.files.map(P=>({path:P.pathTemplate,content:P.content})))],exists:I=>n.exists(I),readFile:I=>n.readFile(I)});if(!y.ok)return ne(f,j.MATERIALIZATION_REJECTED,y.message);let g=await ta({artifact:f.params.artifact,exists:I=>n.exists(I)});return g.ok?await Tn({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}}):ne(f,g.code==="MATERIALIZATION_CONFLICT"?j.MATERIALIZATION_CONFLICT:j.MATERIALIZATION_REJECTED,g.message,g.path?{path:g.path}:void 0)}catch(y){return ne(f,j.INTERNAL_ERROR,Me(y))}finally{h-=1}}async function xp(f,y){if(f.kind!=="insert-child"||f.params.kind!=="insert-child")return ne(f,j.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 ne(f,j.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(f.params.position.documentVersion!==f.documentVersion)return ne(f,j.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 ne(f,j.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(f.documentVersion!==g.version||I.documentVersion!==g.version)return ne(f,j.VERSION_STALE,`Document version ${f.documentVersion} is stale (current: ${g.version}).`);let P=f.params.node.kind==="component-call"?f.params.node.materialization:void 0;if(!P)return ne(f,j.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let F=f.params.position,$=await ra({files:P.files.map(N=>({path:N.pathTemplate,content:N.content})),exists:N=>n.exists(N),readFile:N=>n.readFile(N)});if(!$.ok)return ne(f,j.MATERIALIZATION_REJECTED,$.message);let L=await Yd({manifest:P,generatedRoot:"components/site/generated",controlledFiles:P.files.map(N=>({pathTemplate:N.pathTemplate})),exists:N=>n.exists(N),commit:async N=>{let J=await n.readFile(y.entryFile),X=y.document,ie=y.pageCompositionProjection;if(!X||X.pageComposition?.status!=="supported"||X.version!==f.documentVersion||!ie||ie.status!=="supported"||ie.documentVersion!==X.version)return{ok:!0,data:ne(f,j.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let Z=N.entry.path,ue=wp(N.instanceName),T=Mi({routeId:y.routeId,entryFile:y.entryFile,currentDocumentVersion:X.version,expectedDocumentVersion:f.documentVersion,source:J,projection:ie,placementKey:F.placementKey,component:{source:Z,exportName:N.entry.export.kind==="default"?"default":N.entry.export.name,localName:ue}});if(!T.ok)return{ok:!0,data:ne(f,tc(T.error.code),T.error.message,{diagnostics:T.error.diagnostics})};let O=T.plan.returnStep?tl({source:J,jsx:T.plan.returnStep.node.jsx,placement:T.plan.returnStep.placement,...T.plan.returnStep.replaceOriginal?{replaceOriginal:!0}:{}}):T.plan.insertStep?.parentLocator?hn({source:J,locator:T.plan.insertStep.parentLocator,node:T.plan.insertStep.node,placement:T.plan.insertStep.placement,...T.plan.insertStep.anchorLocator?{anchorLocator:T.plan.insertStep.anchorLocator}:{}}):{ok:!1,source:J,diagnostic:{code:"unsupported-syntax",message:"Route composition rewrite has no insertion step."}};if(!O.ok)return{ok:!0,data:ne(f,j.AST_PARSE_ERROR,O.diagnostic.message)};let Y=xn({source:O.source,moduleSpecifier:T.plan.importStep.moduleSpecifier,imports:T.plan.importStep.imports});if(!Y.ok)return{ok:!0,data:ne(f,j.AST_PARSE_ERROR,Y.diagnostic.message)};let q=N.files.map(Se=>({operation:"create-only",file:Se.path,content:Se.content})),He=[{operation:"upsert",file:y.entryFile,content:Y.source,baseContentHash:le(J)},...q];h+=1;try{let Se=await Tn({request:f,filePlan:{operationId:f.id,kind:"source-edit",target:{kind:"source-file",path:y.entryFile},documentVersion:f.documentVersion,conflictPolicy:"compare-and-swap",edits:He}});return!Se.ok&&Se.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:Se.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:Se}}finally{h-=1}}});return L.ok?L.data:ne(f,j.VERSION_STALE,L.error.message,{materializationCode:L.error.code})}async function Ep(f,y){if(f.kind!=="move-node"&&f.kind!=="remove-node")return ne(f,j.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 ne(f,j.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(f.documentVersion!==g.version||I.documentVersion!==g.version)return ne(f,j.VERSION_STALE,`Document version ${f.documentVersion} is stale (current: ${g.version}).`);let P=await n.readFile(y.entryFile),F=nl({routeId:y.routeId,entryFile:y.entryFile,currentDocumentVersion:g.version,expectedDocumentVersion:f.documentVersion,source:P,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 ne(f,tc(F.error.code),F.error.message,{diagnostics:F.error.diagnostics});let $=F.plan.rewriteStep.kind==="move-node"?yn({source:P,locator:F.plan.rewriteStep.locator,targetParentLocator:F.plan.rewriteStep.targetParentLocator,placement:F.plan.rewriteStep.placement,...F.plan.rewriteStep.anchorLocator?{anchorLocator:F.plan.rewriteStep.anchorLocator}:{}}):pn({source:P,locator:F.plan.rewriteStep.locator});if(!$.ok)return ne(f,j.AST_PARSE_ERROR,$.diagnostic.message);let L=$.source,N=[];if(f.kind==="remove-node"){let X=await Sp({routeState:y,placementUnitKey:f.target.placementUnitKey,source:P,mutatedSource:L});L=X.source,N=await Promise.all(X.files.map(async ie=>({operation:"delete",file:ie,baseContentHash:le(await n.readFile(ie))})))}let J=[{operation:"upsert",file:y.entryFile,content:L,baseContentHash:le(P)},...N];h+=1;try{return await Tn({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 Sp(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 $=[...g.elements.values()].find(q=>q.sourceFile===f.routeState.entryFile&&q.importedFrom&&B(q.sourceRange,F));if(!$?.importedFrom||!$.exportName)return y;let L=A($.importedFrom),N="components/site/generated/";if(!L.startsWith(N))return y;let J=L.slice(N.length).split("/")[0];if(!J||!/-[0-9a-f]{8}$/i.test(J))return y;let X=`${N}${J}`;if([...g.elements.values()].filter(q=>q.sourceFile===f.routeState.entryFile&&A(q.importedFrom??"")===L).length!==1)return y;let Z=await n.listFiles({maxFiles:5e3,maxDepth:32}),ue=Array.isArray(Z)?Z:Z.files;if(!Array.isArray(Z)&&Z.truncated)return y;let T=ue.map(({path:q})=>q).filter(q=>q===X||q.startsWith(`${X}/`));if(T.length===0||!T.includes(L))return y;for(let{path:q}of ue)if(!(q===f.routeState.entryFile||q===X||q.startsWith(`${X}/`)))try{if((await n.readFile(q)).includes(J))return y}catch{return y}let O=R(f.routeState.entryFile,L),Y=En({source:f.mutatedSource,moduleSpecifier:O,imports:$.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:$.exportName}]});return Y.ok?{source:Y.source,files:T.sort((q,He)=>q.localeCompare(He))}:y}async function bp(f){if(n.getFileInfo){for(let P of f)if(await n.exists(P.path)&&await n.getFileInfo(P.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${P.path}`,details:{path:P.path}}}let y=Ip(f);if(y.length===0)return{ok:!0};let g=jb(n,f),I=dr({projectRoot:e.projectRoot,fileSystem:g,routes:[...o.values()].map(P=>({routeId:P.routeId,entryFile:P.entryFile})),externalAdapters:e.externalAdapters,externalSourceResolvers:e.externalSourceResolvers,functionCallContracts:e.functionCallContracts,dev:e.dev});try{for(let P of y)await I.setActiveRoute(P)}catch(P){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${Me(P)}`,details:{routeIds:y}}}finally{I.dispose()}return{ok:!0}}function Ip(f){return f.map(g=>g.path).some(Tf)?[...o.keys()]:[]}function Wo(f,y,g,I){let P=ur(y);return{requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:p,error:{code:P,message:g,...I?{details:I}:{}}}}async function Yo(f){let y=[];for(let g of new Set(f))y.push(await kp(g));return y}async function kp(f){if(!(typeof n.exists=="function"?await n.exists(f):!0))return{file:f,content:"",version:Math.max(0,G(f)),exists:!1};let g=await n.readFile(f);return{file:f,content:g,version:Math.max(1,G(f)),exists:!0,sha256:le(g)}}async function Wa(f,y,g,I){if(!e.historyStore)return null;let P=I.historyTransition;if(!P)throw new Error("Durable history did not provide an exact index transition.");let F=new Map(y.map(N=>[N.file,N])),$=new Map(g.map(N=>[N.file,N])),L=[...new Set([...F.keys(),...$.keys()])].sort().map(N=>{let J=F.get(N),X=$.get(N);return{path:N,preDigest:J?.exists===!1||!J?null:le(J.content),postDigest:X?.exists===!1||!X?null:le(X.content)}});return{schemaVersion:2,transactionId:`${f}:${P.expectedIndexDigest}`,operationId:f,phase:"prepared",historyTransition:P,files:L}}async function Ya(f){return!f||!e.historyStore||await e.historyStore.writeTransactionJournal(f),f}async function nn(f){f&&e.historyStore&&await e.historyStore.clearTransactionJournal(f.transactionId)}async function Go(f,y){let g=[];try{for(let I of f)await Ga(I),typeof n.bumpVersion=="function"&&n.bumpVersion(I.file),g.push(I.file)}catch(I){let P=await Cp(y.filter(F=>g.includes(F.file)));return P.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${Me(I)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${P.failedFiles.join(", ")}: ${Me(I)}`,rolledBack:!1}}return{ok:!0,snapshots:f.map(vp)}}async function Ga(f){if(f.exists===!1){await n.deleteFile(f.file);return}await n.writeFile(f.file,f.content)}async function Cp(f){let y=[];for(let g of f)try{await Ga(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 vp(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 Tn(f){return v.runExclusive(()=>Rp(f))}async function Rp(f){let y=f.filePlan.edits.map(T=>T.file),g=await Yo(y),I=new Map(g.filter(T=>T.exists!==!1).map(T=>[T.file,T.content])),P=p,F=Qa(),$=new Map(d),L=new Set(m),N=f.filePlan.edits.map(T=>T.operation==="delete"?{file:T.file,content:"",version:0,exists:!1}:{file:T.file,content:T.content,version:0,exists:!0,sha256:le(T.content)}),J={operationId:f.filePlan.operationId,intents:f.filePlan.edits.map(T=>T.operation==="delete"?{kind:"delete",path:T.file}:{kind:T.operation==="create-only"?"create-only":"upsert",path:T.file,content:T.content})},X=null,ie=!1,Z=await wo({overlay:I,exists:T=>n.exists(T),plan:J,buildCandidate:async({plan:T})=>({plan:T}),prepareHistory:async()=>{let T=await l.prepareAppend({operationId:f.request.id,kind:f.request.kind,target:f.request.target,preSnapshots:g,postSnapshots:N,...f.selectionRef?{selectionRef:f.selectionRef}:{},...f.output?{output:f.output}:{}});return X=await Wa(f.request.id,g,N,T),X=await Ya(X),T},reverify:async()=>{},writeCandidate:async()=>{let T=await u.executeFilePlan(f.filePlan);if(!T.ok)throw new No(T);return{postSnapshots:await Yo(T.affectedFiles),affectedFiles:T.affectedFiles,internalResultVersion:T.resultVersion}},validateCandidate:async({candidate:T,receipt:O})=>{let Y=await Sr(O.affectedFiles,{changed:!0,minimumVersion:O.internalResultVersion,publish:!1});if(Y.failedRoutes.length>0)throw new en(Y.failedRoutes);let q=qa(F,Y.candidateRouteStates??[]),He=Math.max(O.internalResultVersion,...Y.rebuiltRoutes.map(Se=>Se.version));return{...T,rebuild:Y,routeSnapshots:q,resultVersion:He,...Pf(f.selectionRef,q.map(Se=>Se.state.document))?{selectionRef:Pf(f.selectionRef,q.map(Se=>Se.state.document))}:{}}},publishCandidate:async({candidate:T,history:O,receipt:Y})=>{if(!O)throw new Error("history intent is missing");await l.publishPrepared(O),ie=!0;let q=T.resultVersion??Y.internalResultVersion;return{requestId:f.request.id,kind:f.request.kind,target:f.request.target,ok:!0,resultVersion:q,affectedFiles:Y.affectedFiles,...f.output?{output:f.output}:{},...T.selectionRef?{selectionRef:T.selectionRef}:{}}},swapCandidate:({candidate:T,receipt:O})=>{T.routeSnapshots&&br(T.routeSnapshots),T.rebuild?.candidateSourceCache&&wn(d,T.rebuild.candidateSourceCache),Ja(O.postSnapshots),p=Math.max(p,T.resultVersion??P)},finalizeCandidate:async()=>{await nn(X)},emitCommitted:({candidate:T,published:O})=>{Ho(O,T.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:T,receipt:O})=>{if(ie)throw new Error("history was published before transaction finalization failed");if(O){let Y=await Go(g,O.postSnapshots);if(!Y.ok)throw new Error(Y.reason)}br(F),wn(d,$),Xa(L),p=P,T&&await l.discardPrepared?.(T),await nn(X)}});if(Z.ok)return Z.published;if(Z.stage==="precheck"||Z.stage==="build")try{await nn(X)}catch(T){let O=await Ir(Me(T));return ne(f.request,O,"Unable to clear an uncommitted transaction journal.")}if(Z.recoveryRequired){let T=await Ir(Z.reason);return ne(f.request,T===j.RECOVERY_PERSIST_FAILED?T:j.ROLLBACK_FAILED,Z.reason)}let ue=Z.error;return ue instanceof No?{...ne(f.request,ur(ue.result.errorCode),ue.result.reason),...ue.result.affectedFiles?{affectedFiles:ue.result.affectedFiles}:{}}:ue instanceof en?ne(f.request,j.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${ca(ue.failedRoutes)}`,{failedRoutes:ue.failedRoutes}):ne(f.request,ec(Z.stage),Me(ue))}async function Za(f){return v.runExclusive(async()=>{let y=f==="undo"?await l.prepareUndo():await l.prepareRedo();return y?Pp(f,y):{requestId:f,kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:p,error:{code:j.INTERNAL_ERROR,message:f==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function Pp(f,y){let g=y.entry,I=f==="undo"?g.preSnapshots:g.postSnapshots,P=f==="undo"?g.postSnapshots:g.preSnapshots,F=I.map(O=>O.file),$=await Yo(F),L=new Map($.filter(O=>O.exists!==!1).map(O=>[O.file,O.content])),N=p,J=Qa(),X=new Map(d),ie=new Set(m),Z=null,ue=!1,T=await wo({overlay:L,plan:{operationId:`${f}:${g.operationId}`,intents:I.map(O=>O.exists===!1?{kind:"delete",path:O.file}:{kind:"upsert",path:O.file,content:O.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(Z=await Wa(`${f}:${g.operationId}`,$,I,y),Z=await Ya(Z),y),reverify:async()=>{},writeCandidate:async()=>{let O=await Go(I,P);if(!O.ok)throw new Error(O.reason);return{snapshots:O.snapshots}},validateCandidate:async({candidate:O})=>{let Y=await Sr(F,{changed:!0,minimumVersion:p+1,publish:!1});if(Y.failedRoutes.length>0)throw new en(Y.failedRoutes);let q=qa(J,Y.candidateRouteStates??[]),He=Math.max(p+1,...Y.rebuiltRoutes.map(Se=>Se.version));return{...O,rebuild:Y,routeSnapshots:q,resultVersion:He}},publishCandidate:async({candidate:O,history:Y})=>{if(!Y)throw new Error("history cursor intent is missing");await l.publishPrepared(Y),ue=!0;let q=O.resultVersion??p+1;return{requestId:f,kind:g.kind,target:g.target,ok:!0,resultVersion:q,affectedFiles:F,...g.output?{output:g.output}:{}}},swapCandidate:({candidate:O,receipt:Y})=>{O.routeSnapshots&&br(O.routeSnapshots),O.rebuild?.candidateSourceCache&&wn(d,O.rebuild.candidateSourceCache),Ja(Y.snapshots),p=Math.max(p,O.resultVersion??N)},finalizeCandidate:async()=>{await nn(Z)},emitCommitted:({candidate:O,published:Y})=>Ho(Y,O.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:O,receipt:Y})=>{if(ue)throw new Error("history cursor was published before transaction finalization failed");if(Y){let q=await Go(P,Y.snapshots);if(!q.ok)throw new Error(q.reason)}br(J),wn(d,X),Xa(ie),p=N,O&&await l.discardPrepared?.(O),await nn(Z)}});if(T.ok)return T.published;if(T.stage==="precheck"||T.stage==="build")try{await nn(Z)}catch(O){let Y=await Ir(Me(O));return{requestId:f,kind:g.kind,target:g.target,ok:!1,resultVersion:p,error:{code:Y,message:"Unable to clear an uncommitted transaction journal."}}}if(T.recoveryRequired){let O=await Ir(T.reason);return{requestId:f,kind:g.kind,target:g.target,ok:!1,resultVersion:p,affectedFiles:F,error:{code:O===j.RECOVERY_PERSIST_FAILED?O:j.ROLLBACK_FAILED,message:T.reason}}}return{requestId:f,kind:g.kind,target:g.target,ok:!1,resultVersion:p,affectedFiles:F,error:{code:T.error instanceof en?j.ROUTE_REBUILD_FAILED:ec(T.stage),message:Me(T.error),...T.error instanceof en?{details:{failedRoutes:T.error.failedRoutes}}:{}}}}function Qa(){return[...o.values()].map(f=>({routeId:f.routeId,state:{...f,dependencyFiles:new Set(f.dependencyFiles),fileVersions:new Map(f.fileVersions)}}))}function qa(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 br(f){for(let y of o.values())_(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),w(g,g.dependencyFiles)}}async function Zo(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 Nn(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=Xe(y);return g&&g!==y?f.graph?.elements.has(g)===!0:!1}function ne(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 ec(f){return f==="validate"?j.ROUTE_REBUILD_FAILED:f==="publish"?j.HISTORY_COMMIT_FAILED:j.WRITE_IO_ERROR}async function Ir(f){if(E=!0,!l.markRecoveryRequired)return j.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(f),j.RECOVERY_REQUIRED}catch{return j.RECOVERY_PERSIST_FAILED}}function wp(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 tc(f){return f==="VERSION_STALE"?j.VERSION_STALE:f==="CROSS_PAGE_MOVE_UNSUPPORTED"?j.CROSS_PAGE_MOVE_UNSUPPORTED:j.UNSUPPORTED_OPERATION}async function nc(f){if(f.target.kind==="route"){let g=o.get(f.target.routeId)??null;return g?(g.graph||await Zo(g.routeId),g):ne(f,j.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 Zo(g.routeId),g):ne(f,j.ROUTE_NOT_FOUND,`Route not found: ${f.target.routeId}`)}if(f.target.kind!=="node")return ne(f,j.UNSUPPORTED_OPERATION,`${f.kind} source target execution is not implemented yet.`);if(!f.routeId)return ne(f,j.INVALID_TARGET,"routeId is required when executing a node target");let y=o.get(f.routeId)??null;return y?(y.graph||await Zo(y.routeId),Qo(y,f.target.key)?y:ne(f,j.NODE_NOT_FOUND,`Target key not found: ${f.target.key}`)):ne(f,j.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&&_(g);let I=Rf(f,y);o.set(f,I),w(I,I.dependencyFiles),r.emit({type:"graph-invalidated",routeId:f})},unregisterRoute(f){let y=o.get(f);y&&(_(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 P=o.get(f)?.graph?.version??1;t="ready",r.emit({type:"graph-ready",routeId:f,version:P})}catch(I){throw t="idle",r.emit({type:"graph-error",routeId:f,message:Me(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 C;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=Nn(f,y),I=Xe(f)??f;if(g?.graph&&g.topology&&g.capabilities&&g.detailProjections){let P=g.detailProjections.get(I);if(P){let F=gl(I,g.graph,g.topology,g.capabilities,P.textSources,P.provenances,P.dynamicData);return f===I?F:iI(F,f,g.document??null,g.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${f}`)},getRenderDetail(f,y){let g=Nn(f,y),I=Xe(f)??f;if(g?.graph&&g.topology&&g.capabilities&&g.detailProjections){let P=g.detailProjections.get(I);if(P){let F=hl(I,g.graph,g.topology,g.capabilities,P.textSources,P.writeTarget,P.provenances,P.conditional,P.componentSemantic,P.contentModel,P.mediaModel,P.styleSource,P.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=Nn(f,y),I=Xe(f)??f;if(!g?.graph)throw new Error(`Key not found: ${f}`);let P=g.graph.elements.get(I);if(!P)throw new Error(`Key not found: ${f}`);let F=d.get(P.sourceFile);if(F===void 0)throw new Error(`Source not loaded: ${P.sourceFile}`);return Ml({key:I,route:{routeId:g.routeId,graph:g.graph,source:F}})},refreshSourceForKey:hp,async execute(f){if(await C,E)return ne(f,j.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(f.kind==="source-edit")return gp(f);if(f.kind==="insert-page-resource")return yp(f);let y=await nc(f);if("ok"in y)return y;await Ha(f);let g=await nc(f);if("ok"in g)return g;let I=g;if(f.target.kind==="page-unit"){let L=f;return f.kind==="insert-child"?xp(L,I):f.kind==="move-node"||f.kind==="remove-node"?Ep(L,I):ne(f,j.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"?j.ROUTE_NOT_FOUND:j.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 P=Xb(I,I.graph,I.capabilities,d,o),F=await new ho(P).plan(f);if(!F.ok)return{requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:p,error:{code:ur(F.errorCode),message:F.reason}};let $=F.plan;if($.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:j.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};h+=1;try{if($.steps.some(N=>N.type==="invoke-external-adapter")){let N=await u.execute($);if(!N.ok)return ne(f,ur(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 Ho(J,{rebuiltRoutes:[],failedRoutes:[]}),J}let L=await u.prepareRewritePlan($);return L.ok?await Tn({request:f,filePlan:L.filePlan,...L.selectionRef?{selectionRef:L.selectionRef}:{}}):ne(f,ur(L.errorCode),L.reason)}catch(L){return{requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:p,error:{code:j.INTERNAL_ERROR,message:Me(L)}}}finally{h-=1}},async undo(f){if(await C,E)return{requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:p,error:{code:j.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};h+=1;try{return await Za("undo")}finally{h-=1}},async redo(f){if(await C,E)return{requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:p,error:{code:j.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};h+=1;try{return await Za("redo")}finally{h-=1}},notifyFileChanged(f){Ua([f])},subscribe(f){return r.subscribe(f)}}}function Ub(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function Kb(e,t,n){let r=new Map;for(let i of t.elements.values()){if(i.sourceFile!==n.entryFile||!i.importedFrom||!/^[A-Z]/.test(i.tag))continue;let s=n.placements.find(c=>c.members.some(l=>l.sourceRange!==null&&la(i.sourceRange,l.sourceRange)));if(!s)continue;let a=s.placementUnitKey;r.set(`${i.importedFrom}#${i.tag}`,a),i.exportName&&i.exportName!==i.tag&&r.set(`${i.importedFrom}#${i.exportName}`,a)}let o=n.placements.find(i=>i.placementKey===n.container.placementKey&&i.relation==="append");for(let i of e.entries){let s=t.elements.get(i.key);if(!s)continue;if(s.sourceFile===n.entryFile){if(n.container.sourceRange&&la(s.sourceRange,n.container.sourceRange)&&o){i.pageCompositionUnitKey=o.placementUnitKey;continue}let c=n.placements.find(l=>l.members.some(u=>u.sourceRange!==null&&(la(s.sourceRange,u.sourceRange)||Jb(u.sourceRange,s.sourceRange))));if(c){i.pageCompositionUnitKey=c.placementUnitKey;continue}}let a=r.get(`${s.sourceFile}#${s.componentName}`);a&&(i.pageCompositionUnitKey=a)}}function la(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function Jb(e,t){return Af(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&Af(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function Af(e,t,n,r){return e!==n?e-n:t-r}function Xb(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 v=Xe(E)??E,C=t.elements.get(v);return C?l(E,C):null}).filter(E=>E!==null);let h=t.elements.get(d.baseKey);return h?h.childKeys.map(E=>{let v=t.elements.get(E);return v?l(E,v):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 Ff(e.detailProjections?.get(m.baseKey)?.textTargets.get(d)??null,m.repeatIndex)},async getElementPropertyWriteTarget(u,d){let m=c(u);return Ff(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=bb(u);return d?{baseKey:d.baseKey,repeatIndex:tI(e.document??null,u,d.baseKey,e.documentIndex)??eI(d)}:{baseKey:u,repeatIndex:null}}function l(u,d){let m=Xe(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(v=>({...v}))}:null,resolvedValue:E.resolvedValue}))}}}var zb={"stale-version":j.VERSION_STALE,"capability-denied":j.CAPABILITY_REJECTED,"invalid-params":j.INVALID_PARAMS,"locator-miss":j.LOCATOR_FAILED,"route-not-found":j.ROUTE_NOT_FOUND,"unsupported-operation":j.UNSUPPORTED_OPERATION,"invalid-target":j.INVALID_TARGET,"ast-error":j.AST_PARSE_ERROR,"writeback-failed":j.WRITE_IO_ERROR,"rollback-failed":j.RECOVERY_REQUIRED,unknown:j.INTERNAL_ERROR};function ur(e){return zb[e]}function Me(e){return e instanceof Error&&e.message?e.message:String(e)}function Tf(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function Hb(e){let t=tn(e);if(!Cb.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=>vb.map(a=>`${s}/${a}`))}function Wb(e){let n=tn(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function Yb(e){return Mf(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function Gb(e){return Mf(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function Mf(e,t){let n=[];for(let r of e.matchAll(t)){let o=_f(r[1]??"");o&&n.push(o)}return n}function Nf(e,t){let n=_f(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?tn(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?tn(`${Zb(e)}/${n}`):n.startsWith("/")?tn(n.slice(1)):ua(n)?tn(n):null}function _f(e){return e.split(/[?#]/,1)[0]?.trim()??""}function ua(e){return/\.css$/i.test(e)}function Zb(e){let t=tn(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function Of(e){return Array.from(new Set(e))}function tn(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 Qb(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 To(e){return e?.map(t=>({...t}))}function Ff(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=To(e.collectionPathMap?.[t])??To(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:To(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>To(o)??[])}}function qb(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)=>xb(p,h),c=(p,h,E)=>{let v=o.get(p);if(!v)return a(p,E);let C=a(p,E),A={...v,key:C,parentKey:h,childKeys:[]};return i.push(A),A.childKeys=v.childKeys.flatMap(R=>l(R,E,C)),C},l=(p,h,E)=>{if(!r.has(p))return[c(p,E,h)];let v=d(p,h),C=[];for(let A=0;A<v;A+=1)C.push(c(p,E,[...h,A]));return C},u=Of([...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 v of m(p)){let C=n.get(v);if(C){for(let A of[...C.textTargets.values(),...C.elementPropertyTargets.values()])if(!(A?.kind!=="value-binding"||A.sourceKind!=="repeat-template"))for(let R of nI(A))R.length<=h.length||rI(R,h)&&E.add(R[h.length])}}return E.size>0?E.size:Qb(n.get(p))}function m(p){let h=s.get(p);if(h)return h;let E=[p],v=o.get(p);for(let C of v?.childKeys??[])E.push(...m(C));return s.set(p,E),E}}function eI(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function tI(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((Xe(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function nI(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 rI(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 iI(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 ha from"node:path";import{TextDecoder as sI}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as Lf,SITE_EDIT_SOURCE_ALLOWED_DIRS as jf,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as Bf,SiteEditSourceFileResponseSchema as da,SiteEditSourceLocationSchema as aI,SiteEditSourcePathSchema as Fo,SiteEditSourceTreeResponseSchema as cI,isSiteEditTextSourcePath as lI}from"@vcp-dev/contracts";var uI=[...Bf,...Lf,...jf],fa=2e3,pa=12,ma=24*1024*1024,Df=512*1024,dI=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),fI={".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"},pI={".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"},mI=new sI("utf-8",{fatal:!0});async function Mo(e,t={}){let{files:n,truncated:r}=await II(e,t),o=vI(n.map(i=>i.metadata));return cI.parse({nodes:o,defaultPath:RI(n.map(i=>i.metadata)),totalFiles:n.length,...r?{truncated:r}:{}})}async function _o(e,t,n={}){let r=Fo.parse(t.path),o=await yI(e,r,n);if(!o)throw new Error(`Source file not found: ${r}`);if(ga(r)){let s=Uf(r),a=await EI(e,{path:r,sizeBytes:o.sizeBytes,mimeType:s});return da.parse({path:r,kind:"binary",language:null,sizeBytes:o.sizeBytes,mimeType:s,readonly:!0,...a})}let i=await hI(e,r);return i.ok?da.parse({path:r,kind:"text",language:Kf(r),sizeBytes:i.sizeBytes,contentHash:le(i.content),readonly:!1,content:i.content}):da.parse({path:r,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function hI(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=gI(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 gI(e){if(e.includes(0))return null;try{return mI.decode(e)}catch{return null}}async function yI(e,t,n){if(!SI(t,n))return null;let r=await xI(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function xI(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=$f(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(ga(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function EI(e,t){if(!dI.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>Df)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>Df?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function SI(e,t){return Bf.some(n=>n===e)||Lf.some(n=>n===e)||jf.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=Fo.safeParse(n);return r.success&&r.data===e})}function Oo(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return aI.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 $f(e){return Array.isArray(e)?{files:e}:e}function bI(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function II(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=$f(await e.listFiles({roots:kI(t),maxFiles:fa+1,maxDepth:pa,maxTotalBytes:ma+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=Fo.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>pa){o.add("max-depth");continue}if(r.size>=fa){o.add("max-files");break}if(i+a.sizeBytes>ma){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:CI(l,a.sizeBytes)}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:bI([...o]),maxFiles:fa,maxDepth:pa,maxTotalBytes:ma}}:{}}}function kI(e){let t=new Set(uI);for(let n of e.routeEntryFiles??[]){let r=Fo.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function CI(e,t){return ga(e)?{path:e,kind:"binary",language:null,sizeBytes:t,mimeType:Uf(e),readonly:!0}:{path:e,kind:"text",language:Kf(e),sizeBytes:t,readonly:!1}}function vI(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 Vf(t)}function Vf(e){return e.map(t=>t.kind==="directory"?{...t,children:Vf(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function RI(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 ga(e){return!lI(e)}function Uf(e){let t=ha.posix.extname(e).toLowerCase();return!t&&ha.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":fI[t]??"application/octet-stream"}function Kf(e){let t=ha.posix.extname(e).toLowerCase();return pI[t]??"plaintext"}var Do=class{constructor(t){this.options=t,this.fileSystem=new Kn(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 Rr(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 Pr(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 _o(this.fileSystem,t,{routeEntryFiles:this.options.routes.map(n=>n.entryFile)})}resolveSourceLocation(t){return Oo(t,this.engine.getRenderDetail(t.key,t.routeId))}async planOperation(t){let n=wI.safeParse(t);if(!n.success)return{result:vr(t,n.error.issues.map(i=>i.message))};let r=new Kn(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:Lt(s)},c=r.getChangedFiles();if(c.length===0)return{result:a};let l=AI.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:c.map(u=>TI(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 dr({projectRoot:"/snapshot",fileSystem:t,routes:this.options.routes.map(o=>({routeId:o.routeId,entryFile:o.entryFile})),onEvent:r&&this.options.onEvent?o=>{let i=wr(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})}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 TI(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 NI(e){return new Do(e)}import{SiteEditOperationRequestSchema as _I}from"@vcp-dev/contracts";import rt from"node:fs/promises";import Ae from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as FI,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as MI}from"@vcp-dev/contracts";var Lo=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=dr({...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 _o(this.fileSystem,t,{routeEntryFiles:this.engine.getRouteEntryFiles()})}resolveSourceLocation(t){return Oo(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(Ae.join(n,r),"utf8")},async readFileBytes(r){return rt.readFile(Ae.join(n,r))},async getFileInfo(r){let o=Ae.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 ko(Ae.join(n,r),o)},async createExclusive(r,o){let i=Ae.join(n,r);await rt.mkdir(Ae.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(Ae.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=Ae.join(n,i),a=Ae.dirname(Ae.join(n,o));for(;a!==s&&a.startsWith(`${s}${Ae.sep}`);){try{await rt.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=Ae.dirname(a);continue}break}a=Ae.dirname(a)}},async exists(r){try{return await rt.access(Ae.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...MI,...FI],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=Ae.join(n,...d.split("/")),E;try{E=await rt.lstat(h)}catch{return}if(E.isSymbolicLink())return;if(E.isFile()){let C=E.ino>0?`${String(E.dev)}:${String(E.ino)}`:null;if(C&&s.has(C))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}C&&s.add(C),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 v=await rt.readdir(h,{withFileTypes:!0});for(let C of v)C.isSymbolicLink()||await u(`${d}/${C.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 ya(e){return new Lo(e)}var jo=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=ya({projectRoot:t.projectRoot,fileSystem:t.fileSystem,routes:t.routes.map(n=>({routeId:n.routeId,entryFile:n.entryFile})),onEvent:n=>{let r=wr(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:Rr(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:Pr(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=_I.safeParse(r);if(!o.success)return vr(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:Lt(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:Lt(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:Lt(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 OI(e){return new jo(e)}import{createHash as DI,randomUUID as Aa}from"node:crypto";import he from"node:fs/promises";import ye from"node:path";var ze=1,Ea=1,LI=2,jI="index.json",BI="recovery.json",$I="transaction-journal.json",VI="document-version.json",$o={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 qf(e,t={}){let n=tk(e),r=ok(t.limits),o=xa(n),i=nk(n),s=await _e(i),a=await _e(o)||s;a||(await HI(n),await WI(n)),a||await ik(n);let c=await Le(n),l=new Set(a?(await Xo(n)).map(d=>d.stageId):[]);a||await fr(n,c.entryIds);let u=async()=>{if(await _e(o)||s)throw new z(K.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")};return{rootDir:n,recoveryRequired:a,async readDocumentVersion(){return Zf(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 Zf(n);await pr(sp(n),{schemaVersion:1,version:Math.max(m,d)})},async stageAppend(d,m={}){await u();let p=await Xf(d,r),h={schemaVersion:Ea,stageId:Aa(),entryId:p.entryId,blobIds:p.blobs.map(E=>E.digest)};try{await zf(n,p),await JI(n,h,m.durableManifest!==!1)}catch(E){try{await Wf(n,h)}catch(v){throw new z(K.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:v})}throw E}return{stageId:h.stageId,entryId:h.entryId,blobIds:h.blobIds}},async discardStage(d){await u(),ka(d);let m=await ba(n,d);m&&await Wf(n,m)},async previewStagedAppend(d,m){return await u(),(await Jf(n,r,d,m)).transition},async previewCursor(d,m){await u();let p=await Le(n);return Ca(p,m),Sa(d,p.entryIds.length),ep(p,p.entryIds,d)},async publishStagedAppend(d,m,p){if(await u(),Vo(d,"entryId"),p){ka(p);let E=await ba(n,p);if(!E||E.entryId!==d)throw new z(K.INVALID_SCHEMA,"history stage does not match the published entry")}let h=await Jf(n,r,d,m);return Gf({rootDir:n,previousDigest:h.current.digest,entryIds:h.entryIds,cursor:h.cursor,afterWrite:async()=>{p?await Uo(n,p):await zI(n,d),await fr(n,h.entryIds)}})},async append(d){await u();let m=await Le(n),p=await Xf(d,r),h=[...m.entryIds];m.cursor<h.length-1&&h.splice(m.cursor+1),h.push(p.entryId);try{await zf(n,p);let E=await tp(n,h,r);return await Na(n,E.entryIds,E.cursor),await fr(n,E.entryIds),Le(n)}catch(E){throw await fr(n,m.entryIds),E}},async readEntry(d){return Vo(d,"entryId"),hr(n,d)},async readBlob(d){Vo(d,"blobId");let m=await Ba(n,d),p=await _t(m,K.NOT_FOUND,"blob");return Fa(p,d,m),p},async readIndex(){return Le(n)},async readStatus(){let d=await Le(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 _e(o)||await _e(i)}},async readUndoRedoIds(){let d=await Le(n);return{undoIds:d.undoIds,redoIds:d.redoIds,currentId:d.currentId}},async setCursor(d,m){await u();let p=await Le(n);return Ca(p,m),Sa(d,p.entryIds.length),Gf({rootDir:n,previousDigest:p.digest,entryIds:p.entryIds,cursor:d})},async markRecoveryRequired(d){await _e(o)||await pr(xa(n),{schemaVersion:ze,reason:rk(d),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await he.rm(xa(n),{force:!0})},async readTransactionJournal(){return await _e(i)?Bo(i):null},async writeTransactionJournal(d){await u(),ap(d);try{await pr(i,d)}catch(p){let h=await Bo(i).catch(()=>null);if(h&&Buffer.from(je(h)).equals(Buffer.from(je(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(je(m)).equals(Buffer.from(je(d))))throw new z(K.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(d){let m=await _e(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 _e(i))return;throw p}if(await _e(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 Uo(n,m),l.delete(m);await YI(n);let d=await Le(n);await fr(n,d.entryIds)}}}async function Jf(e,t,n,r){Vo(n,"entryId");let o=await Le(e);Ca(o,r);let i=await hr(e,n),s=[...o.entryIds];o.cursor<s.length-1&&s.splice(o.cursor+1),s.push(i.id);let a=await tp(e,s,t);return{current:o,entryIds:a.entryIds,cursor:a.cursor,transition:ep(o,a.entryIds,a.cursor)}}function ep(e,t,n){return Sa(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:UI(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function UI(e,t){return Ot(je({schemaVersion:ze,entryIds:e,cursor:t}))}function Sa(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new z(K.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function KI(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 Xf(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=ek(c.data),u=Ot(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:ze,kind:e.kind,manifest:e.manifest,blobs:r},i=je({...o}),s=Ot(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 zf(e,t){let n=Oa(e,t.entryId),r={id:t.entryId,...t.entryBody},o=[...t.blobs.map(a=>Hf(Da(e,a.digest),a.bytes,{kind:"blob",digest:a.digest},ja(e,a.digest))),Hf(n,je(r),{kind:"entry",digest:t.entryId},La(e,t.entryId))],s=(await Promise.allSettled(o)).find(a=>a.status==="rejected");if(s)throw s.reason}async function Hf(e,t,n,r){let o=await Pa(e)??(r?await Pa(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 op(e,t)}async function tp(e,t,n){let r=[...t],o=r.length-1;for(;;){if((await rp(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 JI(e,t,n){Ta(t);let r=_a(e,t.stageId);if(n){await pr(r,t);return}await qI(r,t)}async function ba(e,t){let n=await Pa(_a(e,t));if(n===null)return null;let r=gr(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=Ta(r);if(o.stageId!==t)throw new z(K.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function Xo(e){let t=[];for(let n of await Jo(Ma(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);ka(r);let o=await ba(e,r);o&&t.push(o)}return t}async function Wf(e,t){Ta(t);let n=await Le(e),r=(await Xo(e)).filter(s=>s.stageId!==t.stageId),o=new Set(n.entryIds),i=new Set;for(let s of n.entryIds){let a=await hr(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 Yf(Oa(e,t.entryId),La(e,t.entryId));for(let s of t.blobIds)i.has(s)||await Yf(Da(e,s),ja(e,s));await Uo(e,t.stageId),await wa(yr(e)),await wa(xr(e))}async function Uo(e,t){await Ia(_a(e,t)),await XI(e)}async function XI(e){try{await he.rmdir(Ma(e))}catch(t){if(Er(t)||ot(t)&&t.code==="ENOTEMPTY")return;throw t}}async function zI(e,t){for(let n of await Xo(e))n.entryId===t&&await Uo(e,n.stageId)}async function Ia(e){if(await he.rm(e,{force:!0}),await _e(e))throw new z(K.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function Yf(e,t){await Ia(e),await Ia(t)}function Ta(e){if(!ot(e)||e.schemaVersion!==Ea||typeof e.stageId!="string"||!np(e.stageId)||!Be(e.entryId))throw new z(K.INVALID_SCHEMA,"history stage schema is invalid");let t=ip(e.blobIds,"history stage blobIds");return{schemaVersion:Ea,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function ka(e){if(!np(e))throw new z(K.INVALID_PATH,"history stageId must be a UUID")}function np(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 fr(e,t){let n=new Set(t),r=new Set;for(let c of t){let l=await hr(e,c);for(let u of l.blobs)r.add(u.digest)}for(let c of await Xo(e)){n.add(c.entryId);for(let l of c.blobIds)r.add(l)}let o=yr(e),i=await Jo(o);for(let c of i){if(!c.endsWith(".json"))continue;let l=Qf(c.slice(0,-5));l&&!n.has(l)&&await Ko(ye.join(o,c))}let s=xr(e),a=await Jo(s);for(let c of a){let l=Qf(c);l&&!r.has(l)&&await Ko(ye.join(s,c))}}async function Le(e){let t=zo(e),n=await _t(t,K.NOT_FOUND,"index"),r=gr(Buffer.from(n).toString("utf8"),"index"),o=GI(r),i=[...o.entryIds],{totalBytes:s}=await rp(e,i),a=i.slice(0,o.cursor+1).reverse(),c=i.slice(o.cursor+1);return{schemaVersion:ze,digest:o.digest,entryIds:i,cursor:o.cursor,currentId:i[o.cursor]??null,undoIds:a,redoIds:c,totalBytes:s}}async function rp(e,t){let n=0,r=new Set,o=zo(e),i=await _t(o,K.NOT_FOUND,"index");n+=i.byteLength;for(let s of t){let a=await hr(e,s),c=await cp(e,s),l=await _t(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 Ba(e,u.digest),m=await _t(d,K.NOT_FOUND,"blob");Fa(m,u.digest,d),n+=m.byteLength}}return{totalBytes:n}}async function hr(e,t){let n=await cp(e,t),r=await _t(n,K.NOT_FOUND,"entry"),o=gr(Buffer.from(r).toString("utf8"),`entry ${t}`),i=ZI(o);if(i.id!==t)throw new z(K.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(Ot(je({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 Ba(e,a.digest),l=await _t(c,K.NOT_FOUND,"blob");Fa(l,a.digest,c)}return i}async function Na(e,t,n){let r={schemaVersion:ze,digest:Ot(je({schemaVersion:ze,entryIds:t,cursor:n})),entryIds:t,cursor:n};await pr(zo(e),r)}function Ca(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 Gf(e){let t=Ot(je({schemaVersion:ze,entryIds:e.entryIds,cursor:e.cursor}));try{return await Na(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.(),await Le(e.rootDir)}catch(n){let r=await Le(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 HI(e){await he.mkdir(e,{recursive:!0}),await he.mkdir(yr(e),{recursive:!0}),await he.mkdir(xr(e),{recursive:!0}),await he.mkdir(mr(e),{recursive:!0})}async function WI(e){await he.rm(mr(e),{recursive:!0,force:!0}),await he.mkdir(mr(e),{recursive:!0})}async function YI(e){let t=mr(e);await he.mkdir(t,{recursive:!0});for(let n of await Jo(t))n!=="stages"&&await he.rm(ye.join(t,n),{recursive:!0,force:!0})}function GI(e){if(!ot(e))throw new z(K.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==ze)throw new z(K.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=ip(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=Ot(je({schemaVersion:ze,entryIds:t,cursor:r}));if(o!==i)throw new z(K.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:ze,digest:o,entryIds:t,cursor:r}}function ZI(e){if(!ot(e))throw new z(K.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==ze)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=Ra(e.manifest,"entry.manifest"),o=QI(e.blobs);return{id:t,schemaVersion:ze,kind:n,manifest:r,blobs:o}}function QI(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 pr(e,t){await op(e,je(t))}async function qI(e,t){let n=ye.dirname(e),r=ye.basename(e),o=ye.join(n,`.${r}.${process.pid}.${Aa()}.tmp`);await he.mkdir(n,{recursive:!0});try{await he.writeFile(o,je(t),{flag:"wx"}),await he.rename(o,e)}finally{await Ko(o)}}async function op(e,t){let n=ye.dirname(e),r=ye.basename(e),o=ye.join(n,`.${r}.${process.pid}.${Aa()}.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 wa(n)}finally{await Ko(o)}}function je(e){return Buffer.from(JSON.stringify(va(e)),"utf8")}function va(e){if(Array.isArray(e))return e.map(t=>va(t));if(ot(e)){let t={};for(let n of Object.keys(e).sort())t[n]=va(e[n]);return t}return e}function gr(e,t){try{return JSON.parse(e)}catch(n){throw new z(K.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function Ra(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=>Ra(n,t));if(ot(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=Ra(o,t);return n}break}throw new z(K.INVALID_JSON,`${t} must be JSON-serializable`)}function ip(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 Ot(e){return`sha256:${DI("sha256").update(e).digest("hex")}`}function ek(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function _t(e,t,n){try{return await he.readFile(e)}catch(r){throw new z(t,`${n} not found: ${e}`,{cause:r})}}async function Pa(e){try{return await he.readFile(e)}catch(t){if(Er(t))return null;throw t}}function Fa(e,t,n){if(Ot(e)!==t)throw new z(K.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function _e(e){try{return await he.access(e),!0}catch(t){if(Er(t))return!1;throw t}}async function Ko(e){try{await he.rm(e,{force:!0,recursive:!0})}catch{}}async function wa(e){try{let t=await he.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function Jo(e){try{return await he.readdir(e)}catch(t){if(Er(t))return[];throw t}}function tk(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 zo(e){return ye.join(e,jI)}function xa(e){return ye.join(e,BI)}function nk(e){return ye.join(e,$I)}function sp(e){return ye.join(e,VI)}async function Zf(e){try{let t=await he.readFile(sp(e),"utf8"),n=gr(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(Er(t))return 0;throw t}}async function Bo(e){let t=await _t(e,K.RECOVERY_PENDING,"transaction journal"),n=gr(Buffer.from(t).toString("utf8"),"transaction journal");return ap(n),n}function ap(e){if(!ot(e)||e.schemaVersion!==LI||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!KI(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 rk(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function yr(e){return ye.join(e,"entries")}function xr(e){return ye.join(e,"blobs")}function mr(e){return ye.join(e,"tmp")}function Ma(e){return ye.join(mr(e),"stages")}function _a(e,t){return ye.join(Ma(e),`${t}.json`)}function Oa(e,t){return ye.join(yr(e),`${up(t)}.json`)}function Da(e,t){return ye.join(xr(e),up(t))}function La(e,t){return ye.join(yr(e),`${t}.json`)}function ja(e,t){return ye.join(xr(e),t)}async function cp(e,t){return lp(Oa(e,t),La(e,t))}async function Ba(e,t){return lp(Da(e,t),ja(e,t))}async function lp(e,t){return await _e(e)?e:await _e(t)?t:e}function up(e){return e.slice(7)}function Qf(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 Er(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function ok(e){return{maxEntries:e?.maxEntries??$o.maxEntries,maxSessionBytes:e?.maxSessionBytes??$o.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??$o.maxEntryBytes}}async function ik(e){let t=zo(e);await _e(t)||await Na(e,[],-1)}export{z as FileHistoryStoreError,jo as PreviewFileSystemSiteEditEngineRuntime,Vd as SITE_EDIT_RAW_COLOR_LITERAL_RE,Do as SnapshotSiteEditEngineRuntime,OI as createPreviewSiteEditEngineRuntime,NI as createSiteEditEngineRuntime,qf as openFileHistoryStore,cr as scanSiteEditThemeStyleViolations};