@vcp-dev/site-edit-engine 0.6.0 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +0 -2
- package/dist/index.js +7 -7
- package/dist/preview-runtime.d.ts +3 -3
- package/dist/types.d.ts +3 -6
- package/package.json +2 -2
- package/dist/mutation-context-verifier.d.ts +0 -30
package/dist/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import{SiteEditOperationRequestSchema as bS,SiteEditPatchPlanSchema as IS}from"@vcp-dev/contracts";function wt(e){return{requestId:e.requestId,kind:e.kind,target:e.target,resultVersion:e.resultVersion,affectedFiles:e.affectedFiles,...e.selectionRef?{selectionRef:e.selectionRef}:{}}}function cr(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 lr(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}})),pageComposition:e.pageComposition.status==="unsupported"?{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics}:{status:"supported",containerKey:e.pageComposition.container.key,hasBusinessMembers:e.pageComposition.businessMembers.length>0,placementUnitKeys:e.pageComposition.placementUnits.map(n=>n.key),placements:e.pageComposition.placements.map(n=>({placementKey:n.placementKey,placementUnitKey:n.placementUnitKey,relation:n.relation}))}}}function ur(e){return{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:kf(e.capabilities),provenanceChain:e.provenanceChain?{editMode:e.provenanceChain.editMode,diagnostics:e.provenanceChain.diagnostics}:void 0,textSegments:e.textSegments.map(t=>({index:t.index,editable:t.editable,sourceKind:t.source?.kind??null})),boundaryKind:e.boundaryKind}}function dr(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:wt(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 kf(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 pE,getSiteEditSourceDeleteProtectionReason as mE,isSiteEditTextSourcePath as hE,parseSiteEditRepeatInstanceKey as gE,SITE_EDIT_SOURCE_DELETE_CAPABILITY as yE,stripSiteEditRepeatInstanceKeys as He}from"@vcp-dev/contracts";import{parse as xE}from"yaml";import io from"node:path";function Sn(e,t,n){return`${e}::${t}::${n}`}var _={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 jo from"@babel/traverse";import*as g from"@babel/types";import{createHash as Af}from"node:crypto";import*as Ta from"@babel/parser";function Pt(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:Pt(t,n,r,o)}}function _o(e,t,n,r,o){return{ok:!1,source:e,diagnostic:Pt(t,n,r,o)}}var Rf={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function Ze(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:Ta.parse(t,{sourceType:"module",plugins:Rf[n]})}}catch(r){return{ok:!1,source:t,diagnostic:Pt("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function Oo(e,t){return Ze({source:e,profile:Na(t.kind)})}function Lo(e,t){return Ze({source:e,profile:Na(t)})}function Na(e){return"next-app-entry"}function At(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 Cf from"@babel/parser";import*as Xt from"@babel/types";import*as zt from"node:path";var Fa=[".tsx",".ts",".jsx",".js"],vf=Fa.map(e=>`${zt.sep==="\\"?"\\":"/"}index${e}`);function Ma(e){let t=[];for(let n of e.program.body)Xt.isImportDeclaration(n)&&typeof n.source.value=="string"&&bn(n.source.value)&&t.push(n.source.value),Xt.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&bn(n.source.value)&&t.push(n.source.value),Xt.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&bn(n.source.value)&&t.push(n.source.value);return t}function bn(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function wf(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=zt.dirname(e);return zt.join(n,t).replace(/\\/g,"/")}async function Pf(e,t){for(let n of Fa){let r=`${e}${n}`;if(await t(r))return r}for(let n of vf){let r=`${e}${n}`;if(await t(r))return r}return null}async function _a(e,t,n){let r=await fr(e,t,n);return r.ok?r.path:null}async function fr(e,t,n){let r=wf(e,t);try{let o=await Pf(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)}}}}}var Do=(e,t)=>{let n=Ze({source:t,profile:At({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${Af("sha256").update(t).digest("hex")}`,ast:n.ast,imports:Ma(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};var pr="components/ui";function Tt(e){if(!e)return!1;let t=Bo(e);return t===pr||t.startsWith(`${pr}/`)||t.includes(`/${pr}/`)||t.endsWith(`/${pr}`)}function In(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?Tt(e.slice(2)):e.startsWith("./")||e.startsWith("../")?Tt(Bo(`${Tf(t)}/${e}`)):Tt(e):!1}function Bo(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 Tf(e){let t=Bo(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}var Nf=typeof jo=="function"?jo:jo.default;function Ie(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 Ff(e){return/^[A-Z]/.test(e)}function Jo(e){let t=e.openingElement;return g.isJSXIdentifier(t.name)?t.name.name==="Fragment":g.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function Ht(e){return g.isJSXFragment(e)}function Da(e){return g.isJSXIdentifier(e.name)?e.name.name:g.isJSXMemberExpression(e.name)?Ba(e.name):g.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function Ba(e){return g.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:g.isJSXMemberExpression(e.object)?`${Ba(e.object)}.${e.property.name}`:e.property.name}function Mf(e){return e.split(".")[0]??e}function _f(e){let t=e;for(;t;){let n=t.node;if(g.isFunctionDeclaration(n)&&n.id||g.isVariableDeclarator(n)&&g.isIdentifier(n.id))return n.id.name;if(g.isExportDefaultDeclaration(n)){let r=n.declaration;if(g.isFunctionDeclaration(r)&&r.id)return r.id.name;if(g.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function Of(){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 Lf(e){let t=new Map;for(let n of e.program.body){if(!g.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(g.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(g.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(g.isImportSpecifier(o)){let i=g.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function rt(e,t=[]){if(g.isIdentifier(e))return t.push(e.name),t;if(g.isObjectPattern(e)){for(let n of e.properties)g.isObjectProperty(n)?rt(n.value,t):g.isRestElement(n)&&rt(n.argument,t);return t}if(g.isArrayPattern(e)){for(let n of e.elements)n&&(g.isRestElement(n)?rt(n.argument,t):rt(n,t));return t}return g.isAssignmentPattern(e)?(rt(e.left,t),t):(g.isRestElement(e)&&rt(e.argument,t),t)}function dt(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function mr(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 Df(e,t,n){e.set(t,{resolved:!0,value:n})}function Xo(e,t){e.set(t,{resolved:!1})}function ja(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 ot(e,t,n){if(g.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!g.isMemberExpression(e))return null;let r=[],o=e;for(;g.isMemberExpression(o);){if(o.computed)if(g.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(g.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&g.isExpression(o.property)){let i=Ft(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(!g.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return g.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:dt(e,t),base:o.name,path:r}:null}function Ft(e,t){if(g.isStringLiteral(e)||g.isNumericLiteral(e)||g.isBooleanLiteral(e))return e.value;if(g.isNullLiteral(e))return null;if(g.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(g.isIdentifier(e)){let n=mr(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(g.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||g.isSpreadElement(r))return;let o=Ft(r,t);if(o===void 0)return;n.push(o)}return n}if(g.isObjectExpression(e)){let n={};for(let r of e.properties){if(!g.isObjectProperty(r)||r.computed||!g.isExpression(r.value))return;let o=null;if(g.isIdentifier(r.key)?o=r.key.name:g.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!g.isIdentifier(r.value))return;let s=mr(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=Ft(r.value,t);if(i===void 0)return;n[o]=i}return n}if(g.isMemberExpression(e)){let n=ot(e,"",t);if(!n)return;let r=mr(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=ja(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(g.isCallExpression(e))return Va(e,t)??void 0}function $a(e,t,n){let r=ot(e,n,t);if(!r)return g.isMemberExpression(e)||g.isBinaryExpression(e)||g.isLogicalExpression(e)||g.isConditionalExpression(e)||g.isCallExpression(e)?{value:dt(e,n),source:null}:null;let o=mr(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?ja(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 $o(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:Of(),parentStack:[],valueScopes:i,importMap:o}}function Uo(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of rt(o.id))Xo(n,s);if(!g.isIdentifier(o.id)||!o.init||!g.isExpression(o.init))continue;let i=Ft(o.init,t);i!==void 0&&Df(n,o.id.name,i)}}function Bf(e){let t=[];for(let n of e){if(g.isVariableDeclaration(n)){t.push(n);continue}g.isExportNamedDeclaration(n)&&n.declaration&&g.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function jf(e,t,n){let r=[],o=0;for(let i of e)if(g.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:Ie(i),editable:!0,source:null})}else if(g.isJSXExpressionContainer(i)&&g.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:Ie(i),editable:!0,source:null});else if(g.isJSXExpressionContainer(i)&&g.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:Ie(i),editable:!0,source:null}):r.push({index:o++,value:dt(s,n),sourceRange:Ie(i),editable:!0,source:null})}else if(g.isJSXExpressionContainer(i)&&g.isExpression(i.expression)){let s=$a(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:Ie(i),editable:!0,source:s.source})}return r}function $f(e,t,n){let r=[];for(let o of e.attributes)if(!(!g.isJSXAttribute(o)||!g.isJSXIdentifier(o.name))){if(g.isStringLiteral(o.value)){r.push({name:o.name.name,value:o.value.value,sourceRange:Ie(o),source:null});continue}if(g.isJSXExpressionContainer(o.value)&&g.isExpression(o.value.expression)){let i=Ft(o.value.expression,t);if(o.name.name==="className"){let a=typeof i=="string"?i:i===void 0?Va(o.value.expression,t):null;if(a){r.push({name:o.name.name,value:a,sourceRange:Ie(o),source:null,resolvedValue:a});continue}}let s=$a(o.value.expression,t,n);if(i!==void 0&&typeof i!="string"&&typeof i!="number"){r.push({name:o.name.name,value:Oa(i),sourceRange:Ie(o),source:ot(o.value.expression,n,t),resolvedValue:i});continue}if(!s){i!==void 0&&r.push({name:o.name.name,value:Oa(i),sourceRange:Ie(o),source:ot(o.value.expression,n,t),resolvedValue:i});continue}r.push({name:o.name.name,value:s.value,sourceRange:Ie(o),source:s.source})}}return r}function Va(e,t){let n=Wt(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function Wt(e,t){if(g.isStringLiteral(e))return[e.value];if(g.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(g.isNullLiteral(e))return[];if(g.isBooleanLiteral(e))return e.value?null:[];if(g.isIdentifier(e)||g.isMemberExpression(e)){if(g.isIdentifier(e)&&e.name==="undefined")return[];let n=Ft(e,t);return typeof n=="string"?[n]:null}if(g.isConditionalExpression(e)){let n=Wt(e.consequent,t),r=Wt(e.alternate,t);return!n||!r?null:[...n,...r]}if(g.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=Ft(e.left,t);return n===!1||n===null?[]:Wt(e.right,t)}if(g.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||g.isSpreadElement(r))return null;let o=Wt(r,t);if(!o)return null;n.push(...o)}return n}if(g.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!g.isObjectProperty(r))return null;let o=Uf(r.key);if(!o)return null;n.push(o)}return n}if(g.isCallExpression(e)){let n=Vf(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!g.isExpression(o))return null;let i=Wt(o,t);if(!i)return null;r.push(...i)}return r}return null}function Vf(e){return g.isIdentifier(e)?e.name:g.isMemberExpression(e)&&g.isIdentifier(e.property)?e.property.name:null}function Uf(e){return g.isIdentifier(e)?e.name:g.isStringLiteral(e)?e.value:null}function Kf(e,t){let n=e.attributes.find(r=>g.isJSXAttribute(r)&&g.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!g.isJSXAttribute(n)||!g.isJSXExpressionContainer(n.value)?null:n.value.expression}function Jf(e,t){for(let n of t){let r=Kf(e,n);if(r)return r}return null}function Xf(e){return g.isJSXIdentifier(e.name)?e.name.name:null}function Oa(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function zf(e){if(!g.isCallExpression(e)&&!g.isOptionalCallExpression(e))return null;let t=e.callee;return!g.isMemberExpression(t)&&!g.isOptionalMemberExpression(t)||!g.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!g.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function Vo(e){return g.isArrowFunctionExpression(e)||g.isFunctionExpression(e)}function Wf(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function Hf(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function La(e,t,n,r){if(!e||!g.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:dt(e,n),collectionSource:ot(e,n,r)};if(t){let i=t.params[0],s=t.params[1];g.isIdentifier(i)&&(o.itemParamName=i.name),g.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function ft(e,t,n){if(!e)return[];if(g.isJSXElement(e)){if(Jo(e))return Er(e.children,t,n);let r=yr(e,t,n);return r?[r]:[]}return Ht(e)?xr(e,t,n):g.isParenthesizedExpression(e)?ft(e.expression,t,n):g.isExpression(e)?Sr(e,t,n):[]}function hr(e,t,n){let r=new Map;for(let o of e.params)for(let i of rt(o))Xo(r,i);t.valueScopes.push(r);try{if(!g.isBlockStatement(e.body))return ft(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return Ua(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function Ua(e,t,n){let r=[];for(let o of e){if(g.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];i&&Uo([o],t,i);continue}r.push(...Ko(o,t,n))}return r}function Ko(e,t,n){if(g.isReturnStatement(e))return e.argument?ft(e.argument,t,n):[];if(g.isBlockStatement(e))return Nt(e.body,t,n);if(g.isIfStatement(e)){let r=g.isBlockStatement(e.consequent)?Nt(e.consequent.body,t,n):Ko(e.consequent,t,n),o=e.alternate?g.isBlockStatement(e.alternate)?Nt(e.alternate.body,t,n):Ko(e.alternate,t,n):[];return[...r,...o]}if(g.isSwitchStatement(e))return Nt(e.cases.flatMap(r=>r.consequent),t,n);if(g.isTryStatement(e)){let r=Nt(e.block.body,t,n);return e.handler&&r.push(...Nt(e.handler.body.body,t,n)),e.finalizer&&r.push(...Nt(e.finalizer.body,t,n)),r}return[]}function Nt(e,t,n){let r=new Map;t.valueScopes.push(r);try{return Ua(e,t,n)}finally{t.valueScopes.pop()}}function gr(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:Ie(r),sourceCandidates:i&&i.length>0?i:void 0})}function Yf(e,t,n,r){let o=Jf(e.openingElement,["items","dataSource","data"]),i={key:t,tag:Da(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!g.isJSXAttribute(s))continue;let a=Xf(s);if(!a||!g.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!g.isJSXEmptyExpression(c)){if(Wf(a)&&Vo(c)){let l=hr(c,n,r),u=La(o,c,r,n);gr(n,"repeat-region",t,s,l,u?[u]:void 0);continue}if(Hf(a)){let l=Vo(c)?hr(c,n,r):ft(c,n,r);gr(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!g.isJSXExpressionContainer(s)||!Vo(s.expression))continue;let a=hr(s.expression,n,r),c=La(o,s.expression,r,n);gr(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function yr(e,t,n){let r=Da(e.openingElement);if(r==="Fragment"||Jo(e))return Er(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=Ff(r),a;if(s){let A=t.ordinalTracker.getOrdinal(i,r);a=`component:${r}#${A}`}else{let A=t.ordinalTracker.getOrdinal(i,r);a=`${r}#${A}`}let c=o?t.elements.get(o.key)?.identity.structuralPath:void 0,l=c?`${c}/${a}`:a,u=Sn(t.file,t.componentName,l),f={file:t.file,component:t.componentName,structuralPath:l,key:u},p=s?"component-boundary":null,m=jf(e.children,t,n),S=$f(e.openingElement,t,n),b,k,R=!1;if(s){let A=t.importMap.get(r)??t.importMap.get(Mf(r));A&&(b=A.specifier,k=A.exportName,R=In(A.specifier,t.file))}let w={identity:f,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:Ie(e),parentKey:i,childKeys:[],textSegments:m,attributes:S.length>0?S:void 0,boundaryKind:p,isOpaque:s,...R?{isPublicUiComponent:!0}:{},importedFrom:b,exportName:k};return t.elements.set(u,w),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(u),Yf(e,u,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:u,tag:r}),Gf(e.children,t,n),t.parentStack.pop()),u}function xr(e,t,n){return Er(e.children,t,n)}function Er(e,t,n){let r=[];for(let o of e)if(g.isJSXElement(o))if(Jo(o))r.push(...Er(o.children,t,n));else{let i=yr(o,t,n);i&&r.push(i)}else Ht(o)?r.push(...xr(o,t,n)):g.isJSXExpressionContainer(o)&&r.push(...Sr(o.expression,t,n));return r}function Gf(e,t,n){for(let r of e)g.isJSXElement(r)?yr(r,t,n):Ht(r)?xr(r,t,n):g.isJSXExpressionContainer(r)&&Sr(r.expression,t,n)}function Zf(e){return e==="&&"||e==="||"||e==="??"}function Sr(e,t,n){if(g.isJSXEmptyExpression(e))return[];let r=zf(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,c={kind:"repeat-template",collectionExpression:dt(r.collection,n),collectionSource:ot(r.collection,n,t)};if(g.isArrowFunctionExpression(a)||g.isFunctionExpression(a)){let u=a.params[0],f=a.params[1];g.isIdentifier(u)&&(c.itemParamName=u.name),g.isIdentifier(f)&&(c.indexParamName=f.name)}s.push(c);let l={kind:"repeat-region",ownerKey:i?.key??"",childKeys:[],sourceRange:Ie(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(l),(g.isArrowFunctionExpression(a)||g.isFunctionExpression(a))&&l.childKeys.push(...hr(a,t,n)),l.childKeys}if(g.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:dt(e.test,n),conditionSource:ot(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Ie(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...ft(e.consequent,t,n)),s.childKeys.push(...ft(e.alternate,t,n)),s.childKeys}if(g.isLogicalExpression(e)&&Zf(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:dt(e.left,n),conditionSource:ot(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Ie(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...ft(e.right,t,n)),s.childKeys}if(g.isParenthesizedExpression(e))return Sr(e.expression,t,n);if(g.isJSXElement(e)){let o=yr(e,t,n);return o?[o]:[]}return Ht(e)?xr(e,t,n):[]}function Qf(e){let t=e.argument;return t&&(g.isExpression(t)||Ht(t))?t:null}function kn(e,t){let n=[];for(let r of e){if(g.isReturnStatement(r)){let o=Qf(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(g.isIfStatement(r)){let o=g.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...kn(o,r.test)),r.alternate){let i=g.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...kn(i,r.test))}continue}if(g.isSwitchStatement(r))for(let o of r.cases){let i=o.test?g.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...kn(o.consequent,i))}}return n}function Ka(e){let{file:t,source:n,ast:r}=e,o=e.imports.map(f=>f.specifier),i=new Map,s=[],a=[],c=new Map,l=Lf(r);Nf(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(f){let p=_f(f);if(!p)return;let m=f.node,S=[];if(g.isArrowFunctionExpression(m))g.isExpression(m.body)||Ht(m.body)?S=[{argument:m.body,statement:g.returnStatement(g.isExpression(m.body)?m.body:null)}]:g.isBlockStatement(m.body)&&(S=kn(m.body.body));else{let H=m.body;g.isBlockStatement(H)&&(S=kn(H.body))}if(S.length===0){f.skip();return}let b=new Map;Uo(Bf(r.program.body),$o(t,p,i,s,l,[b]),b);let k=new Map;for(let H of m.params)for(let se of rt(H))Xo(k,se);let R=g.isBlockStatement(m.body)?m.body.body:[],w=S[0]?.statement??null;for(let H of R){if(w&&H===w)break;g.isVariableDeclaration(H)&&Uo([H],$o(t,p,i,s,l,[b,k]),k)}let A=$o(t,p,i,s,l,[b,k]);for(let H of S){let se=ft(H.argument,A,n);for(let ue of se)a.includes(ue)||a.push(ue);if(H.condition){let ue={kind:"conditional-branch",conditionExpression:dt(H.condition,n),conditionSource:ot(H.condition,n,A)};gr(A,"conditional-region","",H.statement,se,[ue])}}f.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 zo(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function br(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function Ja(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??Do,c=new Map,l=new Map,u=new Map,f=[],p=new Set,m=R=>{let w=`${R.path}\0${R.code}\0${R.message}\0${JSON.stringify(R.details??{})}`;p.has(w)||(p.add(w),f.push(R))},S=[{file:e,source:t,depth:0,diagnosticEntryFile:e,importStack:[]},...(o.additionalEntries??[]).map(R=>({file:R.file,source:R.source,depth:0,diagnosticEntryFile:R.file,importStack:[]}))],b=new Set;for(;S.length>0;){let R=S.shift(),{file:w,source:A,depth:H,diagnosticEntryFile:se,importStack:ue}=R;if(b.has(w))continue;b.add(w),c.set(w,A);let v=a(w,A);if(!v.ok){m(br(v.diagnostic,se,ue));continue}u.set(w,v.module);let{graph:N,localImports:B}=Ka(v.module);for(let j of N.elements.values())if(j.importedFrom&&bn(j.importedFrom)){let G=j.importedFrom,Z=await fr(w,G,r);Z.ok?(j.importedFrom=Z.path,Tt(Z.path)&&(j.isPublicUiComponent=!0)):In(G,w)||m(br(Z.diagnostic,se,zo(ue,w,G,Z.diagnostic.path)))}if(l.set(w,N),!(H>=i))for(let j of B){if(qf(j))continue;let G=await fr(w,j,r);if(!G.ok){In(j,w)||m(br(G.diagnostic,se,zo(ue,w,j,G.diagnostic.path)));continue}let Z=G.path;if(b.has(Z)||Tt(Z))continue;let fe=zo(ue,w,j,Z);try{let Y=await n(Z);S.push({file:Z,source:Y,depth:H+1,diagnosticEntryFile:se,importStack:fe})}catch(Y){m(br({path:Z,code:"import-read-failed",message:`Failed to read imported file: ${Z}`,details:{fromFile:w,specifier:j,reason:Y instanceof Error?Y.message:String(Y)}},se,fe))}}}let k=ep(e,l,s,(o.additionalEntries??[]).map(R=>R.file));return k.diagnostics=f,{graph:k,allSources:c,diagnostics:f,parsedModules:u,entryModule:u.get(e)??null}}function qf(e){return/\.(?:css|scss|sass|less)(?:\?.*)?$/i.test(e)}function ep(e,t,n,r=[]){let o=new Map,i=[],s=new Map,a=[];for(let[c,l]of t){for(let[u,f]of l.elements)o.set(u,f);for(let u of l.regions)i.push(u);for(let[u,f]of l.fileIndex){let p=s.get(u)??[];s.set(u,[...p,...f])}if(c===e){a=l.rootKeys;continue}r.includes(c)&&(a=[...a,...l.rootKeys])}return{routeId:e,rootKeys:a,elements:o,regions:i,fileIndex:s,version:n}}function Xa(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}),za(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function za(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}),za(s,t,n,r,o))}}import{isSiteEditRuntimeContainerTag as tp,isSiteEditRuntimeVoidElementTag as np}from"@vcp-dev/contracts/site-edit-runtime-capability";function rp(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(A=>({kind:A.kind,message:A.reason})),s=o.isOpaque,c=r.parentKey===null&&o.componentName==="Page",l=o.tag.toLowerCase(),u=o.tag!==l,f=!u&&np(l),p=u||tp(l),m=u&&o.childKeys.length>0&&!o.isPublicUiComponent,S=o.textSegments.length>0&&o.textSegments.some(A=>A.editable);f&&!i.some(A=>A.kind==="void-element")&&i.push({kind:"void-element",message:`Element '${o.tag}' is void: children cannot be inserted`}),!f&&!p&&!i.some(A=>A.kind==="void-element")&&i.push({kind:"void-element",message:`Element '${o.tag}' cannot contain structured children`});let b=S&&!s,k=!o.isPublicUiComponent&&!f&&p&&(!s||m);return{key:e,canUpdateText:b,canInsertChild:k,canMove:!c,canRemove:!c,constraints:i}}function Wa(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,rp(r,e,t));return n}import{createHash as xi}from"node:crypto";import fi from"@babel/traverse";function Wo(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 Am}from"node:crypto";import vc from"node:path";import*as Dr from"@babel/parser";import ai from"@babel/generator";import ci from"@babel/traverse";import*as ht from"@babel/types";import Ho from"@babel/traverse";var pt=typeof Ho=="function"?Ho:Ho.default,Ir=new WeakMap,Ha=new WeakMap;function st(e,t){let n=Oo(e,t);if(!n.ok)return _o(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=ne(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}}:_o(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function ne(e,t){return t.kind==="jsx-node"?Qa(e,t):t.kind==="jsx-attribute"?lp(e,t):t.kind==="value"?up(e,t):t.kind==="expression"?dp(e,t):t.kind==="directive"?fp(e,t):t.kind==="export"?pp(e,t):{ok:!1,diagnostic:Pt("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function Qa(e,t){return t.strategy==="source-range"?op(e,t):ip(e,t)}function op(e,t){let n=null;if(pt(e,{JSXElement(o){if(!Gt(o.node,t.sourceRange))return;let i=ge("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!Gt(o.node,t.sourceRange))return;let i=ge("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!Gt(o.node,t.sourceRange))return;let i=ge("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)}}),!n)return ye("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!Rp(r.path,t.expectedIdentity)?ye("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function ip(e,t){if(t.structuralPath===""){let r=ap(e,t.component);if(r){let o=cp(r);if(o)return o}}let n=null;return pt(e,{JSXElement(r){if(Cn(r)!==t.component||Go(r)!==t.structuralPath)return;let i=ge("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(Cn(r)!==t.component||Go(r)!==t.structuralPath)return;let i=ge("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=sp(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:ye("jsx-node","locator-miss","JSX node not found for structural-path locator")}function sp(e,t,n){let r=null;return pt(e,{JSXElement(o){if(Cn(o)!==t||!Gt(o.node,n))return;let i=ge("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(Cn(o)!==t||!Gt(o.node,n))return;let i=ge("jsx-node",o);i&&(r=i,o.stop())}}),r}function ap(e,t){let n=null;return pt(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 cp(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 ye("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?ye("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 ye("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function lp(e,t){let n=Qa(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>Cp(c,t.name));if(!s||!s.isJSXAttribute())return ye("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=ge("jsx-attribute",s);return a?{ok:!0,match:a}:ye("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function up(e,t){let n=mp(e,t);if(!n.ok)return n;let r=hp(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!it(r.match.path.node.loc,t.expectedRange)?ye("value","locator-miss","Resolved value does not match expected range"):{ok:!0,match:r.match}:r}function dp(e,t){let n=null;return pt(e,{Identifier(r){if(!Sp(r))return;let o=Ga(r);if(!o||!Za(o,t))return;let i=ge("expression",r);i&&(t.expectedRange&&!it(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=Ga(r);if(!o||!Za(o,t))return;let i=ge("expression",r);i&&(t.expectedRange&&!it(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:ye("expression","locator-miss","Expression not found")}function fp(e,t){let n=null;return pt(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!it(i.node.loc,t.expectedRange))return;let s=ge("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:ye("directive","locator-miss",`Directive '${t.value}' not found`)}function pp(e,t){let n=null;return pt(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let c=r.get("declaration");if(c.isFunctionDeclaration()&&c.node.id?.name==="generateMetadata"){let p=ge("export",c);if(!p||t.expectedRange&&!it(c.node.loc,t.expectedRange))return;n=p,r.stop();return}if(!c.isVariableDeclaration())return;let l=Zo(c,"generateMetadata");if(!l||!l.isVariableDeclarator())return;let u=l.get("init");if(!u.node)return;let f=ge("export",u);if(!f||t.expectedRange&&!it(u.node.loc,t.expectedRange))return;n=f,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=Zo(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!it(s.node.loc,t.expectedRange))return;let a=ge("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=ge("export",o);i&&(t.expectedRange&&!it(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:ye("export","export-not-found",`Export '${kp(t)}' not found`)}function mp(e,t){let n=null;return pt(e,{Expression(r){if(n||t.root.kind!=="expression"||!Gt(r.node,t.root.sourceRange))return;let o=ge("value",r);o&&(n=o,r.stop())},VariableDeclarator(r){if(n)return;if(t.root.kind==="binding"){if(r.node.id.type!=="Identifier"||r.node.id.name!==t.root.name)return;let m=r.get("init");if(!m.node)return;let S=ge("value",m);if(!S)return;n=S,r.stop();return}if(t.root.kind!=="hook-state")return;let o=t.root,i=r.get("id"),s=r.get("init");if(!i.isArrayPattern()||!s.isCallExpression()||i.node.elements.findIndex(m=>m?.type==="Identifier"&&m.name===o.name)!==0)return;let c=s.node.callee;if((c.type==="Identifier"?c.name:c.type==="MemberExpression"&&c.property.type==="Identifier"?c.property.name:null)!==o.hook)return;let u=o.hook==="useReducer"?1:0,f=r.get(`init.arguments.${u}`);if(!f||Array.isArray(f)||!f.node)return;let p=ge("value",f);p&&(n=p,r.stop())},ExportNamedDeclaration(r){if(n||t.root.kind!=="named-export")return;let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=Zo(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=ge("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=ge("value",o);i&&(n=i,r.stop())}}),n?{ok:!0,match:n}:ye("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 hp(e,t){let n=Yo(e);for(let o of t){if(n=Yo(n),o.kind==="property"){if(!n.isObjectExpression())return ye("value","unsupported-syntax","Property path requires object expression");let a=n.get("properties");if(a.some(l=>!l.isObjectProperty()))return ye("value","unsupported-syntax","Spread properties are not supported");let c=a.find(l=>vp(l,o.name));if(!c||!c.isObjectProperty())return ye("value","property-not-found",`Property '${o.name}' not found`);n=c.get("value");continue}if(!n.isArrayExpression())return ye("value","unsupported-syntax","Array index path requires array expression");let i=n.get("elements");if(i.some(a=>a.node?.type==="SpreadElement"))return ye("value","unsupported-syntax","Spread array elements are not supported");let s=i[o.index];if(!s?.node)return ye("value","array-index-out-of-range",`Array index ${o.index} is out of range`);n=s}n=Yo(n);let r=ge("value",n);return r?{ok:!0,match:r}:ye("value","locator-miss","Resolved value has no source range")}function Yo(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function ge(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 Gt(e,t){return it(e.loc,t)}function it(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 Go(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!kr(n.node)){let o=qa(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${Ya(n,o)}`):t.unshift(`${o}#${Ya(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||Ep(n.parentPath))break;n=n.parentPath}return t.join("/")}function kr(e){let t=e.openingElement.name;return t.type==="JSXIdentifier"?t.name==="Fragment":t.type==="JSXMemberExpression"&&t.property.name==="Fragment"}function Ya(e,t){let n=gp(e);if(!n)return 0;let r=Ir.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=Ir.get(n.node)?.get(t);if(!i){let s=Ir.get(n.node);s||(s=new Map,Ir.set(n.node,s)),i=new WeakMap,s.set(t,i)}for(let s of Rn(n))if(qa(s.node.openingElement)===t){if(i.set(s.node,o),s.node===e.node)return o;o++}return i.get(e.node)??0}function gp(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(kr(t.node)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Rn(e){let t=Ha.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(kr(o.node)){n.push(...Rn(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Rn(o));continue}o.isJSXExpressionContainer()&&n.push(...Yt(o.get("expression")))}return Ha.set(e.node,n),n}function Yt(e){return e.isJSXElement()?kr(e.node)?Rn(e):[e]:e.isJSXFragment()?Rn(e):e.isParenthesizedExpression()?Yt(e.get("expression")):e.isLogicalExpression()&&yp(e.node.operator)?Yt(e.get("right")):e.isConditionalExpression()?[...Yt(e.get("consequent")),...Yt(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Yt(t)):[]}function yp(e){return e==="&&"||e==="||"||e==="??"}function qa(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?xp(e.name):null}function xp(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 Cn(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 Ep(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function Sp(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function Ga(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 Za(e,t){return e.base===t.base&&bp(e.path,t.path??[])}function bp(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 Ip(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function kp(e){return e.exportKind==="named"?e.name:e.exportKind}function ye(e,t,n,r){return{ok:!1,diagnostic:Pt(t,n,e,r)}}function Rp(e,t){return Cn(e)!==t.component?!1:Go(e)===t.structuralPath}function Cp(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function Zo(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function vp(e,t){return e.isObjectProperty()?Ip(e.node)===t:!1}import Qo from"@babel/generator";var wp=typeof Qo=="function"?Qo:Qo.default;function Pp(e){let t=e.split(`
|
|
2
|
-
`),n=[],r=!1;for(let s of t){let a=s.match(/^(\s+)/);if(a){let c=a[1];c.includes(" ")?r=!0:c.length>0&&n.push(c.length)}}if(r&&t.every(a=>{let c=a.match(/^(\s+)/);return!c||c[1].includes(" ")}))return"tab";if(n.length===0)return"2";function o(s,a){return a===0?s:o(a,s%a)}let i=n[0];for(let s=1;s<n.length;s++)i=o(i,n[s]);return i>=4?"4":"2"}function
|
|
3
|
-
`).map(r=>
|
|
4
|
-
`)}function Rr(e){let{ast:t,source:n}=e;try{let r=Pp(n),i=wp(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=Tp(i,r)),{ok:!0,source:i}}catch(r){return $(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}import*as tc from"@babel/parser";import{arrayExpression as Np,booleanLiteral as Fp,identifier as Mp,jsxAttribute as _p,jsxExpressionContainer as Op,jsxIdentifier as Lp,nullLiteral as Dp,numericLiteral as Bp,objectExpression as jp,objectProperty as $p,stringLiteral as nc}from"@babel/types";function ec(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 vn(e,t,n){return{ok:!0,source:t,operation:{type:n.kind,nodeId:n.target,kind:n.kind,target:n.target,beforeSourceHash:ec(e),afterSourceHash:ec(t),inverse:n.inverse}}}function ce(e,t,n){let r=Rr({ast:e,source:t});return r.ok?vn(t,r.source,n):r}function xe(e,t){let n=Lo(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function Cr(e,t){return Rr({ast:e,source:t})}function Vp(e,t,n){let r=ne(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function rc(e,t,n){let r=Vp(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 oc(e,t){let n=ne(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 Zt(e){return typeof e=="string"?nc(e):typeof e=="number"?Bp(e):typeof e=="boolean"?Fp(e):e===null?Dp():Array.isArray(e)?Np(e.map(t=>Zt(t))):jp(Object.entries(e).map(([t,n])=>$p(Mp(t),Zt(n))))}function Up(e){return typeof e=="string"?nc(e):Op(Zt(e))}function vr(e,t){return _p(Lp(e),Up(t))}function ic(e,t){try{let r=tc.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 wr(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=xe(t,"jsx-node");if(!i.ok)return i.result;let s=ne(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let c=Kp(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=Jp(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 ce(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function Kp(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=Xp(r.get("expression"));o.length>0&&t.push(...o)}}return t}function Jp(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function Xp(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 qo}from"@babel/types";function Qt(e){let{source:t,locator:n}=e,r=xe(t,"jsx-node");if(!r.ok)return r.result;let o=ne(r.ast,n);return o.ok?(zp(o.match.path),ce(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function zp(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(qo());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(qo());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(qo());return}e.remove()}import{cloneNode as rm}from"@babel/types";import ei from"@babel/traverse";import*as V from"@babel/types";var Wp=typeof ei=="function"?ei:ei.default;function _e(e,t,n,r){if(!e.ok)return e;let o=Me(n);if(!o)return e;let i=Hp(t,o,r);return i?{...e,selectionRef:i}:e}function Hp(e,t,n){let r=Yp(e,t);if(!r)return;let o=n.sourceLocator?sc(n.sourceLocator):void 0,i=n.targetParentLocator?sc(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??Zp(r)??i?.component??o?.component;if(!(!s||!a))return{key:Sn(s,a,Qp(r))}}function sc(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function Yp(e,t){let n=null;return Wp(e,{JSXElement(r){r.node===t&&(n=r,r.stop())}}),n}function Me(e){if(!e)return null;if(V.isJSXElement(e))return qt(e)?ac(e.children):e;if(V.isJSXFragment(e))return ac(e.children);if(V.isJSXExpressionContainer(e)||V.isParenthesizedExpression(e)||V.isTSAsExpression(e)||V.isTSSatisfiesExpression(e)||V.isTSTypeAssertion(e)||V.isTSNonNullExpression(e))return Me(e.expression);if(V.isLogicalExpression(e))return Me(e.right);if(V.isConditionalExpression(e))return Me(e.consequent)??Me(e.alternate);if(V.isCallExpression(e)||V.isOptionalCallExpression(e))return fc(e)?Gp(e.arguments[0]):null;if(V.isArrayExpression(e))for(let t of e.elements){if(!t)continue;let n=Me(t);if(n)return n}return null}function ac(e){for(let t of e){let n=Me(t);if(n)return n}return null}function Gp(e){return!e||!V.isArrowFunctionExpression(e)&&!V.isFunctionExpression(e)?null:V.isBlockStatement(e.body)?wn(e.body.body):Me(e.body)}function wn(e){for(let t of e){if(V.isReturnStatement(t)){let n=Me(t.argument);if(n)return n;continue}if(V.isBlockStatement(t)){let n=wn(t.body);if(n)return n;continue}if(V.isIfStatement(t)){let n=cc(t.consequent);if(n)return n;let r=t.alternate?cc(t.alternate):null;if(r)return r;continue}if(V.isSwitchStatement(t))for(let n of t.cases){let r=wn(n.consequent);if(r)return r}}return null}function cc(e){return V.isBlockStatement(e)?wn(e.body):wn([e])}function Zp(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 lc=new WeakMap,uc=new WeakMap,ti=new WeakMap;function Qp(e){let t=lc.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=qp(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return lc.set(e.node,o),o}function qp(e){let t=ni(e.node.openingElement.name);return!t||qt(e.node)?null:/^[A-Z]/.test(t)?`component:${t}#${dc(e,t)}`:`${t}#${dc(e,t)}`}function dc(e,t){let n=em(e);if(!n)return 0;let r=ti.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=ti.get(n.node);o||(o=new Map,ti.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of Mt(n))if(ni(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 em(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(qt(t.node)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Mt(e){let t=uc.get(e.node);if(t)return t;let n=[],r=e.get("children");for(let o of r)if(!Array.isArray(o)){if(o.isJSXElement()){if(qt(o.node)){n.push(...Mt(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Mt(o));continue}o.isJSXExpressionContainer()&&n.push(...at(o.get("expression")))}return uc.set(e.node,n),n}function at(e){if(e.isJSXElement())return qt(e.node)?Mt(e):[e];if(e.isJSXFragment())return Mt(e);if(e.isParenthesizedExpression())return at(e.get("expression"));if(e.isLogicalExpression())return at(e.get("right"));if(e.isConditionalExpression())return[...at(e.get("consequent")),...at(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:at(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&fc(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?tm(n):[]}return[]}function tm(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return qt(t.node)?Mt(t):[t];if(t.isJSXFragment())return Mt(t);if(t.isParenthesizedExpression())return at(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return at(t);if(!t.isBlockStatement())return[];for(let n of t.get("body")){if(!n.isReturnStatement())continue;let r=n.get("argument");return r.node?at(r):[]}return[]}function fc(e){let t=e.callee;return(V.isMemberExpression(t)||V.isOptionalMemberExpression(t))&&V.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function qt(e){let t=ni(e.openingElement.name);return t==="Fragment"||t==="React.Fragment"}function ni(e){return V.isJSXIdentifier(e)?e.name:V.isJSXMemberExpression(e)?pc(e):V.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function pc(e){return`${V.isJSXIdentifier(e.object)?e.object.name:pc(e.object)}.${e.property.name}`}function mt(e,t){if(t.parentPath===e&&t.listKey==="children"&&mc(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!mc(n))return null;let r=n;for(;r&&r!==e;){if(!nm(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function mc(e){return e.isJSXElement()||e.isJSXFragment()}function nm(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 en(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=xe(t,"jsx-node");if(!a.ok)return a.result;let c=ne(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 A=c.match.path.node;if(!A.closingElement||A.openingElement.selfClosing)return $(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=ic(t,r.jsx);if(!u.ok)return u.result;let f=rm(u.node,!0),p=l.node.children,m={...s,targetParentLocator:n},S=A=>s?_e(A,a.ast,f,m):A;if(o==="append")return p.push(f),S(ce(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return p.unshift(f),S(ce(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 b=ne(a.ast,i);if(!b.ok)return{ok:!1,source:t,diagnostic:b.diagnostic};let k=mt(c.match.path,b.match.path);if(!k)return $(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");l=k;let R=l.node.children,w=R.findIndex(A=>A===b.match.path.node);return w===-1?$(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(R.splice(o==="before"?w:w+1,0,f),S(ce(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as hc from"@babel/parser";import{cloneNode as om}from"@babel/types";function Pr(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=xe(t,"jsx-node");if(!a.ok)return a.result;let c=im(t,r);if(!c.ok)return c.result;let l=ne(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 R=l.match.path.node;if(!R.closingElement||R.openingElement.selfClosing)return $(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=l.match.path,f=null;if(i){let R=ne(a.ast,i);if(!R.ok)return{ok:!1,source:t,diagnostic:R.diagnostic};let w=mt(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,f=R.match.path.node}else if(o==="before"||o==="after")return $(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let p=om(c.node,!0),m=u.node.children,S={...s,targetParentLocator:n},b=R=>s?_e(R,a.ast,p,S):R;if(o==="append")return m.push(p),b(ce(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return m.unshift(p),b(ce(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let k=m.findIndex(R=>R===f);return k===-1?$(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(m.splice(o==="before"?k:k+1,0,p),b(ce(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function im(e,t){try{let r=hc.parse(`const __VD_EXPR__ = <>{${t}}</>;`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],o=r?.type==="VariableDeclaration"?r.declarations[0]?.init:null,i=o?.type==="JSXFragment"?o.children[0]:void 0;return i?.type!=="JSXExpressionContainer"?{ok:!1,result:$(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 sm,nullLiteral as ri}from"@babel/types";import*as tn from"@babel/types";function nn(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=xe(t,"jsx-node");if(!a.ok)return a.result;let c=ne(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let l=ne(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 w=l.match.path.node;if(!w.closingElement||w.openingElement.selfClosing)return $(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let f=null;if(i){let w=ne(a.ast,i);if(!w.ok)return{ok:!1,source:t,diagnostic:w.diagnostic};let A=mt(l.match.path,w.match.path);if(!A)return $(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=A,f=w.match.path}else if(o==="before"||o==="after")return $(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let p=f&&typeof f.key=="number"?f.key:-1;if(f&&p===-1)return $(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let m=sm(c.match.path.node,!0);if(!tn.isJSXElement(m)&&!tn.isJSXExpressionContainer(m)&&!tn.isJSXFragment(m))return $(t,"unsupported-syntax","move-node source must resolve to a JSX child","jsx-node");let S=c.match.path.parentPath?.node===u.node&&typeof c.match.path.key=="number"?c.match.path.key:-1;if(f&&c.match.path.parentPath?.node===f.parentPath?.node&&c.match.path.key===f.key)return $(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");am(c.match.path);let b=u.node.children,k={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return b.push(m),_e(Cr(a.ast,t),a.ast,m,k);if(o==="prepend")return b.unshift(m),_e(Cr(a.ast,t),a.ast,m,k);let R=p-(S!==-1&&S<p?1:0);return b.splice(o==="before"?R:R+1,0,m),_e(Cr(a.ast,t),a.ast,m,k)}function am(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 gc from"@babel/parser";import{cloneNode as cm,nullLiteral as oi}from"@babel/types";function Ar(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,c=xe(t,"jsx-node");if(!c.ok)return c.result;let l=lm(t,s);if(!l.ok)return l.result;let u=ne(c.ast,n);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};let f=ne(c.ast,r);if(!f.ok)return{ok:!1,source:t,diagnostic:f.diagnostic};if(!f.match.path.isJSXElement()&&!f.match.path.isJSXFragment())return $(t,"unsupported-syntax","move-repeat-template-child target parent must be a JSXElement or JSXFragment","jsx-node");if(f.match.path.isJSXElement()){let A=f.match.path.node;if(!A.closingElement||A.openingElement.selfClosing)return $(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let p=f.match.path,m=null;if(i){let A=ne(c.ast,i);if(!A.ok)return{ok:!1,source:t,diagnostic:A.diagnostic};let H=mt(f.match.path,A.match.path);if(!H)return $(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");p=H,m=A.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 S=p.node,b=cm(l.node,!0);um(u.match.path);let k={...a,sourceLocator:n,targetParentLocator:r},R=S.children;if(o==="append")return R.push(b),_e(ce(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,b,k);if(o==="prepend")return R.unshift(b),_e(ce(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,b,k);let w=R.findIndex(A=>A===m);return w===-1?$(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(R.splice(o==="before"?w:w+1,0,b),_e(ce(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,b,k))}function lm(e,t){try{let r=gc.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 um(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(oi());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(oi());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(oi());return}e.remove()}function Tr(e){let{source:t,locator:n,props:r}=e,o=xe(t,"jsx-node");if(!o.ok)return o.result;let i=rc(o.ast,n,t);if(!i.ok)return i.result;let s=i.match.path.node.openingElement;for(let[a,c]of Object.entries(r)){if(c===void 0)continue;let l={kind:"jsx-attribute",element:n,name:a},u=oc(o.ast,l);if(u.ok&&u.match!==null){let f=u.match.path.node;f.value=c===""?vr(a,"").value:vr(a,c).value}else s.attributes.push(vr(a,c))}return ce(o.ast,t,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}import{getBindingIdentifiers as dm,identifier as Pn,importDeclaration as fm,importDefaultSpecifier as pm,importNamespaceSpecifier as mm,importSpecifier as hm,isImportDefaultSpecifier as yc,isImportNamespaceSpecifier as xc,isImportSpecifier as Ec,stringLiteral as gm}from"@babel/types";function rn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(k=>!Cm(k));if(o!==-1){let k=r[o],R=k&&typeof k=="object"&&"kind"in k?k.kind:void 0;return $(t,"unsupported-syntax",`Unsupported import spec kind: ${String(R)}`)}let i=Im(r);if(!i.ok)return $(t,"unsupported-syntax",i.message);let s=xe(t);if(!s.ok)return s.result;let{ast:a}=s,c=a.program,l=c.body.filter(k=>k.type==="ImportDeclaration"&&k.source.value===n),u=new Set(l.flatMap(k=>k.specifiers.flatMap(R=>{let w=vm(k,R);return w?[w]:[]}))),f=i.imports.filter(k=>!u.has(Cc(k)));if(f.length===0)return vn(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let p=km(c.body),m=f.find(k=>p.has(ii(k)));if(m)return $(t,"unsupported-syntax",`Import local binding already exists: ${ii(m)}`);let S=bm(f);if(S.reduce((k,R)=>k+R.length,0)!==f.length)return $(t,"unsupported-syntax","Unsupported import specifier grouping");for(let k of S){if(!kc(bc(k)))return $(t,"unsupported-syntax","Unsupported import specifier combination");let R=l.find(w=>ym(w,k));if(R)xm(R,k);else{let w=fm(Sc(k),gm(n));Rm(c.body,w),l.push(w)}}return ce(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function ym(e,t){return e.importKind==="type"?!1:kc(Sm(Em(e),bc(t)))}function xm(e,t){let n=!1,r=new Set(e.specifiers.map(o=>si(o)));for(let o of Sc(t)){let i=si(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return Rc(e.specifiers),{changed:n}}function Sc(e){let t=e.map(n=>{switch(n.kind){case"named":return hm(n.local?Pn(n.local):Pn(n.imported),Pn(n.imported));case"default":return pm(Pn(n.local));case"namespace":return mm(Pn(n.local));default:return n}});return Rc(t),t}function bc(e){let t=Ic();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 Em(e){let t=Ic();for(let n of e.specifiers)yc(n)?t.defaultLocals.add(n.local.name):xc(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function Ic(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function Sm(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function kc(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function Rc(e){let t=[...e.filter(n=>yc(n)),...e.filter(n=>xc(n)),...e.filter(n=>Ec(n))];e.splice(0,e.length,...t)}function bm(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 Im(e){let t=new Map,n=new Map;for(let r of e){let o=Cc(r);if(t.has(o))continue;let i=ii(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 km(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(dm(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 Rm(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 Cm(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 Cc(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 ii(e){return e.kind==="named"?e.local??e.imported:e.local}function vm(e,t){return e.importKind==="type"||Ec(t)&&t.importKind==="type"?null:si(t)}function si(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 on(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(u=>!Pm(u));if(o!==-1){let u=r[o],f=u&&typeof u=="object"&&"kind"in u?u.kind:void 0;return $(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(f)}`)}let i=xe(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 vn(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let l=a.body[c];return r.length===0?(a.body.splice(c,1),ce(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(l.specifiers=l.specifiers.filter(u=>!r.some(f=>wm(u,f))),l.specifiers.length===0&&a.body.splice(c,1),ce(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function wm(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 Pm(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 An(e){let{source:t,locator:n,next:r}=e,o=_r(t,n);return o.ok?(o.path.replaceWith(Zt(r)),ce(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function Nr(e){let{source:t,locator:n,index:r,value:o}=e,i=_r(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,Zt(o)),ce(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 Fr(e){let{source:t,locator:n,index:r}=e,o=_r(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),ce(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 Mr(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=_r(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),ce(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function _r(e,t){let n=xe(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=ne(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 Tm=typeof ai=="function"?ai:ai.default;function ui(e){let t=Fc(e);if(t)return{ok:!1,error:t};let n=e.projection,r=di(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:wc(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=st(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?[]:[Or(c.diagnostic)]}};let l=Lr(e.source,c.match.node.start??null,c.match.node.end??null);if(Mm(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=wc(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 wc(e){let t=Fm(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 Tc(e){let t;try{t=Dr.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=Dr.parseExpression(e.jsx,{plugins:["jsx","typescript"]}),r=!1;return(typeof ci=="function"?ci:ci.default)(t,{ExportDefaultDeclaration(i){let s=i.get("declaration"),a=Nm(i,s);if(a){if(a.isArrowFunctionExpression()&&!a.get("body").isBlockStatement()){let c=a.get("body");c.replaceWith(Pc(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(Pc(l.node,n,e.placement,e.replaceOriginal===!0)),r=!0,c.stop())}}),r&&i.stop()}}}),r?{ok:!0,source:Tm(t,{}).code}:{ok:!1,source:e.source,diagnostic:{message:"Route default return boundary could not be resolved."}}}function Nm(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 Pc(e,t,n,r){if(ht.isNullLiteral(e)||r)return t;let s=n==="before"||n==="prepend"?[t,e]:[e,t];return ht.jsxFragment(ht.jsxOpeningFragment(),ht.jsxClosingFragment(),s)}function Nc(e){let t=Fc(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=Mc(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=li(o.sourceRange),s=st(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?[]:[Or(s.diagnostic)]}};if(Lr(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=di(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 f=li(u),p=st(e.source,f);if(!p.ok||!p.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:p.ok===!1?p.diagnostic.message:"Route page composition target container could not be resolved.",diagnostics:p.ok?[]:[Or(p.diagnostic)]}};if(Lr(e.source,p.match.node.start??null,p.match.node.end??null)!==l.containerSourceHash)return Ac("Route page composition target container hash no longer matches the current source.");if(l.relation==="before"||l.relation==="after"){let S=l.anchorSourceRange,b=l.anchorSourceHash;if(!S||!b)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable anchor boundary.",diagnostics:[]}};let k=li(S),R=st(e.source,k);return!R.ok||!R.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:R.ok===!1?R.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:R.ok?[]:[Or(R.diagnostic)]}}:Lr(e.source,R.match.node.start??null,R.match.node.end??null)!==b?Ac("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:f,anchorLocator:k,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:f,placement:l.relation}}}}function Ac(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Or(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function Fc(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 Fm(e,t){let n=vc.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=vc.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function li(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function Lr(e,t,n){return t==null||n==null?null:`sha256:${Am("sha256").update(e.slice(t,n)).digest("hex")}`}function Mm(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 _m=typeof fi=="function"?fi:fi.default;function Oc(e){if(!e.ast)return Qe(e,[Ce("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=Um(e.ast);if(!t)return Qe(e,[Ce("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=Jm(t);if(n.length===0)return Qe(e,[Ce("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")]);if(n.length>1)return Qe(e,[Ce("MULTIPLE_PAGE_RETURNS","Route default export contains multiple page-level return statements",{returnCount:n.length})]);let r=Xm(n[0].argument);if(!r)return Qe(e,[Ce("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})]);if(r.isNullLiteral())return _c(e,t,"virtual-route-root");if(zm(r,t))return Qe(e,[Ce("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(Wm(r,t)||Hm(r)&&!e.source.includes("DESIGN_PLAN_REPLACE_ME"))return Qe(e,[Ce("UNSUPPORTED_PAGE_SHAPE","Route default export shape does not provide a single safe placement boundary",{reason:"ambiguous-placement"})]);if(r.isJSXFragment()){let i=yt(r);if(i.unsupported)return Qe(e,[Ce("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);let s=pi({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-fragment",source:e.source,containerPath:r,members:i.members});return Br(e,t,s,{kind:"virtual-route-root",sourceKind:"jsx-fragment"})}if(r.isJSXElement()&&!sn(r)){let i=gi(r),s=pi({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[i]});return Br(e,t,s,{kind:"virtual-route-root",sourceKind:"jsx-element"})}if(r.isJSXElement()){let i=yt(r);if(i.unsupported)return Qe(e,[Ce("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);let s=i.members;if(Gm(e.source,r,s))return _c(e,t,"starter-placeholder");let a=pi({input:e,containerKind:"jsx-container",sourceKind:"jsx-element",source:e.source,containerPath:r,members:s});return Br(e,t,a,{kind:"jsx-container",sourceKind:"jsx-element"})}if(Ym(r))return Qe(e,[Ce("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);let o=Qm({input:e,source:e.source,expression:r});return Br(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"})}function di(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Ce("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:Ce("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function Mc(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Ce("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:Ce("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function Lc(e){return e.ok?Om(e.projection):Lm(e.projection)}function Om(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 f=u.members.flatMap((b,k)=>Dc(e,u,b,k,e.container.placementKey)),p=f.filter(({member:b})=>b.isBusinessMember).map(({sourceMember:b})=>Bm(l,b,u.independent)),m=f.length>0?f:[{sourceMember:{key:`source:${l}:empty`,kind:e.container.kind==="starter-placeholder"?"starter-placeholder":"null-return",containerKey:e.container.placementKey,label:"empty-page",sourceFile:e.entryFile,isAtomic:!0},member:null}];r.set(l,m.map(({sourceMember:b})=>b)),o.set(l,p);let S=m[0]?.sourceMember.key??l;n.push({key:l,containerKey:S,businessMemberKeys:p.map(b=>b.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:Dm(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function Lm(e){let t=e.diagnostics.map(jm);return{status:"unsupported",version:e.version,routeId:e.route,reason:$m(e.diagnostics),diagnostics:t}}function Dm(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 Dc(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)=>Dc(e,t,a,c,i))]}function Bm(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function jm(e){return{code:Vm(e),message:e.message}}function $m(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 Vm(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 Um(e){let t=null;return _m(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=Km(o.path);i&&(t=i,n.stop())}}),t}function Km(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 Jm(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 Xm(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 zm(e,t){if(e.isIdentifier())return jr(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return jr(n.node.name,t)}return!1}function Wm(e,t){return e.isConditionalExpression()?gt(e.get("consequent"),t)||gt(e.get("alternate"),t):e.isLogicalExpression()?gt(e.get("left"),t)||gt(e.get("right"),t):!1}function Hm(e){if(!e.isJSXElement()||!sn(e))return!1;let t=yt(e).members;if(t.length!==1)return!1;let n=t[0];return n.kind==="jsx-element"&&!n.isBusinessMember&&n.businessMemberCount>0}function gt(e,t){if(e.isIdentifier())return jr(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return jr(n.node.name,t)}return e.isConditionalExpression()?gt(e.get("consequent"),t)||gt(e.get("alternate"),t):e.isLogicalExpression()?gt(e.get("left"),t)||gt(e.get("right"),t):!1}function jr(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 Ym(e){return e.isJSXSpreadChild()}function Gm(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&hi(t)}function hi(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(!hi(t))return!1;continue}if(t.isJSXElement()&&!hi(t))return!1}return!0}function yt(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:yi(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:$e(r.node.loc),businessMemberCount:0,parentSourceRange:$e(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=yt(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=sn(o)?yt(o):null;n||=i?.unsupported??!1,t.push({...gi(o,i?.members),sourceRange:$e(r.node.loc),parentSourceRange:$e(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:yi(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:$e(r.node.loc),businessMemberCount:1,parentSourceRange:$e(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&Bc(r)){let o=yt(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=sn(r)?yt(r):null;n||=o?.unsupported??!1,t.push({...gi(r,o?.members),parentSourceRange:$e(e.node.loc)})}}return{members:t,unsupported:n}}function gi(e,t){let n=e.isJSXElement()&&sn(e)?t??yt(e).members:[],r=e.isJSXElement()&&!sn(e)&&!Bc(e);return{memberKey:yi(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:$e(e.node.loc),businessMemberCount:r?1:jc(n),parentSourceRange:$e(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:Zm(e)}}function Bc(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 Zm(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 jc(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function $r(e){return e.length===0?0:Math.max(1,jc(e))}function pi(e){let t=$e(e.containerPath.node.loc),n=Vc(e.source,e.containerPath.node.start,e.containerPath.node.end),r=Oe(e.input,e.containerKind,e.sourceKind,t),o=Oe(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:$r(e.members)<=1,memberCount:$r(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function Qm(e){let t=$e(e.expression.node.loc),n=Vc(e.source,e.expression.node.start,e.expression.node.end),r=Oe(e.input,"virtual-route-root","atomic-expression",t),o=Oe(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:Oe(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 Br(e,t,n,r){let o=n.containerSourceRange??n.sourceRange,i=qm(e,n,o),s=Wo(i),a={status:"supported",route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Uc(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 qm(e,t,n){if(t.members.length===0)return[t];let r=[],o=(l,u,f,p,m,S,b=n)=>({...t,placementKey:u,placementUnitKey:f,containerKey:t.placementKey,independent:$r(S)<=1,memberCount:$r(S),sourceRange:p,sourceHash:p?mi(e.source,p):null,relation:l,containerSourceRange:b,containerSourceHash:b?mi(e.source,b):null,anchorSourceRange:m,anchorSourceHash:m?mi(e.source,m):null,members:S}),i=t.placementKey,s=t.members.map(l=>Oe(e,i,"placement-unit",l.sourceRange)),a=s[0]??t.placementUnitKey,c=s.at(-1)??t.placementUnitKey;r.push(o("prepend",Oe(e,i,"prepend",n),a,n,null,[]));for(let l of t.members){let u=l.parentSourceRange??n,f=Oe(e,i,"placement-unit",l.sourceRange);r.push(o("before",Oe(e,f,"before",l.sourceRange),f,l.sourceRange,l.sourceRange,[l],u)),r.push(o("after",Oe(e,f,"after",l.sourceRange),f,l.sourceRange,l.sourceRange,[l],u))}return r.push(o("append",i,c,n,null,[])),r}function _c(e,t,n){let r=Oe(e,n,"empty-container",void 0),o=Oe(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=Wo([i]),a={status:"supported",route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Uc(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 Qe(e,t){return{ok:!1,projection:{status:"unsupported",route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,diagnostics:t}}}function Ce(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function Oe(e,t,n,r){return $c([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function yi(e,t,n){return $c(["member",e,String(t??-1),String(n??-1)])}function $c(e){return`pc_${xi("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function Vc(e,t,n){return t==null||n==null?null:`sha256:${xi("sha256").update(e.slice(t,n)).digest("hex")}`}function mi(e,t){let n=[0];for(let i=0;i<e.length;i+=1)e.charCodeAt(i)===10&&n.push(i+1);let r=n[t.startLine-1],o=n[t.endLine-1];return r===void 0||o===void 0?null:`sha256:${xi("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function $e(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function Uc(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 th(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var nh=160;function Kc(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})}return{routeId:e.routeId,version:e.version,rootKeys:[...e.rootKeys],entries:o}}function Jc(e,t,n,r,o,i,s,a,c,l,u,f){let p=t.elements.get(e),m=n.nodes.get(e),S=r.get(e);if(!p||!m||!S)throw new Error(`Node not found: ${e}`);let b=sh(p.textSegments,s),k=ah(e,t,p,S,b),R=b?lh(b):void 0,w=uh(i,b),A=p.textSegments.map(N=>({index:N.index,value:N.value,editable:ch(N,S,s?.get(N.index)??null),source:o.get(N.index)??null})),H=[],se=p.parentKey;for(;se;){let N=t.elements.get(se);if(!N)break;H.push({key:se,tag:N.tag,label:N.tag}),se=N.parentKey}H.reverse();let ue=p.childKeys.map(N=>{let B=t.elements.get(N);return B?{key:N,tag:B.tag,label:B.tag}:null}).filter(N=>N!==null),v=[];if(p.parentKey){let N=t.elements.get(p.parentKey);if(N)for(let B of N.childKeys){if(B===e)continue;let j=t.elements.get(B);j&&v.push({key:B,tag:j.tag,label:j.tag})}}return{key:e,tag:p.tag,componentName:p.componentName,sourceFile:p.sourceFile,sourceLocator:rh(p),label:p.tag,capabilities:k,writeTarget:i,effectiveWriteTarget:w,provenanceChain:R,componentSemantic:c,contentModel:l,mediaModel:u,styleSource:f,conditional:a,textSegments:A,boundaryKind:p.boundaryKind,isOpaque:p.isOpaque,ancestors:H,children:ue,siblings:v}}function rh(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:oh(e.sourceRange),structuralPath:e.identity.structuralPath,...ih(e.textSegments)}}function oh(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function ih(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,nh)}:{}}function Xc(e,t){let n=t.find(r=>r.editable&&r.source&&r.source.kind!=="literal");return n?.source?{kind:"value-binding",file:n.source.file,componentName:e.componentName,isProxy:n.source.file!==e.file}:{kind:"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function sh(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function ah(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&&zc(c.mode);return{...r,canUpdateText:l,editModes:{updateText:c,insertChild:r.canInsertChild?{mode:"direct",reasonCode:i||s?"repeat-template":void 0}:{mode:"unsupported",reasonCode:"capability-denied"},move:r.canMove?{mode:s?"proxy":"direct",reasonCode:s?"repeat-collection":void 0}:{mode:"unsupported",reasonCode:"capability-denied"},remove:r.canRemove?{mode:s?"proxy":"direct",reasonCode:s?"repeat-collection":void 0}:{mode:"unsupported",reasonCode:"capability-denied"}}}}function ch(e,t,n){return!e.editable||!t.canUpdateText?!1:n?zc(n.editMode):!0}function zc(e){return e==="direct"||e==="proxy"||e==="upstream"}function lh(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 uh(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}:th(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 Wc(e){let{key:t,element:n,graph:r,provenances:o}=e,i=fh(t,n,r),s=i?.tag??(_t(n.tag)?n.tag:n.componentName),a=i?.identity.key??Hc(n,r)??t,c=hh(i),l=gh(t,n,r,o,i),u=dh(t,n,r,o,a);return{componentName:s,instanceKey:a,templateOwner:mh(i??n,s),...c.length>0?{variantKeys:c}:{},...l.length>0?{slotKeys:l}:{},editableStrategy:u,impactScope:yh(u),alternativeStrategies:xh(u)}}function dh(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return Ei(e,n)?"instance":!_t(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function Hc(e,t){if(_t(e.tag))return e.identity.key;let n=[...t.elements.values()].filter(r=>r.importedFrom===e.sourceFile&&ph(r,e.componentName));return n.length!==1?null:n[0].identity.key}function fh(e,t,n){if(_t(t.tag))return t;let r=Ei(e,n);if(r)return r;let o=Hc(t,n);return o?n.elements.get(o)??null:null}function ph(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function mh(e,t){return _t(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function hh(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 gh(e,t,n,r,o){let i=new Set,s=Ei(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&&_t(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function Ei(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(_t(r.tag))return r;n=r.parentKey}return null}function _t(e){return/^[A-Z]/.test(e)}function yh(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function xh(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}var Eh=new Set(["markdown","body","content","value","document"]),Yc=[];function Zc(e){if(!(!Ih(e.tag)||!e.attributes))for(let t of e.attributes){if(!Eh.has(t.name))continue;if(bh(t))return{kind:"markdown",field:t.name,schema:"markdown",valuePath:t.source?.expression,operationBoundary:Yc};let n=Sh(t.resolvedValue);if(n==="prosemirror-doc"||n==="node-array")return{kind:"rich-text-json",field:t.name,valuePath:t.source?.expression,schema:n,operationBoundary:Yc};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 Sh(e){if(e){if(Array.isArray(e)&&e.every(t=>Gc(t)))return"node-array";if(Gc(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 Gc(e){return!Array.isArray(e)&&typeof e=="object"&&e!==null}function bh(e){return e.name==="markdown"}function Ih(e){return/^[A-Z]/.test(e)}var kh=["src","alt","poster","caption","width","height"];function Qc(e){let t=e.attributes?.filter(i=>kh.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=Ch(t.map(i=>i.value));return{kind:Rh(e.tag,n),sourceType:o,fields:n,editableFields:[],operationBoundary:[],...Object.keys(r).length>0?{valuePaths:r}:{}}}function Rh(e,t){return e==="img"?"image":e==="video"||t.includes("poster")?"video":"media"}function Ch(e){return e.some(t=>t.startsWith("cms:"))?"cms-media-field":e.some(t=>/^(\.?\/|\/)/.test(t))?"local-file-reference":"asset-id"}var Si=["set-class-name-source","apply-style-draft"],qc=["block","inline-block","inline","flex","inline-flex","grid","inline-grid","hidden"],el=["static","fixed","absolute","relative","sticky"],Ci=["z-auto","z-0","z-10","z-20","z-30","z-40","z-50"],tl=["flex-row","flex-row-reverse","flex-col","flex-col-reverse"],nl=["flex-nowrap","flex-wrap","flex-wrap-reverse"],bi=["grow","grow-0"],Ii=["shrink","shrink-0"],vi=["basis-auto","basis-full","basis-1/2","basis-1/3","basis-2/3","basis-1/4","basis-3/4","basis-px"],wi=["order-first","order-last","order-none","order-1","order-2","order-3","order-4","order-5","order-6"],Pi=["grid-cols-1","grid-cols-2","grid-cols-3","grid-cols-4","grid-cols-5","grid-cols-6","grid-cols-12","grid-cols-none","grid-cols-subgrid"],Ai=["grid-rows-1","grid-rows-2","grid-rows-3","grid-rows-4","grid-rows-5","grid-rows-6","grid-rows-none","grid-rows-subgrid"],Ti=["col-auto","col-span-1","col-span-2","col-span-3","col-span-4","col-span-6","col-span-12","col-span-full"],Ni=["row-auto","row-span-1","row-span-2","row-span-3","row-span-4","row-span-6","row-span-full"],rl=["items-start","items-end","items-center","items-baseline","items-stretch"],ol=["justify-normal","justify-start","justify-end","justify-center","justify-between","justify-around","justify-evenly","justify-stretch"],il=["overflow-auto","overflow-hidden","overflow-clip","overflow-visible","overflow-scroll"],ki=["font-sans","font-serif","font-mono"],Fi=["font-thin","font-extralight","font-light","font-normal","font-medium","font-semibold","font-bold","font-extrabold","font-black"],Mi=["text-xs","text-sm","text-base","text-lg","text-xl","text-2xl","text-3xl","text-4xl","text-5xl","text-6xl","text-7xl","text-8xl","text-9xl"],_i=["text-left","text-center","text-right","text-justify","text-start","text-end"],sl=["uppercase","lowercase","capitalize","normal-case"],al=["underline","overline","line-through","no-underline"],Oi=["indent-0","indent-4","indent-8","indent-12"],cl=["[writing-mode:horizontal-tb]","[writing-mode:vertical-rl]"],ll=["whitespace-normal","whitespace-nowrap","whitespace-pre","whitespace-pre-line","whitespace-pre-wrap","whitespace-break-spaces"],ul=["break-normal","break-words","break-all","break-keep"],Li=["line-clamp-none","line-clamp-1","line-clamp-2","line-clamp-3","line-clamp-4","line-clamp-5","line-clamp-6"],Ri=["tracking-tighter","tracking-tight","tracking-normal","tracking-wide","tracking-wider","tracking-widest"],Di=["border-solid","border-dashed","border-dotted","border-double","border-hidden","border-none"],Bi=["border","border-0","border-2","border-4","border-8"],dl=["object-contain","object-cover","object-fill","object-none","object-scale-down"],ji=["aspect-auto","aspect-square","aspect-video"],$i=["shadow-none","shadow-sm","shadow","shadow-md","shadow-lg","shadow-xl","shadow-2xl"],Xk=[{property:"display",exact:qc,isMatch:e=>e==="gallery-item",options:[...qc]},{property:"position",exact:el,isMatch:e=>e==="cta-shine",options:[...el]},{property:"top",isMatch:e=>Vr("top",e)},{property:"right",isMatch:e=>Vr("right",e)},{property:"bottom",isMatch:e=>Vr("bottom",e)},{property:"left",isMatch:e=>Vr("left",e)},{property:"zIndex",exact:Ci,isMatch:_h,options:[...Ci]},{property:"flexDirection",exact:tl,options:[...tl]},{property:"flexWrap",exact:nl,options:[...nl]},{property:"flexGrow",exact:bi,isMatch:e=>bi.includes(e)||/^grow-\[.+\]$/.test(e),options:[...bi]},{property:"flexShrink",exact:Ii,isMatch:e=>Ii.includes(e)||/^shrink-\[.+\]$/.test(e)||/^flex-shrink-(?:0|\[.+\])$/.test(e),options:[...Ii]},{property:"flexBasis",exact:vi,isMatch:Ph,options:[...vi]},{property:"flex",isMatch:e=>/^flex-(?:\d+|auto|initial|none|\[.+\])$/.test(e)},{property:"order",exact:wi,isMatch:Ah,options:[...wi]},{property:"gridTemplateColumns",exact:Pi,isMatch:Th,options:[...Pi]},{property:"gridTemplateRows",exact:Ai,isMatch:Nh,options:[...Ai]},{property:"columns",isMatch:e=>e==="gallery-grid"||/^columns-(?:\d+|auto|3xs|2xs|xs|sm|md|lg|xl|2xl|3xl|4xl|5xl|6xl|7xl|\[.+\])$/.test(e)},{property:"gridColumn",exact:Ti,isMatch:Fh,options:[...Ti]},{property:"gridRow",exact:Ni,isMatch:Mh,options:[...Ni]},{property:"gap",prefix:"gap-",isMatch:e=>e.startsWith("gap-")&&!e.startsWith("gap-x-")&&!e.startsWith("gap-y-")},{property:"gapX",prefix:"gap-x-"},{property:"gapY",prefix:"gap-y-"},{property:"spaceX",prefix:"space-x-"},{property:"spaceY",prefix:"space-y-"},{property:"alignItems",exact:rl,options:[...rl]},{property:"alignSelf",isMatch:e=>/^self-(?:auto|start|end|center|stretch|baseline)$/.test(e)},{property:"justifyContent",exact:ol,options:[...ol]},{property:"marginTop",prefix:"mt-",isMatch:e=>xt("m","t",e)},{property:"marginRight",prefix:"mr-",isMatch:e=>xt("m","r",e)},{property:"marginBottom",prefix:"mb-",isMatch:e=>xt("m","b",e)},{property:"marginLeft",prefix:"ml-",isMatch:e=>xt("m","l",e)},{property:"paddingTop",prefix:"pt-",isMatch:e=>xt("p","t",e)},{property:"paddingRight",prefix:"pr-",isMatch:e=>xt("p","r",e)},{property:"paddingBottom",prefix:"pb-",isMatch:e=>xt("p","b",e)},{property:"paddingLeft",prefix:"pl-",isMatch:e=>xt("p","l",e)},{property:"width",prefix:"w-",isMatch:e=>e.startsWith("w-")||fl(e)},{property:"height",prefix:"h-",isMatch:e=>e.startsWith("h-")||fl(e)},{property:"minWidth",prefix:"min-w-"},{property:"minHeight",prefix:"min-h-"},{property:"maxWidth",isMatch:e=>e==="container"||e.startsWith("max-w-")},{property:"maxHeight",prefix:"max-h-"},{property:"overflow",exact:il,isMatch:e=>/^overflow(?:-[xy])?-.+$/.test(e),options:[...il]},{property:"fontFamily",exact:ki,isMatch:e=>ki.includes(e)||/^font-\[.+\]$/.test(e)||/^font-[a-z][\w-]*$/.test(e)&&!$h(e),options:[...ki]},{property:"fontSize",exact:Mi,isMatch:ml,options:[...Mi]},{property:"fontWeight",exact:Fi,options:[...Fi]},{property:"lineHeight",prefix:"leading-"},{property:"letterSpacing",exact:Ri,isMatch:e=>Ri.includes(e)||e.startsWith("tracking-["),options:[...Ri]},{property:"textAlign",exact:_i,options:[..._i]},{property:"textTransform",exact:sl,options:[...sl]},{property:"textDecoration",exact:al,options:[...al]},{property:"textOverflow",exact:["truncate","text-ellipsis","text-clip"]},{property:"fontStyle",exact:["italic","not-italic"]},{property:"textUnderlineOffset",prefix:"underline-offset-"},{property:"textIndent",exact:Oi,isMatch:Dh,options:[...Oi]},{property:"writingMode",exact:cl,options:[...cl]},{property:"whiteSpace",exact:ll,options:[...ll]},{property:"wordBreak",exact:ul,options:[...ul]},{property:"lineClamp",exact:Li,isMatch:Lh,options:[...Li]},{property:"fontVariantNumeric",isMatch:e=>/^(?:normal-nums|ordinal|slashed-zero|lining-nums|oldstyle-nums|proportional-nums|tabular-nums|diagonal-fractions|stacked-fractions)$/.test(e)},{property:"screenReaderOnly",exact:["sr-only","not-sr-only"]},{property:"color",isMatch:vh},{property:"backgroundColor",isMatch:wh},{property:"backgroundImage",isMatch:e=>e.startsWith("bg-[url")||e.startsWith("bg-gradient-")},{property:"borderStyle",exact:Di,options:[...Di]},{property:"borderWidth",exact:Bi,isMatch:hl,options:[...Bi]},{property:"divideWidth",isMatch:e=>/^divide-[xy](?:-\d+|-0|-reverse)?$/.test(e)},{property:"borderRadius",prefix:"rounded"},{property:"borderColor",isMatch:Oh},{property:"divideColor",isMatch:e=>e.startsWith("divide-")&&!/^divide-[xy](?:-\d+|-0|-reverse)?$/.test(e)},{property:"objectFit",exact:dl,options:[...dl]},{property:"objectPosition",isMatch:e=>/^object-(?:bottom|center|left|left-bottom|left-top|right|right-bottom|right-top|top|\[.+\])$/.test(e)},{property:"aspectRatio",exact:ji,isMatch:Bh,options:[...ji]},{property:"opacity",prefix:"opacity-"},{property:"boxShadow",exact:$i,isMatch:jh,options:[...$i]},{property:"transform",isMatch:Vh},{property:"transformOrigin",isMatch:e=>/^origin-(?:center|top|top-right|right|bottom-right|bottom|bottom-left|left|top-left|\[.+\])$/.test(e)},{property:"transitionProperty",isMatch:e=>/^transition(?:-(?:none|all|colors|opacity|shadow|transform|\[.+\]))?$/.test(e)||["motion-link","image-zoom","card-lift","cta-shine","gallery-item-img","showcase-img"].includes(e)},{property:"transitionDuration",isMatch:e=>/^duration-(?:\d+|slow|\[.+\])$/.test(e)},{property:"transitionTimingFunction",isMatch:e=>/^ease-(?:linear|in|out|in-out|\[.+\])$/.test(e)},{property:"animation",isMatch:e=>/^(?:animate-.+|fade-.+|slide-in-.+)$/.test(e)||["section-reveal","scroll-reveal","first-viewport-entrance","media-reveal","media-entrance","gallery-fade-enter","number-pop"].includes(e)},{property:"pointerEvents",exact:["pointer-events-none","pointer-events-auto"]},{property:"cursor",isMatch:e=>/^cursor-(?:auto|default|pointer|wait|text|move|help|not-allowed|none|context-menu|progress|cell|crosshair|vertical-text|alias|copy|no-drop|grab|grabbing|all-scroll|col-resize|row-resize|n-resize|e-resize|s-resize|w-resize|ne-resize|nw-resize|se-resize|sw-resize|ew-resize|ns-resize|nesw-resize|nwse-resize|zoom-in|zoom-out|\[.+\])$/.test(e)},{property:"userSelect",exact:["select-none","select-text","select-all","select-auto"]},{property:"outlineStyle",isMatch:e=>/^outline(?:-(?:none|hidden|solid|dashed|dotted|double|\d+|\[.+\]))?$/.test(e)},{property:"resize",exact:["resize-none","resize","resize-y","resize-x"]},{property:"ringWidth",isMatch:e=>/^ring(?:-\d+|-\[.+\]|-inset)?$/.test(e)},{property:"ringColor",isMatch:e=>e.startsWith("ring-")&&!/^ring(?:-\d+|-\[.+\]|-inset)?$/.test(e)},{property:"backdropFilter",isMatch:e=>/^backdrop-(?:blur|brightness|contrast|grayscale|hue-rotate|invert|opacity|saturate|sepia)(?:-.+)?$/.test(e)},{property:"overscrollBehavior",isMatch:e=>/^overscroll(?:-[xy])?-(?:auto|contain|none)$/.test(e)},{property:"scrollMarginTop",prefix:"scroll-mt-"}];function pl(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:Si,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:Si,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:Si}}function ml(e){return Mi.includes(e)||/^text-\[.+\]$/.test(e)&&!Uh(e.slice(6,-1))}function vh(e){return!e.startsWith("text-")||_i.includes(e)?!1:!ml(e)}function wh(e){return e.startsWith("bg-")?!(e.startsWith("bg-gradient-")||e.startsWith("bg-[url")||["bg-fixed","bg-local","bg-scroll","bg-clip-border","bg-clip-padding","bg-clip-content","bg-clip-text","bg-origin-border","bg-origin-padding","bg-origin-content"].includes(e)):!1}function hl(e){return Bi.includes(e)||/^border-\[.+\]$/.test(e)||/^border-(?:x|y|t|r|b|l)(?:-\d+|-\[.+\])?$/.test(e)}function Vr(e,t){let n=e==="top"||e==="bottom"?"y":e==="right"||e==="left"?"x":"";return new RegExp(`^-?${e}-.+$`).test(t)||new RegExp(`^-?inset-${n}-.+$`).test(t)||/^-?inset-.+$/.test(t)}function Ph(e){return vi.includes(e)||/^basis-\[.+\]$/.test(e)}function Ah(e){return wi.includes(e)||/^-?order-(?:\d+|\[.+\])$/.test(e)}function Th(e){return Pi.includes(e)||/^grid-cols-\[.+\]$/.test(e)}function Nh(e){return Ai.includes(e)||/^grid-rows-\[.+\]$/.test(e)}function Fh(e){return Ti.includes(e)||/^(?:col|col-span|col-start|col-end)-.+$/.test(e)}function Mh(e){return Ni.includes(e)||/^(?:row|row-span|row-start|row-end)-.+$/.test(e)}function _h(e){return Ci.includes(e)||/^-?z-(?:\d+|\[.+\])$/.test(e)}function Oh(e){return e.startsWith("border-")?!(Di.includes(e)||hl(e)||e.startsWith("border-spacing-")||/^border-(?:x|y|t|r|b|l)(?:-|$)/.test(e)):!1}function Lh(e){return Li.includes(e)||/^line-clamp-\[.+\]$/.test(e)}function Dh(e){return Oi.includes(e)||/^-?indent-\[.+\]$/.test(e)}function Bh(e){return ji.includes(e)||/^aspect-\[.+\]$/.test(e)}function jh(e){return $i.includes(e)||/^shadow-(?:\[.+\]|[a-z][\w-]*)$/.test(e)}function $h(e){return Fi.includes(e)}function xt(e,t,n){let r=t==="t"||t==="b"?"y":"x";return new RegExp(`^-?${e}${t}-.+$`).test(n)||new RegExp(`^-?${e}${r}-.+$`).test(n)||new RegExp(`^-?${e}-.+$`).test(n)}function fl(e){return/^size-.+$/.test(e)}function Vh(e){return e==="transform"||e==="transform-gpu"||e==="transform-none"||e.startsWith("translate-")||e.startsWith("-translate-")||e.startsWith("scale-")||e.startsWith("-scale-")||e.startsWith("rotate-")||e.startsWith("-rotate-")||e.startsWith("skew-")||e.startsWith("-skew-")}function Uh(e){return e.startsWith("#")||e.startsWith("rgb")||e.startsWith("hsl")||e.startsWith("oklch")||e.startsWith("color(")}import{createHash as Kh}from"node:crypto";var Tn=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 ae(e){return`sha256:${Kh("sha256").update(e).digest("hex")}`}function xl(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:ae(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=Jh(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:ae(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:yl(r),version:{documentVersion:e.route.graph.version,contentHash:ae(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:gl(e.route.source,o),valueRaw:s?gl(e.route.source,s):null,attrRange:yl(o),diagnostics:[]}}function El(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 Jh(e,t){let n=Ze({source:e,profile:At({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=ne(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:Xh(t.sourceRange)});return!r.ok||r.match.node.type!=="JSXElement"?null:r.match.node}function Sl(e){let t=Ze({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 gl(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function yl(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 Xh(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}import*as rs from"@babel/parser";import Xi from"@babel/traverse";import*as y from"@babel/types";import*as lt from"node:path";import*as Cl from"@babel/parser";import Ki from"@babel/traverse";import*as an from"@babel/types";import*as X from"@babel/types";function Jr(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?Ur(n,t):null}if(e.isMemberExpression()){let n=Zh(e.node),r=zh(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?Ur(o,[...r,...t]):null}return e.isAwaitExpression()||Ui(e.node)?Et(qh(e.node),t,"awaited or fetched expression"):null}function zh(e){let t=[],n=e;for(;X.isMemberExpression(n);){if(n.computed)if(X.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(X.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(X.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return X.isIdentifier(n)?t:null}function Ur(e,t=[]){let n=Wh(e,t);if(n)return n;let r=Hh(e,t);if(r)return r;let o=Yh(e,t);return o||null}function Fn(e){return e?.kind==="api-source"}function Wh(e,t){if(e.path.isVariableDeclarator()&&X.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&Vi(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return Et(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&X.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(c=>X.isObjectProperty(c)&&kl(c)==="data"&&Nn(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&Vi(a.node))return Et(e.identifier.name,t,"query hook data binding")}let n=Gh(e);if(!n||kl(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()||!Vi(i.node)?null:Et(e.identifier.name,t,"query hook data binding")}function Hh(e,t){if(e.path.isVariableDeclarator()&&X.isArrayPattern(e.path.node.id)){let a=e.path.get("init");if(!a?.isCallExpression()||!Il(a.node))return null;let[c,l]=e.path.node.id.elements;return!X.isIdentifier(c)||c.name!==e.identifier.name||!X.isIdentifier(l)?null:bl(e,l.name)?Et(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()||!Il(o.node)||n.node.elements.findIndex(a=>a===e.path.node)!==0)return null;let s=n.node.elements[1];return X.isIdentifier(s)&&bl(e,s.name)?Et(e.identifier.name,t,"state setter is updated by API data"):null}function Yh(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()?Et(e.identifier.name,t,"awaited binding result"):Ui(r.node)?Et(e.identifier.name,t,"fetch-backed binding result"):null:null}function Gh(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 Nn(e,t){return X.isIdentifier(e)?e.name===t:X.isAssignmentPattern(e)?Nn(e.left,t):X.isObjectPattern(e)?e.properties.some(n=>X.isObjectProperty(n)?Nn(n.value,t):Nn(n.argument,t)):X.isArrayPattern(e)?e.elements.some(n=>!!n&&Nn(X.isRestElement(n)?n.argument:n,t)):!1}function bl(e,t){let n=!1,r=!1;return e.scope.path.traverse({CallExpression(i){Ui(i.node)&&(n=!0),(Qh(i.node.callee,t)||i.node.arguments.some(s=>X.isIdentifier(s)&&s.name===t))&&(r=!0)}}),n&&r}function Vi(e){let t=Xr(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function Il(e){return Xr(e.callee)==="useState"}function Ui(e){return Kr(e,t=>X.isCallExpression(t)&&Xr(t.callee)==="fetch")}function Zh(e){let t=e;for(;X.isMemberExpression(t);)t=t.object;return X.isIdentifier(t)?t.name:null}function kl(e){return e.computed?null:X.isIdentifier(e.key)?e.key.name:X.isStringLiteral(e.key)?e.key.value:null}function Xr(e){return X.isIdentifier(e)?e.name:X.isMemberExpression(e)&&X.isIdentifier(e.property)?e.property.name:null}function Qh(e,t){return Kr(e,n=>X.isIdentifier(n)&&n.name===t)}function Kr(e,t){if(t(e))return!0;let n=X.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(X.isNode(i)&&Kr(i,t))return!0;continue}if(X.isNode(o)&&Kr(o,t))return!0}return!1}function qh(e){return X.isIdentifier(e)?e.name:X.isCallExpression(e)?Xr(e.callee)??"api":X.isAwaitExpression(e)?"awaited-api":"api"}function Et(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:eg(e,t),reason:n}}function eg(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var vl=typeof Ki=="function"?Ki:Ki.default;function wl(e,t){let n=Al(e);if(!n)return{allowed:!0};let r=!1;return vl(n,{CallExpression(o){if(!Tl(o.node,t.sourceRange)||!tg(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||Fn(Jr(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function Pl(e,t){let n=Al(e);if(!n)return{allowed:!0};let r=!1;return vl(n,{JSXExpressionContainer(o){Tl(o.node,t.sourceRange)&&(an.isJSXEmptyExpression(o.node.expression)||(r=!0,o.stop()))}}),r?{allowed:!1,reason:"Cannot move subtree across files because it depends on local binding expressions"}:{allowed:!0}}function Al(e){try{return Cl.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function tg(e){let t=e.callee;return an.isMemberExpression(t)&&an.isIdentifier(t.property)&&t.property.name==="map"}function Tl(e,t){let n=e.loc;return n?Rl({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&Rl({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function Rl(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 oe from"@babel/types";function Nl(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 qe(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return Ot(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(oe.isObjectPattern(n)||oe.isArrayPattern(n))return Ot(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(rg(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function Ot(e,t,n=!1){return oe.isIdentifier(e)?e.name===t&&n:oe.isObjectPattern(e)?e.properties.some(r=>oe.isObjectProperty(r)?Ot(r.value,t,n):Ot(r.argument,t,n)):oe.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=oe.isRestElement(r)?r.argument:r;return Ot(o,t,n)}):oe.isAssignmentPattern(e)?Ot(e.left,t,!0):oe.isRestElement(e)?Ot(e.argument,t,n):!1}function cn(e,t){if(e.path.isObjectPattern()){if(t){let r=Ve(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:qe(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:qe(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=Fl(r),i=!1,s=o?o.initBinding&&Ji(o.initBinding)?(i=qe(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=cn(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=Ve(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||qe(e)}}}}let n=sg(e);if(n){let r=ng(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||qe(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=og(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:qe(e)}}let i=Mn(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:qe(e)}:null}if(Ji(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:qe(e)}}return null}function ng(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=Fl(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=Ji(i)?(a=qe(i),[...s]):(()=>{let u=cn(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=Ve(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||qe(t)}:null}function Fl(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=ag(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function Ji(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function rg(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function og(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=Ve(i.node,t);if(a)return a}return null}function Ml(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=zr(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=Mn(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=ig(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=Mn(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 zr(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=Mn(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&Ve(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=zr(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=zr(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=zr(r,t);if(o)return o}}return null}function Ve(e,t,n=[]){if(oe.isIdentifier(e))return e.name===t?n:null;if(oe.isObjectPattern(e)){for(let r of e.properties)if(oe.isObjectProperty(r)){let o=Mn(r);if(!o)continue;let i=Ve(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(oe.isRestElement(r)){let o=Ve(r.argument,t,n);if(o)return o}}if(oe.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=oe.isRestElement(o)?o.argument:o,s=Ve(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return oe.isAssignmentPattern(e)?Ve(e.left,t,n):null}function ig(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function sg(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 Mn(e){return e.computed?null:oe.isIdentifier(e.key)?e.key.name:oe.isStringLiteral(e.key)?e.key.value:null}function ag(e){let t=[],n=e;for(;oe.isMemberExpression(n);){if(n.computed)if(oe.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(oe.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(oe.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return oe.isIdentifier(n)?{base:n.name,path:t}:null}var Rt=typeof Xi=="function"?Xi:Xi.default;function le(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 ln(e){return{file:e.file,component:e.component}}function cg(e){return e.target.kind==="node"?e.target.key:null}function lg(e){return"kind"in e}function Wr(e){return!lg(e)}function Zi(e,t){let n=lt.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=lt.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function zi(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=st(n,le(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function os(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 Ue(e){try{return rs.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function ug(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function dg(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 ie(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function Bt(e,t){let n=ie(e);return!!(n&&Ke(t,n))}function Ke(e,t){return t.start>=e.start&&t.end<=e.end}function Yl(e){if(y.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(y.isJSXMemberExpression(e)){let t=e;for(;y.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function fg(e,t){let n=ie(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);if(!a||Bt(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=Yl(i.node.name);s&&o(s,i)}}),[...r].sort()}function _l(e,t,n){let r=Ue(e);if(!r)return{ok:!0};let o=ne(r,le(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=ne(r,le(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};if(uu(o.match.path,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let s=fg(o.match.path,i.match.path);return s.length>0?{ok:!1,bindingNames:s}:{ok:!0}}function Ol(e,t,n){let r=St(t,n);return r?ct(e,r):null}function St(e,t){let n=ne(e,le(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:ns(e,t)}function ct(e,t){let n=t.findParent(b=>b.isArrowFunctionExpression()||b.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(b=>b===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(!y.isIdentifier(l)||l.name!=="map"||c.computed)return null;let u=a.get("object"),f=Zr(e,u.node),p=r.node.params.map(b=>Zr(e,b)),m=ie(i.node),S=ie(r.node);return!f||p.some(b=>b.length===0)||!m||!S?null:{callStart:m.start,callEnd:m.end,callbackStart:S.start,callbackEnd:S.end,collectionExpression:f,callbackParams:p,mapOperator:y.isOptionalMemberExpression(c)&&c.optional?"?.map":".map",collectionNeedsParens:cs(u.node),callbackPath:r,collectionPath:u}}function Zr(e,t){let n=ie(t);return n?e.slice(n.start,n.end):""}function Hr(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function pg(e,t){let n=ie(e.node);return n?mg(t).some(r=>{let o=ie(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function mg(e){let t=e.callbackPath.node.body;return y.isBlockStatement(t)?bt(t.body):kt(t)}function bt(e){let t=[];for(let n of e){if(y.isReturnStatement(n)){n.argument&&t.push(...kt(n.argument));continue}if(y.isBlockStatement(n)){t.push(...bt(n.body));continue}if(y.isIfStatement(n)){let r=y.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...bt(r)),n.alternate){let o=y.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...bt(o))}continue}if(y.isSwitchStatement(n)){for(let r of n.cases)t.push(...bt(r.consequent));continue}y.isTryStatement(n)&&(t.push(...bt(n.block.body)),n.handler&&t.push(...bt(n.handler.body.body)),n.finalizer&&t.push(...bt(n.finalizer.body)))}return t}function kt(e){return y.isJSXElement(e)?hg(e)?Ll(e.children):[e]:y.isJSXFragment(e)?Ll(e.children):y.isParenthesizedExpression(e)||y.isTSAsExpression(e)||y.isTSSatisfiesExpression(e)||y.isTSNonNullExpression(e)||y.isTSTypeAssertion(e)?kt(e.expression):y.isConditionalExpression(e)?[...kt(e.consequent),...kt(e.alternate)]:y.isLogicalExpression(e)&&fu(e.operator)?kt(e.right):[]}function Ll(e){return e.flatMap(t=>y.isJSXElement(t)||y.isJSXFragment(t)?kt(t):y.isJSXExpressionContainer(t)&&(y.isJSXElement(t.expression)||y.isJSXFragment(t.expression)||y.isConditionalExpression(t.expression)||y.isLogicalExpression(t.expression))?kt(t.expression):[])}function hg(e){let t=e.openingElement.name;return y.isJSXIdentifier(t)?t.name==="Fragment":y.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function gg(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function Wi(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function Dl(e,t,n,r={}){if(!r.preserveConditionalBoundary&&uu(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=ie(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(c=>as(c)).map(c=>n.callbackPath.scope.getBinding(c)?.path.node).filter(Boolean)),s=new Set,a=(c,l)=>{let u=l.scope.getBinding(c);if(!u||Bt(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=Yl(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function Bl(e,t,n){let r=ie(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>as(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return is(e,s=>{let a=s.scope.getBinding(s.node.name);if(!a||Bt(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 yg(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>as(a)).map(a=>e.callbackPath.scope.getBinding(a)?.path.node).filter(Boolean)),r=new Set,o=(a,c)=>{let l=c.scope.getBinding(a);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(y.isIdentifier(l))o(l.name,c);else{let u=xg(l);u&&o(u,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function xg(e){let t=e;for(;y.isTSQualifiedName(t);)t=t.left;return y.isIdentifier(t)?t.name:null}function Gl(e,t){let n=ie(e.node),r=new Set;return is(e,o=>{let i=o.scope.getBinding(o.node.name);if(!i||n&&Bt(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 is(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function Eg(e){let t=Sg(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=pu(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=Mg({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=lu(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?cs(o):!0}}}function Sg(e,t,n){let r=ql(e,t);if(eu(e,r),tu(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 Rt(e,{JSXElement(s){au(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:ss(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 bg(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=>On(a.file)));if(!t.has(On(e.sourceFile))||!t.has(On(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(On(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=Cg(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=Ue(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=Ig(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=Zl({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!Je(s.file,e.targetFile)||ss(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 Ig(e,t){let n=new Map,r=i=>{let s=un(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 kg(i,n))o=r(s)||o}return[...n.values()]}function kg(e,t){let n=[],r=Rg(e,t);for(let o of e.ast.program.body){if(y.isExportDefaultDeclaration(o)&&y.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=Dn(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(y.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=Bn(e.file,o.source.value);for(let s of o.specifiers){if(y.isExportNamespaceSpecifier(s)){let l=It(s.exported);for(let u of t.values())Je(u.file,i)&&n.push({file:e.file,namespace:Qi(l,u.namespace),exportName:u.exportName});continue}if(!y.isExportSpecifier(s))continue;let a=It(s.local),c=[...t.values()].filter(l=>Je(l.file,i)&&Lt(l.namespace,a));if(c.length>0){let l=It(s.exported);for(let u of c){let f=Dn(u.namespace,a,l);f&&n.push({file:e.file,namespace:f,exportName:u.exportName})}continue}t.has(un({file:i,exportName:a}))&&n.push({file:e.file,exportName:It(s.exported)})}continue}if(y.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!y.isExportSpecifier(i))continue;let s=It(i.local),a=r.get(s)??[];if(a.length>0){let c=It(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let u=Dn(l.namespace,s,c);u&&n.push({file:e.file,namespace:u,exportName:l.exportName})}}}continue}if(y.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=Bn(e.file,o.source.value),s=o.exported;if(s){let a=It(s);for(let c of t.values())Je(c.file,i)&&n.push({file:e.file,namespace:Qi(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())Je(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function Qi(e,t){return t?`${e}.${t}`:e}function Lt(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function Dn(e,t,n){return!Lt(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function Rg(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(!y.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=Bn(e.file,i.source.value);for(let a of i.specifiers){if(y.isImportDefaultSpecifier(a)){let c=t.get(un({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(u=>Je(u.file,s)&&Lt(u.namespace,"default"));for(let u of l){let f=Dn(u.namespace,"default",a.local.name);f&&r(a.local.name,{...u,namespace:f})}continue}if(y.isImportSpecifier(a)){let c=It(a.imported),l=[...t.values()].filter(f=>Je(f.file,s)&&Lt(f.namespace,c));for(let f of l)r(a.local.name,f);let u=t.get(un({file:s,exportName:c}));u&&r(a.local.name,u);continue}if(y.isImportNamespaceSpecifier(a))for(let c of t.values())Je(c.file,s)&&r(a.local.name,{...c,namespace:Qi(a.local.name,c.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(y.isVariableDeclaration(i))for(let s of i.declarations){if(!y.isIdentifier(s.id)||!s.init)continue;let a=dn(s.init);if(!a||!y.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(un));for(let f of c){let p=Dn(f.namespace,a.name,s.id.name),m=p?{...f,namespace:p}:f,S=un(m);u.has(S)||(r(s.id.name,m),u.add(S),o=!0)}}}return n}function un(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${es(e.file)}#${t}`}function It(e){return y.isIdentifier(e)?e.name:e.value}function Cg(e,t){for(let n of e.program.body){if(y.isExportDefaultDeclaration(n)){let o=n.declaration;if((y.isFunctionDeclaration(o)||y.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(y.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!y.isExportNamedDeclaration(n))continue;let r=n.declaration;if((y.isFunctionDeclaration(r)||y.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(y.isVariableDeclaration(r)){for(let o of r.declarations)if(y.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!y.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:y.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function Zl(e){let t=vg(e),n=[],r=tu(e.ast,t);return Rt(e.ast,{JSXElement(o){Je(e.file,e.sourceFile)&&ss(o)===e.sourceComponent||au(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function Ql(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function ql(e,t){let n=Ql();return Rt(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function vg(e){let t=Ql();return Je(e.file,e.sourceFile)&&wg(t,ql(e.ast,e.sourceComponent)),Rt(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=Bn(e.file,o),s=e.componentIdentities.filter(a=>Je(a.file,i));if(s.length!==0)for(let a of r.specifiers){let c=n.scope.getBinding(a.local.name);if(c){if(y.isImportDefaultSpecifier(a)&&s.some(l=>l.exportName==="default")&&t.localBindings.add(c),y.isImportDefaultSpecifier(a)){let l=s.filter(u=>Lt(u.namespace,"default"));if(l.length>0){let u=t.namespaceMembers.get(c)??new Set;for(let f of l){let p=$l(f,"default");p&&u.add(p)}t.namespaceMembers.set(c,u)}continue}if(y.isImportSpecifier(a)){let l=y.isIdentifier(a.imported)?a.imported.name:a.imported.value,u=s.filter(f=>Lt(f.namespace,l));if(u.length>0){let f=t.namespaceMembers.get(c)??new Set;for(let p of u){let m=$l(p,l);m&&f.add(m)}t.namespaceMembers.set(c,f);continue}s.some(f=>!f.namespace&&f.exportName===l)&&t.localBindings.add(c);continue}if(y.isImportNamespaceSpecifier(a))for(let l of s){let u=l.namespace?`${l.namespace}.${l.exportName}`:l.exportName,f=t.namespaceMembers.get(c)??new Set;f.add(u),t.namespaceMembers.set(c,f)}}}}}),eu(e.ast,t),t}function wg(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 eu(e,t){Rt(e,{VariableDeclarator(n){if(!n.node.init)return;let r=dn(n.node.init);if(r){if(y.isIdentifier(n.node.id)){let o=Dt(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&qi(t,i,o);return}if(y.isObjectPattern(n.node.id)){let o=Dt(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&ou(n.node.id,o.namespaceMembers,t,n)}}}})}function tu(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return Rt(e,{ReferencedIdentifier(r){if(n){r.stop();return}Pg(r)||!r.isIdentifier()||!nu(r,t)||Ag(r,t)||Tg(r)||(n=!0,r.stop())}}),n}function Pg(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 nu(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)&&Dt(r.node,t,r)?r:null}function Ag(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!jl(e,r))return!1;let o=nu(e,t);if(!o)return!1;if(dn(r.node)===o.node)return!!Dt(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&jl(e,a)&&!!Dt(a.node,t,a)}function Tg(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function jl(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Dt(e,t,n){let r=dn(e);if(!r)return null;if(y.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(y.isObjectExpression(r))return Ng(r,t,n);let o=su(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?ru(s,o.slice(1).join(".")):null}function Ng(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!y.isObjectProperty(i))continue;let s=iu(i);if(!s||!y.isExpression(i.value)){y.isExpression(i.value)&&(o||=Dt(i.value,t,n)!==null);continue}let a=Dt(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 ru(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 qi(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 ou(e,t,n,r){for(let o of e.properties){if(y.isRestElement(o)){if(y.isIdentifier(o.argument)){let c=r.scope.getBinding(o.argument.name);c&&qi(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!y.isObjectProperty(o))continue;let i=iu(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=ru(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=y.isAssignmentPattern(o.value)?o.value.left:o.value;if(y.isIdentifier(a)){let c=r.scope.getBinding(a.name);c&&qi(n,c,s);continue}if(y.isObjectPattern(a)&&s.namespaceMembers.size>0){ou(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function iu(e){return e.computed?y.isStringLiteral(e.key)||y.isNumericLiteral(e.key)?String(e.key.value):null:Fg(e.key)}function Fg(e){return y.isIdentifier(e)?e.name:y.isStringLiteral(e)||y.isNumericLiteral(e)?String(e.value):null}function dn(e){return y.isParenthesizedExpression(e)||y.isTSAsExpression(e)||y.isTSSatisfiesExpression(e)||y.isTSNonNullExpression(e)||y.isTSTypeAssertion(e)?dn(e.expression):y.isExpression(e)?e:null}function su(e){if(y.isIdentifier(e))return[e.name];if((y.isMemberExpression(e)||y.isOptionalMemberExpression(e))&&!e.computed&&y.isIdentifier(e.property)){let t=dn(e.object),n=t?su(t):null;return n?[...n,e.property.name]:null}return null}function $l(e,t){if(!Lt(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 au(e,t){let n=e.node.openingElement.name;if(y.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=cu(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 cu(e){if(y.isJSXIdentifier(e))return[e.name];if(y.isJSXMemberExpression(e)){let t=cu(e.object);return t?[...t,e.property.name]:null}return null}function ss(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()&&y.isIdentifier(n.node.id))return n.node.id.name}return null}function Mg(e){let t=ie(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||Bt(a.path.node,t))return;let c=Lg(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=Bg(e.callSitePath,c.propName,e.source);if(!u.ok){o=u.reason;return}let f=_g(u.expression,c.remainingPath);if(!f){o="Cannot move prop-backed repeat child because the mapped prop path is not a portable expression";return}let p=Gl(u.expressionPath,e.targetParentPath);if(!p.ok){o=p.reason??`Cannot move prop-backed repeat child because the mapped prop source is not visible at the target: ${p.bindingNames.join(", ")}`;return}n.set(`${c.range.start}:${c.range.end}`,{...c.range,text:f});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:jg(e.source,t,[...n.values()])}}function _g(e,t){if(t.length===0)return e;let n=lu(e);if(!n)return null;let r=cs(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=Og(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function Og(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function Lg(e,t,n){let r=Dg(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=cn(t,o);if(!i)return null;let s=r?.range??ie(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function Dg(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!Bt(n.node,t)||n.node.computed||!y.isIdentifier(n.node.property))return null;let r=ie(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function Bg(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()&&y.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=Zr(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 jg(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 lu(e){try{let n=rs.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=y.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&y.isExpression(r)?r:null}catch{return null}}function $g(e){let t=ie(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||Bt(s.path.node,t))return;let a=Vl(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let u=Vl(c,e.targetFile,e.targetFile);(!u||u.moduleFile!==a.moduleFile||!Vg(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 is(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 Vg(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 Vl(e,t,n){let r=Ug(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=Bn(t,i),a=i.startsWith(".")?Zi(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=y.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 Ug(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function Bn(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?lt.normalize(lt.join(lt.dirname(e),t)).replace(/\\/g,"/"):t}function Je(e,t){return es(e)===es(t)}function es(e){let t=On(e);return t.endsWith("/index")?t.slice(0,-6):t}function On(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function as(e){let t=[],n=r=>{if(r){if(y.isIdentifier(r)){t.push(r.name);return}if(y.isObjectPattern(r)){for(let o of r.properties){if(y.isRestElement(o)){n(o.argument);continue}y.isObjectProperty(o)&&n(o.value)}return}if(y.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(y.isAssignmentPattern(r)){n(r.left);return}if(y.isRestElement(r)){n(r.argument);return}y.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function Kg(e){let t=[];for(let n of e.callbackPath.node.params){if(y.isIdentifier(n)){t.push(n.name);continue}if(y.isRestElement(n)&&y.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 Jg(e,t){return{...e,callbackParams:t}}function Ul(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function cs(e){return!(y.isIdentifier(e)||y.isThisExpression(e)||y.isMemberExpression(e)||y.isOptionalMemberExpression(e)||y.isCallExpression(e)||y.isOptionalCallExpression(e))}function uu(e,t){return du(e,t).length>0}function Hi(e,t){let n=ie(e.node),r=ie(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()&&!Xg(o,n,r)))return!0;o=o.parentPath}return!1}function Xg(e,t,n){let r=ie(e.node.consequent);if(r&&Ke(r,t)&&!Ke(r,n))return!1;let o=e.node.alternate?ie(e.node.alternate):null;return!(o&&Ke(o,t)&&!Ke(o,n))}function du(e,t){let n=ie(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=ie(o.node.consequent),a=ie(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()&&fu(o.node.operator)){let s=ie(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 Kl(e,t,n,r){let o=du(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=Zr(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=zg(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${Hg(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function zg(e,t){return Wg(e.node)?t:`(${t})`}function Wg(e){return y.isIdentifier(e)||y.isThisExpression(e)||y.isSuper(e)||y.isMemberExpression(e)||y.isOptionalMemberExpression(e)||y.isCallExpression(e)||y.isOptionalCallExpression(e)||y.isBooleanLiteral(e)||y.isNumericLiteral(e)||y.isStringLiteral(e)||y.isNullLiteral(e)||y.isUnaryExpression(e)}function fu(e){return e==="&&"||e==="||"||e==="??"}function Hg(e){return e.trim().startsWith("<")?e:`(${e})`}function pu(e,t){let n=ie(e.node),r=ie(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=Jl(e),i=Jl(t);if(!o||!i||!Yg(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=Gg(s.node,n);if(a&&!Ke(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=ie(s.node.right);if(a&&Ke(a,n)&&!Ke(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())&&Zg(s)){let a=ie(s.node.body)??ie(s.node);if(a&&!Ke(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 Jl(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?ie(t.node.argument):null;if(t.isArrowFunctionExpression()&&(y.isJSXElement(t.node.body)||y.isJSXFragment(t.node.body)||y.isConditionalExpression(t.node.body)||y.isLogicalExpression(t.node.body)))return ie(t.node.body);t=t.parentPath}return null}function Yg(e,t){return e.start===t.start&&e.end===t.end}function Gg(e,t){let n=ie(e.consequent);if(n&&Ke(n,t))return n;let r=ie(e.alternate);return r&&Ke(r,t)?r:null}function Zg(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(y.isMemberExpression(n)||y.isOptionalMemberExpression(n))&&y.isIdentifier(n.property)&&n.property.name==="map"&&!n.computed}var Qg={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 Yr(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=Qg[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 qg(e,t){for(let n of e.program.body){if(!y.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>y.isImportDefaultSpecifier(o));if(r&&y.isImportDefaultSpecifier(r))return r.local.name}return null}function ey(e,t,n){for(let r of e.program.body){if(!y.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>y.isImportSpecifier(i)&&(y.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&y.isImportSpecifier(o))return o.local.name}return null}function Xl(e){let t=new Set;return Rt(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function zl(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function ty(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=os(e),o=Ue(t);if(n.exportName!=="default"){let a=o?ey(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?zl(r,Xl(o)):r;return{localName:c,importStep:Yi(e,c)}}if(!o)return{localName:r,importStep:Yi(e,r)};let i=qg(o,n.source);if(i)return{localName:i};let s=zl(r,Xl(o));return{localName:s,importStep:Yi(e,s)}}function ny(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??os(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 ry(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?oy(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function oy(e){return Object.fromEntries(Object.entries(e).filter(t=>ts(t[1])))}function ts(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(ts):typeof e=="object"?Object.values(e).every(ts):!1}function iy(e,t){let n=Ue(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=Zl({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 Yi(e,t=os(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 Wl(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 sy(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function _n(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function ls(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function Ln(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:ls(e,t.slice(0,n)),index:r.index}}return null}function Gi(e,t){return e.locator?e.collectionPathMap?.[t]?ls(e.locator,e.collectionPathMap[t]):Ln(e.locator)?cy(e.locator,ly(t,e.collectionIndexMap)):null:null}function ay(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:mu(o,t)}function mu(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=mu(r,t);return o===void 0?void 0:{[n.name]:o}}function Gr(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 cy(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},ls(e,i)}return null}function ly(e,t){return t?.[e]??e}function Hl(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 uy(e,t){return dy(e.root,t.root)&&py(e.path??[],t.path??[])}function dy(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&&fy(e.sourceRange,t.sourceRange)}}function fy(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function ns(e,t){let n=null;return Rt(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 py(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 Qr=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:_n(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:_n(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:_n(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:_n(t.kind,t.params.kind)};let r=t;if(!Wr(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=Wl(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:_n(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=cg(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 f=await this.graph.getElementPropertyWriteTarget?.(r.key,l),p=r.attributes?.find(m=>m.name===l);if(!(typeof p?.resolvedValue=="string"&&p.resolvedValue===u||p?.source===null&&p.value===u)){if(f?.kind==="external-entry")return{ok:!1,errorCode:"capability-denied",reason:`set-props cannot overwrite readonly external property '${l}'`};if(f?.kind==="value-binding"&&f.locator){let m=f.locator;if(f.sourceKind==="repeat-template"&&typeof i.selectionRef?.instanceIndex=="number"){let S=Gi(f,i.selectionRef.instanceIndex);if(!S)return{ok:!1,errorCode:"invalid-params",reason:"set-props could not resolve the selected repeat item"};m=S}a.push({order:n+a.length,file:f.file,type:"update-value",locator:m,value:u});continue}c[l]=u}}return Object.keys(c).length>0&&a.push({order:n+a.length,file:s,type:"set-props",locator:le(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=Gi(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:le(t),segmentIndex:n,newText:r}]}}coerceTextValueForValueTarget(t,n,r,o="update-text"){let i=this.graph.getFileContent(t),s=Ue(i);if(!s)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not inspect the value source`};let a=ne(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!ug(a.match.path))return{ok:!0,value:r};let c=dg(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=Gi(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.buildPlan(t,n,[{order:0,file:o.file,type:"update-array-item",locator:c,value:l.value}],r):l}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 f=i;if(f?.kind==="value-binding"&&f.locator){let p=Ln(f.locator);if(p)return this.buildPlan(t,n,[{order:0,file:f.file,type:"remove-bound-array-item",locator:p.locator,index:p.index}],o)}return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed node removal requires a writable array target"}}let s=Gr(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:le(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||iy(n,t)>1)return null;let r=Zi(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(!Wr(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=Gr(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 f=await this.planRepeatBackedInsertChild(t,n,r,o);if(f)return f;let p=this.getRepeatBackedTemplateStructureReason(r);if(p)return{ok:!1,errorCode:"unsupported-operation",reason:p};let m=wl(this.graph.getFileContent(r.file),r);if(!m.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:m.reason??"Cannot insert child into this node"};let S=Yr(r,n.params.node);if(S)return{ok:!1,errorCode:"unsupported-operation",reason:S};let b=[],k=0,R=n.params.node.kind==="component-call"?ty(n.params.node,this.graph.getFileContent(r.file)):void 0,w=R?.importStep;return w&&b.push({order:k++,file:r.file,type:"add-import",moduleSpecifier:w.moduleSpecifier,imports:w.imports}),b.push({order:k++,file:r.file,type:"insert-child",parentLocator:le(r),node:{jsx:ny(n.params.node,R?.localName)},placement:n.params.position.relation,anchorLocator:i?le(i):void 0}),this.buildPlan(t,n,b,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!Wr(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:ry(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(!Wr(n.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};if(n.params.position.relation!=="append"&&n.params.position.relation!=="prepend")return null;let i=n.params.node;if(i.kind!=="native-tag"||i.text===void 0||!this.graph.getChildNodes)return null;let s=this.graph.getChildNodes(r.key).find(f=>f.isRepeatItemRoot&&f.tag?.toLowerCase()===i.tag.toLowerCase());if(!s)return null;let a=await this.graph.getTextWriteTarget(s.key,0);if(!a||a.kind!=="value-binding"||!a.locator)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires a writable value target"};let c=Ln(a.locator);if(!c)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let l=ay(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"?Hl(0,a.collectionIndexMap):Hl(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=Gr(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=Ue(this.graph.getFileContent(t.file));if(!n)return t.isRepeatItemRoot===!0;let r=ne(n,le(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:ns(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=ct(this.graph.getFileContent(t.file),o);return i?pg(o,i):t.isRepeatItemRoot===!0}isInsideMapCallback(t){let n=Ue(this.graph.getFileContent(t.file));if(!n)return!1;let r=ne(n,le(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:ns(n,t);return o?!!o.findParent(i=>{if(!i.isCallExpression()&&!i.isOptionalCallExpression())return!1;let s=i.node.callee;return(y.isMemberExpression(s)||y.isOptionalMemberExpression(s))&&y.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=Ue(c);if(!l)return null;let u=St(l,r),f=St(l,o);if(!u||!f)return null;let p=ct(c,u),m=ct(c,f);if(!Hr(p,m))return null;if(a&&(s==="before"||s==="after")){let b=St(l,a),k=b?ct(c,b):null;if(!Hr(p,k))return null}if(Hi(u,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let S=_l(c,r,o);return S.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:le(r),targetParentLocator:le(o),placement:s,anchorLocator:a?le(a):void 0,selectionContext:ln(o)}],i):{ok:!1,errorCode:"unsupported-operation",reason:S.reason??`Cannot move node because it depends on bindings outside the target scope: ${S.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=Ue(c);if(!l)return null;let u=St(l,r),f=St(l,o);if(!u||!f)return null;let p=ct(c,u);if(!p)return null;let m=ct(c,f);if(Hr(p,m))return null;if(m&&!gg(m,p))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")){let A=Ol(c,l,a);if(m&&!Hr(m,A)||!m&&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 A=Yr(o,{kind:"native-tag",tag:r.tag});if(A)return{ok:!1,errorCode:"unsupported-operation",reason:A}}let S=zi(this.graph,r);if(!S)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Hi(u,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let b=Kl(c,u,f,S);for(let A of b.conditionPaths){let H=Bl(A,f,p);if(!H.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${H.bindingNames.join(", ")}`}}let k=Dl(u,f,p,{preserveConditionalBoundary:b.conditionPaths.length>0});if(!k.ok)return{ok:!1,errorCode:"unsupported-operation",reason:k.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${k.bindingNames.join(", ")}`};let R=yg(p,f);if(!R.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its callback parameters depend on bindings outside the target scope: ${R.bindingNames.join(", ")}`};let w=p;if(r.component!==o.component){let A=Eg({source:c,ast:l,sourceContext:p,sourceNode:r,targetParent:o,targetParentPath:f});if(!A.ok)return{ok:!1,errorCode:"unsupported-operation",reason:A.reason};w=A.context}else{let A=Gl(p.collectionPath,f);if(!A.ok)return{ok:!1,errorCode:"unsupported-operation",reason:A.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${A.bindingNames.join(", ")}`}}return this.buildPlan(t,n,[{order:0,file:r.file,type:"move-repeat-template-child",locator:le(r),targetParentLocator:le(o),placement:s,anchorLocator:a?le(a):void 0,repeatExpression:Ul(w,b.sourceJsx),selectionContext:ln(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=Ue(c),f=Ue(l);if(!u||!f)return null;let p=bg({knownSourceFiles:this.graph.getKnownSourceFiles?.(),routeEntryFiles:this.graph.getRouteEntryFiles?.(),sourceAst:u,sourceFile:r.file,targetFile:o.file,sourceComponent:r.component,targetComponent:o.component});if(!p.ok)return{ok:!1,errorCode:"unsupported-operation",reason:p.reason};let m=St(u,r),S=St(f,o);if(!m||!S)return null;let b=pu(p.callSitePath,S);if(!b.ok)return{ok:!1,errorCode:"unsupported-operation",reason:b.reason};let k=ct(c,m);if(!k)return null;if(ct(l,S))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")&&Ol(l,f,a))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child relative to a repeat-template anchor outside the target scope"};if(r.tag&&r.tag.toLowerCase()===r.tag){let B=Yr(o,{kind:"native-tag",tag:r.tag});if(B)return{ok:!1,errorCode:"unsupported-operation",reason:B}}let w=zi(this.graph,r);if(!w)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Hi(m,S))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let A=Kl(c,m,S,w);for(let B of A.conditionPaths){let j=Bl(B,S,k);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 H=Dl(m,S,k,{preserveConditionalBoundary:A.conditionPaths.length>0});if(!H.ok)return{ok:!1,errorCode:"unsupported-operation",reason:H.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${H.bindingNames.join(", ")}`};let se=$g({sourceFile:r.file,targetFile:o.file,sourceContext:k,targetParentPath:S});if(!se.ok)return{ok:!1,errorCode:"unsupported-operation",reason:se.reason};let ue=Kg(k);if(!ue.ok)return{ok:!1,errorCode:"unsupported-operation",reason:ue.reason};let v=Jg(k,ue.callbackParams),N=[{order:0,file:r.file,type:"remove-node",locator:le(r),removeWhitespace:!0}];for(let B of se.imports)N.push({order:N.length,file:o.file,type:"add-import",moduleSpecifier:B.moduleSpecifier,imports:B.imports});return N.push({order:N.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:le(o),expression:Ul(v,A.sourceJsx),placement:s,anchorLocator:a?le(a):void 0,selectionContext:ln(o)}),this.buildPlan(t,n,N,i)}async planMoveNode(t,n,r,o){if(!o.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};let i=Wl(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(sy(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 R=n.params.target.relation,w=i.anchorNode&&(R==="before"||R==="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:R,anchorSourceId:w?.kind==="external-entry"?w.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,f=Gr(r,a,this.graph.getTextProvenance?.(r.key,0)??null);if(f&&!Wi(f))return{ok:!1,errorCode:"unsupported-operation",reason:f};if(r.isRepeatItemRoot&&u?.isRepeatItemRoot&&r.repeatOwnerKey&&r.repeatOwnerKey===u.repeatOwnerKey&&(l==="before"||l==="after")){let R=a,w=await this.graph.getTextWriteTarget(u.key,0);if(R?.kind==="value-binding"&&w?.kind==="value-binding"&&R.locator&&w.locator){let A=Ln(R.locator),H=Ln(w.locator);if(A&&H&&R.file===w.file&&uy(A.locator,H.locator)){let se=A.index,ue=H.index,v=l==="before"?ue-(se<ue?1:0):ue+(se<ue?0:1);return this.buildPlan(t,n,[{order:0,file:R.file,type:"move-array-item",locator:A.locator,fromIndex:se,toIndex:v}],o)}}}if(r.isRepeatItemRoot&&this.isRepeatTemplateRootNode(r))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed item outside its collection"};let p=this.getRepeatBackedTemplateStructureReason(r),m=Wi(f)?f:p;if(m&&Wi(m)){let R=this.planRepeatTemplateInternalMove(t,n,r,s,o,l,u);if(R)return R;let w=this.planRepeatTemplateHoistMove(t,n,r,s,o,l,u);if(w)return w;let A=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,l,u);return A||{ok:!1,errorCode:"unsupported-operation",reason:m}}if(p)return{ok:!1,errorCode:"unsupported-operation",reason:p};let S=await this.getUpstreamBackedDescendantReason(r);if(S)return{ok:!1,errorCode:"unsupported-operation",reason:S};if(r.tag&&r.tag.toLowerCase()===r.tag){let R=Yr(s,{kind:"native-tag",tag:r.tag});if(R)return{ok:!1,errorCode:"unsupported-operation",reason:R}}if(c)return this.planCrossFileMove(t,n,r,s,o,l,u);let b=_l(this.graph.getFileContent(r.file),r,s);if(!b.ok)return{ok:!1,errorCode:"unsupported-operation",reason:b.reason??`Cannot move node because it depends on bindings outside the target scope: ${b.bindingNames.join(", ")}`};let k=[{order:0,file:r.file,type:"move-node",locator:le(r),targetParentLocator:le(s),placement:l,anchorLocator:u?le(u):void 0,selectionContext:ln(s)}];return this.buildPlan(t,n,k,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,u=this.graph.getFileContent(r.file),f=zi(this.graph,r)??`<${r.component} />`,p=Pl(u,r);if(!p.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:p.reason??"Cannot move subtree across files"};if(c.push({order:l++,file:r.file,type:"remove-node",locator:le(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let S=r.tag??r.component,k={moduleSpecifier:Zi(o.file,r.importedFrom),imports:r.exportName==="default"?[{kind:"default",local:S}]:[{kind:"named",imported:r.exportName,local:S===r.exportName?void 0:S}]};c.push({order:l++,file:o.file,type:"add-import",moduleSpecifier:k.moduleSpecifier,imports:k.imports}),c.push({order:l++,file:o.file,type:"insert-child",parentLocator:le(o),node:{jsx:f},placement:s,anchorLocator:a?le(a):void 0,selectionContext:ln(o)})}else c.push({order:l++,file:o.file,type:"insert-child",parentLocator:le(o),node:{jsx:f},placement:s,anchorLocator:a?le(a):void 0,selectionContext:ln(o)});let m=this.buildRemoveComponentImportStep(r,u);return m&&c.push({...m,order:l++}),this.buildPlan(t,n,c,i)}buildPlan(t,n,r,o){let s=[...new Set(r.map(a=>a.file))].map(a=>({file:a,content:this.graph.getFileContent(a),version:this.graph.getFileVersion(a),exists:!0,sha256:ae(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 jn from"node:path";import*as vu from"@babel/parser";import us from"@babel/traverse";import*as E from"@babel/types";var wu=typeof us=="function"?us:us.default;function Pu(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}var hu=new WeakMap;function gu(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 Au(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=Ss(s,t,n);if(!a)return null;let c=bs(a,r.sourceRange);if(!c)return null;let l=r.source??await ze({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!l){let m=await Ps({currentFile:t,expressionPath:c,readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:new Set});if(!m)return null;if(m.kind==="external")return{kind:"external-entry",file:m.file,sourceType:m.sourceType,sourceId:m.sourceId,adapterId:m.adapterId,displayExpression:m.displayPath};let S={kind:"value",root:m.root,path:m.path.length>0?m.path:[]};return{kind:"value-binding",file:m.file,locator:S,root:m.root,path:m.path,displayExpression:m.displayExpression??Un(c.node,n),sourceKind:m.sourceKind,...m.collectionIndexMap?{collectionIndexMap:m.collectionIndexMap}:{},...m.collectionPathMap?{collectionPathMap:m.collectionPathMap}:{}}}let u=new Set,f=await Vy({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(!f)return null;if(f.kind==="external")return{kind:"external-entry",file:f.file,sourceType:f.sourceType,sourceId:f.sourceId,adapterId:f.adapterId,displayExpression:f.displayPath};let p={kind:"value",root:f.root,path:f.path.length>0?f.path:[]};return{kind:"value-binding",file:f.file,locator:p,root:f.root,path:f.path,displayExpression:f.displayExpression??l.expression,sourceKind:f.sourceKind,...f.collectionIndexMap?{collectionIndexMap:f.collectionIndexMap}:{},...f.collectionPathMap?{collectionPathMap:f.collectionPathMap}:{}}}async function Tu(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Ss(i,t,n);if(!s)return null;let a=e.expression!==void 0?(e.sourceRange?_u(s,n,e.expression,e.sourceRange):null)??Rs(s,n,e.expression):e.sourceRange?bs(s,e.sourceRange):null;if(!a)return null;let c=yy(a),l=new Set,u=e.sourceInfo??await ze({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:l}),f=u?await Ae({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 tx({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 gy(f,e.expression??Un(c.node,n))}async function Es(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Ss(i,t,n);if(!s)return Pe("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?xy({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}):Ey({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}function Nu(e){try{return vu.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Ss(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=Nu(n);return e.set(t,{source:n,ast:o}),o}function bs(e,t){let n=null,r=-1;for(let o of Vn(e).expressions){let i=o.node.loc;if(!i||!Is(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s>=r&&(n=o,r=s)}return n}function my(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of Vn(e).expressions){if(!hy(o.node.loc,t))continue;let i=(o.node.end??0)-(o.node.start??0);i<=r&&(n=o,r=i)}return n}function Fu(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of Vn(e).jsxElements){let i=o.node.loc;if(!i||!Is(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s<=r&&(n=o,r=s)}return n}function Vn(e){let t=hu.get(e);if(t)return t;let n={expressions:[],jsxElements:[]};return wu(e,{Expression(r){n.expressions.push(r)},JSXElement(r){n.jsxElements.push(r)}}),hu.set(e,n),n}function hy(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 Is(e,t){let n=yu({line:e.start.line,column:e.start.column},{line:t.startLine,column:t.startColumn}),r=yu({line:e.end.line,column:e.end.column},{line:t.endLine,column:t.endColumn});return n>=0&&r<=0}function Mu(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 yu(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 ze(e){if(E.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!E.isMemberExpression(e.expression))return null;let t=await Xu(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:Un(e.expression,e.source),base:t.base,path:t.path}:null}function gy(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 yy(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 Un(e,t){if(t)return ks(e,t);let n=fx(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function ks(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Rs(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of Vn(e).expressions){if(ks(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function _u(e,t,n,r){let o=null,i=Number.POSITIVE_INFINITY;for(let s of Vn(e).expressions){if(ks(s.node,t)!==n)continue;let a=s.node.loc;if(!a||!Is(a,r))continue;let c=(s.node.end??0)-(s.node.start??0);c<=i&&(o=s,i=c)}return o}async function xy(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=bs(r,o.sourceRange),u=o.source??(l?await ze({expression:l.node,scope:l.scope,source:n,currentFile:t,readFile:i,exists:s,fileCache:a,visited:c}):null);if(!u){if(!l)return Sy(t,o.value);let p=await Ps({currentFile:t,expressionPath:l,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});return p?p.kind==="external"?Iu(t,p):gs(t,Un(l.node,n),p):by({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return Pe("unsupported-expression","Unable to locate text expression for provenance resolution");let f=await Ae({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(!f){let p=hs(l.node);if(p)return Pe(p.code,p.message);let m=l.scope.getBinding(u.base);if(m?.path.isVariableDeclarator()){let S=hs(m.path.node.init);if(S)return Pe(S.code,S.message)}return m?.path.isVariableDeclarator()&&E.isCallExpression(m.path.node.init)?Iy("unsupported-expression",ju(m.path.node.init,e.functionCallContracts)):Pe("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return f.kind==="external"?Iu(t,f):gs(t,u.expression,f)}async function Ey(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return Pe("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=Rs(r,n,o.conditionExpression);if(!l)return Pe("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await Ae({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 Pe("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(u.kind==="external")return Pe("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let f=gs(t,o.conditionExpression,u);return f.finalSource?{...f,finalSource:{...f.finalSource,kind:"conditional-branch",displayPath:o.conditionExpression},chain:[...f.chain,{kind:"conditional-branch",file:u.file,displayName:o.conditionExpression,canEditHere:!0}]}:f}function Sy(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 by(e){let t=await Lu(e);if(t.length===0)return Pe("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(ky(e.expression))return Ou(t);if(Bu(e.expression))return Pe("unsupported-expression","i18n helpers require a static message id string");if(E.isMemberExpression(e.expression)&&e.expression.computed&&!E.isNumericLiteral(e.expression.property)&&!E.isStringLiteral(e.expression.property))return Pe("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return Pe(n.code,n.message)}function Pe(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function Iy(e,t){return Ou([{code:e,message:t}])}function Ou(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function ky(e){return E.isCallExpression(e)||E.isConditionalExpression(e)||E.isLogicalExpression(e)||E.isBinaryExpression(e)}function $n(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 Lu(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=hs(t);if(l)return[l];if(E.isCallExpression(t))return[{code:"unsupported-expression",message:ju(t,c)}];if(E.isMemberExpression(t)&&t.computed){let u=t.property;if(!E.isNumericLiteral(u)&&!E.isStringLiteral(u)){if(!E.isExpression(u))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let p=await We(u,n,r,o,i,s,a);if(typeof p!="string"&&!Number.isInteger(p))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}]}}return E.isBinaryExpression(t)?$n([...await ds(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):E.isLogicalExpression(t)?$n([...await ds(t.left,t.right,e),{code:"unsupported-expression",message:t.operator==="??"||t.operator==="||"?"Fallback expressions are recognized but remain readonly until a safer composition editing strategy is available":"Complex conditional expressions are recognized but remain readonly until a safer editing strategy is available"}]):E.isConditionalExpression(t)?$n([...await ds(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 hs(e){return Bu(e)?xu("i18n helpers require a static message id string"):Py(e)?xu("CMS helpers require static entry id and field path string arguments"):null}async function ds(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await Lu({...t,expression:o}));return r}function Ry(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:[Cy(e.sourceType)]}}async function Cs(e){for(let n of Fy){if(!Eu(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return bu(Su(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(!Eu(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return bu(Su(r),e.externalAdapters)}return null}function Cy(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function vy(e){return{code:"external-source-readonly",message:e}}function xu(e){return{code:"unsupported-expression",message:e}}function vs(e){return!e||!E.isCallExpression(e)?null:E.isIdentifier(e.callee)?e.callee.name:E.isMemberExpression(e.callee)&&!e.callee.computed&&E.isIdentifier(e.callee.object)&&E.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function Eu(e,t){if(!t||t.length===0)return!0;let n=vs(e.node);return n?t.includes(n):!1}function Su(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:$n(e.diagnostics??[])}:{match:e,diagnostics:[]}}function bu(e,t){let n=Ry(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:$n([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function wy(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!E.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!E.isStringLiteral(n)||!E.isStringLiteral(r))return null;let o=n.value,i=r.value;return{sourceType:"cms-field",sourceId:`${o}:${i}`,file:`cms://${o}/${i.replace(/\./g,"/")}`,displayPath:`${o}.${i}`}}function Py(e){return!!e&&E.isCallExpression(e)&&E.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!E.isStringLiteral(e.arguments[0])||!E.isStringLiteral(e.arguments[1]))}function Du(e){if(!(!e||!E.isCallExpression(e))){if(E.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&E.isStringLiteral(t)?t.value:null}if(E.isMemberExpression(e.callee)&&!e.callee.computed&&E.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&E.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!E.isObjectExpression(t))return null;for(let n of t.properties)if(E.isObjectProperty(n)&&!n.computed&&(E.isIdentifier(n.key)&&n.key.name==="id"||E.isStringLiteral(n.key)&&n.key.value==="id")&&E.isStringLiteral(n.value))return n.value.value;return null}}}function Bu(e){return Du(e)===null}async function Ay(e,t,n){let r=new Set,o=jn.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=jn.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"]:[jn.posix.join(i,"locales"),jn.posix.join(i,"messages")];for(let a of s){let c=jn.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function Ty(e){let t=Du(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await Ay(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function Ny(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!E.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!E.isExpression(n))return null;let o=await We(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:[vy("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var Fy=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>wy(e)},{helperNames:["apiField"],resolve:e=>Ny(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>Ty({currentFile:e,expressionPath:t,exists:n})}];function Iu(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 gs(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=$y(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 My=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function ws(e,t){let n=[...My,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function ju(e,t){let n=e.callee;return E.isIdentifier(n)&&ws(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 Ps(e){let t=await Cs(e);if(t)return t;let n=await $u({...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 ze({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 Ae({...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 By(e)}async function $u(e){let t=await Xe({...e,allowComposed:!1});return t?.kind==="source"?t.provenance:null}async function Xe(e){let t=_y(e.expressionPath),n=Dy(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 ze({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 Ae({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 ze({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 Ae({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 Xe({...e,expressionPath:r,allowComposed:!0}),a=await Xe({...e,expressionPath:o,allowComposed:!1}),c=await Xe({...e,expressionPath:i,allowComposed:!1});return fs(s,a,c)}if(t.isCallExpression())return Oy({...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 Xe({...e,expressionPath:r,allowComposed:!0}),s=await Xe({...e,expressionPath:o,allowComposed:!0});return fs(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 Xe({...e,expressionPath:r,allowComposed:!0}),s=await Xe({...e,expressionPath:o,allowComposed:!0});return fs(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:Xe({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function _y(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 Oy(e){let t=vs(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:Xe({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(E.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:Xe({...e,expressionPath:o,allowComposed:!1})}}return null}function fs(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!Ly(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function Ly(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 Dy(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function By(e){if(!e.expressionPath.isCallExpression())return null;let t=vs(e.expressionPath.node);if(!t)return null;let n=ws(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 Vu({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 Vu(e){let t=await Cs({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 ze({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 Ae({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 Ps({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 jy(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!E.isCallExpression(t))return null;let n=t.callee;if(!E.isIdentifier(n))return null;let r=ws(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 Vu({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 $y(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=qr(t,e.path);return{sourceId:o,displayPath:o}}async function Vy(e){let t=e.segment.source;return t?Ae({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 Ae(e){let t=e.sourceInfo,n=Uu(e.expressionPath,t.base);if(n){let l=await Ku({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 b=Ky(n.callPath,[...n.basePath,...t.path]);return Fn(b)?gu(e.currentFile,b.sourceId,b.displayPath):null}let u=px(l,[...n.basePath,...t.path]),f=l.collectionIndexMap?.[0]??0,p=[...l.pathPrefix??[],{kind:"index",index:f},...n.basePath,...t.path],m=[{kind:"index",index:0},...n.basePath,...t.path];return et(l.value,m)===void 0?null:{kind:"value",file:l.file,root:l.root,path:u?.[0]??p,sourceKind:"repeat-template",collectionIndexMap:l.collectionIndexMap,...u?{collectionPathMap:u}:{}}}let r=e.expressionPath.scope.getBinding(t.base);if(!r)return null;let o=Nl(r);if(o){let l=o.expressionPath,u=await ze({expression:l.node,scope:l.scope,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(u){let f=await Ae({...e,expressionPath:l,sourceInfo:{...u,expression:qr(u.expression,t.path),path:[...u.path,...t.path]}});if(f)return f}if(t.path.length===0){let f=await $u({currentFile:e.currentFile,expressionPath:l,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(f)return f}}if(r.kind==="param")return sx({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 jy({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=Ur(r,t.path);if(Fn(s))return gu(e.currentFile,s.sourceId,s.displayPath);let a=await fn({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 Uu(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=Ve(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!Uy(s,r)?null:{callPath:s,basePath:i}}function Uy(e,t){let n=e.node.callee;return!E.isMemberExpression(n)||!E.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}async function Ku(e){let{currentFile:t,callPath:n,readFile:r,exists:o,fileCache:i,visited:s}=e,a=n.node.callee;if(!E.isMemberExpression(a)||!E.isIdentifier(a.property)||a.property.name!=="map")return null;let c=n.get("callee");if(!c.isMemberExpression())return null;let l=c.get("object");if(Array.isArray(l)||!l.isExpression())return null;let u=await Kn({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 Ky(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:Jr(r,t)}async function Kn(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 fn({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 Ju({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 Kn({...e,expressionPath:a})}if(n.isArrayExpression()){let a=Mu(n.node);if(!a)return null;let c=await We(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 ze({expression:n.node,scope:n.scope,currentFile:t,readFile:r,exists:o,fileCache:i,visited:s});if(!a)return null;let c=await Ae({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 Jy({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 f=mx(l.value,c.collectionPathMap);if(f)return{kind:"static",file:c.file,root:c.root,value:f.value,sourceKind:c.sourceKind,collectionPathMap:f.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 Jy(e){let{provenance:t}=e;if(t.root.kind==="binding"){let i=e.expressionPath.scope.getBinding(t.root.name);return i?await fn({currentFile:e.currentFile,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 Jn(t.file,e.readFile,e.fileCache);if(!n.ast)return null;let r=my(n.ast,t.root.sourceRange);if(!r)return null;let o=await We(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 Ju(e){return await Xy(e)??await zy(e)??await Wy(e)}async function Xy(e){let{callPath:t}=e,n=t.node.callee;if(!E.isMemberExpression(n)||!E.isIdentifier(n.property)||n.property.name!=="filter")return null;let r=t.get("callee");if(!r.isMemberExpression())return null;let o=r.get("object");if(Array.isArray(o)||!o.isExpression())return null;let i=await Kn({currentFile:e.currentFile,expressionPath:o,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(!i||!Array.isArray(i.value))return null;let[s]=t.node.arguments;if(!E.isArrowFunctionExpression(s)&&!E.isFunctionExpression(s))return null;let a=s.params[0];if(!E.isIdentifier(a))return null;let c=Hy(s);if(!c)return null;let l=[],u=[],f=[];for(let[p,m]of i.value.entries()){let S=Yy(c,a.name,m);if(typeof S!="boolean")return null;if(S){l.push(m),u.push(i.collectionIndexMap?.[p]??p);let b=i.collectionPathMap?.[p];b&&f.push(b)}}return{...i,value:l,pathPrefix:i.pathPrefix,collectionIndexMap:u,...f.length>0?{collectionPathMap:f}:{}}}async function zy(e){let{callPath:t}=e,n=t.node.callee;if(!E.isMemberExpression(n)||!E.isIdentifier(n.property)||n.property.name!=="slice")return null;let r=t.get("callee");if(!r.isMemberExpression())return null;let o=r.get("object");if(Array.isArray(o)||!o.isExpression())return null;let i=await Kn({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=ku(s,0),l=ku(a,i.value.length);if(c===null||l===null)return null;let u=Math.max(0,c<0?i.value.length+c:c),f=Math.max(0,l<0?i.value.length+l:l),p=i.value.map((S,b)=>i.collectionIndexMap?.[b]??b).slice(u,f),m=i.collectionPathMap?.slice(u,f);return{...i,value:i.value.slice(u,f),pathPrefix:i.pathPrefix,collectionIndexMap:p,...m?{collectionPathMap:m}:{}}}function ku(e,t){return e?E.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}async function Wy(e){let{callPath:t}=e,n=t.node.callee;if(!E.isMemberExpression(n)||!E.isIdentifier(n.property)||n.property.name!=="sort"&&n.property.name!=="toSorted")return null;let r=t.get("callee");if(!r.isMemberExpression())return null;let o=r.get("object");if(Array.isArray(o)||!o.isExpression())return null;let i=await Kn({currentFile:e.currentFile,expressionPath:o,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(!i||!Array.isArray(i.value))return null;let[s]=t.node.arguments;if(!E.isArrowFunctionExpression(s)&&!E.isFunctionExpression(s))return null;let[a,c]=s.params;if(!E.isIdentifier(a)||!E.isIdentifier(c))return null;let l=i.value.map((f,p)=>({value:f,sourceIndex:i.collectionIndexMap?.[p]??p,originalIndex:p})),u=[...l];for(let f of l)for(let p of l)if(Ru(s,a.name,c.name,f.value,p.value)===void 0)return null;return u.sort((f,p)=>{let m=Ru(s,a.name,c.name,f.value,p.value)??0;return m===0?f.originalIndex-p.originalIndex:m}),{...i,value:u.map(f=>f.value),pathPrefix:i.pathPrefix,collectionIndexMap:u.map(f=>f.sourceIndex),...i.collectionPathMap?{collectionPathMap:u.map(f=>i.collectionPathMap?.[f.originalIndex]).filter(f=>!!f)}:{}}}function Ru(e,t,n,r,o){let i=E.isExpression(e.body)?e.body:e.body.body.find(a=>E.isReturnStatement(a))?.argument;if(!i||!E.isExpression(i))return;let s=ys(i,t,n,r,o);return typeof s=="number"?s:void 0}function ys(e,t,n,r,o){if(E.isNumericLiteral(e)||E.isStringLiteral(e)||E.isBooleanLiteral(e))return e.value;if(E.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(E.isMemberExpression(e)){let i=xs(e,t);if(i)return et(r,i);let s=xs(e,n);return s?et(o,s):void 0}if(E.isBinaryExpression(e)&&e.operator==="-"){let i=E.isExpression(e.left)?ys(e.left,t,n,r,o):void 0,s=E.isExpression(e.right)?ys(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function Hy(e){if(E.isExpression(e.body))return e.body;for(let t of e.body.body)if(E.isReturnStatement(t)&&t.argument&&E.isExpression(t.argument))return t.argument;return null}function Yy(e,t,n){let r=jt(e,t,n);return typeof r=="boolean"?r:void 0}function jt(e,t,n){if(E.isStringLiteral(e)||E.isNumericLiteral(e)||E.isBooleanLiteral(e))return e.value;if(E.isNullLiteral(e))return null;if(E.isIdentifier(e))return e.name===t?n:void 0;if(E.isMemberExpression(e)){let r=xs(e,t);return r?et(n,r):void 0}if(E.isUnaryExpression(e)&&e.operator==="!"){let r=jt(e.argument,t,n);return r===void 0?void 0:!r}if(E.isLogicalExpression(e)){let r=jt(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&jt(e.right,t,n);if(e.operator==="||")return r||jt(e.right,t,n)}if(E.isBinaryExpression(e)){let r=E.isExpression(e.left)?jt(e.left,t,n):void 0,o=E.isExpression(e.right)?jt(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 xs(e,t){let n=[],r=e;for(;E.isMemberExpression(r);){if(r.computed)if(E.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(E.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!E.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!E.isIdentifier(r)||r.name!==t?null:n}async function fn(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 Gy({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 lx({currentFile:t,binding:n,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,fileCache:i,visited:s});if(n.kind==="param")return null;if(n.path.isVariableDeclarator()){let l=n.path.node.init;if(!l||!E.isExpression(l))return null;let u=n.path.get("init");if(u&&!Array.isArray(u)&&u.isExpression()){let p=await Cs({currentFile:t,expressionPath:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(p)return p;if(u.isCallExpression()){let m=await Ju({currentFile:t,callPath:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(m)return m}}let f=await We(l,n.path.scope,t,r,o,i,s);return f===void 0?null:{kind:"static",file:t,root:{kind:"binding",name:n.identifier.name},value:f,sourceKind:"binding"}}if(n.path.isIdentifier()&&n.path.parentPath?.isExportDefaultDeclaration()){let l=n.path.parentPath.node.declaration;if(!E.isExpression(l))return null;let u=await We(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 Gy(e){let{currentFile:t,binding:n,readFile:r,exists:o,fileCache:i,visited:s}=e;if(!n.path.isVariableDeclarator()||!n.path.get("id").isArrayPattern())return null;let a=n.path,c=a.node.init;if(!c||!E.isCallExpression(c))return null;let l=Zy(c);if(!l||!E.isArrayPattern(a.node.id)||a.node.id.elements.findIndex(S=>E.isIdentifier(S)&&S.name===n.identifier.name)!==0)return null;let f=l==="useReducer"?1:0,p=c.arguments[f];if(!p||!E.isExpression(p))return null;let m=await We(p,a.scope,t,r,o,i,s);return m===void 0?null:{kind:"static",file:t,root:{kind:"hook-state",name:n.identifier.name,hook:l},value:m,sourceKind:"binding"}}function Zy(e){return E.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:E.isMemberExpression(e.callee)&&E.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function Qy(e){let t=e.getFunctionParent();if(!t)return null;if(t.isFunctionDeclaration()){let s=t.node.id?.name;if(!s)return null;let a=t.parentPath?.isExportDefaultDeclaration()?"default":(t.parentPath?.isExportNamedDeclaration(),s);return{componentName:s,exportName:a}}if(!t.isArrowFunctionExpression()&&!t.isFunctionExpression())return null;let n=t.parentPath;if(!n?.isVariableDeclarator()||!E.isIdentifier(n.node.id))return null;let r=n.node.id.name,o=n.parentPath,i=o?.parentPath?.isExportDefaultDeclaration()?"default":(o?.parentPath?.isExportNamedDeclaration(),r);return{componentName:r,exportName:i}}function qy(e,t){let n=Qy(e.path);if(!n)return null;let r=cn(e,t);return r?{...n,...r}:null}function qr(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function ex(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}async function tx(e){let t=rx(e.expressionPath.node);if(!t||!ox(t.segments))return null;let n=await Ae({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 nx({...e,rootPath:n.path,segments:t.segments});return r?{...n,path:r.collectionPathMap[0]??n.path,sourceKind:"repeat-template",displayExpression:Un(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:r.collectionPathMap}:null}async function nx(e){let t=null,n,r=[];for(let i of e.segments){if(i.kind!=="dynamic")continue;let s=await ze({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=Uu(e.expressionPath,s.base);if(!a)return null;let c=await Ku({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,f)=>{let p=et(c.value,[{kind:"index",index:f},...a.basePath,...s.path]);return ix(p)});if(l.some(u=>u===null)||t!==null&&t!==l.length)return null;t=l.length,n??=c.collectionIndexMap,r.push(l)}if(t===null||t===0)return null;let o=[];for(let i=0;i<t;i+=1){let s=[...e.rootPath],a=0;for(let c of e.segments){if(c.kind==="dynamic"){let l=r[a]?.[i];if(!l)return null;s.push(l),a+=1;continue}s.push({...c})}o.push(s)}return{...n?{collectionIndexMap:n}:{},collectionPathMap:o}}function rx(e){let t=[],n=e;for(;E.isMemberExpression(n)||E.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(E.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(E.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(E.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(E.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return E.isIdentifier(n)?{base:n.name,segments:t}:null}function ox(e){return e.some(t=>t.kind==="dynamic")}function ix(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}async function sx(e){let t=qy(e.binding,e.sourceInfo);if(!t||!e.graph)return null;let n=[...e.graph.elements.values()].filter(l=>ex(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 ax({caller:r,propName:t.propName,remainingPath:t.remainingPath,readFile:e.readFile,fileCache:e.fileCache});if(l)return ps(l,{componentName:t.componentName,propName:t.propName,file:r.sourceFile})}if(!o?.source){let l=await cx({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 ps(l,{componentName:t.componentName,propName:t.propName,file:r.sourceFile});let u=Ml(e.binding,t.componentName,t.propName);if(!u||u.propName!==t.propName)return null;let f=await We(u.expressionPath.node,u.expressionPath.scope,e.currentFile,e.readFile,e.exists,e.fileCache,e.visited);if(f===void 0)return null;let p=t.remainingPath;return p.length>0&&et(f,p)===void 0?null:{kind:"value",file:e.currentFile,root:{kind:"binding",name:t.propName},path:p,sourceKind:"binding",semanticKind:"component-prop",displayExpression:u.displayPath,chainPrefix:[{kind:"component-prop",file:e.currentFile,displayName:u.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let i=await Jn(r.sourceFile,e.readFile,e.fileCache);if(!i.ast)return null;let s=_u(i.ast,i.source,o.source.expression,o.sourceRange)??Rs(i.ast,i.source,o.source.expression);if(!s)return null;let a={...o.source,expression:qr(o.source.expression,t.remainingPath),path:[...o.source.path,...t.remainingPath]},c=await Ae({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?ps(c.kind==="external"?c:{...c,displayExpression:a.expression},{componentName:t.componentName,propName:t.propName,file:r.sourceFile}):null}async function ax(e){let t=await Jn(e.caller.sourceFile,e.readFile,e.fileCache);if(!t.ast)return null;let n=Fu(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=Mu(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 cx(e){let t=await Jn(e.caller.sourceFile,e.readFile,e.fileCache);if(!t.ast)return null;let n=Fu(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 ze({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:qr(s.expression,a),path:[...s.path,...a]},l=await Ae({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 ps(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 lx(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 _a(t,c,o);if(!l)return null;if(n.path.isImportDefaultSpecifier()){let m=await Cu({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!m||m.kind!=="static"?null:{kind:"static",file:l,root:{kind:"default-export"},value:m.value,sourceKind:"imported-binding"}}if(!n.path.isImportSpecifier())return null;let u=n.path.node.imported,f=E.isIdentifier(u)?u.name:u.value,p=await Cu({file:l,exportName:f,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});return p?p.kind==="external"?p:{kind:"static",file:l,root:{kind:"named-export",name:f},value:p.value,sourceKind:"imported-binding"}:null}async function Cu(e){let{file:t,exportName:n,readFile:r,exists:o,fileCache:i,visited:s}=e,a=await Jn(t,r,i);if(!a.ast)return;let c=dx(a.ast,n);if(!c||c.kind==="default-expression")return;let l=c.name;if(!l)return;let u=ux(a.ast).getBinding(l);return u?await fn({currentFile:t,binding:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s})??void 0:void 0}function ux(e){let t=null;if(wu(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}function dx(e,t){for(let n of e.program.body){if(t==="default"&&E.isExportDefaultDeclaration(n))return E.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:(E.isFunctionDeclaration(n.declaration)||E.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if(E.isExportNamedDeclaration(n)){if(n.declaration){if(E.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if(E.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if((E.isFunctionDeclaration(n.declaration)||E.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if((E.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&E.isExportSpecifier(r))return{kind:"local-binding",name:r.local.name}}}return null}async function We(e,t,n,r,o,i,s){if(E.isStringLiteral(e)||E.isNumericLiteral(e)||E.isBooleanLiteral(e))return e.value;if(E.isNullLiteral(e))return null;if(E.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(E.isTSAsExpression(e)||E.isTSSatisfiesExpression(e)||E.isTSNonNullExpression(e))return await We(e.expression,t,n,r,o,i,s);if(E.isIdentifier(e)){let a=t.getBinding(e.name);if(!a)return;let c=await fn({currentFile:n,binding:a,readFile:r,exists:o,fileCache:i,visited:s});return c?.kind==="static"?c.value:void 0}if(E.isArrayExpression(e)){let a=[];for(let c of e.elements){if(!c||E.isSpreadElement(c))return;let l=await ms(c,t,n,r,o,i,s);if(l===void 0)return;a.push(l)}return a}if(E.isObjectExpression(e)){let a={};for(let c of e.properties){if(!E.isObjectProperty(c)||c.computed)return;let l=null;if(E.isIdentifier(c.key)?l=c.key.name:E.isStringLiteral(c.key)&&(l=c.key.value),!l)return;if(c.shorthand){if(!E.isIdentifier(c.value))return;let f=await ms(c.value,t,n,r,o,i,s);if(f===void 0)return;a[l]=f;continue}if(!E.isExpression(c.value))return;let u=await ms(c.value,t,n,r,o,i,s);u!==void 0&&(a[l]=u)}return a}if(E.isMemberExpression(e)){let a=await Xu(e,t,n,r,o,i,s);if(!a)return;let c=t.getBinding(a.base);if(!c)return;let l=await fn({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 ms(e,t,n,r,o,i,s){if(!E.isSpreadElement(e))return await We(e,t,n,r,o,i,s)}async function Xu(e,t,n,r,o,i,s){if(E.isIdentifier(e))return{base:e.name,path:[]};if(!E.isMemberExpression(e))return null;let a=[],c=e;for(;E.isMemberExpression(c);){if(c.computed){let l=c.property;if(E.isNumericLiteral(l))a.unshift({kind:"index",index:l.value});else if(E.isStringLiteral(l))a.unshift({kind:"property",name:l.value});else{let u=E.isExpression(l)?await We(l,t,n,r,o,i,s):void 0;if(typeof u=="string")a.unshift({kind:"property",name:u});else if(Number.isInteger(u))a.unshift({kind:"index",index:u});else return null}}else{if(!E.isIdentifier(c.property))return null;a.unshift({kind:"property",name:c.property.name})}c=c.object}return E.isIdentifier(c)?{base:c.name,path:a}:null}function fx(e){if(E.isIdentifier(e))return{base:e.name,path:[]};if(!E.isMemberExpression(e))return null;let t=[],n=e;for(;E.isMemberExpression(n);){if(n.computed)if(E.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(E.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!E.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return E.isIdentifier(n)?{base:n.name,path:t}:null}function 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 px(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 mx(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 Jn(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=Nu(o),s={source:o,ast:i};return n.set(e,s),s}var hx=50,gx=8*1024*1024;function Yu(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??hx),s=Math.max(0,t.maxUndoBytes??gx);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:u,redo:f};async function a(v){let N=[...v.steps].sort((Y,Q)=>Y.order-Q.order),B=N.filter(Y=>Y.type!=="invoke-external-adapter");if(B.length!==N.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let j=new Set(B.map(Y=>Y.file)),G=await w(j),Z=new Map(G.map(Y=>[Y.file,Y.exists===!1?"":Y.content])),fe;for(let Y of B){let Q=Hu(Y,Z.get(Y.file)??"");if(!Q.ok)return{ok:!1,errorCode:Q.errorCode,reason:Q.reason};Z.set(Y.file,Q.source),fe=Q.selectionRef??fe}return{ok:!0,filePlan:{operationId:v.operationId,kind:"source-edit",target:v.target,documentVersion:v.documentVersion,conflictPolicy:"compare-and-swap",edits:[...Z].map(([Y,Q])=>({operation:"upsert",file:Y,content:Q,baseContentHash:G.find(pe=>pe.file===Y)?.sha256??null}))},...fe?{selectionRef:fe}:{}}}async function c(v){let N=[...v.steps].sort((pe,tt)=>pe.order-tt.order),B=N.filter(pe=>pe.type!=="invoke-external-adapter"),j=N.filter(pe=>pe.type==="invoke-external-adapter"),G=new Set(B.map(pe=>pe.file));if(B.length>0&&j.length>0)return{ok:!1,operationId:v.operationId,errorCode:"unsupported-operation",reason:"Mixed local file rewrites and external adapter writes require an explicit compensation contract.",rolledBack:!1};if(B.length===0)return k(v,j);let Z=await w(G),fe=new Map;for(let pe of Z)fe.set(pe.file,pe.exists===!1?"":pe.content);let Y;for(let pe of B){let tt=fe.get(pe.file)??"",ut=Hu(pe,tt);if(!ut.ok)return{ok:!1,operationId:v.operationId,errorCode:ut.errorCode,reason:ut.reason,rolledBack:!1};fe.set(pe.file,ut.source),ut.selectionRef&&(Y=ut.selectionRef)}let Q=await H([...fe].map(([pe,tt])=>({file:pe,content:tt,exists:!0,version:0,sha256:ae(tt)})),Z);return Q.ok===!1?{ok:!1,operationId:v.operationId,errorCode:Q.rolledBack?"writeback-failed":"rollback-failed",reason:Q.reason,rolledBack:Q.rolledBack}:(n.push({operationId:v.operationId,preSnapshots:Z,postSnapshots:Q.snapshots,plan:v}),p(),r.length=0,{ok:!0,operationId:v.operationId,kind:v.kind,target:v.target,resultVersion:Math.max(...Q.snapshots.map(pe=>pe.version)),affectedFiles:[...G],...Y?{selectionRef:Y}:{}})}async function l(v){let N=new Set(v.edits.map(Q=>Q.file)),B=await w(N),j=R(v,B);if(j)return{ok:!1,operationId:v.operationId,errorCode:"stale-version",reason:j.reason,affectedFiles:[j.file],rolledBack:!1};let G=new Map(B.map(Q=>[Q.file,Q])),Z=v.edits.find(Q=>Q.operation==="create-only"&&G.get(Q.file)?.exists!==!1);if(Z)return{ok:!1,operationId:v.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${Z.file}`,affectedFiles:[Z.file],rolledBack:!1};let fe=v.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:ae(Q.content)}),Y=await H(fe,B,new Set(v.edits.filter(Q=>Q.operation==="create-only").map(Q=>Q.file)));return Y.ok===!1?{ok:!1,operationId:v.operationId,errorCode:Y.rolledBack?"writeback-failed":"rollback-failed",reason:Y.reason,rolledBack:Y.rolledBack}:(n.push({operationId:v.operationId,preSnapshots:B,postSnapshots:Y.snapshots,plan:{operationId:v.operationId,kind:v.kind,target:v.target,documentVersion:v.documentVersion,steps:[],preSnapshots:B}}),p(),r.length=0,{ok:!0,operationId:v.operationId,kind:v.kind,target:v.target,resultVersion:Math.max(...Y.snapshots.map(Q=>Q.version)),affectedFiles:[...N]})}async function u(){let v=n.at(-1);if(!v)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let N=await H(v.preSnapshots,v.postSnapshots);return N.ok===!1?{ok:!1,operationId:v.operationId,errorCode:N.rolledBack?"writeback-failed":"rollback-failed",reason:N.reason,rolledBack:N.rolledBack}:(n.pop(),r.push(v),{ok:!0,operationId:v.operationId,kind:v.plan.kind,target:v.plan.target,resultVersion:Math.max(...N.snapshots.map(B=>B.version)),affectedFiles:v.preSnapshots.map(B=>B.file)})}async function f(){let v=r.at(-1);if(!v)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let N=await H(v.postSnapshots,v.preSnapshots);return N.ok===!1?{ok:!1,operationId:v.operationId,errorCode:N.rolledBack?"writeback-failed":"rollback-failed",reason:N.reason,rolledBack:N.rolledBack}:(r.pop(),n.push(v),p(),{ok:!0,operationId:v.operationId,kind:v.plan.kind,target:v.plan.target,resultVersion:Math.max(...N.snapshots.map(B=>B.version)),affectedFiles:v.postSnapshots.map(B=>B.file)})}function p(){for(;n.length>i;)n.shift();for(;n.length>0&&m()>s;)n.shift()}function m(){return n.reduce((v,N)=>v+S(N),0)}function S(v){return b(v.preSnapshots)+b(v.postSnapshots)}function b(v){return v.reduce((N,B)=>N+B.file.length+B.content.length,0)}async function k(v,N){let B=[];for(let j of N){let G=j.capability??"write-text",Z=o.find(Y=>Y.sourceType===j.sourceType&&(j.adapterId===void 0||Y.adapterId===j.adapterId)&&(Y.capabilities===void 0||Y.capabilities.includes(G)));if(!Z)return{ok:!1,operationId:v.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${j.sourceType}`,rolledBack:!1};let fe=await Z.execute(j);if(!fe.ok)return{ok:!1,operationId:v.operationId,errorCode:"writeback-failed",reason:fe.reason??`External adapter failed for ${j.sourceType}`,rolledBack:!1};B.push(j.file)}return{ok:!0,operationId:v.operationId,kind:v.kind,target:v.target,resultVersion:0,affectedFiles:B}}function R(v,N){if(v.conflictPolicy!=="compare-and-swap")return null;let B=new Map(N.map(j=>[j.file,j]));for(let j of v.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 G=B.get(j.file),Z=j.baseContentHash;if(Z===null){if(G?.exists!==!1)return{file:j.file,reason:`Source file ${j.file} was created or changed before save.`};continue}if(!Z)return{file:j.file,reason:`Source file ${j.file} is missing baseContentHash. Reopen the file before saving.`};if(G?.exists===!1||G?.sha256!==Z)return{file:j.file,reason:`Source file ${j.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function w(v){let N=[];for(let B of v)N.push(await A(B));return N}async function A(v){if(!await e.exists(v))return{file:v,content:"",version:0,exists:!1};let B=Math.max(1,e.getVersion(v)),j=await e.readFile(v);return{file:v,content:j,version:B,exists:!0,sha256:ae(j)}}async function H(v,N,B=new Set){let j=[];try{for(let G of v){if(B.has(G.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive(G.file,G.content)}else await se(G);let Z=e.bumpVersion(G.file);j.push(G.file),G.version=Z}}catch(G){let Z=await ue(N.filter(Y=>j.includes(Y.file)));if(Z.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${Z.failedFiles.join(", ")}: ${Wu(G)}`,rolledBack:!1,instanceConflict:zu(G)};let fe=zu(G);return{ok:!1,reason:`${fe?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${Wu(G)}`,rolledBack:!0,instanceConflict:fe}}return{ok:!0,snapshots:v.map(yx)}}async function se(v){if(v.exists===!1){await e.deleteFile(v.file);return}await e.writeFile(v.file,v.content)}async function ue(v){let N=[];for(let B of v)try{await se(B),e.bumpVersion(B.file)}catch{N.push(B.file)}return N.length===0?{ok:!0}:{ok:!1,failedFiles:N}}}function zu(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function yx(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:ae(e.content)}:{}}}function Wu(e){return e instanceof Error?e.message:String(e)}function Hu(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 ve(rn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return ve(on({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return ve(Qt({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return ve(en({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return ve(wr({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return ve(An({source:t,locator:e.locator,next:e.value}));case"update-array-item":return ve(An({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return ve(Nr({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return ve(Pr({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return ve(Fr({source:t,locator:e.locator,index:e.index}));case"move-array-item":return ve(Mr({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return ve(nn({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return ve(Ar({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 xx(e,t);case"set-props":{let n=e;return ve(Tr({source:t,locator:n.locator,props:n.props}))}default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function xx(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!Sl(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!==ae(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:El({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function ve(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 Gu(){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 Ex}from"node:crypto";import eo from"node:fs/promises";import As from"node:path";var Sx={async mkdir(e,t){await eo.mkdir(e,t)},async writeFile(e,t,n){await eo.writeFile(e,t,n)},async rename(e,t){await eo.rename(e,t)},async rm(e,t){await eo.rm(e,t)}};async function to(e,t,n=Sx){let r=As.dirname(e),o=As.basename(e),i=As.join(r,`.${o}.${process.pid}.${Ex()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await n.rename(i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import{randomBytes as _x}from"node:crypto";import Xn from"node:path";import{parse as Ox}from"@babel/parser";import Lx from"@babel/traverse";import{SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as Qu,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as Dx,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as Bx,SiteEditMaterializationSchema as jx}from"@vcp-dev/contracts";var Zu=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,bx=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,Ix=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,kx=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,Rx=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,Cx=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,vx=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,wx=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,Px=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,Ax=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,Tx=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,Nx=/\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,Fx=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,Mx=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function Ts(e,t){let n=no([...Le(e,Ix),...Le(e,kx),...Le(e,Rx),...Le(e,t.includeRgbBackgroundImage?Cx:vx),...t.includeExtendedColorFunctions?[...Le(e,wx),...Le(e,Px)]:[]]),r=no([...Le(e,Ax),...Le(e,Tx)]).filter(o=>t.colorMixPolicy==="always"||Zu.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...Le(e,Nx).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...Le(e,Mx).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:no(Le(e,bx)),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?no(Le(e,Fx)):[]}}function Le(e,t){return e.match(new RegExp(t.source,t.flags))??[]}function no(e){return[...new Set(e)]}var _s="components/site/generated",qu="{{$INSTANCE}}",ro=5,$x=/^[a-z][a-z0-9-]{0,48}$/,Vx=/^[a-f0-9]{8}$/,Ux=/\.tsx?$/,Kx=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,Jx=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],Ns=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Fs=Lx,Xx=typeof Fs=="function"?Fs:Fs.default;function zx(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>Qu)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=nE(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=jx.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=qx(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${_s}.`,path:e.generatedRoot}};if(!id(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=nd(r.data.files),s=nd(e.controlledFiles);if(!rE(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>Qu)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>Dx)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>Bx?{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 Wx(e){let t=zx(e);if(!t.ok)return t;let n=t.data.generatedRoot,r=id(e.manifest.instanceBaseName),o=Math.max(1,Math.min(ro,e.maxAttempts??ro));for(let i=0;i<o;i+=1){let s=eE(e.instanceNameGenerator?.()??_x(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=ad(n,a),l=Hx({manifest:e.manifest,generatedRoot:n,instanceName:a,instanceRoot:c,allowedExternalImports:e.allowedExternalImports??Jx});if(!l.ok)return l;if(!await Yx(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 od(e){let t=Math.max(1,Math.min(ro,e.maxAttempts??ro));for(let n=0;n<t;n+=1){let r=await Wx({...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 Hx(e){let t=[],n=new Set;for(let i of e.manifest.files){let s=ed({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=ed({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=Gx(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 Yx(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function ed(e){if(e.pathTemplate.split(qu).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(qu,e.instanceName),n=tE(t);return n?ad(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||!Ux.test(n)||Kx.test(n)?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab files must be .ts/.tsx source files and cannot be config, layout, provider, or global 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 Gx(e,t,n,r,o){let i=new Set(e.map(u=>u.path)),s=new Map,a=new Map;for(let u of e){let f;try{f=Ox(u.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:u.path}}}let p=Ts(u.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:u.path}};s.set(u.path,f),a.set(u.path,new Set)}for(let u of e){let f=s.get(u.path),p=null;if(Xx(f,{ImportDeclaration(m){let S=td({importer:u.path,source:m.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});S.allowed?S.internalPath&&a.get(u.path).add(S.internalPath):(p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab imports must resolve within the controlled instance or match the starter allowlist.",file:u.path},m.stop())},ExportAllDeclaration(m){p??={code:"MATERIALIZATION_ENTRY_INVALID",message:"Static prefab files cannot use export-star declarations.",file:u.path},m.stop()},ExportNamedDeclaration(m){if(m.node.source){let S=td({importer:u.path,source:m.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});!S.allowed||!S.internalPath?(p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab re-exports must resolve within the controlled instance.",file:u.path},m.stop()):a.get(u.path).add(S.internalPath)}},CallExpression(m){if(m.node.callee.type==="Import"){p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use dynamic import().",file:u.path},m.stop();return}m.node.callee.type==="Identifier"&&m.node.callee.name==="require"&&(p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use require().",file:u.path},m.stop())},NewExpression(m){m.node.callee.type==="Identifier"&&m.node.callee.name==="Function"&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot construct functions dynamically.",file:u.path},m.stop())},MetaProperty(m){m.node.meta.type==="Identifier"&&m.node.meta.name==="import"&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot use import.meta.",file:u.path},m.stop())},MemberExpression(m){let S=rd(m.node);S&&Ns.has(S)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${S}.`,file:u.path},m.stop())},OptionalMemberExpression(m){let S=rd(m.node);S&&Ns.has(S)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${S}.`,file:u.path},m.stop())},Identifier(m){m.isReferencedIdentifier()&&Ns.has(m.node.name)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${m.node.name}.`,file:u.path},m.stop())},JSXAttribute(m){m.node.name.type==="JSXIdentifier"&&m.node.name.name==="style"&&(p??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot use inline style attributes.",file:u.path},m.stop())},JSXOpeningElement(m){m.node.name.type==="JSXIdentifier"&&m.node.name.name.toLowerCase()==="style"&&(p??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot declare style elements.",file:u.path},m.stop())}}),p)return{ok:!1,error:p}}let c=s.get(n);return c?Zx(c,r)?Qx(n,a).size!==e.length?Ms("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",n):{ok:!0,data:{kind:"static-prefab-materialization",instanceName:"",generatedRoot:_s,instanceRoot:"",entry:{path:"",export:{kind:"default"}},files:[]}}:Ms("MATERIALIZATION_EXPORT_MISSING","Static prefab entry does not declare the manifest export.",n):Ms("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",n)}function td(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=Xn.posix.normalize(Xn.posix.join(Xn.posix.dirname(e.importer),e.source));if(t===e.instanceRoot||!t.startsWith(`${e.instanceRoot}/`))return{allowed:!1};let r=[t,`${t}.ts`,`${t}.tsx`,...["ts","tsx"].map(o=>`${t}/index.${o}`)].find(o=>e.filePaths.has(o));return r?{allowed:!0,internalPath:r}:{allowed:!1}}function Zx(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 Qx(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 Ms(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function qx(e){let t=sd(e);return t===_s?t:null}function eE(e){let t=e.trim().toLowerCase();return Vx.test(t)?t:null}function id(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 $x.test(t)?t:null}function sd(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=Xn.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function tE(e){let t=sd(e);return!t||t!==e?null:t}function ad(...e){return Xn.posix.join(...e)}function nd(e){return new Set(e.map(t=>t.pathTemplate))}function nE(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 rE(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function rd(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}}function fd(e){let t=null,n=new WeakMap;async function r(){return t??=oE(e),t}return{async prepareAppend(o){let i=await e.readIndex(),s=await e.stageAppend(dd(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);cd(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(cd(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(dd(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 cd(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 oE(e){let t=await e.readIndex(),n=await Promise.all(t.undoIds.map(async o=>ld(e,o))),r=await Promise.all(t.redoIds.map(async o=>ld(e,o)));return{undo:n.reverse(),redo:r.reverse(),entryIds:[...t.entryIds],cursor:t.cursor}}async function ld(e,t){let n=await e.readEntry(t),r=iE(n);return{historyId:t,operationId:r.operationId,kind:r.kind,target:r.target,...r.selectionRef?{selectionRef:r.selectionRef}:{},preSnapshots:await ud(e,n,r.preSnapshots),postSnapshots:await ud(e,n,r.postSnapshots)}}async function ud(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(sE(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function dd(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}:{},preSnapshots:n(e.preSnapshots,"pre"),postSnapshots:n(e.postSnapshots,"post")};return{kind:"site-edit-operation",manifest:JSON.parse(JSON.stringify(r)),blobs:t}}function iE(e){if(!aE(e.manifest))throw new Error("durable history manifest is not an object");return e.manifest}function sE(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function aE(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import pd from"node:path";function Ls(){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 hd(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=dE(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 oo(e){let t=()=>cE(e);return e.mutex?e.mutex.runExclusive(t):t()}async function cE(e){let t=await hd(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=lE(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 Os({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 Os({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 Os({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 md("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return md("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 lE(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 Os(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:uE(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 md(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function uE(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 dE(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)||pd.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=pd.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 Ds(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function pn(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function Bs(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function js(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 gd(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function fE(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var zn=class extends Error{constructor(t){let n=t.map(gd);super(fE(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function yd(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof zn?{routeId:e,message:n,diagnostics:t.diagnostics.map(gd)}:{routeId:e,message:n}}function $s(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function xd(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 EE=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,SE=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],Ed=32,Sd=256,bd={maxEntries:50,maxBytes:8*1024*1024};function bE(){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 to(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 IE(){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>bd.maxEntries||kE(e)>bd.maxBytes;)e.shift()}}function kE(e){return e.reduce((t,n)=>t+RE(n),0)}function RE(e){return Id(e.preSnapshots)+Id(e.postSnapshots)}function Id(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function kd(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 CE(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=He(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 hn=class extends Error{constructor(t){super(t.message),this.result=t}},ao=class extends Error{constructor(t){super(t.reason),this.result=t}},$t=class extends Error{constructor(t){super($s(t)),this.failedRoutes=t}};function Rd(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=He(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(He(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}var vE=/\.(?:[cm]?[jt]sx?)$/i,wE=/\.json$/i,PE=/\.(?:css|scss|sass)$/i,AE=/\.mdx$/i,TE=/\.ya?ml$/i;function NE(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 FE(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function ME(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=OE(await e.listFiles(r)),i=new Map(o.files.map(a=>[a.path,a]));for(let[a,c]of n)if(_E(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 _E(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function OE(e){return Array.isArray(e)?{files:e}:e}function LE(e){if(!hE(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!==yE||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=mE(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(vE.test(e.path)){let t=Ze({source:e.content,profile:At({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(wE.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${Te(t)}`,details:{path:e.path}}}if(PE.test(e.path)){let t=Cd({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(AE.test(e.path)){let t=Cd({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(TE.test(e.path))try{xE(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${Te(t)}`,details:{path:e.path}}}return{ok:!0}}function Cd({content:e,path:t,profile:n}){let r=[],o=null,i=!1,s=!1,a=!1,c=!1,l=!0;for(let f=0;f<e.length;f+=1){let p=e[f]??"",m=e[f+1]??"";if(n==="mdx"&&l&&e.startsWith("```",f)){c=!c;let S=e.indexOf(`
|
|
1
|
+
import{SiteEditOperationRequestSchema as mS,SiteEditPatchPlanSchema as hS}from"@vcp-dev/contracts";function wt(e){return{requestId:e.requestId,kind:e.kind,target:e.target,resultVersion:e.resultVersion,affectedFiles:e.affectedFiles,...e.selectionRef?{selectionRef:e.selectionRef}:{}}}function ir(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 sr(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}})),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 ar(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:gf(e.capabilities),provenanceChain:e.provenanceChain?{editMode:e.provenanceChain.editMode,diagnostics:e.provenanceChain.diagnostics}:void 0,textSegments:e.textSegments.map(t=>({index:t.index,editable:t.editable,sourceKind:t.source?.kind??null})),boundaryKind:e.boundaryKind}}function cr(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:wt(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 gf(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 sE,getSiteEditSourceDeleteProtectionReason as aE,isSiteEditTextSourcePath as cE,parseSiteEditRepeatInstanceKey as lE,SITE_EDIT_SOURCE_DELETE_CAPABILITY as uE,stripSiteEditRepeatInstanceKeys as He}from"@vcp-dev/contracts";import{parse as dE}from"yaml";import no from"node:path";function yn(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 _o from"@babel/traverse";import*as g from"@babel/types";import{createHash as If}from"node:crypto";import*as Ca from"@babel/parser";function Pt(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:Pt(t,n,r,o)}}function Ao(e,t,n,r,o){return{ok:!1,source:e,diagnostic:Pt(t,n,r,o)}}var yf={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function Ze(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:Ca.parse(t,{sourceType:"module",plugins:yf[n]})}}catch(r){return{ok:!1,source:t,diagnostic:Pt("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function To(e,t){return Ze({source:e,profile:va(t.kind)})}function No(e,t){return Ze({source:e,profile:va(t)})}function va(e){return"next-app-entry"}function At(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 xf from"@babel/parser";import*as Jt from"@babel/types";import*as Xt from"node:path";var wa=[".tsx",".ts",".jsx",".js"],Ef=wa.map(e=>`${Xt.sep==="\\"?"\\":"/"}index${e}`);function Pa(e){let t=[];for(let n of e.program.body)Jt.isImportDeclaration(n)&&typeof n.source.value=="string"&&xn(n.source.value)&&t.push(n.source.value),Jt.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&xn(n.source.value)&&t.push(n.source.value),Jt.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&xn(n.source.value)&&t.push(n.source.value);return t}function xn(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function Sf(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=Xt.dirname(e);return Xt.join(n,t).replace(/\\/g,"/")}async function bf(e,t){for(let n of wa){let r=`${e}${n}`;if(await t(r))return r}for(let n of Ef){let r=`${e}${n}`;if(await t(r))return r}return null}async function Aa(e,t,n){let r=await lr(e,t,n);return r.ok?r.path:null}async function lr(e,t,n){let r=Sf(e,t);try{let o=await bf(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)}}}}}var Fo=(e,t)=>{let n=Ze({source:t,profile:At({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${If("sha256").update(t).digest("hex")}`,ast:n.ast,imports:Pa(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};var ur="components/ui";function Tt(e){if(!e)return!1;let t=Mo(e);return t===ur||t.startsWith(`${ur}/`)||t.includes(`/${ur}/`)||t.endsWith(`/${ur}`)}function En(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?Tt(e.slice(2)):e.startsWith("./")||e.startsWith("../")?Tt(Mo(`${kf(t)}/${e}`)):Tt(e):!1}function Mo(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 kf(e){let t=Mo(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}var Rf=typeof _o=="function"?_o:_o.default;function be(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 Cf(e){return/^[A-Z]/.test(e)}function jo(e){let t=e.openingElement;return g.isJSXIdentifier(t.name)?t.name.name==="Fragment":g.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function Wt(e){return g.isJSXFragment(e)}function Fa(e){return g.isJSXIdentifier(e.name)?e.name.name:g.isJSXMemberExpression(e.name)?Ma(e.name):g.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function Ma(e){return g.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:g.isJSXMemberExpression(e.object)?`${Ma(e.object)}.${e.property.name}`:e.property.name}function vf(e){return e.split(".")[0]??e}function wf(e){let t=e;for(;t;){let n=t.node;if(g.isFunctionDeclaration(n)&&n.id||g.isVariableDeclarator(n)&&g.isIdentifier(n.id))return n.id.name;if(g.isExportDefaultDeclaration(n)){let r=n.declaration;if(g.isFunctionDeclaration(r)&&r.id)return r.id.name;if(g.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function Pf(){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 Af(e){let t=new Map;for(let n of e.program.body){if(!g.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(g.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(g.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(g.isImportSpecifier(o)){let i=g.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function rt(e,t=[]){if(g.isIdentifier(e))return t.push(e.name),t;if(g.isObjectPattern(e)){for(let n of e.properties)g.isObjectProperty(n)?rt(n.value,t):g.isRestElement(n)&&rt(n.argument,t);return t}if(g.isArrayPattern(e)){for(let n of e.elements)n&&(g.isRestElement(n)?rt(n.argument,t):rt(n,t));return t}return g.isAssignmentPattern(e)?(rt(e.left,t),t):(g.isRestElement(e)&&rt(e.argument,t),t)}function dt(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function dr(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 Tf(e,t,n){e.set(t,{resolved:!0,value:n})}function $o(e,t){e.set(t,{resolved:!1})}function _a(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 ot(e,t,n){if(g.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!g.isMemberExpression(e))return null;let r=[],o=e;for(;g.isMemberExpression(o);){if(o.computed)if(g.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(g.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&g.isExpression(o.property)){let i=Ft(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(!g.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return g.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:dt(e,t),base:o.name,path:r}:null}function Ft(e,t){if(g.isStringLiteral(e)||g.isNumericLiteral(e)||g.isBooleanLiteral(e))return e.value;if(g.isNullLiteral(e))return null;if(g.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(g.isIdentifier(e)){let n=dr(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(g.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||g.isSpreadElement(r))return;let o=Ft(r,t);if(o===void 0)return;n.push(o)}return n}if(g.isObjectExpression(e)){let n={};for(let r of e.properties){if(!g.isObjectProperty(r)||r.computed||!g.isExpression(r.value))return;let o=null;if(g.isIdentifier(r.key)?o=r.key.name:g.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!g.isIdentifier(r.value))return;let s=dr(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=Ft(r.value,t);if(i===void 0)return;n[o]=i}return n}if(g.isMemberExpression(e)){let n=ot(e,"",t);if(!n)return;let r=dr(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=_a(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(g.isCallExpression(e))return La(e,t)??void 0}function Oa(e,t,n){let r=ot(e,n,t);if(!r)return g.isMemberExpression(e)||g.isBinaryExpression(e)||g.isLogicalExpression(e)||g.isConditionalExpression(e)||g.isCallExpression(e)?{value:dt(e,n),source:null}:null;let o=dr(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?_a(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 Oo(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:Pf(),parentStack:[],valueScopes:i,importMap:o}}function Do(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of rt(o.id))$o(n,s);if(!g.isIdentifier(o.id)||!o.init||!g.isExpression(o.init))continue;let i=Ft(o.init,t);i!==void 0&&Tf(n,o.id.name,i)}}function Nf(e){let t=[];for(let n of e){if(g.isVariableDeclaration(n)){t.push(n);continue}g.isExportNamedDeclaration(n)&&n.declaration&&g.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function Ff(e,t,n){let r=[],o=0;for(let i of e)if(g.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:be(i),editable:!0,source:null})}else if(g.isJSXExpressionContainer(i)&&g.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:be(i),editable:!0,source:null});else if(g.isJSXExpressionContainer(i)&&g.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:be(i),editable:!0,source:null}):r.push({index:o++,value:dt(s,n),sourceRange:be(i),editable:!0,source:null})}else if(g.isJSXExpressionContainer(i)&&g.isExpression(i.expression)){let s=Oa(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:be(i),editable:!0,source:s.source})}return r}function Mf(e,t,n){let r=[];for(let o of e.attributes)if(!(!g.isJSXAttribute(o)||!g.isJSXIdentifier(o.name))){if(g.isStringLiteral(o.value)){r.push({name:o.name.name,value:o.value.value,sourceRange:be(o),source:null});continue}if(g.isJSXExpressionContainer(o.value)&&g.isExpression(o.value.expression)){let i=Ft(o.value.expression,t);if(o.name.name==="className"){let a=typeof i=="string"?i:i===void 0?La(o.value.expression,t):null;if(a){r.push({name:o.name.name,value:a,sourceRange:be(o),source:null,resolvedValue:a});continue}}let s=Oa(o.value.expression,t,n);if(i!==void 0&&typeof i!="string"&&typeof i!="number"){r.push({name:o.name.name,value:Ta(i),sourceRange:be(o),source:ot(o.value.expression,n,t),resolvedValue:i});continue}if(!s){i!==void 0&&r.push({name:o.name.name,value:Ta(i),sourceRange:be(o),source:ot(o.value.expression,n,t),resolvedValue:i});continue}r.push({name:o.name.name,value:s.value,sourceRange:be(o),source:s.source})}}return r}function La(e,t){let n=zt(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function zt(e,t){if(g.isStringLiteral(e))return[e.value];if(g.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(g.isNullLiteral(e))return[];if(g.isBooleanLiteral(e))return e.value?null:[];if(g.isIdentifier(e)||g.isMemberExpression(e)){if(g.isIdentifier(e)&&e.name==="undefined")return[];let n=Ft(e,t);return typeof n=="string"?[n]:null}if(g.isConditionalExpression(e)){let n=zt(e.consequent,t),r=zt(e.alternate,t);return!n||!r?null:[...n,...r]}if(g.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=Ft(e.left,t);return n===!1||n===null?[]:zt(e.right,t)}if(g.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||g.isSpreadElement(r))return null;let o=zt(r,t);if(!o)return null;n.push(...o)}return n}if(g.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!g.isObjectProperty(r))return null;let o=Of(r.key);if(!o)return null;n.push(o)}return n}if(g.isCallExpression(e)){let n=_f(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!g.isExpression(o))return null;let i=zt(o,t);if(!i)return null;r.push(...i)}return r}return null}function _f(e){return g.isIdentifier(e)?e.name:g.isMemberExpression(e)&&g.isIdentifier(e.property)?e.property.name:null}function Of(e){return g.isIdentifier(e)?e.name:g.isStringLiteral(e)?e.value:null}function Lf(e,t){let n=e.attributes.find(r=>g.isJSXAttribute(r)&&g.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!g.isJSXAttribute(n)||!g.isJSXExpressionContainer(n.value)?null:n.value.expression}function Df(e,t){for(let n of t){let r=Lf(e,n);if(r)return r}return null}function Bf(e){return g.isJSXIdentifier(e.name)?e.name.name:null}function Ta(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function jf(e){if(!g.isCallExpression(e)&&!g.isOptionalCallExpression(e))return null;let t=e.callee;return!g.isMemberExpression(t)&&!g.isOptionalMemberExpression(t)||!g.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!g.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function Lo(e){return g.isArrowFunctionExpression(e)||g.isFunctionExpression(e)}function $f(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function Uf(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function Na(e,t,n,r){if(!e||!g.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:dt(e,n),collectionSource:ot(e,n,r)};if(t){let i=t.params[0],s=t.params[1];g.isIdentifier(i)&&(o.itemParamName=i.name),g.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function ft(e,t,n){if(!e)return[];if(g.isJSXElement(e)){if(jo(e))return gr(e.children,t,n);let r=mr(e,t,n);return r?[r]:[]}return Wt(e)?hr(e,t,n):g.isParenthesizedExpression(e)?ft(e.expression,t,n):g.isExpression(e)?yr(e,t,n):[]}function fr(e,t,n){let r=new Map;for(let o of e.params)for(let i of rt(o))$o(r,i);t.valueScopes.push(r);try{if(!g.isBlockStatement(e.body))return ft(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return Da(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function Da(e,t,n){let r=[];for(let o of e){if(g.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];i&&Do([o],t,i);continue}r.push(...Bo(o,t,n))}return r}function Bo(e,t,n){if(g.isReturnStatement(e))return e.argument?ft(e.argument,t,n):[];if(g.isBlockStatement(e))return Nt(e.body,t,n);if(g.isIfStatement(e)){let r=g.isBlockStatement(e.consequent)?Nt(e.consequent.body,t,n):Bo(e.consequent,t,n),o=e.alternate?g.isBlockStatement(e.alternate)?Nt(e.alternate.body,t,n):Bo(e.alternate,t,n):[];return[...r,...o]}if(g.isSwitchStatement(e))return Nt(e.cases.flatMap(r=>r.consequent),t,n);if(g.isTryStatement(e)){let r=Nt(e.block.body,t,n);return e.handler&&r.push(...Nt(e.handler.body.body,t,n)),e.finalizer&&r.push(...Nt(e.finalizer.body,t,n)),r}return[]}function Nt(e,t,n){let r=new Map;t.valueScopes.push(r);try{return Da(e,t,n)}finally{t.valueScopes.pop()}}function pr(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:be(r),sourceCandidates:i&&i.length>0?i:void 0})}function Vf(e,t,n,r){let o=Df(e.openingElement,["items","dataSource","data"]),i={key:t,tag:Fa(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!g.isJSXAttribute(s))continue;let a=Bf(s);if(!a||!g.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!g.isJSXEmptyExpression(c)){if($f(a)&&Lo(c)){let l=fr(c,n,r),u=Na(o,c,r,n);pr(n,"repeat-region",t,s,l,u?[u]:void 0);continue}if(Uf(a)){let l=Lo(c)?fr(c,n,r):ft(c,n,r);pr(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!g.isJSXExpressionContainer(s)||!Lo(s.expression))continue;let a=fr(s.expression,n,r),c=Na(o,s.expression,r,n);pr(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function mr(e,t,n){let r=Fa(e.openingElement);if(r==="Fragment"||jo(e))return gr(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=Cf(r),a;if(s){let A=t.ordinalTracker.getOrdinal(i,r);a=`component:${r}#${A}`}else{let A=t.ordinalTracker.getOrdinal(i,r);a=`${r}#${A}`}let c=o?t.elements.get(o.key)?.identity.structuralPath:void 0,l=c?`${c}/${a}`:a,u=yn(t.file,t.componentName,l),f={file:t.file,component:t.componentName,structuralPath:l,key:u},p=s?"component-boundary":null,m=Ff(e.children,t,n),S=Mf(e.openingElement,t,n),b,R,k=!1;if(s){let A=t.importMap.get(r)??t.importMap.get(vf(r));A&&(b=A.specifier,R=A.exportName,k=En(A.specifier,t.file))}let P={identity:f,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:be(e),parentKey:i,childKeys:[],textSegments:m,attributes:S.length>0?S:void 0,boundaryKind:p,isOpaque:s,...k?{isPublicUiComponent:!0}:{},importedFrom:b,exportName:R};return t.elements.set(u,P),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(u),Vf(e,u,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:u,tag:r}),Kf(e.children,t,n),t.parentStack.pop()),u}function hr(e,t,n){return gr(e.children,t,n)}function gr(e,t,n){let r=[];for(let o of e)if(g.isJSXElement(o))if(jo(o))r.push(...gr(o.children,t,n));else{let i=mr(o,t,n);i&&r.push(i)}else Wt(o)?r.push(...hr(o,t,n)):g.isJSXExpressionContainer(o)&&r.push(...yr(o.expression,t,n));return r}function Kf(e,t,n){for(let r of e)g.isJSXElement(r)?mr(r,t,n):Wt(r)?hr(r,t,n):g.isJSXExpressionContainer(r)&&yr(r.expression,t,n)}function Jf(e){return e==="&&"||e==="||"||e==="??"}function yr(e,t,n){if(g.isJSXEmptyExpression(e))return[];let r=jf(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,c={kind:"repeat-template",collectionExpression:dt(r.collection,n),collectionSource:ot(r.collection,n,t)};if(g.isArrowFunctionExpression(a)||g.isFunctionExpression(a)){let u=a.params[0],f=a.params[1];g.isIdentifier(u)&&(c.itemParamName=u.name),g.isIdentifier(f)&&(c.indexParamName=f.name)}s.push(c);let l={kind:"repeat-region",ownerKey:i?.key??"",childKeys:[],sourceRange:be(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(l),(g.isArrowFunctionExpression(a)||g.isFunctionExpression(a))&&l.childKeys.push(...fr(a,t,n)),l.childKeys}if(g.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:dt(e.test,n),conditionSource:ot(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:be(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...ft(e.consequent,t,n)),s.childKeys.push(...ft(e.alternate,t,n)),s.childKeys}if(g.isLogicalExpression(e)&&Jf(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:dt(e.left,n),conditionSource:ot(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:be(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...ft(e.right,t,n)),s.childKeys}if(g.isParenthesizedExpression(e))return yr(e.expression,t,n);if(g.isJSXElement(e)){let o=mr(e,t,n);return o?[o]:[]}return Wt(e)?hr(e,t,n):[]}function Xf(e){let t=e.argument;return t&&(g.isExpression(t)||Wt(t))?t:null}function Sn(e,t){let n=[];for(let r of e){if(g.isReturnStatement(r)){let o=Xf(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(g.isIfStatement(r)){let o=g.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...Sn(o,r.test)),r.alternate){let i=g.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...Sn(i,r.test))}continue}if(g.isSwitchStatement(r))for(let o of r.cases){let i=o.test?g.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...Sn(o.consequent,i))}}return n}function Ba(e){let{file:t,source:n,ast:r}=e,o=e.imports.map(f=>f.specifier),i=new Map,s=[],a=[],c=new Map,l=Af(r);Rf(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(f){let p=wf(f);if(!p)return;let m=f.node,S=[];if(g.isArrowFunctionExpression(m))g.isExpression(m.body)||Wt(m.body)?S=[{argument:m.body,statement:g.returnStatement(g.isExpression(m.body)?m.body:null)}]:g.isBlockStatement(m.body)&&(S=Sn(m.body.body));else{let z=m.body;g.isBlockStatement(z)&&(S=Sn(z.body))}if(S.length===0){f.skip();return}let b=new Map;Do(Nf(r.program.body),Oo(t,p,i,s,l,[b]),b);let R=new Map;for(let z of m.params)for(let oe of rt(z))$o(R,oe);let k=g.isBlockStatement(m.body)?m.body.body:[],P=S[0]?.statement??null;for(let z of k){if(P&&z===P)break;g.isVariableDeclaration(z)&&Do([z],Oo(t,p,i,s,l,[b,R]),R)}let A=Oo(t,p,i,s,l,[b,R]);for(let z of S){let oe=ft(z.argument,A,n);for(let le of oe)a.includes(le)||a.push(le);if(z.condition){let le={kind:"conditional-branch",conditionExpression:dt(z.condition,n),conditionSource:ot(z.condition,n,A)};pr(A,"conditional-region","",z.statement,oe,[le])}}f.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 Uo(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function xr(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function ja(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??Fo,c=new Map,l=new Map,u=new Map,f=[],p=new Set,m=k=>{let P=`${k.path}\0${k.code}\0${k.message}\0${JSON.stringify(k.details??{})}`;p.has(P)||(p.add(P),f.push(k))},S=[{file:e,source:t,depth:0,diagnosticEntryFile:e,importStack:[]},...(o.additionalEntries??[]).map(k=>({file:k.file,source:k.source,depth:0,diagnosticEntryFile:k.file,importStack:[]}))],b=new Set;for(;S.length>0;){let k=S.shift(),{file:P,source:A,depth:z,diagnosticEntryFile:oe,importStack:le}=k;if(b.has(P))continue;b.add(P),c.set(P,A);let C=a(P,A);if(!C.ok){m(xr(C.diagnostic,oe,le));continue}u.set(P,C.module);let{graph:M,localImports:O}=Ba(C.module);for(let D of M.elements.values())if(D.importedFrom&&xn(D.importedFrom)){let Y=D.importedFrom,G=await lr(P,Y,r);G.ok?(D.importedFrom=G.path,Tt(G.path)&&(D.isPublicUiComponent=!0)):En(Y,P)||m(xr(G.diagnostic,oe,Uo(le,P,Y,G.diagnostic.path)))}if(l.set(P,M),!(z>=i))for(let D of O){if(zf(D))continue;let Y=await lr(P,D,r);if(!Y.ok){En(D,P)||m(xr(Y.diagnostic,oe,Uo(le,P,D,Y.diagnostic.path)));continue}let G=Y.path;if(b.has(G)||Tt(G))continue;let de=Uo(le,P,D,G);try{let W=await n(G);S.push({file:G,source:W,depth:z+1,diagnosticEntryFile:oe,importStack:de})}catch(W){m(xr({path:G,code:"import-read-failed",message:`Failed to read imported file: ${G}`,details:{fromFile:P,specifier:D,reason:W instanceof Error?W.message:String(W)}},oe,de))}}}let R=Wf(e,l,s,(o.additionalEntries??[]).map(k=>k.file));return R.diagnostics=f,{graph:R,allSources:c,diagnostics:f,parsedModules:u,entryModule:u.get(e)??null}}function zf(e){return/\.(?:css|scss|sass|less)(?:\?.*)?$/i.test(e)}function Wf(e,t,n,r=[]){let o=new Map,i=[],s=new Map,a=[];for(let[c,l]of t){for(let[u,f]of l.elements)o.set(u,f);for(let u of l.regions)i.push(u);for(let[u,f]of l.fileIndex){let p=s.get(u)??[];s.set(u,[...p,...f])}if(c===e){a=l.rootKeys;continue}r.includes(c)&&(a=[...a,...l.rootKeys])}return{routeId:e,rootKeys:a,elements:o,regions:i,fileIndex:s,version:n}}function $a(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}),Ua(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function Ua(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}),Ua(s,t,n,r,o))}}import{isSiteEditRuntimeContainerTag as Hf,isSiteEditRuntimeVoidElementTag as Yf}from"@vcp-dev/contracts/site-edit-runtime-capability";function Gf(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(A=>({kind:A.kind,message:A.reason})),s=o.isOpaque,c=r.parentKey===null&&o.componentName==="Page",l=o.tag.toLowerCase(),u=o.tag!==l,f=!u&&Yf(l),p=u||Hf(l),m=u&&o.childKeys.length>0&&!o.isPublicUiComponent,S=o.textSegments.length>0&&o.textSegments.some(A=>A.editable);f&&!i.some(A=>A.kind==="void-element")&&i.push({kind:"void-element",message:`Element '${o.tag}' is void: children cannot be inserted`}),!f&&!p&&!i.some(A=>A.kind==="void-element")&&i.push({kind:"void-element",message:`Element '${o.tag}' cannot contain structured children`});let b=S&&!s,R=!o.isPublicUiComponent&&!f&&p&&(!s||m);return{key:e,canUpdateText:b,canInsertChild:R,canMove:!c,canRemove:!c,constraints:i}}function Va(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,Gf(r,e,t));return n}import{createHash as pi}from"node:crypto";import ai from"@babel/traverse";function Vo(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 Im}from"node:crypto";import bc from"node:path";import*as _r from"@babel/parser";import ni from"@babel/generator";import ri from"@babel/traverse";import*as ht from"@babel/types";import Ko from"@babel/traverse";var pt=typeof Ko=="function"?Ko:Ko.default,Er=new WeakMap,Ka=new WeakMap;function st(e,t){let n=To(e,t);if(!n.ok)return Ao(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=q(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}}:Ao(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function q(e,t){return t.kind==="jsx-node"?Wa(e,t):t.kind==="jsx-attribute"?np(e,t):t.kind==="value"?rp(e,t):t.kind==="expression"?op(e,t):t.kind==="directive"?ip(e,t):t.kind==="export"?sp(e,t):{ok:!1,diagnostic:Pt("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function Wa(e,t){return t.strategy==="source-range"?Zf(e,t):Qf(e,t)}function Zf(e,t){let n=null;if(pt(e,{JSXElement(o){if(!Yt(o.node,t.sourceRange))return;let i=ge("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!Yt(o.node,t.sourceRange))return;let i=ge("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!Yt(o.node,t.sourceRange))return;let i=ge("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)}}),!n)return ye("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!yp(r.path,t.expectedIdentity)?ye("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function Qf(e,t){if(t.structuralPath===""){let r=ep(e,t.component);if(r){let o=tp(r);if(o)return o}}let n=null;return pt(e,{JSXElement(r){if(In(r)!==t.component||Xo(r)!==t.structuralPath)return;let i=ge("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(In(r)!==t.component||Xo(r)!==t.structuralPath)return;let i=ge("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=qf(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:ye("jsx-node","locator-miss","JSX node not found for structural-path locator")}function qf(e,t,n){let r=null;return pt(e,{JSXElement(o){if(In(o)!==t||!Yt(o.node,n))return;let i=ge("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(In(o)!==t||!Yt(o.node,n))return;let i=ge("jsx-node",o);i&&(r=i,o.stop())}}),r}function ep(e,t){let n=null;return pt(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 tp(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 ye("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?ye("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 ye("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function np(e,t){let n=Wa(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>xp(c,t.name));if(!s||!s.isJSXAttribute())return ye("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=ge("jsx-attribute",s);return a?{ok:!0,match:a}:ye("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function rp(e,t){let n=ap(e,t);if(!n.ok)return n;let r=cp(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!it(r.match.path.node.loc,t.expectedRange)?ye("value","locator-miss","Resolved value does not match expected range"):{ok:!0,match:r.match}:r}function op(e,t){let n=null;return pt(e,{Identifier(r){if(!pp(r))return;let o=Xa(r);if(!o||!za(o,t))return;let i=ge("expression",r);i&&(t.expectedRange&&!it(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=Xa(r);if(!o||!za(o,t))return;let i=ge("expression",r);i&&(t.expectedRange&&!it(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:ye("expression","locator-miss","Expression not found")}function ip(e,t){let n=null;return pt(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!it(i.node.loc,t.expectedRange))return;let s=ge("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:ye("directive","locator-miss",`Directive '${t.value}' not found`)}function sp(e,t){let n=null;return pt(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let c=r.get("declaration");if(c.isFunctionDeclaration()&&c.node.id?.name==="generateMetadata"){let p=ge("export",c);if(!p||t.expectedRange&&!it(c.node.loc,t.expectedRange))return;n=p,r.stop();return}if(!c.isVariableDeclaration())return;let l=zo(c,"generateMetadata");if(!l||!l.isVariableDeclarator())return;let u=l.get("init");if(!u.node)return;let f=ge("export",u);if(!f||t.expectedRange&&!it(u.node.loc,t.expectedRange))return;n=f,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=zo(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!it(s.node.loc,t.expectedRange))return;let a=ge("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=ge("export",o);i&&(t.expectedRange&&!it(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:ye("export","export-not-found",`Export '${gp(t)}' not found`)}function ap(e,t){let n=null;return pt(e,{Expression(r){if(n||t.root.kind!=="expression"||!Yt(r.node,t.root.sourceRange))return;let o=ge("value",r);o&&(n=o,r.stop())},VariableDeclarator(r){if(n)return;if(t.root.kind==="binding"){if(r.node.id.type!=="Identifier"||r.node.id.name!==t.root.name)return;let m=r.get("init");if(!m.node)return;let S=ge("value",m);if(!S)return;n=S,r.stop();return}if(t.root.kind!=="hook-state")return;let o=t.root,i=r.get("id"),s=r.get("init");if(!i.isArrayPattern()||!s.isCallExpression()||i.node.elements.findIndex(m=>m?.type==="Identifier"&&m.name===o.name)!==0)return;let c=s.node.callee;if((c.type==="Identifier"?c.name:c.type==="MemberExpression"&&c.property.type==="Identifier"?c.property.name:null)!==o.hook)return;let u=o.hook==="useReducer"?1:0,f=r.get(`init.arguments.${u}`);if(!f||Array.isArray(f)||!f.node)return;let p=ge("value",f);p&&(n=p,r.stop())},ExportNamedDeclaration(r){if(n||t.root.kind!=="named-export")return;let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=zo(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=ge("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=ge("value",o);i&&(n=i,r.stop())}}),n?{ok:!0,match:n}:ye("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 cp(e,t){let n=Jo(e);for(let o of t){if(n=Jo(n),o.kind==="property"){if(!n.isObjectExpression())return ye("value","unsupported-syntax","Property path requires object expression");let a=n.get("properties");if(a.some(l=>!l.isObjectProperty()))return ye("value","unsupported-syntax","Spread properties are not supported");let c=a.find(l=>Ep(l,o.name));if(!c||!c.isObjectProperty())return ye("value","property-not-found",`Property '${o.name}' not found`);n=c.get("value");continue}if(!n.isArrayExpression())return ye("value","unsupported-syntax","Array index path requires array expression");let i=n.get("elements");if(i.some(a=>a.node?.type==="SpreadElement"))return ye("value","unsupported-syntax","Spread array elements are not supported");let s=i[o.index];if(!s?.node)return ye("value","array-index-out-of-range",`Array index ${o.index} is out of range`);n=s}n=Jo(n);let r=ge("value",n);return r?{ok:!0,match:r}:ye("value","locator-miss","Resolved value has no source range")}function Jo(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function ge(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 Yt(e,t){return it(e.loc,t)}function it(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 Xo(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!Sr(n.node)){let o=Ha(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${Ja(n,o)}`):t.unshift(`${o}#${Ja(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||fp(n.parentPath))break;n=n.parentPath}return t.join("/")}function Sr(e){let t=e.openingElement.name;return t.type==="JSXIdentifier"?t.name==="Fragment":t.type==="JSXMemberExpression"&&t.property.name==="Fragment"}function Ja(e,t){let n=lp(e);if(!n)return 0;let r=Er.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=Er.get(n.node)?.get(t);if(!i){let s=Er.get(n.node);s||(s=new Map,Er.set(n.node,s)),i=new WeakMap,s.set(t,i)}for(let s of bn(n))if(Ha(s.node.openingElement)===t){if(i.set(s.node,o),s.node===e.node)return o;o++}return i.get(e.node)??0}function lp(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Sr(t.node)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function bn(e){let t=Ka.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(Sr(o.node)){n.push(...bn(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...bn(o));continue}o.isJSXExpressionContainer()&&n.push(...Ht(o.get("expression")))}return Ka.set(e.node,n),n}function Ht(e){return e.isJSXElement()?Sr(e.node)?bn(e):[e]:e.isJSXFragment()?bn(e):e.isParenthesizedExpression()?Ht(e.get("expression")):e.isLogicalExpression()&&up(e.node.operator)?Ht(e.get("right")):e.isConditionalExpression()?[...Ht(e.get("consequent")),...Ht(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Ht(t)):[]}function up(e){return e==="&&"||e==="||"||e==="??"}function Ha(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?dp(e.name):null}function dp(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 In(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 fp(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function pp(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function Xa(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 za(e,t){return e.base===t.base&&mp(e.path,t.path??[])}function mp(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 hp(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function gp(e){return e.exportKind==="named"?e.name:e.exportKind}function ye(e,t,n,r){return{ok:!1,diagnostic:Pt(t,n,e,r)}}function yp(e,t){return In(e)!==t.component?!1:Xo(e)===t.structuralPath}function xp(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function zo(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function Ep(e,t){return e.isObjectProperty()?hp(e.node)===t:!1}import Wo from"@babel/generator";var Sp=typeof Wo=="function"?Wo:Wo.default;function bp(e){let t=e.split(`
|
|
2
|
+
`),n=[],r=!1;for(let s of t){let a=s.match(/^(\s+)/);if(a){let c=a[1];c.includes(" ")?r=!0:c.length>0&&n.push(c.length)}}if(r&&t.every(a=>{let c=a.match(/^(\s+)/);return!c||c[1].includes(" ")}))return"tab";if(n.length===0)return"2";function o(s,a){return a===0?s:o(a,s%a)}let i=n[0];for(let s=1;s<n.length;s++)i=o(i,n[s]);return i>=4?"4":"2"}function Ip(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 kp(e,t){return e.split(`
|
|
3
|
+
`).map(r=>Ip(r,t)).join(`
|
|
4
|
+
`)}function br(e){let{ast:t,source:n}=e;try{let r=bp(n),i=Sp(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=kp(i,r)),{ok:!0,source:i}}catch(r){return $(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}import*as Ga from"@babel/parser";import{arrayExpression as Rp,booleanLiteral as Cp,identifier as vp,jsxAttribute as wp,jsxExpressionContainer as Pp,jsxIdentifier as Ap,nullLiteral as Tp,numericLiteral as Np,objectExpression as Fp,objectProperty as Mp,stringLiteral as Za}from"@babel/types";function Ya(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 kn(e,t,n){return{ok:!0,source:t,operation:{type:n.kind,nodeId:n.target,kind:n.kind,target:n.target,beforeSourceHash:Ya(e),afterSourceHash:Ya(t),inverse:n.inverse}}}function ae(e,t,n){let r=br({ast:e,source:t});return r.ok?kn(t,r.source,n):r}function xe(e,t){let n=No(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function Ir(e,t){return br({ast:e,source:t})}function _p(e,t,n){let r=q(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function Qa(e,t,n){let r=_p(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 qa(e,t){let n=q(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 Gt(e){return typeof e=="string"?Za(e):typeof e=="number"?Np(e):typeof e=="boolean"?Cp(e):e===null?Tp():Array.isArray(e)?Rp(e.map(t=>Gt(t))):Fp(Object.entries(e).map(([t,n])=>Mp(vp(t),Gt(n))))}function Op(e){return typeof e=="string"?Za(e):Pp(Gt(e))}function kr(e,t){return wp(Ap(e),Op(t))}function ec(e,t){try{let r=Ga.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 Rr(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=xe(t,"jsx-node");if(!i.ok)return i.result;let s=q(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let c=Lp(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=Dp(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 ae(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function Lp(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=Bp(r.get("expression"));o.length>0&&t.push(...o)}}return t}function Dp(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function Bp(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 Ho}from"@babel/types";function Zt(e){let{source:t,locator:n}=e,r=xe(t,"jsx-node");if(!r.ok)return r.result;let o=q(r.ast,n);return o.ok?(jp(o.match.path),ae(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function jp(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Ho());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Ho());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Ho());return}e.remove()}import{cloneNode as Gp}from"@babel/types";import Yo from"@babel/traverse";import*as U from"@babel/types";var $p=typeof Yo=="function"?Yo:Yo.default;function _e(e,t,n,r){if(!e.ok)return e;let o=Me(n);if(!o)return e;let i=Up(t,o,r);return i?{...e,selectionRef:i}:e}function Up(e,t,n){let r=Vp(e,t);if(!r)return;let o=n.sourceLocator?tc(n.sourceLocator):void 0,i=n.targetParentLocator?tc(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??Jp(r)??i?.component??o?.component;if(!(!s||!a))return{key:yn(s,a,Xp(r))}}function tc(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function Vp(e,t){let n=null;return $p(e,{JSXElement(r){r.node===t&&(n=r,r.stop())}}),n}function Me(e){if(!e)return null;if(U.isJSXElement(e))return Qt(e)?nc(e.children):e;if(U.isJSXFragment(e))return nc(e.children);if(U.isJSXExpressionContainer(e)||U.isParenthesizedExpression(e)||U.isTSAsExpression(e)||U.isTSSatisfiesExpression(e)||U.isTSTypeAssertion(e)||U.isTSNonNullExpression(e))return Me(e.expression);if(U.isLogicalExpression(e))return Me(e.right);if(U.isConditionalExpression(e))return Me(e.consequent)??Me(e.alternate);if(U.isCallExpression(e)||U.isOptionalCallExpression(e))return ac(e)?Kp(e.arguments[0]):null;if(U.isArrayExpression(e))for(let t of e.elements){if(!t)continue;let n=Me(t);if(n)return n}return null}function nc(e){for(let t of e){let n=Me(t);if(n)return n}return null}function Kp(e){return!e||!U.isArrowFunctionExpression(e)&&!U.isFunctionExpression(e)?null:U.isBlockStatement(e.body)?Rn(e.body.body):Me(e.body)}function Rn(e){for(let t of e){if(U.isReturnStatement(t)){let n=Me(t.argument);if(n)return n;continue}if(U.isBlockStatement(t)){let n=Rn(t.body);if(n)return n;continue}if(U.isIfStatement(t)){let n=rc(t.consequent);if(n)return n;let r=t.alternate?rc(t.alternate):null;if(r)return r;continue}if(U.isSwitchStatement(t))for(let n of t.cases){let r=Rn(n.consequent);if(r)return r}}return null}function rc(e){return U.isBlockStatement(e)?Rn(e.body):Rn([e])}function Jp(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 oc=new WeakMap,ic=new WeakMap,Go=new WeakMap;function Xp(e){let t=oc.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=zp(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return oc.set(e.node,o),o}function zp(e){let t=Zo(e.node.openingElement.name);return!t||Qt(e.node)?null:/^[A-Z]/.test(t)?`component:${t}#${sc(e,t)}`:`${t}#${sc(e,t)}`}function sc(e,t){let n=Wp(e);if(!n)return 0;let r=Go.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Go.get(n.node);o||(o=new Map,Go.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of Mt(n))if(Zo(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 Wp(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Qt(t.node)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Mt(e){let t=ic.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(Qt(o.node)){n.push(...Mt(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Mt(o));continue}o.isJSXExpressionContainer()&&n.push(...at(o.get("expression")))}return ic.set(e.node,n),n}function at(e){if(e.isJSXElement())return Qt(e.node)?Mt(e):[e];if(e.isJSXFragment())return Mt(e);if(e.isParenthesizedExpression())return at(e.get("expression"));if(e.isLogicalExpression())return at(e.get("right"));if(e.isConditionalExpression())return[...at(e.get("consequent")),...at(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:at(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&ac(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?Hp(n):[]}return[]}function Hp(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return Qt(t.node)?Mt(t):[t];if(t.isJSXFragment())return Mt(t);if(t.isParenthesizedExpression())return at(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return at(t);if(!t.isBlockStatement())return[];for(let n of t.get("body")){if(!n.isReturnStatement())continue;let r=n.get("argument");return r.node?at(r):[]}return[]}function ac(e){let t=e.callee;return(U.isMemberExpression(t)||U.isOptionalMemberExpression(t))&&U.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function Qt(e){let t=Zo(e.openingElement.name);return t==="Fragment"||t==="React.Fragment"}function Zo(e){return U.isJSXIdentifier(e)?e.name:U.isJSXMemberExpression(e)?cc(e):U.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function cc(e){return`${U.isJSXIdentifier(e.object)?e.object.name:cc(e.object)}.${e.property.name}`}function mt(e,t){if(t.parentPath===e&&t.listKey==="children"&&lc(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!lc(n))return null;let r=n;for(;r&&r!==e;){if(!Yp(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function lc(e){return e.isJSXElement()||e.isJSXFragment()}function Yp(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 qt(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=xe(t,"jsx-node");if(!a.ok)return a.result;let c=q(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 A=c.match.path.node;if(!A.closingElement||A.openingElement.selfClosing)return $(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=ec(t,r.jsx);if(!u.ok)return u.result;let f=Gp(u.node,!0),p=l.node.children,m={...s,targetParentLocator:n},S=A=>s?_e(A,a.ast,f,m):A;if(o==="append")return p.push(f),S(ae(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return p.unshift(f),S(ae(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 b=q(a.ast,i);if(!b.ok)return{ok:!1,source:t,diagnostic:b.diagnostic};let R=mt(c.match.path,b.match.path);if(!R)return $(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");l=R;let k=l.node.children,P=k.findIndex(A=>A===b.match.path.node);return P===-1?$(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(k.splice(o==="before"?P:P+1,0,f),S(ae(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as uc from"@babel/parser";import{cloneNode as Zp}from"@babel/types";function Cr(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=xe(t,"jsx-node");if(!a.ok)return a.result;let c=Qp(t,r);if(!c.ok)return c.result;let l=q(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 k=l.match.path.node;if(!k.closingElement||k.openingElement.selfClosing)return $(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=l.match.path,f=null;if(i){let k=q(a.ast,i);if(!k.ok)return{ok:!1,source:t,diagnostic:k.diagnostic};let P=mt(l.match.path,k.match.path);if(!P)return $(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=P,f=k.match.path.node}else if(o==="before"||o==="after")return $(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let p=Zp(c.node,!0),m=u.node.children,S={...s,targetParentLocator:n},b=k=>s?_e(k,a.ast,p,S):k;if(o==="append")return m.push(p),b(ae(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return m.unshift(p),b(ae(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let R=m.findIndex(k=>k===f);return R===-1?$(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(m.splice(o==="before"?R:R+1,0,p),b(ae(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function Qp(e,t){try{let r=uc.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 qp,nullLiteral as Qo}from"@babel/types";import*as en from"@babel/types";function tn(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=xe(t,"jsx-node");if(!a.ok)return a.result;let c=q(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let l=q(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 P=l.match.path.node;if(!P.closingElement||P.openingElement.selfClosing)return $(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let f=null;if(i){let P=q(a.ast,i);if(!P.ok)return{ok:!1,source:t,diagnostic:P.diagnostic};let A=mt(l.match.path,P.match.path);if(!A)return $(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=A,f=P.match.path}else if(o==="before"||o==="after")return $(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let p=f&&typeof f.key=="number"?f.key:-1;if(f&&p===-1)return $(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let m=qp(c.match.path.node,!0);if(!en.isJSXElement(m)&&!en.isJSXExpressionContainer(m)&&!en.isJSXFragment(m))return $(t,"unsupported-syntax","move-node source must resolve to a JSX child","jsx-node");let S=c.match.path.parentPath?.node===u.node&&typeof c.match.path.key=="number"?c.match.path.key:-1;if(f&&c.match.path.parentPath?.node===f.parentPath?.node&&c.match.path.key===f.key)return $(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");em(c.match.path);let b=u.node.children,R={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return b.push(m),_e(Ir(a.ast,t),a.ast,m,R);if(o==="prepend")return b.unshift(m),_e(Ir(a.ast,t),a.ast,m,R);let k=p-(S!==-1&&S<p?1:0);return b.splice(o==="before"?k:k+1,0,m),_e(Ir(a.ast,t),a.ast,m,R)}function em(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Qo());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Qo());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Qo());return}e.remove()}import*as dc from"@babel/parser";import{cloneNode as tm,nullLiteral as qo}from"@babel/types";function vr(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,c=xe(t,"jsx-node");if(!c.ok)return c.result;let l=nm(t,s);if(!l.ok)return l.result;let u=q(c.ast,n);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};let f=q(c.ast,r);if(!f.ok)return{ok:!1,source:t,diagnostic:f.diagnostic};if(!f.match.path.isJSXElement()&&!f.match.path.isJSXFragment())return $(t,"unsupported-syntax","move-repeat-template-child target parent must be a JSXElement or JSXFragment","jsx-node");if(f.match.path.isJSXElement()){let A=f.match.path.node;if(!A.closingElement||A.openingElement.selfClosing)return $(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let p=f.match.path,m=null;if(i){let A=q(c.ast,i);if(!A.ok)return{ok:!1,source:t,diagnostic:A.diagnostic};let z=mt(f.match.path,A.match.path);if(!z)return $(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");p=z,m=A.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 S=p.node,b=tm(l.node,!0);rm(u.match.path);let R={...a,sourceLocator:n,targetParentLocator:r},k=S.children;if(o==="append")return k.push(b),_e(ae(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,b,R);if(o==="prepend")return k.unshift(b),_e(ae(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,b,R);let P=k.findIndex(A=>A===m);return P===-1?$(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(k.splice(o==="before"?P:P+1,0,b),_e(ae(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,b,R))}function nm(e,t){try{let r=dc.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 rm(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(qo());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(qo());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(qo());return}e.remove()}function wr(e){let{source:t,locator:n,props:r}=e,o=xe(t,"jsx-node");if(!o.ok)return o.result;let i=Qa(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=qa(o.ast,l);if(u.ok&&u.match!==null){let f=u.match.path.node;f.value=c===""?kr(a,"").value:kr(a,c).value}else s.attributes.push(kr(a,c))}return ae(o.ast,t,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}import{getBindingIdentifiers as om,identifier as Cn,importDeclaration as im,importDefaultSpecifier as sm,importNamespaceSpecifier as am,importSpecifier as cm,isImportDefaultSpecifier as fc,isImportNamespaceSpecifier as pc,isImportSpecifier as mc,stringLiteral as lm}from"@babel/types";function nn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(R=>!xm(R));if(o!==-1){let R=r[o],k=R&&typeof R=="object"&&"kind"in R?R.kind:void 0;return $(t,"unsupported-syntax",`Unsupported import spec kind: ${String(k)}`)}let i=hm(r);if(!i.ok)return $(t,"unsupported-syntax",i.message);let s=xe(t);if(!s.ok)return s.result;let{ast:a}=s,c=a.program,l=c.body.filter(R=>R.type==="ImportDeclaration"&&R.source.value===n),u=new Set(l.flatMap(R=>R.specifiers.flatMap(k=>{let P=Em(R,k);return P?[P]:[]}))),f=i.imports.filter(R=>!u.has(Sc(R)));if(f.length===0)return kn(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let p=gm(c.body),m=f.find(R=>p.has(ei(R)));if(m)return $(t,"unsupported-syntax",`Import local binding already exists: ${ei(m)}`);let S=mm(f);if(S.reduce((R,k)=>R+k.length,0)!==f.length)return $(t,"unsupported-syntax","Unsupported import specifier grouping");for(let R of S){if(!xc(gc(R)))return $(t,"unsupported-syntax","Unsupported import specifier combination");let k=l.find(P=>um(P,R));if(k)dm(k,R);else{let P=im(hc(R),lm(n));ym(c.body,P),l.push(P)}}return ae(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function um(e,t){return e.importKind==="type"?!1:xc(pm(fm(e),gc(t)))}function dm(e,t){let n=!1,r=new Set(e.specifiers.map(o=>ti(o)));for(let o of hc(t)){let i=ti(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return Ec(e.specifiers),{changed:n}}function hc(e){let t=e.map(n=>{switch(n.kind){case"named":return cm(n.local?Cn(n.local):Cn(n.imported),Cn(n.imported));case"default":return sm(Cn(n.local));case"namespace":return am(Cn(n.local));default:return n}});return Ec(t),t}function gc(e){let t=yc();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 fm(e){let t=yc();for(let n of e.specifiers)fc(n)?t.defaultLocals.add(n.local.name):pc(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function yc(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function pm(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function xc(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function Ec(e){let t=[...e.filter(n=>fc(n)),...e.filter(n=>pc(n)),...e.filter(n=>mc(n))];e.splice(0,e.length,...t)}function mm(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 hm(e){let t=new Map,n=new Map;for(let r of e){let o=Sc(r);if(t.has(o))continue;let i=ei(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 gm(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(om(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 ym(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 xm(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 Sc(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 ei(e){return e.kind==="named"?e.local??e.imported:e.local}function Em(e,t){return e.importKind==="type"||mc(t)&&t.importKind==="type"?null:ti(t)}function ti(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 rn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(u=>!bm(u));if(o!==-1){let u=r[o],f=u&&typeof u=="object"&&"kind"in u?u.kind:void 0;return $(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(f)}`)}let i=xe(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 kn(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let l=a.body[c];return r.length===0?(a.body.splice(c,1),ae(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(l.specifiers=l.specifiers.filter(u=>!r.some(f=>Sm(u,f))),l.specifiers.length===0&&a.body.splice(c,1),ae(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function Sm(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 bm(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 vn(e){let{source:t,locator:n,next:r}=e,o=Nr(t,n);return o.ok?(o.path.replaceWith(Gt(r)),ae(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function Pr(e){let{source:t,locator:n,index:r,value:o}=e,i=Nr(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,Gt(o)),ae(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 Ar(e){let{source:t,locator:n,index:r}=e,o=Nr(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),ae(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 Tr(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=Nr(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),ae(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function Nr(e,t){let n=xe(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=q(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 km=typeof ni=="function"?ni:ni.default;function ii(e){let t=wc(e);if(t)return{ok:!1,error:t};let n=e.projection,r=si(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:Ic(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=st(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?[]:[Fr(c.diagnostic)]}};let l=Mr(e.source,c.match.node.start??null,c.match.node.end??null);if(vm(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=Ic(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 Ic(e){let t=Cm(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 Cc(e){let t;try{t=_r.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=_r.parseExpression(e.jsx,{plugins:["jsx","typescript"]}),r=!1;return(typeof ri=="function"?ri:ri.default)(t,{ExportDefaultDeclaration(i){let s=i.get("declaration"),a=Rm(i,s);if(a){if(a.isArrowFunctionExpression()&&!a.get("body").isBlockStatement()){let c=a.get("body");c.replaceWith(kc(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(kc(l.node,n,e.placement,e.replaceOriginal===!0)),r=!0,c.stop())}}),r&&i.stop()}}}),r?{ok:!0,source:km(t,{}).code}:{ok:!1,source:e.source,diagnostic:{message:"Route default return boundary could not be resolved."}}}function Rm(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 kc(e,t,n,r){if(ht.isNullLiteral(e)||r)return t;let s=n==="before"||n==="prepend"?[t,e]:[e,t];return ht.jsxFragment(ht.jsxOpeningFragment(),ht.jsxClosingFragment(),s)}function vc(e){let t=wc(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=Pc(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=oi(o.sourceRange),s=st(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?[]:[Fr(s.diagnostic)]}};if(Mr(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=si(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 f=oi(u),p=st(e.source,f);if(!p.ok||!p.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:p.ok===!1?p.diagnostic.message:"Route page composition target container could not be resolved.",diagnostics:p.ok?[]:[Fr(p.diagnostic)]}};if(Mr(e.source,p.match.node.start??null,p.match.node.end??null)!==l.containerSourceHash)return Rc("Route page composition target container hash no longer matches the current source.");if(l.relation==="before"||l.relation==="after"){let S=l.anchorSourceRange,b=l.anchorSourceHash;if(!S||!b)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable anchor boundary.",diagnostics:[]}};let R=oi(S),k=st(e.source,R);return!k.ok||!k.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:k.ok===!1?k.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:k.ok?[]:[Fr(k.diagnostic)]}}:Mr(e.source,k.match.node.start??null,k.match.node.end??null)!==b?Rc("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:f,anchorLocator:R,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:f,placement:l.relation}}}}function Rc(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Fr(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function wc(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 Cm(e,t){let n=bc.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=bc.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function oi(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function Mr(e,t,n){return t==null||n==null?null:`sha256:${Im("sha256").update(e.slice(t,n)).digest("hex")}`}function vm(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 wm=typeof ai=="function"?ai:ai.default;function Tc(e){if(!e.ast)return Qe(e,[Ce("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=Om(e.ast);if(!t)return Qe(e,[Ce("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=Dm(t);if(n.length===0)return Qe(e,[Ce("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")]);if(n.length>1)return Qe(e,[Ce("MULTIPLE_PAGE_RETURNS","Route default export contains multiple page-level return statements",{returnCount:n.length})]);let r=Bm(n[0].argument);if(!r)return Qe(e,[Ce("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})]);if(r.isNullLiteral())return Ac(e,t,"virtual-route-root");if(jm(r,t))return Qe(e,[Ce("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if($m(r,t)||Um(r)&&!e.source.includes("DESIGN_PLAN_REPLACE_ME"))return Qe(e,[Ce("UNSUPPORTED_PAGE_SHAPE","Route default export shape does not provide a single safe placement boundary",{reason:"ambiguous-placement"})]);if(r.isJSXFragment()){let i=yt(r);if(i.unsupported)return Qe(e,[Ce("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);let s=ci({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-fragment",source:e.source,containerPath:r,members:i.members});return Or(e,t,s,{kind:"virtual-route-root",sourceKind:"jsx-fragment"})}if(r.isJSXElement()&&!on(r)){let i=di(r),s=ci({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[i]});return Or(e,t,s,{kind:"virtual-route-root",sourceKind:"jsx-element"})}if(r.isJSXElement()){let i=yt(r);if(i.unsupported)return Qe(e,[Ce("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);let s=i.members;if(Km(e.source,r,s))return Ac(e,t,"starter-placeholder");let a=ci({input:e,containerKind:"jsx-container",sourceKind:"jsx-element",source:e.source,containerPath:r,members:s});return Or(e,t,a,{kind:"jsx-container",sourceKind:"jsx-element"})}if(Vm(r))return Qe(e,[Ce("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);let o=Xm({input:e,source:e.source,expression:r});return Or(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"})}function si(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Ce("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:Ce("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function Pc(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Ce("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:Ce("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function Nc(e){return e.ok?Pm(e.projection):Am(e.projection)}function Pm(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 f=u.members.flatMap((b,R)=>Fc(e,u,b,R,e.container.placementKey)),p=f.filter(({member:b})=>b.isBusinessMember).map(({sourceMember:b})=>Nm(l,b,u.independent)),m=f.length>0?f:[{sourceMember:{key:`source:${l}:empty`,kind:e.container.kind==="starter-placeholder"?"starter-placeholder":"null-return",containerKey:e.container.placementKey,label:"empty-page",sourceFile:e.entryFile,isAtomic:!0},member:null}];r.set(l,m.map(({sourceMember:b})=>b)),o.set(l,p);let S=m[0]?.sourceMember.key??l;n.push({key:l,containerKey:S,businessMemberKeys:p.map(b=>b.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:Tm(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function Am(e){let t=e.diagnostics.map(Fm);return{status:"unsupported",version:e.version,routeId:e.route,reason:Mm(e.diagnostics),diagnostics:t}}function Tm(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 Fc(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)=>Fc(e,t,a,c,i))]}function Nm(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function Fm(e){return{code:_m(e),message:e.message}}function Mm(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 _m(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 Om(e){let t=null;return wm(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=Lm(o.path);i&&(t=i,n.stop())}}),t}function Lm(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 Dm(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 Bm(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 jm(e,t){if(e.isIdentifier())return Lr(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return Lr(n.node.name,t)}return!1}function $m(e,t){return e.isConditionalExpression()?gt(e.get("consequent"),t)||gt(e.get("alternate"),t):e.isLogicalExpression()?gt(e.get("left"),t)||gt(e.get("right"),t):!1}function Um(e){if(!e.isJSXElement()||!on(e))return!1;let t=yt(e).members;if(t.length!==1)return!1;let n=t[0];return n.kind==="jsx-element"&&!n.isBusinessMember&&n.businessMemberCount>0}function gt(e,t){if(e.isIdentifier())return Lr(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return Lr(n.node.name,t)}return e.isConditionalExpression()?gt(e.get("consequent"),t)||gt(e.get("alternate"),t):e.isLogicalExpression()?gt(e.get("left"),t)||gt(e.get("right"),t):!1}function Lr(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 Vm(e){return e.isJSXSpreadChild()}function Km(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&ui(t)}function ui(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(!ui(t))return!1;continue}if(t.isJSXElement()&&!ui(t))return!1}return!0}function yt(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:fi(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:$e(r.node.loc),businessMemberCount:0,parentSourceRange:$e(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=yt(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=on(o)?yt(o):null;n||=i?.unsupported??!1,t.push({...di(o,i?.members),sourceRange:$e(r.node.loc),parentSourceRange:$e(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:fi(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:$e(r.node.loc),businessMemberCount:1,parentSourceRange:$e(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&Mc(r)){let o=yt(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=on(r)?yt(r):null;n||=o?.unsupported??!1,t.push({...di(r,o?.members),parentSourceRange:$e(e.node.loc)})}}return{members:t,unsupported:n}}function di(e,t){let n=e.isJSXElement()&&on(e)?t??yt(e).members:[],r=e.isJSXElement()&&!on(e)&&!Mc(e);return{memberKey:fi(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:$e(e.node.loc),businessMemberCount:r?1:_c(n),parentSourceRange:$e(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:Jm(e)}}function Mc(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 on(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name!=="Fragment"&&t.name[0]===t.name[0]?.toLowerCase()}function Jm(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 _c(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function Dr(e){return e.length===0?0:Math.max(1,_c(e))}function ci(e){let t=$e(e.containerPath.node.loc),n=Lc(e.source,e.containerPath.node.start,e.containerPath.node.end),r=Oe(e.input,e.containerKind,e.sourceKind,t),o=Oe(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:Dr(e.members)<=1,memberCount:Dr(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function Xm(e){let t=$e(e.expression.node.loc),n=Lc(e.source,e.expression.node.start,e.expression.node.end),r=Oe(e.input,"virtual-route-root","atomic-expression",t),o=Oe(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:Oe(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 Or(e,t,n,r){let o=n.containerSourceRange??n.sourceRange,i=zm(e,n,o),s=Vo(i),a={status:"supported",route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Dc(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 zm(e,t,n){if(t.members.length===0)return[t];let r=[],o=(l,u,f,p,m,S,b=n)=>({...t,placementKey:u,placementUnitKey:f,containerKey:t.placementKey,independent:Dr(S)<=1,memberCount:Dr(S),sourceRange:p,sourceHash:p?li(e.source,p):null,relation:l,containerSourceRange:b,containerSourceHash:b?li(e.source,b):null,anchorSourceRange:m,anchorSourceHash:m?li(e.source,m):null,members:S}),i=t.placementKey,s=t.members.map(l=>Oe(e,i,"placement-unit",l.sourceRange)),a=s[0]??t.placementUnitKey,c=s.at(-1)??t.placementUnitKey;r.push(o("prepend",Oe(e,i,"prepend",n),a,n,null,[]));for(let l of t.members){let u=l.parentSourceRange??n,f=Oe(e,i,"placement-unit",l.sourceRange);r.push(o("before",Oe(e,f,"before",l.sourceRange),f,l.sourceRange,l.sourceRange,[l],u)),r.push(o("after",Oe(e,f,"after",l.sourceRange),f,l.sourceRange,l.sourceRange,[l],u))}return r.push(o("append",i,c,n,null,[])),r}function Ac(e,t,n){let r=Oe(e,n,"empty-container",void 0),o=Oe(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=Vo([i]),a={status:"supported",route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Dc(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 Qe(e,t){return{ok:!1,projection:{status:"unsupported",route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,diagnostics:t}}}function Ce(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function Oe(e,t,n,r){return Oc([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function fi(e,t,n){return Oc(["member",e,String(t??-1),String(n??-1)])}function Oc(e){return`pc_${pi("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function Lc(e,t,n){return t==null||n==null?null:`sha256:${pi("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:${pi("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function $e(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function Dc(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 Hm(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var Ym=160;function Bc(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})}return{routeId:e.routeId,version:e.version,rootKeys:[...e.rootKeys],entries:o}}function jc(e,t,n,r,o,i,s,a,c,l,u,f){let p=t.elements.get(e),m=n.nodes.get(e),S=r.get(e);if(!p||!m||!S)throw new Error(`Node not found: ${e}`);let b=qm(p.textSegments,s),R=eh(e,t,p,S,b),k=b?nh(b):void 0,P=rh(i,b),A=p.textSegments.map(M=>({index:M.index,value:M.value,editable:th(M,S,s?.get(M.index)??null),source:o.get(M.index)??null})),z=[],oe=p.parentKey;for(;oe;){let M=t.elements.get(oe);if(!M)break;z.push({key:oe,tag:M.tag,label:M.tag}),oe=M.parentKey}z.reverse();let 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),C=[];if(p.parentKey){let M=t.elements.get(p.parentKey);if(M)for(let O of M.childKeys){if(O===e)continue;let D=t.elements.get(O);D&&C.push({key:O,tag:D.tag,label:D.tag})}}return{key:e,tag:p.tag,componentName:p.componentName,sourceFile:p.sourceFile,sourceLocator:Gm(p),label:p.tag,capabilities:R,writeTarget:i,effectiveWriteTarget:P,provenanceChain:k,componentSemantic:c,contentModel:l,mediaModel:u,styleSource:f,conditional:a,textSegments:A,boundaryKind:p.boundaryKind,isOpaque:p.isOpaque,ancestors:z,children:le,siblings:C}}function Gm(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:Zm(e.sourceRange),structuralPath:e.identity.structuralPath,...Qm(e.textSegments)}}function Zm(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function Qm(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,Ym)}:{}}function $c(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 qm(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function eh(e,t,n,r,o){let i=n.identity.structuralPath.includes("#repeat:"),s=t.regions.some(u=>u.kind==="repeat-region"&&u.childKeys.includes(e)),a=o?.diagnostics.find(u=>u.code==="missing-adapter"||u.code==="external-source-readonly")?.code,c=r.canUpdateText?{mode:o?.editMode??"direct",reasonCode:a??(o?.editMode==="upstream"?"component-prop":o?.finalSource?.kind==="repeat-template"?"repeat-item-data":void 0)}:{mode:"unsupported",reasonCode:"capability-denied"},l=r.canUpdateText&&Uc(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 th(e,t,n){return!e.editable||!t.canUpdateText?!1:n?Uc(n.editMode):!0}function Uc(e){return e==="direct"||e==="proxy"||e==="upstream"}function nh(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 rh(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}:Hm(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 Vc(e){let{key:t,element:n,graph:r,provenances:o}=e,i=ih(t,n,r),s=i?.tag??(_t(n.tag)?n.tag:n.componentName),a=i?.identity.key??Kc(n,r)??t,c=ch(i),l=lh(t,n,r,o,i),u=oh(t,n,r,o,a);return{componentName:s,instanceKey:a,templateOwner:ah(i??n,s),...c.length>0?{variantKeys:c}:{},...l.length>0?{slotKeys:l}:{},editableStrategy:u,impactScope:uh(u),alternativeStrategies:dh(u)}}function oh(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return mi(e,n)?"instance":!_t(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function Kc(e,t){if(_t(e.tag))return e.identity.key;let n=[...t.elements.values()].filter(r=>r.importedFrom===e.sourceFile&&sh(r,e.componentName));return n.length!==1?null:n[0].identity.key}function ih(e,t,n){if(_t(t.tag))return t;let r=mi(e,n);if(r)return r;let o=Kc(t,n);return o?n.elements.get(o)??null:null}function sh(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function ah(e,t){return _t(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function ch(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 lh(e,t,n,r,o){let i=new Set,s=mi(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&&_t(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function mi(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(_t(r.tag))return r;n=r.parentKey}return null}function _t(e){return/^[A-Z]/.test(e)}function uh(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function dh(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}var fh=new Set(["markdown","body","content","value","document"]),Jc=[];function zc(e){if(!(!hh(e.tag)||!e.attributes))for(let t of e.attributes){if(!fh.has(t.name))continue;if(mh(t))return{kind:"markdown",field:t.name,schema:"markdown",valuePath:t.source?.expression,operationBoundary:Jc};let n=ph(t.resolvedValue);if(n==="prosemirror-doc"||n==="node-array")return{kind:"rich-text-json",field:t.name,valuePath:t.source?.expression,schema:n,operationBoundary:Jc};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 ph(e){if(e){if(Array.isArray(e)&&e.every(t=>Xc(t)))return"node-array";if(Xc(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 Xc(e){return!Array.isArray(e)&&typeof e=="object"&&e!==null}function mh(e){return e.name==="markdown"}function hh(e){return/^[A-Z]/.test(e)}var gh=["src","alt","poster","caption","width","height"];function Wc(e){let t=e.attributes?.filter(i=>gh.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=xh(t.map(i=>i.value));return{kind:yh(e.tag,n),sourceType:o,fields:n,editableFields:[],operationBoundary:[],...Object.keys(r).length>0?{valuePaths:r}:{}}}function yh(e,t){return e==="img"?"image":e==="video"||t.includes("poster")?"video":"media"}function xh(e){return e.some(t=>t.startsWith("cms:"))?"cms-media-field":e.some(t=>/^(\.?\/|\/)/.test(t))?"local-file-reference":"asset-id"}var hi=["set-class-name-source","apply-style-draft"],Hc=["block","inline-block","inline","flex","inline-flex","grid","inline-grid","hidden"],Yc=["static","fixed","absolute","relative","sticky"],Si=["z-auto","z-0","z-10","z-20","z-30","z-40","z-50"],Gc=["flex-row","flex-row-reverse","flex-col","flex-col-reverse"],Zc=["flex-nowrap","flex-wrap","flex-wrap-reverse"],gi=["grow","grow-0"],yi=["shrink","shrink-0"],bi=["basis-auto","basis-full","basis-1/2","basis-1/3","basis-2/3","basis-1/4","basis-3/4","basis-px"],Ii=["order-first","order-last","order-none","order-1","order-2","order-3","order-4","order-5","order-6"],ki=["grid-cols-1","grid-cols-2","grid-cols-3","grid-cols-4","grid-cols-5","grid-cols-6","grid-cols-12","grid-cols-none","grid-cols-subgrid"],Ri=["grid-rows-1","grid-rows-2","grid-rows-3","grid-rows-4","grid-rows-5","grid-rows-6","grid-rows-none","grid-rows-subgrid"],Ci=["col-auto","col-span-1","col-span-2","col-span-3","col-span-4","col-span-6","col-span-12","col-span-full"],vi=["row-auto","row-span-1","row-span-2","row-span-3","row-span-4","row-span-6","row-span-full"],Qc=["items-start","items-end","items-center","items-baseline","items-stretch"],qc=["justify-normal","justify-start","justify-end","justify-center","justify-between","justify-around","justify-evenly","justify-stretch"],el=["overflow-auto","overflow-hidden","overflow-clip","overflow-visible","overflow-scroll"],xi=["font-sans","font-serif","font-mono"],wi=["font-thin","font-extralight","font-light","font-normal","font-medium","font-semibold","font-bold","font-extrabold","font-black"],Pi=["text-xs","text-sm","text-base","text-lg","text-xl","text-2xl","text-3xl","text-4xl","text-5xl","text-6xl","text-7xl","text-8xl","text-9xl"],Ai=["text-left","text-center","text-right","text-justify","text-start","text-end"],tl=["uppercase","lowercase","capitalize","normal-case"],nl=["underline","overline","line-through","no-underline"],Ti=["indent-0","indent-4","indent-8","indent-12"],rl=["[writing-mode:horizontal-tb]","[writing-mode:vertical-rl]"],ol=["whitespace-normal","whitespace-nowrap","whitespace-pre","whitespace-pre-line","whitespace-pre-wrap","whitespace-break-spaces"],il=["break-normal","break-words","break-all","break-keep"],Ni=["line-clamp-none","line-clamp-1","line-clamp-2","line-clamp-3","line-clamp-4","line-clamp-5","line-clamp-6"],Ei=["tracking-tighter","tracking-tight","tracking-normal","tracking-wide","tracking-wider","tracking-widest"],Fi=["border-solid","border-dashed","border-dotted","border-double","border-hidden","border-none"],Mi=["border","border-0","border-2","border-4","border-8"],sl=["object-contain","object-cover","object-fill","object-none","object-scale-down"],_i=["aspect-auto","aspect-square","aspect-video"],Oi=["shadow-none","shadow-sm","shadow","shadow-md","shadow-lg","shadow-xl","shadow-2xl"],Pk=[{property:"display",exact:Hc,isMatch:e=>e==="gallery-item",options:[...Hc]},{property:"position",exact:Yc,isMatch:e=>e==="cta-shine",options:[...Yc]},{property:"top",isMatch:e=>Br("top",e)},{property:"right",isMatch:e=>Br("right",e)},{property:"bottom",isMatch:e=>Br("bottom",e)},{property:"left",isMatch:e=>Br("left",e)},{property:"zIndex",exact:Si,isMatch:wh,options:[...Si]},{property:"flexDirection",exact:Gc,options:[...Gc]},{property:"flexWrap",exact:Zc,options:[...Zc]},{property:"flexGrow",exact:gi,isMatch:e=>gi.includes(e)||/^grow-\[.+\]$/.test(e),options:[...gi]},{property:"flexShrink",exact:yi,isMatch:e=>yi.includes(e)||/^shrink-\[.+\]$/.test(e)||/^flex-shrink-(?:0|\[.+\])$/.test(e),options:[...yi]},{property:"flexBasis",exact:bi,isMatch:bh,options:[...bi]},{property:"flex",isMatch:e=>/^flex-(?:\d+|auto|initial|none|\[.+\])$/.test(e)},{property:"order",exact:Ii,isMatch:Ih,options:[...Ii]},{property:"gridTemplateColumns",exact:ki,isMatch:kh,options:[...ki]},{property:"gridTemplateRows",exact:Ri,isMatch:Rh,options:[...Ri]},{property:"columns",isMatch:e=>e==="gallery-grid"||/^columns-(?:\d+|auto|3xs|2xs|xs|sm|md|lg|xl|2xl|3xl|4xl|5xl|6xl|7xl|\[.+\])$/.test(e)},{property:"gridColumn",exact:Ci,isMatch:Ch,options:[...Ci]},{property:"gridRow",exact:vi,isMatch:vh,options:[...vi]},{property:"gap",prefix:"gap-",isMatch:e=>e.startsWith("gap-")&&!e.startsWith("gap-x-")&&!e.startsWith("gap-y-")},{property:"gapX",prefix:"gap-x-"},{property:"gapY",prefix:"gap-y-"},{property:"spaceX",prefix:"space-x-"},{property:"spaceY",prefix:"space-y-"},{property:"alignItems",exact:Qc,options:[...Qc]},{property:"alignSelf",isMatch:e=>/^self-(?:auto|start|end|center|stretch|baseline)$/.test(e)},{property:"justifyContent",exact:qc,options:[...qc]},{property:"marginTop",prefix:"mt-",isMatch:e=>xt("m","t",e)},{property:"marginRight",prefix:"mr-",isMatch:e=>xt("m","r",e)},{property:"marginBottom",prefix:"mb-",isMatch:e=>xt("m","b",e)},{property:"marginLeft",prefix:"ml-",isMatch:e=>xt("m","l",e)},{property:"paddingTop",prefix:"pt-",isMatch:e=>xt("p","t",e)},{property:"paddingRight",prefix:"pr-",isMatch:e=>xt("p","r",e)},{property:"paddingBottom",prefix:"pb-",isMatch:e=>xt("p","b",e)},{property:"paddingLeft",prefix:"pl-",isMatch:e=>xt("p","l",e)},{property:"width",prefix:"w-",isMatch:e=>e.startsWith("w-")||al(e)},{property:"height",prefix:"h-",isMatch:e=>e.startsWith("h-")||al(e)},{property:"minWidth",prefix:"min-w-"},{property:"minHeight",prefix:"min-h-"},{property:"maxWidth",isMatch:e=>e==="container"||e.startsWith("max-w-")},{property:"maxHeight",prefix:"max-h-"},{property:"overflow",exact:el,isMatch:e=>/^overflow(?:-[xy])?-.+$/.test(e),options:[...el]},{property:"fontFamily",exact:xi,isMatch:e=>xi.includes(e)||/^font-\[.+\]$/.test(e)||/^font-[a-z][\w-]*$/.test(e)&&!Mh(e),options:[...xi]},{property:"fontSize",exact:Pi,isMatch:ll,options:[...Pi]},{property:"fontWeight",exact:wi,options:[...wi]},{property:"lineHeight",prefix:"leading-"},{property:"letterSpacing",exact:Ei,isMatch:e=>Ei.includes(e)||e.startsWith("tracking-["),options:[...Ei]},{property:"textAlign",exact:Ai,options:[...Ai]},{property:"textTransform",exact:tl,options:[...tl]},{property:"textDecoration",exact:nl,options:[...nl]},{property:"textOverflow",exact:["truncate","text-ellipsis","text-clip"]},{property:"fontStyle",exact:["italic","not-italic"]},{property:"textUnderlineOffset",prefix:"underline-offset-"},{property:"textIndent",exact:Ti,isMatch:Th,options:[...Ti]},{property:"writingMode",exact:rl,options:[...rl]},{property:"whiteSpace",exact:ol,options:[...ol]},{property:"wordBreak",exact:il,options:[...il]},{property:"lineClamp",exact:Ni,isMatch:Ah,options:[...Ni]},{property:"fontVariantNumeric",isMatch:e=>/^(?:normal-nums|ordinal|slashed-zero|lining-nums|oldstyle-nums|proportional-nums|tabular-nums|diagonal-fractions|stacked-fractions)$/.test(e)},{property:"screenReaderOnly",exact:["sr-only","not-sr-only"]},{property:"color",isMatch:Eh},{property:"backgroundColor",isMatch:Sh},{property:"backgroundImage",isMatch:e=>e.startsWith("bg-[url")||e.startsWith("bg-gradient-")},{property:"borderStyle",exact:Fi,options:[...Fi]},{property:"borderWidth",exact:Mi,isMatch:ul,options:[...Mi]},{property:"divideWidth",isMatch:e=>/^divide-[xy](?:-\d+|-0|-reverse)?$/.test(e)},{property:"borderRadius",prefix:"rounded"},{property:"borderColor",isMatch:Ph},{property:"divideColor",isMatch:e=>e.startsWith("divide-")&&!/^divide-[xy](?:-\d+|-0|-reverse)?$/.test(e)},{property:"objectFit",exact:sl,options:[...sl]},{property:"objectPosition",isMatch:e=>/^object-(?:bottom|center|left|left-bottom|left-top|right|right-bottom|right-top|top|\[.+\])$/.test(e)},{property:"aspectRatio",exact:_i,isMatch:Nh,options:[..._i]},{property:"opacity",prefix:"opacity-"},{property:"boxShadow",exact:Oi,isMatch:Fh,options:[...Oi]},{property:"transform",isMatch:_h},{property:"transformOrigin",isMatch:e=>/^origin-(?:center|top|top-right|right|bottom-right|bottom|bottom-left|left|top-left|\[.+\])$/.test(e)},{property:"transitionProperty",isMatch:e=>/^transition(?:-(?:none|all|colors|opacity|shadow|transform|\[.+\]))?$/.test(e)||["motion-link","image-zoom","card-lift","cta-shine","gallery-item-img","showcase-img"].includes(e)},{property:"transitionDuration",isMatch:e=>/^duration-(?:\d+|slow|\[.+\])$/.test(e)},{property:"transitionTimingFunction",isMatch:e=>/^ease-(?:linear|in|out|in-out|\[.+\])$/.test(e)},{property:"animation",isMatch:e=>/^(?:animate-.+|fade-.+|slide-in-.+)$/.test(e)||["section-reveal","scroll-reveal","first-viewport-entrance","media-reveal","media-entrance","gallery-fade-enter","number-pop"].includes(e)},{property:"pointerEvents",exact:["pointer-events-none","pointer-events-auto"]},{property:"cursor",isMatch:e=>/^cursor-(?:auto|default|pointer|wait|text|move|help|not-allowed|none|context-menu|progress|cell|crosshair|vertical-text|alias|copy|no-drop|grab|grabbing|all-scroll|col-resize|row-resize|n-resize|e-resize|s-resize|w-resize|ne-resize|nw-resize|se-resize|sw-resize|ew-resize|ns-resize|nesw-resize|nwse-resize|zoom-in|zoom-out|\[.+\])$/.test(e)},{property:"userSelect",exact:["select-none","select-text","select-all","select-auto"]},{property:"outlineStyle",isMatch:e=>/^outline(?:-(?:none|hidden|solid|dashed|dotted|double|\d+|\[.+\]))?$/.test(e)},{property:"resize",exact:["resize-none","resize","resize-y","resize-x"]},{property:"ringWidth",isMatch:e=>/^ring(?:-\d+|-\[.+\]|-inset)?$/.test(e)},{property:"ringColor",isMatch:e=>e.startsWith("ring-")&&!/^ring(?:-\d+|-\[.+\]|-inset)?$/.test(e)},{property:"backdropFilter",isMatch:e=>/^backdrop-(?:blur|brightness|contrast|grayscale|hue-rotate|invert|opacity|saturate|sepia)(?:-.+)?$/.test(e)},{property:"overscrollBehavior",isMatch:e=>/^overscroll(?:-[xy])?-(?:auto|contain|none)$/.test(e)},{property:"scrollMarginTop",prefix:"scroll-mt-"}];function cl(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:hi,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element"}]};if(t.source?.expression){let n=t.source.expression,r=typeof t.resolvedValue=="string"?t.resolvedValue:t.value!==n?t.value:void 0;return typeof r!="string"?{kind:"class-name-source",className:"",sourceKind:"dynamic-expression",editable:!1,operationBoundary:[],sourcePath:n,diagnostics:[{code:t.resolvedValue===void 0?"dynamic-binding":"non-string-binding",message:t.resolvedValue===void 0?"Style binding is dynamic and cannot be edited":"Style binding must resolve to a static string before it can be edited"}]}:{kind:"class-name-source",className:r,sourceKind:"static-expression",editable:!0,operationBoundary:hi,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:hi}}function ll(e){return Pi.includes(e)||/^text-\[.+\]$/.test(e)&&!Oh(e.slice(6,-1))}function Eh(e){return!e.startsWith("text-")||Ai.includes(e)?!1:!ll(e)}function Sh(e){return e.startsWith("bg-")?!(e.startsWith("bg-gradient-")||e.startsWith("bg-[url")||["bg-fixed","bg-local","bg-scroll","bg-clip-border","bg-clip-padding","bg-clip-content","bg-clip-text","bg-origin-border","bg-origin-padding","bg-origin-content"].includes(e)):!1}function ul(e){return Mi.includes(e)||/^border-\[.+\]$/.test(e)||/^border-(?:x|y|t|r|b|l)(?:-\d+|-\[.+\])?$/.test(e)}function Br(e,t){let n=e==="top"||e==="bottom"?"y":e==="right"||e==="left"?"x":"";return new RegExp(`^-?${e}-.+$`).test(t)||new RegExp(`^-?inset-${n}-.+$`).test(t)||/^-?inset-.+$/.test(t)}function bh(e){return bi.includes(e)||/^basis-\[.+\]$/.test(e)}function Ih(e){return Ii.includes(e)||/^-?order-(?:\d+|\[.+\])$/.test(e)}function kh(e){return ki.includes(e)||/^grid-cols-\[.+\]$/.test(e)}function Rh(e){return Ri.includes(e)||/^grid-rows-\[.+\]$/.test(e)}function Ch(e){return Ci.includes(e)||/^(?:col|col-span|col-start|col-end)-.+$/.test(e)}function vh(e){return vi.includes(e)||/^(?:row|row-span|row-start|row-end)-.+$/.test(e)}function wh(e){return Si.includes(e)||/^-?z-(?:\d+|\[.+\])$/.test(e)}function Ph(e){return e.startsWith("border-")?!(Fi.includes(e)||ul(e)||e.startsWith("border-spacing-")||/^border-(?:x|y|t|r|b|l)(?:-|$)/.test(e)):!1}function Ah(e){return Ni.includes(e)||/^line-clamp-\[.+\]$/.test(e)}function Th(e){return Ti.includes(e)||/^-?indent-\[.+\]$/.test(e)}function Nh(e){return _i.includes(e)||/^aspect-\[.+\]$/.test(e)}function Fh(e){return Oi.includes(e)||/^shadow-(?:\[.+\]|[a-z][\w-]*)$/.test(e)}function Mh(e){return wi.includes(e)}function xt(e,t,n){let r=t==="t"||t==="b"?"y":"x";return new RegExp(`^-?${e}${t}-.+$`).test(n)||new RegExp(`^-?${e}${r}-.+$`).test(n)||new RegExp(`^-?${e}-.+$`).test(n)}function al(e){return/^size-.+$/.test(e)}function _h(e){return e==="transform"||e==="transform-gpu"||e==="transform-none"||e.startsWith("translate-")||e.startsWith("-translate-")||e.startsWith("scale-")||e.startsWith("-scale-")||e.startsWith("rotate-")||e.startsWith("-rotate-")||e.startsWith("skew-")||e.startsWith("-skew-")}function Oh(e){return e.startsWith("#")||e.startsWith("rgb")||e.startsWith("hsl")||e.startsWith("oklch")||e.startsWith("color(")}import{createHash as Lh}from"node:crypto";var wn=class{constructor(t){this.original=new Map,this.files=new Map,this.versions=new Map;for(let n of t)this.original.set(n.path,n.content),this.files.set(n.path,n.content),this.versions.set(n.path,n.version??1)}async readFile(t){let n=this.files.get(t);if(n===void 0)throw new Error(`Snapshot file not found: ${t}`);return n}async readFileBytes(t){return Buffer.from(await this.readFile(t),"utf8")}async getFileInfo(t){let n=this.files.get(t);return n===void 0?null:{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async writeFile(t,n){this.files.set(t,n)}async createExclusive(t,n){if(this.files.has(t))throw Object.assign(new Error(`Snapshot file already exists: ${t}`),{code:"EEXIST"});this.files.set(t,n)}async deleteFile(t){this.files.delete(t)}async exists(t){return this.files.has(t)}async listFiles(t={}){let n=t.roots??[],r=[...this.files.keys()].filter(a=>n.length===0?!0:n.some(c=>a===c||a.startsWith(`${c}/`))),o=[],i=new Set,s=0;for(let a of r.sort()){let c=Buffer.byteLength(this.files.get(a)??"","utf8"),l=a.split("/").length;if(t.maxDepth!==void 0&&l>t.maxDepth){i.add("max-depth");continue}if(t.maxFiles!==void 0&&o.length>=t.maxFiles){i.add("max-files");break}if(t.maxTotalBytes!==void 0&&s+c>t.maxTotalBytes){i.add("max-total-bytes");break}o.push({path:a,sizeBytes:c}),s+=c}return i.size>0?{files:o,truncated:{reasons:[...i]}}:{files:o}}getVersion(t){return this.versions.get(t)??0}bumpVersion(t){let n=this.getVersion(t)+1;return this.versions.set(t,n),n}getChangedFiles(){let t=new Set([...this.original.keys(),...this.files.keys()]),n=[];for(let r of[...t].sort()){let o=this.original.get(r),i=this.files.get(r);o!==i&&n.push({path:r,before:o,after:i})}return n}};function ie(e){return`sha256:${Lh("sha256").update(e).digest("hex")}`}function pl(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:ie(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=Dh(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:ie(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Unable to locate JSX element for key ${t.identity.key}`}]};let r=n.openingElement,o=r.attributes.find(c=>c.type==="JSXAttribute"&&c.name.type==="JSXIdentifier"&&c.name.name==="className"),i={key:e.key,routeId:e.route.routeId,filePath:t.sourceFile,componentName:t.componentName,openingElementRange:fl(r),version:{documentVersion:e.route.graph.version,contentHash:ie(e.route.source)}};if(!o)return{...i,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element."}]};let s=o.value,a=s?.type==="StringLiteral"?"stringLiteral":"expression";return{...i,sourceKind:a,attrRaw:dl(e.route.source,o),valueRaw:s?dl(e.route.source,s):null,attrRange:fl(o),diagnostics:[]}}function ml(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 Dh(e,t){let n=Ze({source:e,profile:At({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=q(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:Bh(t.sourceRange)});return!r.ok||r.match.node.type!=="JSXElement"?null:r.match.node}function hl(e){let t=Ze({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 dl(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 Bh(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}import*as Qi from"@babel/parser";import $i from"@babel/traverse";import*as x from"@babel/types";import*as lt from"node:path";import*as Sl from"@babel/parser";import Bi from"@babel/traverse";import*as sn from"@babel/types";import*as J from"@babel/types";function Ur(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?jr(n,t):null}if(e.isMemberExpression()){let n=Jh(e.node),r=jh(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?jr(o,[...r,...t]):null}return e.isAwaitExpression()||Di(e.node)?Et(zh(e.node),t,"awaited or fetched expression"):null}function jh(e){let t=[],n=e;for(;J.isMemberExpression(n);){if(n.computed)if(J.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(J.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(J.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return J.isIdentifier(n)?t:null}function jr(e,t=[]){let n=$h(e,t);if(n)return n;let r=Uh(e,t);if(r)return r;let o=Vh(e,t);return o||null}function An(e){return e?.kind==="api-source"}function $h(e,t){if(e.path.isVariableDeclarator()&&J.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&Li(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return Et(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&J.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(c=>J.isObjectProperty(c)&&xl(c)==="data"&&Pn(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&Li(a.node))return Et(e.identifier.name,t,"query hook data binding")}let n=Kh(e);if(!n||xl(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()||!Li(i.node)?null:Et(e.identifier.name,t,"query hook data binding")}function Uh(e,t){if(e.path.isVariableDeclarator()&&J.isArrayPattern(e.path.node.id)){let a=e.path.get("init");if(!a?.isCallExpression()||!yl(a.node))return null;let[c,l]=e.path.node.id.elements;return!J.isIdentifier(c)||c.name!==e.identifier.name||!J.isIdentifier(l)?null:gl(e,l.name)?Et(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()||!yl(o.node)||n.node.elements.findIndex(a=>a===e.path.node)!==0)return null;let s=n.node.elements[1];return J.isIdentifier(s)&&gl(e,s.name)?Et(e.identifier.name,t,"state setter is updated by API data"):null}function Vh(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()?Et(e.identifier.name,t,"awaited binding result"):Di(r.node)?Et(e.identifier.name,t,"fetch-backed binding result"):null:null}function Kh(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 Pn(e,t){return J.isIdentifier(e)?e.name===t:J.isAssignmentPattern(e)?Pn(e.left,t):J.isObjectPattern(e)?e.properties.some(n=>J.isObjectProperty(n)?Pn(n.value,t):Pn(n.argument,t)):J.isArrayPattern(e)?e.elements.some(n=>!!n&&Pn(J.isRestElement(n)?n.argument:n,t)):!1}function gl(e,t){let n=!1,r=!1;return e.scope.path.traverse({CallExpression(i){Di(i.node)&&(n=!0),(Xh(i.node.callee,t)||i.node.arguments.some(s=>J.isIdentifier(s)&&s.name===t))&&(r=!0)}}),n&&r}function Li(e){let t=Vr(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function yl(e){return Vr(e.callee)==="useState"}function Di(e){return $r(e,t=>J.isCallExpression(t)&&Vr(t.callee)==="fetch")}function Jh(e){let t=e;for(;J.isMemberExpression(t);)t=t.object;return J.isIdentifier(t)?t.name:null}function xl(e){return e.computed?null:J.isIdentifier(e.key)?e.key.name:J.isStringLiteral(e.key)?e.key.value:null}function Vr(e){return J.isIdentifier(e)?e.name:J.isMemberExpression(e)&&J.isIdentifier(e.property)?e.property.name:null}function Xh(e,t){return $r(e,n=>J.isIdentifier(n)&&n.name===t)}function $r(e,t){if(t(e))return!0;let n=J.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(J.isNode(i)&&$r(i,t))return!0;continue}if(J.isNode(o)&&$r(o,t))return!0}return!1}function zh(e){return J.isIdentifier(e)?e.name:J.isCallExpression(e)?Vr(e.callee)??"api":J.isAwaitExpression(e)?"awaited-api":"api"}function Et(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:Wh(e,t),reason:n}}function Wh(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var bl=typeof Bi=="function"?Bi:Bi.default;function Il(e,t){let n=Rl(e);if(!n)return{allowed:!0};let r=!1;return bl(n,{CallExpression(o){if(!Cl(o.node,t.sourceRange)||!Hh(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||An(Ur(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=Rl(e);if(!n)return{allowed:!0};let r=!1;return bl(n,{JSXExpressionContainer(o){Cl(o.node,t.sourceRange)&&(sn.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 Rl(e){try{return Sl.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Hh(e){let t=e.callee;return sn.isMemberExpression(t)&&sn.isIdentifier(t.property)&&t.property.name==="map"}function Cl(e,t){let n=e.loc;return n?El({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&El({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function El(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 ee from"@babel/types";function vl(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 qe(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return Ot(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(ee.isObjectPattern(n)||ee.isArrayPattern(n))return Ot(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(Gh(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function Ot(e,t,n=!1){return ee.isIdentifier(e)?e.name===t&&n:ee.isObjectPattern(e)?e.properties.some(r=>ee.isObjectProperty(r)?Ot(r.value,t,n):Ot(r.argument,t,n)):ee.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=ee.isRestElement(r)?r.argument:r;return Ot(o,t,n)}):ee.isAssignmentPattern(e)?Ot(e.left,t,!0):ee.isRestElement(e)?Ot(e.argument,t,n):!1}function an(e,t){if(e.path.isObjectPattern()){if(t){let r=Ue(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:qe(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:qe(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=wl(r),i=!1,s=o?o.initBinding&&ji(o.initBinding)?(i=qe(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=an(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=Ue(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||qe(e)}}}}let n=qh(e);if(n){let r=Yh(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||qe(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=Zh(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:qe(e)}}let i=Tn(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:qe(e)}:null}if(ji(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:qe(e)}}return null}function Yh(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=wl(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=ji(i)?(a=qe(i),[...s]):(()=>{let u=an(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=Ue(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||qe(t)}:null}function wl(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=eg(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function ji(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function Gh(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Zh(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=Ue(i.node,t);if(a)return a}return null}function Pl(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=Kr(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=Tn(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=Qh(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=Tn(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 Kr(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=Tn(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&Ue(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=Kr(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=Kr(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=Kr(r,t);if(o)return o}}return null}function Ue(e,t,n=[]){if(ee.isIdentifier(e))return e.name===t?n:null;if(ee.isObjectPattern(e)){for(let r of e.properties)if(ee.isObjectProperty(r)){let o=Tn(r);if(!o)continue;let i=Ue(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(ee.isRestElement(r)){let o=Ue(r.argument,t,n);if(o)return o}}if(ee.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=ee.isRestElement(o)?o.argument:o,s=Ue(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return ee.isAssignmentPattern(e)?Ue(e.left,t,n):null}function Qh(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function qh(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 Tn(e){return e.computed?null:ee.isIdentifier(e.key)?e.key.name:ee.isStringLiteral(e.key)?e.key.value:null}function eg(e){let t=[],n=e;for(;ee.isMemberExpression(n);){if(n.computed)if(ee.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(ee.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(ee.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return ee.isIdentifier(n)?{base:n.name,path:t}:null}var Rt=typeof $i=="function"?$i:$i.default;function ce(e){return e.structuralPath.includes("#repeat:")||e.isRepeatItemRoot||e.isRepeatRegion?{kind:"jsx-node",strategy:"source-range",sourceRange:e.sourceRange}:{kind:"jsx-node",strategy:"structural-path",file:e.file,component:e.component,structuralPath:e.structuralPath,expectedRange:e.sourceRange}}function cn(e){return{file:e.file,component:e.component}}function tg(e){return e.target.kind==="node"?e.target.key:null}function ng(e){return"kind"in e}function Jr(e){return!ng(e)}function zi(e,t){let n=lt.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=lt.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Ui(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=st(n,ce(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function qi(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 Ve(e){try{return Qi.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function rg(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function og(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 ne(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function Bt(e,t){let n=ne(e);return!!(n&&Ke(t,n))}function Ke(e,t){return t.start>=e.start&&t.end<=e.end}function Jl(e){if(x.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(x.isJSXMemberExpression(e)){let t=e;for(;x.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function ig(e,t){let n=ne(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);if(!a||Bt(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=Jl(i.node.name);s&&o(s,i)}}),[...r].sort()}function Al(e,t,n){let r=Ve(e);if(!r)return{ok:!0};let o=q(r,ce(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=q(r,ce(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};if(iu(o.match.path,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let s=ig(o.match.path,i.match.path);return s.length>0?{ok:!1,bindingNames:s}:{ok:!0}}function Tl(e,t,n){let r=St(t,n);return r?ct(e,r):null}function St(e,t){let n=q(e,ce(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:Zi(e,t)}function ct(e,t){let n=t.findParent(b=>b.isArrowFunctionExpression()||b.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(b=>b===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(!x.isIdentifier(l)||l.name!=="map"||c.computed)return null;let u=a.get("object"),f=Hr(e,u.node),p=r.node.params.map(b=>Hr(e,b)),m=ne(i.node),S=ne(r.node);return!f||p.some(b=>b.length===0)||!m||!S?null:{callStart:m.start,callEnd:m.end,callbackStart:S.start,callbackEnd:S.end,collectionExpression:f,callbackParams:p,mapOperator:x.isOptionalMemberExpression(c)&&c.optional?"?.map":".map",collectionNeedsParens:rs(u.node),callbackPath:r,collectionPath:u}}function Hr(e,t){let n=ne(t);return n?e.slice(n.start,n.end):""}function Xr(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function sg(e,t){let n=ne(e.node);return n?ag(t).some(r=>{let o=ne(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function ag(e){let t=e.callbackPath.node.body;return x.isBlockStatement(t)?bt(t.body):kt(t)}function bt(e){let t=[];for(let n of e){if(x.isReturnStatement(n)){n.argument&&t.push(...kt(n.argument));continue}if(x.isBlockStatement(n)){t.push(...bt(n.body));continue}if(x.isIfStatement(n)){let r=x.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...bt(r)),n.alternate){let o=x.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...bt(o))}continue}if(x.isSwitchStatement(n)){for(let r of n.cases)t.push(...bt(r.consequent));continue}x.isTryStatement(n)&&(t.push(...bt(n.block.body)),n.handler&&t.push(...bt(n.handler.body.body)),n.finalizer&&t.push(...bt(n.finalizer.body)))}return t}function kt(e){return x.isJSXElement(e)?cg(e)?Nl(e.children):[e]:x.isJSXFragment(e)?Nl(e.children):x.isParenthesizedExpression(e)||x.isTSAsExpression(e)||x.isTSSatisfiesExpression(e)||x.isTSNonNullExpression(e)||x.isTSTypeAssertion(e)?kt(e.expression):x.isConditionalExpression(e)?[...kt(e.consequent),...kt(e.alternate)]:x.isLogicalExpression(e)&&au(e.operator)?kt(e.right):[]}function Nl(e){return e.flatMap(t=>x.isJSXElement(t)||x.isJSXFragment(t)?kt(t):x.isJSXExpressionContainer(t)&&(x.isJSXElement(t.expression)||x.isJSXFragment(t.expression)||x.isConditionalExpression(t.expression)||x.isLogicalExpression(t.expression))?kt(t.expression):[])}function cg(e){let t=e.openingElement.name;return x.isJSXIdentifier(t)?t.name==="Fragment":x.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function lg(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function Vi(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function Fl(e,t,n,r={}){if(!r.preserveConditionalBoundary&&iu(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=ne(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(c=>ns(c)).map(c=>n.callbackPath.scope.getBinding(c)?.path.node).filter(Boolean)),s=new Set,a=(c,l)=>{let u=l.scope.getBinding(c);if(!u||Bt(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=Jl(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function Ml(e,t,n){let r=ne(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>ns(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return es(e,s=>{let a=s.scope.getBinding(s.node.name);if(!a||Bt(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 ug(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>ns(a)).map(a=>e.callbackPath.scope.getBinding(a)?.path.node).filter(Boolean)),r=new Set,o=(a,c)=>{let l=c.scope.getBinding(a);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(x.isIdentifier(l))o(l.name,c);else{let u=dg(l);u&&o(u,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function dg(e){let t=e;for(;x.isTSQualifiedName(t);)t=t.left;return x.isIdentifier(t)?t.name:null}function Xl(e,t){let n=ne(e.node),r=new Set;return es(e,o=>{let i=o.scope.getBinding(o.node.name);if(!i||n&&Bt(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 es(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function fg(e){let t=pg(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=cu(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=vg({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=ou(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?rs(o):!0}}}function pg(e,t,n){let r=Hl(e,t);if(Yl(e,r),Gl(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 Rt(e,{JSXElement(s){nu(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:ts(o[0])!==n?{ok:!1,reason:"Cannot move prop-backed repeat child because the call site is outside the target component"}:{ok:!0,path:o[0]}}function mg(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=>Fn(a.file)));if(!t.has(Fn(e.sourceFile))||!t.has(Fn(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(Fn(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=xg(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=Ve(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=hg(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=zl({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!Je(s.file,e.targetFile)||ts(s.path)!==e.targetComponent?{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component because the only call site is outside the target component"}:{ok:!0,callSitePath:s.path}}function hg(e,t){let n=new Map,r=i=>{let s=ln(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 gg(i,n))o=r(s)||o}return[...n.values()]}function gg(e,t){let n=[],r=yg(e,t);for(let o of e.ast.program.body){if(x.isExportDefaultDeclaration(o)&&x.isIdentifier(o.declaration)&&(r.get(o.declaration.name)?.length??0)>0){let i=r.get(o.declaration.name)??[];for(let s of i){if(s.namespace){let a=_n(s.namespace,o.declaration.name,"default");a&&n.push({file:e.file,namespace:a,exportName:s.exportName});continue}n.push({file:e.file,exportName:"default"})}continue}if(x.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=On(e.file,o.source.value);for(let s of o.specifiers){if(x.isExportNamespaceSpecifier(s)){let l=It(s.exported);for(let u of t.values())Je(u.file,i)&&n.push({file:e.file,namespace:Wi(l,u.namespace),exportName:u.exportName});continue}if(!x.isExportSpecifier(s))continue;let a=It(s.local),c=[...t.values()].filter(l=>Je(l.file,i)&&Lt(l.namespace,a));if(c.length>0){let l=It(s.exported);for(let u of c){let f=_n(u.namespace,a,l);f&&n.push({file:e.file,namespace:f,exportName:u.exportName})}continue}t.has(ln({file:i,exportName:a}))&&n.push({file:e.file,exportName:It(s.exported)})}continue}if(x.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!x.isExportSpecifier(i))continue;let s=It(i.local),a=r.get(s)??[];if(a.length>0){let c=It(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let u=_n(l.namespace,s,c);u&&n.push({file:e.file,namespace:u,exportName:l.exportName})}}}continue}if(x.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=On(e.file,o.source.value),s=o.exported;if(s){let a=It(s);for(let c of t.values())Je(c.file,i)&&n.push({file:e.file,namespace:Wi(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())Je(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function Wi(e,t){return t?`${e}.${t}`:e}function Lt(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function _n(e,t,n){return!Lt(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function yg(e,t){let n=new Map,r=(i,s)=>{let a=n.get(i)??[];a.push(s),n.set(i,a)};for(let i of e.ast.program.body){if(!x.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=On(e.file,i.source.value);for(let a of i.specifiers){if(x.isImportDefaultSpecifier(a)){let c=t.get(ln({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(u=>Je(u.file,s)&&Lt(u.namespace,"default"));for(let u of l){let f=_n(u.namespace,"default",a.local.name);f&&r(a.local.name,{...u,namespace:f})}continue}if(x.isImportSpecifier(a)){let c=It(a.imported),l=[...t.values()].filter(f=>Je(f.file,s)&&Lt(f.namespace,c));for(let f of l)r(a.local.name,f);let u=t.get(ln({file:s,exportName:c}));u&&r(a.local.name,u);continue}if(x.isImportNamespaceSpecifier(a))for(let c of t.values())Je(c.file,s)&&r(a.local.name,{...c,namespace:Wi(a.local.name,c.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(x.isVariableDeclaration(i))for(let s of i.declarations){if(!x.isIdentifier(s.id)||!s.init)continue;let a=un(s.init);if(!a||!x.isIdentifier(a))continue;let c=n.get(a.name)??[];if(c.length===0)continue;let l=n.get(s.id.name)??[],u=new Set(l.map(ln));for(let f of c){let p=_n(f.namespace,a.name,s.id.name),m=p?{...f,namespace:p}:f,S=ln(m);u.has(S)||(r(s.id.name,m),u.add(S),o=!0)}}}return n}function ln(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${Yi(e.file)}#${t}`}function It(e){return x.isIdentifier(e)?e.name:e.value}function xg(e,t){for(let n of e.program.body){if(x.isExportDefaultDeclaration(n)){let o=n.declaration;if((x.isFunctionDeclaration(o)||x.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(x.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!x.isExportNamedDeclaration(n))continue;let r=n.declaration;if((x.isFunctionDeclaration(r)||x.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(x.isVariableDeclaration(r)){for(let o of r.declarations)if(x.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!x.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:x.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function zl(e){let t=Eg(e),n=[],r=Gl(e.ast,t);return Rt(e.ast,{JSXElement(o){Je(e.file,e.sourceFile)&&ts(o)===e.sourceComponent||nu(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function Wl(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function Hl(e,t){let n=Wl();return Rt(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function Eg(e){let t=Wl();return Je(e.file,e.sourceFile)&&Sg(t,Hl(e.ast,e.sourceComponent)),Rt(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=On(e.file,o),s=e.componentIdentities.filter(a=>Je(a.file,i));if(s.length!==0)for(let a of r.specifiers){let c=n.scope.getBinding(a.local.name);if(c){if(x.isImportDefaultSpecifier(a)&&s.some(l=>l.exportName==="default")&&t.localBindings.add(c),x.isImportDefaultSpecifier(a)){let l=s.filter(u=>Lt(u.namespace,"default"));if(l.length>0){let u=t.namespaceMembers.get(c)??new Set;for(let f of l){let p=Ol(f,"default");p&&u.add(p)}t.namespaceMembers.set(c,u)}continue}if(x.isImportSpecifier(a)){let l=x.isIdentifier(a.imported)?a.imported.name:a.imported.value,u=s.filter(f=>Lt(f.namespace,l));if(u.length>0){let f=t.namespaceMembers.get(c)??new Set;for(let p of u){let m=Ol(p,l);m&&f.add(m)}t.namespaceMembers.set(c,f);continue}s.some(f=>!f.namespace&&f.exportName===l)&&t.localBindings.add(c);continue}if(x.isImportNamespaceSpecifier(a))for(let l of s){let u=l.namespace?`${l.namespace}.${l.exportName}`:l.exportName,f=t.namespaceMembers.get(c)??new Set;f.add(u),t.namespaceMembers.set(c,f)}}}}}),Yl(e.ast,t),t}function Sg(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 Yl(e,t){Rt(e,{VariableDeclarator(n){if(!n.node.init)return;let r=un(n.node.init);if(r){if(x.isIdentifier(n.node.id)){let o=Dt(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&Hi(t,i,o);return}if(x.isObjectPattern(n.node.id)){let o=Dt(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&ql(n.node.id,o.namespaceMembers,t,n)}}}})}function Gl(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return Rt(e,{ReferencedIdentifier(r){if(n){r.stop();return}bg(r)||!r.isIdentifier()||!Zl(r,t)||Ig(r,t)||kg(r)||(n=!0,r.stop())}}),n}function bg(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 Zl(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)&&Dt(r.node,t,r)?r:null}function Ig(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!_l(e,r))return!1;let o=Zl(e,t);if(!o)return!1;if(un(r.node)===o.node)return!!Dt(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&_l(e,a)&&!!Dt(a.node,t,a)}function kg(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function _l(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Dt(e,t,n){let r=un(e);if(!r)return null;if(x.isIdentifier(r)){let a=n.scope.getBinding(r.name);if(!a)return null;let c=t.namespaceMembers.get(a);return t.localBindings.has(a)?{local:!0,namespaceMembers:new Set,unsupported:!1}:c?{local:!1,namespaceMembers:new Set(c),unsupported:!1}:null}if(x.isObjectExpression(r))return Rg(r,t,n);let o=tu(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?Ql(s,o.slice(1).join(".")):null}function Rg(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!x.isObjectProperty(i))continue;let s=eu(i);if(!s||!x.isExpression(i.value)){x.isExpression(i.value)&&(o||=Dt(i.value,t,n)!==null);continue}let a=Dt(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 Ql(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 Hi(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 ql(e,t,n,r){for(let o of e.properties){if(x.isRestElement(o)){if(x.isIdentifier(o.argument)){let c=r.scope.getBinding(o.argument.name);c&&Hi(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!x.isObjectProperty(o))continue;let i=eu(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=Ql(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=x.isAssignmentPattern(o.value)?o.value.left:o.value;if(x.isIdentifier(a)){let c=r.scope.getBinding(a.name);c&&Hi(n,c,s);continue}if(x.isObjectPattern(a)&&s.namespaceMembers.size>0){ql(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function eu(e){return e.computed?x.isStringLiteral(e.key)||x.isNumericLiteral(e.key)?String(e.key.value):null:Cg(e.key)}function Cg(e){return x.isIdentifier(e)?e.name:x.isStringLiteral(e)||x.isNumericLiteral(e)?String(e.value):null}function un(e){return x.isParenthesizedExpression(e)||x.isTSAsExpression(e)||x.isTSSatisfiesExpression(e)||x.isTSNonNullExpression(e)||x.isTSTypeAssertion(e)?un(e.expression):x.isExpression(e)?e:null}function tu(e){if(x.isIdentifier(e))return[e.name];if((x.isMemberExpression(e)||x.isOptionalMemberExpression(e))&&!e.computed&&x.isIdentifier(e.property)){let t=un(e.object),n=t?tu(t):null;return n?[...n,e.property.name]:null}return null}function Ol(e,t){if(!Lt(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 nu(e,t){let n=e.node.openingElement.name;if(x.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=ru(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 ru(e){if(x.isJSXIdentifier(e))return[e.name];if(x.isJSXMemberExpression(e)){let t=ru(e.object);return t?[...t,e.property.name]:null}return null}function ts(e){let t=e.getFunctionParent();if(!t)return null;if(t.isFunctionDeclaration())return t.node.id?.name??null;if(t.isArrowFunctionExpression()||t.isFunctionExpression()){let n=t.parentPath;if(n?.isVariableDeclarator()&&x.isIdentifier(n.node.id))return n.node.id.name}return null}function vg(e){let t=ne(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||Bt(a.path.node,t))return;let c=Ag(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=Ng(e.callSitePath,c.propName,e.source);if(!u.ok){o=u.reason;return}let f=wg(u.expression,c.remainingPath);if(!f){o="Cannot move prop-backed repeat child because the mapped prop path is not a portable expression";return}let p=Xl(u.expressionPath,e.targetParentPath);if(!p.ok){o=p.reason??`Cannot move prop-backed repeat child because the mapped prop source is not visible at the target: ${p.bindingNames.join(", ")}`;return}n.set(`${c.range.start}:${c.range.end}`,{...c.range,text:f});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:Fg(e.source,t,[...n.values()])}}function wg(e,t){if(t.length===0)return e;let n=ou(e);if(!n)return null;let r=rs(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=Pg(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function Pg(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function Ag(e,t,n){let r=Tg(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=an(t,o);if(!i)return null;let s=r?.range??ne(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function Tg(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!Bt(n.node,t)||n.node.computed||!x.isIdentifier(n.node.property))return null;let r=ne(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function Ng(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()&&x.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=Hr(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 Fg(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 ou(e){try{let n=Qi.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=x.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&x.isExpression(r)?r:null}catch{return null}}function Mg(e){let t=ne(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||Bt(s.path.node,t))return;let a=Ll(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let u=Ll(c,e.targetFile,e.targetFile);(!u||u.moduleFile!==a.moduleFile||!_g(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 es(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 _g(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 Ll(e,t,n){let r=Og(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=On(t,i),a=i.startsWith(".")?zi(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=x.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 Og(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function On(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?lt.normalize(lt.join(lt.dirname(e),t)).replace(/\\/g,"/"):t}function Je(e,t){return Yi(e)===Yi(t)}function Yi(e){let t=Fn(e);return t.endsWith("/index")?t.slice(0,-6):t}function Fn(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function ns(e){let t=[],n=r=>{if(r){if(x.isIdentifier(r)){t.push(r.name);return}if(x.isObjectPattern(r)){for(let o of r.properties){if(x.isRestElement(o)){n(o.argument);continue}x.isObjectProperty(o)&&n(o.value)}return}if(x.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(x.isAssignmentPattern(r)){n(r.left);return}if(x.isRestElement(r)){n(r.argument);return}x.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function Lg(e){let t=[];for(let n of e.callbackPath.node.params){if(x.isIdentifier(n)){t.push(n.name);continue}if(x.isRestElement(n)&&x.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 Dg(e,t){return{...e,callbackParams:t}}function Dl(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function rs(e){return!(x.isIdentifier(e)||x.isThisExpression(e)||x.isMemberExpression(e)||x.isOptionalMemberExpression(e)||x.isCallExpression(e)||x.isOptionalCallExpression(e))}function iu(e,t){return su(e,t).length>0}function Ki(e,t){let n=ne(e.node),r=ne(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()&&!Bg(o,n,r)))return!0;o=o.parentPath}return!1}function Bg(e,t,n){let r=ne(e.node.consequent);if(r&&Ke(r,t)&&!Ke(r,n))return!1;let o=e.node.alternate?ne(e.node.alternate):null;return!(o&&Ke(o,t)&&!Ke(o,n))}function su(e,t){let n=ne(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=ne(o.node.consequent),a=ne(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()&&au(o.node.operator)){let s=ne(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 Bl(e,t,n,r){let o=su(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=Hr(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=jg(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${Ug(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function jg(e,t){return $g(e.node)?t:`(${t})`}function $g(e){return x.isIdentifier(e)||x.isThisExpression(e)||x.isSuper(e)||x.isMemberExpression(e)||x.isOptionalMemberExpression(e)||x.isCallExpression(e)||x.isOptionalCallExpression(e)||x.isBooleanLiteral(e)||x.isNumericLiteral(e)||x.isStringLiteral(e)||x.isNullLiteral(e)||x.isUnaryExpression(e)}function au(e){return e==="&&"||e==="||"||e==="??"}function Ug(e){return e.trim().startsWith("<")?e:`(${e})`}function cu(e,t){let n=ne(e.node),r=ne(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=jl(e),i=jl(t);if(!o||!i||!Vg(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=Kg(s.node,n);if(a&&!Ke(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=ne(s.node.right);if(a&&Ke(a,n)&&!Ke(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())&&Jg(s)){let a=ne(s.node.body)??ne(s.node);if(a&&!Ke(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 jl(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?ne(t.node.argument):null;if(t.isArrowFunctionExpression()&&(x.isJSXElement(t.node.body)||x.isJSXFragment(t.node.body)||x.isConditionalExpression(t.node.body)||x.isLogicalExpression(t.node.body)))return ne(t.node.body);t=t.parentPath}return null}function Vg(e,t){return e.start===t.start&&e.end===t.end}function Kg(e,t){let n=ne(e.consequent);if(n&&Ke(n,t))return n;let r=ne(e.alternate);return r&&Ke(r,t)?r:null}function Jg(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(x.isMemberExpression(n)||x.isOptionalMemberExpression(n))&&x.isIdentifier(n.property)&&n.property.name==="map"&&!n.computed}var Xg={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 zr(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=Xg[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 zg(e,t){for(let n of e.program.body){if(!x.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>x.isImportDefaultSpecifier(o));if(r&&x.isImportDefaultSpecifier(r))return r.local.name}return null}function Wg(e,t,n){for(let r of e.program.body){if(!x.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>x.isImportSpecifier(i)&&(x.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&x.isImportSpecifier(o))return o.local.name}return null}function $l(e){let t=new Set;return Rt(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function Ul(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function Hg(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=qi(e),o=Ve(t);if(n.exportName!=="default"){let a=o?Wg(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?Ul(r,$l(o)):r;return{localName:c,importStep:Ji(e,c)}}if(!o)return{localName:r,importStep:Ji(e,r)};let i=zg(o,n.source);if(i)return{localName:i};let s=Ul(r,$l(o));return{localName:s,importStep:Ji(e,s)}}function Yg(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??qi(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 Gg(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?Zg(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function Zg(e){return Object.fromEntries(Object.entries(e).filter(t=>Gi(t[1])))}function Gi(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(Gi):typeof e=="object"?Object.values(e).every(Gi):!1}function Qg(e,t){let n=Ve(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=zl({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 Ji(e,t=qi(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 Vl(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 qg(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function Nn(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function os(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function Mn(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:os(e,t.slice(0,n)),index:r.index}}return null}function Xi(e,t){return e.locator?e.collectionPathMap?.[t]?os(e.locator,e.collectionPathMap[t]):Mn(e.locator)?ty(e.locator,ny(t,e.collectionIndexMap)):null:null}function ey(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:lu(o,t)}function lu(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=lu(r,t);return o===void 0?void 0:{[n.name]:o}}function Wr(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 ty(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},os(e,i)}return null}function ny(e,t){return t?.[e]??e}function Kl(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 ry(e,t){return oy(e.root,t.root)&&sy(e.path??[],t.path??[])}function oy(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&&iy(e.sourceRange,t.sourceRange)}}function iy(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function Zi(e,t){let n=null;return Rt(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 sy(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 Yr=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:Nn(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:Nn(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:Nn(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:Nn(t.kind,t.params.kind)};let r=t;if(!Jr(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=Vl(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:Nn(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=tg(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 f=await this.graph.getElementPropertyWriteTarget?.(r.key,l),p=r.attributes?.find(m=>m.name===l);if(!(typeof p?.resolvedValue=="string"&&p.resolvedValue===u||p?.source===null&&p.value===u)){if(f?.kind==="external-entry")return{ok:!1,errorCode:"capability-denied",reason:`set-props cannot overwrite readonly external property '${l}'`};if(f?.kind==="value-binding"&&f.locator){let m=f.locator;if(f.sourceKind==="repeat-template"&&typeof i.selectionRef?.instanceIndex=="number"){let S=Xi(f,i.selectionRef.instanceIndex);if(!S)return{ok:!1,errorCode:"invalid-params",reason:"set-props could not resolve the selected repeat item"};m=S}a.push({order:n+a.length,file:f.file,type:"update-value",locator:m,value:u});continue}c[l]=u}}return Object.keys(c).length>0&&a.push({order:n+a.length,file:s,type:"set-props",locator:ce(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=Xi(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:ce(t),segmentIndex:n,newText:r}]}}coerceTextValueForValueTarget(t,n,r,o="update-text"){let i=this.graph.getFileContent(t),s=Ve(i);if(!s)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not inspect the value source`};let a=q(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!rg(a.match.path))return{ok:!0,value:r};let c=og(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=Xi(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.buildPlan(t,n,[{order:0,file:o.file,type:"update-array-item",locator:c,value:l.value}],r):l}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 f=i;if(f?.kind==="value-binding"&&f.locator){let p=Mn(f.locator);if(p)return this.buildPlan(t,n,[{order:0,file:f.file,type:"remove-bound-array-item",locator:p.locator,index:p.index}],o)}return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed node removal requires a writable array target"}}let s=Wr(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:ce(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||Qg(n,t)>1)return null;let r=zi(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(!Jr(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=Wr(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 f=await this.planRepeatBackedInsertChild(t,n,r,o);if(f)return f;let p=this.getRepeatBackedTemplateStructureReason(r);if(p)return{ok:!1,errorCode:"unsupported-operation",reason:p};let m=Il(this.graph.getFileContent(r.file),r);if(!m.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:m.reason??"Cannot insert child into this node"};let S=zr(r,n.params.node);if(S)return{ok:!1,errorCode:"unsupported-operation",reason:S};let b=[],R=0,k=n.params.node.kind==="component-call"?Hg(n.params.node,this.graph.getFileContent(r.file)):void 0,P=k?.importStep;return P&&b.push({order:R++,file:r.file,type:"add-import",moduleSpecifier:P.moduleSpecifier,imports:P.imports}),b.push({order:R++,file:r.file,type:"insert-child",parentLocator:ce(r),node:{jsx:Yg(n.params.node,k?.localName)},placement:n.params.position.relation,anchorLocator:i?ce(i):void 0}),this.buildPlan(t,n,b,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!Jr(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:Gg(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(!Jr(n.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};if(n.params.position.relation!=="append"&&n.params.position.relation!=="prepend")return null;let i=n.params.node;if(i.kind!=="native-tag"||i.text===void 0||!this.graph.getChildNodes)return null;let s=this.graph.getChildNodes(r.key).find(f=>f.isRepeatItemRoot&&f.tag?.toLowerCase()===i.tag.toLowerCase());if(!s)return null;let a=await this.graph.getTextWriteTarget(s.key,0);if(!a||a.kind!=="value-binding"||!a.locator)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires a writable value target"};let c=Mn(a.locator);if(!c)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let l=ey(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"?Kl(0,a.collectionIndexMap):Kl(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=Wr(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=Ve(this.graph.getFileContent(t.file));if(!n)return t.isRepeatItemRoot===!0;let r=q(n,ce(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:Zi(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=ct(this.graph.getFileContent(t.file),o);return i?sg(o,i):t.isRepeatItemRoot===!0}isInsideMapCallback(t){let n=Ve(this.graph.getFileContent(t.file));if(!n)return!1;let r=q(n,ce(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:Zi(n,t);return o?!!o.findParent(i=>{if(!i.isCallExpression()&&!i.isOptionalCallExpression())return!1;let s=i.node.callee;return(x.isMemberExpression(s)||x.isOptionalMemberExpression(s))&&x.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=Ve(c);if(!l)return null;let u=St(l,r),f=St(l,o);if(!u||!f)return null;let p=ct(c,u),m=ct(c,f);if(!Xr(p,m))return null;if(a&&(s==="before"||s==="after")){let b=St(l,a),R=b?ct(c,b):null;if(!Xr(p,R))return null}if(Ki(u,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let S=Al(c,r,o);return S.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:ce(r),targetParentLocator:ce(o),placement:s,anchorLocator:a?ce(a):void 0,selectionContext:cn(o)}],i):{ok:!1,errorCode:"unsupported-operation",reason:S.reason??`Cannot move node because it depends on bindings outside the target scope: ${S.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=Ve(c);if(!l)return null;let u=St(l,r),f=St(l,o);if(!u||!f)return null;let p=ct(c,u);if(!p)return null;let m=ct(c,f);if(Xr(p,m))return null;if(m&&!lg(m,p))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")){let A=Tl(c,l,a);if(m&&!Xr(m,A)||!m&&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 A=zr(o,{kind:"native-tag",tag:r.tag});if(A)return{ok:!1,errorCode:"unsupported-operation",reason:A}}let S=Ui(this.graph,r);if(!S)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Ki(u,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let b=Bl(c,u,f,S);for(let A of b.conditionPaths){let z=Ml(A,f,p);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 R=Fl(u,f,p,{preserveConditionalBoundary:b.conditionPaths.length>0});if(!R.ok)return{ok:!1,errorCode:"unsupported-operation",reason:R.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${R.bindingNames.join(", ")}`};let k=ug(p,f);if(!k.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its callback parameters depend on bindings outside the target scope: ${k.bindingNames.join(", ")}`};let P=p;if(r.component!==o.component){let A=fg({source:c,ast:l,sourceContext:p,sourceNode:r,targetParent:o,targetParentPath:f});if(!A.ok)return{ok:!1,errorCode:"unsupported-operation",reason:A.reason};P=A.context}else{let A=Xl(p.collectionPath,f);if(!A.ok)return{ok:!1,errorCode:"unsupported-operation",reason:A.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${A.bindingNames.join(", ")}`}}return this.buildPlan(t,n,[{order:0,file:r.file,type:"move-repeat-template-child",locator:ce(r),targetParentLocator:ce(o),placement:s,anchorLocator:a?ce(a):void 0,repeatExpression:Dl(P,b.sourceJsx),selectionContext:cn(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&this.isRepeatTemplateRootNode(r)||r.file===o.file)return null;let c=this.graph.getFileContent(r.file),l=this.graph.getFileContent(o.file),u=Ve(c),f=Ve(l);if(!u||!f)return null;let p=mg({knownSourceFiles:this.graph.getKnownSourceFiles?.(),routeEntryFiles:this.graph.getRouteEntryFiles?.(),sourceAst:u,sourceFile:r.file,targetFile:o.file,sourceComponent:r.component,targetComponent:o.component});if(!p.ok)return{ok:!1,errorCode:"unsupported-operation",reason:p.reason};let m=St(u,r),S=St(f,o);if(!m||!S)return null;let b=cu(p.callSitePath,S);if(!b.ok)return{ok:!1,errorCode:"unsupported-operation",reason:b.reason};let R=ct(c,m);if(!R)return null;if(ct(l,S))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")&&Tl(l,f,a))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child relative to a repeat-template anchor outside the target scope"};if(r.tag&&r.tag.toLowerCase()===r.tag){let O=zr(o,{kind:"native-tag",tag:r.tag});if(O)return{ok:!1,errorCode:"unsupported-operation",reason:O}}let P=Ui(this.graph,r);if(!P)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Ki(m,S))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let A=Bl(c,m,S,P);for(let O of A.conditionPaths){let D=Ml(O,S,R);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 z=Fl(m,S,R,{preserveConditionalBoundary:A.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 oe=Mg({sourceFile:r.file,targetFile:o.file,sourceContext:R,targetParentPath:S});if(!oe.ok)return{ok:!1,errorCode:"unsupported-operation",reason:oe.reason};let le=Lg(R);if(!le.ok)return{ok:!1,errorCode:"unsupported-operation",reason:le.reason};let C=Dg(R,le.callbackParams),M=[{order:0,file:r.file,type:"remove-node",locator:ce(r),removeWhitespace:!0}];for(let O of oe.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:ce(o),expression:Dl(C,A.sourceJsx),placement:s,anchorLocator:a?ce(a):void 0,selectionContext:cn(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=Vl(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(qg(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 k=n.params.target.relation,P=i.anchorNode&&(k==="before"||k==="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:k,anchorSourceId:P?.kind==="external-entry"?P.sourceId:null,parentKey:"parentKey"in n.params.target?n.params.target.parentKey:null}}],o)}let c=r.file!==s.file,l=n.params.target.relation,u=i.anchorNode,f=Wr(r,a,this.graph.getTextProvenance?.(r.key,0)??null);if(f&&!Vi(f))return{ok:!1,errorCode:"unsupported-operation",reason:f};if(r.isRepeatItemRoot&&u?.isRepeatItemRoot&&r.repeatOwnerKey&&r.repeatOwnerKey===u.repeatOwnerKey&&(l==="before"||l==="after")){let k=a,P=await this.graph.getTextWriteTarget(u.key,0);if(k?.kind==="value-binding"&&P?.kind==="value-binding"&&k.locator&&P.locator){let A=Mn(k.locator),z=Mn(P.locator);if(A&&z&&k.file===P.file&&ry(A.locator,z.locator)){let oe=A.index,le=z.index,C=l==="before"?le-(oe<le?1:0):le+(oe<le?0:1);return this.buildPlan(t,n,[{order:0,file:k.file,type:"move-array-item",locator:A.locator,fromIndex:oe,toIndex:C}],o)}}}if(r.isRepeatItemRoot&&this.isRepeatTemplateRootNode(r))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed item outside its collection"};let p=this.getRepeatBackedTemplateStructureReason(r),m=Vi(f)?f:p;if(m&&Vi(m)){let k=this.planRepeatTemplateInternalMove(t,n,r,s,o,l,u);if(k)return k;let P=this.planRepeatTemplateHoistMove(t,n,r,s,o,l,u);if(P)return P;let A=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,l,u);return A||{ok:!1,errorCode:"unsupported-operation",reason:m}}if(p)return{ok:!1,errorCode:"unsupported-operation",reason:p};let S=await this.getUpstreamBackedDescendantReason(r);if(S)return{ok:!1,errorCode:"unsupported-operation",reason:S};if(r.tag&&r.tag.toLowerCase()===r.tag){let k=zr(s,{kind:"native-tag",tag:r.tag});if(k)return{ok:!1,errorCode:"unsupported-operation",reason:k}}if(c)return this.planCrossFileMove(t,n,r,s,o,l,u);let b=Al(this.graph.getFileContent(r.file),r,s);if(!b.ok)return{ok:!1,errorCode:"unsupported-operation",reason:b.reason??`Cannot move node because it depends on bindings outside the target scope: ${b.bindingNames.join(", ")}`};let R=[{order:0,file:r.file,type:"move-node",locator:ce(r),targetParentLocator:ce(s),placement:l,anchorLocator:u?ce(u):void 0,selectionContext:cn(s)}];return this.buildPlan(t,n,R,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,u=this.graph.getFileContent(r.file),f=Ui(this.graph,r)??`<${r.component} />`,p=kl(u,r);if(!p.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:p.reason??"Cannot move subtree across files"};if(c.push({order:l++,file:r.file,type:"remove-node",locator:ce(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let S=r.tag??r.component,R={moduleSpecifier:zi(o.file,r.importedFrom),imports:r.exportName==="default"?[{kind:"default",local:S}]:[{kind:"named",imported:r.exportName,local:S===r.exportName?void 0:S}]};c.push({order:l++,file:o.file,type:"add-import",moduleSpecifier:R.moduleSpecifier,imports:R.imports}),c.push({order:l++,file:o.file,type:"insert-child",parentLocator:ce(o),node:{jsx:f},placement:s,anchorLocator:a?ce(a):void 0,selectionContext:cn(o)})}else c.push({order:l++,file:o.file,type:"insert-child",parentLocator:ce(o),node:{jsx:f},placement:s,anchorLocator:a?ce(a):void 0,selectionContext:cn(o)});let m=this.buildRemoveComponentImportStep(r,u);return m&&c.push({...m,order:l++}),this.buildPlan(t,n,c,i)}buildPlan(t,n,r,o){let s=[...new Set(r.map(a=>a.file))].map(a=>({file:a,content:this.graph.getFileContent(a),version:this.graph.getFileVersion(a),exists:!0,sha256:ie(this.graph.getFileContent(a))}));return{ok:!0,plan:{operationId:t,kind:n.kind,target:n.target,documentVersion:n.documentVersion,steps:r,preSnapshots:s,validatedCapability:o}}}};import Ln from"node:path";import*as bu from"@babel/parser";import is from"@babel/traverse";import*as E from"@babel/types";var Iu=typeof is=="function"?is:is.default;function ku(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}var uu=new WeakMap;function du(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 Ru(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=hs(s,t,n);if(!a)return null;let c=gs(a,r.sourceRange);if(!c)return null;let l=r.source??await ze({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!l){let m=await ks({currentFile:t,expressionPath:c,readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:new Set});if(!m)return null;if(m.kind==="external")return{kind:"external-entry",file:m.file,sourceType:m.sourceType,sourceId:m.sourceId,adapterId:m.adapterId,displayExpression:m.displayPath};let S={kind:"value",root:m.root,path:m.path.length>0?m.path:[]};return{kind:"value-binding",file:m.file,locator:S,root:m.root,path:m.path,displayExpression:m.displayExpression??jn(c.node,n),sourceKind:m.sourceKind,...m.collectionIndexMap?{collectionIndexMap:m.collectionIndexMap}:{},...m.collectionPathMap?{collectionPathMap:m.collectionPathMap}:{}}}let u=new Set,f=await _y({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(!f)return null;if(f.kind==="external")return{kind:"external-entry",file:f.file,sourceType:f.sourceType,sourceId:f.sourceId,adapterId:f.adapterId,displayExpression:f.displayPath};let p={kind:"value",root:f.root,path:f.path.length>0?f.path:[]};return{kind:"value-binding",file:f.file,locator:p,root:f.root,path:f.path,displayExpression:f.displayExpression??l.expression,sourceKind:f.sourceKind,...f.collectionIndexMap?{collectionIndexMap:f.collectionIndexMap}:{},...f.collectionPathMap?{collectionPathMap:f.collectionPathMap}:{}}}async function Cu(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=hs(i,t,n);if(!s)return null;let a=e.expression!==void 0?(e.sourceRange?Au(s,n,e.expression,e.sourceRange):null)??Es(s,n,e.expression):e.sourceRange?gs(s,e.sourceRange):null;if(!a)return null;let c=uy(a),l=new Set,u=e.sourceInfo??await ze({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:l}),f=u?await Ae({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 Hy({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 ly(f,e.expression??jn(c.node,n))}async function ms(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=hs(i,t,n);if(!s)return Pe("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?dy({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}):fy({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}function vu(e){try{return bu.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function hs(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=vu(n);return e.set(t,{source:n,ast:o}),o}function gs(e,t){let n=null,r=-1;for(let o of Bn(e).expressions){let i=o.node.loc;if(!i||!ys(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s>=r&&(n=o,r=s)}return n}function ay(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of Bn(e).expressions){if(!cy(o.node.loc,t))continue;let i=(o.node.end??0)-(o.node.start??0);i<=r&&(n=o,r=i)}return n}function wu(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of Bn(e).jsxElements){let i=o.node.loc;if(!i||!ys(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s<=r&&(n=o,r=s)}return n}function Bn(e){let t=uu.get(e);if(t)return t;let n={expressions:[],jsxElements:[]};return Iu(e,{Expression(r){n.expressions.push(r)},JSXElement(r){n.jsxElements.push(r)}}),uu.set(e,n),n}function cy(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 ys(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 Pu(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 ze(e){if(E.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!E.isMemberExpression(e.expression))return null;let t=await $u(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:jn(e.expression,e.source),base:t.base,path:t.path}:null}function ly(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 uy(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 jn(e,t){if(t)return xs(e,t);let n=ix(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function xs(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Es(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of Bn(e).expressions){if(xs(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function Au(e,t,n,r){let o=null,i=Number.POSITIVE_INFINITY;for(let s of Bn(e).expressions){if(xs(s.node,t)!==n)continue;let a=s.node.loc;if(!a||!ys(a,r))continue;let c=(s.node.end??0)-(s.node.start??0);c<=i&&(o=s,i=c)}return o}async function dy(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=gs(r,o.sourceRange),u=o.source??(l?await ze({expression:l.node,scope:l.scope,source:n,currentFile:t,readFile:i,exists:s,fileCache:a,visited:c}):null);if(!u){if(!l)return py(t,o.value);let p=await ks({currentFile:t,expressionPath:l,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});return p?p.kind==="external"?yu(t,p):ds(t,jn(l.node,n),p):my({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return Pe("unsupported-expression","Unable to locate text expression for provenance resolution");let f=await Ae({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(!f){let p=us(l.node);if(p)return Pe(p.code,p.message);let m=l.scope.getBinding(u.base);if(m?.path.isVariableDeclarator()){let S=us(m.path.node.init);if(S)return Pe(S.code,S.message)}return m?.path.isVariableDeclarator()&&E.isCallExpression(m.path.node.init)?hy("unsupported-expression",_u(m.path.node.init,e.functionCallContracts)):Pe("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return f.kind==="external"?yu(t,f):ds(t,u.expression,f)}async function fy(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return Pe("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=Es(r,n,o.conditionExpression);if(!l)return Pe("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await Ae({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 Pe("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(u.kind==="external")return Pe("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let f=ds(t,o.conditionExpression,u);return f.finalSource?{...f,finalSource:{...f.finalSource,kind:"conditional-branch",displayPath:o.conditionExpression},chain:[...f.chain,{kind:"conditional-branch",file:u.file,displayName:o.conditionExpression,canEditHere:!0}]}:f}function py(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 my(e){let t=await Nu(e);if(t.length===0)return Pe("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(gy(e.expression))return Tu(t);if(Mu(e.expression))return Pe("unsupported-expression","i18n helpers require a static message id string");if(E.isMemberExpression(e.expression)&&e.expression.computed&&!E.isNumericLiteral(e.expression.property)&&!E.isStringLiteral(e.expression.property))return Pe("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return Pe(n.code,n.message)}function Pe(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function hy(e,t){return Tu([{code:e,message:t}])}function Tu(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function gy(e){return E.isCallExpression(e)||E.isConditionalExpression(e)||E.isLogicalExpression(e)||E.isBinaryExpression(e)}function Dn(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 Nu(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=us(t);if(l)return[l];if(E.isCallExpression(t))return[{code:"unsupported-expression",message:_u(t,c)}];if(E.isMemberExpression(t)&&t.computed){let u=t.property;if(!E.isNumericLiteral(u)&&!E.isStringLiteral(u)){if(!E.isExpression(u))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let p=await We(u,n,r,o,i,s,a);if(typeof p!="string"&&!Number.isInteger(p))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}]}}return E.isBinaryExpression(t)?Dn([...await ss(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):E.isLogicalExpression(t)?Dn([...await ss(t.left,t.right,e),{code:"unsupported-expression",message:t.operator==="??"||t.operator==="||"?"Fallback expressions are recognized but remain readonly until a safer composition editing strategy is available":"Complex conditional expressions are recognized but remain readonly until a safer editing strategy is available"}]):E.isConditionalExpression(t)?Dn([...await ss(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 us(e){return Mu(e)?pu("i18n helpers require a static message id string"):by(e)?pu("CMS helpers require static entry id and field path string arguments"):null}async function ss(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await Nu({...t,expression:o}));return r}function yy(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:[xy(e.sourceType)]}}async function Ss(e){for(let n of Cy){if(!mu(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return gu(hu(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(!mu(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return gu(hu(r),e.externalAdapters)}return null}function xy(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function Ey(e){return{code:"external-source-readonly",message:e}}function pu(e){return{code:"unsupported-expression",message:e}}function bs(e){return!e||!E.isCallExpression(e)?null:E.isIdentifier(e.callee)?e.callee.name:E.isMemberExpression(e.callee)&&!e.callee.computed&&E.isIdentifier(e.callee.object)&&E.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function mu(e,t){if(!t||t.length===0)return!0;let n=bs(e.node);return n?t.includes(n):!1}function hu(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:Dn(e.diagnostics??[])}:{match:e,diagnostics:[]}}function gu(e,t){let n=yy(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:Dn([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function Sy(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!E.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!E.isStringLiteral(n)||!E.isStringLiteral(r))return null;let o=n.value,i=r.value;return{sourceType:"cms-field",sourceId:`${o}:${i}`,file:`cms://${o}/${i.replace(/\./g,"/")}`,displayPath:`${o}.${i}`}}function by(e){return!!e&&E.isCallExpression(e)&&E.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!E.isStringLiteral(e.arguments[0])||!E.isStringLiteral(e.arguments[1]))}function Fu(e){if(!(!e||!E.isCallExpression(e))){if(E.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&E.isStringLiteral(t)?t.value:null}if(E.isMemberExpression(e.callee)&&!e.callee.computed&&E.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&E.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!E.isObjectExpression(t))return null;for(let n of t.properties)if(E.isObjectProperty(n)&&!n.computed&&(E.isIdentifier(n.key)&&n.key.name==="id"||E.isStringLiteral(n.key)&&n.key.value==="id")&&E.isStringLiteral(n.value))return n.value.value;return null}}}function Mu(e){return Fu(e)===null}async function Iy(e,t,n){let r=new Set,o=Ln.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=Ln.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"]:[Ln.posix.join(i,"locales"),Ln.posix.join(i,"messages")];for(let a of s){let c=Ln.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function ky(e){let t=Fu(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await Iy(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function Ry(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!E.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!E.isExpression(n))return null;let o=await We(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:[Ey("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var Cy=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>Sy(e)},{helperNames:["apiField"],resolve:e=>Ry(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>ky({currentFile:e,expressionPath:t,exists:n})}];function yu(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 ds(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=My(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 vy=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function Is(e,t){let n=[...vy,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function _u(e,t){let n=e.callee;return E.isIdentifier(n)&&Is(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 ks(e){let t=await Ss(e);if(t)return t;let n=await Ou({...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 ze({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 Ae({...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 Ny(e)}async function Ou(e){let t=await Xe({...e,allowComposed:!1});return t?.kind==="source"?t.provenance:null}async function Xe(e){let t=wy(e.expressionPath),n=Ty(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 ze({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 Ae({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 ze({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 Ae({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 Xe({...e,expressionPath:r,allowComposed:!0}),a=await Xe({...e,expressionPath:o,allowComposed:!1}),c=await Xe({...e,expressionPath:i,allowComposed:!1});return as(s,a,c)}if(t.isCallExpression())return Py({...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 Xe({...e,expressionPath:r,allowComposed:!0}),s=await Xe({...e,expressionPath:o,allowComposed:!0});return as(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 Xe({...e,expressionPath:r,allowComposed:!0}),s=await Xe({...e,expressionPath:o,allowComposed:!0});return as(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:Xe({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function wy(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 Py(e){let t=bs(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:Xe({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(E.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:Xe({...e,expressionPath:o,allowComposed:!1})}}return null}function as(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!Ay(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function Ay(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 Ty(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function Ny(e){if(!e.expressionPath.isCallExpression())return null;let t=bs(e.expressionPath.node);if(!t)return null;let n=Is(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 Lu({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 Lu(e){let t=await Ss({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 ze({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 Ae({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 ks({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 Fy(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!E.isCallExpression(t))return null;let n=t.callee;if(!E.isIdentifier(n))return null;let r=Is(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 Lu({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 My(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=Gr(t,e.path);return{sourceId:o,displayPath:o}}async function _y(e){let t=e.segment.source;return t?Ae({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 Ae(e){let t=e.sourceInfo,n=Du(e.expressionPath,t.base);if(n){let l=await Bu({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 b=Ly(n.callPath,[...n.basePath,...t.path]);return An(b)?du(e.currentFile,b.sourceId,b.displayPath):null}let u=sx(l,[...n.basePath,...t.path]),f=l.collectionIndexMap?.[0]??0,p=[...l.pathPrefix??[],{kind:"index",index:f},...n.basePath,...t.path],m=[{kind:"index",index:0},...n.basePath,...t.path];return et(l.value,m)===void 0?null:{kind:"value",file:l.file,root:l.root,path:u?.[0]??p,sourceKind:"repeat-template",collectionIndexMap:l.collectionIndexMap,...u?{collectionPathMap:u}:{}}}let r=e.expressionPath.scope.getBinding(t.base);if(!r)return null;let o=vl(r);if(o){let l=o.expressionPath,u=await ze({expression:l.node,scope:l.scope,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(u){let f=await Ae({...e,expressionPath:l,sourceInfo:{...u,expression:Gr(u.expression,t.path),path:[...u.path,...t.path]}});if(f)return f}if(t.path.length===0){let f=await Ou({currentFile:e.currentFile,expressionPath:l,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(f)return f}}if(r.kind==="param")return qy({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 Fy({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=jr(r,t.path);if(An(s))return du(e.currentFile,s.sourceId,s.displayPath);let a=await dn({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 Du(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=Ue(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!Oy(s,r)?null:{callPath:s,basePath:i}}function Oy(e,t){let n=e.node.callee;return!E.isMemberExpression(n)||!E.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}async function Bu(e){let{currentFile:t,callPath:n,readFile:r,exists:o,fileCache:i,visited:s}=e,a=n.node.callee;if(!E.isMemberExpression(a)||!E.isIdentifier(a.property)||a.property.name!=="map")return null;let c=n.get("callee");if(!c.isMemberExpression())return null;let l=c.get("object");if(Array.isArray(l)||!l.isExpression())return null;let u=await $n({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 Ly(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:Ur(r,t)}async function $n(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 dn({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 ju({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 $n({...e,expressionPath:a})}if(n.isArrayExpression()){let a=Pu(n.node);if(!a)return null;let c=await We(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 ze({expression:n.node,scope:n.scope,currentFile:t,readFile:r,exists:o,fileCache:i,visited:s});if(!a)return null;let c=await Ae({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 Dy({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 f=ax(l.value,c.collectionPathMap);if(f)return{kind:"static",file:c.file,root:c.root,value:f.value,sourceKind:c.sourceKind,collectionPathMap:f.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 Dy(e){let{provenance:t}=e;if(t.root.kind==="binding"){let i=e.expressionPath.scope.getBinding(t.root.name);return i?await dn({currentFile:e.currentFile,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 Un(t.file,e.readFile,e.fileCache);if(!n.ast)return null;let r=ay(n.ast,t.root.sourceRange);if(!r)return null;let o=await We(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 ju(e){return await By(e)??await jy(e)??await $y(e)}async function By(e){let{callPath:t}=e,n=t.node.callee;if(!E.isMemberExpression(n)||!E.isIdentifier(n.property)||n.property.name!=="filter")return null;let r=t.get("callee");if(!r.isMemberExpression())return null;let o=r.get("object");if(Array.isArray(o)||!o.isExpression())return null;let i=await $n({currentFile:e.currentFile,expressionPath:o,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(!i||!Array.isArray(i.value))return null;let[s]=t.node.arguments;if(!E.isArrowFunctionExpression(s)&&!E.isFunctionExpression(s))return null;let a=s.params[0];if(!E.isIdentifier(a))return null;let c=Uy(s);if(!c)return null;let l=[],u=[],f=[];for(let[p,m]of i.value.entries()){let S=Vy(c,a.name,m);if(typeof S!="boolean")return null;if(S){l.push(m),u.push(i.collectionIndexMap?.[p]??p);let b=i.collectionPathMap?.[p];b&&f.push(b)}}return{...i,value:l,pathPrefix:i.pathPrefix,collectionIndexMap:u,...f.length>0?{collectionPathMap:f}:{}}}async function jy(e){let{callPath:t}=e,n=t.node.callee;if(!E.isMemberExpression(n)||!E.isIdentifier(n.property)||n.property.name!=="slice")return null;let r=t.get("callee");if(!r.isMemberExpression())return null;let o=r.get("object");if(Array.isArray(o)||!o.isExpression())return null;let i=await $n({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=xu(s,0),l=xu(a,i.value.length);if(c===null||l===null)return null;let u=Math.max(0,c<0?i.value.length+c:c),f=Math.max(0,l<0?i.value.length+l:l),p=i.value.map((S,b)=>i.collectionIndexMap?.[b]??b).slice(u,f),m=i.collectionPathMap?.slice(u,f);return{...i,value:i.value.slice(u,f),pathPrefix:i.pathPrefix,collectionIndexMap:p,...m?{collectionPathMap:m}:{}}}function xu(e,t){return e?E.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}async function $y(e){let{callPath:t}=e,n=t.node.callee;if(!E.isMemberExpression(n)||!E.isIdentifier(n.property)||n.property.name!=="sort"&&n.property.name!=="toSorted")return null;let r=t.get("callee");if(!r.isMemberExpression())return null;let o=r.get("object");if(Array.isArray(o)||!o.isExpression())return null;let i=await $n({currentFile:e.currentFile,expressionPath:o,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(!i||!Array.isArray(i.value))return null;let[s]=t.node.arguments;if(!E.isArrowFunctionExpression(s)&&!E.isFunctionExpression(s))return null;let[a,c]=s.params;if(!E.isIdentifier(a)||!E.isIdentifier(c))return null;let l=i.value.map((f,p)=>({value:f,sourceIndex:i.collectionIndexMap?.[p]??p,originalIndex:p})),u=[...l];for(let f of l)for(let p of l)if(Eu(s,a.name,c.name,f.value,p.value)===void 0)return null;return u.sort((f,p)=>{let m=Eu(s,a.name,c.name,f.value,p.value)??0;return m===0?f.originalIndex-p.originalIndex:m}),{...i,value:u.map(f=>f.value),pathPrefix:i.pathPrefix,collectionIndexMap:u.map(f=>f.sourceIndex),...i.collectionPathMap?{collectionPathMap:u.map(f=>i.collectionPathMap?.[f.originalIndex]).filter(f=>!!f)}:{}}}function Eu(e,t,n,r,o){let i=E.isExpression(e.body)?e.body:e.body.body.find(a=>E.isReturnStatement(a))?.argument;if(!i||!E.isExpression(i))return;let s=fs(i,t,n,r,o);return typeof s=="number"?s:void 0}function fs(e,t,n,r,o){if(E.isNumericLiteral(e)||E.isStringLiteral(e)||E.isBooleanLiteral(e))return e.value;if(E.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(E.isMemberExpression(e)){let i=ps(e,t);if(i)return et(r,i);let s=ps(e,n);return s?et(o,s):void 0}if(E.isBinaryExpression(e)&&e.operator==="-"){let i=E.isExpression(e.left)?fs(e.left,t,n,r,o):void 0,s=E.isExpression(e.right)?fs(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function Uy(e){if(E.isExpression(e.body))return e.body;for(let t of e.body.body)if(E.isReturnStatement(t)&&t.argument&&E.isExpression(t.argument))return t.argument;return null}function Vy(e,t,n){let r=jt(e,t,n);return typeof r=="boolean"?r:void 0}function jt(e,t,n){if(E.isStringLiteral(e)||E.isNumericLiteral(e)||E.isBooleanLiteral(e))return e.value;if(E.isNullLiteral(e))return null;if(E.isIdentifier(e))return e.name===t?n:void 0;if(E.isMemberExpression(e)){let r=ps(e,t);return r?et(n,r):void 0}if(E.isUnaryExpression(e)&&e.operator==="!"){let r=jt(e.argument,t,n);return r===void 0?void 0:!r}if(E.isLogicalExpression(e)){let r=jt(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&jt(e.right,t,n);if(e.operator==="||")return r||jt(e.right,t,n)}if(E.isBinaryExpression(e)){let r=E.isExpression(e.left)?jt(e.left,t,n):void 0,o=E.isExpression(e.right)?jt(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 ps(e,t){let n=[],r=e;for(;E.isMemberExpression(r);){if(r.computed)if(E.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(E.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!E.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!E.isIdentifier(r)||r.name!==t?null:n}async function dn(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 Ky({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 nx({currentFile:t,binding:n,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,fileCache:i,visited:s});if(n.kind==="param")return null;if(n.path.isVariableDeclarator()){let l=n.path.node.init;if(!l||!E.isExpression(l))return null;let u=n.path.get("init");if(u&&!Array.isArray(u)&&u.isExpression()){let p=await Ss({currentFile:t,expressionPath:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(p)return p;if(u.isCallExpression()){let m=await ju({currentFile:t,callPath:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(m)return m}}let f=await We(l,n.path.scope,t,r,o,i,s);return f===void 0?null:{kind:"static",file:t,root:{kind:"binding",name:n.identifier.name},value:f,sourceKind:"binding"}}if(n.path.isIdentifier()&&n.path.parentPath?.isExportDefaultDeclaration()){let l=n.path.parentPath.node.declaration;if(!E.isExpression(l))return null;let u=await We(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 Ky(e){let{currentFile:t,binding:n,readFile:r,exists:o,fileCache:i,visited:s}=e;if(!n.path.isVariableDeclarator()||!n.path.get("id").isArrayPattern())return null;let a=n.path,c=a.node.init;if(!c||!E.isCallExpression(c))return null;let l=Jy(c);if(!l||!E.isArrayPattern(a.node.id)||a.node.id.elements.findIndex(S=>E.isIdentifier(S)&&S.name===n.identifier.name)!==0)return null;let f=l==="useReducer"?1:0,p=c.arguments[f];if(!p||!E.isExpression(p))return null;let m=await We(p,a.scope,t,r,o,i,s);return m===void 0?null:{kind:"static",file:t,root:{kind:"hook-state",name:n.identifier.name,hook:l},value:m,sourceKind:"binding"}}function Jy(e){return E.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:E.isMemberExpression(e.callee)&&E.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function Xy(e){let t=e.getFunctionParent();if(!t)return null;if(t.isFunctionDeclaration()){let s=t.node.id?.name;if(!s)return null;let a=t.parentPath?.isExportDefaultDeclaration()?"default":(t.parentPath?.isExportNamedDeclaration(),s);return{componentName:s,exportName:a}}if(!t.isArrowFunctionExpression()&&!t.isFunctionExpression())return null;let n=t.parentPath;if(!n?.isVariableDeclarator()||!E.isIdentifier(n.node.id))return null;let r=n.node.id.name,o=n.parentPath,i=o?.parentPath?.isExportDefaultDeclaration()?"default":(o?.parentPath?.isExportNamedDeclaration(),r);return{componentName:r,exportName:i}}function zy(e,t){let n=Xy(e.path);if(!n)return null;let r=an(e,t);return r?{...n,...r}:null}function Gr(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function Wy(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}async function Hy(e){let t=Gy(e.expressionPath.node);if(!t||!Zy(t.segments))return null;let n=await Ae({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 Yy({...e,rootPath:n.path,segments:t.segments});return r?{...n,path:r.collectionPathMap[0]??n.path,sourceKind:"repeat-template",displayExpression:jn(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:r.collectionPathMap}:null}async function Yy(e){let t=null,n,r=[];for(let i of e.segments){if(i.kind!=="dynamic")continue;let s=await ze({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=Du(e.expressionPath,s.base);if(!a)return null;let c=await Bu({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,f)=>{let p=et(c.value,[{kind:"index",index:f},...a.basePath,...s.path]);return Qy(p)});if(l.some(u=>u===null)||t!==null&&t!==l.length)return null;t=l.length,n??=c.collectionIndexMap,r.push(l)}if(t===null||t===0)return null;let o=[];for(let i=0;i<t;i+=1){let s=[...e.rootPath],a=0;for(let c of e.segments){if(c.kind==="dynamic"){let l=r[a]?.[i];if(!l)return null;s.push(l),a+=1;continue}s.push({...c})}o.push(s)}return{...n?{collectionIndexMap:n}:{},collectionPathMap:o}}function Gy(e){let t=[],n=e;for(;E.isMemberExpression(n)||E.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(E.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(E.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(E.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(E.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return E.isIdentifier(n)?{base:n.name,segments:t}:null}function Zy(e){return e.some(t=>t.kind==="dynamic")}function Qy(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}async function qy(e){let t=zy(e.binding,e.sourceInfo);if(!t||!e.graph)return null;let n=[...e.graph.elements.values()].filter(l=>Wy(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 ex({caller:r,propName:t.propName,remainingPath:t.remainingPath,readFile:e.readFile,fileCache:e.fileCache});if(l)return cs(l,{componentName:t.componentName,propName:t.propName,file:r.sourceFile})}if(!o?.source){let l=await tx({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 cs(l,{componentName:t.componentName,propName:t.propName,file:r.sourceFile});let u=Pl(e.binding,t.componentName,t.propName);if(!u||u.propName!==t.propName)return null;let f=await We(u.expressionPath.node,u.expressionPath.scope,e.currentFile,e.readFile,e.exists,e.fileCache,e.visited);if(f===void 0)return null;let p=t.remainingPath;return p.length>0&&et(f,p)===void 0?null:{kind:"value",file:e.currentFile,root:{kind:"binding",name:t.propName},path:p,sourceKind:"binding",semanticKind:"component-prop",displayExpression:u.displayPath,chainPrefix:[{kind:"component-prop",file:e.currentFile,displayName:u.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let i=await Un(r.sourceFile,e.readFile,e.fileCache);if(!i.ast)return null;let s=Au(i.ast,i.source,o.source.expression,o.sourceRange)??Es(i.ast,i.source,o.source.expression);if(!s)return null;let a={...o.source,expression:Gr(o.source.expression,t.remainingPath),path:[...o.source.path,...t.remainingPath]},c=await Ae({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?cs(c.kind==="external"?c:{...c,displayExpression:a.expression},{componentName:t.componentName,propName:t.propName,file:r.sourceFile}):null}async function ex(e){let t=await Un(e.caller.sourceFile,e.readFile,e.fileCache);if(!t.ast)return null;let n=wu(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=Pu(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 tx(e){let t=await Un(e.caller.sourceFile,e.readFile,e.fileCache);if(!t.ast)return null;let n=wu(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 ze({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:Gr(s.expression,a),path:[...s.path,...a]},l=await Ae({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 cs(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 nx(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 Aa(t,c,o);if(!l)return null;if(n.path.isImportDefaultSpecifier()){let m=await Su({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!m||m.kind!=="static"?null:{kind:"static",file:l,root:{kind:"default-export"},value:m.value,sourceKind:"imported-binding"}}if(!n.path.isImportSpecifier())return null;let u=n.path.node.imported,f=E.isIdentifier(u)?u.name:u.value,p=await Su({file:l,exportName:f,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});return p?p.kind==="external"?p:{kind:"static",file:l,root:{kind:"named-export",name:f},value:p.value,sourceKind:"imported-binding"}:null}async function Su(e){let{file:t,exportName:n,readFile:r,exists:o,fileCache:i,visited:s}=e,a=await Un(t,r,i);if(!a.ast)return;let c=ox(a.ast,n);if(!c||c.kind==="default-expression")return;let l=c.name;if(!l)return;let u=rx(a.ast).getBinding(l);return u?await dn({currentFile:t,binding:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s})??void 0:void 0}function rx(e){let t=null;if(Iu(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}function ox(e,t){for(let n of e.program.body){if(t==="default"&&E.isExportDefaultDeclaration(n))return E.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:(E.isFunctionDeclaration(n.declaration)||E.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if(E.isExportNamedDeclaration(n)){if(n.declaration){if(E.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if(E.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if((E.isFunctionDeclaration(n.declaration)||E.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if((E.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&E.isExportSpecifier(r))return{kind:"local-binding",name:r.local.name}}}return null}async function We(e,t,n,r,o,i,s){if(E.isStringLiteral(e)||E.isNumericLiteral(e)||E.isBooleanLiteral(e))return e.value;if(E.isNullLiteral(e))return null;if(E.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(E.isTSAsExpression(e)||E.isTSSatisfiesExpression(e)||E.isTSNonNullExpression(e))return await We(e.expression,t,n,r,o,i,s);if(E.isIdentifier(e)){let a=t.getBinding(e.name);if(!a)return;let c=await dn({currentFile:n,binding:a,readFile:r,exists:o,fileCache:i,visited:s});return c?.kind==="static"?c.value:void 0}if(E.isArrayExpression(e)){let a=[];for(let c of e.elements){if(!c||E.isSpreadElement(c))return;let l=await ls(c,t,n,r,o,i,s);if(l===void 0)return;a.push(l)}return a}if(E.isObjectExpression(e)){let a={};for(let c of e.properties){if(!E.isObjectProperty(c)||c.computed)return;let l=null;if(E.isIdentifier(c.key)?l=c.key.name:E.isStringLiteral(c.key)&&(l=c.key.value),!l)return;if(c.shorthand){if(!E.isIdentifier(c.value))return;let f=await ls(c.value,t,n,r,o,i,s);if(f===void 0)return;a[l]=f;continue}if(!E.isExpression(c.value))return;let u=await ls(c.value,t,n,r,o,i,s);u!==void 0&&(a[l]=u)}return a}if(E.isMemberExpression(e)){let a=await $u(e,t,n,r,o,i,s);if(!a)return;let c=t.getBinding(a.base);if(!c)return;let l=await dn({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 ls(e,t,n,r,o,i,s){if(!E.isSpreadElement(e))return await We(e,t,n,r,o,i,s)}async function $u(e,t,n,r,o,i,s){if(E.isIdentifier(e))return{base:e.name,path:[]};if(!E.isMemberExpression(e))return null;let a=[],c=e;for(;E.isMemberExpression(c);){if(c.computed){let l=c.property;if(E.isNumericLiteral(l))a.unshift({kind:"index",index:l.value});else if(E.isStringLiteral(l))a.unshift({kind:"property",name:l.value});else{let u=E.isExpression(l)?await We(l,t,n,r,o,i,s):void 0;if(typeof u=="string")a.unshift({kind:"property",name:u});else if(Number.isInteger(u))a.unshift({kind:"index",index:u});else return null}}else{if(!E.isIdentifier(c.property))return null;a.unshift({kind:"property",name:c.property.name})}c=c.object}return E.isIdentifier(c)?{base:c.name,path:a}:null}function ix(e){if(E.isIdentifier(e))return{base:e.name,path:[]};if(!E.isMemberExpression(e))return null;let t=[],n=e;for(;E.isMemberExpression(n);){if(n.computed)if(E.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(E.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!E.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return E.isIdentifier(n)?{base:n.name,path:t}:null}function 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 sx(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 ax(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 Un(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=vu(o),s={source:o,ast:i};return n.set(e,s),s}var cx=50,lx=8*1024*1024;function Ju(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??cx),s=Math.max(0,t.maxUndoBytes??lx);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:u,redo:f};async function a(C){let M=[...C.steps].sort((W,Z)=>W.order-Z.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 D=new Set(O.map(W=>W.file)),Y=await P(D),G=new Map(Y.map(W=>[W.file,W.exists===!1?"":W.content])),de;for(let W of O){let Z=Ku(W,G.get(W.file)??"");if(!Z.ok)return{ok:!1,errorCode:Z.errorCode,reason:Z.reason};G.set(W.file,Z.source),de=Z.selectionRef??de}return{ok:!0,filePlan:{operationId:C.operationId,kind:"source-edit",target:C.target,documentVersion:C.documentVersion,conflictPolicy:"compare-and-swap",edits:[...G].map(([W,Z])=>({operation:"upsert",file:W,content:Z,baseContentHash:Y.find(pe=>pe.file===W)?.sha256??null}))},...de?{selectionRef:de}:{}}}async function c(C){let M=[...C.steps].sort((pe,tt)=>pe.order-tt.order),O=M.filter(pe=>pe.type!=="invoke-external-adapter"),D=M.filter(pe=>pe.type==="invoke-external-adapter"),Y=new Set(O.map(pe=>pe.file));if(O.length>0&&D.length>0)return{ok:!1,operationId:C.operationId,errorCode:"unsupported-operation",reason:"Mixed local file rewrites and external adapter writes require an explicit compensation contract.",rolledBack:!1};if(O.length===0)return R(C,D);let G=await P(Y),de=new Map;for(let pe of G)de.set(pe.file,pe.exists===!1?"":pe.content);let W;for(let pe of O){let tt=de.get(pe.file)??"",ut=Ku(pe,tt);if(!ut.ok)return{ok:!1,operationId:C.operationId,errorCode:ut.errorCode,reason:ut.reason,rolledBack:!1};de.set(pe.file,ut.source),ut.selectionRef&&(W=ut.selectionRef)}let Z=await z([...de].map(([pe,tt])=>({file:pe,content:tt,exists:!0,version:0,sha256:ie(tt)})),G);return Z.ok===!1?{ok:!1,operationId:C.operationId,errorCode:Z.rolledBack?"writeback-failed":"rollback-failed",reason:Z.reason,rolledBack:Z.rolledBack}:(n.push({operationId:C.operationId,preSnapshots:G,postSnapshots:Z.snapshots,plan:C}),p(),r.length=0,{ok:!0,operationId:C.operationId,kind:C.kind,target:C.target,resultVersion:Math.max(...Z.snapshots.map(pe=>pe.version)),affectedFiles:[...Y],...W?{selectionRef:W}:{}})}async function l(C){let M=new Set(C.edits.map(Z=>Z.file)),O=await P(M),D=k(C,O);if(D)return{ok:!1,operationId:C.operationId,errorCode:"stale-version",reason:D.reason,affectedFiles:[D.file],rolledBack:!1};let Y=new Map(O.map(Z=>[Z.file,Z])),G=C.edits.find(Z=>Z.operation==="create-only"&&Y.get(Z.file)?.exists!==!1);if(G)return{ok:!1,operationId:C.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${G.file}`,affectedFiles:[G.file],rolledBack:!1};let de=C.edits.map(Z=>Z.operation==="delete"?{file:Z.file,content:"",exists:!1,version:0}:{file:Z.file,content:Z.content,exists:!0,version:0,sha256:ie(Z.content)}),W=await z(de,O,new Set(C.edits.filter(Z=>Z.operation==="create-only").map(Z=>Z.file)));return W.ok===!1?{ok:!1,operationId:C.operationId,errorCode:W.rolledBack?"writeback-failed":"rollback-failed",reason:W.reason,rolledBack:W.rolledBack}:(n.push({operationId:C.operationId,preSnapshots:O,postSnapshots:W.snapshots,plan:{operationId:C.operationId,kind:C.kind,target:C.target,documentVersion:C.documentVersion,steps:[],preSnapshots:O}}),p(),r.length=0,{ok:!0,operationId:C.operationId,kind:C.kind,target:C.target,resultVersion:Math.max(...W.snapshots.map(Z=>Z.version)),affectedFiles:[...M]})}async function u(){let C=n.at(-1);if(!C)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let M=await z(C.preSnapshots,C.postSnapshots);return M.ok===!1?{ok:!1,operationId:C.operationId,errorCode:M.rolledBack?"writeback-failed":"rollback-failed",reason:M.reason,rolledBack:M.rolledBack}:(n.pop(),r.push(C),{ok:!0,operationId:C.operationId,kind:C.plan.kind,target:C.plan.target,resultVersion:Math.max(...M.snapshots.map(O=>O.version)),affectedFiles:C.preSnapshots.map(O=>O.file)})}async function f(){let C=r.at(-1);if(!C)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let M=await z(C.postSnapshots,C.preSnapshots);return M.ok===!1?{ok:!1,operationId:C.operationId,errorCode:M.rolledBack?"writeback-failed":"rollback-failed",reason:M.reason,rolledBack:M.rolledBack}:(r.pop(),n.push(C),p(),{ok:!0,operationId:C.operationId,kind:C.plan.kind,target:C.plan.target,resultVersion:Math.max(...M.snapshots.map(O=>O.version)),affectedFiles:C.postSnapshots.map(O=>O.file)})}function p(){for(;n.length>i;)n.shift();for(;n.length>0&&m()>s;)n.shift()}function m(){return n.reduce((C,M)=>C+S(M),0)}function S(C){return b(C.preSnapshots)+b(C.postSnapshots)}function b(C){return C.reduce((M,O)=>M+O.file.length+O.content.length,0)}async function R(C,M){let O=[];for(let D of M){let Y=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(Y)));if(!G)return{ok:!1,operationId:C.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${D.sourceType}`,rolledBack:!1};let de=await G.execute(D);if(!de.ok)return{ok:!1,operationId:C.operationId,errorCode:"writeback-failed",reason:de.reason??`External adapter failed for ${D.sourceType}`,rolledBack:!1};O.push(D.file)}return{ok:!0,operationId:C.operationId,kind:C.kind,target:C.target,resultVersion:0,affectedFiles:O}}function k(C,M){if(C.conflictPolicy!=="compare-and-swap")return null;let O=new Map(M.map(D=>[D.file,D]));for(let D of C.edits){if(D.operation==="create-only")continue;if(D.baseContentHash===void 0)return{file:D.file,reason:`Source file ${D.file} is missing baseContentHash. Reopen the file before saving.`};let Y=O.get(D.file),G=D.baseContentHash;if(G===null){if(Y?.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(Y?.exists===!1||Y?.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 P(C){let M=[];for(let O of C)M.push(await A(O));return M}async function A(C){if(!await e.exists(C))return{file:C,content:"",version:0,exists:!1};let O=Math.max(1,e.getVersion(C)),D=await e.readFile(C);return{file:C,content:D,version:O,exists:!0,sha256:ie(D)}}async function z(C,M,O=new Set){let D=[];try{for(let Y of C){if(O.has(Y.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive(Y.file,Y.content)}else await oe(Y);let G=e.bumpVersion(Y.file);D.push(Y.file),Y.version=G}}catch(Y){let G=await le(M.filter(W=>D.includes(W.file)));if(G.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${G.failedFiles.join(", ")}: ${Vu(Y)}`,rolledBack:!1,instanceConflict:Uu(Y)};let de=Uu(Y);return{ok:!1,reason:`${de?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${Vu(Y)}`,rolledBack:!0,instanceConflict:de}}return{ok:!0,snapshots:C.map(ux)}}async function oe(C){if(C.exists===!1){await e.deleteFile(C.file);return}await e.writeFile(C.file,C.content)}async function le(C){let M=[];for(let O of C)try{await oe(O),e.bumpVersion(O.file)}catch{M.push(O.file)}return M.length===0?{ok:!0}:{ok:!1,failedFiles:M}}}function Uu(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function ux(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:ie(e.content)}:{}}}function Vu(e){return e instanceof Error?e.message:String(e)}function Ku(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 ve(nn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return ve(rn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return ve(Zt({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return ve(qt({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return ve(Rr({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return ve(vn({source:t,locator:e.locator,next:e.value}));case"update-array-item":return ve(vn({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return ve(Pr({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return ve(Cr({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return ve(Ar({source:t,locator:e.locator,index:e.index}));case"move-array-item":return ve(Tr({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return ve(tn({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return ve(vr({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 dx(e,t);case"set-props":{let n=e;return ve(wr({source:t,locator:n.locator,props:n.props}))}default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function dx(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!hl(n.newAttrRaw))return{ok:!1,reason:"newAttrRaw must be a valid JSX className attribute.",errorCode:"invalid-params"};let r=n.oldAttrRange!==null&&n.oldAttrRaw!==null,o=n.openingElementRange.start,i=n.openingElementRange.end,s=t.slice(o,i);if(!(Number.isInteger(o)&&Number.isInteger(i)&&o>=0&&i>o&&i<=t.length&&s.startsWith("<")&&s.endsWith(">")&&!s.startsWith("</")&&(n.oldAttrRange===null||n.oldAttrRange.start>=o&&n.oldAttrRange.end<=i)))return{ok:!1,reason:"The opening element range changed before className save.",errorCode:"stale-version"};if(!r&&n.expectedVersion.contentHash!==ie(t))return{ok:!1,reason:"The source file changed before className save.",errorCode:"stale-version"};if(n.oldAttrRange){if(t.slice(n.oldAttrRange.start,n.oldAttrRange.end)!==n.oldAttrRaw)return{ok:!1,reason:"The className attribute changed before save.",errorCode:"stale-version"}}else if(n.oldAttrRaw!==null)return{ok:!1,reason:"The className attribute range no longer matches.",errorCode:"stale-version"};return{ok:!0,source:ml({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function ve(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 Xu(){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 fx}from"node:crypto";import Zr from"node:fs/promises";import Rs from"node:path";var px={async mkdir(e,t){await Zr.mkdir(e,t)},async writeFile(e,t,n){await Zr.writeFile(e,t,n)},async rename(e,t){await Zr.rename(e,t)},async rm(e,t){await Zr.rm(e,t)}};async function Qr(e,t,n=px){let r=Rs.dirname(e),o=Rs.basename(e),i=Rs.join(r,`.${o}.${process.pid}.${fx()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await n.rename(i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import{randomBytes as wx}from"node:crypto";import Vn from"node:path";import{parse as Px}from"@babel/parser";import Ax from"@babel/traverse";import{SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as Wu,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as Tx,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as Nx,SiteEditMaterializationSchema as Fx}from"@vcp-dev/contracts";var zu=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,mx=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,hx=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,gx=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,yx=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,xx=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,Ex=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,Sx=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,bx=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,Ix=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,kx=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,Rx=/\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,Cx=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,vx=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function Cs(e,t){let n=qr([...Le(e,hx),...Le(e,gx),...Le(e,yx),...Le(e,t.includeRgbBackgroundImage?xx:Ex),...t.includeExtendedColorFunctions?[...Le(e,Sx),...Le(e,bx)]:[]]),r=qr([...Le(e,Ix),...Le(e,kx)]).filter(o=>t.colorMixPolicy==="always"||zu.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...Le(e,Rx).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...Le(e,vx).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:qr(Le(e,mx)),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?qr(Le(e,Cx)):[]}}function Le(e,t){return e.match(new RegExp(t.source,t.flags))??[]}function qr(e){return[...new Set(e)]}var As="components/site/generated",Hu="{{$INSTANCE}}",eo=5,Mx=/^[a-z][a-z0-9-]{0,48}$/,_x=/^[a-f0-9]{8}$/,Ox=/\.tsx?$/,Lx=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,Dx=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],vs=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),ws=Ax,Bx=typeof ws=="function"?ws:ws.default;function jx(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>Wu)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=Yx(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=Fx.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=zx(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${As}.`,path:e.generatedRoot}};if(!ed(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=Zu(r.data.files),s=Zu(e.controlledFiles);if(!Gx(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>Wu)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>Tx)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>Nx?{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 $x(e){let t=jx(e);if(!t.ok)return t;let n=t.data.generatedRoot,r=ed(e.manifest.instanceBaseName),o=Math.max(1,Math.min(eo,e.maxAttempts??eo));for(let i=0;i<o;i+=1){let s=Wx(e.instanceNameGenerator?.()??wx(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=nd(n,a),l=Ux({manifest:e.manifest,generatedRoot:n,instanceName:a,instanceRoot:c,allowedExternalImports:e.allowedExternalImports??Dx});if(!l.ok)return l;if(!await Vx(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 qu(e){let t=Math.max(1,Math.min(eo,e.maxAttempts??eo));for(let n=0;n<t;n+=1){let r=await $x({...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 Ux(e){let t=[],n=new Set;for(let i of e.manifest.files){let s=Yu({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=Yu({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=Kx(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 Vx(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function Yu(e){if(e.pathTemplate.split(Hu).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(Hu,e.instanceName),n=Hx(t);return n?nd(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||!Ox.test(n)||Lx.test(n)?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab files must be .ts/.tsx source files and cannot be config, layout, provider, or global 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 Kx(e,t,n,r,o){let i=new Set(e.map(u=>u.path)),s=new Map,a=new Map;for(let u of e){let f;try{f=Px(u.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:u.path}}}let p=Cs(u.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:u.path}};s.set(u.path,f),a.set(u.path,new Set)}for(let u of e){let f=s.get(u.path),p=null;if(Bx(f,{ImportDeclaration(m){let S=Gu({importer:u.path,source:m.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});S.allowed?S.internalPath&&a.get(u.path).add(S.internalPath):(p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab imports must resolve within the controlled instance or match the starter allowlist.",file:u.path},m.stop())},ExportAllDeclaration(m){p??={code:"MATERIALIZATION_ENTRY_INVALID",message:"Static prefab files cannot use export-star declarations.",file:u.path},m.stop()},ExportNamedDeclaration(m){if(m.node.source){let S=Gu({importer:u.path,source:m.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});!S.allowed||!S.internalPath?(p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab re-exports must resolve within the controlled instance.",file:u.path},m.stop()):a.get(u.path).add(S.internalPath)}},CallExpression(m){if(m.node.callee.type==="Import"){p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use dynamic import().",file:u.path},m.stop();return}m.node.callee.type==="Identifier"&&m.node.callee.name==="require"&&(p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use require().",file:u.path},m.stop())},NewExpression(m){m.node.callee.type==="Identifier"&&m.node.callee.name==="Function"&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot construct functions dynamically.",file:u.path},m.stop())},MetaProperty(m){m.node.meta.type==="Identifier"&&m.node.meta.name==="import"&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot use import.meta.",file:u.path},m.stop())},MemberExpression(m){let S=Qu(m.node);S&&vs.has(S)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${S}.`,file:u.path},m.stop())},OptionalMemberExpression(m){let S=Qu(m.node);S&&vs.has(S)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${S}.`,file:u.path},m.stop())},Identifier(m){m.isReferencedIdentifier()&&vs.has(m.node.name)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${m.node.name}.`,file:u.path},m.stop())},JSXAttribute(m){m.node.name.type==="JSXIdentifier"&&m.node.name.name==="style"&&(p??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot use inline style attributes.",file:u.path},m.stop())},JSXOpeningElement(m){m.node.name.type==="JSXIdentifier"&&m.node.name.name.toLowerCase()==="style"&&(p??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot declare style elements.",file:u.path},m.stop())}}),p)return{ok:!1,error:p}}let c=s.get(n);return c?Jx(c,r)?Xx(n,a).size!==e.length?Ps("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",n):{ok:!0,data:{kind:"static-prefab-materialization",instanceName:"",generatedRoot:As,instanceRoot:"",entry:{path:"",export:{kind:"default"}},files:[]}}:Ps("MATERIALIZATION_EXPORT_MISSING","Static prefab entry does not declare the manifest export.",n):Ps("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",n)}function Gu(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=Vn.posix.normalize(Vn.posix.join(Vn.posix.dirname(e.importer),e.source));if(t===e.instanceRoot||!t.startsWith(`${e.instanceRoot}/`))return{allowed:!1};let r=[t,`${t}.ts`,`${t}.tsx`,...["ts","tsx"].map(o=>`${t}/index.${o}`)].find(o=>e.filePaths.has(o));return r?{allowed:!0,internalPath:r}:{allowed:!1}}function Jx(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 Xx(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 Ps(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function zx(e){let t=td(e);return t===As?t:null}function Wx(e){let t=e.trim().toLowerCase();return _x.test(t)?t:null}function ed(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 Mx.test(t)?t:null}function td(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=Vn.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function Hx(e){let t=td(e);return!t||t!==e?null:t}function nd(...e){return Vn.posix.join(...e)}function Zu(e){return new Set(e.map(t=>t.pathTemplate))}function Yx(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 Gx(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Qu(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}}function ad(e){let t=null,n=new WeakMap;async function r(){return t??=Zx(e),t}return{async prepareAppend(o){let i=await e.readIndex(),s=await e.stageAppend(sd(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);rd(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(rd(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(sd(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 rd(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 Zx(e){let t=await e.readIndex(),n=await Promise.all(t.undoIds.map(async o=>od(e,o))),r=await Promise.all(t.redoIds.map(async o=>od(e,o)));return{undo:n.reverse(),redo:r.reverse(),entryIds:[...t.entryIds],cursor:t.cursor}}async function od(e,t){let n=await e.readEntry(t),r=Qx(n);return{historyId:t,operationId:r.operationId,kind:r.kind,target:r.target,...r.selectionRef?{selectionRef:r.selectionRef}:{},preSnapshots:await id(e,n,r.preSnapshots),postSnapshots:await id(e,n,r.postSnapshots)}}async function id(e,t,n){let r=new Map(t.blobs.map(o=>[o.name,o.digest]));return Promise.all(n.map(async o=>{let i=o.exists&&o.blobName?Buffer.from(await e.readBlob(qx(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function sd(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}:{},preSnapshots:n(e.preSnapshots,"pre"),postSnapshots:n(e.postSnapshots,"post")};return{kind:"site-edit-operation",manifest:JSON.parse(JSON.stringify(r)),blobs:t}}function Qx(e){if(!eE(e.manifest))throw new Error("durable history manifest is not an object");return e.manifest}function qx(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function eE(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import cd from"node:path";function Ns(){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 ud(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=oE(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 to(e){let t=()=>tE(e);return e.mutex?e.mutex.runExclusive(t):t()}async function tE(e){let t=await ud(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=nE(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 Ts({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 Ts({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 Ts({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 ld("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return ld("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 nE(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 Ts(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:rE(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 ld(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function rE(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 oE(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)||cd.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=cd.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 Fs(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function fn(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function Ms(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function _s(e,t,n,r){if(!e.has(t)&&e.size>=r){let o=e.keys().next().value;o&&e.delete(o)}e.set(t,n)}function dd(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function iE(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var Kn=class extends Error{constructor(t){let n=t.map(dd);super(iE(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function fd(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof Kn?{routeId:e,message:n,diagnostics:t.diagnostics.map(dd)}:{routeId:e,message:n}}function Os(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function pd(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 fE=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,pE=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],md=32,hd=256,gd={maxEntries:50,maxBytes:8*1024*1024};function mE(){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 Qr(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 hE(){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>gd.maxEntries||gE(e)>gd.maxBytes;)e.shift()}}function gE(e){return e.reduce((t,n)=>t+yE(n),0)}function yE(e){return yd(e.preSnapshots)+yd(e.postSnapshots)}function yd(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function xd(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 xE(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=He(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 oo=class extends Error{constructor(t){super(t.reason),this.result=t}},$t=class extends Error{constructor(t){super(Os(t)),this.failedRoutes=t}};function Ed(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=He(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(He(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}var EE=/\.(?:[cm]?[jt]sx?)$/i,SE=/\.json$/i,bE=/\.(?:css|scss|sass)$/i,IE=/\.mdx$/i,kE=/\.ya?ml$/i;function RE(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 CE(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function vE(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=PE(await e.listFiles(r)),i=new Map(o.files.map(a=>[a.path,a]));for(let[a,c]of n)if(wE(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 wE(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function PE(e){return Array.isArray(e)?{files:e}:e}function AE(e){if(!cE(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!==uE||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=aE(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(EE.test(e.path)){let t=Ze({source:e.content,profile:At({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(SE.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${Te(t)}`,details:{path:e.path}}}if(bE.test(e.path)){let t=Sd({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(IE.test(e.path)){let t=Sd({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(kE.test(e.path))try{dE(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${Te(t)}`,details:{path:e.path}}}return{ok:!0}}function Sd({content:e,path:t,profile:n}){let r=[],o=null,i=!1,s=!1,a=!1,c=!1,l=!0;for(let f=0;f<e.length;f+=1){let p=e[f]??"",m=e[f+1]??"";if(n==="mdx"&&l&&e.startsWith("```",f)){c=!c;let S=e.indexOf(`
|
|
5
5
|
`,f);if(S===-1){l=!0;break}f=S,l=!0;continue}if(c){l=p===`
|
|
6
6
|
`||p==="\r";continue}if(s){p==="*"&&m==="/"&&(s=!1,f+=1),l=p===`
|
|
7
7
|
`||p==="\r";continue}if(a){p===`
|
|
8
8
|
`||p==="\r"?(a=!1,l=!0):l=!1;continue}if(o){if(i)i=!1;else if(p==="\\")i=!0;else if(p===o)o=null;else if(n==="css"&&(p===`
|
|
9
|
-
`||p==="\r"))return
|
|
10
|
-
`||p==="\r";continue}if(p==="/"&&m==="*"){s=!0,f+=1,l=!1;continue}if(n==="mdx"&&p==="/"&&m==="/"){a=!0,f+=1,l=!1;continue}if(p==="'"||p==='"'||n==="mdx"&&p==="`"){o=p,l=!1;continue}if(p==="{"||p==="("||p==="["){r.push({char:p,offset:f}),l=!1;continue}if(p==="}"||p===")"||p==="]"){let S=p==="}"?"{":p===")"?"(":"[",b=r.pop();if(!b||b.char!==S)return
|
|
11
|
-
`||p==="\r"}if(s)return mn(t,`Unterminated block comment in ${t}.`);if(o)return mn(t,`Unterminated string literal in ${t}.`);if(c)return mn(t,`Unterminated MDX code fence in ${t}.`);let u=r.at(-1);return u?mn(t,`Unclosed token "${u.char}" in ${t}.`):{ok:!0}}function mn(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function Hn(e){let t="idle",n=e.fileSystem??bE(),r=Gu(),o=new Map,i=new Map,s=null,a=new Set,c=null,l=e.history??(e.historyStore?fd(e.historyStore):IE()),u=Yu(n,{externalAdapters:e.externalAdapters}),f=new Map,p=Math.max(0,e.initialDocumentVersion??0),m=0,S=e.historyStore?.recoveryRequired??!1,b=Ls(),k=H();function R(d){return(io.isAbsolute(d)?io.relative(e.projectRoot,d):d).replace(/\\/g,"/").replace(/^\.\//,"")}function w(d,h){let x=io.posix.dirname(d),I=h.replace(/\.(?:tsx?|jsx?)$/i,""),C=io.posix.relative(x,I);return C.startsWith(".")?C:`./${C}`}function A(d,h){return d.startLine===h.startLine&&d.startColumn===h.startColumn&&d.endLine===h.endLine&&d.endColumn===h.endColumn}async function H(){let d=e.historyStore;if(d)try{let h=await d.readTransactionJournal();if(!h)return;let x=await d.readIndex(),I=await Promise.all(h.files.map(async M=>await n.exists(M.path)?ae(await n.readFile(M.path)):null));if(xd({journal:h,index:x,observedFileDigests:I})!=="ambiguous"){await d.clearTransactionJournal(h.transactionId);let M=await d.readStatus();M.recoveryRequired||(await d.cleanupTmp(),M=await d.readStatus()),S=M.recoveryRequired;return}await d.markRecoveryRequired(`Ambiguous transaction journal ${h.transactionId} at phase ${h.phase}`),S=!0}catch(h){S=!0,await d.markRecoveryRequired(`Transaction journal recovery failed: ${Te(h)}`).catch(()=>{})}}function se(){return t==="disposed"}if(e.onEvent&&r.subscribe(e.onEvent),e.routes)for(let d of e.routes){let h=kd(d.routeId,d.entryFile);o.set(d.routeId,h),ue(h,h.dependencyFiles)}function ue(d,h){let x=new Set(h);v(d),d.dependencyFiles=x;for(let I of d.dependencyFiles){let C=i.get(I);C||(C=new Set,i.set(I,C)),C.add(d.routeId)}}function v(d){for(let h of d.dependencyFiles){let x=i.get(h);x&&(x.delete(d.routeId),x.size===0&&i.delete(h))}d.dependencyFiles.clear()}function N(d){let h=new Set;for(let x of d)for(let I of i.get(x)??[])h.add(I);return h}function B(d){for(let h of d)if(!i.has(h))return!1;return!0}async function j(d,h,x,I,C){let M=new Map,L=Pu(C.values()),F=typeof n.exists=="function"?T=>n.exists(T):async()=>!1;for(let[T,O]of d.elements){let z=h.nodes.get(T);if(!z)continue;let W=x.get(O.sourceFile)??I.get(O.sourceFile),ee=new Map,P=new Map,J=new Map,D=[];for(let de of O.textSegments){if(!W){ee.set(de.index,null);continue}let En=await Au({file:O.sourceFile,source:W,segment:de,readFile:je=>n.readFile(je),exists:F,graph:d,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:je,adapterId:Fo,capabilities:Mo})=>({sourceType:je,adapterId:Fo,capabilities:Mo})),functionCallContracts:e.functionCallContracts,fileCache:L}),Se=await Es({file:O.sourceFile,source:W,target:{kind:"text-segment",segment:de},readFile:je=>n.readFile(je),exists:F,graph:d,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:je,adapterId:Fo,capabilities:Mo})=>({sourceType:je,adapterId:Fo,capabilities:Mo})),functionCallContracts:e.functionCallContracts,fileCache:L}),Jt=NE(En);ee.set(de.index,Jt),P.set(de.index,En),J.set(de.index,Se),D.push({editable:de.editable,source:Jt})}let te=new Map;if(W)for(let de of O.attributes??[]){let En=await Tu({file:O.sourceFile,source:W,sourceRange:de.sourceRange,expression:de.source?.expression??de.value,sourceInfo:de.source,readFile:Se=>n.readFile(Se),exists:F,graph:d,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Se,adapterId:Jt,capabilities:je})=>({sourceType:Se,adapterId:Jt,capabilities:je})),functionCallContracts:e.functionCallContracts,fileCache:L});te.set(de.name,En)}let re=Xc(FE(z.writeTarget),D),he=Wc({key:T,element:O,graph:d,provenances:J}),be=Zc(O),sr=Qc(O),ar=pl(O),nt=d.regions.find(de=>de.kind==="conditional-region"&&de.childKeys.includes(T)),xn,Re=nt?.sourceCandidates?.[0];if(W&&nt&&Re?.kind==="conditional-branch"){let de=await Es({file:O.sourceFile,source:W,target:{kind:"conditional-branch",candidate:Re},readFile:Se=>n.readFile(Se),exists:F,graph:d,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Se,adapterId:Jt,capabilities:je})=>({sourceType:Se,adapterId:Jt,capabilities:je})),functionCallContracts:e.functionCallContracts,fileCache:L});xn={currentBranch:nt.childKeys.indexOf(T)<=0?"then":"else",availableBranches:nt.childKeys.length>1?["then","else"]:["then"],conditionExpression:Re.conditionExpression,provenance:{finalSource:de.finalSource?{kind:de.finalSource.kind,file:de.finalSource.file,displayPath:de.finalSource.displayPath}:null,chain:de.chain.map(Se=>({kind:Se.kind,file:Se.file,displayName:Se.displayName,canEditHere:Se.canEditHere})),confidence:de.confidence,editMode:de.editMode,diagnostics:de.diagnostics.map(Se=>({code:Se.code,message:Se.message}))}}}M.set(T,{textSources:ee,textTargets:P,elementPropertyTargets:te,provenances:J,writeTarget:re,componentSemantic:he,contentModel:be,mediaModel:sr,styleSource:ar,conditional:xn})}return M}function G(d){return typeof n.getVersion=="function"?n.getVersion(d):0}function Z(d,h){let x=1;for(let I of h.values())x=Math.max(x,I);return Math.max(x,d.graph?.version??0)}async function fe(d,h,x={}){let I=o.get(d);if(!I)return null;let C=x.sourceCache??Ds(f,[]),M=await Y(I.entryFile),{graph:L,allSources:F,diagnostics:T,parsedModules:O,entryModule:z}=await Ja(I.entryFile,h,Re=>n.readFile(Re),typeof n.exists=="function"?Re=>n.exists(Re):async()=>!1,{additionalEntries:M,version:I.graph?.version??1});if(T.length>0)throw new zn(T);let W=new Map;for(let Re of F.keys())W.set(Re,G(Re));let ee=Math.max(Z(I,W),x.minimumVersion??0,p);x.changed&&ee<=(I.graph?.version??0)&&(ee=(I.graph?.version??0)+1),L.version=ee;for(let[Re,de]of F)js(C,Re,de,Sd);let P=await Q(I.entryFile,F,C);L.routeId=d;let J=Xa(L),D=Wa(J,L),te=await j(L,J,F,C,O),re=ut(L,D,te),he=WE(Kc(L,J,D,{canUpdateTextByKey:re}),L,te),be=Oc({route:d,entryFile:I.entryFile,version:ee,source:h,ast:z?.ast}),sr=Lc(be);be.ok&&DE(he,L,be.projection);let ar={...he,...P?{styleContext:P}:{},pageComposition:sr},nt=new Set([I.entryFile,...F.keys()]);if(P){nt.add(P.entryCss.path);for(let Re of P.stylesheets)nt.add(Re.path)}let xn={...I,dependencyFiles:nt,graph:L,topology:J,capabilities:D,document:ar,pageComposition:sr,pageCompositionProjection:be.projection,pagePlacementByKey:be.ok?be.projection.placementByKey:null,pagePlacementUnitByKey:be.ok?be.projection.placementUnitByKey:null,pageUnitByKey:be.ok?be.projection.unitByKey:null,pagePlacementsByUnitKey:be.ok?be.projection.placementsByUnitKey:null,documentIndex:CE(ar),detailProjections:te,fileVersions:W,styleContext:P};return x.publish===!1?xn:(pn(f,C),p=Math.max(p,ee),ue(I,nt),Object.assign(I,xn),I)}async function Y(d){let h=[];for(let x of VE(d))typeof n.exists=="function"&&await n.exists(x)&&h.push({file:x,source:await n.readFile(x)});return h}async function Q(d,h,x){let I=[];for(let[T,O]of h){if(Us(T)){I.push(T);continue}for(let z of KE(O)){let W=Pd(T,z);W&&I.push(W)}}if(!I.length){for(let T of UE(d))if(await tt(T)){I.push(T);break}}let C=new Map,M=Fd(I).slice(0,Ed);for(;M.length>0&&C.size<Ed;){let T=M.shift();if(C.has(T)||!Us(T))continue;let O=await pe(T,x);if(O!==null){C.set(T,{path:T,content:O});for(let z of JE(O)){let W=Pd(T,z);W&&!C.has(W)&&!M.includes(W)&&M.push(W)}}}let L=[...C.values()].map(T=>({...T,hash:ae(T.content)})),F=L[0];return F?{revision:ae(JSON.stringify(L.map(({path:T,hash:O})=>({path:T,hash:O})))),entryCss:F,stylesheets:L.slice(1)}:null}async function pe(d,h){let x=h.get(d);if(x!==void 0)return x;if(!await tt(d))return null;let I=await n.readFile(d);return js(h,d,I,Sd),I}async function tt(d){return typeof n.exists=="function"?n.exists(d):!1}function ut(d,h,x){let I=new Map;for(let[C,M]of d.elements){if(!h.get(C)?.canUpdateText){I.set(C,!1);continue}let F=x.get(C),T=M.textSegments.some(O=>{if(!O.editable)return!1;let z=F?.provenances.get(O.index)??null;return!z||cf(z)});I.set(C,T)}return I}function cf(d){return d.editMode==="direct"||d.editMode==="proxy"||d.editMode==="upstream"}async function tr(d,h={}){let x=[...new Set(d)],I=N(x);if(I.size===0||!B(x))for(let F of o.values())ga(F,x)&&I.add(F.routeId);let C=I.size===0&&x.some(wd),M=h.publish===!1?Ds(f,x):void 0,L={rebuiltRoutes:[],failedRoutes:[],...h.publish===!1?{candidateRouteStates:[],candidateSourceCache:M}:{}};for(let F of o.values())if(I.has(F.routeId)||C)try{let O=!!F.graph,z=await n.readFile(F.entryFile),W=await fe(F.routeId,z,{...h,...M?{sourceCache:M}:{}});W?.graph&&(L.rebuiltRoutes.push({documentChanged:O,routeId:F.routeId,version:W.graph.version}),L.candidateRouteStates?.push({routeId:F.routeId,state:W}))}catch(O){L.failedRoutes.push(yd(F.routeId,O))}return L}function ha(d){let h=[...new Set(d)],x=N(h);if(x.size>0&&B(h))return[...x];for(let I of o.values())ga(I,h)&&x.add(I.routeId);return[...x]}function Ro(d,h){r.emit({type:"operation-completed",result:d});for(let{routeId:x,version:I}of h.rebuiltRoutes)r.emit({type:"document-changed",routeId:x,version:I});for(let{routeId:x,message:I}of h.failedRoutes)r.emit({type:"graph-error",routeId:x,message:I})}function ga(d,h){return h.some(x=>d.dependencyFiles.has(x)||d.entryFile===x||d.graph?.fileIndex.has(x))}function ya(d){for(let h of d)a.add(h);c||se()||(c=(async()=>{t="building";let h=!1;try{for(;a.size>0;){if(se())return;await lf();let x=[...a];a.clear();let I=await xa(x);if(I.length===0)continue;let C=ha(I);for(let F of C)r.emit({type:"graph-invalidated",routeId:F});let{rebuiltRoutes:M,failedRoutes:L}=await tr(I,{changed:!0});for(let{documentChanged:F,routeId:T,version:O}of M)r.emit({type:"graph-ready",routeId:T,version:O}),F&&r.emit({type:"document-changed",routeId:T,version:O});for(let{routeId:F,message:T}of L)h=!0,r.emit({type:"graph-error",routeId:F,message:T})}}finally{if(c=null,t!=="disposed"){let x=s?o.get(s):null;t=!h&&x?.graph?"ready":"idle"}a.size>0&&ya([])}})())}async function lf(){for(;m>0;)await new Promise(d=>setTimeout(d,0))}async function xa(d){let h=[];for(let x of new Set(d)){let I=f.get(x);if(I===void 0){h.push(x);continue}try{await n.readFile(x)!==I&&h.push(x)}catch{h.push(x)}}return h}async function Ea(d){let h=await xa(d);if(h.length===0)return;let x=ha(h);for(let M of x)r.emit({type:"graph-invalidated",routeId:M});let{rebuiltRoutes:I,failedRoutes:C}=await tr(h,{changed:!0});for(let{documentChanged:M,routeId:L,version:F}of I)r.emit({type:"graph-ready",routeId:L,version:F}),M&&r.emit({type:"document-changed",routeId:L,version:F});for(let{routeId:M,message:L}of C)r.emit({type:"graph-error",routeId:M,message:L})}async function uf(d,h){let x=or(d,h);if(!x?.graph)return;let I=He(d)??d,C=x.graph.elements.get(I);C&&await Ea([C.sourceFile])}async function Sa(d){let h=new Set;if(d.target.kind==="node"){let x=or(d.target.key,d.routeId),I=He(d.target.key)??d.target.key,C=x?.graph?.elements.get(I);C&&h.add(C.sourceFile)}else if(d.target.kind==="route"){let x=o.get(d.target.routeId);x&&h.add(x.entryFile)}else if(d.target.kind==="page-unit"){let x=o.get(d.target.routeId);x&&h.add(x.entryFile)}else if(d.target.kind==="source-file")h.add(d.target.path);else if(d.target.kind==="source-batch")for(let x of d.target.paths)h.add(x);await Ea(h)}async function Ut(d){if(!d)return{ok:!1,code:_.MUTATION_SESSION_REQUIRED,message:"A mutation session is required for write operations."};if(!e.mutationContextVerifier||!e.tenantId||!e.siteId||!e.snapshotId)return{ok:!1,code:_.LEASE_ASSERTION_INVALID,message:"Lease assertion verification is unavailable."};try{return await e.mutationContextVerifier.verify(d,{tenantId:e.tenantId,siteId:e.siteId,snapshotId:e.snapshotId,editingSessionId:d.editingSessionId,lockId:d.lockId,ownerId:d.ownerId})}catch{return{ok:!1,code:_.LEASE_ASSERTION_INVALID,message:"Lease assertion verification failed."}}}function Co(d,h){return q(d,h.code,h.message)}function vo(d,h,x){return{requestId:d,kind:x?.kind??"update-text",target:x?.target??{kind:"node",key:""},ok:!1,resultVersion:p,error:{code:h.code,message:h.message}}}async function df(d){if(d.params.kind!=="source-edit")return wo(d,"invalid-params","source-edit requires source-edit params");for(let h of d.params.edits){let x=LE(h);if(!x.ok)return wo(d,x.errorCode,x.message,x.details)}m+=1;try{let h=await hf(d.params.edits);if(!h.ok)return wo(d,h.errorCode,h.message,h.details);let x={operationId:d.id,kind:"source-edit",target:d.target,documentVersion:d.documentVersion,conflictPolicy:d.params.conflictPolicy,edits:d.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 nr({request:d,filePlan:x})}catch(h){return{requestId:d.id,kind:d.kind,target:d.target,ok:!1,resultVersion:p,error:{code:_.INTERNAL_ERROR,message:Te(h)}}}finally{m-=1}}async function ff(d,h){if(d.kind!=="insert-child"||d.params.kind!=="insert-child")return q(d,_.UNSUPPORTED_OPERATION,"Only page-unit insert-child is currently supported by the page composition transaction.");if(!("kind"in d.params.position)||d.params.position.kind!=="page-composition")return q(d,_.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(d.params.position.documentVersion!==d.documentVersion)return q(d,_.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.");if(!d.mutationContext)return q(d,_.INVALID_TARGET,"Page-unit insert-child requires a mutation context.");if(!e.mutationContextVerifier)return q(d,_.INVALID_TARGET,"Page-unit insert-child requires a configured mutation context verifier.");let x=h.document,I=h.pageCompositionProjection;if(!x||x.pageComposition?.status!=="supported"||!I||I.status!=="supported")return q(d,_.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(d.documentVersion!==x.version||I.documentVersion!==x.version)return q(d,_.VERSION_STALE,`Document version ${d.documentVersion} is stale (current: ${x.version}).`);let C=d.params.node.kind==="component-call"?d.params.node.materialization:void 0;if(!C)return q(d,_.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let M=d.params.position,L=await od({manifest:C,generatedRoot:"components/site/generated",controlledFiles:C.files.map(F=>({pathTemplate:F.pathTemplate})),exists:F=>n.exists(F),commit:async F=>{let T=await n.readFile(h.entryFile),O=h.document,z=h.pageCompositionProjection;if(!O||O.pageComposition?.status!=="supported"||O.version!==d.documentVersion||!z||z.status!=="supported"||z.documentVersion!==O.version)return{ok:!0,data:q(d,_.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let W=F.entry.path,ee=If(F.instanceName),P=ui({routeId:h.routeId,entryFile:h.entryFile,currentDocumentVersion:O.version,expectedDocumentVersion:d.documentVersion,source:T,projection:z,placementKey:M.placementKey,component:{source:W,exportName:F.entry.export.kind==="default"?"default":F.entry.export.name,localName:ee}});if(!P.ok)return{ok:!0,data:q(d,Pa(P.error.code),P.error.message,{diagnostics:P.error.diagnostics})};let J=P.plan.returnStep?Tc({source:T,jsx:P.plan.returnStep.node.jsx,placement:P.plan.returnStep.placement,...P.plan.returnStep.replaceOriginal?{replaceOriginal:!0}:{}}):P.plan.insertStep?.parentLocator?en({source:T,locator:P.plan.insertStep.parentLocator,node:P.plan.insertStep.node,placement:P.plan.insertStep.placement,...P.plan.insertStep.anchorLocator?{anchorLocator:P.plan.insertStep.anchorLocator}:{}}):{ok:!1,source:T,diagnostic:{code:"unsupported-syntax",message:"Route composition rewrite has no insertion step."}};if(!J.ok)return{ok:!0,data:q(d,_.AST_PARSE_ERROR,J.diagnostic.message)};let D=rn({source:J.source,moduleSpecifier:P.plan.importStep.moduleSpecifier,imports:P.plan.importStep.imports});if(!D.ok)return{ok:!0,data:q(d,_.AST_PARSE_ERROR,D.diagnostic.message)};let te=F.files.map(he=>({operation:"create-only",file:he.path,content:he.content})),re=[{operation:"upsert",file:h.entryFile,content:D.source,baseContentHash:ae(T)},...te];m+=1;try{let he=await nr({request:d,filePlan:{operationId:d.id,kind:"source-edit",target:{kind:"source-file",path:h.entryFile},documentVersion:d.documentVersion,conflictPolicy:"compare-and-swap",edits:re}});return!he.ok&&he.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:he.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:he}}finally{m-=1}}});return L.ok?L.data:q(d,_.VERSION_STALE,L.error.message,{materializationCode:L.error.code})}async function pf(d,h){if(d.kind!=="move-node"&&d.kind!=="remove-node")return q(d,_.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");if(!d.mutationContext)return q(d,_.INVALID_TARGET,"Page-unit mutation requires a mutation context.");if(!e.mutationContextVerifier)return q(d,_.INVALID_TARGET,"Page-unit mutation requires a configured mutation context verifier.");let x=h.document,I=h.pageCompositionProjection;if(!x||x.pageComposition?.status!=="supported"||!I||I.status!=="supported")return q(d,_.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(d.documentVersion!==x.version||I.documentVersion!==x.version)return q(d,_.VERSION_STALE,`Document version ${d.documentVersion} is stale (current: ${x.version}).`);let C=await n.readFile(h.entryFile),M=Nc({routeId:h.routeId,entryFile:h.entryFile,currentDocumentVersion:x.version,expectedDocumentVersion:d.documentVersion,source:C,projection:I,placementUnitKey:d.target.placementUnitKey,operation:d.kind,targetPlacement:d.kind==="move-node"&&d.params.kind==="move-node"&&"kind"in d.params.target&&d.params.target.kind==="page-composition"?d.params.target:void 0});if(!M.ok)return q(d,Pa(M.error.code),M.error.message,{diagnostics:M.error.diagnostics});let L=M.plan.rewriteStep.kind==="move-node"?nn({source:C,locator:M.plan.rewriteStep.locator,targetParentLocator:M.plan.rewriteStep.targetParentLocator,placement:M.plan.rewriteStep.placement,...M.plan.rewriteStep.anchorLocator?{anchorLocator:M.plan.rewriteStep.anchorLocator}:{}}):Qt({source:C,locator:M.plan.rewriteStep.locator});if(!L.ok)return q(d,_.AST_PARSE_ERROR,L.diagnostic.message);let F=L.source,T=[];if(d.kind==="remove-node"){let z=await mf({routeState:h,placementUnitKey:d.target.placementUnitKey,source:C,mutatedSource:F});F=z.source,T=await Promise.all(z.files.map(async W=>({operation:"delete",file:W,baseContentHash:ae(await n.readFile(W))})))}let O=[{operation:"upsert",file:h.entryFile,content:F,baseContentHash:ae(C)},...T];m+=1;try{return await nr({request:d,filePlan:{operationId:d.id,kind:"source-edit",target:{kind:"source-file",path:h.entryFile},documentVersion:d.documentVersion,conflictPolicy:"compare-and-swap",edits:O}})}finally{m-=1}}async function mf(d){let h={source:d.mutatedSource,files:[]},x=d.routeState.graph,I=d.routeState.pageCompositionProjection;if(!x||!I||I.status!=="supported"||!n.listFiles)return h;let M=I.placementUnitByKey.get(d.placementUnitKey)?.sourceRange;if(!M)return h;let L=[...x.elements.values()].find(re=>re.sourceFile===d.routeState.entryFile&&re.importedFrom&&A(re.sourceRange,M));if(!L?.importedFrom||!L.exportName)return h;let F=R(L.importedFrom),T="components/site/generated/";if(!F.startsWith(T))return h;let O=F.slice(T.length).split("/")[0];if(!O||!/-[0-9a-f]{8}$/i.test(O))return h;let z=`${T}${O}`;if([...x.elements.values()].filter(re=>re.sourceFile===d.routeState.entryFile&&R(re.importedFrom??"")===F).length!==1)return h;let ee=await n.listFiles({maxFiles:5e3,maxDepth:32}),P=Array.isArray(ee)?ee:ee.files;if(!Array.isArray(ee)&&ee.truncated)return h;let J=P.map(({path:re})=>re).filter(re=>re===z||re.startsWith(`${z}/`));if(J.length===0||!J.includes(F))return h;for(let{path:re}of P)if(!(re===d.routeState.entryFile||re===z||re.startsWith(`${z}/`)))try{if((await n.readFile(re)).includes(O))return h}catch{return h}let D=w(d.routeState.entryFile,F),te=on({source:d.mutatedSource,moduleSpecifier:D,imports:L.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:L.exportName}]});return te.ok?{source:te.source,files:J.sort((re,he)=>re.localeCompare(he))}:h}async function hf(d){if(n.getFileInfo){for(let C of d)if(await n.exists(C.path)&&await n.getFileInfo(C.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${C.path}`,details:{path:C.path}}}let h=gf(d);if(h.length===0)return{ok:!0};let x=ME(n,d),I=Hn({projectRoot:e.projectRoot,fileSystem:x,routes:[...o.values()].map(C=>({routeId:C.routeId,entryFile:C.entryFile})),externalAdapters:e.externalAdapters,externalSourceResolvers:e.externalSourceResolvers,functionCallContracts:e.functionCallContracts,dev:e.dev});try{for(let C of h)await I.setActiveRoute(C)}catch(C){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${Te(C)}`,details:{routeIds:h}}}finally{I.dispose()}return{ok:!0}}function gf(d){return d.map(x=>x.path).some(wd)?[...o.keys()]:[]}function wo(d,h,x,I){let C=Wn(h);return{requestId:d.id,kind:d.kind,target:d.target,ok:!1,resultVersion:p,error:{code:C,message:x,...I?{details:I}:{}}}}async function Po(d){let h=[];for(let x of new Set(d))h.push(await yf(x));return h}async function yf(d){if(!(typeof n.exists=="function"?await n.exists(d):!0))return{file:d,content:"",version:Math.max(0,G(d)),exists:!1};let x=await n.readFile(d);return{file:d,content:x,version:Math.max(1,G(d)),exists:!0,sha256:ae(x)}}async function ba(d,h,x,I){if(!e.historyStore)return null;let C=I.historyTransition;if(!C)throw new Error("Durable history did not provide an exact index transition.");let M=new Map(h.map(T=>[T.file,T])),L=new Map(x.map(T=>[T.file,T])),F=[...new Set([...M.keys(),...L.keys()])].sort().map(T=>{let O=M.get(T),z=L.get(T);return{path:T,preDigest:O?.exists===!1||!O?null:ae(O.content),postDigest:z?.exists===!1||!z?null:ae(z.content)}});return{schemaVersion:2,transactionId:`${d}:${C.expectedIndexDigest}`,operationId:d,phase:"prepared",historyTransition:C,files:F}}async function Ia(d){return!d||!e.historyStore||await e.historyStore.writeTransactionJournal(d),d}async function Kt(d){d&&e.historyStore&&await e.historyStore.clearTransactionJournal(d.transactionId)}async function Ao(d,h){let x=[];try{for(let I of d)await ka(I),typeof n.bumpVersion=="function"&&n.bumpVersion(I.file),x.push(I.file)}catch(I){let C=await xf(h.filter(M=>x.includes(M.file)));return C.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${Te(I)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${C.failedFiles.join(", ")}: ${Te(I)}`,rolledBack:!1}}return{ok:!0,snapshots:d.map(Ef)}}async function ka(d){if(d.exists===!1){await n.deleteFile(d.file);return}await n.writeFile(d.file,d.content)}async function xf(d){let h=[];for(let x of d)try{await ka(x),typeof n.bumpVersion=="function"&&n.bumpVersion(x.file)}catch{h.push(x.file)}return h.length===0?{ok:!0}:{ok:!1,failedFiles:h}}function Ef(d){let h=d.exists!==!1;return{file:d.file,content:h?d.content:"",version:d.version,exists:h,...h?{sha256:ae(d.content)}:{}}}async function nr(d){return b.runExclusive(()=>Sf(d))}async function Sf(d){let h=d.filePlan.edits.map(P=>P.file),x=await Po(h),I=new Map(x.filter(P=>P.exists!==!1).map(P=>[P.file,P.content])),C=p,M=Ca(),L=new Map(f),F=d.filePlan.edits.map(P=>P.operation==="delete"?{file:P.file,content:"",version:0,exists:!1}:{file:P.file,content:P.content,version:0,exists:!0,sha256:ae(P.content)}),T={operationId:d.filePlan.operationId,intents:d.filePlan.edits.map(P=>P.operation==="delete"?{kind:"delete",path:P.file}:{kind:P.operation==="create-only"?"create-only":"upsert",path:P.file,content:P.content})},O=null,z=!1,W=await oo({overlay:I,exists:P=>n.exists(P),plan:T,buildCandidate:async({plan:P})=>({plan:P}),prepareHistory:async()=>{let P=await l.prepareAppend({operationId:d.request.id,kind:d.request.kind,target:d.request.target,preSnapshots:x,postSnapshots:F,...d.selectionRef?{selectionRef:d.selectionRef}:{}});return O=await ba(d.request.id,x,F,P),O=await Ia(O),P},reverify:async()=>{let P=await Ut(d.request.mutationContext);if(!P.ok)throw new hn(P)},writeCandidate:async()=>{let P=await u.executeFilePlan(d.filePlan);if(!P.ok)throw new ao(P);return{postSnapshots:await Po(P.affectedFiles),affectedFiles:P.affectedFiles,internalResultVersion:P.resultVersion}},validateCandidate:async({candidate:P,receipt:J})=>{let D=await tr(J.affectedFiles,{changed:!0,minimumVersion:J.internalResultVersion,publish:!1});if(D.failedRoutes.length>0)throw new $t(D.failedRoutes);let te=va(M,D.candidateRouteStates??[]),re=Math.max(J.internalResultVersion,...D.rebuiltRoutes.map(he=>he.version));return{...P,rebuild:D,routeSnapshots:te,resultVersion:re,...Rd(d.selectionRef,te.map(he=>he.state.document))?{selectionRef:Rd(d.selectionRef,te.map(he=>he.state.document))}:{}}},publishCandidate:async({candidate:P,history:J,receipt:D})=>{if(!J)throw new Error("history intent is missing");await l.publishPrepared(J),z=!0;let te=P.resultVersion??D.internalResultVersion;return{requestId:d.request.id,kind:d.request.kind,target:d.request.target,ok:!0,resultVersion:te,affectedFiles:D.affectedFiles,...P.selectionRef?{selectionRef:P.selectionRef}:{}}},swapCandidate:({candidate:P,receipt:J})=>{P.routeSnapshots&&rr(P.routeSnapshots),P.rebuild?.candidateSourceCache&&pn(f,P.rebuild.candidateSourceCache),Bs(f,J.postSnapshots),p=Math.max(p,P.resultVersion??C)},finalizeCandidate:async()=>{await Kt(O)},emitCommitted:({candidate:P,published:J})=>{Ro(J,P.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:P,receipt:J})=>{if(z)throw new Error("history was published before transaction finalization failed");if(J){let D=await Ao(x,J.postSnapshots);if(!D.ok)throw new Error(D.reason)}rr(M),pn(f,L),p=C,P&&await l.discardPrepared?.(P),await Kt(O)}});if(W.ok)return W.published;if(W.stage==="precheck"||W.stage==="build")try{await Kt(O)}catch(P){let J=await ir(Te(P));return q(d.request,J,"Unable to clear an uncommitted transaction journal.")}if(W.recoveryRequired){let P=await ir(W.reason);return q(d.request,P===_.RECOVERY_PERSIST_FAILED?P:_.ROLLBACK_FAILED,W.reason)}let ee=W.error;return ee instanceof hn?Co(d.request,ee.result):ee instanceof ao?{...q(d.request,Wn(ee.result.errorCode),ee.result.reason),...ee.result.affectedFiles?{affectedFiles:ee.result.affectedFiles}:{}}:ee instanceof $t?q(d.request,_.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${$s(ee.failedRoutes)}`,{failedRoutes:ee.failedRoutes}):q(d.request,wa(W.stage),Te(ee))}async function Ra(d,h){return b.runExclusive(async()=>{let x=d==="undo"?await l.prepareUndo():await l.prepareRedo();return x?bf(d,h,x):{requestId:d,kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:p,error:{code:_.INTERNAL_ERROR,message:d==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function bf(d,h,x){let I=x.entry,C=d==="undo"?I.preSnapshots:I.postSnapshots,M=d==="undo"?I.postSnapshots:I.preSnapshots,L=C.map(D=>D.file),F=await Po(L),T=new Map(F.filter(D=>D.exists!==!1).map(D=>[D.file,D.content])),O=p,z=Ca(),W=new Map(f),ee=null,P=!1,J=await oo({overlay:T,plan:{operationId:`${d}:${I.operationId}`,intents:C.map(D=>D.exists===!1?{kind:"delete",path:D.file}:{kind:"upsert",path:D.file,content:D.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(ee=await ba(`${d}:${I.operationId}`,F,C,x),ee=await Ia(ee),x),reverify:async()=>{let D=await Ut(h);if(!D.ok)throw new hn(D)},writeCandidate:async()=>{let D=await Ao(C,M);if(!D.ok)throw new Error(D.reason);return{snapshots:D.snapshots}},validateCandidate:async({candidate:D})=>{let te=await tr(L,{changed:!0,minimumVersion:p+1,publish:!1});if(te.failedRoutes.length>0)throw new $t(te.failedRoutes);let re=va(z,te.candidateRouteStates??[]),he=Math.max(p+1,...te.rebuiltRoutes.map(be=>be.version));return{...D,rebuild:te,routeSnapshots:re,resultVersion:he}},publishCandidate:async({candidate:D,history:te})=>{if(!te)throw new Error("history cursor intent is missing");await l.publishPrepared(te),P=!0;let re=D.resultVersion??p+1;return{requestId:d,kind:I.kind,target:I.target,ok:!0,resultVersion:re,affectedFiles:L}},swapCandidate:({candidate:D,receipt:te})=>{D.routeSnapshots&&rr(D.routeSnapshots),D.rebuild?.candidateSourceCache&&pn(f,D.rebuild.candidateSourceCache),Bs(f,te.snapshots),p=Math.max(p,D.resultVersion??O)},finalizeCandidate:async()=>{await Kt(ee)},emitCommitted:({candidate:D,published:te})=>Ro(te,D.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:D,receipt:te})=>{if(P)throw new Error("history cursor was published before transaction finalization failed");if(te){let re=await Ao(M,te.snapshots);if(!re.ok)throw new Error(re.reason)}rr(z),pn(f,W),p=O,D&&await l.discardPrepared?.(D),await Kt(ee)}});if(J.ok)return J.published;if(J.stage==="precheck"||J.stage==="build")try{await Kt(ee)}catch(D){let te=await ir(Te(D));return{requestId:d,kind:I.kind,target:I.target,ok:!1,resultVersion:p,error:{code:te,message:"Unable to clear an uncommitted transaction journal."}}}if(J.recoveryRequired){let D=await ir(J.reason);return{requestId:d,kind:I.kind,target:I.target,ok:!1,resultVersion:p,affectedFiles:L,error:{code:D===_.RECOVERY_PERSIST_FAILED?D:_.ROLLBACK_FAILED,message:J.reason}}}return J.error instanceof hn?vo(d,J.error.result,I):{requestId:d,kind:I.kind,target:I.target,ok:!1,resultVersion:p,affectedFiles:L,error:{code:J.error instanceof $t?_.ROUTE_REBUILD_FAILED:wa(J.stage),message:Te(J.error),...J.error instanceof $t?{details:{failedRoutes:J.error.failedRoutes}}:{}}}}function Ca(){return[...o.values()].map(d=>({routeId:d.routeId,state:{...d,dependencyFiles:new Set(d.dependencyFiles),fileVersions:new Map(d.fileVersions)}}))}function va(d,h){let x=new Map(d.map(I=>[I.routeId,I]));for(let I of h)x.set(I.routeId,I);return[...x.values()]}function rr(d){for(let h of o.values())v(h);for(let h of d){let x={...h.state,dependencyFiles:new Set(h.state.dependencyFiles),fileVersions:new Map(h.state.fileVersions)};o.set(h.routeId,x),ue(x,x.dependencyFiles)}}async function To(d){let h=o.get(d);if(!h)throw new Error(`Route not found: ${d}`);if(h.graph)return;let x=await n.readFile(h.entryFile);await fe(d,x)}function or(d,h){if(h){let x=o.get(h)??null;return!x||!No(x,d)?null:x}for(let x of o.values())if(No(x,d))return x;return null}function No(d,h){if(d.documentIndex?.entriesByKey.has(h)||d.graph?.elements.has(h))return!0;let x=He(h);return x&&x!==h?d.graph?.elements.has(x)===!0:!1}function q(d,h,x,I){return{requestId:d.id,kind:d.kind,target:d.target,ok:!1,resultVersion:p,error:{code:h,message:x,...I?{details:I}:{}}}}function wa(d){return d==="validate"?_.ROUTE_REBUILD_FAILED:d==="publish"?_.HISTORY_COMMIT_FAILED:_.WRITE_IO_ERROR}async function ir(d){if(S=!0,!l.markRecoveryRequired)return _.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(d),_.RECOVERY_REQUIRED}catch{return _.RECOVERY_PERSIST_FAILED}}function If(d){let x=d.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(I=>I.charAt(0).toUpperCase()+I.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return x?`Prefab${x}`:"GeneratedPrefab"}function Pa(d){return d==="VERSION_STALE"?_.VERSION_STALE:d==="CROSS_PAGE_MOVE_UNSUPPORTED"?_.CROSS_PAGE_MOVE_UNSUPPORTED:_.UNSUPPORTED_OPERATION}async function Aa(d){if(d.target.kind==="route"){let x=o.get(d.target.routeId)??null;return x?(x.graph||await To(x.routeId),x):q(d,_.ROUTE_NOT_FOUND,`Route not found: ${d.target.routeId}`)}if(d.target.kind==="page-unit"){let x=o.get(d.target.routeId)??null;return x?(x.graph||await To(x.routeId),x):q(d,_.ROUTE_NOT_FOUND,`Route not found: ${d.target.routeId}`)}if(d.target.kind!=="node")return q(d,_.UNSUPPORTED_OPERATION,`${d.kind} source target execution is not implemented yet.`);if(!d.routeId)return q(d,_.INVALID_TARGET,"routeId is required when executing a node target");let h=o.get(d.routeId)??null;return h?(h.graph||await To(h.routeId),No(h,d.target.key)?h:q(d,_.NODE_NOT_FOUND,`Target key not found: ${d.target.key}`)):q(d,_.ROUTE_NOT_FOUND,`Route not found: ${d.routeId}`)}return{get status(){return t},dispose(){t="disposed",a.clear(),o.clear(),i.clear(),f.clear(),s=null},registerRoute(d,h){let x=o.get(d);if(x?.entryFile===h)return;x&&v(x);let I=kd(d,h);o.set(d,I),ue(I,I.dependencyFiles),r.emit({type:"graph-invalidated",routeId:d})},unregisterRoute(d){let h=o.get(d);h&&(v(h),o.delete(d),s===d&&(s=null,t="idle"),r.emit({type:"graph-invalidated",routeId:d}))},getRouteEntryFiles(){return[...o.values()].map(d=>d.entryFile)},async setActiveRoute(d){let h=o.get(d);if(!h)throw new Error(`Route not found: ${d}`);let x=s===d;if(s=d,!h.graph){t="building";try{let I=await n.readFile(h.entryFile);await fe(d,I);let C=o.get(d)?.graph?.version??1;t="ready",r.emit({type:"graph-ready",routeId:d,version:C})}catch(I){throw t="idle",r.emit({type:"graph-error",routeId:d,message:Te(I)}),I}return}t="ready",x||r.emit({type:"graph-ready",routeId:d,version:h.graph.version})},getDocument(d){let h=o.get(d);if(!h)throw new Error(`Route not found: ${d}`);if(!h.document)throw new Error(`Route not built: ${d}`);return h.document},async getHistoryStatus(){await k;let d=await l.getStatus?.();return d?{...d,recoveryRequired:S}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:S}},getRenderDetail(d,h){let x=or(d,h),I=He(d)??d;if(x?.graph&&x.topology&&x.capabilities&&x.detailProjections){let C=x.detailProjections.get(I);if(C){let M=Jc(I,x.graph,x.topology,x.capabilities,C.textSources,C.writeTarget,C.provenances,C.conditional,C.componentSemantic,C.contentModel,C.mediaModel,C.styleSource);return d===I?M:QE(M,d,x.document??null,x.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${d}`)},getClassNameSource(d,h){let x=or(d,h),I=He(d)??d;if(!x?.graph)throw new Error(`Key not found: ${d}`);let C=x.graph.elements.get(I);if(!C)throw new Error(`Key not found: ${d}`);let M=f.get(C.sourceFile);if(M===void 0)throw new Error(`Source not loaded: ${C.sourceFile}`);return xl({key:I,route:{routeId:x.routeId,graph:x.graph,source:M}})},refreshSourceForKey:uf,async execute(d){if(await k,S)return q(d,_.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");let h=await Ut(d.mutationContext);if(!h.ok)return Co(d,h);if(d.kind==="source-edit")return await Sa(d),df(d);let x=await Aa(d);if("ok"in x)return x;await Sa(d);let I=await Aa(d);if("ok"in I)return I;let C=I;if(d.target.kind==="page-unit"){let T=d;return d.kind==="insert-child"?ff(T,C):d.kind==="move-node"||d.kind==="remove-node"?pf(T,C):q(d,_.UNSUPPORTED_OPERATION,"Only page-unit insert-child, move-node, and remove-node are currently supported by the page composition transaction.")}if(!C.graph||!C.topology||!C.capabilities)return{requestId:d.id,kind:d.kind,target:d.target,ok:!1,resultVersion:p,error:{code:d.target.kind==="route"?_.ROUTE_NOT_FOUND:_.NODE_NOT_FOUND,message:d.target.kind==="route"?`Route not ready: ${d.target.routeId}`:d.target.kind==="node"?`Target key not found: ${d.target.key}`:`${d.kind} source target execution is not implemented yet.`}};let M=jE(C,C.graph,C.capabilities,f,o),L=await new Qr(M).plan(d);if(!L.ok)return{requestId:d.id,kind:d.kind,target:d.target,ok:!1,resultVersion:p,error:{code:Wn(L.errorCode),message:L.reason}};let F=L.plan;if(F.steps.length===0)return d.kind==="set-props"?{requestId:d.id,kind:d.kind,target:d.target,ok:!0,resultVersion:p,affectedFiles:[]}:{requestId:d.id,kind:d.kind,target:d.target,ok:!1,resultVersion:p,error:{code:_.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};m+=1;try{if(F.steps.some(O=>O.type==="invoke-external-adapter")){let O=await Ut(d.mutationContext);if(!O.ok)return Co(d,O);let z=await u.execute(F);if(!z.ok)return q(d,Wn(z.errorCode),z.reason);let W={requestId:d.id,kind:d.kind,target:d.target,ok:!0,resultVersion:Math.max(p,z.resultVersion),affectedFiles:z.affectedFiles,...z.selectionRef?{selectionRef:z.selectionRef}:{}};return Ro(W,{rebuiltRoutes:[],failedRoutes:[]}),W}let T=await u.prepareRewritePlan(F);return T.ok?await nr({request:d,filePlan:T.filePlan,...T.selectionRef?{selectionRef:T.selectionRef}:{}}):q(d,Wn(T.errorCode),T.reason)}catch(T){return{requestId:d.id,kind:d.kind,target:d.target,ok:!1,resultVersion:p,error:{code:_.INTERNAL_ERROR,message:Te(T)}}}finally{m-=1}},async undo(d){if(await k,S)return{requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:p,error:{code:_.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};let h=await Ut(d);if(!h.ok)return vo("undo",h);m+=1;try{return await Ra("undo",d)}finally{m-=1}},async redo(d){if(await k,S)return{requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:p,error:{code:_.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};let h=await Ut(d);if(!h.ok)return vo("redo",h);m+=1;try{return await Ra("redo",d)}finally{m-=1}},notifyFileChanged(d){ya([d])},subscribe(d){return r.subscribe(d)}}}function DE(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&&Vs(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&&Vs(s.sourceRange,n.container.sourceRange)&&o){i.pageCompositionUnitKey=o.placementUnitKey;continue}let c=n.placements.find(l=>l.members.some(u=>u.sourceRange!==null&&(Vs(s.sourceRange,u.sourceRange)||BE(u.sourceRange,s.sourceRange))));if(c){i.pageCompositionUnitKey=c.placementUnitKey;continue}}let a=r.get(`${s.sourceFile}#${s.componentName}`);a&&(i.pageCompositionUnitKey=a)}}function Vs(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function BE(e,t){return vd(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&vd(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function vd(e,t,n,r){return e!==n?e-n:t-r}function jE(e,t,n,r,o){let i=new Map,s=new Map,a=(u,f)=>{if(s.has(u))return;s.set(u,f);let p=t.elements.get(u);for(let m of p?.childKeys??[])a(m,f)};for(let u of t.regions)if(u.kind==="repeat-region")for(let f of u.childKeys)i.set(f,u.ownerKey),a(f,u.ownerKey);return{getNode(u){let f=c(u),p=t.elements.get(f.baseKey);return p?l(u,p):null},getChildNodes(u){let f=c(u),m=e.documentIndex?.entriesByKey.get(u)?.childKeys;if(m)return m.map(b=>{let k=He(b)??b,R=t.elements.get(k);return R?l(b,R):null}).filter(b=>b!==null);let S=t.elements.get(f.baseKey);return S?S.childKeys.map(b=>{let k=t.elements.get(b);return k?l(b,k):null}).filter(b=>b!==null):[]},getKnownSourceFiles(){return[...r.entries()].map(([u,f])=>({file:u,content:f}))},getRouteEntryFiles(){return[...o.values()].map(u=>u.entryFile)},getCapability(u){let f=c(u),p=n.get(f.baseKey);return p?{...p,key:u,constraints:p.constraints.map(m=>({...m})),...p.editModes?{editModes:{...p.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 f=c(u);return e.detailProjections?.get(f.baseKey)?.componentSemantic??null},getEditableTextSegmentIndex(u){let f=c(u),m=e.detailProjections?.get(f.baseKey)?.textTargets.keys()?.next();return m&&!m.done?m.value:null},async getTextWriteTarget(u,f){let p=c(u);return Ad(e.detailProjections?.get(p.baseKey)?.textTargets.get(f)??null,p.repeatIndex)},async getElementPropertyWriteTarget(u,f){let p=c(u);return Ad(e.detailProjections?.get(p.baseKey)?.elementPropertyTargets.get(f)??null,p.repeatIndex)},getTextProvenance(u,f){let p=c(u);return e.detailProjections?.get(p.baseKey)?.provenances.get(f)??null}};function c(u){let f=gE(u);return f?{baseKey:f.baseKey,repeatIndex:YE(e.document??null,u,f.baseKey,e.documentIndex)??HE(f)}:{baseKey:u,repeatIndex:null}}function l(u,f){let p=He(u)??u,m=e.documentIndex?.entriesByKey.get(u),S=e.detailProjections?.get(p);return{key:u,file:f.sourceFile,component:f.componentName,tag:f.tag,structuralPath:f.identity.structuralPath,sourceRange:f.sourceRange,parentKey:m?.parentKey??f.parentKey??void 0,isRepeatRegion:f.boundaryKind==="repeat-region"||s.has(p),isBoundary:!1,importedFrom:f.importedFrom,exportName:f.exportName,isRepeatItemRoot:i.has(p),repeatOwnerKey:i.get(p)??s.get(p),contentModel:S?.contentModel,attributes:f.attributes?.map(b=>({name:b.name,value:b.value,source:b.source?{expression:b.source.expression,base:b.source.base,path:b.source.path.map(k=>({...k}))}:null,resolvedValue:b.resolvedValue}))}}}var $E={"stale-version":_.VERSION_STALE,"capability-denied":_.CAPABILITY_REJECTED,"invalid-params":_.INVALID_PARAMS,"locator-miss":_.LOCATOR_FAILED,"route-not-found":_.ROUTE_NOT_FOUND,"unsupported-operation":_.UNSUPPORTED_OPERATION,"invalid-target":_.INVALID_TARGET,"ast-error":_.AST_PARSE_ERROR,"writeback-failed":_.WRITE_IO_ERROR,"rollback-failed":_.RECOVERY_REQUIRED,unknown:_.INTERNAL_ERROR};function Wn(e){return $E[e]}function Te(e){return e instanceof Error&&e.message?e.message:String(e)}function wd(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function VE(e){let t=Vt(e);if(!EE.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=>SE.map(a=>`${s}/${a}`))}function UE(e){let n=Vt(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function KE(e){return Td(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function JE(e){return Td(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function Td(e,t){let n=[];for(let r of e.matchAll(t)){let o=Nd(r[1]??"");o&&n.push(o)}return n}function Pd(e,t){let n=Nd(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?Vt(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?Vt(`${XE(e)}/${n}`):n.startsWith("/")?Vt(n.slice(1)):Us(n)?Vt(n):null}function Nd(e){return e.split(/[?#]/,1)[0]?.trim()??""}function Us(e){return/\.css$/i.test(e)}function XE(e){let t=Vt(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function Fd(e){return Array.from(new Set(e))}function Vt(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 zE(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 so(e){return e?.map(t=>({...t}))}function Ad(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=so(e.collectionPathMap?.[t])??so(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:so(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>so(o)??[])}}function WE(e,t,n){let r=new Set;for(let m of t.regions)if(m.kind==="repeat-region")for(let S of m.childKeys)r.add(S);if(r.size===0)return e;let o=new Map(e.entries.map(m=>[m.key,m])),i=[],s=new Map,a=(m,S)=>pE(m,S),c=(m,S,b)=>{let k=o.get(m);if(!k)return a(m,b);let R=a(m,b),w={...k,key:R,parentKey:S,childKeys:[]};return i.push(w),w.childKeys=k.childKeys.flatMap(A=>l(A,b,R)),R},l=(m,S,b)=>{if(!r.has(m))return[c(m,b,S)];let k=f(m,S),R=[];for(let w=0;w<k;w+=1)R.push(c(m,b,[...S,w]));return R},u=Fd([...e.rootKeys,...e.entries.filter(m=>m.parentKey===null).map(m=>m.key)]);for(let m of u){if(!r.has(m)){c(m,null,[]);continue}let S=f(m,[]);for(let b=0;b<S;b+=1)c(m,null,[b])}return{...e,rootKeys:[...e.rootKeys],entries:i};function f(m,S){let b=new Set;for(let k of p(m)){let R=n.get(k);if(R){for(let w of[...R.textTargets.values(),...R.elementPropertyTargets.values()])if(!(w?.kind!=="value-binding"||w.sourceKind!=="repeat-template"))for(let A of GE(w))A.length<=S.length||ZE(A,S)&&b.add(A[S.length])}}return b.size>0?b.size:zE(n.get(m))}function p(m){let S=s.get(m);if(S)return S;let b=[m],k=o.get(m);for(let R of k?.childKeys??[])b.push(...p(R));return s.set(m,b),b}}function HE(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function YE(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((He(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function GE(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 ZE(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 QE(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}}import Ws from"node:path";import{TextDecoder as qE}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as _d,SITE_EDIT_SOURCE_ALLOWED_DIRS as Od,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as Ld,SiteEditSourceFileResponseSchema as Ks,SiteEditSourceLocationSchema as eS,SiteEditSourcePathSchema as co,SiteEditSourceTreeResponseSchema as tS,isSiteEditTextSourcePath as nS}from"@vcp-dev/contracts";var rS=[...Ld,..._d,...Od],Js=2e3,Xs=12,zs=24*1024*1024,Md=512*1024,oS=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),iS={".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"},sS={".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"},aS=new qE("utf-8",{fatal:!0});async function lo(e,t={}){let{files:n,truncated:r}=await hS(e,t),o=xS(n.map(i=>i.metadata));return tS.parse({nodes:o,defaultPath:ES(n.map(i=>i.metadata)),totalFiles:n.length,...r?{truncated:r}:{}})}async function uo(e,t,n={}){let r=co.parse(t.path),o=await uS(e,r,n);if(!o)throw new Error(`Source file not found: ${r}`);if(Hs(r)){let s=jd(r),a=await fS(e,{path:r,sizeBytes:o.sizeBytes,mimeType:s});return Ks.parse({path:r,kind:"binary",language:null,sizeBytes:o.sizeBytes,mimeType:s,readonly:!0,...a})}let i=await cS(e,r);return i.ok?Ks.parse({path:r,kind:"text",language:$d(r),sizeBytes:i.sizeBytes,contentHash:ae(i.content),readonly:!1,content:i.content}):Ks.parse({path:r,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function cS(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=lS(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 lS(e){if(e.includes(0))return null;try{return aS.decode(e)}catch{return null}}async function uS(e,t,n){if(!pS(t,n))return null;let r=await dS(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function dS(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=Dd(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(Hs(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function fS(e,t){if(!oS.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>Md)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>Md?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function pS(e,t){return Ld.some(n=>n===e)||_d.some(n=>n===e)||Od.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=co.safeParse(n);return r.success&&r.data===e})}function fo(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return eS.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 Dd(e){return Array.isArray(e)?{files:e}:e}function mS(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function hS(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=Dd(await e.listFiles({roots:gS(t),maxFiles:Js+1,maxDepth:Xs,maxTotalBytes:zs+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=co.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>Xs){o.add("max-depth");continue}if(r.size>=Js){o.add("max-files");break}if(i+a.sizeBytes>zs){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:yS(l,a.sizeBytes)}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:mS([...o]),maxFiles:Js,maxDepth:Xs,maxTotalBytes:zs}}:{}}}function gS(e){let t=new Set(rS);for(let n of e.routeEntryFiles??[]){let r=co.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function yS(e,t){return Hs(e)?{path:e,kind:"binary",language:null,sizeBytes:t,mimeType:jd(e),readonly:!0}:{path:e,kind:"text",language:$d(e),sizeBytes:t,readonly:!1}}function xS(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 Bd(t)}function Bd(e){return e.map(t=>t.kind==="directory"?{...t,children:Bd(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function ES(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 Hs(e){return!nS(e)}function jd(e){let t=Ws.posix.extname(e).toLowerCase();return!t&&Ws.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":iS[t]??"application/octet-stream"}function $d(e){let t=Ws.posix.extname(e).toLowerCase();return sS[t]??"plaintext"}var po=class{constructor(t){this.options=t,this.fileSystem=new Tn(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 lr(this.engine.getDocument(t),{siteId:this.options.siteId,snapshotId:this.options.snapshotId})}getInternalDocument(t){return this.engine.getDocument(t)}getStyleContext(t){return this.engine.getDocument(t).styleContext??null}getObjectEditContext(t,n){return ur(this.engine.getRenderDetail(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(){return lo(this.fileSystem,{routeEntryFiles:this.options.routes.map(t=>t.entryFile)})}getSourceFile(t){return uo(this.fileSystem,t,{routeEntryFiles:this.options.routes.map(n=>n.entryFile)})}resolveSourceLocation(t){return fo(t,this.engine.getRenderDetail(t.key,t.routeId))}async planOperation(t){let n=bS.safeParse(t);if(!n.success)return{result:cr(t,n.error.issues.map(i=>i.message))};let r=new Tn(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:wt(s)},c=r.getChangedFiles();if(c.length===0)return{result:a};let l=IS.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:c.map(u=>kS(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 Hn({projectRoot:"/snapshot",fileSystem:t,routes:this.options.routes.map(o=>({routeId:o.routeId,entryFile:o.entryFile})),onEvent:r&&this.options.onEvent?o=>{let i=dr(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.mutationContextVerifier?{mutationContextVerifier:this.options.mutationContextVerifier}:{},...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 kS(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:ae(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:ae(e.before)},fullContent:e.after}}function RS(e){return new po(e)}import{SiteEditOperationRequestSchema as wS}from"@vcp-dev/contracts";import Ye from"node:fs/promises";import ke from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as CS,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as vS}from"@vcp-dev/contracts";var mo=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=Hn({...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()}getRenderDetail(t,n){return this.engine.getRenderDetail(t,n)}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(){return lo(this.fileSystem,{routeEntryFiles:this.engine.getRouteEntryFiles()})}getSourceFile(t){return uo(this.fileSystem,t,{routeEntryFiles:this.engine.getRouteEntryFiles()})}resolveSourceLocation(t){return fo(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 Ye.readFile(ke.join(n,r),"utf8")},async readFileBytes(r){return Ye.readFile(ke.join(n,r))},async getFileInfo(r){let o=ke.join(n,...r.split("/"));try{let i=await Ye.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await to(ke.join(n,r),o)},async createExclusive(r,o){let i=ke.join(n,r);await Ye.mkdir(ke.dirname(i),{recursive:!0});let s=await Ye.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await Ye.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await Ye.rm(ke.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=ke.join(n,i),a=ke.dirname(ke.join(n,o));for(;a!==s&&a.startsWith(`${s}${ke.sep}`);){try{await Ye.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=ke.dirname(a);continue}break}a=ke.dirname(a)}},async exists(r){try{return await Ye.access(ke.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...vS,...CS],i=[],s=new Set,a=0;for(let u of o)await l(u,i,1);let c=i.sort((u,f)=>u.path.localeCompare(f.path));return s.size>0?{files:c,truncated:{reasons:[...s]}}:{files:c};async function l(u,f,p){if(r.maxFiles!==void 0&&f.length>=r.maxFiles){s.add("max-files");return}if(r.maxDepth!==void 0&&p>r.maxDepth){s.add("max-depth");return}let m=ke.join(n,...u.split("/")),S;try{S=await Ye.lstat(m)}catch{return}if(S.isSymbolicLink())return;if(S.isFile()){if(r.maxTotalBytes!==void 0&&a+S.size>r.maxTotalBytes){s.add("max-total-bytes");return}f.push({path:u,sizeBytes:S.size}),a+=S.size;return}if(!S.isDirectory())return;let b=await Ye.readdir(m,{withFileTypes:!0});for(let k of b)k.isSymbolicLink()||await l(`${u}/${k.name}`,f,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 Ys(e){return new mo(e)}var ho=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=Ys({projectRoot:t.projectRoot,fileSystem:t.fileSystem,routes:t.routes.map(n=>({routeId:n.routeId,entryFile:n.entryFile})),onEvent:n=>{let r=dr(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.mutationContextVerifier?{mutationContextVerifier:t.mutationContextVerifier}:{},...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:lr(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:ur(this.engine.getRenderDetail(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=wS.safeParse(r);if(!o.success)return cr(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:wt(i)}}async undo(t){let n=await this.engine.undo(t);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:wt(n)}}async redo(t){let n=await this.engine.redo(t);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:wt(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 PS(e){return new ho(e)}import{createPublicKey as AS,timingSafeEqual as TS,verify as NS}from"node:crypto";var FS={ok:!0},gn={ok:!1,code:"LEASE_ASSERTION_INVALID",message:"Lease assertion is invalid."},MS={ok:!1,code:"LEASE_ASSERTION_EXPIRED",message:"Lease assertion has expired."},Vd={ok:!1,code:"LEASE_ASSERTION_SCOPE_MISMATCH",message:"Lease assertion does not match the active edit scope."};function _S(e){let t=typeof e.publicKey=="string"?AS(e.publicKey):e.publicKey,n=e.now??(()=>Math.floor(Date.now()/1e3)),r=e.clockSkewSeconds??5;return{async verify(o,i){return OS(o.leaseAssertion,t,{...e,now:n,clockSkewSeconds:r,expected:i})}}}function OS(e,t,n){let r=e.split(".");if(r.length!==3||r.some(b=>b.length===0))return gn;let[o,i,s]=r,a=Ud(o),c=Ud(i);if(!a||!c||a.alg!=="EdDSA"||a.kid!==n.keyId)return gn;let l=Buffer.from(`${o}.${i}`,"ascii"),u=LS(s);if(!u||u.length!==64||!NS(null,l,t,u))return gn;let f=n.now();if(typeof c.exp!="number")return gn;if(c.exp<=f-n.clockSkewSeconds)return MS;if(c.nbf!==void 0&&(typeof c.nbf!="number"||c.nbf>f+n.clockSkewSeconds)||c.iat!==void 0&&(typeof c.iat!="number"||c.iat>f+n.clockSkewSeconds))return gn;let p=n.issuer??"vcp-api",m=n.audience??"site-edit-engine";if(c.iss!==p||!DS(c.aud,m))return Vd;let S={tenantId:c.tenant_id,siteId:c.site_id,snapshotId:c.snapshot_id,editingSessionId:c.editing_session_id,lockId:c.lock_id,ownerId:c.owner_id};if(Object.values(S).some(b=>typeof b!="string"))return gn;for(let[b,k]of Object.entries(n.expected))if(!BS(S[b],k))return Vd;return FS}function Ud(e){try{let t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return typeof t=="object"&&t!==null?t:null}catch{return null}}function LS(e){try{return Buffer.from(e,"base64url")}catch{return null}}function DS(e,t){return e===t||Array.isArray(e)&&e.includes(t)}function BS(e,t){let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&TS(n,r)}import{createHash as jS,randomUUID as aa}from"node:crypto";import me from"node:fs/promises";import Ee from"node:path";var Be=1,Zs=1,$S=2,VS="index.json",US="recovery.json",KS="transaction-journal.json",JS="document-version.json",yo={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"},K=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 Zd(e,t={}){let n=nb(e),r=ib(t.limits),o=Gs(n),i=rb(n),s=await De(i),a=await De(o)||s;a||(await GS(n),await Yd(n)),a||await sb(n);let c=await Ne(n);a||await Yn(n,c.entryIds);let l=async()=>{if(await De(o)||s)throw new K(U.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")};return{rootDir:n,recoveryRequired:a,async readDocumentVersion(){return Gd(n)},async writeDocumentVersion(u){if(await l(),!Number.isInteger(u)||u<0)throw new K(U.INVALID_SCHEMA,"document version must be a non-negative integer");let f=await Gd(n);await Gn(sf(n),{schemaVersion:1,version:Math.max(f,u)})},async stageAppend(u,f={}){await l();let p=await Jd(u,r),m={schemaVersion:Zs,stageId:aa(),entryId:p.entryId,blobIds:p.blobs.map(S=>S.digest)};try{await Xd(n,p),await WS(n,m,f.durableManifest!==!1)}catch(S){try{await Wd(n,m)}catch(b){throw new K(U.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:b})}throw S}return{stageId:m.stageId,entryId:m.entryId,blobIds:m.blobIds}},async discardStage(u){await l(),ta(u);let f=await qs(n,u);f&&await Wd(n,f)},async previewStagedAppend(u,f){return await l(),(await Kd(n,r,u,f)).transition},async previewCursor(u,f){await l();let p=await Ne(n);return na(p,f),Qs(u,p.entryIds.length),Qd(p,p.entryIds,u)},async publishStagedAppend(u,f,p){if(await l(),xo(u,"entryId"),p){ta(p);let S=await qs(n,p);if(!S||S.entryId!==u)throw new K(U.INVALID_SCHEMA,"history stage does not match the published entry")}let m=await Kd(n,r,u,f);return Hd({rootDir:n,previousDigest:m.current.digest,entryIds:m.entryIds,cursor:m.cursor,afterWrite:async()=>{p?await la(n,p):await YS(n,u),await Yn(n,m.entryIds)}})},async append(u){await l();let f=await Ne(n),p=await Jd(u,r),m=[...f.entryIds];f.cursor<m.length-1&&m.splice(f.cursor+1),m.push(p.entryId);try{await Xd(n,p);let S=await qd(n,m,r);return await da(n,S.entryIds,S.cursor),await Yn(n,S.entryIds),Ne(n)}catch(S){throw await Yn(n,f.entryIds),S}},async readEntry(u){return xo(u,"entryId"),Zn(n,u)},async readBlob(u){xo(u,"blobId");let f=yn(n,u),p=await Ct(f,U.NOT_FOUND,"blob");return fa(p,u,f),p},async readIndex(){return Ne(n)},async readStatus(){let u=await Ne(n);return{canUndo:u.undoIds.length>0,canRedo:u.redoIds.length>0,undoDepth:u.undoIds.length,redoDepth:u.redoIds.length,cursor:u.cursor,recoveryRequired:await De(o)||await De(i)}},async readUndoRedoIds(){let u=await Ne(n);return{undoIds:u.undoIds,redoIds:u.redoIds,currentId:u.currentId}},async setCursor(u,f){await l();let p=await Ne(n);return na(p,f),Qs(u,p.entryIds.length),Hd({rootDir:n,previousDigest:p.digest,entryIds:p.entryIds,cursor:u})},async markRecoveryRequired(u){await De(o)||await Gn(Gs(n),{schemaVersion:Be,reason:ob(u),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await me.rm(Gs(n),{force:!0})},async readTransactionJournal(){return await De(i)?go(i):null},async writeTransactionJournal(u){await l(),af(u);try{await Gn(i,u)}catch(p){let m=await go(i).catch(()=>null);if(m&&Buffer.from(Fe(m)).equals(Buffer.from(Fe(u))))return;throw m?new K(U.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:p}):p}let f=await go(i);if(!Buffer.from(Fe(f)).equals(Buffer.from(Fe(u))))throw new K(U.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(u){let f=await De(i)?await go(i):null;if(f&&f.transactionId!==u)throw new K(U.INVALID_SCHEMA,"transaction journal changed concurrently");try{await me.rm(i,{force:!0})}catch(p){if(!await De(i))return;throw p}if(await De(i))throw new K(U.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await l(),await Yd(n);let u=await Ne(n);await Yn(n,u.entryIds)}}}async function Kd(e,t,n,r){xo(n,"entryId");let o=await Ne(e);na(o,r);let i=await Zn(e,n),s=[...o.entryIds];o.cursor<s.length-1&&s.splice(o.cursor+1),s.push(i.id);let a=await qd(e,s,t);return{current:o,entryIds:a.entryIds,cursor:a.cursor,transition:Qd(o,a.entryIds,a.cursor)}}function Qd(e,t,n){return Qs(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:XS(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function XS(e,t){return vt(Fe({schemaVersion:Be,entryIds:e,cursor:t}))}function Qs(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new K(U.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function zS(e){if(!Ge(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!we(e.expectedIndexDigest)||!we(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!we(n)?!1:t===-1?n===null:we(n)}async function Jd(e,t){if(!e.kind.trim())throw new K(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 K(U.INVALID_JSON,"history blob name must not be empty");let l=tb(c.data),u=vt(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:Be,kind:e.kind,manifest:e.manifest,blobs:r},i=Fe({...o}),s=vt(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new K(U.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function Xd(e,t){let n=qn(e,t.entryId),r={id:t.entryId,...t.entryBody},o=[...t.blobs.map(a=>zd(yn(e,a.digest),a.bytes,{kind:"blob",digest:a.digest})),zd(n,Fe(r),{kind:"entry",digest:t.entryId})],s=(await Promise.allSettled(o)).find(a=>a.status==="rejected");if(s)throw s.reason}async function zd(e,t,n){let r=await of(e);if(r!==null){if(Buffer.compare(r,t)!==0)throw new K(n.kind==="blob"?U.BLOB_CORRUPT:U.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await nf(e,t)}async function qd(e,t,n){let r=[...t],o=r.length-1;for(;;){if((await tf(e,r)).totalBytes<=n.maxSessionBytes&&r.length<=n.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new K(U.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");r.shift(),o-=1}}async function WS(e,t,n){ua(t);let r=ma(e,t.stageId);if(n){await Gn(r,t);return}await eb(r,t)}async function qs(e,t){let n=await of(ma(e,t));if(n===null)return null;let r=Qn(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=ua(r);if(o.stageId!==t)throw new K(U.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function ca(e){let t=[];for(let n of await sa(pa(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);ta(r);let o=await qs(e,r);o&&t.push(o)}return t}async function Wd(e,t){ua(t);let n=await Ne(e),r=(await ca(e)).filter(s=>s.stageId!==t.stageId),o=new Set(n.entryIds),i=new Set;for(let s of n.entryIds){let a=await Zn(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 ea(qn(e,t.entryId));for(let s of t.blobIds)i.has(s)||await ea(yn(e,s));await la(e,t.stageId),await ia(Io(e)),await ia(ko(e))}async function la(e,t){await ea(ma(e,t)),await HS(e)}async function HS(e){try{await me.rmdir(pa(e))}catch(t){if(er(t)||Ge(t)&&t.code==="ENOTEMPTY")return;throw t}}async function YS(e,t){for(let n of await ca(e))n.entryId===t&&await la(e,n.stageId)}async function ea(e){if(await me.rm(e,{force:!0}),await De(e))throw new K(U.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}function ua(e){if(!Ge(e)||e.schemaVersion!==Zs||typeof e.stageId!="string"||!ef(e.stageId)||!we(e.entryId))throw new K(U.INVALID_SCHEMA,"history stage schema is invalid");let t=rf(e.blobIds,"history stage blobIds");return{schemaVersion:Zs,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function ta(e){if(!ef(e))throw new K(U.INVALID_PATH,"history stageId must be a UUID")}function ef(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 Yn(e,t){let n=new Set(t),r=new Set;for(let c of t){let l=await Zn(e,c);for(let u of l.blobs)r.add(u.digest)}for(let c of await ca(e)){n.add(c.entryId);for(let l of c.blobIds)r.add(l)}let o=Io(e),i=await sa(o);for(let c of i){if(!c.endsWith(".json"))continue;let l=c.slice(0,-5);we(l)&&!n.has(l)&&await Eo(qn(e,l))}let s=ko(e),a=await sa(s);for(let c of a){let l=c;we(l)&&!r.has(l)&&await Eo(yn(e,l))}}async function Ne(e){let t=bo(e),n=await Ct(t,U.NOT_FOUND,"index"),r=Qn(Buffer.from(n).toString("utf8"),"index"),o=ZS(r),i=[...o.entryIds],{totalBytes:s}=await tf(e,i),a=i.slice(0,o.cursor+1).reverse(),c=i.slice(o.cursor+1);return{schemaVersion:Be,digest:o.digest,entryIds:i,cursor:o.cursor,currentId:i[o.cursor]??null,undoIds:a,redoIds:c,totalBytes:s}}async function tf(e,t){let n=0,r=new Set,o=bo(e),i=await Ct(o,U.NOT_FOUND,"index");n+=i.byteLength;for(let s of t){let a=await Zn(e,s),c=qn(e,s),l=await Ct(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 f=yn(e,u.digest),p=await Ct(f,U.NOT_FOUND,"blob");fa(p,u.digest,f),n+=p.byteLength}}return{totalBytes:n}}async function Zn(e,t){let n=qn(e,t),r=await Ct(n,U.NOT_FOUND,"entry"),o=Qn(Buffer.from(r).toString("utf8"),`entry ${t}`),i=QS(o);if(i.id!==t)throw new K(U.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(vt(Fe({schemaVersion:i.schemaVersion,kind:i.kind,manifest:i.manifest,blobs:i.blobs}))!==t)throw new K(U.ENTRY_CORRUPT,`entry hash mismatch for ${t}`);for(let a of i.blobs){let c=yn(e,a.digest),l=await Ct(c,U.NOT_FOUND,"blob");fa(l,a.digest,c)}return i}async function da(e,t,n){let r={schemaVersion:Be,digest:vt(Fe({schemaVersion:Be,entryIds:t,cursor:n})),entryIds:t,cursor:n};await Gn(bo(e),r)}function na(e,t){if(t!==void 0&&e.digest!==t)throw new K(U.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function Hd(e){let t=vt(Fe({schemaVersion:Be,entryIds:e.entryIds,cursor:e.cursor}));try{return await da(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.(),await Ne(e.rootDir)}catch(n){let r=await Ne(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new K(U.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function GS(e){await me.mkdir(e,{recursive:!0}),await me.mkdir(Io(e),{recursive:!0}),await me.mkdir(ko(e),{recursive:!0}),await me.mkdir(So(e),{recursive:!0})}async function Yd(e){await me.rm(So(e),{recursive:!0,force:!0}),await me.mkdir(So(e),{recursive:!0})}function ZS(e){if(!Ge(e))throw new K(U.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==Be)throw new K(U.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=rf(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new K(U.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!we(o))throw new K(U.INDEX_CORRUPT,"index digest is invalid");let i=vt(Fe({schemaVersion:Be,entryIds:t,cursor:r}));if(o!==i)throw new K(U.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:Be,digest:o,entryIds:t,cursor:r}}function QS(e){if(!Ge(e))throw new K(U.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==Be)throw new K(U.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!we(t))throw new K(U.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new K(U.ENTRY_CORRUPT,"entry kind is invalid");let r=oa(e.manifest,"entry.manifest"),o=qS(e.blobs);return{id:t,schemaVersion:Be,kind:n,manifest:r,blobs:o}}function qS(e){if(!Array.isArray(e))throw new K(U.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!Ge(t))throw new K(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 K(U.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!we(o))throw new K(U.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new K(U.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function Gn(e,t){await nf(e,Fe(t))}async function eb(e,t){let n=Ee.dirname(e),r=Ee.basename(e),o=Ee.join(n,`.${r}.${process.pid}.${aa()}.tmp`);await me.mkdir(n,{recursive:!0});try{await me.writeFile(o,Fe(t),{flag:"wx"}),await me.rename(o,e)}finally{await Eo(o)}}async function nf(e,t){let n=Ee.dirname(e),r=Ee.basename(e),o=Ee.join(n,`.${r}.${process.pid}.${aa()}.tmp`);await me.mkdir(n,{recursive:!0});try{let i=await me.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await me.rename(o,e),await ia(n)}finally{await Eo(o)}}function Fe(e){return Buffer.from(JSON.stringify(ra(e)),"utf8")}function ra(e){if(Array.isArray(e))return e.map(t=>ra(t));if(Ge(e)){let t={};for(let n of Object.keys(e).sort())t[n]=ra(e[n]);return t}return e}function Qn(e,t){try{return JSON.parse(e)}catch(n){throw new K(U.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function oa(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=>oa(n,t));if(Ge(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=oa(o,t);return n}break}throw new K(U.INVALID_JSON,`${t} must be JSON-serializable`)}function rf(e,t){if(!Array.isArray(e))throw new K(U.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!we(n))throw new K(U.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function xo(e,t){if(!we(e))throw new K(U.INVALID_PATH,`${t} must be a sha256 digest`)}function we(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function vt(e){return`sha256:${jS("sha256").update(e).digest("hex")}`}function tb(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function Ct(e,t,n){try{return await me.readFile(e)}catch(r){throw new K(t,`${n} not found: ${e}`,{cause:r})}}async function of(e){try{return await me.readFile(e)}catch(t){if(er(t))return null;throw t}}function fa(e,t,n){if(vt(e)!==t)throw new K(U.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function De(e){try{return await me.access(e),!0}catch(t){if(er(t))return!1;throw t}}async function Eo(e){try{await me.rm(e,{force:!0,recursive:!0})}catch{}}async function ia(e){try{let t=await me.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function sa(e){try{return await me.readdir(e)}catch(t){if(er(t))return[];throw t}}function nb(e){if(typeof e!="string"||e.trim().length===0)throw new K(U.INVALID_ROOT,"history store rootDir must be a non-empty string");return Ee.resolve(e)}function bo(e){return Ee.join(e,VS)}function Gs(e){return Ee.join(e,US)}function rb(e){return Ee.join(e,KS)}function sf(e){return Ee.join(e,JS)}async function Gd(e){try{let t=await me.readFile(sf(e),"utf8"),n=Qn(t,"document version");if(!Ge(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new K(U.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(er(t))return 0;throw t}}async function go(e){let t=await Ct(e,U.RECOVERY_PENDING,"transaction journal"),n=Qn(Buffer.from(t).toString("utf8"),"transaction journal");return af(n),n}function af(e){if(!Ge(e)||e.schemaVersion!==$S||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!zS(e.historyTransition)||!Array.isArray(e.files))throw new K(U.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!Ge(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!we(t.preDigest)||t.postDigest!==null&&!we(t.postDigest))throw new K(U.INVALID_SCHEMA,"transaction journal file digest is invalid")}function ob(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function Io(e){return Ee.join(e,"entries")}function ko(e){return Ee.join(e,"blobs")}function So(e){return Ee.join(e,"tmp")}function pa(e){return Ee.join(So(e),"stages")}function ma(e,t){return Ee.join(pa(e),`${t}.json`)}function qn(e,t){return Ee.join(Io(e),`${t}.json`)}function yn(e,t){return Ee.join(ko(e),t)}function Ge(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 ib(e){return{maxEntries:e?.maxEntries??yo.maxEntries,maxSessionBytes:e?.maxSessionBytes??yo.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??yo.maxEntryBytes}}async function sb(e){let t=bo(e);await De(t)||await da(e,[],-1)}export{K as FileHistoryStoreError,ho as PreviewFileSystemSiteEditEngineRuntime,Zu as SITE_EDIT_RAW_COLOR_LITERAL_RE,po as SnapshotSiteEditEngineRuntime,_S as createEd25519MutationContextVerifier,PS as createPreviewSiteEditEngineRuntime,RS as createSiteEditEngineRuntime,Zd as openFileHistoryStore,Ts as scanSiteEditThemeStyleViolations};
|
|
9
|
+
`||p==="\r"))return pn(t,`Unterminated string literal in ${t}.`);l=p===`
|
|
10
|
+
`||p==="\r";continue}if(p==="/"&&m==="*"){s=!0,f+=1,l=!1;continue}if(n==="mdx"&&p==="/"&&m==="/"){a=!0,f+=1,l=!1;continue}if(p==="'"||p==='"'||n==="mdx"&&p==="`"){o=p,l=!1;continue}if(p==="{"||p==="("||p==="["){r.push({char:p,offset:f}),l=!1;continue}if(p==="}"||p===")"||p==="]"){let S=p==="}"?"{":p===")"?"(":"[",b=r.pop();if(!b||b.char!==S)return pn(t,`Unexpected closing token "${p}" in ${t}.`);l=!1;continue}l=p===`
|
|
11
|
+
`||p==="\r"}if(s)return pn(t,`Unterminated block comment in ${t}.`);if(o)return pn(t,`Unterminated string literal in ${t}.`);if(c)return pn(t,`Unterminated MDX code fence in ${t}.`);let u=r.at(-1);return u?pn(t,`Unclosed token "${u.char}" in ${t}.`):{ok:!0}}function pn(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function Xn(e){let t="idle",n=e.fileSystem??mE(),r=Xu(),o=new Map,i=new Map,s=null,a=new Set,c=null,l=e.history??(e.historyStore?ad(e.historyStore):hE()),u=Ju(n,{externalAdapters:e.externalAdapters}),f=new Map,p=Math.max(0,e.initialDocumentVersion??0),m=0,S=e.historyStore?.recoveryRequired??!1,b=Ns(),R=z();function k(d){return(no.isAbsolute(d)?no.relative(e.projectRoot,d):d).replace(/\\/g,"/").replace(/^\.\//,"")}function P(d,h){let y=no.posix.dirname(d),I=h.replace(/\.(?:tsx?|jsx?)$/i,""),v=no.posix.relative(y,I);return v.startsWith(".")?v:`./${v}`}function A(d,h){return d.startLine===h.startLine&&d.startColumn===h.startColumn&&d.endLine===h.endLine&&d.endColumn===h.endColumn}async function z(){let d=e.historyStore;if(d)try{let h=await d.readTransactionJournal();if(!h)return;let y=await d.readIndex(),I=await Promise.all(h.files.map(async F=>await n.exists(F.path)?ie(await n.readFile(F.path)):null));if(pd({journal:h,index:y,observedFileDigests:I})!=="ambiguous"){await d.clearTransactionJournal(h.transactionId);let F=await d.readStatus();F.recoveryRequired||(await d.cleanupTmp(),F=await d.readStatus()),S=F.recoveryRequired;return}await d.markRecoveryRequired(`Ambiguous transaction journal ${h.transactionId} at phase ${h.phase}`),S=!0}catch(h){S=!0,await d.markRecoveryRequired(`Transaction journal recovery failed: ${Te(h)}`).catch(()=>{})}}function oe(){return t==="disposed"}if(e.onEvent&&r.subscribe(e.onEvent),e.routes)for(let d of e.routes){let h=xd(d.routeId,d.entryFile);o.set(d.routeId,h),le(h,h.dependencyFiles)}function le(d,h){let y=new Set(h);C(d),d.dependencyFiles=y;for(let I of d.dependencyFiles){let v=i.get(I);v||(v=new Set,i.set(I,v)),v.add(d.routeId)}}function C(d){for(let h of d.dependencyFiles){let y=i.get(h);y&&(y.delete(d.routeId),y.size===0&&i.delete(h))}d.dependencyFiles.clear()}function M(d){let h=new Set;for(let y of d)for(let I of i.get(y)??[])h.add(I);return h}function O(d){for(let h of d)if(!i.has(h))return!1;return!0}async function D(d,h,y,I,v){let F=new Map,B=ku(v.values()),N=typeof n.exists=="function"?T=>n.exists(T):async()=>!1;for(let[T,L]of d.elements){let Q=h.nodes.get(T);if(!Q)continue;let X=y.get(L.sourceFile)??I.get(L.sourceFile),re=new Map,w=new Map,_=new Map,H=[];for(let ue of L.textSegments){if(!X){re.set(ue.index,null);continue}let gn=await Ru({file:L.sourceFile,source:X,segment:ue,readFile:je=>n.readFile(je),exists:N,graph:d,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:je,adapterId:wo,capabilities:Po})=>({sourceType:je,adapterId:wo,capabilities:Po})),functionCallContracts:e.functionCallContracts,fileCache:B}),Se=await ms({file:L.sourceFile,source:X,target:{kind:"text-segment",segment:ue},readFile:je=>n.readFile(je),exists:N,graph:d,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:je,adapterId:wo,capabilities:Po})=>({sourceType:je,adapterId:wo,capabilities:Po})),functionCallContracts:e.functionCallContracts,fileCache:B}),Kt=RE(gn);re.set(ue.index,Kt),w.set(ue.index,gn),_.set(ue.index,Se),H.push({editable:ue.editable,source:Kt})}let fe=new Map;if(X)for(let ue of L.attributes??[]){let gn=await Cu({file:L.sourceFile,source:X,sourceRange:ue.sourceRange,expression:ue.source?.expression??ue.value,sourceInfo:ue.source,readFile:Se=>n.readFile(Se),exists:N,graph:d,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Se,adapterId:Kt,capabilities:je})=>({sourceType:Se,adapterId:Kt,capabilities:je})),functionCallContracts:e.functionCallContracts,fileCache:B});fe.set(ue.name,gn)}let se=$c(CE(Q.writeTarget),H),he=Vc({key:T,element:L,graph:d,provenances:_}),ke=zc(L),rr=Wc(L),or=cl(L),nt=d.regions.find(ue=>ue.kind==="conditional-region"&&ue.childKeys.includes(T)),hn,Re=nt?.sourceCandidates?.[0];if(X&&nt&&Re?.kind==="conditional-branch"){let ue=await ms({file:L.sourceFile,source:X,target:{kind:"conditional-branch",candidate:Re},readFile:Se=>n.readFile(Se),exists:N,graph:d,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Se,adapterId:Kt,capabilities:je})=>({sourceType:Se,adapterId:Kt,capabilities:je})),functionCallContracts:e.functionCallContracts,fileCache:B});hn={currentBranch:nt.childKeys.indexOf(T)<=0?"then":"else",availableBranches:nt.childKeys.length>1?["then","else"]:["then"],conditionExpression:Re.conditionExpression,provenance:{finalSource:ue.finalSource?{kind:ue.finalSource.kind,file:ue.finalSource.file,displayPath:ue.finalSource.displayPath}:null,chain:ue.chain.map(Se=>({kind:Se.kind,file:Se.file,displayName:Se.displayName,canEditHere:Se.canEditHere})),confidence:ue.confidence,editMode:ue.editMode,diagnostics:ue.diagnostics.map(Se=>({code:Se.code,message:Se.message}))}}}F.set(T,{textSources:re,textTargets:w,elementPropertyTargets:fe,provenances:_,writeTarget:se,componentSemantic:he,contentModel:ke,mediaModel:rr,styleSource:or,conditional:hn})}return F}function Y(d){return typeof n.getVersion=="function"?n.getVersion(d):0}function G(d,h){let y=1;for(let I of h.values())y=Math.max(y,I);return Math.max(y,d.graph?.version??0)}async function de(d,h,y={}){let I=o.get(d);if(!I)return null;let v=y.sourceCache??Fs(f,[]),F=await W(I.entryFile),{graph:B,allSources:N,diagnostics:T,parsedModules:L,entryModule:Q}=await ja(I.entryFile,h,Re=>n.readFile(Re),typeof n.exists=="function"?Re=>n.exists(Re):async()=>!1,{additionalEntries:F,version:I.graph?.version??1});if(T.length>0)throw new Kn(T);let X=new Map;for(let Re of N.keys())X.set(Re,Y(Re));let re=Math.max(G(I,X),y.minimumVersion??0,p);y.changed&&re<=(I.graph?.version??0)&&(re=(I.graph?.version??0)+1),B.version=re;for(let[Re,ue]of N)_s(v,Re,ue,hd);let w=await Z(I.entryFile,N,v);B.routeId=d;let _=$a(B),H=Va(_,B),fe=await D(B,_,N,v,L),se=ut(B,H,fe),he=$E(Bc(B,_,H,{canUpdateTextByKey:se}),B,fe),ke=Tc({route:d,entryFile:I.entryFile,version:re,source:h,ast:Q?.ast}),rr=Nc(ke);ke.ok&&TE(he,B,ke.projection);let or={...he,...w?{styleContext:w}:{},pageComposition:rr},nt=new Set([I.entryFile,...N.keys()]);if(w){nt.add(w.entryCss.path);for(let Re of w.stylesheets)nt.add(Re.path)}let hn={...I,dependencyFiles:nt,graph:B,topology:_,capabilities:H,document:or,pageComposition:rr,pageCompositionProjection:ke.projection,pagePlacementByKey:ke.ok?ke.projection.placementByKey:null,pagePlacementUnitByKey:ke.ok?ke.projection.placementUnitByKey:null,pageUnitByKey:ke.ok?ke.projection.unitByKey:null,pagePlacementsByUnitKey:ke.ok?ke.projection.placementsByUnitKey:null,documentIndex:xE(or),detailProjections:fe,fileVersions:X,styleContext:w};return y.publish===!1?hn:(fn(f,v),p=Math.max(p,re),le(I,nt),Object.assign(I,hn),I)}async function W(d){let h=[];for(let y of _E(d))typeof n.exists=="function"&&await n.exists(y)&&h.push({file:y,source:await n.readFile(y)});return h}async function Z(d,h,y){let I=[];for(let[T,L]of h){if(Ds(T)){I.push(T);continue}for(let Q of LE(L)){let X=kd(T,Q);X&&I.push(X)}}if(!I.length){for(let T of OE(d))if(await tt(T)){I.push(T);break}}let v=new Map,F=wd(I).slice(0,md);for(;F.length>0&&v.size<md;){let T=F.shift();if(v.has(T)||!Ds(T))continue;let L=await pe(T,y);if(L!==null){v.set(T,{path:T,content:L});for(let Q of DE(L)){let X=kd(T,Q);X&&!v.has(X)&&!F.includes(X)&&F.push(X)}}}let B=[...v.values()].map(T=>({...T,hash:ie(T.content)})),N=B[0];return N?{revision:ie(JSON.stringify(B.map(({path:T,hash:L})=>({path:T,hash:L})))),entryCss:N,stylesheets:B.slice(1)}:null}async function pe(d,h){let y=h.get(d);if(y!==void 0)return y;if(!await tt(d))return null;let I=await n.readFile(d);return _s(h,d,I,hd),I}async function tt(d){return typeof n.exists=="function"?n.exists(d):!1}function ut(d,h,y){let I=new Map;for(let[v,F]of d.elements){if(!h.get(v)?.canUpdateText){I.set(v,!1);continue}let N=y.get(v),T=F.textSegments.some(L=>{if(!L.editable)return!1;let Q=N?.provenances.get(L.index)??null;return!Q||ef(Q)});I.set(v,T)}return I}function ef(d){return d.editMode==="direct"||d.editMode==="proxy"||d.editMode==="upstream"}async function Qn(d,h={}){let y=[...new Set(d)],I=M(y);if(I.size===0||!O(y))for(let N of o.values())da(N,y)&&I.add(N.routeId);let v=I.size===0&&y.some(Id),F=h.publish===!1?Fs(f,y):void 0,B={rebuiltRoutes:[],failedRoutes:[],...h.publish===!1?{candidateRouteStates:[],candidateSourceCache:F}:{}};for(let N of o.values())if(I.has(N.routeId)||v)try{let L=!!N.graph,Q=await n.readFile(N.entryFile),X=await de(N.routeId,Q,{...h,...F?{sourceCache:F}:{}});X?.graph&&(B.rebuiltRoutes.push({documentChanged:L,routeId:N.routeId,version:X.graph.version}),B.candidateRouteStates?.push({routeId:N.routeId,state:X}))}catch(L){B.failedRoutes.push(fd(N.routeId,L))}return B}function ua(d){let h=[...new Set(d)],y=M(h);if(y.size>0&&O(h))return[...y];for(let I of o.values())da(I,h)&&y.add(I.routeId);return[...y]}function bo(d,h){r.emit({type:"operation-completed",result:d});for(let{routeId:y,version:I}of h.rebuiltRoutes)r.emit({type:"document-changed",routeId:y,version:I});for(let{routeId:y,message:I}of h.failedRoutes)r.emit({type:"graph-error",routeId:y,message:I})}function da(d,h){return h.some(y=>d.dependencyFiles.has(y)||d.entryFile===y||d.graph?.fileIndex.has(y))}function fa(d){for(let h of d)a.add(h);c||oe()||(c=(async()=>{t="building";let h=!1;try{for(;a.size>0;){if(oe())return;await tf();let y=[...a];a.clear();let I=await pa(y);if(I.length===0)continue;let v=ua(I);for(let N of v)r.emit({type:"graph-invalidated",routeId:N});let{rebuiltRoutes:F,failedRoutes:B}=await Qn(I,{changed:!0});for(let{documentChanged:N,routeId:T,version:L}of F)r.emit({type:"graph-ready",routeId:T,version:L}),N&&r.emit({type:"document-changed",routeId:T,version:L});for(let{routeId:N,message:T}of B)h=!0,r.emit({type:"graph-error",routeId:N,message:T})}}finally{if(c=null,t!=="disposed"){let y=s?o.get(s):null;t=!h&&y?.graph?"ready":"idle"}a.size>0&&fa([])}})())}async function tf(){for(;m>0;)await new Promise(d=>setTimeout(d,0))}async function pa(d){let h=[];for(let y of new Set(d)){let I=f.get(y);if(I===void 0){h.push(y);continue}try{await n.readFile(y)!==I&&h.push(y)}catch{h.push(y)}}return h}async function ma(d){let h=await pa(d);if(h.length===0)return;let y=ua(h);for(let F of y)r.emit({type:"graph-invalidated",routeId:F});let{rebuiltRoutes:I,failedRoutes:v}=await Qn(h,{changed:!0});for(let{documentChanged:F,routeId:B,version:N}of I)r.emit({type:"graph-ready",routeId:B,version:N}),F&&r.emit({type:"document-changed",routeId:B,version:N});for(let{routeId:F,message:B}of v)r.emit({type:"graph-error",routeId:F,message:B})}async function nf(d,h){let y=tr(d,h);if(!y?.graph)return;let I=He(d)??d,v=y.graph.elements.get(I);v&&await ma([v.sourceFile])}async function ha(d){let h=new Set;if(d.target.kind==="node"){let y=tr(d.target.key,d.routeId),I=He(d.target.key)??d.target.key,v=y?.graph?.elements.get(I);v&&h.add(v.sourceFile)}else if(d.target.kind==="route"){let y=o.get(d.target.routeId);y&&h.add(y.entryFile)}else if(d.target.kind==="page-unit"){let y=o.get(d.target.routeId);y&&h.add(y.entryFile)}else if(d.target.kind==="source-file")h.add(d.target.path);else if(d.target.kind==="source-batch")for(let y of d.target.paths)h.add(y);await ma(h)}async function rf(d){if(d.params.kind!=="source-edit")return Io(d,"invalid-params","source-edit requires source-edit params");for(let h of d.params.edits){let y=AE(h);if(!y.ok)return Io(d,y.errorCode,y.message,y.details)}m+=1;try{let h=await cf(d.params.edits);if(!h.ok)return Io(d,h.errorCode,h.message,h.details);let y={operationId:d.id,kind:"source-edit",target:d.target,documentVersion:d.documentVersion,conflictPolicy:d.params.conflictPolicy,edits:d.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 qn({request:d,filePlan:y})}catch(h){return{requestId:d.id,kind:d.kind,target:d.target,ok:!1,resultVersion:p,error:{code:j.INTERNAL_ERROR,message:Te(h)}}}finally{m-=1}}async function of(d,h){if(d.kind!=="insert-child"||d.params.kind!=="insert-child")return te(d,j.UNSUPPORTED_OPERATION,"Only page-unit insert-child is currently supported by the page composition transaction.");if(!("kind"in d.params.position)||d.params.position.kind!=="page-composition")return te(d,j.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(d.params.position.documentVersion!==d.documentVersion)return te(d,j.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.");let y=h.document,I=h.pageCompositionProjection;if(!y||y.pageComposition?.status!=="supported"||!I||I.status!=="supported")return te(d,j.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(d.documentVersion!==y.version||I.documentVersion!==y.version)return te(d,j.VERSION_STALE,`Document version ${d.documentVersion} is stale (current: ${y.version}).`);let v=d.params.node.kind==="component-call"?d.params.node.materialization:void 0;if(!v)return te(d,j.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let F=d.params.position,B=await qu({manifest:v,generatedRoot:"components/site/generated",controlledFiles:v.files.map(N=>({pathTemplate:N.pathTemplate})),exists:N=>n.exists(N),commit:async N=>{let T=await n.readFile(h.entryFile),L=h.document,Q=h.pageCompositionProjection;if(!L||L.pageComposition?.status!=="supported"||L.version!==d.documentVersion||!Q||Q.status!=="supported"||Q.documentVersion!==L.version)return{ok:!0,data:te(d,j.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let X=N.entry.path,re=hf(N.instanceName),w=ii({routeId:h.routeId,entryFile:h.entryFile,currentDocumentVersion:L.version,expectedDocumentVersion:d.documentVersion,source:T,projection:Q,placementKey:F.placementKey,component:{source:X,exportName:N.entry.export.kind==="default"?"default":N.entry.export.name,localName:re}});if(!w.ok)return{ok:!0,data:te(d,ka(w.error.code),w.error.message,{diagnostics:w.error.diagnostics})};let _=w.plan.returnStep?Cc({source:T,jsx:w.plan.returnStep.node.jsx,placement:w.plan.returnStep.placement,...w.plan.returnStep.replaceOriginal?{replaceOriginal:!0}:{}}):w.plan.insertStep?.parentLocator?qt({source:T,locator:w.plan.insertStep.parentLocator,node:w.plan.insertStep.node,placement:w.plan.insertStep.placement,...w.plan.insertStep.anchorLocator?{anchorLocator:w.plan.insertStep.anchorLocator}:{}}):{ok:!1,source:T,diagnostic:{code:"unsupported-syntax",message:"Route composition rewrite has no insertion step."}};if(!_.ok)return{ok:!0,data:te(d,j.AST_PARSE_ERROR,_.diagnostic.message)};let H=nn({source:_.source,moduleSpecifier:w.plan.importStep.moduleSpecifier,imports:w.plan.importStep.imports});if(!H.ok)return{ok:!0,data:te(d,j.AST_PARSE_ERROR,H.diagnostic.message)};let fe=N.files.map(he=>({operation:"create-only",file:he.path,content:he.content})),se=[{operation:"upsert",file:h.entryFile,content:H.source,baseContentHash:ie(T)},...fe];m+=1;try{let he=await qn({request:d,filePlan:{operationId:d.id,kind:"source-edit",target:{kind:"source-file",path:h.entryFile},documentVersion:d.documentVersion,conflictPolicy:"compare-and-swap",edits:se}});return!he.ok&&he.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:he.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:he}}finally{m-=1}}});return B.ok?B.data:te(d,j.VERSION_STALE,B.error.message,{materializationCode:B.error.code})}async function sf(d,h){if(d.kind!=="move-node"&&d.kind!=="remove-node")return te(d,j.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let y=h.document,I=h.pageCompositionProjection;if(!y||y.pageComposition?.status!=="supported"||!I||I.status!=="supported")return te(d,j.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(d.documentVersion!==y.version||I.documentVersion!==y.version)return te(d,j.VERSION_STALE,`Document version ${d.documentVersion} is stale (current: ${y.version}).`);let v=await n.readFile(h.entryFile),F=vc({routeId:h.routeId,entryFile:h.entryFile,currentDocumentVersion:y.version,expectedDocumentVersion:d.documentVersion,source:v,projection:I,placementUnitKey:d.target.placementUnitKey,operation:d.kind,targetPlacement:d.kind==="move-node"&&d.params.kind==="move-node"&&"kind"in d.params.target&&d.params.target.kind==="page-composition"?d.params.target:void 0});if(!F.ok)return te(d,ka(F.error.code),F.error.message,{diagnostics:F.error.diagnostics});let B=F.plan.rewriteStep.kind==="move-node"?tn({source:v,locator:F.plan.rewriteStep.locator,targetParentLocator:F.plan.rewriteStep.targetParentLocator,placement:F.plan.rewriteStep.placement,...F.plan.rewriteStep.anchorLocator?{anchorLocator:F.plan.rewriteStep.anchorLocator}:{}}):Zt({source:v,locator:F.plan.rewriteStep.locator});if(!B.ok)return te(d,j.AST_PARSE_ERROR,B.diagnostic.message);let N=B.source,T=[];if(d.kind==="remove-node"){let Q=await af({routeState:h,placementUnitKey:d.target.placementUnitKey,source:v,mutatedSource:N});N=Q.source,T=await Promise.all(Q.files.map(async X=>({operation:"delete",file:X,baseContentHash:ie(await n.readFile(X))})))}let L=[{operation:"upsert",file:h.entryFile,content:N,baseContentHash:ie(v)},...T];m+=1;try{return await qn({request:d,filePlan:{operationId:d.id,kind:"source-edit",target:{kind:"source-file",path:h.entryFile},documentVersion:d.documentVersion,conflictPolicy:"compare-and-swap",edits:L}})}finally{m-=1}}async function af(d){let h={source:d.mutatedSource,files:[]},y=d.routeState.graph,I=d.routeState.pageCompositionProjection;if(!y||!I||I.status!=="supported"||!n.listFiles)return h;let F=I.placementUnitByKey.get(d.placementUnitKey)?.sourceRange;if(!F)return h;let B=[...y.elements.values()].find(se=>se.sourceFile===d.routeState.entryFile&&se.importedFrom&&A(se.sourceRange,F));if(!B?.importedFrom||!B.exportName)return h;let N=k(B.importedFrom),T="components/site/generated/";if(!N.startsWith(T))return h;let L=N.slice(T.length).split("/")[0];if(!L||!/-[0-9a-f]{8}$/i.test(L))return h;let Q=`${T}${L}`;if([...y.elements.values()].filter(se=>se.sourceFile===d.routeState.entryFile&&k(se.importedFrom??"")===N).length!==1)return h;let re=await n.listFiles({maxFiles:5e3,maxDepth:32}),w=Array.isArray(re)?re:re.files;if(!Array.isArray(re)&&re.truncated)return h;let _=w.map(({path:se})=>se).filter(se=>se===Q||se.startsWith(`${Q}/`));if(_.length===0||!_.includes(N))return h;for(let{path:se}of w)if(!(se===d.routeState.entryFile||se===Q||se.startsWith(`${Q}/`)))try{if((await n.readFile(se)).includes(L))return h}catch{return h}let H=P(d.routeState.entryFile,N),fe=rn({source:d.mutatedSource,moduleSpecifier:H,imports:B.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:B.exportName}]});return fe.ok?{source:fe.source,files:_.sort((se,he)=>se.localeCompare(he))}:h}async function cf(d){if(n.getFileInfo){for(let v of d)if(await n.exists(v.path)&&await n.getFileInfo(v.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${v.path}`,details:{path:v.path}}}let h=lf(d);if(h.length===0)return{ok:!0};let y=vE(n,d),I=Xn({projectRoot:e.projectRoot,fileSystem:y,routes:[...o.values()].map(v=>({routeId:v.routeId,entryFile:v.entryFile})),externalAdapters:e.externalAdapters,externalSourceResolvers:e.externalSourceResolvers,functionCallContracts:e.functionCallContracts,dev:e.dev});try{for(let v of h)await I.setActiveRoute(v)}catch(v){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${Te(v)}`,details:{routeIds:h}}}finally{I.dispose()}return{ok:!0}}function lf(d){return d.map(y=>y.path).some(Id)?[...o.keys()]:[]}function Io(d,h,y,I){let v=Jn(h);return{requestId:d.id,kind:d.kind,target:d.target,ok:!1,resultVersion:p,error:{code:v,message:y,...I?{details:I}:{}}}}async function ko(d){let h=[];for(let y of new Set(d))h.push(await uf(y));return h}async function uf(d){if(!(typeof n.exists=="function"?await n.exists(d):!0))return{file:d,content:"",version:Math.max(0,Y(d)),exists:!1};let y=await n.readFile(d);return{file:d,content:y,version:Math.max(1,Y(d)),exists:!0,sha256:ie(y)}}async function ga(d,h,y,I){if(!e.historyStore)return null;let v=I.historyTransition;if(!v)throw new Error("Durable history did not provide an exact index transition.");let F=new Map(h.map(T=>[T.file,T])),B=new Map(y.map(T=>[T.file,T])),N=[...new Set([...F.keys(),...B.keys()])].sort().map(T=>{let L=F.get(T),Q=B.get(T);return{path:T,preDigest:L?.exists===!1||!L?null:ie(L.content),postDigest:Q?.exists===!1||!Q?null:ie(Q.content)}});return{schemaVersion:2,transactionId:`${d}:${v.expectedIndexDigest}`,operationId:d,phase:"prepared",historyTransition:v,files:N}}async function ya(d){return!d||!e.historyStore||await e.historyStore.writeTransactionJournal(d),d}async function Vt(d){d&&e.historyStore&&await e.historyStore.clearTransactionJournal(d.transactionId)}async function Ro(d,h){let y=[];try{for(let I of d)await xa(I),typeof n.bumpVersion=="function"&&n.bumpVersion(I.file),y.push(I.file)}catch(I){let v=await df(h.filter(F=>y.includes(F.file)));return v.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${Te(I)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${v.failedFiles.join(", ")}: ${Te(I)}`,rolledBack:!1}}return{ok:!0,snapshots:d.map(ff)}}async function xa(d){if(d.exists===!1){await n.deleteFile(d.file);return}await n.writeFile(d.file,d.content)}async function df(d){let h=[];for(let y of d)try{await xa(y),typeof n.bumpVersion=="function"&&n.bumpVersion(y.file)}catch{h.push(y.file)}return h.length===0?{ok:!0}:{ok:!1,failedFiles:h}}function ff(d){let h=d.exists!==!1;return{file:d.file,content:h?d.content:"",version:d.version,exists:h,...h?{sha256:ie(d.content)}:{}}}async function qn(d){return b.runExclusive(()=>pf(d))}async function pf(d){let h=d.filePlan.edits.map(w=>w.file),y=await ko(h),I=new Map(y.filter(w=>w.exists!==!1).map(w=>[w.file,w.content])),v=p,F=Sa(),B=new Map(f),N=d.filePlan.edits.map(w=>w.operation==="delete"?{file:w.file,content:"",version:0,exists:!1}:{file:w.file,content:w.content,version:0,exists:!0,sha256:ie(w.content)}),T={operationId:d.filePlan.operationId,intents:d.filePlan.edits.map(w=>w.operation==="delete"?{kind:"delete",path:w.file}:{kind:w.operation==="create-only"?"create-only":"upsert",path:w.file,content:w.content})},L=null,Q=!1,X=await to({overlay:I,exists:w=>n.exists(w),plan:T,buildCandidate:async({plan:w})=>({plan:w}),prepareHistory:async()=>{let w=await l.prepareAppend({operationId:d.request.id,kind:d.request.kind,target:d.request.target,preSnapshots:y,postSnapshots:N,...d.selectionRef?{selectionRef:d.selectionRef}:{}});return L=await ga(d.request.id,y,N,w),L=await ya(L),w},reverify:async()=>{},writeCandidate:async()=>{let w=await u.executeFilePlan(d.filePlan);if(!w.ok)throw new oo(w);return{postSnapshots:await ko(w.affectedFiles),affectedFiles:w.affectedFiles,internalResultVersion:w.resultVersion}},validateCandidate:async({candidate:w,receipt:_})=>{let H=await Qn(_.affectedFiles,{changed:!0,minimumVersion:_.internalResultVersion,publish:!1});if(H.failedRoutes.length>0)throw new $t(H.failedRoutes);let fe=ba(F,H.candidateRouteStates??[]),se=Math.max(_.internalResultVersion,...H.rebuiltRoutes.map(he=>he.version));return{...w,rebuild:H,routeSnapshots:fe,resultVersion:se,...Ed(d.selectionRef,fe.map(he=>he.state.document))?{selectionRef:Ed(d.selectionRef,fe.map(he=>he.state.document))}:{}}},publishCandidate:async({candidate:w,history:_,receipt:H})=>{if(!_)throw new Error("history intent is missing");await l.publishPrepared(_),Q=!0;let fe=w.resultVersion??H.internalResultVersion;return{requestId:d.request.id,kind:d.request.kind,target:d.request.target,ok:!0,resultVersion:fe,affectedFiles:H.affectedFiles,...w.selectionRef?{selectionRef:w.selectionRef}:{}}},swapCandidate:({candidate:w,receipt:_})=>{w.routeSnapshots&&er(w.routeSnapshots),w.rebuild?.candidateSourceCache&&fn(f,w.rebuild.candidateSourceCache),Ms(f,_.postSnapshots),p=Math.max(p,w.resultVersion??v)},finalizeCandidate:async()=>{await Vt(L)},emitCommitted:({candidate:w,published:_})=>{bo(_,w.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:w,receipt:_})=>{if(Q)throw new Error("history was published before transaction finalization failed");if(_){let H=await Ro(y,_.postSnapshots);if(!H.ok)throw new Error(H.reason)}er(F),fn(f,B),p=v,w&&await l.discardPrepared?.(w),await Vt(L)}});if(X.ok)return X.published;if(X.stage==="precheck"||X.stage==="build")try{await Vt(L)}catch(w){let _=await nr(Te(w));return te(d.request,_,"Unable to clear an uncommitted transaction journal.")}if(X.recoveryRequired){let w=await nr(X.reason);return te(d.request,w===j.RECOVERY_PERSIST_FAILED?w:j.ROLLBACK_FAILED,X.reason)}let re=X.error;return re instanceof oo?{...te(d.request,Jn(re.result.errorCode),re.result.reason),...re.result.affectedFiles?{affectedFiles:re.result.affectedFiles}:{}}:re instanceof $t?te(d.request,j.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${Os(re.failedRoutes)}`,{failedRoutes:re.failedRoutes}):te(d.request,Ia(X.stage),Te(re))}async function Ea(d){return b.runExclusive(async()=>{let h=d==="undo"?await l.prepareUndo():await l.prepareRedo();return h?mf(d,h):{requestId:d,kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:p,error:{code:j.INTERNAL_ERROR,message:d==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function mf(d,h){let y=h.entry,I=d==="undo"?y.preSnapshots:y.postSnapshots,v=d==="undo"?y.postSnapshots:y.preSnapshots,F=I.map(_=>_.file),B=await ko(F),N=new Map(B.filter(_=>_.exists!==!1).map(_=>[_.file,_.content])),T=p,L=Sa(),Q=new Map(f),X=null,re=!1,w=await to({overlay:N,plan:{operationId:`${d}:${y.operationId}`,intents:I.map(_=>_.exists===!1?{kind:"delete",path:_.file}:{kind:"upsert",path:_.file,content:_.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(X=await ga(`${d}:${y.operationId}`,B,I,h),X=await ya(X),h),reverify:async()=>{},writeCandidate:async()=>{let _=await Ro(I,v);if(!_.ok)throw new Error(_.reason);return{snapshots:_.snapshots}},validateCandidate:async({candidate:_})=>{let H=await Qn(F,{changed:!0,minimumVersion:p+1,publish:!1});if(H.failedRoutes.length>0)throw new $t(H.failedRoutes);let fe=ba(L,H.candidateRouteStates??[]),se=Math.max(p+1,...H.rebuiltRoutes.map(he=>he.version));return{..._,rebuild:H,routeSnapshots:fe,resultVersion:se}},publishCandidate:async({candidate:_,history:H})=>{if(!H)throw new Error("history cursor intent is missing");await l.publishPrepared(H),re=!0;let fe=_.resultVersion??p+1;return{requestId:d,kind:y.kind,target:y.target,ok:!0,resultVersion:fe,affectedFiles:F}},swapCandidate:({candidate:_,receipt:H})=>{_.routeSnapshots&&er(_.routeSnapshots),_.rebuild?.candidateSourceCache&&fn(f,_.rebuild.candidateSourceCache),Ms(f,H.snapshots),p=Math.max(p,_.resultVersion??T)},finalizeCandidate:async()=>{await Vt(X)},emitCommitted:({candidate:_,published:H})=>bo(H,_.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:_,receipt:H})=>{if(re)throw new Error("history cursor was published before transaction finalization failed");if(H){let fe=await Ro(v,H.snapshots);if(!fe.ok)throw new Error(fe.reason)}er(L),fn(f,Q),p=T,_&&await l.discardPrepared?.(_),await Vt(X)}});if(w.ok)return w.published;if(w.stage==="precheck"||w.stage==="build")try{await Vt(X)}catch(_){let H=await nr(Te(_));return{requestId:d,kind:y.kind,target:y.target,ok:!1,resultVersion:p,error:{code:H,message:"Unable to clear an uncommitted transaction journal."}}}if(w.recoveryRequired){let _=await nr(w.reason);return{requestId:d,kind:y.kind,target:y.target,ok:!1,resultVersion:p,affectedFiles:F,error:{code:_===j.RECOVERY_PERSIST_FAILED?_:j.ROLLBACK_FAILED,message:w.reason}}}return{requestId:d,kind:y.kind,target:y.target,ok:!1,resultVersion:p,affectedFiles:F,error:{code:w.error instanceof $t?j.ROUTE_REBUILD_FAILED:Ia(w.stage),message:Te(w.error),...w.error instanceof $t?{details:{failedRoutes:w.error.failedRoutes}}:{}}}}function Sa(){return[...o.values()].map(d=>({routeId:d.routeId,state:{...d,dependencyFiles:new Set(d.dependencyFiles),fileVersions:new Map(d.fileVersions)}}))}function ba(d,h){let y=new Map(d.map(I=>[I.routeId,I]));for(let I of h)y.set(I.routeId,I);return[...y.values()]}function er(d){for(let h of o.values())C(h);for(let h of d){let y={...h.state,dependencyFiles:new Set(h.state.dependencyFiles),fileVersions:new Map(h.state.fileVersions)};o.set(h.routeId,y),le(y,y.dependencyFiles)}}async function Co(d){let h=o.get(d);if(!h)throw new Error(`Route not found: ${d}`);if(h.graph)return;let y=await n.readFile(h.entryFile);await de(d,y)}function tr(d,h){if(h){let y=o.get(h)??null;return!y||!vo(y,d)?null:y}for(let y of o.values())if(vo(y,d))return y;return null}function vo(d,h){if(d.documentIndex?.entriesByKey.has(h)||d.graph?.elements.has(h))return!0;let y=He(h);return y&&y!==h?d.graph?.elements.has(y)===!0:!1}function te(d,h,y,I){return{requestId:d.id,kind:d.kind,target:d.target,ok:!1,resultVersion:p,error:{code:h,message:y,...I?{details:I}:{}}}}function Ia(d){return d==="validate"?j.ROUTE_REBUILD_FAILED:d==="publish"?j.HISTORY_COMMIT_FAILED:j.WRITE_IO_ERROR}async function nr(d){if(S=!0,!l.markRecoveryRequired)return j.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(d),j.RECOVERY_REQUIRED}catch{return j.RECOVERY_PERSIST_FAILED}}function hf(d){let y=d.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(I=>I.charAt(0).toUpperCase()+I.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return y?`Prefab${y}`:"GeneratedPrefab"}function ka(d){return d==="VERSION_STALE"?j.VERSION_STALE:d==="CROSS_PAGE_MOVE_UNSUPPORTED"?j.CROSS_PAGE_MOVE_UNSUPPORTED:j.UNSUPPORTED_OPERATION}async function Ra(d){if(d.target.kind==="route"){let y=o.get(d.target.routeId)??null;return y?(y.graph||await Co(y.routeId),y):te(d,j.ROUTE_NOT_FOUND,`Route not found: ${d.target.routeId}`)}if(d.target.kind==="page-unit"){let y=o.get(d.target.routeId)??null;return y?(y.graph||await Co(y.routeId),y):te(d,j.ROUTE_NOT_FOUND,`Route not found: ${d.target.routeId}`)}if(d.target.kind!=="node")return te(d,j.UNSUPPORTED_OPERATION,`${d.kind} source target execution is not implemented yet.`);if(!d.routeId)return te(d,j.INVALID_TARGET,"routeId is required when executing a node target");let h=o.get(d.routeId)??null;return h?(h.graph||await Co(h.routeId),vo(h,d.target.key)?h:te(d,j.NODE_NOT_FOUND,`Target key not found: ${d.target.key}`)):te(d,j.ROUTE_NOT_FOUND,`Route not found: ${d.routeId}`)}return{get status(){return t},dispose(){t="disposed",a.clear(),o.clear(),i.clear(),f.clear(),s=null},registerRoute(d,h){let y=o.get(d);if(y?.entryFile===h)return;y&&C(y);let I=xd(d,h);o.set(d,I),le(I,I.dependencyFiles),r.emit({type:"graph-invalidated",routeId:d})},unregisterRoute(d){let h=o.get(d);h&&(C(h),o.delete(d),s===d&&(s=null,t="idle"),r.emit({type:"graph-invalidated",routeId:d}))},getRouteEntryFiles(){return[...o.values()].map(d=>d.entryFile)},async setActiveRoute(d){let h=o.get(d);if(!h)throw new Error(`Route not found: ${d}`);let y=s===d;if(s=d,!h.graph){t="building";try{let I=await n.readFile(h.entryFile);await de(d,I);let v=o.get(d)?.graph?.version??1;t="ready",r.emit({type:"graph-ready",routeId:d,version:v})}catch(I){throw t="idle",r.emit({type:"graph-error",routeId:d,message:Te(I)}),I}return}t="ready",y||r.emit({type:"graph-ready",routeId:d,version:h.graph.version})},getDocument(d){let h=o.get(d);if(!h)throw new Error(`Route not found: ${d}`);if(!h.document)throw new Error(`Route not built: ${d}`);return h.document},async getHistoryStatus(){await R;let d=await l.getStatus?.();return d?{...d,recoveryRequired:S}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:S}},getRenderDetail(d,h){let y=tr(d,h),I=He(d)??d;if(y?.graph&&y.topology&&y.capabilities&&y.detailProjections){let v=y.detailProjections.get(I);if(v){let F=jc(I,y.graph,y.topology,y.capabilities,v.textSources,v.writeTarget,v.provenances,v.conditional,v.componentSemantic,v.contentModel,v.mediaModel,v.styleSource);return d===I?F:XE(F,d,y.document??null,y.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${d}`)},getClassNameSource(d,h){let y=tr(d,h),I=He(d)??d;if(!y?.graph)throw new Error(`Key not found: ${d}`);let v=y.graph.elements.get(I);if(!v)throw new Error(`Key not found: ${d}`);let F=f.get(v.sourceFile);if(F===void 0)throw new Error(`Source not loaded: ${v.sourceFile}`);return pl({key:I,route:{routeId:y.routeId,graph:y.graph,source:F}})},refreshSourceForKey:nf,async execute(d){if(await R,S)return te(d,j.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(d.kind==="source-edit")return await ha(d),rf(d);let h=await Ra(d);if("ok"in h)return h;await ha(d);let y=await Ra(d);if("ok"in y)return y;let I=y;if(d.target.kind==="page-unit"){let N=d;return d.kind==="insert-child"?of(N,I):d.kind==="move-node"||d.kind==="remove-node"?sf(N,I):te(d,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:d.id,kind:d.kind,target:d.target,ok:!1,resultVersion:p,error:{code:d.target.kind==="route"?j.ROUTE_NOT_FOUND:j.NODE_NOT_FOUND,message:d.target.kind==="route"?`Route not ready: ${d.target.routeId}`:d.target.kind==="node"?`Target key not found: ${d.target.key}`:`${d.kind} source target execution is not implemented yet.`}};let v=FE(I,I.graph,I.capabilities,f,o),F=await new Yr(v).plan(d);if(!F.ok)return{requestId:d.id,kind:d.kind,target:d.target,ok:!1,resultVersion:p,error:{code:Jn(F.errorCode),message:F.reason}};let B=F.plan;if(B.steps.length===0)return d.kind==="set-props"?{requestId:d.id,kind:d.kind,target:d.target,ok:!0,resultVersion:p,affectedFiles:[]}:{requestId:d.id,kind:d.kind,target:d.target,ok:!1,resultVersion:p,error:{code:j.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};m+=1;try{if(B.steps.some(T=>T.type==="invoke-external-adapter")){let T=await u.execute(B);if(!T.ok)return te(d,Jn(T.errorCode),T.reason);let L={requestId:d.id,kind:d.kind,target:d.target,ok:!0,resultVersion:Math.max(p,T.resultVersion),affectedFiles:T.affectedFiles,...T.selectionRef?{selectionRef:T.selectionRef}:{}};return bo(L,{rebuiltRoutes:[],failedRoutes:[]}),L}let N=await u.prepareRewritePlan(B);return N.ok?await qn({request:d,filePlan:N.filePlan,...N.selectionRef?{selectionRef:N.selectionRef}:{}}):te(d,Jn(N.errorCode),N.reason)}catch(N){return{requestId:d.id,kind:d.kind,target:d.target,ok:!1,resultVersion:p,error:{code:j.INTERNAL_ERROR,message:Te(N)}}}finally{m-=1}},async undo(d){if(await R,S)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."}};m+=1;try{return await Ea("undo")}finally{m-=1}},async redo(d){if(await R,S)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."}};m+=1;try{return await Ea("redo")}finally{m-=1}},notifyFileChanged(d){fa([d])},subscribe(d){return r.subscribe(d)}}}function TE(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&&Ls(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&&Ls(s.sourceRange,n.container.sourceRange)&&o){i.pageCompositionUnitKey=o.placementUnitKey;continue}let c=n.placements.find(l=>l.members.some(u=>u.sourceRange!==null&&(Ls(s.sourceRange,u.sourceRange)||NE(u.sourceRange,s.sourceRange))));if(c){i.pageCompositionUnitKey=c.placementUnitKey;continue}}let a=r.get(`${s.sourceFile}#${s.componentName}`);a&&(i.pageCompositionUnitKey=a)}}function Ls(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function NE(e,t){return bd(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&bd(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function bd(e,t,n,r){return e!==n?e-n:t-r}function FE(e,t,n,r,o){let i=new Map,s=new Map,a=(u,f)=>{if(s.has(u))return;s.set(u,f);let p=t.elements.get(u);for(let m of p?.childKeys??[])a(m,f)};for(let u of t.regions)if(u.kind==="repeat-region")for(let f of u.childKeys)i.set(f,u.ownerKey),a(f,u.ownerKey);return{getNode(u){let f=c(u),p=t.elements.get(f.baseKey);return p?l(u,p):null},getChildNodes(u){let f=c(u),m=e.documentIndex?.entriesByKey.get(u)?.childKeys;if(m)return m.map(b=>{let R=He(b)??b,k=t.elements.get(R);return k?l(b,k):null}).filter(b=>b!==null);let S=t.elements.get(f.baseKey);return S?S.childKeys.map(b=>{let R=t.elements.get(b);return R?l(b,R):null}).filter(b=>b!==null):[]},getKnownSourceFiles(){return[...r.entries()].map(([u,f])=>({file:u,content:f}))},getRouteEntryFiles(){return[...o.values()].map(u=>u.entryFile)},getCapability(u){let f=c(u),p=n.get(f.baseKey);return p?{...p,key:u,constraints:p.constraints.map(m=>({...m})),...p.editModes?{editModes:{...p.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 f=c(u);return e.detailProjections?.get(f.baseKey)?.componentSemantic??null},getEditableTextSegmentIndex(u){let f=c(u),m=e.detailProjections?.get(f.baseKey)?.textTargets.keys()?.next();return m&&!m.done?m.value:null},async getTextWriteTarget(u,f){let p=c(u);return Rd(e.detailProjections?.get(p.baseKey)?.textTargets.get(f)??null,p.repeatIndex)},async getElementPropertyWriteTarget(u,f){let p=c(u);return Rd(e.detailProjections?.get(p.baseKey)?.elementPropertyTargets.get(f)??null,p.repeatIndex)},getTextProvenance(u,f){let p=c(u);return e.detailProjections?.get(p.baseKey)?.provenances.get(f)??null}};function c(u){let f=lE(u);return f?{baseKey:f.baseKey,repeatIndex:VE(e.document??null,u,f.baseKey,e.documentIndex)??UE(f)}:{baseKey:u,repeatIndex:null}}function l(u,f){let p=He(u)??u,m=e.documentIndex?.entriesByKey.get(u),S=e.detailProjections?.get(p);return{key:u,file:f.sourceFile,component:f.componentName,tag:f.tag,structuralPath:f.identity.structuralPath,sourceRange:f.sourceRange,parentKey:m?.parentKey??f.parentKey??void 0,isRepeatRegion:f.boundaryKind==="repeat-region"||s.has(p),isBoundary:!1,importedFrom:f.importedFrom,exportName:f.exportName,isRepeatItemRoot:i.has(p),repeatOwnerKey:i.get(p)??s.get(p),contentModel:S?.contentModel,attributes:f.attributes?.map(b=>({name:b.name,value:b.value,source:b.source?{expression:b.source.expression,base:b.source.base,path:b.source.path.map(R=>({...R}))}:null,resolvedValue:b.resolvedValue}))}}}var ME={"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 Jn(e){return ME[e]}function Te(e){return e instanceof Error&&e.message?e.message:String(e)}function Id(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function _E(e){let t=Ut(e);if(!fE.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=>pE.map(a=>`${s}/${a}`))}function OE(e){let n=Ut(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function LE(e){return Cd(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function DE(e){return Cd(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function Cd(e,t){let n=[];for(let r of e.matchAll(t)){let o=vd(r[1]??"");o&&n.push(o)}return n}function kd(e,t){let n=vd(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?Ut(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?Ut(`${BE(e)}/${n}`):n.startsWith("/")?Ut(n.slice(1)):Ds(n)?Ut(n):null}function vd(e){return e.split(/[?#]/,1)[0]?.trim()??""}function Ds(e){return/\.css$/i.test(e)}function BE(e){let t=Ut(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function wd(e){return Array.from(new Set(e))}function Ut(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 jE(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 ro(e){return e?.map(t=>({...t}))}function Rd(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=ro(e.collectionPathMap?.[t])??ro(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:ro(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>ro(o)??[])}}function $E(e,t,n){let r=new Set;for(let m of t.regions)if(m.kind==="repeat-region")for(let S of m.childKeys)r.add(S);if(r.size===0)return e;let o=new Map(e.entries.map(m=>[m.key,m])),i=[],s=new Map,a=(m,S)=>sE(m,S),c=(m,S,b)=>{let R=o.get(m);if(!R)return a(m,b);let k=a(m,b),P={...R,key:k,parentKey:S,childKeys:[]};return i.push(P),P.childKeys=R.childKeys.flatMap(A=>l(A,b,k)),k},l=(m,S,b)=>{if(!r.has(m))return[c(m,b,S)];let R=f(m,S),k=[];for(let P=0;P<R;P+=1)k.push(c(m,b,[...S,P]));return k},u=wd([...e.rootKeys,...e.entries.filter(m=>m.parentKey===null).map(m=>m.key)]);for(let m of u){if(!r.has(m)){c(m,null,[]);continue}let S=f(m,[]);for(let b=0;b<S;b+=1)c(m,null,[b])}return{...e,rootKeys:[...e.rootKeys],entries:i};function f(m,S){let b=new Set;for(let R of p(m)){let k=n.get(R);if(k){for(let P of[...k.textTargets.values(),...k.elementPropertyTargets.values()])if(!(P?.kind!=="value-binding"||P.sourceKind!=="repeat-template"))for(let A of KE(P))A.length<=S.length||JE(A,S)&&b.add(A[S.length])}}return b.size>0?b.size:jE(n.get(m))}function p(m){let S=s.get(m);if(S)return S;let b=[m],R=o.get(m);for(let k of R?.childKeys??[])b.push(...p(k));return s.set(m,b),b}}function UE(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function VE(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((He(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function KE(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 JE(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 XE(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}}import Vs from"node:path";import{TextDecoder as zE}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as Ad,SITE_EDIT_SOURCE_ALLOWED_DIRS as Td,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as Nd,SiteEditSourceFileResponseSchema as Bs,SiteEditSourceLocationSchema as WE,SiteEditSourcePathSchema as io,SiteEditSourceTreeResponseSchema as HE,isSiteEditTextSourcePath as YE}from"@vcp-dev/contracts";var GE=[...Nd,...Ad,...Td],js=2e3,$s=12,Us=24*1024*1024,Pd=512*1024,ZE=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),QE={".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"},qE={".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"},eS=new zE("utf-8",{fatal:!0});async function so(e,t={}){let{files:n,truncated:r}=await cS(e,t),o=dS(n.map(i=>i.metadata));return HE.parse({nodes:o,defaultPath:fS(n.map(i=>i.metadata)),totalFiles:n.length,...r?{truncated:r}:{}})}async function ao(e,t,n={}){let r=io.parse(t.path),o=await rS(e,r,n);if(!o)throw new Error(`Source file not found: ${r}`);if(Ks(r)){let s=_d(r),a=await iS(e,{path:r,sizeBytes:o.sizeBytes,mimeType:s});return Bs.parse({path:r,kind:"binary",language:null,sizeBytes:o.sizeBytes,mimeType:s,readonly:!0,...a})}let i=await tS(e,r);return i.ok?Bs.parse({path:r,kind:"text",language:Od(r),sizeBytes:i.sizeBytes,contentHash:ie(i.content),readonly:!1,content:i.content}):Bs.parse({path:r,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function tS(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=nS(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 nS(e){if(e.includes(0))return null;try{return eS.decode(e)}catch{return null}}async function rS(e,t,n){if(!sS(t,n))return null;let r=await oS(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function oS(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=Fd(await e.listFiles({roots:[t],maxFiles:1,maxDepth:t.split("/").length})).files.find(i=>i.path===t);if(o)return o}if(!await e.exists(t))return null;if(e.readFileBytes){let r=await e.readFileBytes(t);return{path:t,sizeBytes:r.byteLength}}if(Ks(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function iS(e,t){if(!ZE.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>Pd)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>Pd?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function sS(e,t){return Nd.some(n=>n===e)||Ad.some(n=>n===e)||Td.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=io.safeParse(n);return r.success&&r.data===e})}function co(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return WE.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 Fd(e){return Array.isArray(e)?{files:e}:e}function aS(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function cS(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=Fd(await e.listFiles({roots:lS(t),maxFiles:js+1,maxDepth:$s,maxTotalBytes:Us+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=io.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>$s){o.add("max-depth");continue}if(r.size>=js){o.add("max-files");break}if(i+a.sizeBytes>Us){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:uS(l,a.sizeBytes)}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:aS([...o]),maxFiles:js,maxDepth:$s,maxTotalBytes:Us}}:{}}}function lS(e){let t=new Set(GE);for(let n of e.routeEntryFiles??[]){let r=io.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function uS(e,t){return Ks(e)?{path:e,kind:"binary",language:null,sizeBytes:t,mimeType:_d(e),readonly:!0}:{path:e,kind:"text",language:Od(e),sizeBytes:t,readonly:!1}}function dS(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 Md(t)}function Md(e){return e.map(t=>t.kind==="directory"?{...t,children:Md(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function fS(e){let t=e.find(r=>r.path.toLowerCase()==="design.md");if(t)return t.path;let n=e.find(r=>r.path==="app/page.tsx");return n?n.path:e.find(r=>r.kind==="text")?.path??e.at(0)?.path}function Ks(e){return!YE(e)}function _d(e){let t=Vs.posix.extname(e).toLowerCase();return!t&&Vs.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":QE[t]??"application/octet-stream"}function Od(e){let t=Vs.posix.extname(e).toLowerCase();return qE[t]??"plaintext"}var lo=class{constructor(t){this.options=t,this.fileSystem=new wn(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 sr(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 ar(this.engine.getRenderDetail(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(){return so(this.fileSystem,{routeEntryFiles:this.options.routes.map(t=>t.entryFile)})}getSourceFile(t){return ao(this.fileSystem,t,{routeEntryFiles:this.options.routes.map(n=>n.entryFile)})}resolveSourceLocation(t){return co(t,this.engine.getRenderDetail(t.key,t.routeId))}async planOperation(t){let n=mS.safeParse(t);if(!n.success)return{result:ir(t,n.error.issues.map(i=>i.message))};let r=new wn(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:wt(s)},c=r.getChangedFiles();if(c.length===0)return{result:a};let l=hS.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:c.map(u=>gS(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 Xn({projectRoot:"/snapshot",fileSystem:t,routes:this.options.routes.map(o=>({routeId:o.routeId,entryFile:o.entryFile})),onEvent:r&&this.options.onEvent?o=>{let i=cr(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 gS(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:ie(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:ie(e.before)},fullContent:e.after}}function yS(e){return new lo(e)}import{SiteEditOperationRequestSchema as SS}from"@vcp-dev/contracts";import Ye from"node:fs/promises";import Ie from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as xS,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as ES}from"@vcp-dev/contracts";var uo=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=Xn({...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()}getRenderDetail(t,n){return this.engine.getRenderDetail(t,n)}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(){return so(this.fileSystem,{routeEntryFiles:this.engine.getRouteEntryFiles()})}getSourceFile(t){return ao(this.fileSystem,t,{routeEntryFiles:this.engine.getRouteEntryFiles()})}resolveSourceLocation(t){return co(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 Ye.readFile(Ie.join(n,r),"utf8")},async readFileBytes(r){return Ye.readFile(Ie.join(n,r))},async getFileInfo(r){let o=Ie.join(n,...r.split("/"));try{let i=await Ye.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await Qr(Ie.join(n,r),o)},async createExclusive(r,o){let i=Ie.join(n,r);await Ye.mkdir(Ie.dirname(i),{recursive:!0});let s=await Ye.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await Ye.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await Ye.rm(Ie.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=Ie.join(n,i),a=Ie.dirname(Ie.join(n,o));for(;a!==s&&a.startsWith(`${s}${Ie.sep}`);){try{await Ye.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=Ie.dirname(a);continue}break}a=Ie.dirname(a)}},async exists(r){try{return await Ye.access(Ie.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...ES,...xS],i=[],s=new Set,a=0;for(let u of o)await l(u,i,1);let c=i.sort((u,f)=>u.path.localeCompare(f.path));return s.size>0?{files:c,truncated:{reasons:[...s]}}:{files:c};async function l(u,f,p){if(r.maxFiles!==void 0&&f.length>=r.maxFiles){s.add("max-files");return}if(r.maxDepth!==void 0&&p>r.maxDepth){s.add("max-depth");return}let m=Ie.join(n,...u.split("/")),S;try{S=await Ye.lstat(m)}catch{return}if(S.isSymbolicLink())return;if(S.isFile()){if(r.maxTotalBytes!==void 0&&a+S.size>r.maxTotalBytes){s.add("max-total-bytes");return}f.push({path:u,sizeBytes:S.size}),a+=S.size;return}if(!S.isDirectory())return;let b=await Ye.readdir(m,{withFileTypes:!0});for(let R of b)R.isSymbolicLink()||await l(`${u}/${R.name}`,f,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 Js(e){return new uo(e)}var fo=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=Js({projectRoot:t.projectRoot,fileSystem:t.fileSystem,routes:t.routes.map(n=>({routeId:n.routeId,entryFile:n.entryFile})),onEvent:n=>{let r=cr(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:sr(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:ar(this.engine.getRenderDetail(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=SS.safeParse(r);if(!o.success)return ir(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:wt(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:wt(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:wt(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 bS(e){return new fo(e)}import{createHash as IS,randomUUID as na}from"node:crypto";import me from"node:fs/promises";import Ee from"node:path";var Be=1,zs=1,kS=2,RS="index.json",CS="recovery.json",vS="transaction-journal.json",wS="document-version.json",mo={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},V={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"},K=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 Jd(e,t={}){let n=jS(e),r=VS(t.limits),o=Xs(n),i=$S(n),s=await De(i),a=await De(o)||s;a||(await MS(n),await Vd(n)),a||await KS(n);let c=await Ne(n);a||await zn(n,c.entryIds);let l=async()=>{if(await De(o)||s)throw new K(V.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")};return{rootDir:n,recoveryRequired:a,async readDocumentVersion(){return Kd(n)},async writeDocumentVersion(u){if(await l(),!Number.isInteger(u)||u<0)throw new K(V.INVALID_SCHEMA,"document version must be a non-negative integer");let f=await Kd(n);await Wn(Qd(n),{schemaVersion:1,version:Math.max(f,u)})},async stageAppend(u,f={}){await l();let p=await Dd(u,r),m={schemaVersion:zs,stageId:na(),entryId:p.entryId,blobIds:p.blobs.map(S=>S.digest)};try{await Bd(n,p),await TS(n,m,f.durableManifest!==!1)}catch(S){try{await $d(n,m)}catch(b){throw new K(V.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:b})}throw S}return{stageId:m.stageId,entryId:m.entryId,blobIds:m.blobIds}},async discardStage(u){await l(),Gs(u);let f=await Hs(n,u);f&&await $d(n,f)},async previewStagedAppend(u,f){return await l(),(await Ld(n,r,u,f)).transition},async previewCursor(u,f){await l();let p=await Ne(n);return Zs(p,f),Ws(u,p.entryIds.length),Xd(p,p.entryIds,u)},async publishStagedAppend(u,f,p){if(await l(),ho(u,"entryId"),p){Gs(p);let S=await Hs(n,p);if(!S||S.entryId!==u)throw new K(V.INVALID_SCHEMA,"history stage does not match the published entry")}let m=await Ld(n,r,u,f);return Ud({rootDir:n,previousDigest:m.current.digest,entryIds:m.entryIds,cursor:m.cursor,afterWrite:async()=>{p?await oa(n,p):await FS(n,u),await zn(n,m.entryIds)}})},async append(u){await l();let f=await Ne(n),p=await Dd(u,r),m=[...f.entryIds];f.cursor<m.length-1&&m.splice(f.cursor+1),m.push(p.entryId);try{await Bd(n,p);let S=await zd(n,m,r);return await sa(n,S.entryIds,S.cursor),await zn(n,S.entryIds),Ne(n)}catch(S){throw await zn(n,f.entryIds),S}},async readEntry(u){return ho(u,"entryId"),Hn(n,u)},async readBlob(u){ho(u,"blobId");let f=mn(n,u),p=await Ct(f,V.NOT_FOUND,"blob");return aa(p,u,f),p},async readIndex(){return Ne(n)},async readStatus(){let u=await Ne(n);return{canUndo:u.undoIds.length>0,canRedo:u.redoIds.length>0,undoDepth:u.undoIds.length,redoDepth:u.redoIds.length,cursor:u.cursor,recoveryRequired:await De(o)||await De(i)}},async readUndoRedoIds(){let u=await Ne(n);return{undoIds:u.undoIds,redoIds:u.redoIds,currentId:u.currentId}},async setCursor(u,f){await l();let p=await Ne(n);return Zs(p,f),Ws(u,p.entryIds.length),Ud({rootDir:n,previousDigest:p.digest,entryIds:p.entryIds,cursor:u})},async markRecoveryRequired(u){await De(o)||await Wn(Xs(n),{schemaVersion:Be,reason:US(u),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await me.rm(Xs(n),{force:!0})},async readTransactionJournal(){return await De(i)?po(i):null},async writeTransactionJournal(u){await l(),qd(u);try{await Wn(i,u)}catch(p){let m=await po(i).catch(()=>null);if(m&&Buffer.from(Fe(m)).equals(Buffer.from(Fe(u))))return;throw m?new K(V.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:p}):p}let f=await po(i);if(!Buffer.from(Fe(f)).equals(Buffer.from(Fe(u))))throw new K(V.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(u){let f=await De(i)?await po(i):null;if(f&&f.transactionId!==u)throw new K(V.INVALID_SCHEMA,"transaction journal changed concurrently");try{await me.rm(i,{force:!0})}catch(p){if(!await De(i))return;throw p}if(await De(i))throw new K(V.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await l(),await Vd(n);let u=await Ne(n);await zn(n,u.entryIds)}}}async function Ld(e,t,n,r){ho(n,"entryId");let o=await Ne(e);Zs(o,r);let i=await Hn(e,n),s=[...o.entryIds];o.cursor<s.length-1&&s.splice(o.cursor+1),s.push(i.id);let a=await zd(e,s,t);return{current:o,entryIds:a.entryIds,cursor:a.cursor,transition:Xd(o,a.entryIds,a.cursor)}}function Xd(e,t,n){return Ws(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:PS(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function PS(e,t){return vt(Fe({schemaVersion:Be,entryIds:e,cursor:t}))}function Ws(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new K(V.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function AS(e){if(!Ge(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!we(e.expectedIndexDigest)||!we(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!we(n)?!1:t===-1?n===null:we(n)}async function Dd(e,t){if(!e.kind.trim())throw new K(V.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new K(V.INVALID_JSON,"history blob name must not be empty");let l=BS(c.data),u=vt(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:Be,kind:e.kind,manifest:e.manifest,blobs:r},i=Fe({...o}),s=vt(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new K(V.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function Bd(e,t){let n=Gn(e,t.entryId),r={id:t.entryId,...t.entryBody},o=[...t.blobs.map(a=>jd(mn(e,a.digest),a.bytes,{kind:"blob",digest:a.digest})),jd(n,Fe(r),{kind:"entry",digest:t.entryId})],s=(await Promise.allSettled(o)).find(a=>a.status==="rejected");if(s)throw s.reason}async function jd(e,t,n){let r=await Zd(e);if(r!==null){if(Buffer.compare(r,t)!==0)throw new K(n.kind==="blob"?V.BLOB_CORRUPT:V.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await Yd(e,t)}async function zd(e,t,n){let r=[...t],o=r.length-1;for(;;){if((await Hd(e,r)).totalBytes<=n.maxSessionBytes&&r.length<=n.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new K(V.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");r.shift(),o-=1}}async function TS(e,t,n){ia(t);let r=la(e,t.stageId);if(n){await Wn(r,t);return}await DS(r,t)}async function Hs(e,t){let n=await Zd(la(e,t));if(n===null)return null;let r=Yn(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=ia(r);if(o.stageId!==t)throw new K(V.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function ra(e){let t=[];for(let n of await ta(ca(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);Gs(r);let o=await Hs(e,r);o&&t.push(o)}return t}async function $d(e,t){ia(t);let n=await Ne(e),r=(await ra(e)).filter(s=>s.stageId!==t.stageId),o=new Set(n.entryIds),i=new Set;for(let s of n.entryIds){let a=await Hn(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 Ys(Gn(e,t.entryId));for(let s of t.blobIds)i.has(s)||await Ys(mn(e,s));await oa(e,t.stageId),await ea(Eo(e)),await ea(So(e))}async function oa(e,t){await Ys(la(e,t)),await NS(e)}async function NS(e){try{await me.rmdir(ca(e))}catch(t){if(Zn(t)||Ge(t)&&t.code==="ENOTEMPTY")return;throw t}}async function FS(e,t){for(let n of await ra(e))n.entryId===t&&await oa(e,n.stageId)}async function Ys(e){if(await me.rm(e,{force:!0}),await De(e))throw new K(V.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}function ia(e){if(!Ge(e)||e.schemaVersion!==zs||typeof e.stageId!="string"||!Wd(e.stageId)||!we(e.entryId))throw new K(V.INVALID_SCHEMA,"history stage schema is invalid");let t=Gd(e.blobIds,"history stage blobIds");return{schemaVersion:zs,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function Gs(e){if(!Wd(e))throw new K(V.INVALID_PATH,"history stageId must be a UUID")}function Wd(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 zn(e,t){let n=new Set(t),r=new Set;for(let c of t){let l=await Hn(e,c);for(let u of l.blobs)r.add(u.digest)}for(let c of await ra(e)){n.add(c.entryId);for(let l of c.blobIds)r.add(l)}let o=Eo(e),i=await ta(o);for(let c of i){if(!c.endsWith(".json"))continue;let l=c.slice(0,-5);we(l)&&!n.has(l)&&await go(Gn(e,l))}let s=So(e),a=await ta(s);for(let c of a){let l=c;we(l)&&!r.has(l)&&await go(mn(e,l))}}async function Ne(e){let t=xo(e),n=await Ct(t,V.NOT_FOUND,"index"),r=Yn(Buffer.from(n).toString("utf8"),"index"),o=_S(r),i=[...o.entryIds],{totalBytes:s}=await Hd(e,i),a=i.slice(0,o.cursor+1).reverse(),c=i.slice(o.cursor+1);return{schemaVersion:Be,digest:o.digest,entryIds:i,cursor:o.cursor,currentId:i[o.cursor]??null,undoIds:a,redoIds:c,totalBytes:s}}async function Hd(e,t){let n=0,r=new Set,o=xo(e),i=await Ct(o,V.NOT_FOUND,"index");n+=i.byteLength;for(let s of t){let a=await Hn(e,s),c=Gn(e,s),l=await Ct(c,V.NOT_FOUND,"entry");n+=l.byteLength;for(let u of a.blobs){if(r.has(u.digest))continue;r.add(u.digest);let f=mn(e,u.digest),p=await Ct(f,V.NOT_FOUND,"blob");aa(p,u.digest,f),n+=p.byteLength}}return{totalBytes:n}}async function Hn(e,t){let n=Gn(e,t),r=await Ct(n,V.NOT_FOUND,"entry"),o=Yn(Buffer.from(r).toString("utf8"),`entry ${t}`),i=OS(o);if(i.id!==t)throw new K(V.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(vt(Fe({schemaVersion:i.schemaVersion,kind:i.kind,manifest:i.manifest,blobs:i.blobs}))!==t)throw new K(V.ENTRY_CORRUPT,`entry hash mismatch for ${t}`);for(let a of i.blobs){let c=mn(e,a.digest),l=await Ct(c,V.NOT_FOUND,"blob");aa(l,a.digest,c)}return i}async function sa(e,t,n){let r={schemaVersion:Be,digest:vt(Fe({schemaVersion:Be,entryIds:t,cursor:n})),entryIds:t,cursor:n};await Wn(xo(e),r)}function Zs(e,t){if(t!==void 0&&e.digest!==t)throw new K(V.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function Ud(e){let t=vt(Fe({schemaVersion:Be,entryIds:e.entryIds,cursor:e.cursor}));try{return await sa(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.(),await Ne(e.rootDir)}catch(n){let r=await Ne(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new K(V.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function MS(e){await me.mkdir(e,{recursive:!0}),await me.mkdir(Eo(e),{recursive:!0}),await me.mkdir(So(e),{recursive:!0}),await me.mkdir(yo(e),{recursive:!0})}async function Vd(e){await me.rm(yo(e),{recursive:!0,force:!0}),await me.mkdir(yo(e),{recursive:!0})}function _S(e){if(!Ge(e))throw new K(V.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==Be)throw new K(V.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=Gd(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new K(V.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!we(o))throw new K(V.INDEX_CORRUPT,"index digest is invalid");let i=vt(Fe({schemaVersion:Be,entryIds:t,cursor:r}));if(o!==i)throw new K(V.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:Be,digest:o,entryIds:t,cursor:r}}function OS(e){if(!Ge(e))throw new K(V.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==Be)throw new K(V.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!we(t))throw new K(V.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new K(V.ENTRY_CORRUPT,"entry kind is invalid");let r=qs(e.manifest,"entry.manifest"),o=LS(e.blobs);return{id:t,schemaVersion:Be,kind:n,manifest:r,blobs:o}}function LS(e){if(!Array.isArray(e))throw new K(V.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!Ge(t))throw new K(V.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new K(V.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!we(o))throw new K(V.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new K(V.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function Wn(e,t){await Yd(e,Fe(t))}async function DS(e,t){let n=Ee.dirname(e),r=Ee.basename(e),o=Ee.join(n,`.${r}.${process.pid}.${na()}.tmp`);await me.mkdir(n,{recursive:!0});try{await me.writeFile(o,Fe(t),{flag:"wx"}),await me.rename(o,e)}finally{await go(o)}}async function Yd(e,t){let n=Ee.dirname(e),r=Ee.basename(e),o=Ee.join(n,`.${r}.${process.pid}.${na()}.tmp`);await me.mkdir(n,{recursive:!0});try{let i=await me.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await me.rename(o,e),await ea(n)}finally{await go(o)}}function Fe(e){return Buffer.from(JSON.stringify(Qs(e)),"utf8")}function Qs(e){if(Array.isArray(e))return e.map(t=>Qs(t));if(Ge(e)){let t={};for(let n of Object.keys(e).sort())t[n]=Qs(e[n]);return t}return e}function Yn(e,t){try{return JSON.parse(e)}catch(n){throw new K(V.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function qs(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=>qs(n,t));if(Ge(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=qs(o,t);return n}break}throw new K(V.INVALID_JSON,`${t} must be JSON-serializable`)}function Gd(e,t){if(!Array.isArray(e))throw new K(V.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!we(n))throw new K(V.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function ho(e,t){if(!we(e))throw new K(V.INVALID_PATH,`${t} must be a sha256 digest`)}function we(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function vt(e){return`sha256:${IS("sha256").update(e).digest("hex")}`}function BS(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function Ct(e,t,n){try{return await me.readFile(e)}catch(r){throw new K(t,`${n} not found: ${e}`,{cause:r})}}async function Zd(e){try{return await me.readFile(e)}catch(t){if(Zn(t))return null;throw t}}function aa(e,t,n){if(vt(e)!==t)throw new K(V.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function De(e){try{return await me.access(e),!0}catch(t){if(Zn(t))return!1;throw t}}async function go(e){try{await me.rm(e,{force:!0,recursive:!0})}catch{}}async function ea(e){try{let t=await me.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function ta(e){try{return await me.readdir(e)}catch(t){if(Zn(t))return[];throw t}}function jS(e){if(typeof e!="string"||e.trim().length===0)throw new K(V.INVALID_ROOT,"history store rootDir must be a non-empty string");return Ee.resolve(e)}function xo(e){return Ee.join(e,RS)}function Xs(e){return Ee.join(e,CS)}function $S(e){return Ee.join(e,vS)}function Qd(e){return Ee.join(e,wS)}async function Kd(e){try{let t=await me.readFile(Qd(e),"utf8"),n=Yn(t,"document version");if(!Ge(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new K(V.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(Zn(t))return 0;throw t}}async function po(e){let t=await Ct(e,V.RECOVERY_PENDING,"transaction journal"),n=Yn(Buffer.from(t).toString("utf8"),"transaction journal");return qd(n),n}function qd(e){if(!Ge(e)||e.schemaVersion!==kS||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!AS(e.historyTransition)||!Array.isArray(e.files))throw new K(V.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!Ge(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!we(t.preDigest)||t.postDigest!==null&&!we(t.postDigest))throw new K(V.INVALID_SCHEMA,"transaction journal file digest is invalid")}function US(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function Eo(e){return Ee.join(e,"entries")}function So(e){return Ee.join(e,"blobs")}function yo(e){return Ee.join(e,"tmp")}function ca(e){return Ee.join(yo(e),"stages")}function la(e,t){return Ee.join(ca(e),`${t}.json`)}function Gn(e,t){return Ee.join(Eo(e),`${t}.json`)}function mn(e,t){return Ee.join(So(e),t)}function Ge(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Zn(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function VS(e){return{maxEntries:e?.maxEntries??mo.maxEntries,maxSessionBytes:e?.maxSessionBytes??mo.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??mo.maxEntryBytes}}async function KS(e){let t=xo(e);await De(t)||await sa(e,[],-1)}export{K as FileHistoryStoreError,fo as PreviewFileSystemSiteEditEngineRuntime,zu as SITE_EDIT_RAW_COLOR_LITERAL_RE,lo as SnapshotSiteEditEngineRuntime,bS as createPreviewSiteEditEngineRuntime,yS as createSiteEditEngineRuntime,Jd as openFileHistoryStore,Cs as scanSiteEditThemeStyleViolations};
|