@vcp-dev/site-edit-engine 0.4.0 → 0.4.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.js CHANGED
@@ -1,4 +1,11 @@
1
- import{SiteEditOperationRequestSchema as qf,SiteEditPatchPlanSchema as Qf}from"@vcp-dev/contracts";function _e(e){return{requestId:e.requestId,kind:e.kind,target:e.target,resultVersion:e.resultVersion,affectedFiles:e.affectedFiles,...e.selectionRef?{selectionRef:e.selectionRef}:{}}}function Ut(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 zt(e,t){return{siteId:t.siteId,snapshotId:t.snapshotId,routeId:e.routeId,version:e.version,rootKeys:e.rootKeys,entries:e.entries.map(n=>({key:n.key,tag:n.tag,label:n.label,parentKey:n.parentKey,childKeys:n.childKeys,operationSummary:{canUpdateText:n.operationSummary.canUpdateText,canInsertChild:n.operationSummary.canInsertChild,canMove:n.operationSummary.canMove,canRemove:n.operationSummary.canRemove}}))}}function Ht(e){return{key:e.key,tag:e.tag,label:e.label,sourceLocator:e.sourceLocator?{sourceFile:e.sourceLocator.sourceFile,componentName:e.sourceLocator.componentName,openingElementRange:{startLine:e.sourceLocator.openingElementRange.startLine,startColumn:e.sourceLocator.openingElementRange.startColumn,endLine:e.sourceLocator.openingElementRange.endLine,endColumn:e.sourceLocator.openingElementRange.endColumn},structuralPath:e.sourceLocator.structuralPath,textPreview:e.sourceLocator.textPreview}:void 0,capabilities:{constraints:e.capabilities.constraints},isOpaque:e.isOpaque,provenanceChain:e.provenanceChain?{editMode:e.provenanceChain.editMode,diagnostics:e.provenanceChain.diagnostics}:void 0,ancestors:e.ancestors}}function Gt(e){return{key:e.key,componentName:e.componentName,sourceFile:e.sourceFile,capabilities:el(e.capabilities),writeTarget:{kind:e.writeTarget.kind,file:e.writeTarget.file,componentName:e.writeTarget.componentName,isProxy:e.writeTarget.isProxy},effectiveWriteTarget:e.effectiveWriteTarget?{kind:e.effectiveWriteTarget.kind,file:e.effectiveWriteTarget.file,isProxy:e.effectiveWriteTarget.isProxy,displayPath:e.effectiveWriteTarget.displayPath,sourceType:e.effectiveWriteTarget.sourceType,sourceId:e.effectiveWriteTarget.sourceId}:void 0,provenanceChain:tl(e),componentSemantic:nl(e.componentSemantic),textSegments:e.textSegments.map(t=>({index:t.index,value:t.value,editable:t.editable,source:t.source?{kind:t.source.kind,file:t.source.file,expression:t.source.expression,bindingName:t.source.bindingName,path:t.source.path}:null})),boundaryKind:e.boundaryKind,children:e.children,siblings:e.siblings}}function Yt(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:_e(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 el(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}}function tl(e){return e.provenanceChain?{finalSource:e.provenanceChain.finalSource?{kind:e.provenanceChain.finalSource.kind,file:e.provenanceChain.finalSource.file,displayPath:e.provenanceChain.finalSource.displayPath,externalSource:e.provenanceChain.finalSource.externalSource?{sourceType:e.provenanceChain.finalSource.externalSource.sourceType,sourceId:e.provenanceChain.finalSource.externalSource.sourceId,adapterId:e.provenanceChain.finalSource.externalSource.adapterId}:void 0}:null,chain:e.provenanceChain.chain.map(t=>({kind:t.kind,file:t.file,displayName:t.displayName,canEditHere:t.canEditHere})),confidence:e.provenanceChain.confidence,editMode:e.provenanceChain.editMode,diagnostics:e.provenanceChain.diagnostics}:void 0}function nl(e){return e||void 0}import{composeSiteEditRepeatInstanceKey as Rf,parseSiteEditRepeatInstanceKey as wf,stripSiteEditRepeatInstanceKeys as ke}from"@vcp-dev/contracts";function vt(e,t,n){return`${e}::${t}::${n}`}var G={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",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",INTERNAL_ERROR:"INTERNAL_ERROR"};import*as zo from"@babel/parser";import qn from"@babel/traverse";import*as p from"@babel/types";import*as rl from"@babel/parser";import*as rt from"@babel/types";import*as ot from"node:path";var Vo=[".tsx",".ts",".jsx",".js"],ol=Vo.map(e=>`${ot.sep==="\\"?"\\":"/"}index${e}`);function _o(e){let t=[];for(let n of e.program.body)rt.isImportDeclaration(n)&&typeof n.source.value=="string"&&kt(n.source.value)&&t.push(n.source.value),rt.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&kt(n.source.value)&&t.push(n.source.value),rt.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&kt(n.source.value)&&t.push(n.source.value);return t}function kt(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function il(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=ot.dirname(e);return ot.join(n,t).replace(/\\/g,"/")}async function sl(e,t){for(let n of Vo){let r=`${e}${n}`;if(await t(r))return r}for(let n of ol){let r=`${e}${n}`;if(await t(r))return r}return null}async function Ct(e,t,n){let r=il(e,t);return sl(r,n)}var Zt="components/ui";function Xe(e){if(!e)return!1;let t=Zn(e);return t===Zt||t.startsWith(`${Zt}/`)||t.includes(`/${Zt}/`)||t.endsWith(`/${Zt}`)}function Xo(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?Xe(e.slice(2)):e.startsWith("./")||e.startsWith("../")?Xe(Zn(`${al(t)}/${e}`)):Xe(e):!1}function Zn(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 al(e){let t=Zn(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}var ll=typeof qn=="function"?qn:qn.default;function cl(e){try{return zo.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function oe(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 ul(e){return/^[A-Z]/.test(e)}function rr(e){let t=e.openingElement;return p.isJSXIdentifier(t.name)?t.name.name==="Fragment":p.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function st(e){return p.isJSXFragment(e)}function Ho(e){return p.isJSXIdentifier(e.name)?e.name.name:p.isJSXMemberExpression(e.name)?Go(e.name):p.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function Go(e){return p.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:p.isJSXMemberExpression(e.object)?`${Go(e.object)}.${e.property.name}`:e.property.name}function dl(e){return e.split(".")[0]??e}function pl(e){let t=e;for(;t;){let n=t.node;if(p.isFunctionDeclaration(n)&&n.id||p.isVariableDeclarator(n)&&p.isIdentifier(n.id))return n.id.name;if(p.isExportDefaultDeclaration(n)){let r=n.declaration;if(p.isFunctionDeclaration(r)&&r.id)return r.id.name;if(p.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function fl(){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 ml(e){let t=new Map;for(let n of e.program.body){if(!p.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(p.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(p.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(p.isImportSpecifier(o)){let i=p.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function Re(e,t=[]){if(p.isIdentifier(e))return t.push(e.name),t;if(p.isObjectPattern(e)){for(let n of e.properties)p.isObjectProperty(n)?Re(n.value,t):p.isRestElement(n)&&Re(n.argument,t);return t}if(p.isArrayPattern(e)){for(let n of e.elements)n&&(p.isRestElement(n)?Re(n.argument,t):Re(n,t));return t}return p.isAssignmentPattern(e)?(Re(e.left,t),t):(p.isRestElement(e)&&Re(e.argument,t),t)}function Te(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function qt(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 hl(e,t,n){e.set(t,{resolved:!0,value:n})}function or(e,t){e.set(t,{resolved:!1})}function Yo(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 we(e,t,n){if(p.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!p.isMemberExpression(e))return null;let r=[],o=e;for(;p.isMemberExpression(o);){if(o.computed)if(p.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(p.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&p.isExpression(o.property)){let i=Ue(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(!p.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return p.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:Te(e,t),base:o.name,path:r}:null}function Ue(e,t){if(p.isStringLiteral(e)||p.isNumericLiteral(e)||p.isBooleanLiteral(e))return e.value;if(p.isNullLiteral(e))return null;if(p.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(p.isIdentifier(e)){let n=qt(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(p.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||p.isSpreadElement(r))return;let o=Ue(r,t);if(o===void 0)return;n.push(o)}return n}if(p.isObjectExpression(e)){let n={};for(let r of e.properties){if(!p.isObjectProperty(r)||r.computed||!p.isExpression(r.value))return;let o=null;if(p.isIdentifier(r.key)?o=r.key.name:p.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!p.isIdentifier(r.value))return;let s=qt(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=Ue(r.value,t);if(i===void 0)return;n[o]=i}return n}if(p.isMemberExpression(e)){let n=we(e,"",t);if(!n)return;let r=qt(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=Yo(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(p.isCallExpression(e))return qo(e,t)??void 0}function Zo(e,t,n){let r=we(e,n,t);if(!r)return p.isMemberExpression(e)||p.isBinaryExpression(e)||p.isLogicalExpression(e)||p.isConditionalExpression(e)||p.isCallExpression(e)?{value:Te(e,n),source:null}:null;let o=qt(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?Yo(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 Qn(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:fl(),parentStack:[],valueScopes:i,importMap:o}}function tr(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of Re(o.id))or(n,s);if(!p.isIdentifier(o.id)||!o.init||!p.isExpression(o.init))continue;let i=Ue(o.init,t);i!==void 0&&hl(n,o.id.name,i)}}function gl(e){let t=[];for(let n of e){if(p.isVariableDeclaration(n)){t.push(n);continue}p.isExportNamedDeclaration(n)&&n.declaration&&p.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function xl(e,t,n){let r=[],o=0;for(let i of e)if(p.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:oe(i),editable:!0,source:null})}else if(p.isJSXExpressionContainer(i)&&p.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:oe(i),editable:!0,source:null});else if(p.isJSXExpressionContainer(i)&&p.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:oe(i),editable:!0,source:null}):r.push({index:o++,value:Te(s,n),sourceRange:oe(i),editable:!0,source:null})}else if(p.isJSXExpressionContainer(i)&&p.isExpression(i.expression)){let s=Zo(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:oe(i),editable:!0,source:s.source})}return r}function yl(e,t,n){let r=[];for(let o of e.attributes)if(!(!p.isJSXAttribute(o)||!p.isJSXIdentifier(o.name))){if(p.isStringLiteral(o.value)){r.push({name:o.name.name,value:o.value.value,sourceRange:oe(o),source:null});continue}if(p.isJSXExpressionContainer(o.value)&&p.isExpression(o.value.expression)){let i=Ue(o.value.expression,t);if(o.name.name==="className"){let a=typeof i=="string"?i:i===void 0?qo(o.value.expression,t):null;if(a){r.push({name:o.name.name,value:a,sourceRange:oe(o),source:null,resolvedValue:a});continue}}let s=Zo(o.value.expression,t,n);if(i!==void 0&&typeof i!="string"&&typeof i!="number"){r.push({name:o.name.name,value:Wo(i),sourceRange:oe(o),source:we(o.value.expression,n,t),resolvedValue:i});continue}if(!s){i!==void 0&&r.push({name:o.name.name,value:Wo(i),sourceRange:oe(o),source:we(o.value.expression,n,t),resolvedValue:i});continue}r.push({name:o.name.name,value:s.value,sourceRange:oe(o),source:s.source})}}return r}function qo(e,t){let n=it(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function it(e,t){if(p.isStringLiteral(e))return[e.value];if(p.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(p.isNullLiteral(e))return[];if(p.isBooleanLiteral(e))return e.value?null:[];if(p.isIdentifier(e)||p.isMemberExpression(e)){if(p.isIdentifier(e)&&e.name==="undefined")return[];let n=Ue(e,t);return typeof n=="string"?[n]:null}if(p.isConditionalExpression(e)){let n=it(e.consequent,t),r=it(e.alternate,t);return!n||!r?null:[...n,...r]}if(p.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=Ue(e.left,t);return n===!1||n===null?[]:it(e.right,t)}if(p.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||p.isSpreadElement(r))return null;let o=it(r,t);if(!o)return null;n.push(...o)}return n}if(p.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!p.isObjectProperty(r))return null;let o=bl(r.key);if(!o)return null;n.push(o)}return n}if(p.isCallExpression(e)){let n=Sl(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!p.isExpression(o))return null;let i=it(o,t);if(!i)return null;r.push(...i)}return r}return null}function Sl(e){return p.isIdentifier(e)?e.name:p.isMemberExpression(e)&&p.isIdentifier(e.property)?e.property.name:null}function bl(e){return p.isIdentifier(e)?e.name:p.isStringLiteral(e)?e.value:null}function vl(e,t){let n=e.attributes.find(r=>p.isJSXAttribute(r)&&p.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!p.isJSXAttribute(n)||!p.isJSXExpressionContainer(n.value)?null:n.value.expression}function kl(e,t){for(let n of t){let r=vl(e,n);if(r)return r}return null}function Cl(e){return p.isJSXIdentifier(e.name)?e.name.name:null}function Wo(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function El(e){if(!p.isCallExpression(e)&&!p.isOptionalCallExpression(e))return null;let t=e.callee;return!p.isMemberExpression(t)&&!p.isOptionalMemberExpression(t)||!p.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!p.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function er(e){return p.isArrowFunctionExpression(e)||p.isFunctionExpression(e)}function Il(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function Pl(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function Uo(e,t,n,r){if(!e||!p.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:Te(e,n),collectionSource:we(e,n,r)};if(t){let i=t.params[0],s=t.params[1];p.isIdentifier(i)&&(o.itemParamName=i.name),p.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function Oe(e,t,n){if(!e)return[];if(p.isJSXElement(e)){if(rr(e))return rn(e.children,t,n);let r=tn(e,t,n);return r?[r]:[]}return st(e)?nn(e,t,n):p.isParenthesizedExpression(e)?Oe(e.expression,t,n):p.isExpression(e)?on(e,t,n):[]}function Qt(e,t,n){let r=new Map;for(let o of e.params)for(let i of Re(o))or(r,i);t.valueScopes.push(r);try{if(!p.isBlockStatement(e.body))return Oe(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return Qo(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function Qo(e,t,n){let r=[];for(let o of e){if(p.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];i&&tr([o],t,i);continue}r.push(...nr(o,t,n))}return r}function nr(e,t,n){if(p.isReturnStatement(e))return e.argument?Oe(e.argument,t,n):[];if(p.isBlockStatement(e))return We(e.body,t,n);if(p.isIfStatement(e)){let r=p.isBlockStatement(e.consequent)?We(e.consequent.body,t,n):nr(e.consequent,t,n),o=e.alternate?p.isBlockStatement(e.alternate)?We(e.alternate.body,t,n):nr(e.alternate,t,n):[];return[...r,...o]}if(p.isSwitchStatement(e))return We(e.cases.flatMap(r=>r.consequent),t,n);if(p.isTryStatement(e)){let r=We(e.block.body,t,n);return e.handler&&r.push(...We(e.handler.body.body,t,n)),e.finalizer&&r.push(...We(e.finalizer.body,t,n)),r}return[]}function We(e,t,n){let r=new Map;t.valueScopes.push(r);try{return Qo(e,t,n)}finally{t.valueScopes.pop()}}function en(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:oe(r),sourceCandidates:i&&i.length>0?i:void 0})}function Rl(e,t,n,r){let o=kl(e.openingElement,["items","dataSource","data"]),i={key:t,tag:Ho(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!p.isJSXAttribute(s))continue;let a=Cl(s);if(!a||!p.isJSXExpressionContainer(s.value))continue;let l=s.value.expression;if(!p.isJSXEmptyExpression(l)){if(Il(a)&&er(l)){let c=Qt(l,n,r),u=Uo(o,l,r,n);en(n,"repeat-region",t,s,c,u?[u]:void 0);continue}if(Pl(a)){let c=er(l)?Qt(l,n,r):Oe(l,n,r);en(n,"conditional-region",t,s,c)}}}if(o)for(let s of e.children){if(!p.isJSXExpressionContainer(s)||!er(s.expression))continue;let a=Qt(s.expression,n,r),l=Uo(o,s.expression,r,n);en(n,"repeat-region",t,s,a,l?[l]:void 0)}}finally{n.parentStack.pop()}}function tn(e,t,n){let r=Ho(e.openingElement);if(r==="Fragment"||rr(e))return rn(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=ul(r),a;if(s){let I=t.ordinalTracker.getOrdinal(i,r);a=`component:${r}#${I}`}else{let I=t.ordinalTracker.getOrdinal(i,r);a=`${r}#${I}`}let l=o?t.elements.get(o.key)?.identity.structuralPath:void 0,c=l?`${l}/${a}`:a,u=vt(t.file,t.componentName,c),d={file:t.file,component:t.componentName,structuralPath:c,key:u},g=s?"component-boundary":null,h=xl(e.children,t,n),S=yl(e.openingElement,t,n),y,k,E=!1;if(s){let I=t.importMap.get(r)??t.importMap.get(dl(r));I&&(y=I.specifier,k=I.exportName,E=Xo(I.specifier,t.file))}let R={identity:d,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:oe(e),parentKey:i,childKeys:[],textSegments:h,attributes:S.length>0?S:void 0,boundaryKind:g,isOpaque:s,...E?{isPublicUiComponent:!0}:{},importedFrom:y,exportName:k};return t.elements.set(u,R),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(u),Rl(e,u,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:u,tag:r}),wl(e.children,t,n),t.parentStack.pop()),u}function nn(e,t,n){return rn(e.children,t,n)}function rn(e,t,n){let r=[];for(let o of e)if(p.isJSXElement(o))if(rr(o))r.push(...rn(o.children,t,n));else{let i=tn(o,t,n);i&&r.push(i)}else st(o)?r.push(...nn(o,t,n)):p.isJSXExpressionContainer(o)&&r.push(...on(o.expression,t,n));return r}function wl(e,t,n){for(let r of e)p.isJSXElement(r)?tn(r,t,n):st(r)?nn(r,t,n):p.isJSXExpressionContainer(r)&&on(r.expression,t,n)}function Fl(e){return e==="&&"||e==="||"||e==="??"}function on(e,t,n){if(p.isJSXEmptyExpression(e))return[];let r=El(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,l={kind:"repeat-template",collectionExpression:Te(r.collection,n),collectionSource:we(r.collection,n,t)};if(p.isArrowFunctionExpression(a)||p.isFunctionExpression(a)){let u=a.params[0],d=a.params[1];p.isIdentifier(u)&&(l.itemParamName=u.name),p.isIdentifier(d)&&(l.indexParamName=d.name)}s.push(l);let c={kind:"repeat-region",ownerKey:i?.key??"",childKeys:[],sourceRange:oe(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(c),(p.isArrowFunctionExpression(a)||p.isFunctionExpression(a))&&c.childKeys.push(...Qt(a,t,n)),c.childKeys}if(p.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:Te(e.test,n),conditionSource:we(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:oe(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Oe(e.consequent,t,n)),s.childKeys.push(...Oe(e.alternate,t,n)),s.childKeys}if(p.isLogicalExpression(e)&&Fl(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:Te(e.left,n),conditionSource:we(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:oe(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Oe(e.right,t,n)),s.childKeys}if(p.isParenthesizedExpression(e))return on(e.expression,t,n);if(p.isJSXElement(e)){let o=tn(e,t,n);return o?[o]:[]}return st(e)?nn(e,t,n):[]}function Nl(e){let t=e.argument;return t&&(p.isExpression(t)||st(t))?t:null}function Et(e,t){let n=[];for(let r of e){if(p.isReturnStatement(r)){let o=Nl(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(p.isIfStatement(r)){let o=p.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...Et(o,r.test)),r.alternate){let i=p.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...Et(i,r.test))}continue}if(p.isSwitchStatement(r))for(let o of r.cases){let i=o.test?p.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...Et(o.consequent,i))}}return n}function ei(e,t){let n={routeId:e,rootKeys:[],elements:new Map,regions:[],fileIndex:new Map,version:1},r=cl(t);if(!r)return{graph:n,localImports:[]};let o=_o(r),i=new Map,s=[],a=[],l=new Map,c=ml(r);ll(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(d){let g=pl(d);if(!g)return;let h=d.node,S=[];if(p.isArrowFunctionExpression(h))p.isExpression(h.body)||st(h.body)?S=[{argument:h.body,statement:p.returnStatement(p.isExpression(h.body)?h.body:null)}]:p.isBlockStatement(h.body)&&(S=Et(h.body.body));else{let b=h.body;p.isBlockStatement(b)&&(S=Et(b.body))}if(S.length===0){d.skip();return}let y=new Map;tr(gl(r.program.body),Qn(e,g,i,s,c,[y]),y);let k=new Map;for(let b of h.params)for(let M of Re(b))or(k,M);let E=p.isBlockStatement(h.body)?h.body.body:[],R=S[0]?.statement??null;for(let b of E){if(R&&b===R)break;p.isVariableDeclaration(b)&&tr([b],Qn(e,g,i,s,c,[y,k]),k)}let I=Qn(e,g,i,s,c,[y,k]);for(let b of S){let M=Oe(b.argument,I,t);for(let T of M)a.includes(T)||a.push(T);if(b.condition){let T={kind:"conditional-branch",conditionExpression:Te(b.condition,t),conditionSource:we(b.condition,t,I)};en(I,"conditional-region","",b.statement,M,[T])}}d.skip()}});let u=[...i.keys()];return u.length>0&&l.set(e,u),{graph:{routeId:e,rootKeys:a,elements:i,regions:s,fileIndex:l,version:1},localImports:o}}async function ti(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=new Map,l=new Map,c=[{file:e,source:t,depth:0},...(o.additionalEntries??[]).map(g=>({file:g.file,source:g.source,depth:0}))],u=new Set;for(;c.length>0;){let g=c.shift(),{file:h,source:S,depth:y}=g;if(u.has(h))continue;u.add(h),a.set(h,S);let{graph:k,localImports:E}=ei(h,S);for(let R of k.elements.values())if(R.importedFrom&&kt(R.importedFrom))try{let I=await Ct(h,R.importedFrom,r);I&&(R.importedFrom=I,Xe(I)&&(R.isPublicUiComponent=!0))}catch{}if(l.set(h,k),!(y>=i))for(let R of E)try{let I=await Ct(h,R,r);if(!I||u.has(I)||Xe(I))continue;let b=await n(I);c.push({file:I,source:b,depth:y+1})}catch{}}return{graph:Al(e,l,s,(o.additionalEntries??[]).map(g=>g.file)),allSources:a}}function Al(e,t,n,r=[]){let o=new Map,i=[],s=new Map,a=[];for(let[l,c]of t){for(let[u,d]of c.elements)o.set(u,d);for(let u of c.regions)i.push(u);for(let[u,d]of c.fileIndex){let g=s.get(u)??[];s.set(u,[...g,...d])}if(l===e){a=c.rootKeys;continue}r.includes(l)&&(a=[...a,...c.rootKeys])}return{routeId:e,rootKeys:a,elements:o,regions:i,fileIndex:s,version:n}}function ni(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 l={key:n,writeTarget:i,boundaryKind:s,parentKey:r.parentKey,childKeys:[...r.childKeys],constraints:a};t.set(n,l)}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}),ri(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function ri(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(l=>l.kind===t)&&(a.constraints.push({kind:t,reason:n}),ri(s,t,n,r,o))}}import{isSiteEditRuntimeContainerTag as Ml,isSiteEditRuntimeVoidElementTag as Tl}from"@vcp-dev/contracts/site-edit-runtime-capability";function Ol(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(I=>({kind:I.kind,message:I.reason})),s=o.isOpaque,l=r.parentKey===null&&o.componentName==="Page",c=o.tag.toLowerCase(),u=o.tag!==c,d=!u&&Tl(c),g=u||Ml(c),h=u&&o.childKeys.length>0&&!o.isPublicUiComponent,S=o.textSegments.length>0&&o.textSegments.some(I=>I.editable);d&&!i.some(I=>I.kind==="void-element")&&i.push({kind:"void-element",message:`Element '${o.tag}' is void: children cannot be inserted`}),!d&&!g&&!i.some(I=>I.kind==="void-element")&&i.push({kind:"void-element",message:`Element '${o.tag}' cannot contain structured children`});let y=S&&!s,k=!o.isPublicUiComponent&&!d&&g&&(!s||h);return{key:e,canUpdateText:y,canInsertChild:k,canMove:!l,canRemove:!l,constraints:i}}function oi(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,Ol(r,e,t));return n}function Ll(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var jl=160;function ii(e,t,n,r={}){let o=[];for(let[i,s]of e.elements){let a=n.get(i),l={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:l})}return{routeId:e.routeId,version:e.version,rootKeys:[...e.rootKeys],entries:o}}function si(e,t,n,r,o,i,s,a,l,c,u,d){let g=t.elements.get(e),h=n.nodes.get(e),S=r.get(e);if(!g||!h||!S)throw new Error(`Node not found: ${e}`);let y=Bl(g.textSegments,s),k=Jl(e,t,g,S,y),E=y?_l(y):void 0,R=Xl(i,y),I=g.textSegments.map(L=>({index:L.index,value:L.value,editable:Vl(L,S,s?.get(L.index)??null),source:o.get(L.index)??null})),b=[],M=g.parentKey;for(;M;){let L=t.elements.get(M);if(!L)break;b.push({key:M,tag:L.tag,label:L.tag}),M=L.parentKey}b.reverse();let T=g.childKeys.map(L=>{let B=t.elements.get(L);return B?{key:L,tag:B.tag,label:B.tag}:null}).filter(L=>L!==null),J=[];if(g.parentKey){let L=t.elements.get(g.parentKey);if(L)for(let B of L.childKeys){if(B===e)continue;let te=t.elements.get(B);te&&J.push({key:B,tag:te.tag,label:te.tag})}}return{key:e,tag:g.tag,componentName:g.componentName,sourceFile:g.sourceFile,sourceLocator:Dl(g),label:g.tag,capabilities:k,writeTarget:i,effectiveWriteTarget:R,provenanceChain:E,componentSemantic:l,contentModel:c,mediaModel:u,styleSource:d,conditional:a,textSegments:I,boundaryKind:g.boundaryKind,isOpaque:g.isOpaque,ancestors:b,children:T,siblings:J}}function Dl(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:$l(e.sourceRange),structuralPath:e.identity.structuralPath,...Kl(e.textSegments)}}function $l(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function Kl(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,jl)}:{}}function ai(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 Bl(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function Jl(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,l=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"},c=r.canUpdateText&&li(l.mode);return{...r,canUpdateText:c,editModes:{updateText:l,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 Vl(e,t,n){return!e.editable||!t.canUpdateText?!1:n?li(n.editMode):!0}function li(e){return e==="direct"||e==="proxy"||e==="upstream"}function _l(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 Xl(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}:Ll(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 ci(e){let{key:t,element:n,graph:r,provenances:o}=e,i=Ul(t,n,r),s=i?.tag??(ze(n.tag)?n.tag:n.componentName),a=i?.identity.key??ui(n,r)??t,l=Gl(i),c=Yl(t,n,r,o,i),u=Wl(t,n,r,o,a);return{componentName:s,instanceKey:a,templateOwner:Hl(i??n,s),...l.length>0?{variantKeys:l}:{},...c.length>0?{slotKeys:c}:{},editableStrategy:u,impactScope:Zl(u),alternativeStrategies:ql(u)}}function Wl(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return ir(e,n)?"instance":!ze(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function ui(e,t){if(ze(e.tag))return e.identity.key;let n=[...t.elements.values()].filter(r=>r.importedFrom===e.sourceFile&&zl(r,e.componentName));return n.length!==1?null:n[0].identity.key}function Ul(e,t,n){if(ze(t.tag))return t;let r=ir(e,n);if(r)return r;let o=ui(t,n);return o?n.elements.get(o)??null:null}function zl(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function Hl(e,t){return ze(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function Gl(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 Yl(e,t,n,r,o){let i=new Set,s=ir(e,n);s&&o?.identity.key===s.identity.key&&i.add("children");for(let a of r.values()){let l=a?.chain.find(u=>u.kind==="component-prop");if(!l)continue;let c=l.displayName.split(".").pop();c&&i.add(c)}return i.size===0&&ze(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function ir(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(ze(r.tag))return r;n=r.parentKey}return null}function ze(e){return/^[A-Z]/.test(e)}function Zl(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function ql(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}var Ql=new Set(["markdown","body","content","value","document"]),di=[];function fi(e){if(!(!nc(e.tag)||!e.attributes))for(let t of e.attributes){if(!Ql.has(t.name))continue;if(tc(t))return{kind:"markdown",field:t.name,schema:"markdown",valuePath:t.source?.expression,operationBoundary:di};let n=ec(t.resolvedValue);if(n==="prosemirror-doc"||n==="node-array")return{kind:"rich-text-json",field:t.name,valuePath:t.source?.expression,schema:n,operationBoundary:di};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 ec(e){if(e){if(Array.isArray(e)&&e.every(t=>pi(t)))return"node-array";if(pi(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 pi(e){return!Array.isArray(e)&&typeof e=="object"&&e!==null}function tc(e){return e.name==="markdown"}function nc(e){return/^[A-Z]/.test(e)}var rc=["src","alt","poster","caption","width","height"];function mi(e){let t=e.attributes?.filter(i=>rc.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=ic(t.map(i=>i.value));return{kind:oc(e.tag,n),sourceType:o,fields:n,editableFields:[],operationBoundary:[],...Object.keys(r).length>0?{valuePaths:r}:{}}}function oc(e,t){return e==="img"?"image":e==="video"||t.includes("poster")?"video":"media"}function ic(e){return e.some(t=>t.startsWith("cms:"))?"cms-media-field":e.some(t=>/^(\.?\/|\/)/.test(t))?"local-file-reference":"asset-id"}var sr=["set-class-name-source","apply-style-draft"],hi=["block","inline-block","inline","flex","inline-flex","grid","inline-grid","hidden"],gi=["static","fixed","absolute","relative","sticky"],dr=["z-auto","z-0","z-10","z-20","z-30","z-40","z-50"],xi=["flex-row","flex-row-reverse","flex-col","flex-col-reverse"],yi=["flex-nowrap","flex-wrap","flex-wrap-reverse"],ar=["grow","grow-0"],lr=["shrink","shrink-0"],pr=["basis-auto","basis-full","basis-1/2","basis-1/3","basis-2/3","basis-1/4","basis-3/4","basis-px"],fr=["order-first","order-last","order-none","order-1","order-2","order-3","order-4","order-5","order-6"],mr=["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"],hr=["grid-rows-1","grid-rows-2","grid-rows-3","grid-rows-4","grid-rows-5","grid-rows-6","grid-rows-none","grid-rows-subgrid"],gr=["col-auto","col-span-1","col-span-2","col-span-3","col-span-4","col-span-6","col-span-12","col-span-full"],xr=["row-auto","row-span-1","row-span-2","row-span-3","row-span-4","row-span-6","row-span-full"],Si=["items-start","items-end","items-center","items-baseline","items-stretch"],bi=["justify-normal","justify-start","justify-end","justify-center","justify-between","justify-around","justify-evenly","justify-stretch"],vi=["overflow-auto","overflow-hidden","overflow-clip","overflow-visible","overflow-scroll"],cr=["font-sans","font-serif","font-mono"],yr=["font-thin","font-extralight","font-light","font-normal","font-medium","font-semibold","font-bold","font-extrabold","font-black"],Sr=["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"],br=["text-left","text-center","text-right","text-justify","text-start","text-end"],ki=["uppercase","lowercase","capitalize","normal-case"],Ci=["underline","overline","line-through","no-underline"],vr=["indent-0","indent-4","indent-8","indent-12"],Ei=["[writing-mode:horizontal-tb]","[writing-mode:vertical-rl]"],Ii=["whitespace-normal","whitespace-nowrap","whitespace-pre","whitespace-pre-line","whitespace-pre-wrap","whitespace-break-spaces"],Pi=["break-normal","break-words","break-all","break-keep"],kr=["line-clamp-none","line-clamp-1","line-clamp-2","line-clamp-3","line-clamp-4","line-clamp-5","line-clamp-6"],ur=["tracking-tighter","tracking-tight","tracking-normal","tracking-wide","tracking-wider","tracking-widest"],Cr=["border-solid","border-dashed","border-dotted","border-double","border-hidden","border-none"],Er=["border","border-0","border-2","border-4","border-8"],Ri=["object-contain","object-cover","object-fill","object-none","object-scale-down"],Ir=["aspect-auto","aspect-square","aspect-video"],Pr=["shadow-none","shadow-sm","shadow","shadow-md","shadow-lg","shadow-xl","shadow-2xl"],Fm=[{property:"display",exact:hi,isMatch:e=>e==="gallery-item",options:[...hi]},{property:"position",exact:gi,isMatch:e=>e==="cta-shine",options:[...gi]},{property:"top",isMatch:e=>sn("top",e)},{property:"right",isMatch:e=>sn("right",e)},{property:"bottom",isMatch:e=>sn("bottom",e)},{property:"left",isMatch:e=>sn("left",e)},{property:"zIndex",exact:dr,isMatch:mc,options:[...dr]},{property:"flexDirection",exact:xi,options:[...xi]},{property:"flexWrap",exact:yi,options:[...yi]},{property:"flexGrow",exact:ar,isMatch:e=>ar.includes(e)||/^grow-\[.+\]$/.test(e),options:[...ar]},{property:"flexShrink",exact:lr,isMatch:e=>lr.includes(e)||/^shrink-\[.+\]$/.test(e)||/^flex-shrink-(?:0|\[.+\])$/.test(e),options:[...lr]},{property:"flexBasis",exact:pr,isMatch:lc,options:[...pr]},{property:"flex",isMatch:e=>/^flex-(?:\d+|auto|initial|none|\[.+\])$/.test(e)},{property:"order",exact:fr,isMatch:cc,options:[...fr]},{property:"gridTemplateColumns",exact:mr,isMatch:uc,options:[...mr]},{property:"gridTemplateRows",exact:hr,isMatch:dc,options:[...hr]},{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:gr,isMatch:pc,options:[...gr]},{property:"gridRow",exact:xr,isMatch:fc,options:[...xr]},{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:Si,options:[...Si]},{property:"alignSelf",isMatch:e=>/^self-(?:auto|start|end|center|stretch|baseline)$/.test(e)},{property:"justifyContent",exact:bi,options:[...bi]},{property:"marginTop",prefix:"mt-",isMatch:e=>Le("m","t",e)},{property:"marginRight",prefix:"mr-",isMatch:e=>Le("m","r",e)},{property:"marginBottom",prefix:"mb-",isMatch:e=>Le("m","b",e)},{property:"marginLeft",prefix:"ml-",isMatch:e=>Le("m","l",e)},{property:"paddingTop",prefix:"pt-",isMatch:e=>Le("p","t",e)},{property:"paddingRight",prefix:"pr-",isMatch:e=>Le("p","r",e)},{property:"paddingBottom",prefix:"pb-",isMatch:e=>Le("p","b",e)},{property:"paddingLeft",prefix:"pl-",isMatch:e=>Le("p","l",e)},{property:"width",prefix:"w-",isMatch:e=>e.startsWith("w-")||wi(e)},{property:"height",prefix:"h-",isMatch:e=>e.startsWith("h-")||wi(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:vi,isMatch:e=>/^overflow(?:-[xy])?-.+$/.test(e),options:[...vi]},{property:"fontFamily",exact:cr,isMatch:e=>cr.includes(e)||/^font-\[.+\]$/.test(e)||/^font-[a-z][\w-]*$/.test(e)&&!bc(e),options:[...cr]},{property:"fontSize",exact:Sr,isMatch:Ni,options:[...Sr]},{property:"fontWeight",exact:yr,options:[...yr]},{property:"lineHeight",prefix:"leading-"},{property:"letterSpacing",exact:ur,isMatch:e=>ur.includes(e)||e.startsWith("tracking-["),options:[...ur]},{property:"textAlign",exact:br,options:[...br]},{property:"textTransform",exact:ki,options:[...ki]},{property:"textDecoration",exact:Ci,options:[...Ci]},{property:"textOverflow",exact:["truncate","text-ellipsis","text-clip"]},{property:"fontStyle",exact:["italic","not-italic"]},{property:"textUnderlineOffset",prefix:"underline-offset-"},{property:"textIndent",exact:vr,isMatch:xc,options:[...vr]},{property:"writingMode",exact:Ei,options:[...Ei]},{property:"whiteSpace",exact:Ii,options:[...Ii]},{property:"wordBreak",exact:Pi,options:[...Pi]},{property:"lineClamp",exact:kr,isMatch:gc,options:[...kr]},{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:sc},{property:"backgroundColor",isMatch:ac},{property:"backgroundImage",isMatch:e=>e.startsWith("bg-[url")||e.startsWith("bg-gradient-")},{property:"borderStyle",exact:Cr,options:[...Cr]},{property:"borderWidth",exact:Er,isMatch:Ai,options:[...Er]},{property:"divideWidth",isMatch:e=>/^divide-[xy](?:-\d+|-0|-reverse)?$/.test(e)},{property:"borderRadius",prefix:"rounded"},{property:"borderColor",isMatch:hc},{property:"divideColor",isMatch:e=>e.startsWith("divide-")&&!/^divide-[xy](?:-\d+|-0|-reverse)?$/.test(e)},{property:"objectFit",exact:Ri,options:[...Ri]},{property:"objectPosition",isMatch:e=>/^object-(?:bottom|center|left|left-bottom|left-top|right|right-bottom|right-top|top|\[.+\])$/.test(e)},{property:"aspectRatio",exact:Ir,isMatch:yc,options:[...Ir]},{property:"opacity",prefix:"opacity-"},{property:"boxShadow",exact:Pr,isMatch:Sc,options:[...Pr]},{property:"transform",isMatch:vc},{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 Fi(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:sr,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:sr,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:sr}}function Ni(e){return Sr.includes(e)||/^text-\[.+\]$/.test(e)&&!kc(e.slice(6,-1))}function sc(e){return!e.startsWith("text-")||br.includes(e)?!1:!Ni(e)}function ac(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 Ai(e){return Er.includes(e)||/^border-\[.+\]$/.test(e)||/^border-(?:x|y|t|r|b|l)(?:-\d+|-\[.+\])?$/.test(e)}function sn(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 lc(e){return pr.includes(e)||/^basis-\[.+\]$/.test(e)}function cc(e){return fr.includes(e)||/^-?order-(?:\d+|\[.+\])$/.test(e)}function uc(e){return mr.includes(e)||/^grid-cols-\[.+\]$/.test(e)}function dc(e){return hr.includes(e)||/^grid-rows-\[.+\]$/.test(e)}function pc(e){return gr.includes(e)||/^(?:col|col-span|col-start|col-end)-.+$/.test(e)}function fc(e){return xr.includes(e)||/^(?:row|row-span|row-start|row-end)-.+$/.test(e)}function mc(e){return dr.includes(e)||/^-?z-(?:\d+|\[.+\])$/.test(e)}function hc(e){return e.startsWith("border-")?!(Cr.includes(e)||Ai(e)||e.startsWith("border-spacing-")||/^border-(?:x|y|t|r|b|l)(?:-|$)/.test(e)):!1}function gc(e){return kr.includes(e)||/^line-clamp-\[.+\]$/.test(e)}function xc(e){return vr.includes(e)||/^-?indent-\[.+\]$/.test(e)}function yc(e){return Ir.includes(e)||/^aspect-\[.+\]$/.test(e)}function Sc(e){return Pr.includes(e)||/^shadow-(?:\[.+\]|[a-z][\w-]*)$/.test(e)}function bc(e){return yr.includes(e)}function Le(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 wi(e){return/^size-.+$/.test(e)}function vc(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 kc(e){return e.startsWith("#")||e.startsWith("rgb")||e.startsWith("hsl")||e.startsWith("oklch")||e.startsWith("color(")}import Ar from"@babel/traverse";function He(e,t,n,r){return{code:e,message:t,locatorKind:n,details:r}}function F(e,t,n,r,o){return{ok:!1,source:e,diagnostic:He(t,n,r,o)}}function Rr(e,t,n,r,o){return{ok:!1,source:e,diagnostic:He(t,n,r,o)}}import*as Mi from"@babel/parser";var Cc={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function at(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:Mi.parse(t,{sourceType:"module",plugins:Cc[n]})}}catch(r){return{ok:!1,source:t,diagnostic:He("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function wr(e,t){return at({source:e,profile:Ti(t.kind)})}function Fr(e,t){return at({source:e,profile:Ti(t)})}function Ti(e){return"next-app-entry"}function Nr(e){let{filePath:t,source:n}=e,r=t.toLowerCase().split(".").pop()??"";return r==="tsx"?"tsx-module":r==="ts"?"ts-module":r==="jsx"||r==="js"||r===""&&/<\w[\s\S]*>/.test(n)?"tsx-module":"next-app-entry"}var je=typeof Ar=="function"?Ar:Ar.default,an=new WeakMap,Oi=new WeakMap;function cn(e,t){let n=wr(e,t);if(!n.ok)return Rr(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=K(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}}:Rr(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function K(e,t){return t.kind==="jsx-node"?$i(e,t):t.kind==="jsx-attribute"?Fc(e,t):t.kind==="value"?Nc(e,t):t.kind==="expression"?Ac(e,t):t.kind==="directive"?Mc(e,t):t.kind==="export"?Tc(e,t):{ok:!1,diagnostic:He("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function $i(e,t){return t.strategy==="source-range"?Ec(e,t):Ic(e,t)}function Ec(e,t){let n=null;if(je(e,{JSXElement(o){if(!ln(o.node,t.sourceRange))return;let i=Q("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}}}),!n)return Z("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!Xc(r.path,t.expectedIdentity)?Z("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function Ic(e,t){if(t.structuralPath===""){let r=Rc(e,t.component);if(r){let o=wc(r);if(o)return o}}let n=null;return je(e,{JSXElement(r){if(Pt(r)!==t.component||Tr(r)!==t.structuralPath)return;let i=Q("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(Pt(r)!==t.component||Tr(r)!==t.structuralPath)return;let i=Q("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=Pc(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:Z("jsx-node","locator-miss","JSX node not found for structural-path locator")}function Pc(e,t,n){let r=null;return je(e,{JSXElement(o){if(Pt(o)!==t||!ln(o.node,n))return;let i=Q("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(Pt(o)!==t||!ln(o.node,n))return;let i=Q("jsx-node",o);i&&(r=i,o.stop())}}),r}function Rc(e,t){let n=null;return je(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 wc(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 Z("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?Z("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 Z("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function Fc(e,t){let n=$i(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(l=>Wc(l,t.name));if(!s||!s.isJSXAttribute())return Z("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=Q("jsx-attribute",s);return a?{ok:!0,match:a}:Z("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function Nc(e,t){let n=Oc(e,t);if(!n.ok)return n;let r=Lc(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!Fe(r.match.path.node.loc,t.expectedRange)?Z("value","locator-miss","Resolved value does not match expected range"):{ok:!0,match:r.match}:r}function Ac(e,t){let n=null;return je(e,{Identifier(r){if(!Bc(r))return;let o=ji(r);if(!o||!Di(o,t))return;let i=Q("expression",r);i&&(t.expectedRange&&!Fe(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=ji(r);if(!o||!Di(o,t))return;let i=Q("expression",r);i&&(t.expectedRange&&!Fe(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Z("expression","locator-miss","Expression not found")}function Mc(e,t){let n=null;return je(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!Fe(i.node.loc,t.expectedRange))return;let s=Q("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:Z("directive","locator-miss",`Directive '${t.value}' not found`)}function Tc(e,t){let n=null;return je(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let l=r.get("declaration");if(l.isFunctionDeclaration()&&l.node.id?.name==="generateMetadata"){let g=Q("export",l);if(!g||t.expectedRange&&!Fe(l.node.loc,t.expectedRange))return;n=g,r.stop();return}if(!l.isVariableDeclaration())return;let c=Or(l,"generateMetadata");if(!c||!c.isVariableDeclarator())return;let u=c.get("init");if(!u.node)return;let d=Q("export",u);if(!d||t.expectedRange&&!Fe(u.node.loc,t.expectedRange))return;n=d,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=Or(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!Fe(s.node.loc,t.expectedRange))return;let a=Q("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=Q("export",o);i&&(t.expectedRange&&!Fe(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Z("export","export-not-found",`Export '${_c(t)}' not found`)}function Oc(e,t){let n=null;return je(e,{Expression(r){if(n||t.root.kind!=="expression"||!ln(r.node,t.root.sourceRange))return;let o=Q("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 h=r.get("init");if(!h.node)return;let S=Q("value",h);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(h=>h?.type==="Identifier"&&h.name===o.name)!==0)return;let l=s.node.callee;if((l.type==="Identifier"?l.name:l.type==="MemberExpression"&&l.property.type==="Identifier"?l.property.name:null)!==o.hook)return;let u=o.hook==="useReducer"?1:0,d=r.get(`init.arguments.${u}`);if(!d||Array.isArray(d)||!d.node)return;let g=Q("value",d);g&&(n=g,r.stop())},ExportNamedDeclaration(r){if(n||t.root.kind!=="named-export")return;let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=Or(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=Q("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=Q("value",o);i&&(n=i,r.stop())}}),n?{ok:!0,match:n}:Z("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 Lc(e,t){let n=Mr(e);for(let o of t){if(n=Mr(n),o.kind==="property"){if(!n.isObjectExpression())return Z("value","unsupported-syntax","Property path requires object expression");let a=n.get("properties");if(a.some(c=>!c.isObjectProperty()))return Z("value","unsupported-syntax","Spread properties are not supported");let l=a.find(c=>Uc(c,o.name));if(!l||!l.isObjectProperty())return Z("value","property-not-found",`Property '${o.name}' not found`);n=l.get("value");continue}if(!n.isArrayExpression())return Z("value","unsupported-syntax","Array index path requires array expression");let i=n.get("elements");if(i.some(a=>a.node?.type==="SpreadElement"))return Z("value","unsupported-syntax","Spread array elements are not supported");let s=i[o.index];if(!s?.node)return Z("value","array-index-out-of-range",`Array index ${o.index} is out of range`);n=s}n=Mr(n);let r=Q("value",n);return r?{ok:!0,match:r}:Z("value","locator-miss","Resolved value has no source range")}function Mr(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function Q(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 ln(e,t){return Fe(e.loc,t)}function Fe(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 Tr(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!un(n.node)){let o=Ki(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${Li(n,o)}`):t.unshift(`${o}#${Li(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||Kc(n.parentPath))break;n=n.parentPath}return t.join("/")}function un(e){let t=e.openingElement.name;return t.type==="JSXIdentifier"?t.name==="Fragment":t.type==="JSXMemberExpression"&&t.property.name==="Fragment"}function Li(e,t){let n=jc(e);if(!n)return 0;let r=an.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=an.get(n.node)?.get(t);if(!i){let s=an.get(n.node);s||(s=new Map,an.set(n.node,s)),i=new WeakMap,s.set(t,i)}for(let s of It(n))if(Ki(s.node.openingElement)===t){if(i.set(s.node,o),s.node===e.node)return o;o++}return i.get(e.node)??0}function jc(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(un(t.node)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function It(e){let t=Oi.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(un(o.node)){n.push(...It(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...It(o));continue}o.isJSXExpressionContainer()&&n.push(...lt(o.get("expression")))}return Oi.set(e.node,n),n}function lt(e){return e.isJSXElement()?un(e.node)?It(e):[e]:e.isJSXFragment()?It(e):e.isParenthesizedExpression()?lt(e.get("expression")):e.isLogicalExpression()&&Dc(e.node.operator)?lt(e.get("right")):e.isConditionalExpression()?[...lt(e.get("consequent")),...lt(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:lt(t)):[]}function Dc(e){return e==="&&"||e==="||"||e==="??"}function Ki(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?$c(e.name):null}function $c(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 Pt(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 Kc(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function Bc(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function ji(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 Di(e,t){return e.base===t.base&&Jc(e.path,t.path??[])}function Jc(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 Vc(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function _c(e){return e.exportKind==="named"?e.name:e.exportKind}function Z(e,t,n,r){return{ok:!1,diagnostic:He(t,n,e,r)}}function Xc(e,t){return Pt(e)!==t.component?!1:Tr(e)===t.structuralPath}function Wc(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function Or(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function Uc(e,t){return e.isObjectProperty()?Vc(e.node)===t:!1}import{createHash as zc}from"node:crypto";var Rt=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 writeFile(t,n){this.files.set(t,n)}async deleteFile(t){this.files.delete(t)}async exists(t){return this.files.has(t)}getVersion(t){return this.versions.get(t)??0}bumpVersion(t){let n=this.getVersion(t)+1;return this.versions.set(t,n),n}getChangedFiles(){let t=new Set([...this.original.keys(),...this.files.keys()]),n=[];for(let r of[...t].sort()){let o=this.original.get(r),i=this.files.get(r);o!==i&&n.push({path:r,before:o,after:i})}return n}};function re(e){return`sha256:${zc("sha256").update(e).digest("hex")}`}var Lr="site-edit-classname-source@1";function Ji(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,valueRange:null,openingElementRange:{start:0,end:0},version:{documentVersion:e.route.graph.version,contentHash:re(e.route.source),parserVersion:Lr},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=Hc(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,valueRange:null,openingElementRange:{start:0,end:0},version:{documentVersion:e.route.graph.version,contentHash:re(e.route.source),parserVersion:Lr},diagnostics:[{code:"source-locator-warning",message:`Unable to locate JSX element for key ${t.identity.key}`}]};let r=n.openingElement,o=r.attributes.find(l=>l.type==="JSXAttribute"&&l.name.type==="JSXIdentifier"&&l.name.name==="className"),i={key:e.key,routeId:e.route.routeId,filePath:t.sourceFile,componentName:t.componentName,openingElementRange:jr(r),version:{documentVersion:e.route.graph.version,contentHash:re(e.route.source),parserVersion:Lr}};if(!o)return{...i,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,valueRange: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:Bi(e.route.source,o),valueRaw:s?Bi(e.route.source,s):null,attrRange:jr(o),valueRange:s?jr(s):null,diagnostics:[]}}function Vi(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,l=o?`${a<n.start?" ":""}${o}`:"";return t.slice(0,a)+l+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 Hc(e,t){let n=at({source:e,profile:Nr({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=K(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:Gc(t.sourceRange)});return!r.ok||r.match.node.type!=="JSXElement"?null:r.match.node}function _i(e){let t=at({source:`const __v = <div ${e} />;`,profile:"tsx-module"});if(!t.ok)return!1;let n=t.ast.program.body[0],o=(n?.type==="VariableDeclaration"?n.declarations[0]:null)?.init;if(o?.type!=="JSXElement")return!1;let i=o.openingElement.attributes;return i.length===1&&i[0]?.type==="JSXAttribute"&&i[0].name.type==="JSXIdentifier"&&i[0].name.name==="className"}function Bi(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function jr(e){if(e.start==null||e.end==null)throw new Error("AST node does not include offsets.");return{start:e.start,end:e.end,startLine:e.loc?.start.line,startColumn:e.loc?.start.column,endLine:e.loc?.end.line,endColumn:e.loc?.end.column}}function Gc(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}import Dr from"@babel/generator";var Yc=typeof Dr=="function"?Dr:Dr.default;function Zc(e){let t=e.split(`
2
- `),n=[],r=!1;for(let s of t){let a=s.match(/^(\s+)/);if(a){let l=a[1];l.includes(" ")?r=!0:l.length>0&&n.push(l.length)}}if(r&&t.every(a=>{let l=a.match(/^(\s+)/);return!l||l[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 qc(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 Qc(e,t){return e.split(`
3
- `).map(r=>qc(r,t)).join(`
4
- `)}function dn(e){let{ast:t,source:n}=e;try{let r=Zc(n),i=Yc(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=Qc(i,r)),{ok:!0,source:i}}catch(r){return F(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}import*as Wi from"@babel/parser";import{arrayExpression as eu,booleanLiteral as tu,identifier as nu,jsxAttribute as ru,jsxExpressionContainer as ou,jsxIdentifier as iu,nullLiteral as su,numericLiteral as au,objectExpression as lu,objectProperty as cu,stringLiteral as Ui}from"@babel/types";function Xi(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 wt(e,t,n){return{ok:!0,source:t,operation:{type:n.kind,nodeId:n.target,kind:n.kind,target:n.target,beforeSourceHash:Xi(e),afterSourceHash:Xi(t),inverse:n.inverse}}}function X(e,t,n){let r=dn({ast:e,source:t});return r.ok?wt(t,r.source,n):r}function q(e,t){let n=Fr(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function pn(e,t){return dn({ast:e,source:t})}function uu(e,t,n){let r=K(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function zi(e,t,n){let r=uu(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:F(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function Hi(e,t){let n=K(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 ct(e){return typeof e=="string"?Ui(e):typeof e=="number"?au(e):typeof e=="boolean"?tu(e):e===null?su():Array.isArray(e)?eu(e.map(t=>ct(t))):lu(Object.entries(e).map(([t,n])=>cu(nu(t),ct(n))))}function du(e){return typeof e=="string"?Ui(e):ou(ct(e))}function fn(e,t){return ru(iu(e),du(t))}function Gi(e,t){try{let r=Wi.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:F(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:F(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function mn(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=q(t,"jsx-node");if(!i.ok)return i.result;let s=K(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let l=pu(s.match.path)[r];if(!l)return F(t,"locator-miss",`Text segment ${r} not found`,"jsx-node");switch(l.kind){case"jsx-text":l.path.node.value=fu(l.path.node.value,o);break;case"string-literal":l.path.node.value=o;break;case"template-literal":{let c=l.quasiIndex;l.path.node.quasis[c].value.raw=o,l.path.node.quasis[c].value.cooked=o;break}}return X(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function pu(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=mu(r.get("expression"));o.length>0&&t.push(...o)}}return t}function fu(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function mu(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 $r}from"@babel/types";function hn(e){let{source:t,locator:n}=e,r=q(t,"jsx-node");if(!r.ok)return r.result;let o=K(r.ast,n);return o.ok?(hu(o.match.path),X(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function hu(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith($r());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith($r());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith($r());return}e.remove()}import{cloneNode as Pu}from"@babel/types";import Kr from"@babel/traverse";import*as N from"@babel/types";var gu=typeof Kr=="function"?Kr:Kr.default;function ue(e,t,n,r){if(!e.ok)return e;let o=ce(n);if(!o)return e;let i=xu(t,o,r);return i?{...e,selectionRef:i}:e}function xu(e,t,n){let r=yu(e,t);if(!r)return;let o=n.sourceLocator?Yi(n.sourceLocator):void 0,i=n.targetParentLocator?Yi(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??bu(r)??i?.component??o?.component;if(!(!s||!a))return{key:vt(s,a,vu(r))}}function Yi(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function yu(e,t){let n=null;return gu(e,{JSXElement(r){r.node===t&&(n=r,r.stop())}}),n}function ce(e){if(!e)return null;if(N.isJSXElement(e))return ut(e)?Zi(e.children):e;if(N.isJSXFragment(e))return Zi(e.children);if(N.isJSXExpressionContainer(e)||N.isParenthesizedExpression(e)||N.isTSAsExpression(e)||N.isTSSatisfiesExpression(e)||N.isTSTypeAssertion(e)||N.isTSNonNullExpression(e))return ce(e.expression);if(N.isLogicalExpression(e))return ce(e.right);if(N.isConditionalExpression(e))return ce(e.consequent)??ce(e.alternate);if(N.isCallExpression(e)||N.isOptionalCallExpression(e))return ns(e)?Su(e.arguments[0]):null;if(N.isArrayExpression(e))for(let t of e.elements){if(!t)continue;let n=ce(t);if(n)return n}return null}function Zi(e){for(let t of e){let n=ce(t);if(n)return n}return null}function Su(e){return!e||!N.isArrowFunctionExpression(e)&&!N.isFunctionExpression(e)?null:N.isBlockStatement(e.body)?Ft(e.body.body):ce(e.body)}function Ft(e){for(let t of e){if(N.isReturnStatement(t)){let n=ce(t.argument);if(n)return n;continue}if(N.isBlockStatement(t)){let n=Ft(t.body);if(n)return n;continue}if(N.isIfStatement(t)){let n=qi(t.consequent);if(n)return n;let r=t.alternate?qi(t.alternate):null;if(r)return r;continue}if(N.isSwitchStatement(t))for(let n of t.cases){let r=Ft(n.consequent);if(r)return r}}return null}function qi(e){return N.isBlockStatement(e)?Ft(e.body):Ft([e])}function bu(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(N.isFunctionDeclaration(n))return n.id?.name??"default"}if(t.isVariableDeclarator()&&N.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 Qi=new WeakMap,es=new WeakMap,Br=new WeakMap;function vu(e){let t=Qi.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=ku(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return Qi.set(e.node,o),o}function ku(e){let t=Jr(e.node.openingElement.name);return!t||ut(e.node)?null:/^[A-Z]/.test(t)?`component:${t}#${ts(e,t)}`:`${t}#${ts(e,t)}`}function ts(e,t){let n=Cu(e);if(!n)return 0;let r=Br.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Br.get(n.node);o||(o=new Map,Br.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of Ge(n))if(Jr(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 Cu(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(ut(t.node)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Ge(e){let t=es.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(ut(o.node)){n.push(...Ge(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Ge(o));continue}o.isJSXExpressionContainer()&&n.push(...Ne(o.get("expression")))}return es.set(e.node,n),n}function Ne(e){if(e.isJSXElement())return ut(e.node)?Ge(e):[e];if(e.isJSXFragment())return Ge(e);if(e.isParenthesizedExpression())return Ne(e.get("expression"));if(e.isLogicalExpression())return Ne(e.get("right"));if(e.isConditionalExpression())return[...Ne(e.get("consequent")),...Ne(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Ne(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&ns(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?Eu(n):[]}return[]}function Eu(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return ut(t.node)?Ge(t):[t];if(t.isJSXFragment())return Ge(t);if(t.isParenthesizedExpression())return Ne(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return Ne(t);if(!t.isBlockStatement())return[];for(let n of t.get("body")){if(!n.isReturnStatement())continue;let r=n.get("argument");return r.node?Ne(r):[]}return[]}function ns(e){let t=e.callee;return(N.isMemberExpression(t)||N.isOptionalMemberExpression(t))&&N.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function ut(e){let t=Jr(e.openingElement.name);return t==="Fragment"||t==="React.Fragment"}function Jr(e){return N.isJSXIdentifier(e)?e.name:N.isJSXMemberExpression(e)?rs(e):N.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function rs(e){return`${N.isJSXIdentifier(e.object)?e.object.name:rs(e.object)}.${e.property.name}`}function De(e,t){if(t.parentPath===e&&t.listKey==="children"&&os(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!os(n))return null;let r=n;for(;r&&r!==e;){if(!Iu(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function os(e){return e.isJSXElement()||e.isJSXFragment()}function Iu(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 gn(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=q(t,"jsx-node");if(!a.ok)return a.result;let l=K(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return F(t,"unsupported-syntax","insert-child target must be a JSXElement or JSXFragment","jsx-node");let c=l.match.path;if(l.match.path.isJSXElement()){let I=l.match.path.node;if(!I.closingElement||I.openingElement.selfClosing)return F(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=Gi(t,r.jsx);if(!u.ok)return u.result;let d=Pu(u.node,!0),g=c.node.children,h={...s,targetParentLocator:n},S=I=>s?ue(I,a.ast,d,h):I;if(o==="append")return g.push(d),S(X(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return g.unshift(d),S(X(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(!i)return F(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let y=K(a.ast,i);if(!y.ok)return{ok:!1,source:t,diagnostic:y.diagnostic};let k=De(l.match.path,y.match.path);if(!k)return F(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");c=k;let E=c.node.children,R=E.findIndex(I=>I===y.match.path.node);return R===-1?F(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(E.splice(o==="before"?R:R+1,0,d),S(X(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as is from"@babel/parser";import{cloneNode as Ru}from"@babel/types";function xn(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=q(t,"jsx-node");if(!a.ok)return a.result;let l=wu(t,r);if(!l.ok)return l.result;let c=K(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return F(t,"unsupported-syntax","insert-jsx-expression-child target must be a JSXElement or JSXFragment","jsx-node");if(c.match.path.isJSXElement()){let E=c.match.path.node;if(!E.closingElement||E.openingElement.selfClosing)return F(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=c.match.path,d=null;if(i){let E=K(a.ast,i);if(!E.ok)return{ok:!1,source:t,diagnostic:E.diagnostic};let R=De(c.match.path,E.match.path);if(!R)return F(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=R,d=E.match.path.node}else if(o==="before"||o==="after")return F(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let g=Ru(l.node,!0),h=u.node.children,S={...s,targetParentLocator:n},y=E=>s?ue(E,a.ast,g,S):E;if(o==="append")return h.push(g),y(X(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return h.unshift(g),y(X(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let k=h.findIndex(E=>E===d);return k===-1?F(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(h.splice(o==="before"?k:k+1,0,g),y(X(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function wu(e,t){try{let r=is.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:F(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:F(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as Fu,nullLiteral as Vr}from"@babel/types";import*as ss from"@babel/types";function yn(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=q(t,"jsx-node");if(!a.ok)return a.result;let l=K(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};let c=K(a.ast,r);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement())return F(t,"unsupported-syntax","move-node target parent must be a JSXElement","jsx-node");let u=c.match.path,d=c.match.path.node;if(!d.closingElement||d.openingElement.selfClosing)return F(t,"self-closing-element","Cannot move child into self-closing element","jsx-node");let g=null;if(i){let E=K(a.ast,i);if(!E.ok)return{ok:!1,source:t,diagnostic:E.diagnostic};let R=De(c.match.path,E.match.path);if(!R)return F(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=R,g=E.match.path.node}else if(o==="before"||o==="after")return F(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let h=Fu(l.match.path.node,!0);if(!ss.isJSXElement(h))return F(t,"unsupported-syntax","move-node source must resolve to a JSXElement","jsx-node");Nu(l.match.path);let S=u.node.children,y={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return S.push(h),ue(pn(a.ast,t),a.ast,h,y);if(o==="prepend")return S.unshift(h),ue(pn(a.ast,t),a.ast,h,y);let k=S.findIndex(E=>E===g);return k===-1?F(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(S.splice(o==="before"?k:k+1,0,h),ue(pn(a.ast,t),a.ast,h,y))}function Nu(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Vr());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Vr());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Vr());return}e.remove()}import*as as from"@babel/parser";import{cloneNode as Au,nullLiteral as _r}from"@babel/types";function Sn(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,l=q(t,"jsx-node");if(!l.ok)return l.result;let c=Mu(t,s);if(!c.ok)return c.result;let u=K(l.ast,n);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};let d=K(l.ast,r);if(!d.ok)return{ok:!1,source:t,diagnostic:d.diagnostic};if(!d.match.path.isJSXElement()&&!d.match.path.isJSXFragment())return F(t,"unsupported-syntax","move-repeat-template-child target parent must be a JSXElement or JSXFragment","jsx-node");if(d.match.path.isJSXElement()){let I=d.match.path.node;if(!I.closingElement||I.openingElement.selfClosing)return F(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let g=d.match.path,h=null;if(i){let I=K(l.ast,i);if(!I.ok)return{ok:!1,source:t,diagnostic:I.diagnostic};let b=De(d.match.path,I.match.path);if(!b)return F(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");g=b,h=I.match.path.node}else if(o==="before"||o==="after")return F(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!u.match.path.isJSXElement())return F(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let S=g.node,y=Au(c.node,!0);Tu(u.match.path);let k={...a,sourceLocator:n,targetParentLocator:r},E=S.children;if(o==="append")return E.push(y),ue(X(l.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),l.ast,y,k);if(o==="prepend")return E.unshift(y),ue(X(l.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),l.ast,y,k);let R=E.findIndex(I=>I===h);return R===-1?F(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(E.splice(o==="before"?R:R+1,0,y),ue(X(l.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),l.ast,y,k))}function Mu(e,t){try{let r=as.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:F(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:F(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function Tu(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(_r());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(_r());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(_r());return}e.remove()}function bn(e){let{source:t,locator:n,props:r}=e,o=q(t,"jsx-node");if(!o.ok)return o.result;let i=zi(o.ast,n,t);if(!i.ok)return i.result;let s=i.match.path.node.openingElement;for(let[a,l]of Object.entries(r)){if(l===void 0)continue;let c={kind:"jsx-attribute",element:n,name:a},u=Hi(o.ast,c);if(u.ok&&u.match!==null){let d=u.match.path.node;d.value=l===""?fn(a,"").value:fn(a,l).value}else s.attributes.push(fn(a,l))}return X(o.ast,t,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}import{getBindingIdentifiers as Ou,identifier as Nt,importDeclaration as Lu,importDefaultSpecifier as ju,importNamespaceSpecifier as Du,importSpecifier as $u,isImportDefaultSpecifier as ls,isImportNamespaceSpecifier as cs,isImportSpecifier as us,stringLiteral as Ku}from"@babel/types";function vn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(k=>!Hu(k));if(o!==-1){let k=r[o],E=k&&typeof k=="object"&&"kind"in k?k.kind:void 0;return F(t,"unsupported-syntax",`Unsupported import spec kind: ${String(E)}`)}let i=Wu(r);if(!i.ok)return F(t,"unsupported-syntax",i.message);let s=q(t);if(!s.ok)return s.result;let{ast:a}=s,l=a.program,c=l.body.filter(k=>k.type==="ImportDeclaration"&&k.source.value===n),u=new Set(c.flatMap(k=>k.specifiers.flatMap(E=>{let R=Gu(k,E);return R?[R]:[]}))),d=i.imports.filter(k=>!u.has(gs(k)));if(d.length===0)return wt(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let g=Uu(l.body),h=d.find(k=>g.has(Xr(k)));if(h)return F(t,"unsupported-syntax",`Import local binding already exists: ${Xr(h)}`);let S=Xu(d);if(S.reduce((k,E)=>k+E.length,0)!==d.length)return F(t,"unsupported-syntax","Unsupported import specifier grouping");for(let k of S){if(!ms(ps(k)))return F(t,"unsupported-syntax","Unsupported import specifier combination");let E=c.find(R=>Bu(R,k));if(E)Ju(E,k);else{let R=Lu(ds(k),Ku(n));zu(l.body,R),c.push(R)}}return X(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function Bu(e,t){return e.importKind==="type"?!1:ms(_u(Vu(e),ps(t)))}function Ju(e,t){let n=!1,r=new Set(e.specifiers.map(o=>Wr(o)));for(let o of ds(t)){let i=Wr(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return hs(e.specifiers),{changed:n}}function ds(e){let t=e.map(n=>{switch(n.kind){case"named":return $u(n.local?Nt(n.local):Nt(n.imported),Nt(n.imported));case"default":return ju(Nt(n.local));case"namespace":return Du(Nt(n.local));default:return n}});return hs(t),t}function ps(e){let t=fs();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 Vu(e){let t=fs();for(let n of e.specifiers)ls(n)?t.defaultLocals.add(n.local.name):cs(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function fs(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function _u(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function ms(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function hs(e){let t=[...e.filter(n=>ls(n)),...e.filter(n=>cs(n)),...e.filter(n=>us(n))];e.splice(0,e.length,...t)}function Xu(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=[],l=t[s],c=n[s];l&&a.push(l),c&&a.push(c),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 Wu(e){let t=new Map,n=new Map;for(let r of e){let o=gs(r);if(t.has(o))continue;let i=Xr(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 Uu(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(Ou(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 zu(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 Hu(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 gs(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 Xr(e){return e.kind==="named"?e.local??e.imported:e.local}function Gu(e,t){return e.importKind==="type"||us(t)&&t.importKind==="type"?null:Wr(t)}function Wr(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 kn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(u=>!Zu(u));if(o!==-1){let u=r[o],d=u&&typeof u=="object"&&"kind"in u?u.kind:void 0;return F(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(d)}`)}let i=q(t);if(!i.ok)return i.result;let{ast:s}=i,a=s.program,l=a.body.findIndex(u=>u.type==="ImportDeclaration"&&u.source.value===n);if(l===-1)return wt(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let c=a.body[l];return r.length===0?(a.body.splice(l,1),X(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(c.specifiers=c.specifiers.filter(u=>!r.some(d=>Yu(u,d))),c.specifiers.length===0&&a.body.splice(l,1),X(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function Yu(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 Zu(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 At(e){let{source:t,locator:n,next:r}=e,o=Pn(t,n);return o.ok?(o.path.replaceWith(ct(r)),X(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function Cn(e){let{source:t,locator:n,index:r,value:o}=e,i=Pn(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(s=>s?.type==="SpreadElement")?F(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>i.path.node.elements.length?F(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,0,ct(o)),X(i.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):F(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function En(e){let{source:t,locator:n,index:r}=e,o=Pn(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(i=>i?.type==="SpreadElement")?F(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=o.path.node.elements.length?F(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(o.path.node.elements.splice(r,1),X(o.ast,t,{kind:"remove-array-element",target:"value",inverse:"insert-array-element"})):F(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function In(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=Pn(t,n);if(!i.ok)return i.result;if(!i.path.isArrayExpression())return F(t,"unsupported-syntax","Array operations require array expression target","value");if(i.path.node.elements.some(l=>l?.type==="SpreadElement"))return F(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 F(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),X(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function Pn(e,t){let n=q(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=K(n.ast,t);return r.ok?{ok:!0,ast:n.ast,path:r.match.path}:{ok:!1,result:{ok:!1,source:e,diagnostic:r.diagnostic}}}import*as so from"@babel/parser";import Gr from"@babel/traverse";import*as f from"@babel/types";import*as Me from"node:path";import*as ks from"@babel/parser";import zr from"@babel/traverse";import*as dt from"@babel/types";import*as D from"@babel/types";function Fn(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?Rn(n,t):null}if(e.isMemberExpression()){let n=nd(e.node);if(!n)return null;let r=e.scope.getBinding(n);return r?Rn(r,t):null}return e.isAwaitExpression()||Ur(e.node)?Ye(od(e.node),t,"awaited or fetched expression"):null}function Rn(e,t=[]){let n=qu(e,t);if(n)return n;let r=Qu(e,t);if(r)return r;let o=ed(e,t);return o||null}function Tt(e){return e?.kind==="api-source"}function qu(e,t){if(e.path.isVariableDeclarator()&&D.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(l=>D.isObjectProperty(l)&&bs(l)==="data"&&Mt(l.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&ys(a.node))return Ye(e.identifier.name,t,"query hook data binding")}let n=td(e);if(!n||bs(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()||!ys(i.node)?null:Ye(e.identifier.name,t,"query hook data binding")}function Qu(e,t){if(e.path.isVariableDeclarator()&&D.isArrayPattern(e.path.node.id)){let a=e.path.get("init");if(!a?.isCallExpression()||!Ss(a.node))return null;let[l,c]=e.path.node.id.elements;return!D.isIdentifier(l)||l.name!==e.identifier.name||!D.isIdentifier(c)?null:xs(e,c.name)?Ye(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()||!Ss(o.node)||n.node.elements.findIndex(a=>a===e.path.node)!==0)return null;let s=n.node.elements[1];return D.isIdentifier(s)&&xs(e,s.name)?Ye(e.identifier.name,t,"state setter is updated by API data"):null}function ed(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()?Ye(e.identifier.name,t,"awaited binding result"):Ur(r.node)?Ye(e.identifier.name,t,"fetch-backed binding result"):null:null}function td(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 Mt(e,t){return D.isIdentifier(e)?e.name===t:D.isAssignmentPattern(e)?Mt(e.left,t):D.isObjectPattern(e)?e.properties.some(n=>D.isObjectProperty(n)?Mt(n.value,t):Mt(n.argument,t)):D.isArrayPattern(e)?e.elements.some(n=>!!n&&Mt(D.isRestElement(n)?n.argument:n,t)):!1}function xs(e,t){let n=!1,r=!1;return e.scope.path.traverse({CallExpression(i){Ur(i.node)&&(n=!0),(rd(i.node.callee,t)||i.node.arguments.some(s=>D.isIdentifier(s)&&s.name===t))&&(r=!0)}}),n&&r}function ys(e){let t=Nn(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function Ss(e){return Nn(e.callee)==="useState"}function Ur(e){return wn(e,t=>D.isCallExpression(t)&&Nn(t.callee)==="fetch")}function nd(e){let t=e;for(;D.isMemberExpression(t);)t=t.object;return D.isIdentifier(t)?t.name:null}function bs(e){return e.computed?null:D.isIdentifier(e.key)?e.key.name:D.isStringLiteral(e.key)?e.key.value:null}function Nn(e){return D.isIdentifier(e)?e.name:D.isMemberExpression(e)&&D.isIdentifier(e.property)?e.property.name:null}function rd(e,t){return wn(e,n=>D.isIdentifier(n)&&n.name===t)}function wn(e,t){if(t(e))return!0;let n=D.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(D.isNode(i)&&wn(i,t))return!0;continue}if(D.isNode(o)&&wn(o,t))return!0}return!1}function od(e){return D.isIdentifier(e)?e.name:D.isCallExpression(e)?Nn(e.callee)??"api":D.isAwaitExpression(e)?"awaited-api":"api"}function Ye(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:id(e,t),reason:n}}function id(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var Cs=typeof zr=="function"?zr:zr.default;function Es(e,t){let n=Ps(e);if(!n)return{allowed:!0};let r=!1;return Cs(n,{CallExpression(o){if(!Rs(o.node,t.sourceRange)||!sd(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||Tt(Fn(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function Is(e,t){let n=Ps(e);if(!n)return{allowed:!0};let r=!1;return Cs(n,{JSXExpressionContainer(o){Rs(o.node,t.sourceRange)&&(dt.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 Ps(e){try{return ks.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function sd(e){let t=e.callee;return dt.isMemberExpression(t)&&dt.isIdentifier(t.property)&&t.property.name==="map"}function Rs(e,t){let n=e.loc;return n?vs({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&vs({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function vs(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 H from"@babel/types";function ws(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 Se(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return pt(e.path.node,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(ld(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function pt(e,t,n=!1){return H.isIdentifier(e)?e.name===t&&n:H.isObjectPattern(e)?e.properties.some(r=>H.isObjectProperty(r)?pt(r.value,t,n):pt(r.argument,t,n)):H.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=H.isRestElement(r)?r.argument:r;return pt(o,t,n)}):H.isAssignmentPattern(e)?pt(e.left,t,!0):H.isRestElement(e)?pt(e.argument,t,n):!1}function ft(e,t){if(e.path.isObjectPattern()){if(t){let r=be(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:Se(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:Se(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isIdentifier()){let o=r.scope.getBinding(r.node.name),i=!1,s=o&&Hr(o)?(i=Se(o),[]):o?(()=>{let l=ft(o,{kind:"identifier",expression:r.node.name,base:r.node.name,path:[]});return i=l?.hasDefault??!1,l?[{kind:"property",name:l.propName},...l.remainingPath]:null})():null,a=be(e.path.node.id,e.identifier.name);if(s&&a){let l=[...s,...a],[c,...u]=l;return!c||c.kind!=="property"?null:{propName:c.name,remainingPath:[...u,...t?.path??[]],hasDefault:i||Se(e)}}}}let n=dd(e);if(n){let r=ad(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||Se(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=cd(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:Se(e)}}let i=An(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:Se(e)}:null}if(Hr(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:Se(e)}}return null}function ad(e,t){let n=e.findParent(l=>l.isVariableDeclarator());if(!n?.isVariableDeclarator())return null;let r=n.get("init");if(!r?.isIdentifier())return null;let o=r.scope.getBinding(r.node.name);if(!o)return null;let i=!1,s=Hr(o)?(i=Se(o),[]):(()=>{let l=ft(o,{kind:"identifier",expression:r.node.name,base:r.node.name,path:[]});return i=l?.hasDefault??!1,l?[{kind:"property",name:l.propName},...l.remainingPath]:null})();if(!s)return null;let a=be(n.node.id,t.identifier.name);return a?{path:[...s,...a],hasDefault:i||Se(t)}:null}function Hr(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function ld(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function cd(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=be(i.node,t);if(a)return a}return null}function Fs(e,t,n){if(e.path.isObjectPattern())for(let a of e.path.get("properties")){if(!a.isObjectProperty())continue;let l=An(a.node);if(!l||n&&l!==n)continue;let c=a.get("value");if(!c.isAssignmentPattern())continue;let u=c.get("right");if(u.isExpression())return{propName:l,componentName:t,expressionPath:u,displayPath:`${t}.${l}.default`}}let r=ud(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=An(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 be(e,t,n=[]){if(H.isIdentifier(e))return e.name===t?n:null;if(H.isObjectPattern(e)){for(let r of e.properties)if(H.isObjectProperty(r)){let o=An(r);if(!o)continue;let i=be(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(H.isRestElement(r)){let o=be(r.argument,t,n);if(o)return o}}if(H.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=H.isRestElement(o)?o.argument:o,s=be(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return H.isAssignmentPattern(e)?be(e.left,t,n):null}function ud(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function dd(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 An(e){return e.computed?null:H.isIdentifier(e.key)?e.key.name:H.isStringLiteral(e.key)?e.key.value:null}var Ve=typeof Gr=="function"?Gr:Gr.default;function W(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 mt(e){return{file:e.file,component:e.component}}function pd(e){return e.target.kind==="node"?e.target.key:null}function eo(e,t){let n=Me.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Me.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Yr(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=cn(n,W(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function ao(e){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 pe(e){try{return so.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function fd(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function md(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 V(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function Qe(e,t){let n=V(e);return!!(n&&fe(t,n))}function fe(e,t){return t.start>=e.start&&t.end<=e.end}function Xs(e){if(f.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(f.isJSXMemberExpression(e)){let t=e;for(;f.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function hd(e,t){let n=V(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);if(!a||Qe(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=Xs(i.node.name);s&&o(s,i)}}),[...r].sort()}function Ns(e,t,n){let r=pe(e);if(!r)return{ok:!0};let o=K(r,W(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=K(r,W(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};if(ia(o.match.path,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let s=hd(o.match.path,i.match.path);return s.length>0?{ok:!1,bindingNames:s}:{ok:!0}}function As(e,t,n){let r=$e(t,n);return r?Ae(e,r):null}function $e(e,t){let n=K(e,W(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:io(e,t)}function Ae(e,t){let n=t.findParent(y=>y.isArrowFunctionExpression()||y.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(y=>y===r.node)!==0)return null;let a=i.get("callee");if(!a.isMemberExpression()&&!a.isOptionalMemberExpression())return null;let l=a.node,c=l.property;if(!f.isIdentifier(c)||c.name!=="map"||l.computed)return null;let u=a.get("object"),d=jn(e,u.node),g=r.node.params.map(y=>jn(e,y)),h=V(i.node),S=V(r.node);return!d||g.some(y=>y.length===0)||!h||!S?null:{callStart:h.start,callEnd:h.end,callbackStart:S.start,callbackEnd:S.end,collectionExpression:d,callbackParams:g,mapOperator:f.isOptionalMemberExpression(l)&&l.optional?"?.map":".map",collectionNeedsParens:po(u.node),callbackPath:r,collectionPath:u}}function jn(e,t){let n=V(t);return n?e.slice(n.start,n.end):""}function Mn(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function gd(e,t){let n=V(e.node);return n?xd(t).some(r=>{let o=V(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function xd(e){let t=e.callbackPath.node.body;return f.isBlockStatement(t)?Ke(t.body):Je(t)}function Ke(e){let t=[];for(let n of e){if(f.isReturnStatement(n)){n.argument&&t.push(...Je(n.argument));continue}if(f.isBlockStatement(n)){t.push(...Ke(n.body));continue}if(f.isIfStatement(n)){let r=f.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...Ke(r)),n.alternate){let o=f.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...Ke(o))}continue}if(f.isSwitchStatement(n)){for(let r of n.cases)t.push(...Ke(r.consequent));continue}f.isTryStatement(n)&&(t.push(...Ke(n.block.body)),n.handler&&t.push(...Ke(n.handler.body.body)),n.finalizer&&t.push(...Ke(n.finalizer.body)))}return t}function Je(e){return f.isJSXElement(e)?yd(e)?Ms(e.children):[e]:f.isJSXFragment(e)?Ms(e.children):f.isParenthesizedExpression(e)||f.isTSAsExpression(e)||f.isTSSatisfiesExpression(e)||f.isTSNonNullExpression(e)||f.isTSTypeAssertion(e)?Je(e.expression):f.isConditionalExpression(e)?[...Je(e.consequent),...Je(e.alternate)]:f.isLogicalExpression(e)&&aa(e.operator)?Je(e.right):[]}function Ms(e){return e.flatMap(t=>f.isJSXElement(t)||f.isJSXFragment(t)?Je(t):f.isJSXExpressionContainer(t)&&(f.isJSXElement(t.expression)||f.isJSXFragment(t.expression)||f.isConditionalExpression(t.expression)||f.isLogicalExpression(t.expression))?Je(t.expression):[])}function yd(e){let t=e.openingElement.name;return f.isJSXIdentifier(t)?t.name==="Fragment":f.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function Sd(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function Zr(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function Ts(e,t,n,r={}){if(!r.preserveConditionalBoundary&&ia(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=V(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(l=>uo(l)).map(l=>n.callbackPath.scope.getBinding(l)?.path.node).filter(Boolean)),s=new Set,a=(l,c)=>{let u=c.scope.getBinding(l);if(!u||Qe(u.path.node,o)||i.has(u.path.node))return;t.scope.getBinding(l)!==u&&s.add(l)};return e.traverse({ReferencedIdentifier(l){a(l.node.name,l)},JSXOpeningElement(l){let c=Xs(l.node.name);c&&a(c,l)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function Os(e,t,n){let r=V(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>uo(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return lo(e,s=>{let a=s.scope.getBinding(s.node.name);if(!a||Qe(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 bd(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>uo(a)).map(a=>e.callbackPath.scope.getBinding(a)?.path.node).filter(Boolean)),r=new Set,o=(a,l)=>{let c=l.scope.getBinding(a);if(!c||n.has(c.path.node))return;t.scope.getBinding(a)!==c&&r.add(a)},i=e.callbackPath.get("params"),s=Array.isArray(i)?i:[i];for(let a of s)a.traverse({ReferencedIdentifier(l){o(l.node.name,l)},TSTypeReference(l){let c=l.node.typeName;if(f.isIdentifier(c))o(c.name,l);else{let u=vd(c);u&&o(u,l)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function vd(e){let t=e;for(;f.isTSQualifiedName(t);)t=t.left;return f.isIdentifier(t)?t.name:null}function Ws(e,t){let n=V(e.node),r=new Set;return lo(e,o=>{let i=o.scope.getBinding(o.node.name);if(!i||n&&Qe(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 lo(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function kd(e){let t=Cd(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=la(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=jd({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=oa(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?po(o):!0}}}function Cd(e,t,n){let r=Hs(e,t);if(Gs(e,r),Ys(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 Ve(e,{JSXElement(s){na(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:co(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 Ed(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=>Ot(a.file)));if(!t.has(Ot(e.sourceFile))||!t.has(Ot(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(Ot(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=wd(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 l=pe(a.content);if(!l)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:l})}let o=Id(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let l=Us({ast:a.ast,file:a.file,sourceFile:e.sourceFile,sourceComponent:e.sourceComponent,componentIdentities:o});if(l.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(...l.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!me(s.file,e.targetFile)||co(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 Id(e,t){let n=new Map,r=i=>{let s=ht(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 Pd(i,n))o=r(s)||o}return[...n.values()]}function Pd(e,t){let n=[],r=Rd(e,t);for(let o of e.ast.program.body){if(f.isExportDefaultDeclaration(o)&&f.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=jt(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(f.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=Dt(e.file,o.source.value);for(let s of o.specifiers){if(f.isExportNamespaceSpecifier(s)){let c=Be(s.exported);for(let u of t.values())me(u.file,i)&&n.push({file:e.file,namespace:to(c,u.namespace),exportName:u.exportName});continue}if(!f.isExportSpecifier(s))continue;let a=Be(s.local),l=[...t.values()].filter(c=>me(c.file,i)&&Ze(c.namespace,a));if(l.length>0){let c=Be(s.exported);for(let u of l){let d=jt(u.namespace,a,c);d&&n.push({file:e.file,namespace:d,exportName:u.exportName})}continue}t.has(ht({file:i,exportName:a}))&&n.push({file:e.file,exportName:Be(s.exported)})}continue}if(f.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!f.isExportSpecifier(i))continue;let s=Be(i.local),a=r.get(s)??[];if(a.length>0){let l=Be(i.exported);n.push({file:e.file,exportName:l});for(let c of a){let u=jt(c.namespace,s,l);u&&n.push({file:e.file,namespace:u,exportName:c.exportName})}}}continue}if(f.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=Dt(e.file,o.source.value),s=o.exported;if(s){let a=Be(s);for(let l of t.values())me(l.file,i)&&n.push({file:e.file,namespace:to(a,l.namespace),exportName:l.exportName});continue}for(let a of t.values())me(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function to(e,t){return t?`${e}.${t}`:e}function Ze(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function jt(e,t,n){return!Ze(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function Rd(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(!f.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=Dt(e.file,i.source.value);for(let a of i.specifiers){if(f.isImportDefaultSpecifier(a)){let l=t.get(ht({file:s,exportName:"default"}));l&&r(a.local.name,l);let c=[...t.values()].filter(u=>me(u.file,s)&&Ze(u.namespace,"default"));for(let u of c){let d=jt(u.namespace,"default",a.local.name);d&&r(a.local.name,{...u,namespace:d})}continue}if(f.isImportSpecifier(a)){let l=Be(a.imported),c=[...t.values()].filter(d=>me(d.file,s)&&Ze(d.namespace,l));for(let d of c)r(a.local.name,d);let u=t.get(ht({file:s,exportName:l}));u&&r(a.local.name,u);continue}if(f.isImportNamespaceSpecifier(a))for(let l of t.values())me(l.file,s)&&r(a.local.name,{...l,namespace:to(a.local.name,l.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(f.isVariableDeclaration(i))for(let s of i.declarations){if(!f.isIdentifier(s.id)||!s.init)continue;let a=gt(s.init);if(!a||!f.isIdentifier(a))continue;let l=n.get(a.name)??[];if(l.length===0)continue;let c=n.get(s.id.name)??[],u=new Set(c.map(ht));for(let d of l){let g=jt(d.namespace,a.name,s.id.name),h=g?{...d,namespace:g}:d,S=ht(h);u.has(S)||(r(s.id.name,h),u.add(S),o=!0)}}}return n}function ht(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${ro(e.file)}#${t}`}function Be(e){return f.isIdentifier(e)?e.name:e.value}function wd(e,t){for(let n of e.program.body){if(f.isExportDefaultDeclaration(n)){let o=n.declaration;if((f.isFunctionDeclaration(o)||f.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(f.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!f.isExportNamedDeclaration(n))continue;let r=n.declaration;if((f.isFunctionDeclaration(r)||f.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(f.isVariableDeclaration(r)){for(let o of r.declarations)if(f.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!f.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:f.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function Us(e){let t=Fd(e),n=[],r=Ys(e.ast,t);return Ve(e.ast,{JSXElement(o){me(e.file,e.sourceFile)&&co(o)===e.sourceComponent||na(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function zs(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function Hs(e,t){let n=zs();return Ve(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function Fd(e){let t=zs();return me(e.file,e.sourceFile)&&Nd(t,Hs(e.ast,e.sourceComponent)),Ve(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=Dt(e.file,o),s=e.componentIdentities.filter(a=>me(a.file,i));if(s.length!==0)for(let a of r.specifiers){let l=n.scope.getBinding(a.local.name);if(l){if(f.isImportDefaultSpecifier(a)&&s.some(c=>c.exportName==="default")&&t.localBindings.add(l),f.isImportDefaultSpecifier(a)){let c=s.filter(u=>Ze(u.namespace,"default"));if(c.length>0){let u=t.namespaceMembers.get(l)??new Set;for(let d of c){let g=js(d,"default");g&&u.add(g)}t.namespaceMembers.set(l,u)}continue}if(f.isImportSpecifier(a)){let c=f.isIdentifier(a.imported)?a.imported.name:a.imported.value,u=s.filter(d=>Ze(d.namespace,c));if(u.length>0){let d=t.namespaceMembers.get(l)??new Set;for(let g of u){let h=js(g,c);h&&d.add(h)}t.namespaceMembers.set(l,d);continue}s.some(d=>!d.namespace&&d.exportName===c)&&t.localBindings.add(l);continue}if(f.isImportNamespaceSpecifier(a))for(let c of s){let u=c.namespace?`${c.namespace}.${c.exportName}`:c.exportName,d=t.namespaceMembers.get(l)??new Set;d.add(u),t.namespaceMembers.set(l,d)}}}}}),Gs(e.ast,t),t}function Nd(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 Gs(e,t){Ve(e,{VariableDeclarator(n){if(!n.node.init)return;let r=gt(n.node.init);if(r){if(f.isIdentifier(n.node.id)){let o=qe(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&no(t,i,o);return}if(f.isObjectPattern(n.node.id)){let o=qe(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&Qs(n.node.id,o.namespaceMembers,t,n)}}}})}function Ys(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return Ve(e,{ReferencedIdentifier(r){if(n){r.stop();return}Ad(r)||!r.isIdentifier()||!Zs(r,t)||Md(r,t)||Td(r)||(n=!0,r.stop())}}),n}function Ad(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 Zs(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)&&qe(r.node,t,r)?r:null}function Md(e,t){let n=e.findParent(l=>l.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!Ls(e,r))return!1;let o=Zs(e,t);if(!o)return!1;if(gt(r.node)===o.node)return!!qe(r.node,t,r);let s=e.findParent(l=>l.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&Ls(e,a)&&!!qe(a.node,t,a)}function Td(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function Ls(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function qe(e,t,n){let r=gt(e);if(!r)return null;if(f.isIdentifier(r)){let a=n.scope.getBinding(r.name);if(!a)return null;let l=t.namespaceMembers.get(a);return t.localBindings.has(a)?{local:!0,namespaceMembers:new Set,unsupported:!1}:l?{local:!1,namespaceMembers:new Set(l),unsupported:!1}:null}if(f.isObjectExpression(r))return Od(r,t,n);let o=ta(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?qs(s,o.slice(1).join(".")):null}function Od(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!f.isObjectProperty(i))continue;let s=ea(i);if(!s||!f.isExpression(i.value)){f.isExpression(i.value)&&(o||=qe(i.value,t,n)!==null);continue}let a=qe(i.value,t,n);if(a){o||=a.unsupported,a.local&&r.add(s);for(let l of a.namespaceMembers)r.add(`${s}.${l}`)}}return r.size>0||o?{local:!1,namespaceMembers:r,unsupported:o}:null}function qs(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 no(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 Qs(e,t,n,r){for(let o of e.properties){if(f.isRestElement(o)){if(f.isIdentifier(o.argument)){let l=r.scope.getBinding(o.argument.name);l&&no(n,l,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!f.isObjectProperty(o))continue;let i=ea(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=qs(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=f.isAssignmentPattern(o.value)?o.value.left:o.value;if(f.isIdentifier(a)){let l=r.scope.getBinding(a.name);l&&no(n,l,s);continue}if(f.isObjectPattern(a)&&s.namespaceMembers.size>0){Qs(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function ea(e){return e.computed?f.isStringLiteral(e.key)||f.isNumericLiteral(e.key)?String(e.key.value):null:Ld(e.key)}function Ld(e){return f.isIdentifier(e)?e.name:f.isStringLiteral(e)||f.isNumericLiteral(e)?String(e.value):null}function gt(e){return f.isParenthesizedExpression(e)||f.isTSAsExpression(e)||f.isTSSatisfiesExpression(e)||f.isTSNonNullExpression(e)||f.isTSTypeAssertion(e)?gt(e.expression):f.isExpression(e)?e:null}function ta(e){if(f.isIdentifier(e))return[e.name];if((f.isMemberExpression(e)||f.isOptionalMemberExpression(e))&&!e.computed&&f.isIdentifier(e.property)){let t=gt(e.object),n=t?ta(t):null;return n?[...n,e.property.name]:null}return null}function js(e,t){if(!Ze(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 na(e,t){let n=e.node.openingElement.name;if(f.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=ra(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 ra(e){if(f.isJSXIdentifier(e))return[e.name];if(f.isJSXMemberExpression(e)){let t=ra(e.object);return t?[...t,e.property.name]:null}return null}function co(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()&&f.isIdentifier(n.node.id))return n.node.id.name}return null}function jd(e){let t=V(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||Qe(a.path.node,t))return;let l=Kd(s,a,t);if(l){if(l.hasDefault){o="Cannot move prop-backed repeat child because the collection prop has a default value that cannot be preserved safely";return}let u=Jd(e.callSitePath,l.propName,e.source);if(!u.ok){o=u.reason;return}let d=Dd(u.expression,l.remainingPath);if(!d){o="Cannot move prop-backed repeat child because the mapped prop path is not a portable expression";return}let g=Ws(u.expressionPath,e.targetParentPath);if(!g.ok){o=g.reason??`Cannot move prop-backed repeat child because the mapped prop source is not visible at the target: ${g.bindingNames.join(", ")}`;return}n.set(`${l.range.start}:${l.range.end}`,{...l.range,text:d});return}e.targetParentPath.scope.getBinding(s.node.name)!==a&&r.add(s.node.name)};return e.sourceContext.collectionPath.isIdentifier()&&e.sourceContext.collectionPath.isReferencedIdentifier()&&i(e.sourceContext.collectionPath),e.sourceContext.collectionPath.traverse({ReferencedIdentifier(s){s.isIdentifier()&&i(s)}}),o?{ok:!1,reason:o}:r.size>0?{ok:!1,reason:`Cannot move prop-backed repeat child because the collection depends on bindings outside the target scope: ${[...r].sort().join(", ")}`}:n.size===0?{ok:!1,reason:"Cannot move repeat-backed child out of its component without an explicit prop mapping"}:{ok:!0,collectionExpression:Vd(e.source,t,[...n.values()])}}function Dd(e,t){if(t.length===0)return e;let n=oa(e);if(!n)return null;let r=po(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=$d(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function $d(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function Kd(e,t,n){let r=Bd(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=ft(t,o);if(!i)return null;let s=r?.range??V(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function Bd(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!Qe(n.node,t)||n.node.computed||!f.isIdentifier(n.node.property))return null;let r=V(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function Jd(e,t,n){let r=e.get("openingElement").get("attributes");if(r.some(l=>l.isJSXSpreadAttribute()))return{ok:!1,reason:"Cannot move prop-backed repeat child through spread props; use an explicit prop mapping"};let o=r.find(l=>l.isJSXAttribute()&&f.isJSXIdentifier(l.node.name)&&l.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=jn(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 Vd(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 oa(e){try{let n=so.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=f.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&f.isExpression(r)?r:null}catch{return null}}function _d(e){let t=V(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||Qe(s.path.node,t))return;let a=Ds(s,e.sourceFile,e.targetFile);if(a){let l=e.targetParentPath.scope.getBinding(a.localName);if(l){let u=Ds(l,e.targetFile,e.targetFile);(!u||u.moduleFile!==a.moduleFile||!Xd(u.importSpec,a.importSpec))&&r.add(a.localName);return}let c=n.get(a.moduleSpecifier)??[];c.some(u=>JSON.stringify(u)===JSON.stringify(a.importSpec))||c.push(a.importSpec),n.set(a.moduleSpecifier,c);return}r.add(i.node.name)};return lo(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 Xd(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 Ds(e,t,n){let r=Wd(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=Dt(t,i),a=i.startsWith(".")?eo(n,s):i;if(r.isImportDefaultSpecifier()){let l=r.node.local.name;return{localName:l,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"default",local:l}}}if(r.isImportNamespaceSpecifier()){let l=r.node.local.name;return{localName:l,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"namespace",local:l}}}if(r.isImportSpecifier()){let l=f.isIdentifier(r.node.imported)?r.node.imported.name:r.node.imported.value,c=r.node.local.name;return{localName:c,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"named",imported:l,local:c===l?void 0:c}}}return null}function Wd(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function Dt(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?Me.normalize(Me.join(Me.dirname(e),t)).replace(/\\/g,"/"):t}function me(e,t){return ro(e)===ro(t)}function ro(e){let t=Ot(e);return t.endsWith("/index")?t.slice(0,-6):t}function Ot(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function uo(e){let t=[],n=r=>{if(r){if(f.isIdentifier(r)){t.push(r.name);return}if(f.isObjectPattern(r)){for(let o of r.properties){if(f.isRestElement(o)){n(o.argument);continue}f.isObjectProperty(o)&&n(o.value)}return}if(f.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(f.isAssignmentPattern(r)){n(r.left);return}if(f.isRestElement(r)){n(r.argument);return}f.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function Ud(e){let t=[];for(let n of e.callbackPath.node.params){if(f.isIdentifier(n)){t.push(n.name);continue}if(f.isRestElement(n)&&f.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 zd(e,t){return{...e,callbackParams:t}}function $s(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function po(e){return!(f.isIdentifier(e)||f.isThisExpression(e)||f.isMemberExpression(e)||f.isOptionalMemberExpression(e)||f.isCallExpression(e)||f.isOptionalCallExpression(e))}function ia(e,t){return sa(e,t).length>0}function qr(e,t){let n=V(e.node),r=V(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()&&!Hd(o,n,r)))return!0;o=o.parentPath}return!1}function Hd(e,t,n){let r=V(e.node.consequent);if(r&&fe(r,t)&&!fe(r,n))return!1;let o=e.node.alternate?V(e.node.alternate):null;return!(o&&fe(o,t)&&!fe(o,n))}function sa(e,t){let n=V(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=V(o.node.consequent),a=V(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()&&aa(o.node.operator)){let s=V(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 Ks(e,t,n,r){let o=sa(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let l=jn(e,a.conditionPath.node);if(!l)return{sourceJsx:r,conditionPaths:[]};let c=Gd(a.conditionPath,l);if(s.push(a.conditionPath),a.kind==="logical"){i=`${c} ${a.operator} ${Zd(i)}`;continue}i=a.branch==="consequent"?`${c} ? ${i} : null`:`${c} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function Gd(e,t){return Yd(e.node)?t:`(${t})`}function Yd(e){return f.isIdentifier(e)||f.isThisExpression(e)||f.isSuper(e)||f.isMemberExpression(e)||f.isOptionalMemberExpression(e)||f.isCallExpression(e)||f.isOptionalCallExpression(e)||f.isBooleanLiteral(e)||f.isNumericLiteral(e)||f.isStringLiteral(e)||f.isNullLiteral(e)||f.isUnaryExpression(e)}function aa(e){return e==="&&"||e==="||"||e==="??"}function Zd(e){return e.trim().startsWith("<")?e:`(${e})`}function la(e,t){let n=V(e.node),r=V(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=Bs(e),i=Bs(t);if(!o||!i||!qd(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=Qd(s.node,n);if(a&&!fe(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=V(s.node.right);if(a&&fe(a,n)&&!fe(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())&&ep(s)){let a=V(s.node.body)??V(s.node);if(a&&!fe(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 Bs(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?V(t.node.argument):null;if(t.isArrowFunctionExpression()&&(f.isJSXElement(t.node.body)||f.isJSXFragment(t.node.body)||f.isConditionalExpression(t.node.body)||f.isLogicalExpression(t.node.body)))return V(t.node.body);t=t.parentPath}return null}function qd(e,t){return e.start===t.start&&e.end===t.end}function Qd(e,t){let n=V(e.consequent);if(n&&fe(n,t))return n;let r=V(e.alternate);return r&&fe(r,t)?r:null}function ep(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(f.isMemberExpression(n)||f.isOptionalMemberExpression(n))&&f.isIdentifier(n.property)&&n.property.name==="map"&&!n.computed}var tp={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 Tn(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=tp[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 np(e,t){for(let n of e.program.body){if(!f.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>f.isImportDefaultSpecifier(o));if(r&&f.isImportDefaultSpecifier(r))return r.local.name}return null}function rp(e){let t=new Set;return Ve(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function op(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function ip(e,t){let n=ao(e);if(e.component.exportName!=="default")return{localName:n,importStep:Qr(e,n)};let r=pe(t);if(!r)return{localName:n,importStep:Qr(e,n)};let o=np(r,e.component.source);if(o)return{localName:o};let i=op(n,rp(r));return{localName:i,importStep:Qr(e,i)}}function sp(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??ao(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 ap(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};let t=e.props?lp(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function lp(e){return Object.fromEntries(Object.entries(e).filter(t=>oo(t[1])))}function oo(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(oo):typeof e=="object"?Object.values(e).every(oo):!1}function cp(e,t){let n=pe(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=Us({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 Qr(e,t=ao(e)){return{moduleSpecifier:e.component.source,imports:e.component.exportName==="default"?[{kind:"default",local:t}]:[{kind:"named",imported:e.component.exportName}]}}function Js(e,t){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 up(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function On(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function fo(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function Lt(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:fo(e,t.slice(0,n)),index:r.index}}return null}function Vs(e,t){return e.locator?e.collectionPathMap?.[t]?fo(e.locator,e.collectionPathMap[t]):Lt(e.locator)?pp(e.locator,fp(t,e.collectionIndexMap)):null:null}function dp(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:ca(o,t)}function ca(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=ca(r,t);return o===void 0?void 0:{[n.name]:o}}function Ln(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 pp(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},fo(e,i)}return null}function fp(e,t){return t?.[e]??e}function _s(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 mp(e,t){return hp(e.root,t.root)&&xp(e.path??[],t.path??[])}function hp(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&&gp(e.sourceRange,t.sourceRange)}}function gp(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function io(e,t){let n=null;return Ve(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 xp(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 Dn=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:On(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"remove-node":{if(t.params.kind!=="remove-node")return{ok:!1,errorCode:"unknown",reason:On(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:On(t.kind,t.params.kind)};let r=t,o=Js(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:On(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=pd(t);if(!n)return{ok:!1,result:{ok:!1,errorCode:"invalid-target",reason:`Operation '${t.kind}' requires a node target`}};let r=this.graph.getNode(n);return r?{ok:!0,node:r}:{ok:!1,result:{ok:!1,errorCode:"locator-miss",reason:`Target key '${n}' not found in graph`}}}planNodeAttributeOperation(t,n,r){let o=r.file,i=this.graph.getCapability(r.key);return n.params.filePath!==o?{ok:!1,errorCode:"stale-version",reason:"The className source file changed before save."}:this.buildPlan(t,n,[{order:0,file:o,type:"set-class-name-source",request:{...n.params,key:r.key}}],i)}async planSetProps(t,n,r){let o=this.graph.getCapability(r.key),i=await this.buildSetPropsSteps({initialOrder:0,node:r,props:n.params.props,request:n});return i.ok?this.buildPlan(t,n,i.steps,o):i}async planApplyStyleDraft(t,n,r){let o=r.file,i=this.graph.getCapability(r.key),s=[];if(n.params.className){if(n.params.className.filePath!==o)return{ok:!1,errorCode:"stale-version",reason:"The className source file changed before save."};s.push({order:s.length,file:o,type:"set-class-name-source",request:{kind:"set-class-name-source",...n.params.className,key:r.key}})}if(n.params.props){let a=await this.buildSetPropsSteps({initialOrder:s.length,node:r,props:n.params.props,request:n});if(!a.ok)return a;s.push(...a.steps)}return this.buildPlan(t,n,s,i)}async buildSetPropsSteps(t){let{initialOrder:n,node:r,props:o,request:i}=t,s=r.file,a=[],l={};for(let[c,u]of Object.entries(o)){if(u===void 0)continue;let d=await this.graph.getElementPropertyWriteTarget?.(r.key,c);if(d?.kind==="value-binding"&&d.locator){let g=d.locator;if(d.sourceKind==="repeat-template"&&typeof i.selectionRef?.instanceIndex=="number"){let h=Vs(d,i.selectionRef.instanceIndex);if(!h)return{ok:!1,errorCode:"invalid-params",reason:"set-props could not resolve the selected repeat item"};g=h}a.push({order:n+a.length,file:d.file,type:"update-value",locator:g,value:u});continue}l[c]=u}return Object.keys(l).length>0&&a.push({order:n+a.length,file:s,type:"set-props",locator:W(r),props:l}),{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=Vs(o,i.instanceIndex);if(!a)return{ok:!1,errorCode:"invalid-params",reason:"update-text could not resolve the selected repeat item"};let l=this.coerceTextValueForValueTarget(o.file,a,r);return l.ok?{ok:!0,steps:[{order:0,file:o.file,type:"update-array-item",locator:a,value:l.value}]}:l}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:W(t),segmentIndex:n,newText:r}]}}coerceTextValueForValueTarget(t,n,r){let o=this.graph.getFileContent(t),i=pe(o);if(!i)return{ok:!1,errorCode:"invalid-params",reason:"update-text could not inspect the value source"};let s=K(i,n);if(!s.ok)return{ok:!1,errorCode:"invalid-params",reason:"update-text could not resolve the value source"};if(!fd(s.match.path))return{ok:!0,value:r};let a=md(r);return a===null?{ok:!1,errorCode:"invalid-params",reason:"update-text value must be a valid number for numeric source"}:{ok:!0,value:a}}planUpdateText(t,n,r,o,i){if(!o.canUpdateText)return{ok:!1,errorCode:"capability-denied",reason:"Cannot update text on this node"};let s=this.buildTextRewriteSteps(r,n.params.segmentIndex,n.params.value,i,n.selectionRef);return s.ok?this.buildPlan(t,n,s.steps,o):s}async planRemoveNode(t,n,r,o){if(!o.canRemove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot remove this node"};let i=await this.graph.getTextWriteTarget(r.key,0);if(i?.kind==="external-entry")return this.buildPlan(t,n,[{order:0,file:`external:${i.sourceId}`,type:"invoke-external-adapter",sourceType:i.sourceType,sourceId:i.sourceId,adapterId:i.adapterId,capability:"remove-node",value:{operation:"remove-node"}}],o);if(r.isRepeatItemRoot){let d=i;if(d?.kind==="value-binding"&&d.locator){let g=Lt(d.locator);if(g)return this.buildPlan(t,n,[{order:0,file:d.file,type:"remove-bound-array-item",locator:g.locator,index:g.index}],o)}return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed node removal requires a writable array target"}}let s=Ln(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 l=await this.getUpstreamBackedDescendantReason(r);if(l)return{ok:!1,errorCode:"unsupported-operation",reason:l};let c=[{order:0,file:r.file,type:"remove-node",locator:W(r),removeWhitespace:!0}],u=this.buildRemoveComponentImportStep(r);return u&&c.push({...u,order:c.length}),this.buildPlan(t,n,c,o)}buildRemoveComponentImportStep(t,n=this.graph.getFileContent(t.file)){if(!t.importedFrom||!t.exportName||!t.tag||cp(n,t)>1)return null;let r=eo(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(!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,l=Ln(r,a,s!==null?this.graph.getTextProvenance?.(r.key,s)??null:null);if(l)return{ok:!1,errorCode:"unsupported-operation",reason:l};let c=await this.getUpstreamBackedDescendantReason(r);if(c)return{ok:!1,errorCode:"unsupported-operation",reason:c};let u=await this.planExternalBackedInsertChild(t,n,r,o,i,a);if(u)return u;let d=await this.planRepeatBackedInsertChild(t,n,r,o);if(d)return d;let g=this.getRepeatBackedTemplateStructureReason(r);if(g)return{ok:!1,errorCode:"unsupported-operation",reason:g};let h=Es(this.graph.getFileContent(r.file),r);if(!h.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:h.reason??"Cannot insert child into this node"};let S=Tn(r,n.params.node);if(S)return{ok:!1,errorCode:"unsupported-operation",reason:S};let y=[],k=0,E=n.params.node.kind==="component-call"?ip(n.params.node,this.graph.getFileContent(r.file)):void 0,R=E?.importStep;return R&&y.push({order:k++,file:r.file,type:"add-import",moduleSpecifier:R.moduleSpecifier,imports:R.imports}),y.push({order:k++,file:r.file,type:"insert-child",parentLocator:W(r),node:{jsx:sp(n.params.node,E?.localName)},placement:n.params.position.relation,anchorLocator:i?W(i):void 0}),this.buildPlan(t,n,y,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){let a=s?.kind==="external-entry"?s:await this.findExternalInsertContext(r,i);if(!a)return null;let l=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:l?.kind==="external-entry"?l.sourceId:null,node:ap(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(n.params.position.relation!=="append"&&n.params.position.relation!=="prepend")return null;let i=n.params.node;if(i.kind!=="native-tag"||i.text===void 0||!this.graph.getChildNodes)return null;let s=this.graph.getChildNodes(r.key).find(d=>d.isRepeatItemRoot&&d.tag?.toLowerCase()===i.tag.toLowerCase());if(!s)return null;let a=await this.graph.getTextWriteTarget(s.key,0);if(!a||a.kind!=="value-binding"||!a.locator)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires a writable value target"};let l=Lt(a.locator);if(!l)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let c=dp(a.locator,i.text);if(c===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"?_s(0,a.collectionIndexMap):_s(a.collectionIndexMap?.length??l.index+1,a.collectionIndexMap);return this.buildPlan(t,n,[{order:0,file:a.file,type:"insert-bound-array-item",locator:l.locator,index:u,value:c}],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=Ln(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=pe(this.graph.getFileContent(t.file));if(!n)return t.isRepeatItemRoot===!0;let r=K(n,W(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:io(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=Ae(this.graph.getFileContent(t.file),o);return i?gd(o,i):t.isRepeatItemRoot===!0}isInsideMapCallback(t){let n=pe(this.graph.getFileContent(t.file));if(!n)return!1;let r=K(n,W(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:io(n,t);return o?!!o.findParent(i=>{if(!i.isCallExpression()&&!i.isOptionalCallExpression())return!1;let s=i.node.callee;return(f.isMemberExpression(s)||f.isOptionalMemberExpression(s))&&f.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 l=this.graph.getFileContent(r.file),c=pe(l);if(!c)return null;let u=$e(c,r),d=$e(c,o);if(!u||!d)return null;let g=Ae(l,u),h=Ae(l,d);if(!Mn(g,h))return null;if(a&&(s==="before"||s==="after")){let y=$e(c,a),k=y?Ae(l,y):null;if(!Mn(g,k))return null}if(qr(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let S=Ns(l,r,o);return S.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:W(r),targetParentLocator:W(o),placement:s,anchorLocator:a?W(a):void 0,selectionContext:mt(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 l=this.graph.getFileContent(r.file),c=pe(l);if(!c)return null;let u=$e(c,r),d=$e(c,o);if(!u||!d)return null;let g=Ae(l,u);if(!g)return null;let h=Ae(l,d);if(Mn(g,h))return null;if(h&&!Sd(h,g))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")){let I=As(l,c,a);if(h&&!Mn(h,I)||!h&&I)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 I=Tn(o,{kind:"native-tag",tag:r.tag});if(I)return{ok:!1,errorCode:"unsupported-operation",reason:I}}let S=Yr(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(qr(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let y=Ks(l,u,d,S);for(let I of y.conditionPaths){let b=Os(I,d,g);if(!b.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${b.bindingNames.join(", ")}`}}let k=Ts(u,d,g,{preserveConditionalBoundary:y.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 E=bd(g,d);if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its callback parameters depend on bindings outside the target scope: ${E.bindingNames.join(", ")}`};let R=g;if(r.component!==o.component){let I=kd({source:l,ast:c,sourceContext:g,sourceNode:r,targetParent:o,targetParentPath:d});if(!I.ok)return{ok:!1,errorCode:"unsupported-operation",reason:I.reason};R=I.context}else{let I=Ws(g.collectionPath,d);if(!I.ok)return{ok:!1,errorCode:"unsupported-operation",reason:I.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${I.bindingNames.join(", ")}`}}return this.buildPlan(t,n,[{order:0,file:r.file,type:"move-repeat-template-child",locator:W(r),targetParentLocator:W(o),placement:s,anchorLocator:a?W(a):void 0,repeatExpression:$s(R,y.sourceJsx),selectionContext:mt(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&this.isRepeatTemplateRootNode(r)||r.file===o.file)return null;let l=this.graph.getFileContent(r.file),c=this.graph.getFileContent(o.file),u=pe(l),d=pe(c);if(!u||!d)return null;let g=Ed({knownSourceFiles:this.graph.getKnownSourceFiles?.(),routeEntryFiles:this.graph.getRouteEntryFiles?.(),sourceAst:u,sourceFile:r.file,targetFile:o.file,sourceComponent:r.component,targetComponent:o.component});if(!g.ok)return{ok:!1,errorCode:"unsupported-operation",reason:g.reason};let h=$e(u,r),S=$e(d,o);if(!h||!S)return null;let y=la(g.callSitePath,S);if(!y.ok)return{ok:!1,errorCode:"unsupported-operation",reason:y.reason};let k=Ae(l,h);if(!k)return null;if(Ae(c,S))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")&&As(c,d,a))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child relative to a repeat-template anchor outside the target scope"};if(r.tag&&r.tag.toLowerCase()===r.tag){let B=Tn(o,{kind:"native-tag",tag:r.tag});if(B)return{ok:!1,errorCode:"unsupported-operation",reason:B}}let R=Yr(this.graph,r);if(!R)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(qr(h,S))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let I=Ks(l,h,S,R);for(let B of I.conditionPaths){let te=Os(B,S,k);if(!te.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${te.bindingNames.join(", ")}`}}let b=Ts(h,S,k,{preserveConditionalBoundary:I.conditionPaths.length>0});if(!b.ok)return{ok:!1,errorCode:"unsupported-operation",reason:b.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${b.bindingNames.join(", ")}`};let M=_d({sourceFile:r.file,targetFile:o.file,sourceContext:k,targetParentPath:S});if(!M.ok)return{ok:!1,errorCode:"unsupported-operation",reason:M.reason};let T=Ud(k);if(!T.ok)return{ok:!1,errorCode:"unsupported-operation",reason:T.reason};let J=zd(k,T.callbackParams),L=[{order:0,file:r.file,type:"remove-node",locator:W(r),removeWhitespace:!0}];for(let B of M.imports)L.push({order:L.length,file:o.file,type:"add-import",moduleSpecifier:B.moduleSpecifier,imports:B.imports});return L.push({order:L.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:W(o),expression:$s(J,I.sourceJsx),placement:s,anchorLocator:a?W(a):void 0,selectionContext:mt(o)}),this.buildPlan(t,n,L,i)}async planMoveNode(t,n,r,o){if(!o.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};let i=Js(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(up(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 E=n.params.target.relation,R=i.anchorNode&&(E==="before"||E==="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:E,anchorSourceId:R?.kind==="external-entry"?R.sourceId:null,parentKey:"parentKey"in n.params.target?n.params.target.parentKey:null}}],o)}let l=r.file!==s.file,c=n.params.target.relation,u=i.anchorNode,d=Ln(r,a,this.graph.getTextProvenance?.(r.key,0)??null);if(d&&!Zr(d))return{ok:!1,errorCode:"unsupported-operation",reason:d};if(r.isRepeatItemRoot&&u?.isRepeatItemRoot&&r.repeatOwnerKey&&r.repeatOwnerKey===u.repeatOwnerKey&&(c==="before"||c==="after")){let E=a,R=await this.graph.getTextWriteTarget(u.key,0);if(E?.kind==="value-binding"&&R?.kind==="value-binding"&&E.locator&&R.locator){let I=Lt(E.locator),b=Lt(R.locator);if(I&&b&&E.file===R.file&&mp(I.locator,b.locator)){let M=I.index,T=b.index,J=c==="before"?T-(M<T?1:0):T+(M<T?0:1);return this.buildPlan(t,n,[{order:0,file:E.file,type:"move-array-item",locator:I.locator,fromIndex:M,toIndex:J}],o)}}}if(r.isRepeatItemRoot&&this.isRepeatTemplateRootNode(r))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed item outside its collection"};let g=this.getRepeatBackedTemplateStructureReason(r),h=Zr(d)?d:g;if(h&&Zr(h)){let E=this.planRepeatTemplateInternalMove(t,n,r,s,o,c,u);if(E)return E;let R=this.planRepeatTemplateHoistMove(t,n,r,s,o,c,u);if(R)return R;let I=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,c,u);return I||{ok:!1,errorCode:"unsupported-operation",reason:h}}if(g)return{ok:!1,errorCode:"unsupported-operation",reason:g};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 E=Tn(s,{kind:"native-tag",tag:r.tag});if(E)return{ok:!1,errorCode:"unsupported-operation",reason:E}}if(l)return this.planCrossFileMove(t,n,r,s,o,c,u);let y=Ns(this.graph.getFileContent(r.file),r,s);if(!y.ok)return{ok:!1,errorCode:"unsupported-operation",reason:y.reason??`Cannot move node because it depends on bindings outside the target scope: ${y.bindingNames.join(", ")}`};let k=[{order:0,file:r.file,type:"move-node",locator:W(r),targetParentLocator:W(s),placement:c,anchorLocator:u?W(u):void 0,selectionContext:mt(s)}];return this.buildPlan(t,n,k,o)}planCrossFileMove(t,n,r,o,i,s,a){let l=[],c=0,u=this.graph.getFileContent(r.file),d=Yr(this.graph,r)??`<${r.component} />`,g=Is(u,r);if(!g.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:g.reason??"Cannot move subtree across files"};if(l.push({order:c++,file:r.file,type:"remove-node",locator:W(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let S=r.tag??r.component,k={moduleSpecifier:eo(o.file,r.importedFrom),imports:r.exportName==="default"?[{kind:"default",local:S}]:[{kind:"named",imported:r.exportName,local:S===r.exportName?void 0:S}]};l.push({order:c++,file:o.file,type:"add-import",moduleSpecifier:k.moduleSpecifier,imports:k.imports}),l.push({order:c++,file:o.file,type:"insert-child",parentLocator:W(o),node:{jsx:d},placement:s,anchorLocator:a?W(a):void 0,selectionContext:mt(o)})}else l.push({order:c++,file:o.file,type:"insert-child",parentLocator:W(o),node:{jsx:d},placement:s,anchorLocator:a?W(a):void 0,selectionContext:mt(o)});let h=this.buildRemoveComponentImportStep(r,u);return h&&l.push({...h,order:c++}),this.buildPlan(t,n,l,i)}buildPlan(t,n,r,o){let s=[...new Set(r.map(a=>a.file))].map(a=>({file:a,content:this.graph.getFileContent(a),version:this.graph.getFileVersion(a),exists:!0,sha256:re(this.graph.getFileContent(a))}));return{ok:!0,plan:{operationId:t,kind:n.kind,target:n.target,documentVersion:n.documentVersion,steps:r,preSnapshots:s,validatedCapability:o}}}};import $t from"node:path";import*as ba from"@babel/parser";import mo from"@babel/traverse";import*as x from"@babel/types";var yt=typeof mo=="function"?mo:mo.default;function ua(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 va(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=Eo(s,t,n);if(!a)return null;let l=Io(a,r.sourceRange);if(!l)return null;let c=r.source??await ge({expression:l.node,scope:l.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!c){let h=await Mo({currentFile:t,expressionPath:l,readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:new Set});if(!h)return null;if(h.kind==="external")return{kind:"external-entry",file:h.file,sourceType:h.sourceType,sourceId:h.sourceId,adapterId:h.adapterId,displayExpression:h.displayPath};let S={kind:"value",root:h.root,path:h.path.length>0?h.path:[]};return{kind:"value-binding",file:h.file,locator:S,root:h.root,path:h.path,displayExpression:h.displayExpression??Bt(l.node,n),sourceKind:h.sourceKind,...h.collectionIndexMap?{collectionIndexMap:h.collectionIndexMap}:{},...h.collectionPathMap?{collectionPathMap:h.collectionPathMap}:{}}}let u=new Set,d=await Wp({currentFile:t,expressionPath:l,segment:{...r,source:c},readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:u});if(!d)return null;if(d.kind==="external")return{kind:"external-entry",file:d.file,sourceType:d.sourceType,sourceId:d.sourceId,adapterId:d.adapterId,displayExpression:d.displayPath};let g={kind:"value",root:d.root,path:d.path.length>0?d.path:[]};return{kind:"value-binding",file:d.file,locator:g,root:d.root,path:d.path,displayExpression:d.displayExpression??c.expression,sourceKind:d.sourceKind,...d.collectionIndexMap?{collectionIndexMap:d.collectionIndexMap}:{},...d.collectionPathMap?{collectionPathMap:d.collectionPathMap}:{}}}async function ka(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Eo(i,t,n);if(!s)return null;let a=e.expression!==void 0?Pa(s,n,e.expression,e.sourceRange)??wo(s,n,e.expression):Io(s,e.sourceRange);if(!a)return null;let l=vp(a),c=new Set,u=e.sourceInfo??await ge({expression:l.node,scope:l.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:c}),d=u?await ae({currentFile:t,expressionPath:l,sourceInfo:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:c}):await sf({currentFile:t,expressionPath:l,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:c});return bp(d,e.expression??Bt(l.node,n))}async function Co(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Eo(i,t,n);if(!s)return se("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?kp({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}):Cp({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}function Ca(e){try{return ba.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Eo(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=Ca(n);return e.set(t,{source:n,ast:o}),o}function Io(e,t){let n=null,r=-1;return yt(e,{Expression(o){let i=o.node.loc;if(!i||!Po(i,t))return;let s=(o.node.end??0)-(o.node.start??0);s>=r&&(n=o,r=s)}}),n}function yp(e,t){let n=null,r=Number.POSITIVE_INFINITY;return yt(e,{Expression(o){if(!Sp(o.node.loc,t))return;let i=(o.node.end??0)-(o.node.start??0);i<=r&&(n=o,r=i)}}),n}function Ea(e,t){let n=null,r=Number.POSITIVE_INFINITY;return yt(e,{JSXElement(o){let i=o.node.loc;if(!i||!Po(i,t))return;let s=(o.node.end??0)-(o.node.start??0);s<=r&&(n=o,r=s)}}),n}function Sp(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 Po(e,t){let n=da({line:e.start.line,column:e.start.column},{line:t.startLine,column:t.startColumn}),r=da({line:e.end.line,column:e.end.column},{line:t.endLine,column:t.endColumn});return n>=0&&r<=0}function Ia(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 da(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 ge(e){if(x.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!x.isMemberExpression(e.expression))return null;let t=await Da(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:Bt(e.expression,e.source),base:t.base,path:t.path}:null}function bp(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 vp(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 Bt(e,t){if(t)return Ro(e,t);let n=xf(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function Ro(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function wo(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;return yt(e,{Expression(i){if(Ro(i.node,t)!==n)return;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}}),r}function Pa(e,t,n,r){let o=null,i=Number.POSITIVE_INFINITY;return yt(e,{Expression(s){if(Ro(s.node,t)!==n)return;let a=s.node.loc;if(!a||!Po(a,r))return;let l=(s.node.end??0)-(s.node.start??0);l<=i&&(o=s,i=l)}}),o}async function kp(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:l}=e,c=Io(r,o.sourceRange),u=o.source??(c?await ge({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:i,exists:s,fileCache:a,visited:l}):null);if(!u){if(!c)return Ep(t,o.value);let g=await Mo({currentFile:t,expressionPath:c,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:l});return g?g.kind==="external"?ga(t,g):bo(t,Bt(c.node,n),g):Ip({expression:c.node,scope:c.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:l,functionCallContracts:e.functionCallContracts})}if(!c)return se("unsupported-expression","Unable to locate text expression for provenance resolution");let d=await ae({currentFile:t,expressionPath:c,sourceInfo:u,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:l});if(!d){let g=So(c.node);if(g)return se(g.code,g.message);let h=c.scope.getBinding(u.base);if(h?.path.isVariableDeclarator()){let S=So(h.path.node.init);if(S)return se(S.code,S.message)}return h?.path.isVariableDeclarator()&&x.isCallExpression(h.path.node.init)?Pp("unsupported-expression",Aa(h.path.node.init,e.functionCallContracts)):se("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return d.kind==="external"?ga(t,d):bo(t,u.expression,d)}async function Cp(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:l}=e;if(!o.conditionSource)return se("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let c=wo(r,n,o.conditionExpression);if(!c)return se("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await ae({currentFile:t,expressionPath:c,sourceInfo:o.conditionSource,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:l});if(!u)return se("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(u.kind==="external")return se("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let d=bo(t,o.conditionExpression,u);return d.finalSource?{...d,finalSource:{...d.finalSource,kind:"conditional-branch",displayPath:o.conditionExpression},chain:[...d.chain,{kind:"conditional-branch",file:u.file,displayName:o.conditionExpression,canEditHere:!0}]}:d}function Ep(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 Ip(e){let t=await wa(e);if(t.length===0)return se("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(Rp(e.expression))return Ra(t);if(Na(e.expression))return se("unsupported-expression","i18n helpers require a static message id string");if(x.isMemberExpression(e.expression)&&e.expression.computed&&!x.isNumericLiteral(e.expression.property)&&!x.isStringLiteral(e.expression.property))return se("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return se(n.code,n.message)}function se(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function Pp(e,t){return Ra([{code:e,message:t}])}function Ra(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function Rp(e){return x.isCallExpression(e)||x.isConditionalExpression(e)||x.isLogicalExpression(e)||x.isBinaryExpression(e)}function Kt(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 wa(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:l}=e,c=So(t);if(c)return[c];if(x.isCallExpression(t))return[{code:"unsupported-expression",message:Aa(t,l)}];if(x.isMemberExpression(t)&&t.computed){let u=t.property;if(!x.isNumericLiteral(u)&&!x.isStringLiteral(u)){if(!x.isExpression(u))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let g=await xe(u,n,r,o,i,s,a);if(typeof g!="string"&&!Number.isInteger(g))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}]}}return x.isBinaryExpression(t)?Kt([...await ho(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):x.isLogicalExpression(t)?Kt([...await ho(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"}]):x.isConditionalExpression(t)?Kt([...await ho(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 So(e){return Na(e)?pa("i18n helpers require a static message id string"):Mp(e)?pa("CMS helpers require static entry id and field path string arguments"):null}async function ho(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await wa({...t,expression:o}));return r}function wp(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:[Fp(e.sourceType)]}}async function Fo(e){for(let n of jp){if(!fa(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return ha(ma(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(!fa(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return ha(ma(r),e.externalAdapters)}return null}function Fp(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function Np(e){return{code:"external-source-readonly",message:e}}function pa(e){return{code:"unsupported-expression",message:e}}function No(e){return!e||!x.isCallExpression(e)?null:x.isIdentifier(e.callee)?e.callee.name:x.isMemberExpression(e.callee)&&!e.callee.computed&&x.isIdentifier(e.callee.object)&&x.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function fa(e,t){if(!t||t.length===0)return!0;let n=No(e.node);return n?t.includes(n):!1}function ma(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:Kt(e.diagnostics??[])}:{match:e,diagnostics:[]}}function ha(e,t){let n=wp(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:Kt([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function Ap(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!x.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!x.isStringLiteral(n)||!x.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 Mp(e){return!!e&&x.isCallExpression(e)&&x.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!x.isStringLiteral(e.arguments[0])||!x.isStringLiteral(e.arguments[1]))}function Fa(e){if(!(!e||!x.isCallExpression(e))){if(x.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&x.isStringLiteral(t)?t.value:null}if(x.isMemberExpression(e.callee)&&!e.callee.computed&&x.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&x.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!x.isObjectExpression(t))return null;for(let n of t.properties)if(x.isObjectProperty(n)&&!n.computed&&(x.isIdentifier(n.key)&&n.key.name==="id"||x.isStringLiteral(n.key)&&n.key.value==="id")&&x.isStringLiteral(n.value))return n.value.value;return null}}}function Na(e){return Fa(e)===null}async function Tp(e,t,n){let r=new Set,o=$t.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=$t.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"]:[$t.posix.join(i,"locales"),$t.posix.join(i,"messages")];for(let a of s){let l=$t.posix.join(a,`${t}.json`);if(await n(l))return l}}return null}async function Op(e){let t=Fa(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await Tp(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function Lp(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!x.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!x.isExpression(n))return null;let o=await xe(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:[Np("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var jp=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>Ap(e)},{helperNames:["apiField"],resolve:e=>Lp(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>Op({currentFile:e,expressionPath:t,exists:n})}];function ga(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 bo(e,t,n){let r={kind:"value",root:n.root,path:n.path.length>0?n.path:[]},o=n.path.some(c=>c.kind==="index"),i=Xp(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,l=[...n.chainPrefix??[]];return n.sourceKind==="binding"?l.push({kind:"binding",file:n.file,displayName:n.root.kind==="binding"?n.root.name:a,canEditHere:!0}):n.sourceKind==="imported-binding"?l.push({kind:"imported-binding",file:n.file,displayName:n.root.kind==="named-export"?n.root.name:"default",canEditHere:!0}):n.sourceKind==="repeat-template"&&l.push({kind:"repeat-template",file:n.file,displayName:t,canEditHere:!0}),n.path.length>0&&n.sourceKind!=="repeat-template"&&l.push({kind:o?"array-item":"object-field",file:n.file,displayName:a,canEditHere:!0}),i&&l.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:l,confidence:n.sourceKind==="repeat-template"?"safe-derived":"exact",editMode:n.editMode??(n.file===e?"direct":"proxy"),diagnostics:n.diagnostics??[]}}var Dp=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function Ao(e,t){let n=[...Dp,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function Aa(e,t){let n=e.callee;return x.isIdentifier(n)&&Ao(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 Mo(e){let t=await Fo(e);if(t)return t;let n=await Ma({...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 ge({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 Vp(e)}async function Ma(e){let t=await he({...e,allowComposed:!1});return t?.kind==="source"?t.provenance:null}async function he(e){let t=$p(e.expressionPath),n=Jp(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 ge({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 ge({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 he({...e,expressionPath:r,allowComposed:!0}),a=await he({...e,expressionPath:o,allowComposed:!1}),l=await he({...e,expressionPath:i,allowComposed:!1});return go(s,a,l)}if(t.isCallExpression())return Kp({...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 he({...e,expressionPath:r,allowComposed:!0}),s=await he({...e,expressionPath:o,allowComposed:!0});return go(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 he({...e,expressionPath:r,allowComposed:!0}),s=await he({...e,expressionPath:o,allowComposed:!0});return go(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:he({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function $p(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 Kp(e){let t=No(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:he({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(x.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:he({...e,expressionPath:o,allowComposed:!1})}}return null}function go(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!Bp(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function Bp(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 Jp(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function Vp(e){if(!e.expressionPath.isCallExpression())return null;let t=No(e.expressionPath.node);if(!t)return null;let n=Ao(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 Ta({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 Ta(e){let t=await Fo({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 ge({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 Mo({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 _p(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!x.isCallExpression(t))return null;let n=t.callee;if(!x.isIdentifier(n))return null;let r=Ao(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 Ta({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 Xp(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=$n(t,e.path);return{sourceId:o,displayPath:o}}async function Wp(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=Oa(e.expressionPath,t.base);if(n){let c=await La({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(!c){let y=zp(n.callPath,[...n.basePath,...t.path]);return Tt(y)?ua(e.currentFile,y.sourceId,y.displayPath):null}let u=yf(c,[...n.basePath,...t.path]),d=c.collectionIndexMap?.[0]??0,g=[...c.pathPrefix??[],{kind:"index",index:d},...n.basePath,...t.path],h=[{kind:"index",index:0},...n.basePath,...t.path];return ve(c.value,h)===void 0?null:{kind:"value",file:c.file,root:c.root,path:u?.[0]??g,sourceKind:"repeat-template",collectionIndexMap:c.collectionIndexMap,...u?{collectionPathMap:u}:{}}}let r=e.expressionPath.scope.getBinding(t.base);if(!r)return null;let o=ws(r);if(o){let c=o.expressionPath,u=await ge({expression:c.node,scope:c.scope,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(u){let d=await ae({...e,expressionPath:c,sourceInfo:{...u,expression:$n(u.expression,t.path),path:[...u.path,...t.path]}});if(d)return d}if(t.path.length===0){let d=await Ma({currentFile:e.currentFile,expressionPath: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(d)return d}}if(r.kind==="param")return df({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 _p({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=Rn(r,t.path);if(Tt(s))return ua(e.currentFile,s.sourceId,s.displayPath);let a=await xt({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:ve(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 Oa(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=be(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!Up(s,r)?null:{callPath:s,basePath:i}}function Up(e,t){let n=e.node.callee;return!x.isMemberExpression(n)||!x.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}async function La(e){let{currentFile:t,callPath:n,readFile:r,exists:o,fileCache:i,visited:s}=e,a=n.node.callee;if(!x.isMemberExpression(a)||!x.isIdentifier(a.property)||a.property.name!=="map")return null;let l=n.get("callee");if(!l.isMemberExpression())return null;let c=l.get("object");if(Array.isArray(c)||!c.isExpression())return null;let u=await Jt({currentFile:t,expressionPath:c,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 zp(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:Fn(r,t)}async function Jt(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 l=await xt({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 l?.kind==="static"?l:null}if(n.isCallExpression())return ja({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 Jt({...e,expressionPath:a})}if(n.isArrayExpression()){let a=Ia(n.node);if(!a)return null;let l=await xe(n.node,n.scope,t,r,o,i,s);return Array.isArray(l)?{kind:"static",file:t,root:{kind:"expression",sourceRange:a},value:l,sourceKind:"binding"}:null}if(n.isMemberExpression()){let a=await ge({expression:n.node,scope:n.scope,currentFile:t,readFile:r,exists:o,fileCache:i,visited:s});if(!a)return null;let l=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(!l||l.kind==="external")return null;let c=await Hp({currentFile:t,expressionPath:n,provenance:l,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(!c||c.kind!=="static")return null;if(l.collectionPathMap?.length){let d=Sf(c.value,l.collectionPathMap);if(d)return{kind:"static",file:l.file,root:l.root,value:d.value,sourceKind:l.sourceKind,collectionPathMap:d.collectionPathMap}}let u=ve(c.value,l.path);return Array.isArray(u)?{kind:"static",file:l.file,root:l.root,value:u,sourceKind:l.sourceKind,pathPrefix:l.path,collectionIndexMap:l.collectionIndexMap,collectionPathMap:l.collectionPathMap}:null}return null}async function Hp(e){let{provenance:t}=e;if(t.root.kind==="binding"){let i=e.expressionPath.scope.getBinding(t.root.name);return i?await xt({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 Vt(t.file,e.readFile,e.fileCache);if(!n.ast)return null;let r=yp(n.ast,t.root.sourceRange);if(!r)return null;let o=await xe(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 ja(e){return await Gp(e)??await Yp(e)??await Zp(e)}async function Gp(e){let{callPath:t}=e,n=t.node.callee;if(!x.isMemberExpression(n)||!x.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 Jt({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(!x.isArrowFunctionExpression(s)&&!x.isFunctionExpression(s))return null;let a=s.params[0];if(!x.isIdentifier(a))return null;let l=qp(s);if(!l)return null;let c=[],u=[],d=[];for(let[g,h]of i.value.entries()){let S=Qp(l,a.name,h);if(typeof S!="boolean")return null;if(S){c.push(h),u.push(i.collectionIndexMap?.[g]??g);let y=i.collectionPathMap?.[g];y&&d.push(y)}}return{...i,value:c,pathPrefix:i.pathPrefix,collectionIndexMap:u,...d.length>0?{collectionPathMap:d}:{}}}async function Yp(e){let{callPath:t}=e,n=t.node.callee;if(!x.isMemberExpression(n)||!x.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 Jt({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,l=xa(s,0),c=xa(a,i.value.length);if(l===null||c===null)return null;let u=Math.max(0,l<0?i.value.length+l:l),d=Math.max(0,c<0?i.value.length+c:c),g=i.value.map((S,y)=>i.collectionIndexMap?.[y]??y).slice(u,d),h=i.collectionPathMap?.slice(u,d);return{...i,value:i.value.slice(u,d),pathPrefix:i.pathPrefix,collectionIndexMap:g,...h?{collectionPathMap:h}:{}}}function xa(e,t){return e?x.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}async function Zp(e){let{callPath:t}=e,n=t.node.callee;if(!x.isMemberExpression(n)||!x.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 Jt({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(!x.isArrowFunctionExpression(s)&&!x.isFunctionExpression(s))return null;let[a,l]=s.params;if(!x.isIdentifier(a)||!x.isIdentifier(l))return null;let c=i.value.map((d,g)=>({value:d,sourceIndex:i.collectionIndexMap?.[g]??g,originalIndex:g})),u=[...c];for(let d of c)for(let g of c)if(ya(s,a.name,l.name,d.value,g.value)===void 0)return null;return u.sort((d,g)=>{let h=ya(s,a.name,l.name,d.value,g.value)??0;return h===0?d.originalIndex-g.originalIndex:h}),{...i,value:u.map(d=>d.value),pathPrefix:i.pathPrefix,collectionIndexMap:u.map(d=>d.sourceIndex),...i.collectionPathMap?{collectionPathMap:u.map(d=>i.collectionPathMap?.[d.originalIndex]).filter(d=>!!d)}:{}}}function ya(e,t,n,r,o){let i=x.isExpression(e.body)?e.body:e.body.body.find(a=>x.isReturnStatement(a))?.argument;if(!i||!x.isExpression(i))return;let s=vo(i,t,n,r,o);return typeof s=="number"?s:void 0}function vo(e,t,n,r,o){if(x.isNumericLiteral(e)||x.isStringLiteral(e)||x.isBooleanLiteral(e))return e.value;if(x.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(x.isMemberExpression(e)){let i=ko(e,t);if(i)return ve(r,i);let s=ko(e,n);return s?ve(o,s):void 0}if(x.isBinaryExpression(e)&&e.operator==="-"){let i=x.isExpression(e.left)?vo(e.left,t,n,r,o):void 0,s=x.isExpression(e.right)?vo(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function qp(e){if(x.isExpression(e.body))return e.body;for(let t of e.body.body)if(x.isReturnStatement(t)&&t.argument&&x.isExpression(t.argument))return t.argument;return null}function Qp(e,t,n){let r=et(e,t,n);return typeof r=="boolean"?r:void 0}function et(e,t,n){if(x.isStringLiteral(e)||x.isNumericLiteral(e)||x.isBooleanLiteral(e))return e.value;if(x.isNullLiteral(e))return null;if(x.isIdentifier(e))return e.name===t?n:void 0;if(x.isMemberExpression(e)){let r=ko(e,t);return r?ve(n,r):void 0}if(x.isUnaryExpression(e)&&e.operator==="!"){let r=et(e.argument,t,n);return r===void 0?void 0:!r}if(x.isLogicalExpression(e)){let r=et(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&et(e.right,t,n);if(e.operator==="||")return r||et(e.right,t,n)}if(x.isBinaryExpression(e)){let r=x.isExpression(e.left)?et(e.left,t,n):void 0,o=x.isExpression(e.right)?et(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 ko(e,t){let n=[],r=e;for(;x.isMemberExpression(r);){if(r.computed)if(x.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(x.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!x.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!x.isIdentifier(r)||r.name!==t?null:n}async function xt(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 l=await ef({currentFile:t,binding:n,readFile:r,exists:o,fileCache:i,visited:s});if(l)return l;if(n.path.isImportSpecifier()||n.path.isImportDefaultSpecifier())return await mf({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 c=n.path.node.init;if(!c||!x.isExpression(c))return null;let u=n.path.get("init");if(u&&!Array.isArray(u)&&u.isExpression()){let g=await Fo({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(g)return g;if(u.isCallExpression()){let h=await ja({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(h)return h}}let d=await xe(c,n.path.scope,t,r,o,i,s);return d===void 0?null:{kind:"static",file:t,root:{kind:"binding",name:n.identifier.name},value:d,sourceKind:"binding"}}if(n.path.isIdentifier()&&n.path.parentPath?.isExportDefaultDeclaration()){let c=n.path.parentPath.node.declaration;if(!x.isExpression(c))return null;let u=await xe(c,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 ef(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,l=a.node.init;if(!l||!x.isCallExpression(l))return null;let c=tf(l);if(!c||!x.isArrayPattern(a.node.id)||a.node.id.elements.findIndex(S=>x.isIdentifier(S)&&S.name===n.identifier.name)!==0)return null;let d=c==="useReducer"?1:0,g=l.arguments[d];if(!g||!x.isExpression(g))return null;let h=await xe(g,a.scope,t,r,o,i,s);return h===void 0?null:{kind:"static",file:t,root:{kind:"hook-state",name:n.identifier.name,hook:c},value:h,sourceKind:"binding"}}function tf(e){return x.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:x.isMemberExpression(e.callee)&&x.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function nf(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()||!x.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 rf(e,t){let n=nf(e.path);if(!n)return null;let r=ft(e,t);return r?{...n,...r}:null}function $n(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function of(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}async function sf(e){let t=lf(e.expressionPath.node);if(!t||!cf(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 af({...e,rootPath:n.path,segments:t.segments});return r?{...n,path:r.collectionPathMap[0]??n.path,sourceKind:"repeat-template",displayExpression:Bt(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:r.collectionPathMap}:null}async function af(e){let t=null,n,r=[];for(let i of e.segments){if(i.kind!=="dynamic")continue;let s=await ge({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=Oa(e.expressionPath,s.base);if(!a)return null;let l=await La({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(!l||!Array.isArray(l.value))return null;let c=l.value.map((u,d)=>{let g=ve(l.value,[{kind:"index",index:d},...a.basePath,...s.path]);return uf(g)});if(c.some(u=>u===null)||t!==null&&t!==c.length)return null;t=c.length,n??=l.collectionIndexMap,r.push(c)}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 l of e.segments){if(l.kind==="dynamic"){let c=r[a]?.[i];if(!c)return null;s.push(c),a+=1;continue}s.push({...l})}o.push(s)}return{...n?{collectionIndexMap:n}:{},collectionPathMap:o}}function lf(e){let t=[],n=e;for(;x.isMemberExpression(n)||x.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(x.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(x.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(x.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(x.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return x.isIdentifier(n)?{base:n.name,segments:t}:null}function cf(e){return e.some(t=>t.kind==="dynamic")}function uf(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}async function df(e){let t=rf(e.binding,e.sourceInfo);if(!t||!e.graph)return null;let n=[...e.graph.elements.values()].filter(c=>of(c,e.currentFile,t.componentName,t.exportName));if(n.length!==1)return null;let r=n[0],o=r.attributes?.find(c=>c.name===t.propName);if(o&&!o.source){let c=await pf({caller:r,propName:t.propName,remainingPath:t.remainingPath,readFile:e.readFile,fileCache:e.fileCache});if(c)return xo(c,{componentName:t.componentName,propName:t.propName,file:r.sourceFile})}if(!o?.source){let c=await ff({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(c)return xo(c,{componentName:t.componentName,propName:t.propName,file:r.sourceFile});let u=Fs(e.binding,t.componentName,t.propName);if(!u||u.propName!==t.propName)return null;let d=await xe(u.expressionPath.node,u.expressionPath.scope,e.currentFile,e.readFile,e.exists,e.fileCache,e.visited);if(d===void 0)return null;let g=t.remainingPath;return g.length>0&&ve(d,g)===void 0?null:{kind:"value",file:e.currentFile,root:{kind:"binding",name:t.propName},path:g,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 Vt(r.sourceFile,e.readFile,e.fileCache);if(!i.ast)return null;let s=Pa(i.ast,i.source,o.source.expression,o.sourceRange)??wo(i.ast,i.source,o.source.expression);if(!s)return null;let a={...o.source,expression:$n(o.source.expression,t.remainingPath),path:[...o.source.path,...t.remainingPath]},l=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 l?xo(l.kind==="external"?l:{...l,displayExpression:a.expression},{componentName:t.componentName,propName:t.propName,file:r.sourceFile}):null}async function pf(e){let t=await Vt(e.caller.sourceFile,e.readFile,e.fileCache);if(!t.ast)return null;let n=Ea(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=Ia(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 ff(e){let t=await Vt(e.caller.sourceFile,e.readFile,e.fileCache);if(!t.ast)return null;let n=Ea(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 ge({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],l={...s,expression:$n(s.expression,a),path:[...s.path,...a]},c=await ae({currentFile:e.caller.sourceFile,expressionPath:i,sourceInfo: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(c)return c.kind==="external"?c:{...c,displayExpression:l.expression}}return null}function xo(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 mf(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 l=a.node.source.value;if(typeof l!="string")return null;let c=await Ct(t,l,o);if(!c)return null;if(n.path.isImportDefaultSpecifier()){let h=await Sa({file:c,exportName:"default",readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});return!h||h.kind!=="static"?null:{kind:"static",file:c,root:{kind:"default-export"},value:h.value,sourceKind:"imported-binding"}}if(!n.path.isImportSpecifier())return null;let u=n.path.node.imported,d=x.isIdentifier(u)?u.name:u.value,g=await Sa({file:c,exportName:d,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});return g?g.kind==="external"?g:{kind:"static",file:c,root:{kind:"named-export",name:d},value:g.value,sourceKind:"imported-binding"}:null}async function Sa(e){let{file:t,exportName:n,readFile:r,exists:o,fileCache:i,visited:s}=e,a=await Vt(t,r,i);if(!a.ast)return;let l=gf(a.ast,n);if(!l||l.kind==="default-expression")return;let c=l.name;if(!c)return;let u=hf(a.ast).getBinding(c);return u?await xt({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 hf(e){let t=null;if(yt(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}function gf(e,t){for(let n of e.program.body){if(t==="default"&&x.isExportDefaultDeclaration(n))return x.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:(x.isFunctionDeclaration(n.declaration)||x.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if(x.isExportNamedDeclaration(n)){if(n.declaration){if(x.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if(x.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if((x.isFunctionDeclaration(n.declaration)||x.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if((x.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&x.isExportSpecifier(r))return{kind:"local-binding",name:r.local.name}}}return null}async function xe(e,t,n,r,o,i,s){if(x.isStringLiteral(e)||x.isNumericLiteral(e)||x.isBooleanLiteral(e))return e.value;if(x.isNullLiteral(e))return null;if(x.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(x.isTSAsExpression(e)||x.isTSSatisfiesExpression(e)||x.isTSNonNullExpression(e))return await xe(e.expression,t,n,r,o,i,s);if(x.isIdentifier(e)){let a=t.getBinding(e.name);if(!a)return;let l=await xt({currentFile:n,binding:a,readFile:r,exists:o,fileCache:i,visited:s});return l?.kind==="static"?l.value:void 0}if(x.isArrayExpression(e)){let a=[];for(let l of e.elements){if(!l||x.isSpreadElement(l))return;let c=await yo(l,t,n,r,o,i,s);if(c===void 0)return;a.push(c)}return a}if(x.isObjectExpression(e)){let a={};for(let l of e.properties){if(!x.isObjectProperty(l)||l.computed)return;let c=null;if(x.isIdentifier(l.key)?c=l.key.name:x.isStringLiteral(l.key)&&(c=l.key.value),!c)return;if(l.shorthand){if(!x.isIdentifier(l.value))return;let d=await yo(l.value,t,n,r,o,i,s);if(d===void 0)return;a[c]=d;continue}if(!x.isExpression(l.value))return;let u=await yo(l.value,t,n,r,o,i,s);u!==void 0&&(a[c]=u)}return a}if(x.isMemberExpression(e)){let a=await Da(e,t,n,r,o,i,s);if(!a)return;let l=t.getBinding(a.base);if(!l)return;let c=await xt({currentFile:n,binding:l,readFile:r,exists:o,fileCache:i,visited:s});return!c||c.kind!=="static"?void 0:ve(c.value,a.path)}}async function yo(e,t,n,r,o,i,s){if(!x.isSpreadElement(e))return await xe(e,t,n,r,o,i,s)}async function Da(e,t,n,r,o,i,s){if(x.isIdentifier(e))return{base:e.name,path:[]};if(!x.isMemberExpression(e))return null;let a=[],l=e;for(;x.isMemberExpression(l);){if(l.computed){let c=l.property;if(x.isNumericLiteral(c))a.unshift({kind:"index",index:c.value});else if(x.isStringLiteral(c))a.unshift({kind:"property",name:c.value});else{let u=x.isExpression(c)?await xe(c,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(!x.isIdentifier(l.property))return null;a.unshift({kind:"property",name:l.property.name})}l=l.object}return x.isIdentifier(l)?{base:l.name,path:a}:null}function xf(e){if(x.isIdentifier(e))return{base:e.name,path:[]};if(!x.isMemberExpression(e))return null;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))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return x.isIdentifier(n)?{base:n.name,path:t}:null}function ve(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 yf(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 Sf(e,t){let n=[],r=[];for(let o of t){let i=ve(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 Vt(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=Ca(o),s={source:o,ast:i};return n.set(e,s),s}var bf=50,vf=8*1024*1024;function Ka(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??bf),s=Math.max(0,t.maxUndoBytes??vf);return{execute:a,undo:l,redo:c};async function a(b){let M=[...b.steps].sort((Y,Ee)=>Y.order-Ee.order),T=M.filter(Y=>Y.type!=="invoke-external-adapter"),J=M.filter(Y=>Y.type==="invoke-external-adapter"),L=new Set(T.map(Y=>Y.file));if(T.length>0&&J.length>0)return{ok:!1,operationId:b.operationId,errorCode:"unsupported-operation",reason:"Mixed local file rewrites and external adapter writes require an explicit compensation contract.",rolledBack:!1};if(T.length===0)return S(b,J);let B=await y(L),te=new Map;for(let Y of B)te.set(Y.file,Y.exists===!1?"":Y.content);let le;for(let Y of T){let Ee=te.get(Y.file)??"",Ie=Cf(Y,Ee);if(!Ie.ok)return{ok:!1,operationId:b.operationId,errorCode:Ie.errorCode,reason:Ie.reason,rolledBack:!1};te.set(Y.file,Ie.source),Ie.selectionRef&&(le=Ie.selectionRef)}let Ce=await E([...te].map(([Y,Ee])=>({file:Y,content:Ee,exists:!0,version:0,sha256:re(Ee)})),B);return Ce.ok?(n.push({operationId:b.operationId,preSnapshots:B,postSnapshots:Ce.snapshots,plan:b}),u(),r.length=0,{ok:!0,operationId:b.operationId,kind:b.kind,target:b.target,resultVersion:Math.max(...Ce.snapshots.map(Y=>Y.version)),affectedFiles:[...L],...le?{selectionRef:le}:{}}):{ok:!1,operationId:b.operationId,errorCode:Ce.rolledBack?"writeback-failed":"rollback-failed",reason:Ce.reason,rolledBack:Ce.rolledBack}}async function l(){let b=n.at(-1);if(!b)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let M=await E(b.preSnapshots,b.postSnapshots);return M.ok?(n.pop(),r.push(b),{ok:!0,operationId:b.operationId,kind:b.plan.kind,target:b.plan.target,resultVersion:Math.max(...M.snapshots.map(T=>T.version)),affectedFiles:b.preSnapshots.map(T=>T.file)}):{ok:!1,operationId:b.operationId,errorCode:M.rolledBack?"writeback-failed":"rollback-failed",reason:M.reason,rolledBack:M.rolledBack}}async function c(){let b=r.at(-1);if(!b)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let M=await E(b.postSnapshots,b.preSnapshots);return M.ok?(r.pop(),n.push(b),u(),{ok:!0,operationId:b.operationId,kind:b.plan.kind,target:b.plan.target,resultVersion:Math.max(...M.snapshots.map(T=>T.version)),affectedFiles:b.postSnapshots.map(T=>T.file)}):{ok:!1,operationId:b.operationId,errorCode:M.rolledBack?"writeback-failed":"rollback-failed",reason:M.reason,rolledBack:M.rolledBack}}function u(){for(;n.length>i;)n.shift();for(;n.length>0&&d()>s;)n.shift()}function d(){return n.reduce((b,M)=>b+g(M),0)}function g(b){return h(b.preSnapshots)+h(b.postSnapshots)}function h(b){return b.reduce((M,T)=>M+T.file.length+T.content.length,0)}async function S(b,M){let T=[];for(let J of M){let L=J.capability??"write-text",B=o.find(le=>le.sourceType===J.sourceType&&(J.adapterId===void 0||le.adapterId===J.adapterId)&&(le.capabilities===void 0||le.capabilities.includes(L)));if(!B)return{ok:!1,operationId:b.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${J.sourceType}`,rolledBack:!1};let te=await B.execute(J);if(!te.ok)return{ok:!1,operationId:b.operationId,errorCode:"writeback-failed",reason:te.reason??`External adapter failed for ${J.sourceType}`,rolledBack:!1};T.push(J.file)}return{ok:!0,operationId:b.operationId,kind:b.kind,target:b.target,resultVersion:0,affectedFiles:T}}async function y(b){let M=[];for(let T of b)M.push(await k(T));return M}async function k(b){if(!await e.exists(b))return{file:b,content:"",version:0,exists:!1};let T=Math.max(1,e.getVersion(b)),J=await e.readFile(b);return{file:b,content:J,version:T,exists:!0,sha256:re(J)}}async function E(b,M){let T=[];try{for(let J of b){await R(J);let L=e.bumpVersion(J.file);T.push(J.file),J.version=L}}catch(J){let L=await I(M.filter(B=>T.includes(B.file)));return{ok:!1,reason:L.ok?`Writeback failed and committed files were restored: ${$a(J)}`:`Writeback failed, then rollback failed for ${L.failedFiles.join(", ")}: ${$a(J)}`,rolledBack:L.ok}}return{ok:!0,snapshots:b.map(kf)}}async function R(b){if(b.exists===!1){await e.deleteFile(b.file);return}await e.writeFile(b.file,b.content)}async function I(b){let M=[];for(let T of b)try{await R(T),e.bumpVersion(T.file)}catch{M.push(T.file)}return M.length===0?{ok:!0}:{ok:!1,failedFiles:M}}}function kf(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:re(e.content)}:{}}}function $a(e){return e instanceof Error?e.message:String(e)}function Cf(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 ie(vn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return ie(kn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return ie(hn({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return ie(gn({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return ie(mn({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return ie(At({source:t,locator:e.locator,next:e.value}));case"update-array-item":return ie(At({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return ie(Cn({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return ie(xn({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return ie(En({source:t,locator:e.locator,index:e.index}));case"move-array-item":return ie(In({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return ie(yn({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return ie(Sn({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 Ef(e,t);case"set-props":{let n=e;return ie(bn({source:t,locator:n.locator,props:n.props}))}default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function Ef(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!_i(n.newAttrRaw))return{ok:!1,reason:"newAttrRaw must be a valid JSX className attribute.",errorCode:"invalid-params"};if(!(n.oldAttrRange!==null&&n.oldAttrRaw!==null)&&n.expectedVersion.contentHash!==re(t))return{ok:!1,reason:"The source file changed before className save.",errorCode:"stale-version"};if(n.oldAttrRange){if(t.slice(n.oldAttrRange.start,n.oldAttrRange.end)!==n.oldAttrRaw)return{ok:!1,reason:"The className attribute changed before save.",errorCode:"stale-version"}}else if(n.oldAttrRaw!==null)return{ok:!1,reason:"The className attribute range no longer matches.",errorCode:"stale-version"};return{ok:!0,source:Vi({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function ie(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 Ba(){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 If}from"node:crypto";import To from"node:fs/promises";import Oo from"node:path";var Pf={async writeFile(e,t,n){await To.writeFile(e,t,n)},async rename(e,t){await To.rename(e,t)},async rm(e,t){await To.rm(e,t)}};async function Kn(e,t,n=Pf){let r=Oo.dirname(e),o=Oo.basename(e),i=Oo.join(r,`.${o}.${process.pid}.${If()}.tmp`),s=!1;try{await n.writeFile(i,t,"utf8"),await n.rename(i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}var Ff=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,Nf=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],Ja=32,Af=256;function Mf(){let e=new Map;return{async readFile(t){return(await import("node:fs/promises")).readFile(t,"utf-8")},async writeFile(t,n){await Kn(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 Va(e,t){return{routeId:e,entryFile:t,graph:null,topology:null,capabilities:null,document:null,detailProjections:null,fileVersions:new Map,styleContext:null}}function Tf(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 Of(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function Lf(e,t){if(!e)return;let n=[...t];for(let o of n)if(o?.entries.some(i=>i.key===e.key))return e;let r=ke(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(ke(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}function Vn(e){let t="idle",n=e.fileSystem??Mf(),r=Ba(),o=new Map,i=null,s=new Set,a=null,l=Ka(n,{externalAdapters:e.externalAdapters}),c=new Map,u=0,d=0;function g(){return t==="disposed"}if(e.onEvent&&r.subscribe(e.onEvent),e.routes)for(let m of e.routes)o.set(m.routeId,Va(m.routeId,m.entryFile));async function h(m,v,C){let P=new Map,A=new Map,w=typeof n.exists=="function"?O=>n.exists(O):async()=>!1;for(let[O,$]of m.elements){let j=v.nodes.get(O);if(!j)continue;let _=C.get($.sourceFile)??c.get($.sourceFile),ee=new Map,z=new Map,Pe=new Map,_t=[];for(let U of $.textSegments){if(!_){ee.set(U.index,null);continue}let bt=await va({file:$.sourceFile,source:_,segment:U,readFile:de=>n.readFile(de),exists:w,graph:m,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:de,adapterId:Gn,capabilities:Yn})=>({sourceType:de,adapterId:Gn,capabilities:Yn})),functionCallContracts:e.functionCallContracts,fileCache:A}),ne=await Co({file:$.sourceFile,source:_,target:{kind:"text-segment",segment:U},readFile:de=>n.readFile(de),exists:w,graph:m,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:de,adapterId:Gn,capabilities:Yn})=>({sourceType:de,adapterId:Gn,capabilities:Yn})),functionCallContracts:e.functionCallContracts,fileCache:A}),nt=Tf(bt);ee.set(U.index,nt),z.set(U.index,bt),Pe.set(U.index,ne),_t.push({editable:U.editable,source:nt})}let Xt=new Map;if(_)for(let U of $.attributes??[]){let bt=await ka({file:$.sourceFile,source:_,sourceRange:U.sourceRange,expression:U.source?.expression??U.value,sourceInfo:U.source,readFile:ne=>n.readFile(ne),exists:w,graph:m,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:ne,adapterId:nt,capabilities:de})=>({sourceType:ne,adapterId:nt,capabilities:de})),functionCallContracts:e.functionCallContracts,fileCache:A});Xt.set(U.name,bt)}let ye=ai(Of(j.writeTarget),_t),zn=ci({key:O,element:$,graph:m,provenances:Pe}),Za=fi($),qa=mi($),Qa=Fi($),Wt=m.regions.find(U=>U.kind==="conditional-region"&&U.childKeys.includes(O)),Jo,Hn=Wt?.sourceCandidates?.[0];if(_&&Wt&&Hn?.kind==="conditional-branch"){let U=await Co({file:$.sourceFile,source:_,target:{kind:"conditional-branch",candidate:Hn},readFile:ne=>n.readFile(ne),exists:w,graph:m,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:ne,adapterId:nt,capabilities:de})=>({sourceType:ne,adapterId:nt,capabilities:de})),functionCallContracts:e.functionCallContracts,fileCache:A});Jo={currentBranch:Wt.childKeys.indexOf(O)<=0?"then":"else",availableBranches:Wt.childKeys.length>1?["then","else"]:["then"],conditionExpression:Hn.conditionExpression,provenance:{finalSource:U.finalSource?{kind:U.finalSource.kind,file:U.finalSource.file,displayPath:U.finalSource.displayPath}:null,chain:U.chain.map(ne=>({kind:ne.kind,file:ne.file,displayName:ne.displayName,canEditHere:ne.canEditHere})),confidence:U.confidence,editMode:U.editMode,diagnostics:U.diagnostics.map(ne=>({code:ne.code,message:ne.message}))}}}P.set(O,{textSources:ee,textTargets:z,elementPropertyTargets:Xt,provenances:Pe,writeTarget:ye,componentSemantic:zn,contentModel:Za,mediaModel:qa,styleSource:Qa,conditional:Jo})}return P}function S(m){return typeof n.getVersion=="function"?n.getVersion(m):0}function y(m,v){let C=1;for(let P of v.values())C=Math.max(C,P);return Math.max(C,m.graph?.version??0)}async function k(m,v,C={}){let P=o.get(m);if(!P)return;let A=await E(P.entryFile),{graph:w,allSources:O}=await ti(P.entryFile,v,ye=>n.readFile(ye),typeof n.exists=="function"?ye=>n.exists(ye):async()=>!1,{additionalEntries:A,version:P.graph?.version??1}),$=new Map;for(let ye of O.keys())$.set(ye,S(ye));let j=Math.max(y(P,$),C.minimumVersion??0);C.changed&&j<=(P.graph?.version??0)&&(j=(P.graph?.version??0)+1),w.version=j,u=Math.max(u,j);for(let[ye,zn]of O)b(ye,zn);let _=await R(P.entryFile,O,j);w.routeId=m;let ee=ni(w),z=oi(ee,w),Pe=await h(w,ee,O),_t=T(w,z,Pe),Xt=Wf(ii(w,ee,z,{canUpdateTextByKey:_t}),w,Pe);P.graph=w,P.topology=ee,P.capabilities=z,P.document=Xt,P.detailProjections=Pe,P.fileVersions=$,P.styleContext=_}async function E(m){let v=[];for(let C of Kf(m))typeof n.exists=="function"&&await n.exists(C)&&v.push({file:C,source:await n.readFile(C)});return v}async function R(m,v,C){let P=[];for(let[j,_]of v){if(Do(j)){P.push(j);continue}for(let ee of Jf(_)){let z=_a(j,ee);z&&P.push(z)}}if(!P.length){for(let j of Bf(m))if(await M(j)){P.push(j);break}}let A=new Map,w=za(P).slice(0,Ja);for(;w.length>0&&A.size<Ja;){let j=w.shift();if(A.has(j)||!Do(j))continue;let _=await I(j);if(_!==null){A.set(j,{path:j,content:_});for(let ee of Vf(_)){let z=_a(j,ee);z&&!A.has(z)&&!w.includes(z)&&w.push(z)}}}let O=[...A.values()].map(j=>({...j,hash:re(j.content)})),$=O[0];return $?{revision:re(JSON.stringify({routeVersion:C,stylesheets:O.map(({path:j,hash:_})=>({path:j,hash:_}))})),entryCss:$,stylesheets:O.slice(1)}:null}async function I(m){let v=c.get(m);if(v!==void 0)return v;if(!await M(m))return null;let C=await n.readFile(m);return b(m,C),C}function b(m,v){if(!c.has(m)&&c.size>=Af){let C=c.keys().next().value;C&&c.delete(C)}c.set(m,v)}async function M(m){return typeof n.exists=="function"?n.exists(m):!1}function T(m,v,C){let P=new Map;for(let[A,w]of m.elements){if(!v.get(A)?.canUpdateText){P.set(A,!1);continue}let $=C.get(A),j=w.textSegments.some(_=>{if(!_.editable)return!1;let ee=$?.provenances.get(_.index)??null;return!ee||J(ee)});P.set(A,j)}return P}function J(m){return m.editMode==="direct"||m.editMode==="proxy"||m.editMode==="upstream"}async function L(m,v={}){let C=[...new Set(m)],P=new Set;for(let O of o.values())le(O,C)&&P.add(O.routeId);let A=P.size===0&&C.some($f),w={rebuiltRoutes:[],failedRoutes:[]};for(let O of o.values())if(P.has(O.routeId)||A)try{let j=!!O.graph,_=await n.readFile(O.entryFile);await k(O.routeId,_,v),O.graph&&w.rebuiltRoutes.push({documentChanged:j,routeId:O.routeId,version:O.graph.version})}catch(j){w.failedRoutes.push({routeId:O.routeId,message:Lo(j)})}return w}function B(m,v=0){let C=[...new Set(m)],P=v;for(let A of o.values())le(A,C)&&A.graph&&(P=Math.max(P,A.graph.version));return P}function te(m){let v=[...new Set(m)],C=new Set;for(let P of o.values())le(P,v)&&C.add(P.routeId);return[...C]}function le(m,v){return v.some(C=>m.entryFile===C||m.graph?.fileIndex.has(C))}function Ce(m){for(let v of m)s.add(v);a||g()||(a=(async()=>{t="building";let v=!1;try{for(;s.size>0;){if(g())return;await Y();let C=[...s];s.clear();let P=await Ee(C);if(P.length===0)continue;let A=te(P);for(let $ of A)r.emit({type:"graph-invalidated",routeId:$});let{rebuiltRoutes:w,failedRoutes:O}=await L(P,{changed:!0});for(let{documentChanged:$,routeId:j,version:_}of w)r.emit({type:"graph-ready",routeId:j,version:_}),$&&r.emit({type:"document-changed",routeId:j,version:_});for(let{routeId:$,message:j}of O)v=!0,r.emit({type:"graph-error",routeId:$,message:j})}}finally{if(a=null,t!=="disposed"){let C=i?o.get(i):null;t=!v&&C?.graph?"ready":"idle"}s.size>0&&Ce([])}})())}async function Y(){for(;d>0;)await new Promise(m=>setTimeout(m,0))}async function Ee(m){let v=[];for(let C of new Set(m)){let P=c.get(C);if(P===void 0){v.push(C);continue}try{await n.readFile(C)!==P&&v.push(C)}catch{v.push(C)}}return v}async function Ie(m){let v=await Ee(m);if(v.length===0)return;let C=te(v);for(let w of C)r.emit({type:"graph-invalidated",routeId:w});let{rebuiltRoutes:P,failedRoutes:A}=await L(v,{changed:!0});for(let{documentChanged:w,routeId:O,version:$}of P)r.emit({type:"graph-ready",routeId:O,version:$}),w&&r.emit({type:"document-changed",routeId:O,version:$});for(let{routeId:w,message:O}of A)r.emit({type:"graph-error",routeId:w,message:O})}async function Ha(m,v){let C=St(m,v);if(!C?.graph)return;let P=ke(m)??m,A=C.graph.elements.get(P);A&&await Ie([A.sourceFile])}async function Ga(m){let v=new Set;if(m.target.kind==="node"){let C=St(m.target.key,m.routeId),P=ke(m.target.key)??m.target.key,A=C?.graph?.elements.get(P);A&&v.add(A.sourceFile)}else{let C=o.get(m.target.routeId);C&&v.add(C.entryFile)}m.params.kind==="set-class-name-source"&&v.add(m.params.filePath),m.params.kind==="apply-style-draft"&&m.params.className&&v.add(m.params.className.filePath),await Ie(v)}async function Ya(m){let v=o.get(m);if(!v)throw new Error(`Route not found: ${m}`);if(v.graph)return;let C=await n.readFile(v.entryFile);await k(m,C)}function St(m,v){if(v){let C=o.get(v)??null;return!C||!Bo(C,m)?null:C}for(let C of o.values())if(Bo(C,m))return C;return null}function Bo(m,v){if(m.document?.entries.some(P=>P.key===v)||m.graph?.elements.has(v))return!0;let C=ke(v);return C&&C!==v?m.graph?.elements.has(C)===!0:!1}return{get status(){return t},dispose(){t="disposed",s.clear(),o.clear(),c.clear(),i=null},registerRoute(m,v){o.get(m)?.entryFile!==v&&(o.set(m,Va(m,v)),r.emit({type:"graph-invalidated",routeId:m}))},unregisterRoute(m){o.delete(m)&&(i===m&&(i=null,t="idle"),r.emit({type:"graph-invalidated",routeId:m}))},async setActiveRoute(m){let v=o.get(m);if(!v)throw new Error(`Route not found: ${m}`);let C=i===m;if(i=m,!v.graph){t="building";try{let P=await n.readFile(v.entryFile);await k(m,P);let A=o.get(m)?.graph?.version??1;t="ready",r.emit({type:"graph-ready",routeId:m,version:A})}catch(P){throw t="idle",r.emit({type:"graph-error",routeId:m,message:Lo(P)}),P}return}t="ready",C||r.emit({type:"graph-ready",routeId:m,version:v.graph.version})},getDocument(m){let v=o.get(m);if(!v)throw new Error(`Route not found: ${m}`);if(!v.document)throw new Error(`Route not built: ${m}`);return v.document},getRenderDetail(m,v){let C=St(m,v),P=ke(m)??m;if(C?.graph&&C.topology&&C.capabilities&&C.detailProjections){let A=C.detailProjections.get(P);if(A){let w=si(P,C.graph,C.topology,C.capabilities,A.textSources,A.writeTarget,A.provenances,A.conditional,A.componentSemantic,A.contentModel,A.mediaModel,A.styleSource);return m===P?w:Yf(w,m,C.document??null)}}throw new Error(`Key not found: ${m}`)},getClassNameSource(m,v){let C=St(m,v),P=ke(m)??m;if(!C?.graph)throw new Error(`Key not found: ${m}`);let A=C.graph.elements.get(P);if(!A)throw new Error(`Key not found: ${m}`);let w=c.get(A.sourceFile);if(w===void 0)throw new Error(`Source not loaded: ${A.sourceFile}`);let O=Ji({key:P,route:{routeId:C.routeId,graph:C.graph,source:w}});return C.styleContext?{...O,styleContext:C.styleContext}:O},refreshSourceForKey:Ha,async execute(m){await Ga(m);let v=null;if(m.target.kind==="node"?v=St(m.target.key,m.routeId):(v=o.get(m.target.routeId)??null,v&&!v.graph&&await Ya(v.routeId)),!v)return{requestId:m.id,kind:m.kind,target:m.target,ok:!1,resultVersion:u,error:{code:m.target.kind==="route"?G.ROUTE_NOT_FOUND:G.NODE_NOT_FOUND,message:m.target.kind==="route"?`Route not found: ${m.target.routeId}`:`Target key not found: ${m.target.key}`}};if(!v.graph||!v.topology||!v.capabilities)return{requestId:m.id,kind:m.kind,target:m.target,ok:!1,resultVersion:u,error:{code:m.target.kind==="route"?G.ROUTE_NOT_FOUND:G.NODE_NOT_FOUND,message:m.target.kind==="route"?`Route not ready: ${m.target.routeId}`:`Target key not found: ${m.target.key}`}};let C=jf(v,v.graph,v.capabilities,c,o),P=await new Dn(C).plan(m);if(!P.ok)return{requestId:m.id,kind:m.kind,target:m.target,ok:!1,resultVersion:u,error:{code:Bn(P.errorCode),message:P.reason}};let A=P.plan;if(A.steps.length===0)return{requestId:m.id,kind:m.kind,target:m.target,ok:!1,resultVersion:u,error:{code:G.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};d+=1;try{let w=await l.execute(A);if(!w.ok)return{requestId:m.id,kind:m.kind,target:m.target,ok:!1,resultVersion:u,error:{code:Bn(w.errorCode),message:w.reason}};let O=await L(w.affectedFiles,{changed:!0,minimumVersion:w.resultVersion});if(O.failedRoutes.length>0){let z=Math.max(w.resultVersion,B(w.affectedFiles,w.resultVersion));return u=Math.max(u,z),{requestId:m.id,kind:m.kind,target:m.target,ok:!1,resultVersion:z,affectedFiles:w.affectedFiles,error:{code:G.AST_PARSE_ERROR,message:`Source committed but route rebuild failed: ${jo(O.failedRoutes)}`,details:{sourceCommitted:!0,failedRoutes:O.failedRoutes}}}}let $=B(w.affectedFiles,w.resultVersion);u=Math.max(u,$);let j=[v.document,...[...o.values()].filter(z=>z!==v).map(z=>z.document)],_=Lf(w.selectionRef,j),ee={requestId:m.id,kind:m.kind,target:m.target,ok:!0,resultVersion:$,affectedFiles:w.affectedFiles,..._?{selectionRef:_}:{}};r.emit({type:"operation-completed",result:ee});for(let{routeId:z,version:Pe}of O.rebuiltRoutes)r.emit({type:"document-changed",routeId:z,version:Pe});return ee}catch(w){return{requestId:m.id,kind:m.kind,target:m.target,ok:!1,resultVersion:u,error:{code:G.INTERNAL_ERROR,message:Lo(w)}}}finally{d-=1}},async undo(){d+=1;try{let m=await l.undo();if(!m.ok)return{requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:u,error:{code:Bn(m.errorCode),message:m.reason}};let v=await L(m.affectedFiles,{changed:!0,minimumVersion:m.resultVersion});if(v.failedRoutes.length>0){let P=B(m.affectedFiles,m.resultVersion);return u=Math.max(u,P),{requestId:"undo",kind:m.kind,target:m.target,ok:!1,resultVersion:P,affectedFiles:m.affectedFiles,error:{code:G.AST_PARSE_ERROR,message:`Undo committed but route rebuild failed: ${jo(v.failedRoutes)}`,details:{sourceCommitted:!0,failedRoutes:v.failedRoutes}}}}let C=B(m.affectedFiles,m.resultVersion);return u=Math.max(u,C),{requestId:"undo",kind:m.kind,target:m.target,ok:!0,resultVersion:C,affectedFiles:m.affectedFiles}}finally{d-=1}},async redo(){d+=1;try{let m=await l.redo();if(!m.ok)return{requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:u,error:{code:Bn(m.errorCode),message:m.reason}};let v=await L(m.affectedFiles,{changed:!0,minimumVersion:m.resultVersion});if(v.failedRoutes.length>0){let P=B(m.affectedFiles,m.resultVersion);return u=Math.max(u,P),{requestId:"redo",kind:m.kind,target:m.target,ok:!1,resultVersion:P,affectedFiles:m.affectedFiles,error:{code:G.AST_PARSE_ERROR,message:`Redo committed but route rebuild failed: ${jo(v.failedRoutes)}`,details:{sourceCommitted:!0,failedRoutes:v.failedRoutes}}}}let C=B(m.affectedFiles,m.resultVersion);return u=Math.max(u,C),{requestId:"redo",kind:m.kind,target:m.target,ok:!0,resultVersion:C,affectedFiles:m.affectedFiles}}finally{d-=1}},notifyFileChanged(m){Ce([m])},subscribe(m){return r.subscribe(m)}}}function jf(e,t,n,r,o){let i=new Map,s=new Map,a=(u,d)=>{if(s.has(u))return;s.set(u,d);let g=t.elements.get(u);for(let h of g?.childKeys??[])a(h,d)};for(let u of t.regions)if(u.kind==="repeat-region")for(let d of u.childKeys)i.set(d,u.ownerKey),a(d,u.ownerKey);return{getNode(u){let d=l(u),g=t.elements.get(d.baseKey);return g?c(u,g):null},getChildNodes(u){let d=l(u),h=e.document?.entries.find(y=>y.key===u)?.childKeys;if(h)return h.map(y=>{let k=ke(y)??y,E=t.elements.get(k);return E?c(y,E):null}).filter(y=>y!==null);let S=t.elements.get(d.baseKey);return S?S.childKeys.map(y=>{let k=t.elements.get(y);return k?c(y,k):null}).filter(y=>y!==null):[]},getKnownSourceFiles(){return[...r.entries()].map(([u,d])=>({file:u,content:d}))},getRouteEntryFiles(){return[...o.values()].map(u=>u.entryFile)},getCapability(u){let d=l(u),g=n.get(d.baseKey);return g?{...g,key:u,constraints:g.constraints.map(h=>({...h})),...g.editModes?{editModes:{...g.editModes}}:{}}:{key:u,canUpdateText:!1,canRemove:!1,canInsertChild:!1,canMove:!1,constraints:[]}},getFileContent(u){return r.get(u)??""},getFileVersion(u){return Math.max(e.fileVersions.get(u)??0,t.version)},getRouteEntryFile(u){return e.routeId===u?e.entryFile:null},getComponentSemantic(u){let d=l(u);return e.detailProjections?.get(d.baseKey)?.componentSemantic??null},getEditableTextSegmentIndex(u){let d=l(u),h=e.detailProjections?.get(d.baseKey)?.textTargets.keys()?.next();return h&&!h.done?h.value:null},async getTextWriteTarget(u,d){let g=l(u);return Xa(e.detailProjections?.get(g.baseKey)?.textTargets.get(d)??null,g.repeatIndex)},async getElementPropertyWriteTarget(u,d){let g=l(u);return Xa(e.detailProjections?.get(g.baseKey)?.elementPropertyTargets.get(d)??null,g.repeatIndex)},getTextProvenance(u,d){let g=l(u);return e.detailProjections?.get(g.baseKey)?.provenances.get(d)??null}};function l(u){let d=wf(u);return d?{baseKey:d.baseKey,repeatIndex:zf(e.document??null,u,d.baseKey)??Uf(d)}:{baseKey:u,repeatIndex:null}}function c(u,d){let g=ke(u)??u,h=e.document?.entries.find(y=>y.key===u),S=e.detailProjections?.get(g);return{key:u,file:d.sourceFile,component:d.componentName,tag:d.tag,structuralPath:d.identity.structuralPath,sourceRange:d.sourceRange,parentKey:h?.parentKey??d.parentKey??void 0,isRepeatRegion:d.boundaryKind==="repeat-region"||s.has(g),isBoundary:!1,importedFrom:d.importedFrom,exportName:d.exportName,isRepeatItemRoot:i.has(g),repeatOwnerKey:i.get(g)??s.get(g),contentModel:S?.contentModel,attributes:d.attributes?.map(y=>({name:y.name,value:y.value,source:y.source?{expression:y.source.expression,base:y.source.base,path:y.source.path.map(k=>({...k}))}:null,resolvedValue:y.resolvedValue}))}}}var Df={"stale-version":G.VERSION_STALE,"capability-denied":G.CAPABILITY_REJECTED,"invalid-params":G.INVALID_PARAMS,"locator-miss":G.LOCATOR_FAILED,"route-not-found":G.ROUTE_NOT_FOUND,"unsupported-operation":G.UNSUPPORTED_OPERATION,"invalid-target":G.INVALID_TARGET,"ast-error":G.AST_PARSE_ERROR,"writeback-failed":G.WRITE_IO_ERROR,"rollback-failed":G.ROLLBACK_FAILED,unknown:G.INTERNAL_ERROR};function Bn(e){return Df[e]}function Lo(e){return e instanceof Error&&e.message?e.message:String(e)}function $f(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function jo(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function Kf(e){let t=tt(e);if(!Ff.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=>Nf.map(a=>`${s}/${a}`))}function Bf(e){let n=tt(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function Jf(e){return Wa(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function Vf(e){return Wa(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function Wa(e,t){let n=[];for(let r of e.matchAll(t)){let o=Ua(r[1]??"");o&&n.push(o)}return n}function _a(e,t){let n=Ua(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?tt(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?tt(`${_f(e)}/${n}`):n.startsWith("/")?tt(n.slice(1)):Do(n)?tt(n):null}function Ua(e){return e.split(/[?#]/,1)[0]?.trim()??""}function Do(e){return/\.css$/i.test(e)}function _f(e){let t=tt(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function za(e){return Array.from(new Set(e))}function tt(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 Xf(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 Jn(e){return e?.map(t=>({...t}))}function Xa(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=Jn(e.collectionPathMap?.[t])??Jn(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:Jn(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>Jn(o)??[])}}function Wf(e,t,n){let r=new Set;for(let h of t.regions)if(h.kind==="repeat-region")for(let S of h.childKeys)r.add(S);if(r.size===0)return e;let o=new Map(e.entries.map(h=>[h.key,h])),i=[],s=new Map,a=(h,S)=>Rf(h,S),l=(h,S,y)=>{let k=o.get(h);if(!k)return a(h,y);let E=a(h,y),R={...k,key:E,parentKey:S,childKeys:[]};return i.push(R),R.childKeys=k.childKeys.flatMap(I=>c(I,y,E)),E},c=(h,S,y)=>{if(!r.has(h))return[l(h,y,S)];let k=d(h,S),E=[];for(let R=0;R<k;R+=1)E.push(l(h,y,[...S,R]));return E},u=za([...e.rootKeys,...e.entries.filter(h=>h.parentKey===null).map(h=>h.key)]);for(let h of u){if(!r.has(h)){l(h,null,[]);continue}let S=d(h,[]);for(let y=0;y<S;y+=1)l(h,null,[y])}return{...e,rootKeys:[...e.rootKeys],entries:i};function d(h,S){let y=new Set;for(let k of g(h)){let E=n.get(k);if(E){for(let R of[...E.textTargets.values(),...E.elementPropertyTargets.values()])if(!(R?.kind!=="value-binding"||R.sourceKind!=="repeat-template"))for(let I of Hf(R))I.length<=S.length||Gf(I,S)&&y.add(I[S.length])}}return y.size>0?y.size:Xf(n.get(h))}function g(h){let S=s.get(h);if(S)return S;let y=[h],k=o.get(h);for(let E of k?.childKeys??[])y.push(...g(E));return s.set(h,y),y}}function Uf(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function zf(e,t,n){if(!e)return null;let o=e.entries.filter(i=>(ke(i.key)??i.key)===n).findIndex(i=>i.key===t);return o>=0?o:null}function Hf(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 Gf(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 Yf(e,t,n){if(!n)return{...e,key:t};let r=new Map(n.entries.map(c=>[c.key,c])),o=r.get(t);if(!o)return{...e,key:t};let i=[],s=o.parentKey;for(;s;){let c=r.get(s);if(!c)break;i.push({key:c.key,tag:c.tag,label:c.label}),s=c.parentKey}i.reverse();let a=o.childKeys.map(c=>r.get(c)).filter(c=>c!==void 0).map(c=>({key:c.key,tag:c.tag,label:c.label})),l=o.parentKey===null?[]:(r.get(o.parentKey)?.childKeys??[]).filter(c=>c!==o.key).map(c=>r.get(c)).filter(c=>c!==void 0).map(c=>({key:c.key,tag:c.tag,label:c.label}));return{...e,key:o.key,ancestors:i,children:a,siblings:l}}var _n=class{constructor(t){this.options=t,this.fileSystem=new Rt(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 zt(this.engine.getDocument(t),{siteId:this.options.siteId,snapshotId:this.options.snapshotId})}getObjectSummary(t,n){return Ht(this.engine.getRenderDetail(t,n))}getObjectEditContext(t,n){return Gt(this.engine.getRenderDetail(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}async planOperation(t){let n=qf.safeParse(t);if(!n.success)return{result:Ut(t,n.error.issues.map(i=>i.message))};let r=new Rt(this.options.files),o=this.createEngine(r,{emitEvents:!1});try{for(let c of this.options.routes)await o.setActiveRoute(c.routeId);let i=await o.execute(n.data);if(!i.ok)return{result:{ok:!1,error:{code:i.error?.code??"INTERNAL_ERROR",message:i.error?.message??"Operation failed"},data:{requestId:i.requestId,kind:i.kind,target:i.target,resultVersion:i.resultVersion}}};let s={ok:!0,data:_e(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let l=Qf.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(c=>({path:c.path,operation:c.before===void 0?"create":"update",expectedHash:c.before===void 0?void 0:re(c.before),fullContent:c.after})),changedRouteIds:this.getChangedRouteIds(a.map(c=>c.path)),diagnostics:[]});return this.options.onEvent?.({type:"site-edit.operation.planned",siteId:t.siteId,operationId:t.id,baseSnapshotId:t.baseSnapshotId,changedFiles:l.patches.map(c=>c.path),at:new Date().toISOString()}),{result:s,patchPlan:l}}finally{o.dispose()}}dispose(){this.engine.dispose()}createEngine(t,n={}){let r=n.emitEvents??!0;return Vn({projectRoot:"/snapshot",fileSystem:t,routes:this.options.routes.map(o=>({routeId:o.routeId,entryFile:o.entryFile})),onEvent:r&&this.options.onEvent?o=>{let i=Yt(o,{siteId:this.options.siteId,snapshotId:this.options.snapshotId});i&&this.options.onEvent?.(i)}:void 0,dev:this.options.dev})}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 em(e){return new _n(e)}import{SiteEditOperationRequestSchema as tm}from"@vcp-dev/contracts";import $o from"node:fs/promises";import Xn from"node:path";var Wn=class{constructor(t){this.options=t,this.engine=Vn({...t,fileSystem:this.createFileSystem()})}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)}getRenderDetail(t,n){return this.engine.getRenderDetail(t,n)}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}refreshSourceForKey(t,n){return this.engine.refreshSourceForKey(t,n)}execute(t){return this.engine.execute(t)}undo(){return this.engine.undo()}redo(){return this.engine.redo()}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 $o.readFile(Xn.join(n,r),"utf8")},async writeFile(r,o){await Kn(Xn.join(n,r),o)},async deleteFile(r){await $o.rm(Xn.join(n,r),{force:!0})},async exists(r){try{return await $o.access(Xn.join(n,r)),!0}catch{return!1}},getVersion(r){return t.get(r)??1},bumpVersion(r){let o=(t.get(r)??1)+1;return t.set(r,o),o}}}};function Ko(e){return new Wn(e)}var Un=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=Ko({projectRoot:t.projectRoot,fileSystem:t.fileSystem,routes:t.routes.map(n=>({routeId:n.routeId,entryFile:n.entryFile})),onEvent:n=>{let r=Yt(n,{siteId:t.siteId,snapshotId:t.snapshotId});if(r){t.onEvent?.(r);for(let o of this.listeners)o(r)}},dev:t.dev})}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:zt(this.engine.getDocument(t),{siteId:this.options.siteId,snapshotId:this.options.snapshotId})}}getObjectSummary(t,n){return{ok:!0,data:Ht(this.engine.getRenderDetail(t,n))}}getObjectEditContext(t,n){return{ok:!0,data:Gt(this.engine.getRenderDetail(t,n))}}getClassNameSource(t,n){return{ok:!0,data:this.engine.getClassNameSource(t,n)}}refreshSourceForKey(t,n){return this.engine.refreshSourceForKey(t,n)}async executeOperation(t){let n=tm.safeParse(t);if(!n.success)return Ut(t,n.error.issues.map(o=>o.message));let r=await this.engine.execute(n.data);if(!r.ok){let o=r.error;if(!o)throw new Error("executeOperation failed without an error payload");return{ok:!1,error:{code:o.code,message:o.message},data:{requestId:r.requestId,kind:r.kind,target:r.target,resultVersion:r.resultVersion}}}return{ok:!0,data:_e(r)}}async undo(){let t=await this.engine.undo();if(!t.ok){let n=t.error;if(!n)throw new Error("undo failed without an error payload");return{ok:!1,error:{code:n.code,message:n.message},data:{requestId:t.requestId,kind:t.kind,target:t.target,resultVersion:t.resultVersion}}}return{ok:!0,data:_e(t)}}async redo(){let t=await this.engine.redo();if(!t.ok){let n=t.error;if(!n)throw new Error("redo failed without an error payload");return{ok:!1,error:{code:n.code,message:n.message},data:{requestId:t.requestId,kind:t.kind,target:t.target,resultVersion:t.resultVersion}}}return{ok:!0,data:_e(t)}}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 nm(e){return new Un(e)}export{Un as PreviewFileSystemSiteEditEngineRuntime,_n as SnapshotSiteEditEngineRuntime,nm as createPreviewSiteEditEngineRuntime,em as createSiteEditEngineRuntime};
1
+ import{SiteEditOperationRequestSchema as mh,SiteEditPatchPlanSchema as hh}from"@vcp-dev/contracts";function He(e){return{requestId:e.requestId,kind:e.kind,target:e.target,resultVersion:e.resultVersion,affectedFiles:e.affectedFiles,...e.selectionRef?{selectionRef:e.selectionRef}:{}}}function sn(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 an(e,t){return{siteId:t.siteId,snapshotId:t.snapshotId,routeId:e.routeId,version:e.version,rootKeys:e.rootKeys,entries:e.entries.map(n=>({key:n.key,tag:n.tag,label:n.label,parentKey:n.parentKey,childKeys:n.childKeys,operationSummary:{canUpdateText:n.operationSummary.canUpdateText,canInsertChild:n.operationSummary.canInsertChild,canMove:n.operationSummary.canMove,canRemove:n.operationSummary.canRemove}}))}}function ln(e){return{key:e.key,tag:e.tag,label:e.label,sourceLocator:e.sourceLocator?{sourceFile:e.sourceLocator.sourceFile,componentName:e.sourceLocator.componentName,openingElementRange:{startLine:e.sourceLocator.openingElementRange.startLine,startColumn:e.sourceLocator.openingElementRange.startColumn,endLine:e.sourceLocator.openingElementRange.endLine,endColumn:e.sourceLocator.openingElementRange.endColumn},structuralPath:e.sourceLocator.structuralPath,textPreview:e.sourceLocator.textPreview}:void 0,capabilities:{constraints:e.capabilities.constraints},isOpaque:e.isOpaque,provenanceChain:e.provenanceChain?{editMode:e.provenanceChain.editMode,diagnostics:e.provenanceChain.diagnostics}:void 0,ancestors:e.ancestors}}function cn(e){return{key:e.key,componentName:e.componentName,sourceFile:e.sourceFile,capabilities:Dl(e.capabilities),writeTarget:{kind:e.writeTarget.kind,file:e.writeTarget.file,componentName:e.writeTarget.componentName,isProxy:e.writeTarget.isProxy},effectiveWriteTarget:e.effectiveWriteTarget?{kind:e.effectiveWriteTarget.kind,file:e.effectiveWriteTarget.file,isProxy:e.effectiveWriteTarget.isProxy,displayPath:e.effectiveWriteTarget.displayPath,sourceType:e.effectiveWriteTarget.sourceType,sourceId:e.effectiveWriteTarget.sourceId}:void 0,provenanceChain:jl(e),componentSemantic:$l(e.componentSemantic),textSegments:e.textSegments.map(t=>({index:t.index,value:t.value,editable:t.editable,source:t.source?{kind:t.source.kind,file:t.source.file,expression:t.source.expression,bindingName:t.source.bindingName,path:t.source.path}:null})),boundaryKind:e.boundaryKind,children:e.children,siblings:e.siblings}}function un(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:He(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 Dl(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}}function jl(e){return e.provenanceChain?{finalSource:e.provenanceChain.finalSource?{kind:e.provenanceChain.finalSource.kind,file:e.provenanceChain.finalSource.file,displayPath:e.provenanceChain.finalSource.displayPath,externalSource:e.provenanceChain.finalSource.externalSource?{sourceType:e.provenanceChain.finalSource.externalSource.sourceType,sourceId:e.provenanceChain.finalSource.externalSource.sourceId,adapterId:e.provenanceChain.finalSource.externalSource.adapterId}:void 0}:null,chain:e.provenanceChain.chain.map(t=>({kind:t.kind,file:t.file,displayName:t.displayName,canEditHere:t.canEditHere})),confidence:e.provenanceChain.confidence,editMode:e.provenanceChain.editMode,diagnostics:e.provenanceChain.diagnostics}:void 0}function $l(e){return e||void 0}import{composeSiteEditRepeatInstanceKey as dm,getSiteEditSourceDeleteProtectionReason as fm,isSiteEditTextSourcePath as pm,parseSiteEditRepeatInstanceKey as mm,SITE_EDIT_SOURCE_DELETE_CAPABILITY as hm,stripSiteEditRepeatInstanceKeys as Ie}from"@vcp-dev/contracts";function At(e,t,n){return`${e}::${t}::${n}`}var U={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",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",INTERNAL_ERROR:"INTERNAL_ERROR"};import*as xo from"@babel/parser";import mr from"@babel/traverse";import*as m from"@babel/types";import*as Bl from"@babel/parser";import*as ut from"@babel/types";import*as dt from"node:path";var fo=[".tsx",".ts",".jsx",".js"],_l=fo.map(e=>`${dt.sep==="\\"?"\\":"/"}index${e}`);function po(e){let t=[];for(let n of e.program.body)ut.isImportDeclaration(n)&&typeof n.source.value=="string"&&Nt(n.source.value)&&t.push(n.source.value),ut.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&Nt(n.source.value)&&t.push(n.source.value),ut.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&Nt(n.source.value)&&t.push(n.source.value);return t}function Nt(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function Kl(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=dt.dirname(e);return dt.join(n,t).replace(/\\/g,"/")}async function Vl(e,t){for(let n of fo){let r=`${e}${n}`;if(await t(r))return r}for(let n of _l){let r=`${e}${n}`;if(await t(r))return r}return null}async function Tt(e,t,n){let r=Kl(e,t);return Vl(r,n)}var dn="components/ui";function Ge(e){if(!e)return!1;let t=pr(e);return t===dn||t.startsWith(`${dn}/`)||t.includes(`/${dn}/`)||t.endsWith(`/${dn}`)}function mo(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?Ge(e.slice(2)):e.startsWith("./")||e.startsWith("../")?Ge(pr(`${Jl(t)}/${e}`)):Ge(e):!1}function pr(e){let n=(e.split("?")[0]??e).replace(/\\/g,"/").replace(/^\.\//,""),r=[];for(let i of n.split("/"))if(!(!i||i===".")){if(i===".."){r.pop();continue}r.push(i)}return r.join("/")}function Jl(e){let t=pr(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}var Xl=typeof mr=="function"?mr:mr.default;function Wl(e){try{return xo.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function ae(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 Ul(e){return/^[A-Z]/.test(e)}function Sr(e){let t=e.openingElement;return m.isJSXIdentifier(t.name)?t.name.name==="Fragment":m.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function pt(e){return m.isJSXFragment(e)}function yo(e){return m.isJSXIdentifier(e.name)?e.name.name:m.isJSXMemberExpression(e.name)?So(e.name):m.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function So(e){return m.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:m.isJSXMemberExpression(e.object)?`${So(e.object)}.${e.property.name}`:e.property.name}function zl(e){return e.split(".")[0]??e}function Hl(e){let t=e;for(;t;){let n=t.node;if(m.isFunctionDeclaration(n)&&n.id||m.isVariableDeclarator(n)&&m.isIdentifier(n.id))return n.id.name;if(m.isExportDefaultDeclaration(n)){let r=n.declaration;if(m.isFunctionDeclaration(r)&&r.id)return r.id.name;if(m.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function Gl(){let e=new Map;return{getOrdinal(t,n){let r=t??"__root__";e.has(r)||e.set(r,new Map);let i=e.get(r),o=i.get(n)??0;return i.set(n,o+1),o}}}function Yl(e){let t=new Map;for(let n of e.program.body){if(!m.isImportDeclaration(n))continue;let r=n.source.value;for(let i of n.specifiers)if(m.isImportDefaultSpecifier(i))t.set(i.local.name,{specifier:r,exportName:"default"});else if(m.isImportNamespaceSpecifier(i))t.set(i.local.name,{specifier:r,exportName:"*"});else if(m.isImportSpecifier(i)){let o=m.isIdentifier(i.imported)?i.imported.name:i.imported.value;t.set(i.local.name,{specifier:r,exportName:o})}}return t}function Ae(e,t=[]){if(m.isIdentifier(e))return t.push(e.name),t;if(m.isObjectPattern(e)){for(let n of e.properties)m.isObjectProperty(n)?Ae(n.value,t):m.isRestElement(n)&&Ae(n.argument,t);return t}if(m.isArrayPattern(e)){for(let n of e.elements)n&&(m.isRestElement(n)?Ae(n.argument,t):Ae(n,t));return t}return m.isAssignmentPattern(e)?(Ae(e.left,t),t):(m.isRestElement(e)&&Ae(e.argument,t),t)}function De(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function fn(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 Zl(e,t,n){e.set(t,{resolved:!0,value:n})}function kr(e,t){e.set(t,{resolved:!1})}function ko(e,t){let n=e;for(let r of t){if(r.kind==="property"){if(n==null||Array.isArray(n)||typeof n!="object"||!(r.name in n))return{kind:"known-empty"};n=n[r.name];continue}if(!Array.isArray(n)||r.index<0||r.index>=n.length)return{kind:"known-empty"};n=n[r.index]}return{kind:"resolved",value:n}}function Ne(e,t,n){if(m.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!m.isMemberExpression(e))return null;let r=[],i=e;for(;m.isMemberExpression(i);){if(i.computed)if(m.isNumericLiteral(i.property))r.unshift({kind:"index",index:i.property.value});else if(m.isStringLiteral(i.property))r.unshift({kind:"property",name:i.property.value});else if(n&&m.isExpression(i.property)){let o=Ze(i.property,n);if(typeof o=="string")r.unshift({kind:"property",name:o});else if(Number.isInteger(o))r.unshift({kind:"index",index:o});else return null}else return null;else{if(!m.isIdentifier(i.property))return null;r.unshift({kind:"property",name:i.property.name})}i=i.object}return m.isIdentifier(i)?{kind:r.some(o=>o.kind==="index")?"index-expression":"member-expression",expression:De(e,t),base:i.name,path:r}:null}function Ze(e,t){if(m.isStringLiteral(e)||m.isNumericLiteral(e)||m.isBooleanLiteral(e))return e.value;if(m.isNullLiteral(e))return null;if(m.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(m.isIdentifier(e)){let n=fn(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(m.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||m.isSpreadElement(r))return;let i=Ze(r,t);if(i===void 0)return;n.push(i)}return n}if(m.isObjectExpression(e)){let n={};for(let r of e.properties){if(!m.isObjectProperty(r)||r.computed||!m.isExpression(r.value))return;let i=null;if(m.isIdentifier(r.key)?i=r.key.name:m.isStringLiteral(r.key)&&(i=r.key.value),!i)return;let o;if(r.shorthand){if(!m.isIdentifier(r.value))return;let s=fn(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;o=s.value}else o=Ze(r.value,t);if(o===void 0)return;n[i]=o}return n}if(m.isMemberExpression(e)){let n=Ne(e,"",t);if(!n)return;let r=fn(n.base,t.valueScopes);if(r.kind!=="resolved")return;let i=ko(r.value,n.path);return i.kind==="resolved"?i.value:void 0}if(m.isCallExpression(e))return vo(e,t)??void 0}function bo(e,t,n){let r=Ne(e,n,t);if(!r)return m.isMemberExpression(e)||m.isBinaryExpression(e)||m.isLogicalExpression(e)||m.isConditionalExpression(e)||m.isCallExpression(e)?{value:De(e,n),source:null}:null;let i=fn(r.base,t.valueScopes),o=r.kind==="identifier"?i:i.kind==="resolved"?ko(i.value,r.path):i;return o.kind==="resolved"&&(typeof o.value=="string"||typeof o.value=="number")?{value:String(o.value),source:r}:o.kind==="resolved"&&(typeof o.value=="boolean"||o.value===null)||o.kind==="known-empty"?null:{value:r.expression,source:r}}function hr(e,t,n,r,i,o){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:Gl(),parentStack:[],valueScopes:o,importMap:i}}function xr(e,t,n){for(let r of e)for(let i of r.declarations){for(let s of Ae(i.id))kr(n,s);if(!m.isIdentifier(i.id)||!i.init||!m.isExpression(i.init))continue;let o=Ze(i.init,t);o!==void 0&&Zl(n,i.id.name,o)}}function Ql(e){let t=[];for(let n of e){if(m.isVariableDeclaration(n)){t.push(n);continue}m.isExportNamedDeclaration(n)&&n.declaration&&m.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function ql(e,t,n){let r=[],i=0;for(let o of e)if(m.isJSXText(o)){let s=o.value.trim();s&&r.push({index:i++,value:s,sourceRange:ae(o),editable:!0,source:null})}else if(m.isJSXExpressionContainer(o)&&m.isStringLiteral(o.expression))r.push({index:i++,value:o.expression.value,sourceRange:ae(o),editable:!0,source:null});else if(m.isJSXExpressionContainer(o)&&m.isTemplateLiteral(o.expression)){let s=o.expression;s.expressions.length===0&&s.quasis.length===1?r.push({index:i++,value:s.quasis[0].value.cooked??s.quasis[0].value.raw,sourceRange:ae(o),editable:!0,source:null}):r.push({index:i++,value:De(s,n),sourceRange:ae(o),editable:!0,source:null})}else if(m.isJSXExpressionContainer(o)&&m.isExpression(o.expression)){let s=bo(o.expression,t,n);s&&r.push({index:i++,value:s.value,sourceRange:ae(o),editable:!0,source:s.source})}return r}function ec(e,t,n){let r=[];for(let i of e.attributes)if(!(!m.isJSXAttribute(i)||!m.isJSXIdentifier(i.name))){if(m.isStringLiteral(i.value)){r.push({name:i.name.name,value:i.value.value,sourceRange:ae(i),source:null});continue}if(m.isJSXExpressionContainer(i.value)&&m.isExpression(i.value.expression)){let o=Ze(i.value.expression,t);if(i.name.name==="className"){let a=typeof o=="string"?o:o===void 0?vo(i.value.expression,t):null;if(a){r.push({name:i.name.name,value:a,sourceRange:ae(i),source:null,resolvedValue:a});continue}}let s=bo(i.value.expression,t,n);if(o!==void 0&&typeof o!="string"&&typeof o!="number"){r.push({name:i.name.name,value:ho(o),sourceRange:ae(i),source:Ne(i.value.expression,n,t),resolvedValue:o});continue}if(!s){o!==void 0&&r.push({name:i.name.name,value:ho(o),sourceRange:ae(i),source:Ne(i.value.expression,n,t),resolvedValue:o});continue}r.push({name:i.name.name,value:s.value,sourceRange:ae(i),source:s.source})}}return r}function vo(e,t){let n=ft(e,t);return n&&n.map(i=>i.trim()).filter(Boolean).join(" ")||null}function ft(e,t){if(m.isStringLiteral(e))return[e.value];if(m.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(m.isNullLiteral(e))return[];if(m.isBooleanLiteral(e))return e.value?null:[];if(m.isIdentifier(e)||m.isMemberExpression(e)){if(m.isIdentifier(e)&&e.name==="undefined")return[];let n=Ze(e,t);return typeof n=="string"?[n]:null}if(m.isConditionalExpression(e)){let n=ft(e.consequent,t),r=ft(e.alternate,t);return!n||!r?null:[...n,...r]}if(m.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=Ze(e.left,t);return n===!1||n===null?[]:ft(e.right,t)}if(m.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||m.isSpreadElement(r))return null;let i=ft(r,t);if(!i)return null;n.push(...i)}return n}if(m.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!m.isObjectProperty(r))return null;let i=nc(r.key);if(!i)return null;n.push(i)}return n}if(m.isCallExpression(e)){let n=tc(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let i of e.arguments){if(!m.isExpression(i))return null;let o=ft(i,t);if(!o)return null;r.push(...o)}return r}return null}function tc(e){return m.isIdentifier(e)?e.name:m.isMemberExpression(e)&&m.isIdentifier(e.property)?e.property.name:null}function nc(e){return m.isIdentifier(e)?e.name:m.isStringLiteral(e)?e.value:null}function rc(e,t){let n=e.attributes.find(r=>m.isJSXAttribute(r)&&m.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!m.isJSXAttribute(n)||!m.isJSXExpressionContainer(n.value)?null:n.value.expression}function ic(e,t){for(let n of t){let r=rc(e,n);if(r)return r}return null}function oc(e){return m.isJSXIdentifier(e.name)?e.name.name:null}function ho(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function sc(e){if(!m.isCallExpression(e)&&!m.isOptionalCallExpression(e))return null;let t=e.callee;return!m.isMemberExpression(t)&&!m.isOptionalMemberExpression(t)||!m.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!m.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function gr(e){return m.isArrowFunctionExpression(e)||m.isFunctionExpression(e)}function ac(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function lc(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function go(e,t,n,r){if(!e||!m.isExpression(e))return null;let i={kind:"repeat-template",collectionExpression:De(e,n),collectionSource:Ne(e,n,r)};if(t){let o=t.params[0],s=t.params[1];m.isIdentifier(o)&&(i.itemParamName=o.name),m.isIdentifier(s)&&(i.indexParamName=s.name)}return i}function je(e,t,n){if(!e)return[];if(m.isJSXElement(e)){if(Sr(e))return xn(e.children,t,n);let r=hn(e,t,n);return r?[r]:[]}return pt(e)?gn(e,t,n):m.isParenthesizedExpression(e)?je(e.expression,t,n):m.isExpression(e)?yn(e,t,n):[]}function pn(e,t,n){let r=new Map;for(let i of e.params)for(let o of Ae(i))kr(r,o);t.valueScopes.push(r);try{if(!m.isBlockStatement(e.body))return je(e.body,t,n);let i=new Map;t.valueScopes.push(i);try{return Eo(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function Eo(e,t,n){let r=[];for(let i of e){if(m.isVariableDeclaration(i)){let o=t.valueScopes[t.valueScopes.length-1];o&&xr([i],t,o);continue}r.push(...yr(i,t,n))}return r}function yr(e,t,n){if(m.isReturnStatement(e))return e.argument?je(e.argument,t,n):[];if(m.isBlockStatement(e))return Ye(e.body,t,n);if(m.isIfStatement(e)){let r=m.isBlockStatement(e.consequent)?Ye(e.consequent.body,t,n):yr(e.consequent,t,n),i=e.alternate?m.isBlockStatement(e.alternate)?Ye(e.alternate.body,t,n):yr(e.alternate,t,n):[];return[...r,...i]}if(m.isSwitchStatement(e))return Ye(e.cases.flatMap(r=>r.consequent),t,n);if(m.isTryStatement(e)){let r=Ye(e.block.body,t,n);return e.handler&&r.push(...Ye(e.handler.body.body,t,n)),e.finalizer&&r.push(...Ye(e.finalizer.body,t,n)),r}return[]}function Ye(e,t,n){let r=new Map;t.valueScopes.push(r);try{return Eo(e,t,n)}finally{t.valueScopes.pop()}}function mn(e,t,n,r,i,o){i.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:i,sourceRange:ae(r),sourceCandidates:o&&o.length>0?o:void 0})}function cc(e,t,n,r){let i=ic(e.openingElement,["items","dataSource","data"]),o={key:t,tag:yo(e.openingElement)};n.parentStack.push(o);try{for(let s of e.openingElement.attributes){if(!m.isJSXAttribute(s))continue;let a=oc(s);if(!a||!m.isJSXExpressionContainer(s.value))continue;let l=s.value.expression;if(!m.isJSXEmptyExpression(l)){if(ac(a)&&gr(l)){let u=pn(l,n,r),c=go(i,l,r,n);mn(n,"repeat-region",t,s,u,c?[c]:void 0);continue}if(lc(a)){let u=gr(l)?pn(l,n,r):je(l,n,r);mn(n,"conditional-region",t,s,u)}}}if(i)for(let s of e.children){if(!m.isJSXExpressionContainer(s)||!gr(s.expression))continue;let a=pn(s.expression,n,r),l=go(i,s.expression,r,n);mn(n,"repeat-region",t,s,a,l?[l]:void 0)}}finally{n.parentStack.pop()}}function hn(e,t,n){let r=yo(e.openingElement);if(r==="Fragment"||Sr(e))return xn(e.children,t,n),null;let i=t.parentStack[t.parentStack.length-1]??null,o=i?.key??null,s=Ul(r),a;if(s){let I=t.ordinalTracker.getOrdinal(o,r);a=`component:${r}#${I}`}else{let I=t.ordinalTracker.getOrdinal(o,r);a=`${r}#${I}`}let l=i?t.elements.get(i.key)?.identity.structuralPath:void 0,u=l?`${l}/${a}`:a,c=At(t.file,t.componentName,u),d={file:t.file,component:t.componentName,structuralPath:u,key:c},p=s?"component-boundary":null,h=ql(e.children,t,n),k=ec(e.openingElement,t,n),b,E,P=!1;if(s){let I=t.importMap.get(r)??t.importMap.get(zl(r));I&&(b=I.specifier,E=I.exportName,P=mo(I.specifier,t.file))}let R={identity:d,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:ae(e),parentKey:o,childKeys:[],textSegments:h,attributes:k.length>0?k:void 0,boundaryKind:p,isOpaque:s,...P?{isPublicUiComponent:!0}:{},importedFrom:b,exportName:E};return t.elements.set(c,R),o&&t.elements.has(o)&&t.elements.get(o).childKeys.push(c),cc(e,c,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:c,tag:r}),uc(e.children,t,n),t.parentStack.pop()),c}function gn(e,t,n){return xn(e.children,t,n)}function xn(e,t,n){let r=[];for(let i of e)if(m.isJSXElement(i))if(Sr(i))r.push(...xn(i.children,t,n));else{let o=hn(i,t,n);o&&r.push(o)}else pt(i)?r.push(...gn(i,t,n)):m.isJSXExpressionContainer(i)&&r.push(...yn(i.expression,t,n));return r}function uc(e,t,n){for(let r of e)m.isJSXElement(r)?hn(r,t,n):pt(r)?gn(r,t,n):m.isJSXExpressionContainer(r)&&yn(r.expression,t,n)}function dc(e){return e==="&&"||e==="||"||e==="??"}function yn(e,t,n){if(m.isJSXEmptyExpression(e))return[];let r=sc(e);if(r){let i=r.call,o=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,l={kind:"repeat-template",collectionExpression:De(r.collection,n),collectionSource:Ne(r.collection,n,t)};if(m.isArrowFunctionExpression(a)||m.isFunctionExpression(a)){let c=a.params[0],d=a.params[1];m.isIdentifier(c)&&(l.itemParamName=c.name),m.isIdentifier(d)&&(l.indexParamName=d.name)}s.push(l);let u={kind:"repeat-region",ownerKey:o?.key??"",childKeys:[],sourceRange:ae(i),sourceCandidates:s.length>0?s:void 0};return t.regions.push(u),(m.isArrowFunctionExpression(a)||m.isFunctionExpression(a))&&u.childKeys.push(...pn(a,t,n)),u.childKeys}if(m.isConditionalExpression(e)){let i=t.parentStack[t.parentStack.length-1]??null,o={kind:"conditional-branch",conditionExpression:De(e.test,n),conditionSource:Ne(e.test,n,t)},s={kind:"conditional-region",ownerKey:i?.key??"",childKeys:[],sourceRange:ae(e),sourceCandidates:[o]};return t.regions.push(s),s.childKeys.push(...je(e.consequent,t,n)),s.childKeys.push(...je(e.alternate,t,n)),s.childKeys}if(m.isLogicalExpression(e)&&dc(e.operator)){let i=t.parentStack[t.parentStack.length-1]??null,o={kind:"conditional-branch",conditionExpression:De(e.left,n),conditionSource:Ne(e.left,n,t)},s={kind:"conditional-region",ownerKey:i?.key??"",childKeys:[],sourceRange:ae(e),sourceCandidates:[o]};return t.regions.push(s),s.childKeys.push(...je(e.right,t,n)),s.childKeys}if(m.isParenthesizedExpression(e))return yn(e.expression,t,n);if(m.isJSXElement(e)){let i=hn(e,t,n);return i?[i]:[]}return pt(e)?gn(e,t,n):[]}function fc(e){let t=e.argument;return t&&(m.isExpression(t)||pt(t))?t:null}function Mt(e,t){let n=[];for(let r of e){if(m.isReturnStatement(r)){let i=fc(r);i&&n.push({argument:i,statement:r,condition:t});continue}if(m.isIfStatement(r)){let i=m.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...Mt(i,r.test)),r.alternate){let o=m.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...Mt(o,r.test))}continue}if(m.isSwitchStatement(r))for(let i of r.cases){let o=i.test?m.binaryExpression("===",r.discriminant,i.test):r.discriminant;n.push(...Mt(i.consequent,o))}}return n}function Co(e,t){let n={routeId:e,rootKeys:[],elements:new Map,regions:[],fileIndex:new Map,version:1},r=Wl(t);if(!r)return{graph:n,localImports:[]};let i=po(r),o=new Map,s=[],a=[],l=new Map,u=Yl(r);Xl(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(d){let p=Hl(d);if(!p)return;let h=d.node,k=[];if(m.isArrowFunctionExpression(h))m.isExpression(h.body)||pt(h.body)?k=[{argument:h.body,statement:m.returnStatement(m.isExpression(h.body)?h.body:null)}]:m.isBlockStatement(h.body)&&(k=Mt(h.body.body));else{let B=h.body;m.isBlockStatement(B)&&(k=Mt(B.body))}if(k.length===0){d.skip();return}let b=new Map;xr(Ql(r.program.body),hr(e,p,o,s,u,[b]),b);let E=new Map;for(let B of h.params)for(let G of Ae(B))kr(E,G);let P=m.isBlockStatement(h.body)?h.body.body:[],R=k[0]?.statement??null;for(let B of P){if(R&&B===R)break;m.isVariableDeclaration(B)&&xr([B],hr(e,p,o,s,u,[b,E]),E)}let I=hr(e,p,o,s,u,[b,E]);for(let B of k){let G=je(B.argument,I,t);for(let C of G)a.includes(C)||a.push(C);if(B.condition){let C={kind:"conditional-branch",conditionExpression:De(B.condition,t),conditionSource:Ne(B.condition,t,I)};mn(I,"conditional-region","",B.statement,G,[C])}}d.skip()}});let c=[...o.keys()];return c.length>0&&l.set(e,c),{graph:{routeId:e,rootKeys:a,elements:o,regions:s,fileIndex:l,version:1},localImports:i}}async function Io(e,t,n,r,i={}){let o=i.maxDepth??10,s=i.version??1,a=new Map,l=new Map,u=[{file:e,source:t,depth:0},...(i.additionalEntries??[]).map(p=>({file:p.file,source:p.source,depth:0}))],c=new Set;for(;u.length>0;){let p=u.shift(),{file:h,source:k,depth:b}=p;if(c.has(h))continue;c.add(h),a.set(h,k);let{graph:E,localImports:P}=Co(h,k);for(let R of E.elements.values())if(R.importedFrom&&Nt(R.importedFrom))try{let I=await Tt(h,R.importedFrom,r);I&&(R.importedFrom=I,Ge(I)&&(R.isPublicUiComponent=!0))}catch{}if(l.set(h,E),!(b>=o))for(let R of P)try{let I=await Tt(h,R,r);if(!I||c.has(I)||Ge(I))continue;let B=await n(I);u.push({file:I,source:B,depth:b+1})}catch{}}return{graph:pc(e,l,s,(i.additionalEntries??[]).map(p=>p.file)),allSources:a}}function pc(e,t,n,r=[]){let i=new Map,o=[],s=new Map,a=[];for(let[l,u]of t){for(let[c,d]of u.elements)i.set(c,d);for(let c of u.regions)o.push(c);for(let[c,d]of u.fileIndex){let p=s.get(c)??[];s.set(c,[...p,...d])}if(l===e){a=u.rootKeys;continue}r.includes(l)&&(a=[...a,...u.rootKeys])}return{routeId:e,rootKeys:a,elements:i,regions:o,fileIndex:s,version:n}}function Po(e){let t=new Map;for(let[n,r]of e.elements){let i=/^[A-Z]/.test(r.tag),o={file:r.sourceFile,componentName:r.componentName,isProxy:i},s=r.boundaryKind,a=[];r.isOpaque&&a.push({kind:"opaque-region",reason:`Component '${r.tag}' is opaque: internal structure not editable`}),i&&!r.isOpaque&&a.push({kind:"component-boundary",reason:`Component '${r.tag}' boundary: editing requires source file access`});let l={key:n,writeTarget:o,boundaryKind:s,parentKey:r.parentKey,childKeys:[...r.childKeys],constraints:a};t.set(n,l)}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",i=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 o of n.childKeys){let s=t.get(o);s&&s.constraints.push({kind:r,reason:i}),Ro(o,r,i,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function Ro(e,t,n,r,i){let o=i.elements.get(e);if(o)for(let s of o.childKeys){let a=r.get(s);a&&!a.constraints.some(l=>l.kind===t)&&(a.constraints.push({kind:t,reason:n}),Ro(s,t,n,r,i))}}import{isSiteEditRuntimeContainerTag as mc,isSiteEditRuntimeVoidElementTag as hc}from"@vcp-dev/contracts/site-edit-runtime-capability";function gc(e,t,n){let r=t.nodes.get(e),i=n.elements.get(e);if(!r||!i)return{key:e,canUpdateText:!1,canInsertChild:!1,canMove:!1,canRemove:!1,constraints:[{kind:"opaque-region",message:"Node not found in graph"}]};let o=r.constraints.map(I=>({kind:I.kind,message:I.reason})),s=i.isOpaque,l=r.parentKey===null&&i.componentName==="Page",u=i.tag.toLowerCase(),c=i.tag!==u,d=!c&&hc(u),p=c||mc(u),h=c&&i.childKeys.length>0&&!i.isPublicUiComponent,k=i.textSegments.length>0&&i.textSegments.some(I=>I.editable);d&&!o.some(I=>I.kind==="void-element")&&o.push({kind:"void-element",message:`Element '${i.tag}' is void: children cannot be inserted`}),!d&&!p&&!o.some(I=>I.kind==="void-element")&&o.push({kind:"void-element",message:`Element '${i.tag}' cannot contain structured children`});let b=k&&!s,E=!i.isPublicUiComponent&&!d&&p&&(!s||h);return{key:e,canUpdateText:b,canInsertChild:E,canMove:!l,canRemove:!l,constraints:o}}function wo(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,gc(r,e,t));return n}function xc(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var yc=160;function Fo(e,t,n,r={}){let i=[];for(let[o,s]of e.elements){let a=n.get(o),l={canUpdateText:r.canUpdateTextByKey?.get(o)??a?.canUpdateText??!1,canInsertChild:a?.canInsertChild??!1,canMove:a?.canMove??!1,canRemove:a?.canRemove??!1};i.push({key:o,tag:s.tag,label:s.tag===s.componentName?s.tag:`${s.tag} (${s.componentName})`,parentKey:s.parentKey,childKeys:[...s.childKeys],operationSummary:l})}return{routeId:e.routeId,version:e.version,rootKeys:[...e.rootKeys],entries:i}}function Ao(e,t,n,r,i,o,s,a,l,u,c,d){let p=t.elements.get(e),h=n.nodes.get(e),k=r.get(e);if(!p||!h||!k)throw new Error(`Node not found: ${e}`);let b=vc(p.textSegments,s),E=Ec(e,t,p,k,b),P=b?Ic(b):void 0,R=Pc(o,b),I=p.textSegments.map(F=>({index:F.index,value:F.value,editable:Cc(F,k,s?.get(F.index)??null),source:i.get(F.index)??null})),B=[],G=p.parentKey;for(;G;){let F=t.elements.get(G);if(!F)break;B.push({key:G,tag:F.tag,label:F.tag}),G=F.parentKey}B.reverse();let C=p.childKeys.map(F=>{let A=t.elements.get(F);return A?{key:F,tag:A.tag,label:A.tag}:null}).filter(F=>F!==null),j=[];if(p.parentKey){let F=t.elements.get(p.parentKey);if(F)for(let A of F.childKeys){if(A===e)continue;let z=t.elements.get(A);z&&j.push({key:A,tag:z.tag,label:z.tag})}}return{key:e,tag:p.tag,componentName:p.componentName,sourceFile:p.sourceFile,sourceLocator:Sc(p),label:p.tag,capabilities:E,writeTarget:o,effectiveWriteTarget:R,provenanceChain:P,componentSemantic:l,contentModel:u,mediaModel:c,styleSource:d,conditional:a,textSegments:I,boundaryKind:p.boundaryKind,isOpaque:p.isOpaque,ancestors:B,children:C,siblings:j}}function Sc(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:kc(e.sourceRange),structuralPath:e.identity.structuralPath,...bc(e.textSegments)}}function kc(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function bc(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,yc)}:{}}function No(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 vc(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function Ec(e,t,n,r,i){let o=n.identity.structuralPath.includes("#repeat:"),s=t.regions.some(c=>c.kind==="repeat-region"&&c.childKeys.includes(e)),a=i?.diagnostics.find(c=>c.code==="missing-adapter"||c.code==="external-source-readonly")?.code,l=r.canUpdateText?{mode:i?.editMode??"direct",reasonCode:a??(i?.editMode==="upstream"?"component-prop":i?.finalSource?.kind==="repeat-template"?"repeat-item-data":void 0)}:{mode:"unsupported",reasonCode:"capability-denied"},u=r.canUpdateText&&To(l.mode);return{...r,canUpdateText:u,editModes:{updateText:l,insertChild:r.canInsertChild?{mode:"direct",reasonCode:o||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 Cc(e,t,n){return!e.editable||!t.canUpdateText?!1:n?To(n.editMode):!0}function To(e){return e==="direct"||e==="proxy"||e==="upstream"}function Ic(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 Pc(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}:xc(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 Mo(e){let{key:t,element:n,graph:r,provenances:i}=e,o=wc(t,n,r),s=o?.tag??(Qe(n.tag)?n.tag:n.componentName),a=o?.identity.key??Lo(n,r)??t,l=Nc(o),u=Tc(t,n,r,i,o),c=Rc(t,n,r,i,a);return{componentName:s,instanceKey:a,templateOwner:Ac(o??n,s),...l.length>0?{variantKeys:l}:{},...u.length>0?{slotKeys:u}:{},editableStrategy:c,impactScope:Mc(c),alternativeStrategies:Lc(c)}}function Rc(e,t,n,r,i){for(let o of r.values())if(o?.editMode==="upstream")return"upstream";return br(e,n)?"instance":!Qe(t.tag)&&t.sourceFile!==n.routeId&&i!==e?"template":"instance"}function Lo(e,t){if(Qe(e.tag))return e.identity.key;let n=[...t.elements.values()].filter(r=>r.importedFrom===e.sourceFile&&Fc(r,e.componentName));return n.length!==1?null:n[0].identity.key}function wc(e,t,n){if(Qe(t.tag))return t;let r=br(e,n);if(r)return r;let i=Lo(t,n);return i?n.elements.get(i)??null:null}function Fc(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function Ac(e,t){return Qe(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function Nc(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 Tc(e,t,n,r,i){let o=new Set,s=br(e,n);s&&i?.identity.key===s.identity.key&&o.add("children");for(let a of r.values()){let l=a?.chain.find(c=>c.kind==="component-prop");if(!l)continue;let u=l.displayName.split(".").pop();u&&o.add(u)}return o.size===0&&Qe(t.tag)&&t.childKeys.length>0&&o.add("children"),[...o]}function br(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(Qe(r.tag))return r;n=r.parentKey}return null}function Qe(e){return/^[A-Z]/.test(e)}function Mc(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function Lc(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}var Oc=new Set(["markdown","body","content","value","document"]),Oo=[];function jo(e){if(!(!$c(e.tag)||!e.attributes))for(let t of e.attributes){if(!Oc.has(t.name))continue;if(jc(t))return{kind:"markdown",field:t.name,schema:"markdown",valuePath:t.source?.expression,operationBoundary:Oo};let n=Dc(t.resolvedValue);if(n==="prosemirror-doc"||n==="node-array")return{kind:"rich-text-json",field:t.name,valuePath:t.source?.expression,schema:n,operationBoundary:Oo};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 Dc(e){if(e){if(Array.isArray(e)&&e.every(t=>Do(t)))return"node-array";if(Do(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 Do(e){return!Array.isArray(e)&&typeof e=="object"&&e!==null}function jc(e){return e.name==="markdown"}function $c(e){return/^[A-Z]/.test(e)}var Bc=["src","alt","poster","caption","width","height"];function $o(e){let t=e.attributes?.filter(o=>Bc.includes(o.name))??[];if(t.length===0)return;let n=t.map(o=>o.name),r=Object.fromEntries(t.filter(o=>o.source?.expression).map(o=>[o.name,o.source.expression])),i=Kc(t.map(o=>o.value));return{kind:_c(e.tag,n),sourceType:i,fields:n,editableFields:[],operationBoundary:[],...Object.keys(r).length>0?{valuePaths:r}:{}}}function _c(e,t){return e==="img"?"image":e==="video"||t.includes("poster")?"video":"media"}function Kc(e){return e.some(t=>t.startsWith("cms:"))?"cms-media-field":e.some(t=>/^(\.?\/|\/)/.test(t))?"local-file-reference":"asset-id"}var vr=["set-class-name-source","apply-style-draft"],Bo=["block","inline-block","inline","flex","inline-flex","grid","inline-grid","hidden"],_o=["static","fixed","absolute","relative","sticky"],Rr=["z-auto","z-0","z-10","z-20","z-30","z-40","z-50"],Ko=["flex-row","flex-row-reverse","flex-col","flex-col-reverse"],Vo=["flex-nowrap","flex-wrap","flex-wrap-reverse"],Er=["grow","grow-0"],Cr=["shrink","shrink-0"],wr=["basis-auto","basis-full","basis-1/2","basis-1/3","basis-2/3","basis-1/4","basis-3/4","basis-px"],Fr=["order-first","order-last","order-none","order-1","order-2","order-3","order-4","order-5","order-6"],Ar=["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"],Nr=["grid-rows-1","grid-rows-2","grid-rows-3","grid-rows-4","grid-rows-5","grid-rows-6","grid-rows-none","grid-rows-subgrid"],Tr=["col-auto","col-span-1","col-span-2","col-span-3","col-span-4","col-span-6","col-span-12","col-span-full"],Mr=["row-auto","row-span-1","row-span-2","row-span-3","row-span-4","row-span-6","row-span-full"],Jo=["items-start","items-end","items-center","items-baseline","items-stretch"],Xo=["justify-normal","justify-start","justify-end","justify-center","justify-between","justify-around","justify-evenly","justify-stretch"],Wo=["overflow-auto","overflow-hidden","overflow-clip","overflow-visible","overflow-scroll"],Ir=["font-sans","font-serif","font-mono"],Lr=["font-thin","font-extralight","font-light","font-normal","font-medium","font-semibold","font-bold","font-extrabold","font-black"],Or=["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"],Dr=["text-left","text-center","text-right","text-justify","text-start","text-end"],Uo=["uppercase","lowercase","capitalize","normal-case"],zo=["underline","overline","line-through","no-underline"],jr=["indent-0","indent-4","indent-8","indent-12"],Ho=["[writing-mode:horizontal-tb]","[writing-mode:vertical-rl]"],Go=["whitespace-normal","whitespace-nowrap","whitespace-pre","whitespace-pre-line","whitespace-pre-wrap","whitespace-break-spaces"],Yo=["break-normal","break-words","break-all","break-keep"],$r=["line-clamp-none","line-clamp-1","line-clamp-2","line-clamp-3","line-clamp-4","line-clamp-5","line-clamp-6"],Pr=["tracking-tighter","tracking-tight","tracking-normal","tracking-wide","tracking-wider","tracking-widest"],Br=["border-solid","border-dashed","border-dotted","border-double","border-hidden","border-none"],_r=["border","border-0","border-2","border-4","border-8"],Zo=["object-contain","object-cover","object-fill","object-none","object-scale-down"],Kr=["aspect-auto","aspect-square","aspect-video"],Vr=["shadow-none","shadow-sm","shadow","shadow-md","shadow-lg","shadow-xl","shadow-2xl"],Hh=[{property:"display",exact:Bo,isMatch:e=>e==="gallery-item",options:[...Bo]},{property:"position",exact:_o,isMatch:e=>e==="cta-shine",options:[..._o]},{property:"top",isMatch:e=>Sn("top",e)},{property:"right",isMatch:e=>Sn("right",e)},{property:"bottom",isMatch:e=>Sn("bottom",e)},{property:"left",isMatch:e=>Sn("left",e)},{property:"zIndex",exact:Rr,isMatch:Yc,options:[...Rr]},{property:"flexDirection",exact:Ko,options:[...Ko]},{property:"flexWrap",exact:Vo,options:[...Vo]},{property:"flexGrow",exact:Er,isMatch:e=>Er.includes(e)||/^grow-\[.+\]$/.test(e),options:[...Er]},{property:"flexShrink",exact:Cr,isMatch:e=>Cr.includes(e)||/^shrink-\[.+\]$/.test(e)||/^flex-shrink-(?:0|\[.+\])$/.test(e),options:[...Cr]},{property:"flexBasis",exact:wr,isMatch:Xc,options:[...wr]},{property:"flex",isMatch:e=>/^flex-(?:\d+|auto|initial|none|\[.+\])$/.test(e)},{property:"order",exact:Fr,isMatch:Wc,options:[...Fr]},{property:"gridTemplateColumns",exact:Ar,isMatch:Uc,options:[...Ar]},{property:"gridTemplateRows",exact:Nr,isMatch:zc,options:[...Nr]},{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:Tr,isMatch:Hc,options:[...Tr]},{property:"gridRow",exact:Mr,isMatch:Gc,options:[...Mr]},{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:Jo,options:[...Jo]},{property:"alignSelf",isMatch:e=>/^self-(?:auto|start|end|center|stretch|baseline)$/.test(e)},{property:"justifyContent",exact:Xo,options:[...Xo]},{property:"marginTop",prefix:"mt-",isMatch:e=>$e("m","t",e)},{property:"marginRight",prefix:"mr-",isMatch:e=>$e("m","r",e)},{property:"marginBottom",prefix:"mb-",isMatch:e=>$e("m","b",e)},{property:"marginLeft",prefix:"ml-",isMatch:e=>$e("m","l",e)},{property:"paddingTop",prefix:"pt-",isMatch:e=>$e("p","t",e)},{property:"paddingRight",prefix:"pr-",isMatch:e=>$e("p","r",e)},{property:"paddingBottom",prefix:"pb-",isMatch:e=>$e("p","b",e)},{property:"paddingLeft",prefix:"pl-",isMatch:e=>$e("p","l",e)},{property:"width",prefix:"w-",isMatch:e=>e.startsWith("w-")||Qo(e)},{property:"height",prefix:"h-",isMatch:e=>e.startsWith("h-")||Qo(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:Wo,isMatch:e=>/^overflow(?:-[xy])?-.+$/.test(e),options:[...Wo]},{property:"fontFamily",exact:Ir,isMatch:e=>Ir.includes(e)||/^font-\[.+\]$/.test(e)||/^font-[a-z][\w-]*$/.test(e)&&!nu(e),options:[...Ir]},{property:"fontSize",exact:Or,isMatch:es,options:[...Or]},{property:"fontWeight",exact:Lr,options:[...Lr]},{property:"lineHeight",prefix:"leading-"},{property:"letterSpacing",exact:Pr,isMatch:e=>Pr.includes(e)||e.startsWith("tracking-["),options:[...Pr]},{property:"textAlign",exact:Dr,options:[...Dr]},{property:"textTransform",exact:Uo,options:[...Uo]},{property:"textDecoration",exact:zo,options:[...zo]},{property:"textOverflow",exact:["truncate","text-ellipsis","text-clip"]},{property:"fontStyle",exact:["italic","not-italic"]},{property:"textUnderlineOffset",prefix:"underline-offset-"},{property:"textIndent",exact:jr,isMatch:qc,options:[...jr]},{property:"writingMode",exact:Ho,options:[...Ho]},{property:"whiteSpace",exact:Go,options:[...Go]},{property:"wordBreak",exact:Yo,options:[...Yo]},{property:"lineClamp",exact:$r,isMatch:Qc,options:[...$r]},{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:Vc},{property:"backgroundColor",isMatch:Jc},{property:"backgroundImage",isMatch:e=>e.startsWith("bg-[url")||e.startsWith("bg-gradient-")},{property:"borderStyle",exact:Br,options:[...Br]},{property:"borderWidth",exact:_r,isMatch:ts,options:[..._r]},{property:"divideWidth",isMatch:e=>/^divide-[xy](?:-\d+|-0|-reverse)?$/.test(e)},{property:"borderRadius",prefix:"rounded"},{property:"borderColor",isMatch:Zc},{property:"divideColor",isMatch:e=>e.startsWith("divide-")&&!/^divide-[xy](?:-\d+|-0|-reverse)?$/.test(e)},{property:"objectFit",exact:Zo,options:[...Zo]},{property:"objectPosition",isMatch:e=>/^object-(?:bottom|center|left|left-bottom|left-top|right|right-bottom|right-top|top|\[.+\])$/.test(e)},{property:"aspectRatio",exact:Kr,isMatch:eu,options:[...Kr]},{property:"opacity",prefix:"opacity-"},{property:"boxShadow",exact:Vr,isMatch:tu,options:[...Vr]},{property:"transform",isMatch:ru},{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 qo(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:vr,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:vr,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:vr}}function es(e){return Or.includes(e)||/^text-\[.+\]$/.test(e)&&!iu(e.slice(6,-1))}function Vc(e){return!e.startsWith("text-")||Dr.includes(e)?!1:!es(e)}function Jc(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 ts(e){return _r.includes(e)||/^border-\[.+\]$/.test(e)||/^border-(?:x|y|t|r|b|l)(?:-\d+|-\[.+\])?$/.test(e)}function Sn(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 Xc(e){return wr.includes(e)||/^basis-\[.+\]$/.test(e)}function Wc(e){return Fr.includes(e)||/^-?order-(?:\d+|\[.+\])$/.test(e)}function Uc(e){return Ar.includes(e)||/^grid-cols-\[.+\]$/.test(e)}function zc(e){return Nr.includes(e)||/^grid-rows-\[.+\]$/.test(e)}function Hc(e){return Tr.includes(e)||/^(?:col|col-span|col-start|col-end)-.+$/.test(e)}function Gc(e){return Mr.includes(e)||/^(?:row|row-span|row-start|row-end)-.+$/.test(e)}function Yc(e){return Rr.includes(e)||/^-?z-(?:\d+|\[.+\])$/.test(e)}function Zc(e){return e.startsWith("border-")?!(Br.includes(e)||ts(e)||e.startsWith("border-spacing-")||/^border-(?:x|y|t|r|b|l)(?:-|$)/.test(e)):!1}function Qc(e){return $r.includes(e)||/^line-clamp-\[.+\]$/.test(e)}function qc(e){return jr.includes(e)||/^-?indent-\[.+\]$/.test(e)}function eu(e){return Kr.includes(e)||/^aspect-\[.+\]$/.test(e)}function tu(e){return Vr.includes(e)||/^shadow-(?:\[.+\]|[a-z][\w-]*)$/.test(e)}function nu(e){return Lr.includes(e)}function $e(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 Qo(e){return/^size-.+$/.test(e)}function ru(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 iu(e){return e.startsWith("#")||e.startsWith("rgb")||e.startsWith("hsl")||e.startsWith("oklch")||e.startsWith("color(")}import Ur from"@babel/traverse";function qe(e,t,n,r){return{code:e,message:t,locatorKind:n,details:r}}function T(e,t,n,r,i){return{ok:!1,source:e,diagnostic:qe(t,n,r,i)}}function Jr(e,t,n,r,i){return{ok:!1,source:e,diagnostic:qe(t,n,r,i)}}import*as ns from"@babel/parser";var ou={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function Be(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:ns.parse(t,{sourceType:"module",plugins:ou[n]})}}catch(r){return{ok:!1,source:t,diagnostic:qe("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function Xr(e,t){return Be({source:e,profile:rs(t.kind)})}function Wr(e,t){return Be({source:e,profile:rs(t)})}function rs(e){return"next-app-entry"}function Lt(e){let{filePath:t,source:n}=e,r=t.toLowerCase().split(".").pop()??"";return r==="tsx"?"tsx-module":r==="ts"?"ts-module":r==="jsx"||r==="js"||r===""&&/<\w[\s\S]*>/.test(n)?"tsx-module":"next-app-entry"}var _e=typeof Ur=="function"?Ur:Ur.default,kn=new WeakMap,is=new WeakMap;function vn(e,t){let n=Xr(e,t);if(!n.ok)return Jr(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=_(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}}:Jr(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function _(e,t){return t.kind==="jsx-node"?ls(e,t):t.kind==="jsx-attribute"?du(e,t):t.kind==="value"?fu(e,t):t.kind==="expression"?pu(e,t):t.kind==="directive"?mu(e,t):t.kind==="export"?hu(e,t):{ok:!1,diagnostic:qe("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function ls(e,t){return t.strategy==="source-range"?su(e,t):au(e,t)}function su(e,t){let n=null;if(_e(e,{JSXElement(i){if(!bn(i.node,t.sourceRange))return;let o=ne("jsx-node",i);if(o){if(!n){n=o;return}o.end-o.start<n.end-n.start&&(n=o)}}}),!n)return Q("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!Pu(r.path,t.expectedIdentity)?Q("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function au(e,t){if(t.structuralPath===""){let r=cu(e,t.component);if(r){let i=uu(r);if(i)return i}}let n=null;return _e(e,{JSXElement(r){if(Dt(r)!==t.component||Hr(r)!==t.structuralPath)return;let o=ne("jsx-node",r);o&&(n=o,r.stop())},JSXFragment(r){if(Dt(r)!==t.component||Hr(r)!==t.structuralPath)return;let o=ne("jsx-node",r);o&&(n=o,r.stop())}}),!n&&t.expectedRange&&(n=lu(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:Q("jsx-node","locator-miss","JSX node not found for structural-path locator")}function lu(e,t,n){let r=null;return _e(e,{JSXElement(i){if(Dt(i)!==t||!bn(i.node,n))return;let o=ne("jsx-node",i);o&&(r=o,i.stop())},JSXFragment(i){if(Dt(i)!==t||!bn(i.node,n))return;let o=ne("jsx-node",i);o&&(r=o,i.stop())}}),r}function cu(e,t){let n=null;return _e(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 i=r.get("init");(i.isArrowFunctionExpression()||i.isFunctionExpression())&&(n=i),r.stop()}}}),n}function uu(e){if(e.isArrowFunctionExpression()){let t=e.get("body");if(t.isBlockStatement()){let r=t.get("body").find(i=>i.isReturnStatement());if(r){let i=r.get("argument");if((i.isParenthesizedExpression()?i.get("expression"):i).isJSXFragment())return Q("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?Q("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 Q("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function du(e,t){let n=ls(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(l=>Ru(l,t.name));if(!s||!s.isJSXAttribute())return Q("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=ne("jsx-attribute",s);return a?{ok:!0,match:a}:Q("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function fu(e,t){let n=gu(e,t);if(!n.ok)return n;let r=xu(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!Te(r.match.path.node.loc,t.expectedRange)?Q("value","locator-miss","Resolved value does not match expected range"):{ok:!0,match:r.match}:r}function pu(e,t){let n=null;return _e(e,{Identifier(r){if(!vu(r))return;let i=ss(r);if(!i||!as(i,t))return;let o=ne("expression",r);o&&(t.expectedRange&&!Te(r.node.loc,t.expectedRange)||(n=o,r.stop()))},MemberExpression(r){let i=ss(r);if(!i||!as(i,t))return;let o=ne("expression",r);o&&(t.expectedRange&&!Te(r.node.loc,t.expectedRange)||(n=o,r.stop()))}}),n?{ok:!0,match:n}:Q("expression","locator-miss","Expression not found")}function mu(e,t){let n=null;return _e(e,{Program(r){let o=r.get("directives").find(a=>a.node.value.value===t.value);if(!o||t.expectedRange&&!Te(o.node.loc,t.expectedRange))return;let s=ne("directive",o);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:Q("directive","locator-miss",`Directive '${t.value}' not found`)}function hu(e,t){let n=null;return _e(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let l=r.get("declaration");if(l.isFunctionDeclaration()&&l.node.id?.name==="generateMetadata"){let p=ne("export",l);if(!p||t.expectedRange&&!Te(l.node.loc,t.expectedRange))return;n=p,r.stop();return}if(!l.isVariableDeclaration())return;let u=Gr(l,"generateMetadata");if(!u||!u.isVariableDeclarator())return;let c=u.get("init");if(!c.node)return;let d=ne("export",c);if(!d||t.expectedRange&&!Te(c.node.loc,t.expectedRange))return;n=d,r.stop();return}let i=r.get("declaration");if(!i.isVariableDeclaration())return;let o=Gr(i,t.exportKind==="named"?t.name:"metadata");if(!o||!o.isVariableDeclarator())return;let s=o.get("init");if(!s.node||t.expectedRange&&!Te(s.node.loc,t.expectedRange))return;let a=ne("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let i=r.get("declaration"),o=ne("export",i);o&&(t.expectedRange&&!Te(i.node.loc,t.expectedRange)||(n=o,r.stop()))}}),n?{ok:!0,match:n}:Q("export","export-not-found",`Export '${Iu(t)}' not found`)}function gu(e,t){let n=null;return _e(e,{Expression(r){if(n||t.root.kind!=="expression"||!bn(r.node,t.root.sourceRange))return;let i=ne("value",r);i&&(n=i,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 h=r.get("init");if(!h.node)return;let k=ne("value",h);if(!k)return;n=k,r.stop();return}if(t.root.kind!=="hook-state")return;let i=t.root,o=r.get("id"),s=r.get("init");if(!o.isArrayPattern()||!s.isCallExpression()||o.node.elements.findIndex(h=>h?.type==="Identifier"&&h.name===i.name)!==0)return;let l=s.node.callee;if((l.type==="Identifier"?l.name:l.type==="MemberExpression"&&l.property.type==="Identifier"?l.property.name:null)!==i.hook)return;let c=i.hook==="useReducer"?1:0,d=r.get(`init.arguments.${c}`);if(!d||Array.isArray(d)||!d.node)return;let p=ne("value",d);p&&(n=p,r.stop())},ExportNamedDeclaration(r){if(n||t.root.kind!=="named-export")return;let i=r.get("declaration");if(!i.isVariableDeclaration())return;let o=Gr(i,t.root.name);if(!o||!o.isVariableDeclarator())return;let s=o.get("init");if(!s.node)return;let a=ne("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let i=r.get("declaration"),o=ne("value",i);o&&(n=o,r.stop())}}),n?{ok:!0,match:n}:Q("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 xu(e,t){let n=zr(e);for(let i of t){if(n=zr(n),i.kind==="property"){if(!n.isObjectExpression())return Q("value","unsupported-syntax","Property path requires object expression");let a=n.get("properties");if(a.some(u=>!u.isObjectProperty()))return Q("value","unsupported-syntax","Spread properties are not supported");let l=a.find(u=>wu(u,i.name));if(!l||!l.isObjectProperty())return Q("value","property-not-found",`Property '${i.name}' not found`);n=l.get("value");continue}if(!n.isArrayExpression())return Q("value","unsupported-syntax","Array index path requires array expression");let o=n.get("elements");if(o.some(a=>a.node?.type==="SpreadElement"))return Q("value","unsupported-syntax","Spread array elements are not supported");let s=o[i.index];if(!s?.node)return Q("value","array-index-out-of-range",`Array index ${i.index} is out of range`);n=s}n=zr(n);let r=ne("value",n);return r?{ok:!0,match:r}:Q("value","locator-miss","Resolved value has no source range")}function zr(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function ne(e,t){let n=t.node;return n.start==null||n.end==null?null:{locatorKind:e,node:n,start:n.start,end:n.end,path:t}}function bn(e,t){return Te(e.loc,t)}function Te(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 Hr(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!En(n.node)){let i=cs(n.node.openingElement);i&&(/^[A-Z]/.test(i)?t.unshift(`component:${i}#${os(n,i)}`):t.unshift(`${i}#${os(n,i)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||bu(n.parentPath))break;n=n.parentPath}return t.join("/")}function En(e){let t=e.openingElement.name;return t.type==="JSXIdentifier"?t.name==="Fragment":t.type==="JSXMemberExpression"&&t.property.name==="Fragment"}function os(e,t){let n=yu(e);if(!n)return 0;let r=kn.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let i=0,o=kn.get(n.node)?.get(t);if(!o){let s=kn.get(n.node);s||(s=new Map,kn.set(n.node,s)),o=new WeakMap,s.set(t,o)}for(let s of Ot(n))if(cs(s.node.openingElement)===t){if(o.set(s.node,i),s.node===e.node)return i;i++}return o.get(e.node)??0}function yu(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(En(t.node)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Ot(e){let t=is.get(e.node);if(t)return t;let n=[],r=e.get("children");for(let i of r)if(!Array.isArray(i)){if(i.isJSXElement()){if(En(i.node)){n.push(...Ot(i));continue}n.push(i);continue}if(i.isJSXFragment()){n.push(...Ot(i));continue}i.isJSXExpressionContainer()&&n.push(...mt(i.get("expression")))}return is.set(e.node,n),n}function mt(e){return e.isJSXElement()?En(e.node)?Ot(e):[e]:e.isJSXFragment()?Ot(e):e.isParenthesizedExpression()?mt(e.get("expression")):e.isLogicalExpression()&&Su(e.node.operator)?mt(e.get("right")):e.isConditionalExpression()?[...mt(e.get("consequent")),...mt(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:mt(t)):[]}function Su(e){return e==="&&"||e==="||"||e==="??"}function cs(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?ku(e.name):null}function ku(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 Dt(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 bu(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function vu(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function ss(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 as(e,t){return e.base===t.base&&Eu(e.path,t.path??[])}function Eu(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(r.kind!==i.kind)return!1;if(r.kind==="property"){if(i.kind!=="property"||r.name!==i.name)return!1;continue}if(i.kind!=="index"||r.index!==i.index)return!1}return!0}function Cu(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function Iu(e){return e.exportKind==="named"?e.name:e.exportKind}function Q(e,t,n,r){return{ok:!1,diagnostic:qe(t,n,e,r)}}function Pu(e,t){return Dt(e)!==t.component?!1:Hr(e)===t.structuralPath}function Ru(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function Gr(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function wu(e,t){return e.isObjectProperty()?Cu(e.node)===t:!1}import{createHash as Fu}from"node:crypto";var jt=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 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(l=>a===l||a.startsWith(`${l}/`))),i=[],o=new Set,s=0;for(let a of r.sort()){let l=Buffer.byteLength(this.files.get(a)??"","utf8"),u=a.split("/").length;if(t.maxDepth!==void 0&&u>t.maxDepth){o.add("max-depth");continue}if(t.maxFiles!==void 0&&i.length>=t.maxFiles){o.add("max-files");break}if(t.maxTotalBytes!==void 0&&s+l>t.maxTotalBytes){o.add("max-total-bytes");break}i.push({path:a,sizeBytes:l}),s+=l}return o.size>0?{files:i,truncated:{reasons:[...o]}}:{files:i}}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 i=this.original.get(r),o=this.files.get(r);i!==o&&n.push({path:r,before:i,after:o})}return n}};function q(e){return`sha256:${Fu("sha256").update(e).digest("hex")}`}var Yr="site-edit-classname-source@1";function ds(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,valueRange:null,openingElementRange:{start:0,end:0},version:{documentVersion:e.route.graph.version,contentHash:q(e.route.source),parserVersion:Yr},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=Au(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,valueRange:null,openingElementRange:{start:0,end:0},version:{documentVersion:e.route.graph.version,contentHash:q(e.route.source),parserVersion:Yr},diagnostics:[{code:"source-locator-warning",message:`Unable to locate JSX element for key ${t.identity.key}`}]};let r=n.openingElement,i=r.attributes.find(l=>l.type==="JSXAttribute"&&l.name.type==="JSXIdentifier"&&l.name.name==="className"),o={key:e.key,routeId:e.route.routeId,filePath:t.sourceFile,componentName:t.componentName,openingElementRange:Zr(r),version:{documentVersion:e.route.graph.version,contentHash:q(e.route.source),parserVersion:Yr}};if(!i)return{...o,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,valueRange:null,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element."}]};let s=i.value,a=s?.type==="StringLiteral"?"stringLiteral":"expression";return{...o,sourceKind:a,attrRaw:us(e.route.source,i),valueRaw:s?us(e.route.source,s):null,attrRange:Zr(i),valueRange:s?Zr(s):null,diagnostics:[]}}function fs(e){let{source:t,oldAttrRange:n,openingElementRange:r,newAttrRaw:i}=e;if(n){let a=n.start>0&&/\s/.test(t[n.start-1]??"")?n.start-1:n.start,l=i?`${a<n.start?" ":""}${i}`:"";return t.slice(0,a)+l+t.slice(n.end)}if(!i)return t;let o=r.end,s=t.slice(Math.max(0,o-2),o)==="/>"?o-2:o-1;return t.slice(0,s)+` ${i}`+t.slice(s)}function Au(e,t){let n=Be({source:e,profile:Lt({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=_(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:Nu(t.sourceRange)});return!r.ok||r.match.node.type!=="JSXElement"?null:r.match.node}function ps(e){let t=Be({source:`const __v = <div ${e} />;`,profile:"tsx-module"});if(!t.ok)return!1;let n=t.ast.program.body[0],i=(n?.type==="VariableDeclaration"?n.declarations[0]:null)?.init;if(i?.type!=="JSXElement")return!1;let o=i.openingElement.attributes;return o.length===1&&o[0]?.type==="JSXAttribute"&&o[0].name.type==="JSXIdentifier"&&o[0].name.name==="className"}function us(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function Zr(e){if(e.start==null||e.end==null)throw new Error("AST node does not include offsets.");return{start:e.start,end:e.end,startLine:e.loc?.start.line,startColumn:e.loc?.start.column,endLine:e.loc?.end.line,endColumn:e.loc?.end.column}}function Nu(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}import Qr from"@babel/generator";var Tu=typeof Qr=="function"?Qr:Qr.default;function Mu(e){let t=e.split(`
2
+ `),n=[],r=!1;for(let s of t){let a=s.match(/^(\s+)/);if(a){let l=a[1];l.includes(" ")?r=!0:l.length>0&&n.push(l.length)}}if(r&&t.every(a=>{let l=a.match(/^(\s+)/);return!l||l[1].includes(" ")}))return"tab";if(n.length===0)return"2";function i(s,a){return a===0?s:i(a,s%a)}let o=n[0];for(let s=1;s<n.length;s++)o=i(o,n[s]);return o>=4?"4":"2"}function Lu(e,t){let n=e.match(/^(\s+)(.*)/s);if(!n)return e;let r=n[1],i=n[2];if(r.length===0)return e;let o=r.includes(" ")?r.split(" ").length-1:Math.max(1,Math.round(r.length/2)),s=Math.min(Math.max(o,0),20);return t==="tab"?" ".repeat(s)+i:t==="4"?" ".repeat(s)+i:" ".repeat(s)+i}function Ou(e,t){return e.split(`
3
+ `).map(r=>Lu(r,t)).join(`
4
+ `)}function Cn(e){let{ast:t,source:n}=e;try{let r=Mu(n),o=Tu(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(o=Ou(o,r)),{ok:!0,source:o}}catch(r){return T(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}import*as hs from"@babel/parser";import{arrayExpression as Du,booleanLiteral as ju,identifier as $u,jsxAttribute as Bu,jsxExpressionContainer as _u,jsxIdentifier as Ku,nullLiteral as Vu,numericLiteral as Ju,objectExpression as Xu,objectProperty as Wu,stringLiteral as gs}from"@babel/types";function ms(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 $t(e,t,n){return{ok:!0,source:t,operation:{type:n.kind,nodeId:n.target,kind:n.kind,target:n.target,beforeSourceHash:ms(e),afterSourceHash:ms(t),inverse:n.inverse}}}function X(e,t,n){let r=Cn({ast:e,source:t});return r.ok?$t(t,r.source,n):r}function ee(e,t){let n=Wr(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function In(e,t){return Cn({ast:e,source:t})}function Uu(e,t,n){let r=_(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function xs(e,t,n){let r=Uu(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:T(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function ys(e,t){let n=_(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 ht(e){return typeof e=="string"?gs(e):typeof e=="number"?Ju(e):typeof e=="boolean"?ju(e):e===null?Vu():Array.isArray(e)?Du(e.map(t=>ht(t))):Xu(Object.entries(e).map(([t,n])=>Wu($u(t),ht(n))))}function zu(e){return typeof e=="string"?gs(e):_u(ht(e))}function Pn(e,t){return Bu(Ku(e),zu(t))}function Ss(e,t){try{let r=hs.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:T(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:T(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function Rn(e){let{source:t,locator:n,segmentIndex:r,newText:i}=e,o=ee(t,"jsx-node");if(!o.ok)return o.result;let s=_(o.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let l=Hu(s.match.path)[r];if(!l)return T(t,"locator-miss",`Text segment ${r} not found`,"jsx-node");switch(l.kind){case"jsx-text":l.path.node.value=Gu(l.path.node.value,i);break;case"string-literal":l.path.node.value=i;break;case"template-literal":{let u=l.quasiIndex;l.path.node.quasis[u].value.raw=i,l.path.node.quasis[u].value.cooked=i;break}}return X(o.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function Hu(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 i=Yu(r.get("expression"));i.length>0&&t.push(...i)}}return t}function Gu(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function Yu(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 qr}from"@babel/types";function wn(e){let{source:t,locator:n}=e,r=ee(t,"jsx-node");if(!r.ok)return r.result;let i=_(r.ast,n);return i.ok?(Zu(i.match.path),X(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:i.diagnostic}}function Zu(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(qr());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(qr());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(qr());return}e.remove()}import{cloneNode as ld}from"@babel/types";import ei from"@babel/traverse";import*as M from"@babel/types";var Qu=typeof ei=="function"?ei:ei.default;function me(e,t,n,r){if(!e.ok)return e;let i=pe(n);if(!i)return e;let o=qu(t,i,r);return o?{...e,selectionRef:o}:e}function qu(e,t,n){let r=ed(e,t);if(!r)return;let i=n.sourceLocator?ks(n.sourceLocator):void 0,o=n.targetParentLocator?ks(n.targetParentLocator):void 0,s=n.file??o?.file??i?.file,a=n.component??nd(r)??o?.component??i?.component;if(!(!s||!a))return{key:At(s,a,rd(r))}}function ks(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function ed(e,t){let n=null;return Qu(e,{JSXElement(r){r.node===t&&(n=r,r.stop())}}),n}function pe(e){if(!e)return null;if(M.isJSXElement(e))return gt(e)?bs(e.children):e;if(M.isJSXFragment(e))return bs(e.children);if(M.isJSXExpressionContainer(e)||M.isParenthesizedExpression(e)||M.isTSAsExpression(e)||M.isTSSatisfiesExpression(e)||M.isTSTypeAssertion(e)||M.isTSNonNullExpression(e))return pe(e.expression);if(M.isLogicalExpression(e))return pe(e.right);if(M.isConditionalExpression(e))return pe(e.consequent)??pe(e.alternate);if(M.isCallExpression(e)||M.isOptionalCallExpression(e))return Ps(e)?td(e.arguments[0]):null;if(M.isArrayExpression(e))for(let t of e.elements){if(!t)continue;let n=pe(t);if(n)return n}return null}function bs(e){for(let t of e){let n=pe(t);if(n)return n}return null}function td(e){return!e||!M.isArrowFunctionExpression(e)&&!M.isFunctionExpression(e)?null:M.isBlockStatement(e.body)?Bt(e.body.body):pe(e.body)}function Bt(e){for(let t of e){if(M.isReturnStatement(t)){let n=pe(t.argument);if(n)return n;continue}if(M.isBlockStatement(t)){let n=Bt(t.body);if(n)return n;continue}if(M.isIfStatement(t)){let n=vs(t.consequent);if(n)return n;let r=t.alternate?vs(t.alternate):null;if(r)return r;continue}if(M.isSwitchStatement(t))for(let n of t.cases){let r=Bt(n.consequent);if(r)return r}}return null}function vs(e){return M.isBlockStatement(e)?Bt(e.body):Bt([e])}function nd(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(M.isFunctionDeclaration(n))return n.id?.name??"default"}if(t.isVariableDeclarator()&&M.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 Es=new WeakMap,Cs=new WeakMap,ti=new WeakMap;function rd(e){let t=Es.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let o=id(r);o&&n.unshift(o)}r=r.parentPath}let i=n.join("/");return Es.set(e.node,i),i}function id(e){let t=ni(e.node.openingElement.name);return!t||gt(e.node)?null:/^[A-Z]/.test(t)?`component:${t}#${Is(e,t)}`:`${t}#${Is(e,t)}`}function Is(e,t){let n=od(e);if(!n)return 0;let r=ti.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let i=ti.get(n.node);i||(i=new Map,ti.set(n.node,i));let o=i.get(t);o||(o=new WeakMap,i.set(t,o));let s=0;for(let a of et(n))if(ni(a.node.openingElement.name)===t){if(o.set(a.node,s),a.node===e.node)return s;s+=1}return o.get(e.node)??0}function od(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(gt(t.node)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function et(e){let t=Cs.get(e.node);if(t)return t;let n=[],r=e.get("children");for(let i of r)if(!Array.isArray(i)){if(i.isJSXElement()){if(gt(i.node)){n.push(...et(i));continue}n.push(i);continue}if(i.isJSXFragment()){n.push(...et(i));continue}i.isJSXExpressionContainer()&&n.push(...Me(i.get("expression")))}return Cs.set(e.node,n),n}function Me(e){if(e.isJSXElement())return gt(e.node)?et(e):[e];if(e.isJSXFragment())return et(e);if(e.isParenthesizedExpression())return Me(e.get("expression"));if(e.isLogicalExpression())return Me(e.get("right"));if(e.isConditionalExpression())return[...Me(e.get("consequent")),...Me(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Me(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&Ps(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?sd(n):[]}return[]}function sd(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return gt(t.node)?et(t):[t];if(t.isJSXFragment())return et(t);if(t.isParenthesizedExpression())return Me(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return Me(t);if(!t.isBlockStatement())return[];for(let n of t.get("body")){if(!n.isReturnStatement())continue;let r=n.get("argument");return r.node?Me(r):[]}return[]}function Ps(e){let t=e.callee;return(M.isMemberExpression(t)||M.isOptionalMemberExpression(t))&&M.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function gt(e){let t=ni(e.openingElement.name);return t==="Fragment"||t==="React.Fragment"}function ni(e){return M.isJSXIdentifier(e)?e.name:M.isJSXMemberExpression(e)?Rs(e):M.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function Rs(e){return`${M.isJSXIdentifier(e.object)?e.object.name:Rs(e.object)}.${e.property.name}`}function Ke(e,t){if(t.parentPath===e&&t.listKey==="children"&&ws(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!ws(n))return null;let r=n;for(;r&&r!==e;){if(!ad(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function ws(e){return e.isJSXElement()||e.isJSXFragment()}function ad(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 Fn(e){let{source:t,locator:n,node:r,placement:i,anchorLocator:o,selectionContext:s}=e,a=ee(t,"jsx-node");if(!a.ok)return a.result;let l=_(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(t,"unsupported-syntax","insert-child target must be a JSXElement or JSXFragment","jsx-node");let u=l.match.path;if(l.match.path.isJSXElement()){let I=l.match.path.node;if(!I.closingElement||I.openingElement.selfClosing)return T(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let c=Ss(t,r.jsx);if(!c.ok)return c.result;let d=ld(c.node,!0),p=u.node.children,h={...s,targetParentLocator:n},k=I=>s?me(I,a.ast,d,h):I;if(i==="append")return p.push(d),k(X(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(i==="prepend")return p.unshift(d),k(X(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(!o)return T(t,"locator-miss",`Placement '${i}' requires anchorLocator`,"jsx-node");let b=_(a.ast,o);if(!b.ok)return{ok:!1,source:t,diagnostic:b.diagnostic};let E=Ke(l.match.path,b.match.path);if(!E)return T(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=E;let P=u.node.children,R=P.findIndex(I=>I===b.match.path.node);return R===-1?T(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(P.splice(i==="before"?R:R+1,0,d),k(X(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as Fs from"@babel/parser";import{cloneNode as cd}from"@babel/types";function An(e){let{source:t,locator:n,expression:r,placement:i,anchorLocator:o,selectionContext:s}=e,a=ee(t,"jsx-node");if(!a.ok)return a.result;let l=ud(t,r);if(!l.ok)return l.result;let u=_(a.ast,n);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};if(!u.match.path.isJSXElement()&&!u.match.path.isJSXFragment())return T(t,"unsupported-syntax","insert-jsx-expression-child target must be a JSXElement or JSXFragment","jsx-node");if(u.match.path.isJSXElement()){let P=u.match.path.node;if(!P.closingElement||P.openingElement.selfClosing)return T(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let c=u.match.path,d=null;if(o){let P=_(a.ast,o);if(!P.ok)return{ok:!1,source:t,diagnostic:P.diagnostic};let R=Ke(u.match.path,P.match.path);if(!R)return T(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");c=R,d=P.match.path.node}else if(i==="before"||i==="after")return T(t,"locator-miss",`Placement '${i}' requires anchorLocator`,"jsx-node");let p=cd(l.node,!0),h=c.node.children,k={...s,targetParentLocator:n},b=P=>s?me(P,a.ast,p,k):P;if(i==="append")return h.push(p),b(X(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(i==="prepend")return h.unshift(p),b(X(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let E=h.findIndex(P=>P===d);return E===-1?T(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(h.splice(i==="before"?E:E+1,0,p),b(X(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function ud(e,t){try{let r=Fs.parse(`const __VD_EXPR__ = <>{${t}}</>;`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],i=r?.type==="VariableDeclaration"?r.declarations[0]?.init:null,o=i?.type==="JSXFragment"?i.children[0]:void 0;return o?.type!=="JSXExpressionContainer"?{ok:!1,result:T(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:o}}catch(n){return{ok:!1,result:T(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as dd,nullLiteral as ri}from"@babel/types";import*as As from"@babel/types";function Nn(e){let{source:t,locator:n,targetParentLocator:r,placement:i,anchorLocator:o,selectionContext:s}=e,a=ee(t,"jsx-node");if(!a.ok)return a.result;let l=_(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};let u=_(a.ast,r);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};if(!u.match.path.isJSXElement())return T(t,"unsupported-syntax","move-node target parent must be a JSXElement","jsx-node");let c=u.match.path,d=u.match.path.node;if(!d.closingElement||d.openingElement.selfClosing)return T(t,"self-closing-element","Cannot move child into self-closing element","jsx-node");let p=null;if(o){let P=_(a.ast,o);if(!P.ok)return{ok:!1,source:t,diagnostic:P.diagnostic};let R=Ke(u.match.path,P.match.path);if(!R)return T(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");c=R,p=P.match.path.node}else if(i==="before"||i==="after")return T(t,"locator-miss",`Placement '${i}' requires anchorLocator`,"jsx-node");let h=dd(l.match.path.node,!0);if(!As.isJSXElement(h))return T(t,"unsupported-syntax","move-node source must resolve to a JSXElement","jsx-node");fd(l.match.path);let k=c.node.children,b={...s,sourceLocator:n,targetParentLocator:r};if(i==="append")return k.push(h),me(In(a.ast,t),a.ast,h,b);if(i==="prepend")return k.unshift(h),me(In(a.ast,t),a.ast,h,b);let E=k.findIndex(P=>P===p);return E===-1?T(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(k.splice(i==="before"?E:E+1,0,h),me(In(a.ast,t),a.ast,h,b))}function fd(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 Ns from"@babel/parser";import{cloneNode as pd,nullLiteral as ii}from"@babel/types";function Tn(e){let{source:t,locator:n,targetParentLocator:r,placement:i,anchorLocator:o,repeatExpression:s,selectionContext:a}=e,l=ee(t,"jsx-node");if(!l.ok)return l.result;let u=md(t,s);if(!u.ok)return u.result;let c=_(l.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let d=_(l.ast,r);if(!d.ok)return{ok:!1,source:t,diagnostic:d.diagnostic};if(!d.match.path.isJSXElement()&&!d.match.path.isJSXFragment())return T(t,"unsupported-syntax","move-repeat-template-child target parent must be a JSXElement or JSXFragment","jsx-node");if(d.match.path.isJSXElement()){let I=d.match.path.node;if(!I.closingElement||I.openingElement.selfClosing)return T(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let p=d.match.path,h=null;if(o){let I=_(l.ast,o);if(!I.ok)return{ok:!1,source:t,diagnostic:I.diagnostic};let B=Ke(d.match.path,I.match.path);if(!B)return T(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");p=B,h=I.match.path.node}else if(i==="before"||i==="after")return T(t,"locator-miss",`Placement '${i}' requires anchorLocator`,"jsx-node");if(!c.match.path.isJSXElement())return T(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let k=p.node,b=pd(u.node,!0);hd(c.match.path);let E={...a,sourceLocator:n,targetParentLocator:r},P=k.children;if(i==="append")return P.push(b),me(X(l.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),l.ast,b,E);if(i==="prepend")return P.unshift(b),me(X(l.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),l.ast,b,E);let R=P.findIndex(I=>I===h);return R===-1?T(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(P.splice(i==="before"?R:R+1,0,b),me(X(l.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),l.ast,b,E))}function md(e,t){try{let r=Ns.parse(`const __VD_EXPR__ = <>{${t}}</>;`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],i=r?.type==="VariableDeclaration"?r.declarations[0]?.init:null,o=i?.type==="JSXFragment"?i.children[0]:void 0;return o?.type!=="JSXExpressionContainer"?{ok:!1,result:T(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:o}}catch(n){return{ok:!1,result:T(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function hd(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(ii());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(ii());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(ii());return}e.remove()}function Mn(e){let{source:t,locator:n,props:r}=e,i=ee(t,"jsx-node");if(!i.ok)return i.result;let o=xs(i.ast,n,t);if(!o.ok)return o.result;let s=o.match.path.node.openingElement;for(let[a,l]of Object.entries(r)){if(l===void 0)continue;let u={kind:"jsx-attribute",element:n,name:a},c=ys(i.ast,u);if(c.ok&&c.match!==null){let d=c.match.path.node;d.value=l===""?Pn(a,"").value:Pn(a,l).value}else s.attributes.push(Pn(a,l))}return X(i.ast,t,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}import{getBindingIdentifiers as gd,identifier as _t,importDeclaration as xd,importDefaultSpecifier as yd,importNamespaceSpecifier as Sd,importSpecifier as kd,isImportDefaultSpecifier as Ts,isImportNamespaceSpecifier as Ms,isImportSpecifier as Ls,stringLiteral as bd}from"@babel/types";function Ln(e){let{source:t,moduleSpecifier:n,imports:r}=e,i=r.findIndex(E=>!Ad(E));if(i!==-1){let E=r[i],P=E&&typeof E=="object"&&"kind"in E?E.kind:void 0;return T(t,"unsupported-syntax",`Unsupported import spec kind: ${String(P)}`)}let o=Rd(r);if(!o.ok)return T(t,"unsupported-syntax",o.message);let s=ee(t);if(!s.ok)return s.result;let{ast:a}=s,l=a.program,u=l.body.filter(E=>E.type==="ImportDeclaration"&&E.source.value===n),c=new Set(u.flatMap(E=>E.specifiers.flatMap(P=>{let R=Nd(E,P);return R?[R]:[]}))),d=o.imports.filter(E=>!c.has(_s(E)));if(d.length===0)return $t(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let p=wd(l.body),h=d.find(E=>p.has(oi(E)));if(h)return T(t,"unsupported-syntax",`Import local binding already exists: ${oi(h)}`);let k=Pd(d);if(k.reduce((E,P)=>E+P.length,0)!==d.length)return T(t,"unsupported-syntax","Unsupported import specifier grouping");for(let E of k){if(!$s(Ds(E)))return T(t,"unsupported-syntax","Unsupported import specifier combination");let P=u.find(R=>vd(R,E));if(P)Ed(P,E);else{let R=xd(Os(E),bd(n));Fd(l.body,R),u.push(R)}}return X(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function vd(e,t){return e.importKind==="type"?!1:$s(Id(Cd(e),Ds(t)))}function Ed(e,t){let n=!1,r=new Set(e.specifiers.map(i=>si(i)));for(let i of Os(t)){let o=si(i);r.has(o)||(e.specifiers.push(i),r.add(o),n=!0)}return Bs(e.specifiers),{changed:n}}function Os(e){let t=e.map(n=>{switch(n.kind){case"named":return kd(n.local?_t(n.local):_t(n.imported),_t(n.imported));case"default":return yd(_t(n.local));case"namespace":return Sd(_t(n.local));default:return n}});return Bs(t),t}function Ds(e){let t=js();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 Cd(e){let t=js();for(let n of e.specifiers)Ts(n)?t.defaultLocals.add(n.local.name):Ms(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function js(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function Id(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function $s(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function Bs(e){let t=[...e.filter(n=>Ts(n)),...e.filter(n=>Ms(n)),...e.filter(n=>Ls(n))];e.splice(0,e.length,...t)}function Pd(e){let t=e.filter(o=>o.kind==="default"),n=e.filter(o=>o.kind==="namespace"),r=e.filter(o=>o.kind==="named"),i=[];if(n.length>0){let o=Math.max(t.length,n.length);for(let s=0;s<o;s+=1){let a=[],l=t[s],u=n[s];l&&a.push(l),u&&a.push(u),i.push(a)}return r.length>0&&i.push(r),i}if(t.length>0){i.push([t[0],...r]);for(let o of t.slice(1))i.push([o])}else r.length>0&&i.push(r);return i}function Rd(e){let t=new Map,n=new Map;for(let r of e){let i=_s(r);if(t.has(i))continue;let o=oi(r),s=n.get(o);if(s&&s!==i)return{ok:!1,message:`Import local binding is requested more than once: ${o}`};t.set(i,r),n.set(o,i)}return{ok:!0,imports:[...t.values()]}}function wd(e){let t=new Set;for(let n of e){if(n.type==="ImportDeclaration"){for(let i of n.specifiers)t.add(i.local.name);continue}let r=(n.type==="ExportNamedDeclaration"||n.type==="ExportDefaultDeclaration")&&n.declaration?n.declaration:n;if(r.type==="VariableDeclaration")for(let i of r.declarations)for(let o of Object.keys(gd(i.id)))t.add(o);else(r.type==="FunctionDeclaration"||r.type==="ClassDeclaration"||r.type==="TSEnumDeclaration")&&r.id&&t.add(r.id.name)}return t}function Fd(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 Ad(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 _s(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 oi(e){return e.kind==="named"?e.local??e.imported:e.local}function Nd(e,t){return e.importKind==="type"||Ls(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,i=r.findIndex(c=>!Md(c));if(i!==-1){let c=r[i],d=c&&typeof c=="object"&&"kind"in c?c.kind:void 0;return T(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(d)}`)}let o=ee(t);if(!o.ok)return o.result;let{ast:s}=o,a=s.program,l=a.body.findIndex(c=>c.type==="ImportDeclaration"&&c.source.value===n);if(l===-1)return $t(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let u=a.body[l];return r.length===0?(a.body.splice(l,1),X(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(u.specifiers=u.specifiers.filter(c=>!r.some(d=>Td(c,d))),u.specifiers.length===0&&a.body.splice(l,1),X(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function Td(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 Md(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 Kt(e){let{source:t,locator:n,next:r}=e,i=Bn(t,n);return i.ok?(i.path.replaceWith(ht(r)),X(i.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):i.result}function Dn(e){let{source:t,locator:n,index:r,value:i}=e,o=Bn(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(s=>s?.type==="SpreadElement")?T(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>o.path.node.elements.length?T(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(o.path.node.elements.splice(r,0,ht(i)),X(o.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):T(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function jn(e){let{source:t,locator:n,index:r}=e,i=Bn(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(o=>o?.type==="SpreadElement")?T(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=i.path.node.elements.length?T(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,1),X(i.ast,t,{kind:"remove-array-element",target:"value",inverse:"insert-array-element"})):T(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function $n(e){let{source:t,locator:n,fromIndex:r,toIndex:i}=e,o=Bn(t,n);if(!o.ok)return o.result;if(!o.path.isArrayExpression())return T(t,"unsupported-syntax","Array operations require array expression target","value");if(o.path.node.elements.some(l=>l?.type==="SpreadElement"))return T(t,"unsupported-syntax","Spread array elements are not supported","value");if(r<0||r>=o.path.node.elements.length||i<0||i>o.path.node.elements.length)return T(t,"array-index-out-of-range","Array move indices are out of range","value");let[s]=o.path.node.elements.splice(r,1),a=Math.min(i,o.path.node.elements.length);return o.path.node.elements.splice(a,0,s),X(o.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function Bn(e,t){let n=ee(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=_(n.ast,t);return r.ok?{ok:!0,ast:n.ast,path:r.match.path}:{ok:!1,result:{ok:!1,source:e,diagnostic:r.diagnostic}}}import*as vi from"@babel/parser";import di from"@babel/traverse";import*as g from"@babel/types";import*as Oe from"node:path";import*as Ws from"@babel/parser";import ci from"@babel/traverse";import*as xt from"@babel/types";import*as O from"@babel/types";function Vn(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?_n(n,t):null}if(e.isMemberExpression()){let n=Bd(e.node),r=Ld(e.node);if(!n||r===null)return null;let i=e.scope.getBinding(n);return i?_n(i,[...r,...t]):null}return e.isAwaitExpression()||li(e.node)?Ve(Kd(e.node),t,"awaited or fetched expression"):null}function Ld(e){let t=[],n=e;for(;O.isMemberExpression(n);){if(n.computed)if(O.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(O.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(O.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return O.isIdentifier(n)?t:null}function _n(e,t=[]){let n=Od(e,t);if(n)return n;let r=Dd(e,t);if(r)return r;let i=jd(e,t);return i||null}function Jt(e){return e?.kind==="api-source"}function Od(e,t){if(e.path.isVariableDeclarator()&&O.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&ai(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return Ve(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&O.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(l=>O.isObjectProperty(l)&&Js(l)==="data"&&Vt(l.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&ai(a.node))return Ve(e.identifier.name,t,"query hook data binding")}let n=$d(e);if(!n||Js(n.node)!=="data")return null;let i=n.findParent(s=>s.isVariableDeclarator());if(!i?.isVariableDeclarator())return null;let o=i.get("init");return!o?.isCallExpression()||!ai(o.node)?null:Ve(e.identifier.name,t,"query hook data binding")}function Dd(e,t){if(e.path.isVariableDeclarator()&&O.isArrayPattern(e.path.node.id)){let a=e.path.get("init");if(!a?.isCallExpression()||!Vs(a.node))return null;let[l,u]=e.path.node.id.elements;return!O.isIdentifier(l)||l.name!==e.identifier.name||!O.isIdentifier(u)?null:Ks(e,u.name)?Ve(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 i=r.get("init");if(!i?.isCallExpression()||!Vs(i.node)||n.node.elements.findIndex(a=>a===e.path.node)!==0)return null;let s=n.node.elements[1];return O.isIdentifier(s)&&Ks(e,s.name)?Ve(e.identifier.name,t,"state setter is updated by API data"):null}function jd(e,t){let n=e.path.isVariableDeclarator()?e.path:e.path.findParent(i=>i.isVariableDeclarator());if(!n?.isVariableDeclarator())return null;let r=n.get("init");return r?.isExpression()?r.isAwaitExpression()?Ve(e.identifier.name,t,"awaited binding result"):li(r.node)?Ve(e.identifier.name,t,"fetch-backed binding result"):null:null}function $d(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 Vt(e,t){return O.isIdentifier(e)?e.name===t:O.isAssignmentPattern(e)?Vt(e.left,t):O.isObjectPattern(e)?e.properties.some(n=>O.isObjectProperty(n)?Vt(n.value,t):Vt(n.argument,t)):O.isArrayPattern(e)?e.elements.some(n=>!!n&&Vt(O.isRestElement(n)?n.argument:n,t)):!1}function Ks(e,t){let n=!1,r=!1;return e.scope.path.traverse({CallExpression(o){li(o.node)&&(n=!0),(_d(o.node.callee,t)||o.node.arguments.some(s=>O.isIdentifier(s)&&s.name===t))&&(r=!0)}}),n&&r}function ai(e){let t=Jn(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function Vs(e){return Jn(e.callee)==="useState"}function li(e){return Kn(e,t=>O.isCallExpression(t)&&Jn(t.callee)==="fetch")}function Bd(e){let t=e;for(;O.isMemberExpression(t);)t=t.object;return O.isIdentifier(t)?t.name:null}function Js(e){return e.computed?null:O.isIdentifier(e.key)?e.key.name:O.isStringLiteral(e.key)?e.key.value:null}function Jn(e){return O.isIdentifier(e)?e.name:O.isMemberExpression(e)&&O.isIdentifier(e.property)?e.property.name:null}function _d(e,t){return Kn(e,n=>O.isIdentifier(n)&&n.name===t)}function Kn(e,t){if(t(e))return!0;let n=O.VISITOR_KEYS[e.type];if(!n)return!1;for(let r of n){let i=e[r];if(Array.isArray(i)){for(let o of i)if(O.isNode(o)&&Kn(o,t))return!0;continue}if(O.isNode(i)&&Kn(i,t))return!0}return!1}function Kd(e){return O.isIdentifier(e)?e.name:O.isCallExpression(e)?Jn(e.callee)??"api":O.isAwaitExpression(e)?"awaited-api":"api"}function Ve(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:Vd(e,t),reason:n}}function Vd(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var Us=typeof ci=="function"?ci:ci.default;function zs(e,t){let n=Gs(e);if(!n)return{allowed:!0};let r=!1;return Us(n,{CallExpression(i){if(!Ys(i.node,t.sourceRange)||!Jd(i.node))return;let o=i.get("callee");if(!o.isMemberExpression())return;let s=o.get("object");Array.isArray(s)||!s.isExpression()||Jt(Vn(s))&&(r=!0,i.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function Hs(e,t){let n=Gs(e);if(!n)return{allowed:!0};let r=!1;return Us(n,{JSXExpressionContainer(i){Ys(i.node,t.sourceRange)&&(xt.isJSXEmptyExpression(i.node.expression)||(r=!0,i.stop()))}}),r?{allowed:!1,reason:"Cannot move subtree across files because it depends on local binding expressions"}:{allowed:!0}}function Gs(e){try{return Ws.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Jd(e){let t=e.callee;return xt.isMemberExpression(t)&&xt.isIdentifier(t.property)&&t.property.name==="map"}function Ys(e,t){let n=e.loc;return n?Xs({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&Xs({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function Xs(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 K from"@babel/types";function Zs(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 we(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return tt(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(K.isObjectPattern(n)||K.isArrayPattern(n))return tt(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(Wd(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function tt(e,t,n=!1){return K.isIdentifier(e)?e.name===t&&n:K.isObjectPattern(e)?e.properties.some(r=>K.isObjectProperty(r)?tt(r.value,t,n):tt(r.argument,t,n)):K.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let i=K.isRestElement(r)?r.argument:r;return tt(i,t,n)}):K.isAssignmentPattern(e)?tt(e.left,t,!0):K.isRestElement(e)?tt(e.argument,t,n):!1}function yt(e,t){if(e.path.isObjectPattern()){if(t){let r=ye(e.path.node,t.base),[i,...o]=r??[];if(i?.kind==="property")return{propName:i.name,remainingPath:[...o,...t.path],hasDefault:we(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:we(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let i=Qs(r),o=!1,s=i?i.initBinding&&ui(i.initBinding)?(o=we(i.initBinding),[...i.initPathPrefix]):i.initBinding?(()=>{let l=yt(i.initBinding,{kind:"identifier",expression:i.initBinding.identifier.name,base:i.initBinding.identifier.name,path:[]});return o=l?.hasDefault??!1,l?[{kind:"property",name:l.propName},...l.remainingPath,...i.initPathPrefix]:null})():null:null,a=ye(e.path.node.id,e.identifier.name);if(s&&a){let l=[...s,...a],[u,...c]=l;return!u||u.kind!=="property"?null:{propName:u.name,remainingPath:[...c,...t?.path??[]],hasDefault:o||we(e)}}}}let n=Hd(e);if(n){let r=Xd(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||we(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let i=Ud(e);if(i){let[s,...a]=i;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:we(e)}}let o=Xt(n.node);return o?{propName:o,remainingPath:t?.path??[],hasDefault:we(e)}:null}if(ui(e)){let[r,...i]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:i,hasDefault:we(e)}}return null}function Xd(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return null;let r=n.get("init");if(!r?.isExpression())return null;let i=Qs(r);if(!i)return null;let{initBinding:o,initPathPrefix:s}=i;if(!o)return null;let a=!1,l=ui(o)?(a=we(o),[...s]):(()=>{let c=yt(o,{kind:"identifier",expression:o.identifier.name,base:o.identifier.name,path:[]});return a=c?.hasDefault??!1,c?[{kind:"property",name:c.propName},...c.remainingPath,...s]:null})();if(!l)return null;let u=ye(n.node.id,t.identifier.name);return u?{path:[...l,...u],hasDefault:a||we(t)}:null}function Qs(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=Gd(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function ui(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function Wd(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Ud(e){let t=e.identifier.name,n=e.path.getFunctionParent();if(!n)return null;let r=n.get("params"),i=Array.isArray(r)?r:[r];for(let o of i){let a=ye(o.node,t);if(a)return a}return null}function qs(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let l=Xn(a,e.identifier.name);if(l&&(!n||l.propName===n))return{propName:l.propName,componentName:t,expressionPath:l.expressionPath,displayPath:`${t}.${l.propName}.default`}}}if(e.path.isObjectPattern())for(let a of e.path.get("properties")){if(!a.isObjectProperty())continue;let l=Xt(a.node);if(!l||n&&l!==n)continue;let u=a.get("value");if(!u.isAssignmentPattern())continue;let c=u.get("right");if(c.isExpression())return{propName:l,componentName:t,expressionPath:c,displayPath:`${t}.${l}.default`}}let r=zd(e);if(!r)return null;let i=r.parentPath;if(!i?.isObjectProperty())return null;let o=Xt(i.node);if(!o||n&&o!==n)return null;let s=r.get("right");return s.isExpression()?{propName:o,componentName:t,expressionPath:s,displayPath:`${t}.${o}.default`}:null}function Xn(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=Xt(n.node),i=n.get("value");if(i.isAssignmentPattern()){let o=i.get("left"),s=i.get("right");if(r&&!Array.isArray(o)&&ye(o.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(i)&&(i.isObjectPattern()||i.isArrayPattern())){let o=Xn(i,t);if(o)return o}}else if(n.isRestElement()){let r=n.get("argument");if(!Array.isArray(r)&&(r.isObjectPattern()||r.isArrayPattern())){let i=Xn(r,t);if(i)return i}}}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 i=Xn(r,t);if(i)return i}}return null}function ye(e,t,n=[]){if(K.isIdentifier(e))return e.name===t?n:null;if(K.isObjectPattern(e)){for(let r of e.properties)if(K.isObjectProperty(r)){let i=Xt(r);if(!i)continue;let o=ye(r.value,t,[...n,{kind:"property",name:i}]);if(o)return o}else if(K.isRestElement(r)){let i=ye(r.argument,t,n);if(i)return i}}if(K.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let i=e.elements[r];if(!i)continue;let o=K.isRestElement(i)?i.argument:i,s=ye(o,t,[...n,{kind:"index",index:r}]);if(s)return s}return K.isAssignmentPattern(e)?ye(e.left,t,n):null}function zd(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function Hd(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 Xt(e){return e.computed?null:K.isIdentifier(e.key)?e.key.name:K.isStringLiteral(e.key)?e.key.value:null}function Gd(e){let t=[],n=e;for(;K.isMemberExpression(n);){if(n.computed)if(K.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(K.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(K.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return K.isIdentifier(n)?{base:n.name,path:t}:null}var ze=typeof di=="function"?di:di.default;function W(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 St(e){return{file:e.file,component:e.component}}function Yd(e){return e.target.kind==="node"?e.target.key:null}function gi(e,t){let n=Oe.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),i=Oe.relative(n,r);return i=i.replace(/\\/g,"/"),i.startsWith(".")||(i=`./${i}`),i}function fi(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=vn(n,W(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function Ei(e){if(e.component.exportName!=="default")return e.component.exportName;let t=e.component.source.replace(/\\/g,"/").replace(/\/$/,""),n=t.split("/").pop()||"Component",o=(n==="index"?t.split("/").slice(-2,-1)[0]||"Component":n).replace(/\.[^.]+$/,"").split(/[^A-Za-z0-9]+/).filter(Boolean);return o.length===0?"Component":o.map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join("")}function Se(e){try{return vi.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Zd(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function Qd(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 J(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function it(e,t){let n=J(e);return!!(n&&ke(t,n))}function ke(e,t){return t.start>=e.start&&t.end<=e.end}function ma(e){if(g.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(g.isJSXMemberExpression(e)){let t=e;for(;g.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function qd(e,t){let n=J(e.node);if(!n)return[];let r=new Set,i=(o,s)=>{let a=s.scope.getBinding(o);if(!a||it(a.path.node,n))return;t.scope.getBinding(o)!==a&&r.add(o)};return e.traverse({ReferencedIdentifier(o){i(o.node.name,o)},JSXOpeningElement(o){let s=ma(o.node.name);s&&i(s,o)}}),[...r].sort()}function ea(e,t,n){let r=Se(e);if(!r)return{ok:!0};let i=_(r,W(t));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};let o=_(r,W(n));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};if(Fa(i.match.path,o.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let s=qd(i.match.path,o.match.path);return s.length>0?{ok:!1,bindingNames:s}:{ok:!0}}function ta(e,t,n){let r=Je(t,n);return r?Le(e,r):null}function Je(e,t){let n=_(e,W(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:bi(e,t)}function Le(e,t){let n=t.findParent(b=>b.isArrowFunctionExpression()||b.isFunctionExpression());if(!n||!n.isArrowFunctionExpression()&&!n.isFunctionExpression())return null;let r=n,i=r.parentPath;if(!i||!i.isCallExpression()&&!i.isOptionalCallExpression())return null;let o=i;if(o.node.arguments.findIndex(b=>b===r.node)!==0)return null;let a=o.get("callee");if(!a.isMemberExpression()&&!a.isOptionalMemberExpression())return null;let l=a.node,u=l.property;if(!g.isIdentifier(u)||u.name!=="map"||l.computed)return null;let c=a.get("object"),d=Gn(e,c.node),p=r.node.params.map(b=>Gn(e,b)),h=J(o.node),k=J(r.node);return!d||p.some(b=>b.length===0)||!h||!k?null:{callStart:h.start,callEnd:h.end,callbackStart:k.start,callbackEnd:k.end,collectionExpression:d,callbackParams:p,mapOperator:g.isOptionalMemberExpression(l)&&l.optional?"?.map":".map",collectionNeedsParens:Ri(c.node),callbackPath:r,collectionPath:c}}function Gn(e,t){let n=J(t);return n?e.slice(n.start,n.end):""}function Wn(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function ef(e,t){let n=J(e.node);return n?tf(t).some(r=>{let i=J(r);return r===e.node||!!(i&&i.start===n.start&&i.end===n.end)}):!1}function tf(e){let t=e.callbackPath.node.body;return g.isBlockStatement(t)?Xe(t.body):Ue(t)}function Xe(e){let t=[];for(let n of e){if(g.isReturnStatement(n)){n.argument&&t.push(...Ue(n.argument));continue}if(g.isBlockStatement(n)){t.push(...Xe(n.body));continue}if(g.isIfStatement(n)){let r=g.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...Xe(r)),n.alternate){let i=g.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...Xe(i))}continue}if(g.isSwitchStatement(n)){for(let r of n.cases)t.push(...Xe(r.consequent));continue}g.isTryStatement(n)&&(t.push(...Xe(n.block.body)),n.handler&&t.push(...Xe(n.handler.body.body)),n.finalizer&&t.push(...Xe(n.finalizer.body)))}return t}function Ue(e){return g.isJSXElement(e)?nf(e)?na(e.children):[e]:g.isJSXFragment(e)?na(e.children):g.isParenthesizedExpression(e)||g.isTSAsExpression(e)||g.isTSSatisfiesExpression(e)||g.isTSNonNullExpression(e)||g.isTSTypeAssertion(e)?Ue(e.expression):g.isConditionalExpression(e)?[...Ue(e.consequent),...Ue(e.alternate)]:g.isLogicalExpression(e)&&Na(e.operator)?Ue(e.right):[]}function na(e){return e.flatMap(t=>g.isJSXElement(t)||g.isJSXFragment(t)?Ue(t):g.isJSXExpressionContainer(t)&&(g.isJSXElement(t.expression)||g.isJSXFragment(t.expression)||g.isConditionalExpression(t.expression)||g.isLogicalExpression(t.expression))?Ue(t.expression):[])}function nf(e){let t=e.openingElement.name;return g.isJSXIdentifier(t)?t.name==="Fragment":g.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function rf(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function pi(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function ra(e,t,n,r={}){if(!r.preserveConditionalBoundary&&Fa(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let i=J(e.node);if(!i)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(l=>Pi(l)).map(l=>n.callbackPath.scope.getBinding(l)?.path.node).filter(Boolean)),s=new Set,a=(l,u)=>{let c=u.scope.getBinding(l);if(!c||it(c.path.node,i)||o.has(c.path.node))return;t.scope.getBinding(l)!==c&&s.add(l)};return e.traverse({ReferencedIdentifier(l){a(l.node.name,l)},JSXOpeningElement(l){let u=ma(l.node.name);u&&a(u,l)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function ia(e,t,n){let r=J(e.node);if(!r)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(s=>Pi(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),o=new Set;return Ci(e,s=>{let a=s.scope.getBinding(s.node.name);if(!a||it(a.path.node,r)||i.has(a.path.node))return;t.scope.getBinding(s.node.name)!==a&&o.add(s.node.name)}),o.size>0?{ok:!1,bindingNames:[...o].sort()}:{ok:!0}}function of(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>Pi(a)).map(a=>e.callbackPath.scope.getBinding(a)?.path.node).filter(Boolean)),r=new Set,i=(a,l)=>{let u=l.scope.getBinding(a);if(!u||n.has(u.path.node))return;t.scope.getBinding(a)!==u&&r.add(a)},o=e.callbackPath.get("params"),s=Array.isArray(o)?o:[o];for(let a of s)a.traverse({ReferencedIdentifier(l){i(l.node.name,l)},TSTypeReference(l){let u=l.node.typeName;if(g.isIdentifier(u))i(u.name,l);else{let c=sf(u);c&&i(c,l)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function sf(e){let t=e;for(;g.isTSQualifiedName(t);)t=t.left;return g.isIdentifier(t)?t.name:null}function ha(e,t){let n=J(e.node),r=new Set;return Ci(e,i=>{let o=i.scope.getBinding(i.node.name);if(!o||n&&it(o.path.node,n))return;t.scope.getBinding(i.node.name)!==o&&r.add(i.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 Ci(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function af(e){let t=lf(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=Ta(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=bf({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let i=wa(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:i?Ri(i):!0}}}function lf(e,t,n){let r=ya(e,t);if(Sa(e,r),ka(e,r))return{ok:!1,reason:"Cannot move prop-backed repeat child because the component is referenced through an unsupported value usage"};let i=[];return ze(e,{JSXElement(s){Pa(s,r)&&i.push(s)}}),i.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:Ii(i[0])!==n?{ok:!1,reason:"Cannot move prop-backed repeat child because the call site is outside the target component"}:{ok:!0,path:i[0]}}function cf(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=>Wt(a.file)));if(!t.has(Wt(e.sourceFile))||!t.has(Wt(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(Wt(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=pf(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 l=Se(a.content);if(!l)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:l})}let i=uf(r,{file:e.sourceFile,exportName:n.exportName}),o=[];for(let a of r){let l=ga({ast:a.ast,file:a.file,sourceFile:e.sourceFile,sourceComponent:e.sourceComponent,componentIdentities:i});if(l.hasUnsafeReference)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component because the component has unsupported value usages"};o.push(...l.callSites)}if(o.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]=o;return!be(s.file,e.targetFile)||Ii(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 uf(e,t){let n=new Map,r=o=>{let s=kt(o);return n.has(s)?!1:(n.set(s,o),!0)};r(t);let i=!0;for(;i;){i=!1;for(let o of e)for(let s of df(o,n))i=r(s)||i}return[...n.values()]}function df(e,t){let n=[],r=ff(e,t);for(let i of e.ast.program.body){if(g.isExportDefaultDeclaration(i)&&g.isIdentifier(i.declaration)&&(r.get(i.declaration.name)?.length??0)>0){let o=r.get(i.declaration.name)??[];for(let s of o){if(s.namespace){let a=zt(s.namespace,i.declaration.name,"default");a&&n.push({file:e.file,namespace:a,exportName:s.exportName});continue}n.push({file:e.file,exportName:"default"})}continue}if(g.isExportNamedDeclaration(i)&&i.source&&typeof i.source.value=="string"){let o=Ht(e.file,i.source.value);for(let s of i.specifiers){if(g.isExportNamespaceSpecifier(s)){let u=We(s.exported);for(let c of t.values())be(c.file,o)&&n.push({file:e.file,namespace:xi(u,c.namespace),exportName:c.exportName});continue}if(!g.isExportSpecifier(s))continue;let a=We(s.local),l=[...t.values()].filter(u=>be(u.file,o)&&nt(u.namespace,a));if(l.length>0){let u=We(s.exported);for(let c of l){let d=zt(c.namespace,a,u);d&&n.push({file:e.file,namespace:d,exportName:c.exportName})}continue}t.has(kt({file:o,exportName:a}))&&n.push({file:e.file,exportName:We(s.exported)})}continue}if(g.isExportNamedDeclaration(i)&&!i.source){for(let o of i.specifiers){if(!g.isExportSpecifier(o))continue;let s=We(o.local),a=r.get(s)??[];if(a.length>0){let l=We(o.exported);n.push({file:e.file,exportName:l});for(let u of a){let c=zt(u.namespace,s,l);c&&n.push({file:e.file,namespace:c,exportName:u.exportName})}}}continue}if(g.isExportAllDeclaration(i)&&typeof i.source.value=="string"){let o=Ht(e.file,i.source.value),s=i.exported;if(s){let a=We(s);for(let l of t.values())be(l.file,o)&&n.push({file:e.file,namespace:xi(a,l.namespace),exportName:l.exportName});continue}for(let a of t.values())be(a.file,o)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function xi(e,t){return t?`${e}.${t}`:e}function nt(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function zt(e,t,n){return!nt(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function ff(e,t){let n=new Map,r=(o,s)=>{let a=n.get(o)??[];a.push(s),n.set(o,a)};for(let o of e.ast.program.body){if(!g.isImportDeclaration(o)||typeof o.source.value!="string")continue;let s=Ht(e.file,o.source.value);for(let a of o.specifiers){if(g.isImportDefaultSpecifier(a)){let l=t.get(kt({file:s,exportName:"default"}));l&&r(a.local.name,l);let u=[...t.values()].filter(c=>be(c.file,s)&&nt(c.namespace,"default"));for(let c of u){let d=zt(c.namespace,"default",a.local.name);d&&r(a.local.name,{...c,namespace:d})}continue}if(g.isImportSpecifier(a)){let l=We(a.imported),u=[...t.values()].filter(d=>be(d.file,s)&&nt(d.namespace,l));for(let d of u)r(a.local.name,d);let c=t.get(kt({file:s,exportName:l}));c&&r(a.local.name,c);continue}if(g.isImportNamespaceSpecifier(a))for(let l of t.values())be(l.file,s)&&r(a.local.name,{...l,namespace:xi(a.local.name,l.namespace)})}}let i=!0;for(;i;){i=!1;for(let o of e.ast.program.body)if(g.isVariableDeclaration(o))for(let s of o.declarations){if(!g.isIdentifier(s.id)||!s.init)continue;let a=bt(s.init);if(!a||!g.isIdentifier(a))continue;let l=n.get(a.name)??[];if(l.length===0)continue;let u=n.get(s.id.name)??[],c=new Set(u.map(kt));for(let d of l){let p=zt(d.namespace,a.name,s.id.name),h=p?{...d,namespace:p}:d,k=kt(h);c.has(k)||(r(s.id.name,h),c.add(k),i=!0)}}}return n}function kt(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${Si(e.file)}#${t}`}function We(e){return g.isIdentifier(e)?e.name:e.value}function pf(e,t){for(let n of e.program.body){if(g.isExportDefaultDeclaration(n)){let i=n.declaration;if((g.isFunctionDeclaration(i)||g.isClassDeclaration(i))&&i.id?.name===t)return{exportName:"default"};if(g.isIdentifier(i)&&i.name===t)return{exportName:"default"}}if(!g.isExportNamedDeclaration(n))continue;let r=n.declaration;if((g.isFunctionDeclaration(r)||g.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(g.isVariableDeclaration(r)){for(let i of r.declarations)if(g.isIdentifier(i.id,{name:t}))return{exportName:t}}for(let i of n.specifiers){if(!g.isExportSpecifier(i)||i.local.name!==t)continue;return{exportName:g.isIdentifier(i.exported)?i.exported.name:i.exported.value}}}return null}function ga(e){let t=mf(e),n=[],r=ka(e.ast,t);return ze(e.ast,{JSXElement(i){be(e.file,e.sourceFile)&&Ii(i)===e.sourceComponent||Pa(i,t)&&n.push({file:e.file,path:i})}}),{callSites:n,hasUnsafeReference:r}}function xa(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function ya(e,t){let n=xa();return ze(e,{Program(r){let i=r.scope.getBinding(t);i&&n.localBindings.add(i),r.stop()}}),n}function mf(e){let t=xa();return be(e.file,e.sourceFile)&&hf(t,ya(e.ast,e.sourceComponent)),ze(e.ast,{ImportDeclaration(n){let r=n.node,i=r.source.value;if(typeof i!="string")return;let o=Ht(e.file,i),s=e.componentIdentities.filter(a=>be(a.file,o));if(s.length!==0)for(let a of r.specifiers){let l=n.scope.getBinding(a.local.name);if(l){if(g.isImportDefaultSpecifier(a)&&s.some(u=>u.exportName==="default")&&t.localBindings.add(l),g.isImportDefaultSpecifier(a)){let u=s.filter(c=>nt(c.namespace,"default"));if(u.length>0){let c=t.namespaceMembers.get(l)??new Set;for(let d of u){let p=sa(d,"default");p&&c.add(p)}t.namespaceMembers.set(l,c)}continue}if(g.isImportSpecifier(a)){let u=g.isIdentifier(a.imported)?a.imported.name:a.imported.value,c=s.filter(d=>nt(d.namespace,u));if(c.length>0){let d=t.namespaceMembers.get(l)??new Set;for(let p of c){let h=sa(p,u);h&&d.add(h)}t.namespaceMembers.set(l,d);continue}s.some(d=>!d.namespace&&d.exportName===u)&&t.localBindings.add(l);continue}if(g.isImportNamespaceSpecifier(a))for(let u of s){let c=u.namespace?`${u.namespace}.${u.exportName}`:u.exportName,d=t.namespaceMembers.get(l)??new Set;d.add(c),t.namespaceMembers.set(l,d)}}}}}),Sa(e.ast,t),t}function hf(e,t){e.hasUnsupportedAlias||=t.hasUnsupportedAlias;for(let n of t.localBindings)e.localBindings.add(n);for(let[n,r]of t.namespaceMembers){let i=e.namespaceMembers.get(n)??new Set;for(let o of r)i.add(o);e.namespaceMembers.set(n,i)}}function Sa(e,t){ze(e,{VariableDeclarator(n){if(!n.node.init)return;let r=bt(n.node.init);if(r){if(g.isIdentifier(n.node.id)){let i=rt(r,t,n),o=n.scope.getBinding(n.node.id.name);i&&o&&yi(t,o,i);return}if(g.isObjectPattern(n.node.id)){let i=rt(r,t,n);i?.unsupported||i?.local?t.hasUnsupportedAlias=!0:i&&i.namespaceMembers.size>0&&Ea(n.node.id,i.namespaceMembers,t,n)}}}})}function ka(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return ze(e,{ReferencedIdentifier(r){if(n){r.stop();return}gf(r)||!r.isIdentifier()||!ba(r,t)||xf(r,t)||yf(r)||(n=!0,r.stop())}}),n}function gf(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 ba(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)&&rt(r.node,t,r)?r:null}function xf(e,t){let n=e.findParent(l=>l.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!oa(e,r))return!1;let i=ba(e,t);if(!i)return!1;if(bt(r.node)===i.node)return!!rt(r.node,t,r);let s=e.findParent(l=>l.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&oa(e,a)&&!!rt(a.node,t,a)}function yf(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function oa(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function rt(e,t,n){let r=bt(e);if(!r)return null;if(g.isIdentifier(r)){let a=n.scope.getBinding(r.name);if(!a)return null;let l=t.namespaceMembers.get(a);return t.localBindings.has(a)?{local:!0,namespaceMembers:new Set,unsupported:!1}:l?{local:!1,namespaceMembers:new Set(l),unsupported:!1}:null}if(g.isObjectExpression(r))return Sf(r,t,n);let i=Ia(r);if(!i||i.length===0)return null;let o=n.scope.getBinding(i[0]);if(!o)return null;let s=t.namespaceMembers.get(o);return s?va(s,i.slice(1).join(".")):null}function Sf(e,t,n){let r=new Set,i=!1;for(let o of e.properties){if(!g.isObjectProperty(o))continue;let s=Ca(o);if(!s||!g.isExpression(o.value)){g.isExpression(o.value)&&(i||=rt(o.value,t,n)!==null);continue}let a=rt(o.value,t,n);if(a){i||=a.unsupported,a.local&&r.add(s);for(let l of a.namespaceMembers)r.add(`${s}.${l}`)}}return r.size>0||i?{local:!1,namespaceMembers:r,unsupported:i}:null}function va(e,t){if(!t)return{local:!1,namespaceMembers:new Set(e),unsupported:!1};let n=new Set,r=!1;for(let i of e){if(i===t){r=!0;continue}i.startsWith(`${t}.`)&&n.add(i.slice(t.length+1))}return r||n.size>0?{local:r,namespaceMembers:n,unsupported:!1}:null}function yi(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 i of n.namespaceMembers)r.add(i);e.namespaceMembers.set(t,r)}}function Ea(e,t,n,r){for(let i of e.properties){if(g.isRestElement(i)){if(g.isIdentifier(i.argument)){let l=r.scope.getBinding(i.argument.name);l&&yi(n,l,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!g.isObjectProperty(i))continue;let o=Ca(i);if(!o){n.hasUnsupportedAlias=!0;continue}let s=va(t,o);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=g.isAssignmentPattern(i.value)?i.value.left:i.value;if(g.isIdentifier(a)){let l=r.scope.getBinding(a.name);l&&yi(n,l,s);continue}if(g.isObjectPattern(a)&&s.namespaceMembers.size>0){Ea(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function Ca(e){return e.computed?g.isStringLiteral(e.key)||g.isNumericLiteral(e.key)?String(e.key.value):null:kf(e.key)}function kf(e){return g.isIdentifier(e)?e.name:g.isStringLiteral(e)||g.isNumericLiteral(e)?String(e.value):null}function bt(e){return g.isParenthesizedExpression(e)||g.isTSAsExpression(e)||g.isTSSatisfiesExpression(e)||g.isTSNonNullExpression(e)||g.isTSTypeAssertion(e)?bt(e.expression):g.isExpression(e)?e:null}function Ia(e){if(g.isIdentifier(e))return[e.name];if((g.isMemberExpression(e)||g.isOptionalMemberExpression(e))&&!e.computed&&g.isIdentifier(e.property)){let t=bt(e.object),n=t?Ia(t):null;return n?[...n,e.property.name]:null}return null}function sa(e,t){if(!nt(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 Pa(e,t){let n=e.node.openingElement.name;if(g.isJSXIdentifier(n)){let i=e.scope.getBinding(n.name);return!!(i&&t.localBindings.has(i))}let r=Ra(n);if(r&&r.length>1){let i=e.scope.getBinding(r[0]);return i?t.namespaceMembers.get(i)?.has(r.slice(1).join("."))===!0:!1}return!1}function Ra(e){if(g.isJSXIdentifier(e))return[e.name];if(g.isJSXMemberExpression(e)){let t=Ra(e.object);return t?[...t,e.property.name]:null}return null}function Ii(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()&&g.isIdentifier(n.node.id))return n.node.id.name}return null}function bf(e){let t=J(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,i=null,o=s=>{if(i)return;let a=s.scope.getBinding(s.node.name);if(!a||it(a.path.node,t))return;let l=Cf(s,a,t);if(l){if(l.hasDefault){i="Cannot move prop-backed repeat child because the collection prop has a default value that cannot be preserved safely";return}let c=Pf(e.callSitePath,l.propName,e.source);if(!c.ok){i=c.reason;return}let d=vf(c.expression,l.remainingPath);if(!d){i="Cannot move prop-backed repeat child because the mapped prop path is not a portable expression";return}let p=ha(c.expressionPath,e.targetParentPath);if(!p.ok){i=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(`${l.range.start}:${l.range.end}`,{...l.range,text:d});return}e.targetParentPath.scope.getBinding(s.node.name)!==a&&r.add(s.node.name)};return e.sourceContext.collectionPath.isIdentifier()&&e.sourceContext.collectionPath.isReferencedIdentifier()&&o(e.sourceContext.collectionPath),e.sourceContext.collectionPath.traverse({ReferencedIdentifier(s){s.isIdentifier()&&o(s)}}),i?{ok:!1,reason:i}: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:Rf(e.source,t,[...n.values()])}}function vf(e,t){if(t.length===0)return e;let n=wa(e);if(!n)return null;let r=Ri(n)?`(${e})`:e;for(let i of t){if(i.kind==="property"){r=Ef(i.name)?`${r}.${i.name}`:`${r}[${JSON.stringify(i.name)}]`;continue}r=`${r}[${i.index}]`}return r}function Ef(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function Cf(e,t,n){let r=If(e,n),i=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:[]},o=yt(t,i);if(!o)return null;let s=r?.range??J(e.node);return s?{propName:o.propName,remainingPath:o.remainingPath,hasDefault:o.hasDefault,range:s}:null}function If(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!it(n.node,t)||n.node.computed||!g.isIdentifier(n.node.property))return null;let r=J(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function Pf(e,t,n){let r=e.get("openingElement").get("attributes");if(r.some(l=>l.isJSXSpreadAttribute()))return{ok:!1,reason:"Cannot move prop-backed repeat child through spread props; use an explicit prop mapping"};let i=r.find(l=>l.isJSXAttribute()&&g.isJSXIdentifier(l.node.name)&&l.node.name.name===t);if(!i?.isJSXAttribute())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not passed explicitly`};let o=i.get("value");if(!o.isJSXExpressionContainer())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not an expression`};let s=o.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=Gn(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 Rf(e,t,n){let r=e.slice(t.start,t.end),i=[...n].sort((o,s)=>s.start-o.start);for(let o of i)r=r.slice(0,o.start-t.start)+o.text+r.slice(o.end-t.start);return r}function wa(e){try{let n=vi.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=g.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&g.isExpression(r)?r:null}catch{return null}}function wf(e){let t=J(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,i=o=>{let s=o.scope.getBinding(o.node.name);if(!s||it(s.path.node,t))return;let a=aa(s,e.sourceFile,e.targetFile);if(a){let l=e.targetParentPath.scope.getBinding(a.localName);if(l){let c=aa(l,e.targetFile,e.targetFile);(!c||c.moduleFile!==a.moduleFile||!Ff(c.importSpec,a.importSpec))&&r.add(a.localName);return}let u=n.get(a.moduleSpecifier)??[];u.some(c=>JSON.stringify(c)===JSON.stringify(a.importSpec))||u.push(a.importSpec),n.set(a.moduleSpecifier,u);return}r.add(o.node.name)};return Ci(e.sourceContext.collectionPath,i),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(([o,s])=>({moduleSpecifier:o,imports:s}))}}function Ff(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 aa(e,t,n){let r=Af(e),i=r?.parentPath;if(!r||!i?.isImportDeclaration())return null;let o=i.node.source.value;if(typeof o!="string")return null;let s=Ht(t,o),a=o.startsWith(".")?gi(n,s):o;if(r.isImportDefaultSpecifier()){let l=r.node.local.name;return{localName:l,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"default",local:l}}}if(r.isImportNamespaceSpecifier()){let l=r.node.local.name;return{localName:l,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"namespace",local:l}}}if(r.isImportSpecifier()){let l=g.isIdentifier(r.node.imported)?r.node.imported.name:r.node.imported.value,u=r.node.local.name;return{localName:u,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"named",imported:l,local:u===l?void 0:u}}}return null}function Af(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function Ht(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?Oe.normalize(Oe.join(Oe.dirname(e),t)).replace(/\\/g,"/"):t}function be(e,t){return Si(e)===Si(t)}function Si(e){let t=Wt(e);return t.endsWith("/index")?t.slice(0,-6):t}function Wt(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function Pi(e){let t=[],n=r=>{if(r){if(g.isIdentifier(r)){t.push(r.name);return}if(g.isObjectPattern(r)){for(let i of r.properties){if(g.isRestElement(i)){n(i.argument);continue}g.isObjectProperty(i)&&n(i.value)}return}if(g.isArrayPattern(r)){for(let i of r.elements)n(i);return}if(g.isAssignmentPattern(r)){n(r.left);return}if(g.isRestElement(r)){n(r.argument);return}g.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function Nf(e){let t=[];for(let n of e.callbackPath.node.params){if(g.isIdentifier(n)){t.push(n.name);continue}if(g.isRestElement(n)&&g.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 Tf(e,t){return{...e,callbackParams:t}}function la(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function Ri(e){return!(g.isIdentifier(e)||g.isThisExpression(e)||g.isMemberExpression(e)||g.isOptionalMemberExpression(e)||g.isCallExpression(e)||g.isOptionalCallExpression(e))}function Fa(e,t){return Aa(e,t).length>0}function mi(e,t){let n=J(e.node),r=J(t.node);if(!n||!r)return!1;let i=e.parentPath;for(;i;){if((i.isIfStatement()||i.isSwitchCase())&&(!!!t.findParent(s=>s.node===i?.node)||i.isIfStatement()&&!Mf(i,n,r)))return!0;i=i.parentPath}return!1}function Mf(e,t,n){let r=J(e.node.consequent);if(r&&ke(r,t)&&!ke(r,n))return!1;let i=e.node.alternate?J(e.node.alternate):null;return!(i&&ke(i,t)&&!ke(i,n))}function Aa(e,t){let n=J(e.node);if(!n)return[];let r=[],i=e.parentPath;for(;i;){let o=!!t.findParent(s=>s.node===i?.node);if(!o&&i.isConditionalExpression()){let s=J(i.node.consequent),a=J(i.node.alternate);s&&n.start>=s.start&&n.end<=s.end?r.push({kind:"conditional",path:i,conditionPath:i.get("test"),branch:"consequent"}):a&&n.start>=a.start&&n.end<=a.end&&r.push({kind:"conditional",path:i,conditionPath:i.get("test"),branch:"alternate"})}else if(!o&&i.isLogicalExpression()&&Na(i.node.operator)){let s=J(i.node.right);s&&n.start>=s.start&&n.end<=s.end&&r.push({kind:"logical",path:i,conditionPath:i.get("left"),operator:i.node.operator})}i=i.parentPath}return r}function ca(e,t,n,r){let i=Aa(t,n);if(i.length===0)return{sourceJsx:r,conditionPaths:[]};let o=r,s=[];for(let a of i){let l=Gn(e,a.conditionPath.node);if(!l)return{sourceJsx:r,conditionPaths:[]};let u=Lf(a.conditionPath,l);if(s.push(a.conditionPath),a.kind==="logical"){o=`${u} ${a.operator} ${Df(o)}`;continue}o=a.branch==="consequent"?`${u} ? ${o} : null`:`${u} ? null : ${o}`}return{sourceJsx:o,conditionPaths:s}}function Lf(e,t){return Of(e.node)?t:`(${t})`}function Of(e){return g.isIdentifier(e)||g.isThisExpression(e)||g.isSuper(e)||g.isMemberExpression(e)||g.isOptionalMemberExpression(e)||g.isCallExpression(e)||g.isOptionalCallExpression(e)||g.isBooleanLiteral(e)||g.isNumericLiteral(e)||g.isStringLiteral(e)||g.isNullLiteral(e)||g.isUnaryExpression(e)}function Na(e){return e==="&&"||e==="||"||e==="??"}function Df(e){return e.trim().startsWith("<")?e:`(${e})`}function Ta(e,t){let n=J(e.node),r=J(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 i=ua(e),o=ua(t);if(!i||!o||!jf(i,o))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=$f(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=J(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())&&Bf(s)){let a=J(s.node.body)??J(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 ua(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?J(t.node.argument):null;if(t.isArrowFunctionExpression()&&(g.isJSXElement(t.node.body)||g.isJSXFragment(t.node.body)||g.isConditionalExpression(t.node.body)||g.isLogicalExpression(t.node.body)))return J(t.node.body);t=t.parentPath}return null}function jf(e,t){return e.start===t.start&&e.end===t.end}function $f(e,t){let n=J(e.consequent);if(n&&ke(n,t))return n;let r=J(e.alternate);return r&&ke(r,t)?r:null}function Bf(e){let t=e.parentPath;if(!t||!t.isCallExpression()&&!t.isOptionalCallExpression()||t.node.arguments[0]!==e.node)return!1;let n=t.node.callee;return(g.isMemberExpression(n)||g.isOptionalMemberExpression(n))&&g.isIdentifier(n.property)&&n.property.name==="map"&&!n.computed}var _f={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 Un(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=_f[n];if(!r)return null;let i=t.tag.toLowerCase();return r.has(i)?null:`Cannot insert <${t.tag}> into <${e.tag}>; expected ${[...r].map(o=>`<${o}>`).join(", ")}`}function Kf(e,t){for(let n of e.program.body){if(!g.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(i=>g.isImportDefaultSpecifier(i));if(r&&g.isImportDefaultSpecifier(r))return r.local.name}return null}function Vf(e){let t=new Set;return ze(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function Jf(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function Xf(e,t){let n=Ei(e);if(e.component.exportName!=="default")return{localName:n,importStep:hi(e,n)};let r=Se(t);if(!r)return{localName:n,importStep:hi(e,n)};let i=Kf(r,e.component.source);if(i)return{localName:i};let o=Jf(n,Vf(r));return{localName:o,importStep:hi(e,o)}}function Wf(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??Ei(e);if(e.props&&Object.keys(e.props).length>0){let r=Object.entries(e.props).map(([i,o])=>typeof o=="string"?`${i}="${o}"`:`${i}={${JSON.stringify(o)}}`).join(" ");return`<${n} ${r} />`}return`<${n} />`}function Uf(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};let t=e.props?zf(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function zf(e){return Object.fromEntries(Object.entries(e).filter(t=>ki(t[1])))}function ki(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(ki):typeof e=="object"?Object.values(e).every(ki):!1}function Hf(e,t){let n=Se(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=ga({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 hi(e,t=Ei(e)){return{moduleSpecifier:e.component.source,imports:e.component.exportName==="default"?[{kind:"default",local:t}]:[{kind:"named",imported:e.component.exportName}]}}function da(e,t){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 Gf(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function zn(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function wi(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function Ut(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:wi(e,t.slice(0,n)),index:r.index}}return null}function fa(e,t){return e.locator?e.collectionPathMap?.[t]?wi(e.locator,e.collectionPathMap[t]):Ut(e.locator)?Zf(e.locator,Qf(t,e.collectionIndexMap)):null:null}function Yf(e,t){let n=e.path??[],r=n.findLastIndex(o=>o.kind==="index");if(r===-1)return;let i=n.slice(r+1);return i.length===0?t:Ma(i,t)}function Ma(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let i=Ma(r,t);return i===void 0?void 0:{[n.name]:i}}function Hn(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 Zf(e,t){let n=e.path??[];for(let r=n.length-1;r>=0;r-=1)if(n[r].kind==="index"){let o=[...n];return o[r]={kind:"index",index:t},wi(e,o)}return null}function Qf(e,t){return t?.[e]??e}function pa(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 qf(e,t){return ep(e.root,t.root)&&np(e.path??[],t.path??[])}function ep(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&&tp(e.sourceRange,t.sourceRange)}}function tp(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function bi(e,t){let n=null;return ze(e,{JSXElement(r){let i=r.node.loc;i&&i.start.line===t.sourceRange.startLine&&i.start.column===t.sourceRange.startColumn&&i.end.line===t.sourceRange.endLine&&i.end.column===t.sourceRange.endColumn&&(n=r,r.stop())}}),n}function np(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(r.kind!==i.kind)return!1;if(r.kind==="property"){if(i.kind!=="property"||r.name!==i.name)return!1;continue}if(i.kind!=="index"||r.index!==i.index)return!1}return!0}var Yn=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:zn(t.kind,t.params.kind)};let r=t,i=this.resolveNodeRequest(t);if(!i.ok)return i.result;let o=i.node,s=this.graph.getFileVersion(o.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,o,this.graph.getCapability(o.key),await this.graph.getTextWriteTarget(o.key,r.params.segmentIndex))}case"remove-node":{if(t.params.kind!=="remove-node")return{ok:!1,errorCode:"unknown",reason:zn(t.kind,t.params.kind)};let r=t,i=this.resolveNodeRequest(t);if(!i.ok)return i.result;let o=i.node,s=this.graph.getFileVersion(o.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,o,this.graph.getCapability(o.key))}case"insert-child":{if(t.params.kind!=="insert-child")return{ok:!1,errorCode:"unknown",reason:zn(t.kind,t.params.kind)};let r=t,i=da(r.params.position,this.graph);if(!i.parentNode)return{ok:!1,errorCode:"locator-miss",reason:`Insert target parent for request '${t.id}' not found in graph`};let o=this.graph.getFileVersion(i.parentNode.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.planInsertChild(n,r,i.parentNode,this.graph.getCapability(i.parentNode.key),i.anchorNode)}case"move-node":{if(t.params.kind!=="move-node")return{ok:!1,errorCode:"unknown",reason:zn(t.kind,t.params.kind)};let r=t,i=this.resolveNodeRequest(t);if(!i.ok)return i.result;let o=i.node,s=this.graph.getFileVersion(o.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,o,this.graph.getCapability(o.key))}case"set-class-name-source":{let r=this.resolveNodeRequest(t);if(!r.ok)return r.result;let i=this.graph.getFileVersion(r.node.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.planNodeAttributeOperation(n,t,r.node)}case"set-props":{let r=this.resolveNodeRequest(t);if(!r.ok)return r.result;let i=this.graph.getFileVersion(r.node.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})`}:await this.planSetProps(n,t,r.node)}case"apply-style-draft":{let r=this.resolveNodeRequest(t);if(!r.ok)return r.result;let i=this.graph.getFileVersion(r.node.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})`}:await this.planApplyStyleDraft(n,t,r.node)}default:return{ok:!1,errorCode:"unknown",reason:`Unknown operation kind: ${t.kind}`}}}resolveNodeRequest(t){let n=Yd(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 i=r.file,o=this.graph.getCapability(r.key);return n.params.filePath!==i?{ok:!1,errorCode:"stale-version",reason:"The className source file changed before save."}:this.buildPlan(t,n,[{order:0,file:i,type:"set-class-name-source",request:{...n.params,key:r.key}}],o)}async planSetProps(t,n,r){let i=this.graph.getCapability(r.key),o=await this.buildSetPropsSteps({initialOrder:0,node:r,props:n.params.props,request:n});return o.ok?this.buildPlan(t,n,o.steps,i):o}async planApplyStyleDraft(t,n,r){let i=r.file,o=this.graph.getCapability(r.key),s=[];if(n.params.className){if(n.params.className.filePath!==i)return{ok:!1,errorCode:"stale-version",reason:"The className source file changed before save."};s.push({order:s.length,file:i,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,o)}async buildSetPropsSteps(t){let{initialOrder:n,node:r,props:i,request:o}=t,s=r.file,a=[],l={};for(let[u,c]of Object.entries(i)){if(c===void 0)continue;let d=await this.graph.getElementPropertyWriteTarget?.(r.key,u);if(d?.kind==="value-binding"&&d.locator){let p=d.locator;if(d.sourceKind==="repeat-template"&&typeof o.selectionRef?.instanceIndex=="number"){let h=fa(d,o.selectionRef.instanceIndex);if(!h)return{ok:!1,errorCode:"invalid-params",reason:"set-props could not resolve the selected repeat item"};p=h}a.push({order:n+a.length,file:d.file,type:"update-value",locator:p,value:c});continue}l[u]=c}return Object.keys(l).length>0&&a.push({order:n+a.length,file:s,type:"set-props",locator:W(r),props:l}),{ok:!0,steps:a}}buildTextRewriteSteps(t,n,r,i,o){if(i?.kind==="value-binding"&&i.locator){if(i.sourceKind==="repeat-template"&&typeof o?.instanceIndex=="number"){let a=fa(i,o.instanceIndex);if(!a)return{ok:!1,errorCode:"invalid-params",reason:"update-text could not resolve the selected repeat item"};let l=this.coerceTextValueForValueTarget(i.file,a,r);return l.ok?{ok:!0,steps:[{order:0,file:i.file,type:"update-array-item",locator:a,value:l.value}]}:l}let s=this.coerceTextValueForValueTarget(i.file,i.locator,r);return s.ok?{ok:!0,steps:[{order:0,file:i.file,type:"update-value",locator:i.locator,value:s.value}]}:s}return{ok:!0,steps:i?.kind==="external-entry"?[{order:0,file:`external:${i.sourceId}`,type:"invoke-external-adapter",sourceType:i.sourceType,sourceId:i.sourceId,adapterId:i.adapterId,capability:"write-text",value:r}]:[{order:0,file:t.file,type:"update-text",locator:W(t),segmentIndex:n,newText:r}]}}coerceTextValueForValueTarget(t,n,r){let i=this.graph.getFileContent(t),o=Se(i);if(!o)return{ok:!1,errorCode:"invalid-params",reason:"update-text could not inspect the value source"};let s=_(o,n);if(!s.ok)return{ok:!1,errorCode:"invalid-params",reason:"update-text could not resolve the value source"};if(!Zd(s.match.path))return{ok:!0,value:r};let a=Qd(r);return a===null?{ok:!1,errorCode:"invalid-params",reason:"update-text value must be a valid number for numeric source"}:{ok:!0,value:a}}planUpdateText(t,n,r,i,o){if(!i.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,o,n.selectionRef);return s.ok?this.buildPlan(t,n,s.steps,i):s}async planRemoveNode(t,n,r,i){if(!i.canRemove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot remove this node"};let o=await this.graph.getTextWriteTarget(r.key,0);if(o?.kind==="external-entry")return this.buildPlan(t,n,[{order:0,file:`external:${o.sourceId}`,type:"invoke-external-adapter",sourceType:o.sourceType,sourceId:o.sourceId,adapterId:o.adapterId,capability:"remove-node",value:{operation:"remove-node"}}],i);if(r.isRepeatItemRoot){let d=o;if(d?.kind==="value-binding"&&d.locator){let p=Ut(d.locator);if(p)return this.buildPlan(t,n,[{order:0,file:d.file,type:"remove-bound-array-item",locator:p.locator,index:p.index}],i)}return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed node removal requires a writable array target"}}let s=Hn(r,o,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 l=await this.getUpstreamBackedDescendantReason(r);if(l)return{ok:!1,errorCode:"unsupported-operation",reason:l};let u=[{order:0,file:r.file,type:"remove-node",locator:W(r),removeWhitespace:!0}],c=this.buildRemoveComponentImportStep(r);return c&&u.push({...c,order:u.length}),this.buildPlan(t,n,u,i)}buildRemoveComponentImportStep(t,n=this.graph.getFileContent(t.file)){if(!t.importedFrom||!t.exportName||!t.tag||Hf(n,t)>1)return null;let r=gi(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,i,o){if(!i.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,l=Hn(r,a,s!==null?this.graph.getTextProvenance?.(r.key,s)??null:null);if(l)return{ok:!1,errorCode:"unsupported-operation",reason:l};let u=await this.getUpstreamBackedDescendantReason(r);if(u)return{ok:!1,errorCode:"unsupported-operation",reason:u};let c=await this.planExternalBackedInsertChild(t,n,r,i,o,a);if(c)return c;let d=await this.planRepeatBackedInsertChild(t,n,r,i);if(d)return d;let p=this.getRepeatBackedTemplateStructureReason(r);if(p)return{ok:!1,errorCode:"unsupported-operation",reason:p};let h=zs(this.graph.getFileContent(r.file),r);if(!h.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:h.reason??"Cannot insert child into this node"};let k=Un(r,n.params.node);if(k)return{ok:!1,errorCode:"unsupported-operation",reason:k};let b=[],E=0,P=n.params.node.kind==="component-call"?Xf(n.params.node,this.graph.getFileContent(r.file)):void 0,R=P?.importStep;return R&&b.push({order:E++,file:r.file,type:"add-import",moduleSpecifier:R.moduleSpecifier,imports:R.imports}),b.push({order:E++,file:r.file,type:"insert-child",parentLocator:W(r),node:{jsx:Wf(n.params.node,P?.localName)},placement:n.params.position.relation,anchorLocator:o?W(o):void 0}),this.buildPlan(t,n,b,i)}async planExternalBackedInsertChild(t,n,r,i,o,s){let a=s?.kind==="external-entry"?s:await this.findExternalInsertContext(r,o);if(!a)return null;let l=o?await this.graph.getTextWriteTarget(o.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:l?.kind==="external-entry"?l.sourceId:null,node:Uf(n.params.node)}}],i)}async findExternalInsertContext(t,n){if(n){let i=await this.graph.getTextWriteTarget(n.key,0);if(i?.kind==="external-entry")return i}if(!this.graph.getChildNodes)return null;let r=[...this.graph.getChildNodes(t.key)];for(;r.length>0;){let i=r.shift();if(!i)continue;let o=await this.graph.getTextWriteTarget(i.key,0);if(o?.kind==="external-entry")return o;let s=this.graph.getTextProvenance?.(i.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(i.key))}return null}async planRepeatBackedInsertChild(t,n,r,i){if(n.params.position.relation!=="append"&&n.params.position.relation!=="prepend")return null;let o=n.params.node;if(o.kind!=="native-tag"||o.text===void 0||!this.graph.getChildNodes)return null;let s=this.graph.getChildNodes(r.key).find(d=>d.isRepeatItemRoot&&d.tag?.toLowerCase()===o.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 l=Ut(a.locator);if(!l)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let u=Yf(a.locator,o.text);if(u===void 0)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child could not infer an item shape from the template"};let c=n.params.position.relation==="prepend"?pa(0,a.collectionIndexMap):pa(a.collectionIndexMap?.length??l.index+1,a.collectionIndexMap);return this.buildPlan(t,n,[{order:0,file:a.file,type:"insert-bound-array-item",locator:l.locator,index:c,value:u}],i)}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 i=this.graph.getEditableTextSegmentIndex(r.key),o=i!==null?await this.graph.getTextWriteTarget(r.key,i):null,s=Hn(r,o,i!==null?this.graph.getTextProvenance?.(r.key,i)??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=Se(this.graph.getFileContent(t.file));if(!n)return t.isRepeatItemRoot===!0;let r=_(n,W(t)),i=r.ok&&r.match.path.isJSXElement()?r.match.path:bi(n,t);if(!i)return t.isRepeatItemRoot===!0;let o=Le(this.graph.getFileContent(t.file),i);return o?ef(i,o):t.isRepeatItemRoot===!0}isInsideMapCallback(t){let n=Se(this.graph.getFileContent(t.file));if(!n)return!1;let r=_(n,W(t)),i=r.ok&&r.match.path.isJSXElement()?r.match.path:bi(n,t);return i?!!i.findParent(o=>{if(!o.isCallExpression()&&!o.isOptionalCallExpression())return!1;let s=o.node.callee;return(g.isMemberExpression(s)||g.isOptionalMemberExpression(s))&&g.isIdentifier(s.property)&&s.property.name==="map"}):!1}planRepeatTemplateInternalMove(t,n,r,i,o,s,a){if(r.isRepeatItemRoot&&this.isRepeatTemplateRootNode(r)||r.file!==i.file)return null;let l=this.graph.getFileContent(r.file),u=Se(l);if(!u)return null;let c=Je(u,r),d=Je(u,i);if(!c||!d)return null;let p=Le(l,c),h=Le(l,d);if(!Wn(p,h))return null;if(a&&(s==="before"||s==="after")){let b=Je(u,a),E=b?Le(l,b):null;if(!Wn(p,E))return null}if(mi(c,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let k=ea(l,r,i);return k.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:W(r),targetParentLocator:W(i),placement:s,anchorLocator:a?W(a):void 0,selectionContext:St(i)}],o):{ok:!1,errorCode:"unsupported-operation",reason:k.reason??`Cannot move node because it depends on bindings outside the target scope: ${k.bindingNames.join(", ")}`}}planRepeatTemplateHoistMove(t,n,r,i,o,s,a){if(r.isRepeatItemRoot&&this.isRepeatTemplateRootNode(r)||r.file!==i.file)return null;let l=this.graph.getFileContent(r.file),u=Se(l);if(!u)return null;let c=Je(u,r),d=Je(u,i);if(!c||!d)return null;let p=Le(l,c);if(!p)return null;let h=Le(l,d);if(Wn(p,h))return null;if(h&&!rf(h,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 I=ta(l,u,a);if(h&&!Wn(h,I)||!h&&I)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 I=Un(i,{kind:"native-tag",tag:r.tag});if(I)return{ok:!1,errorCode:"unsupported-operation",reason:I}}let k=fi(this.graph,r);if(!k)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(mi(c,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let b=ca(l,c,d,k);for(let I of b.conditionPaths){let B=ia(I,d,p);if(!B.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${B.bindingNames.join(", ")}`}}let E=ra(c,d,p,{preserveConditionalBoundary:b.conditionPaths.length>0});if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:E.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${E.bindingNames.join(", ")}`};let P=of(p,d);if(!P.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its callback parameters depend on bindings outside the target scope: ${P.bindingNames.join(", ")}`};let R=p;if(r.component!==i.component){let I=af({source:l,ast:u,sourceContext:p,sourceNode:r,targetParent:i,targetParentPath:d});if(!I.ok)return{ok:!1,errorCode:"unsupported-operation",reason:I.reason};R=I.context}else{let I=ha(p.collectionPath,d);if(!I.ok)return{ok:!1,errorCode:"unsupported-operation",reason:I.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${I.bindingNames.join(", ")}`}}return this.buildPlan(t,n,[{order:0,file:r.file,type:"move-repeat-template-child",locator:W(r),targetParentLocator:W(i),placement:s,anchorLocator:a?W(a):void 0,repeatExpression:la(R,b.sourceJsx),selectionContext:St(i)}],o)}planCrossFileRepeatTemplateHoistMove(t,n,r,i,o,s,a){if(r.isRepeatItemRoot&&this.isRepeatTemplateRootNode(r)||r.file===i.file)return null;let l=this.graph.getFileContent(r.file),u=this.graph.getFileContent(i.file),c=Se(l),d=Se(u);if(!c||!d)return null;let p=cf({knownSourceFiles:this.graph.getKnownSourceFiles?.(),routeEntryFiles:this.graph.getRouteEntryFiles?.(),sourceAst:c,sourceFile:r.file,targetFile:i.file,sourceComponent:r.component,targetComponent:i.component});if(!p.ok)return{ok:!1,errorCode:"unsupported-operation",reason:p.reason};let h=Je(c,r),k=Je(d,i);if(!h||!k)return null;let b=Ta(p.callSitePath,k);if(!b.ok)return{ok:!1,errorCode:"unsupported-operation",reason:b.reason};let E=Le(l,h);if(!E)return null;if(Le(u,k))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")&&ta(u,d,a))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child relative to a repeat-template anchor outside the target scope"};if(r.tag&&r.tag.toLowerCase()===r.tag){let A=Un(i,{kind:"native-tag",tag:r.tag});if(A)return{ok:!1,errorCode:"unsupported-operation",reason:A}}let R=fi(this.graph,r);if(!R)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(mi(h,k))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let I=ca(l,h,k,R);for(let A of I.conditionPaths){let z=ia(A,k,E);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 B=ra(h,k,E,{preserveConditionalBoundary:I.conditionPaths.length>0});if(!B.ok)return{ok:!1,errorCode:"unsupported-operation",reason:B.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${B.bindingNames.join(", ")}`};let G=wf({sourceFile:r.file,targetFile:i.file,sourceContext:E,targetParentPath:k});if(!G.ok)return{ok:!1,errorCode:"unsupported-operation",reason:G.reason};let C=Nf(E);if(!C.ok)return{ok:!1,errorCode:"unsupported-operation",reason:C.reason};let j=Tf(E,C.callbackParams),F=[{order:0,file:r.file,type:"remove-node",locator:W(r),removeWhitespace:!0}];for(let A of G.imports)F.push({order:F.length,file:i.file,type:"add-import",moduleSpecifier:A.moduleSpecifier,imports:A.imports});return F.push({order:F.length,file:i.file,type:"insert-jsx-expression-child",parentLocator:W(i),expression:la(j,I.sourceJsx),placement:s,anchorLocator:a?W(a):void 0,selectionContext:St(i)}),this.buildPlan(t,n,F,o)}async planMoveNode(t,n,r,i){if(!i.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};let o=da(n.params.target,this.graph),s=o.parentNode;if(!s)return{ok:!1,errorCode:"locator-miss",reason:`Target parent for request '${n.id}' not found in graph`};if(Gf(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 P=n.params.target.relation,R=o.anchorNode&&(P==="before"||P==="after")?await this.graph.getTextWriteTarget(o.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:P,anchorSourceId:R?.kind==="external-entry"?R.sourceId:null,parentKey:"parentKey"in n.params.target?n.params.target.parentKey:null}}],i)}let l=r.file!==s.file,u=n.params.target.relation,c=o.anchorNode,d=Hn(r,a,this.graph.getTextProvenance?.(r.key,0)??null);if(d&&!pi(d))return{ok:!1,errorCode:"unsupported-operation",reason:d};if(r.isRepeatItemRoot&&c?.isRepeatItemRoot&&r.repeatOwnerKey&&r.repeatOwnerKey===c.repeatOwnerKey&&(u==="before"||u==="after")){let P=a,R=await this.graph.getTextWriteTarget(c.key,0);if(P?.kind==="value-binding"&&R?.kind==="value-binding"&&P.locator&&R.locator){let I=Ut(P.locator),B=Ut(R.locator);if(I&&B&&P.file===R.file&&qf(I.locator,B.locator)){let G=I.index,C=B.index,j=u==="before"?C-(G<C?1:0):C+(G<C?0:1);return this.buildPlan(t,n,[{order:0,file:P.file,type:"move-array-item",locator:I.locator,fromIndex:G,toIndex:j}],i)}}}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),h=pi(d)?d:p;if(h&&pi(h)){let P=this.planRepeatTemplateInternalMove(t,n,r,s,i,u,c);if(P)return P;let R=this.planRepeatTemplateHoistMove(t,n,r,s,i,u,c);if(R)return R;let I=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,i,u,c);return I||{ok:!1,errorCode:"unsupported-operation",reason:h}}if(p)return{ok:!1,errorCode:"unsupported-operation",reason:p};let k=await this.getUpstreamBackedDescendantReason(r);if(k)return{ok:!1,errorCode:"unsupported-operation",reason:k};if(r.tag&&r.tag.toLowerCase()===r.tag){let P=Un(s,{kind:"native-tag",tag:r.tag});if(P)return{ok:!1,errorCode:"unsupported-operation",reason:P}}if(l)return this.planCrossFileMove(t,n,r,s,i,u,c);let b=ea(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 E=[{order:0,file:r.file,type:"move-node",locator:W(r),targetParentLocator:W(s),placement:u,anchorLocator:c?W(c):void 0,selectionContext:St(s)}];return this.buildPlan(t,n,E,i)}planCrossFileMove(t,n,r,i,o,s,a){let l=[],u=0,c=this.graph.getFileContent(r.file),d=fi(this.graph,r)??`<${r.component} />`,p=Hs(c,r);if(!p.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:p.reason??"Cannot move subtree across files"};if(l.push({order:u++,file:r.file,type:"remove-node",locator:W(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let k=r.tag??r.component,E={moduleSpecifier:gi(i.file,r.importedFrom),imports:r.exportName==="default"?[{kind:"default",local:k}]:[{kind:"named",imported:r.exportName,local:k===r.exportName?void 0:k}]};l.push({order:u++,file:i.file,type:"add-import",moduleSpecifier:E.moduleSpecifier,imports:E.imports}),l.push({order:u++,file:i.file,type:"insert-child",parentLocator:W(i),node:{jsx:d},placement:s,anchorLocator:a?W(a):void 0,selectionContext:St(i)})}else l.push({order:u++,file:i.file,type:"insert-child",parentLocator:W(i),node:{jsx:d},placement:s,anchorLocator:a?W(a):void 0,selectionContext:St(i)});let h=this.buildRemoveComponentImportStep(r,c);return h&&l.push({...h,order:u++}),this.buildPlan(t,n,l,o)}buildPlan(t,n,r,i){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:q(this.graph.getFileContent(a))}));return{ok:!0,plan:{operationId:t,kind:n.kind,target:n.target,documentVersion:n.documentVersion,steps:r,preSnapshots:s,validatedCapability:i}}}};import Gt from"node:path";import*as Xa from"@babel/parser";import Fi from"@babel/traverse";import*as x from"@babel/types";var Et=typeof Fi=="function"?Fi:Fi.default;function La(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 Wa(e){let{file:t,source:n,segment:r,readFile:i,exists:o}=e,s=e.fileCache??new Map,a=Bi(s,t,n);if(!a)return null;let l=_i(a,r.sourceRange);if(!l)return null;let u=r.source??await Ee({expression:l.node,scope:l.scope,source:n,currentFile:t,readFile:i,exists:o,fileCache:s,visited:new Set});if(!u){let h=await zi({currentFile:t,expressionPath:l,readFile:i,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:new Set});if(!h)return null;if(h.kind==="external")return{kind:"external-entry",file:h.file,sourceType:h.sourceType,sourceId:h.sourceId,adapterId:h.adapterId,displayExpression:h.displayPath};let k={kind:"value",root:h.root,path:h.path.length>0?h.path:[]};return{kind:"value-binding",file:h.file,locator:k,root:h.root,path:h.path,displayExpression:h.displayExpression??Zt(l.node,n),sourceKind:h.sourceKind,...h.collectionIndexMap?{collectionIndexMap:h.collectionIndexMap}:{},...h.collectionPathMap?{collectionPathMap:h.collectionPathMap}:{}}}let c=new Set,d=await Ap({currentFile:t,expressionPath:l,segment:{...r,source:u},readFile:i,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:c});if(!d)return null;if(d.kind==="external")return{kind:"external-entry",file:d.file,sourceType:d.sourceType,sourceId:d.sourceId,adapterId:d.adapterId,displayExpression:d.displayPath};let p={kind:"value",root:d.root,path:d.path.length>0?d.path:[]};return{kind:"value-binding",file:d.file,locator:p,root:d.root,path:d.path,displayExpression:d.displayExpression??u.expression,sourceKind:d.sourceKind,...d.collectionIndexMap?{collectionIndexMap:d.collectionIndexMap}:{},...d.collectionPathMap?{collectionPathMap:d.collectionPathMap}:{}}}async function Ua(e){let{file:t,source:n,readFile:r,exists:i}=e,o=e.fileCache??new Map,s=Bi(o,t,n);if(!s)return null;let a=e.expression!==void 0?(e.sourceRange?Ya(s,n,e.expression,e.sourceRange):null)??Ji(s,n,e.expression):e.sourceRange?_i(s,e.sourceRange):null;if(!a)return null;let l=sp(a),u=new Set,c=e.sourceInfo??await Ee({expression:l.node,scope:l.scope,source:n,currentFile:t,readFile:r,exists:i,fileCache:o,visited:u}),d=c?await de({currentFile:t,expressionPath:l,sourceInfo:c,readFile:r,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:o,visited:u}):await Xp({currentFile:t,expressionPath:l,readFile:r,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:o,visited:u});return op(d,e.expression??Zt(l.node,n))}async function $i(e){let{file:t,source:n,readFile:r,exists:i}=e,o=e.fileCache??new Map,s=Bi(o,t,n);if(!s)return ue("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?ap({file:t,source:n,ast:s,segment:e.target.segment,readFile:r,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:o,visited:a}):lp({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:i,graph:e.graph,fileCache:o,visited:a})}function za(e){try{return Xa.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Bi(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let i=za(n);return e.set(t,{source:n,ast:i}),i}function _i(e,t){let n=null,r=-1;return Et(e,{Expression(i){let o=i.node.loc;if(!o||!Ki(o,t))return;let s=(i.node.end??0)-(i.node.start??0);s>=r&&(n=i,r=s)}}),n}function rp(e,t){let n=null,r=Number.POSITIVE_INFINITY;return Et(e,{Expression(i){if(!ip(i.node.loc,t))return;let o=(i.node.end??0)-(i.node.start??0);o<=r&&(n=i,r=o)}}),n}function Ha(e,t){let n=null,r=Number.POSITIVE_INFINITY;return Et(e,{JSXElement(i){let o=i.node.loc;if(!o||!Ki(o,t))return;let s=(i.node.end??0)-(i.node.start??0);s<=r&&(n=i,r=s)}}),n}function ip(e,t){return e?e.start.line===t.startLine&&e.start.column===t.startColumn&&e.end.line===t.endLine&&e.end.column===t.endColumn:!1}function Ki(e,t){let n=Oa({line:e.start.line,column:e.start.column},{line:t.startLine,column:t.startColumn}),r=Oa({line:e.end.line,column:e.end.column},{line:t.endLine,column:t.endColumn});return n>=0&&r<=0}function Ga(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 Oa(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 Ee(e){if(x.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!x.isMemberExpression(e.expression))return null;let t=await al(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:Zt(e.expression,e.source),base:t.base,path:t.path}:null}function op(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 sp(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 Zt(e,t){if(t)return Vi(e,t);let n=tm(e);return n?n.path.reduce((r,i)=>i.kind==="property"?`${r}.${i.name}`:`${r}[${i.index}]`,n.base):""}function Vi(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Ji(e,t,n){let r=null,i=Number.POSITIVE_INFINITY;return Et(e,{Expression(o){if(Vi(o.node,t)!==n)return;let s=(o.node.end??0)-(o.node.start??0);s<=i&&(r=o,i=s)}}),r}function Ya(e,t,n,r){let i=null,o=Number.POSITIVE_INFINITY;return Et(e,{Expression(s){if(Vi(s.node,t)!==n)return;let a=s.node.loc;if(!a||!Ki(a,r))return;let l=(s.node.end??0)-(s.node.start??0);l<=o&&(i=s,o=l)}}),i}async function ap(e){let{file:t,source:n,ast:r,segment:i,readFile:o,exists:s,fileCache:a,visited:l}=e,u=_i(r,i.sourceRange),c=i.source??(u?await Ee({expression:u.node,scope:u.scope,source:n,currentFile:t,readFile:o,exists:s,fileCache:a,visited:l}):null);if(!c){if(!u)return cp(t,i.value);let p=await zi({currentFile:t,expressionPath:u,readFile:o,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:l});return p?p.kind==="external"?_a(t,p):Oi(t,Zt(u.node,n),p):up({expression:u.node,scope:u.scope,currentFile:t,source:n,readFile:o,exists:s,fileCache:a,visited:l,functionCallContracts:e.functionCallContracts})}if(!u)return ue("unsupported-expression","Unable to locate text expression for provenance resolution");let d=await de({currentFile:t,expressionPath:u,sourceInfo:c,readFile:o,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:l});if(!d){let p=Li(u.node);if(p)return ue(p.code,p.message);let h=u.scope.getBinding(c.base);if(h?.path.isVariableDeclarator()){let k=Li(h.path.node.init);if(k)return ue(k.code,k.message)}return h?.path.isVariableDeclarator()&&x.isCallExpression(h.path.node.init)?dp("unsupported-expression",tl(h.path.node.init,e.functionCallContracts)):ue("unsupported-expression",`Unable to resolve provenance for expression "${c.expression}"`)}return d.kind==="external"?_a(t,d):Oi(t,c.expression,d)}async function lp(e){let{file:t,source:n,ast:r,candidate:i,readFile:o,exists:s,fileCache:a,visited:l}=e;if(!i.conditionSource)return ue("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${i.conditionExpression}"`);let u=Ji(r,n,i.conditionExpression);if(!u)return ue("conditional-branch-unresolved",`Unable to locate conditional expression "${i.conditionExpression}"`);let c=await de({currentFile:t,expressionPath:u,sourceInfo:i.conditionSource,readFile:o,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:l});if(!c)return ue("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${i.conditionExpression}"`);if(c.kind==="external")return ue("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${i.conditionExpression}"`);let d=Oi(t,i.conditionExpression,c);return d.finalSource?{...d,finalSource:{...d.finalSource,kind:"conditional-branch",displayPath:i.conditionExpression},chain:[...d.chain,{kind:"conditional-branch",file:c.file,displayName:i.conditionExpression,canEditHere:!0}]}:d}function cp(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 up(e){let t=await Qa(e);if(t.length===0)return ue("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(fp(e.expression))return Za(t);if(el(e.expression))return ue("unsupported-expression","i18n helpers require a static message id string");if(x.isMemberExpression(e.expression)&&e.expression.computed&&!x.isNumericLiteral(e.expression.property)&&!x.isStringLiteral(e.expression.property))return ue("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return ue(n.code,n.message)}function ue(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function dp(e,t){return Za([{code:e,message:t}])}function Za(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function fp(e){return x.isCallExpression(e)||x.isConditionalExpression(e)||x.isLogicalExpression(e)||x.isBinaryExpression(e)}function Yt(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 Qa(e){let{expression:t,scope:n,currentFile:r,readFile:i,exists:o,fileCache:s,visited:a,functionCallContracts:l}=e,u=Li(t);if(u)return[u];if(x.isCallExpression(t))return[{code:"unsupported-expression",message:tl(t,l)}];if(x.isMemberExpression(t)&&t.computed){let c=t.property;if(!x.isNumericLiteral(c)&&!x.isStringLiteral(c)){if(!x.isExpression(c))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let p=await Ce(c,n,r,i,o,s,a);if(typeof p!="string"&&!Number.isInteger(p))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}]}}return x.isBinaryExpression(t)?Yt([...await Ai(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):x.isLogicalExpression(t)?Yt([...await Ai(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"}]):x.isConditionalExpression(t)?Yt([...await Ai(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 Li(e){return el(e)?Da("i18n helpers require a static message id string"):xp(e)?Da("CMS helpers require static entry id and field path string arguments"):null}async function Ai(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let i of n)r.push(...await Qa({...t,expression:i}));return r}function pp(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(i=>i.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:[mp(e.sourceType)]}}async function Xi(e){for(let n of bp){if(!ja(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return Ba($a(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(!ja(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return Ba($a(r),e.externalAdapters)}return null}function mp(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function hp(e){return{code:"external-source-readonly",message:e}}function Da(e){return{code:"unsupported-expression",message:e}}function Wi(e){return!e||!x.isCallExpression(e)?null:x.isIdentifier(e.callee)?e.callee.name:x.isMemberExpression(e.callee)&&!e.callee.computed&&x.isIdentifier(e.callee.object)&&x.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function ja(e,t){if(!t||t.length===0)return!0;let n=Wi(e.node);return n?t.includes(n):!1}function $a(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:Yt(e.diagnostics??[])}:{match:e,diagnostics:[]}}function Ba(e,t){let n=pp(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:Yt([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function gp(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!x.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!x.isStringLiteral(n)||!x.isStringLiteral(r))return null;let i=n.value,o=r.value;return{sourceType:"cms-field",sourceId:`${i}:${o}`,file:`cms://${i}/${o.replace(/\./g,"/")}`,displayPath:`${i}.${o}`}}function xp(e){return!!e&&x.isCallExpression(e)&&x.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!x.isStringLiteral(e.arguments[0])||!x.isStringLiteral(e.arguments[1]))}function qa(e){if(!(!e||!x.isCallExpression(e))){if(x.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&x.isStringLiteral(t)?t.value:null}if(x.isMemberExpression(e.callee)&&!e.callee.computed&&x.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&x.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!x.isObjectExpression(t))return null;for(let n of t.properties)if(x.isObjectProperty(n)&&!n.computed&&(x.isIdentifier(n.key)&&n.key.name==="id"||x.isStringLiteral(n.key)&&n.key.value==="id")&&x.isStringLiteral(n.value))return n.value.value;return null}}}function el(e){return qa(e)===null}async function yp(e,t,n){let r=new Set,i=Gt.posix.dirname(e);for(;r.add(i),!(i==="."||i==="/");){let o=Gt.posix.dirname(i);if(o===i){r.add(".");break}i=o}r.add("src"),r.add(".");for(let o of r){let s=o==="."?["locales","messages"]:[Gt.posix.join(o,"locales"),Gt.posix.join(o,"messages")];for(let a of s){let l=Gt.posix.join(a,`${t}.json`);if(await n(l))return l}}return null}async function Sp(e){let t=qa(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await yp(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function kp(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!x.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!x.isExpression(n))return null;let i=await Ce(n,e.expressionPath.scope,e.currentFile,e.readFile,e.exists,e.fileCache,e.visited);if(typeof i!="string"||i.length===0)return null;let o={sourceType:"api-field",sourceId:i,file:`api://${i}`,displayPath:i};return r?{match:o,editMode:"readonly",diagnostics:[hp("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:o}var bp=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>gp(e)},{helperNames:["apiField"],resolve:e=>kp(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>Sp({currentFile:e,expressionPath:t,exists:n})}];function _a(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 Oi(e,t,n){let r={kind:"value",root:n.root,path:n.path.length>0?n.path:[]},i=n.path.some(u=>u.kind==="index"),o=Fp(n),s;n.semanticKind?s=n.semanticKind:o?s="config-entry":n.sourceKind==="repeat-template"?s="repeat-template":n.path.length===0?s=n.sourceKind==="imported-binding"?"imported-binding":"binding":s=i?"array-item":"object-field";let a=n.displayExpression??t,l=[...n.chainPrefix??[]];return n.sourceKind==="binding"?l.push({kind:"binding",file:n.file,displayName:n.root.kind==="binding"?n.root.name:a,canEditHere:!0}):n.sourceKind==="imported-binding"?l.push({kind:"imported-binding",file:n.file,displayName:n.root.kind==="named-export"?n.root.name:"default",canEditHere:!0}):n.sourceKind==="repeat-template"&&l.push({kind:"repeat-template",file:n.file,displayName:t,canEditHere:!0}),n.path.length>0&&n.sourceKind!=="repeat-template"&&l.push({kind:i?"array-item":"object-field",file:n.file,displayName:a,canEditHere:!0}),o&&l.push({kind:"config-entry",file:n.file,displayName:o.displayPath,canEditHere:!0}),{finalSource:{kind:s,file:n.file,locator:r,root:n.root,path:n.path,displayPath:a,externalSource:o?{sourceType:"config-entry",sourceId:o.sourceId}:void 0},chain:l,confidence:n.sourceKind==="repeat-template"?"safe-derived":"exact",editMode:n.editMode??(n.file===e?"direct":"proxy"),diagnostics:n.diagnostics??[]}}var vp=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function Ui(e,t){let n=[...vp,...t??[]];for(let r=n.length-1;r>=0;r-=1){let i=n[r];if(i?.helperName===e)return i}return null}function tl(e,t){let n=e.callee;return x.isIdentifier(n)&&Ui(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 zi(e){let t=await Xi(e);if(t)return t;let n=await nl({...e,expressionPath:e.expressionPath});if(n)return n;if(e.expressionPath.isTemplateLiteral()){let r=e.expressionPath.node.expressions[0],i=e.expressionPath.get("expressions.0");if(e.expressionPath.node.expressions.length===1&&r&&i&&!Array.isArray(i)&&i.isExpression()){let o=await Ee({expression:i.node,scope:i.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(o){let s=await de({...e,expressionPath:i,sourceInfo:o});if(s&&s.kind==="value")return{...s,displayExpression:o.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 Rp(e)}async function nl(e){let t=await ve({...e,allowComposed:!1});return t?.kind==="source"?t.provenance:null}async function ve(e){let t=Ep(e.expressionPath),n=Pp(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 Ee({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 i=await de({currentFile:e.currentFile,expressionPath:t,sourceInfo:r,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return!i||i.kind==="external"?null:{kind:"source",provenance:i}}if(t.isMemberExpression()){let r=await Ee({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 i=await de({currentFile:e.currentFile,expressionPath:t,sourceInfo:r,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return!i||i.kind==="external"?null:{kind:"source",provenance:i}}if(t.isConditionalExpression()){let r=t.get("test"),i=t.get("consequent"),o=t.get("alternate");if(Array.isArray(r)||Array.isArray(i)||Array.isArray(o)||!r.isExpression()||!i.isExpression()||!o.isExpression())return null;let s=await ve({...e,expressionPath:r,allowComposed:!0}),a=await ve({...e,expressionPath:i,allowComposed:!1}),l=await ve({...e,expressionPath:o,allowComposed:!1});return Ni(s,a,l)}if(t.isCallExpression())return Cp({...e,expressionPath:t});if(!e.allowComposed)return null;if(t.isBinaryExpression()){let r=t.get("left"),i=t.get("right");if(Array.isArray(r)||Array.isArray(i)||!r.isExpression()||!i.isExpression())return null;let o=await ve({...e,expressionPath:r,allowComposed:!0}),s=await ve({...e,expressionPath:i,allowComposed:!0});return Ni(o,s)}if(t.isLogicalExpression()){let r=t.get("left"),i=t.get("right");if(Array.isArray(r)||Array.isArray(i)||!r.isExpression()||!i.isExpression())return null;let o=await ve({...e,expressionPath:r,allowComposed:!0}),s=await ve({...e,expressionPath:i,allowComposed:!0});return Ni(o,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:ve({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function Ep(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 Cp(e){let t=Wi(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:ve({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(x.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let i=n.get("object");return Array.isArray(i)||!i.isExpression()?null:ve({...e,expressionPath:i,allowComposed:!1})}}return null}function Ni(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!Ip(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function Ip(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 Pp(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function Rp(e){if(!e.expressionPath.isCallExpression())return null;let t=Wi(e.expressionPath.node);if(!t)return null;let n=Ui(t,e.functionCallContracts);if(!n||n.purity!=="pure")return null;let r=n.sourceArgIndex??0,i=e.expressionPath.get(`arguments.${r}`);return!i||Array.isArray(i)||!i.isExpression()?null:await rl({currentFile:e.currentFile,argumentPath: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})}async function rl(e){let t=await Xi({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 Ee({expression:e.argumentPath.node,scope:e.argumentPath.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(n){let r=await de({currentFile:e.currentFile,expressionPath:e.argumentPath,sourceInfo:n,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return!r||r.kind==="external"?r:{...r,displayExpression:n.expression}}return await zi({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 wp(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!x.isCallExpression(t))return null;let n=t.callee;if(!x.isIdentifier(n))return null;let r=Ui(n.name,e.functionCallContracts);if(!r||r.purity!=="pure")return null;let i=r.sourceArgIndex??0,o=e.binding.path.get("init");if(!o||Array.isArray(o)||!o.isCallExpression())return null;let s=o.get(`arguments.${i}`);return!s||Array.isArray(s)||!s.isExpression()?null:await rl({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 Fp(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 i=Zn(t,e.path);return{sourceId:i,displayPath:i}}async function Ap(e){let t=e.segment.source;return t?de({currentFile:e.currentFile,expressionPath:e.expressionPath,sourceInfo:t,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited}):null}async function de(e){let t=e.sourceInfo,n=il(e.expressionPath,t.base);if(n){let u=await ol({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(!u){let b=Tp(n.callPath,[...n.basePath,...t.path]);return Jt(b)?La(e.currentFile,b.sourceId,b.displayPath):null}let c=nm(u,[...n.basePath,...t.path]),d=u.collectionIndexMap?.[0]??0,p=[...u.pathPrefix??[],{kind:"index",index:d},...n.basePath,...t.path],h=[{kind:"index",index:0},...n.basePath,...t.path];return Fe(u.value,h)===void 0?null:{kind:"value",file:u.file,root:u.root,path:c?.[0]??p,sourceKind:"repeat-template",collectionIndexMap:u.collectionIndexMap,...c?{collectionPathMap:c}:{}}}let r=e.expressionPath.scope.getBinding(t.base);if(!r)return null;let i=Zs(r);if(i){let u=i.expressionPath,c=await Ee({expression:u.node,scope:u.scope,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(c){let d=await de({...e,expressionPath:u,sourceInfo:{...c,expression:Zn(c.expression,t.path),path:[...c.path,...t.path]}});if(d)return d}if(t.path.length===0){let d=await nl({currentFile:e.currentFile,expressionPath:u,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(d)return d}}if(r.kind==="param")return Gp({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 o=await wp({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(o)return o;let s=_n(r,t.path);if(Jt(s))return La(e.currentFile,s.sourceId,s.displayPath);let a=await vt({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:Fe(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 il(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 i=r.node.params[0],o=ye(i,t);if(!o)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!Np(s,r)?null:{callPath:s,basePath:o}}function Np(e,t){let n=e.node.callee;return!x.isMemberExpression(n)||!x.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}async function ol(e){let{currentFile:t,callPath:n,readFile:r,exists:i,fileCache:o,visited:s}=e,a=n.node.callee;if(!x.isMemberExpression(a)||!x.isIdentifier(a.property)||a.property.name!=="map")return null;let l=n.get("callee");if(!l.isMemberExpression())return null;let u=l.get("object");if(Array.isArray(u)||!u.isExpression())return null;let c=await Qt({currentFile:t,expressionPath:u,readFile:r,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:o,visited:s});return!c||!Array.isArray(c.value)||c.value.length===0?null:c}function Tp(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:Vn(r,t)}async function Qt(e){let{currentFile:t,expressionPath:n,readFile:r,exists:i,fileCache:o,visited:s}=e;if(n.isIdentifier()){let a=n.scope.getBinding(n.node.name);if(!a)return null;let l=await vt({currentFile:t,binding:a,readFile:r,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:o,visited:s});return l?.kind==="static"?l:null}if(n.isCallExpression())return sl({currentFile:t,callPath:n,readFile:r,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:o,visited:s});if(n.isTSAsExpression()||n.isTSSatisfiesExpression()||n.isTSNonNullExpression()){let a=n.get("expression");if(!Array.isArray(a)&&a.isExpression())return Qt({...e,expressionPath:a})}if(n.isArrayExpression()){let a=Ga(n.node);if(!a)return null;let l=await Ce(n.node,n.scope,t,r,i,o,s);return Array.isArray(l)?{kind:"static",file:t,root:{kind:"expression",sourceRange:a},value:l,sourceKind:"binding"}:null}if(n.isMemberExpression()){let a=await Ee({expression:n.node,scope:n.scope,currentFile:t,readFile:r,exists:i,fileCache:o,visited:s});if(!a)return null;let l=await de({currentFile:t,expressionPath:n,sourceInfo:a,readFile:r,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:o,visited:s});if(!l||l.kind==="external")return null;let u=await Mp({currentFile:t,expressionPath:n,provenance:l,readFile:r,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:o,visited:s});if(!u||u.kind!=="static")return null;if(l.collectionPathMap?.length){let d=rm(u.value,l.collectionPathMap);if(d)return{kind:"static",file:l.file,root:l.root,value:d.value,sourceKind:l.sourceKind,collectionPathMap:d.collectionPathMap}}let c=Fe(u.value,l.path);return Array.isArray(c)?{kind:"static",file:l.file,root:l.root,value:c,sourceKind:l.sourceKind,pathPrefix:l.path,collectionIndexMap:l.collectionIndexMap,collectionPathMap:l.collectionPathMap}:null}return null}async function Mp(e){let{provenance:t}=e;if(t.root.kind==="binding"){let o=e.expressionPath.scope.getBinding(t.root.name);return o?await vt({currentFile:e.currentFile,binding: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}):null}if(t.root.kind!=="expression")return null;let n=await qt(t.file,e.readFile,e.fileCache);if(!n.ast)return null;let r=rp(n.ast,t.root.sourceRange);if(!r)return null;let i=await Ce(r.node,r.scope,t.file,e.readFile,e.exists,e.fileCache,e.visited);return i===void 0?null:{kind:"static",file:t.file,root:t.root,value:i,sourceKind:t.sourceKind}}async function sl(e){return await Lp(e)??await Op(e)??await Dp(e)}async function Lp(e){let{callPath:t}=e,n=t.node.callee;if(!x.isMemberExpression(n)||!x.isIdentifier(n.property)||n.property.name!=="filter")return null;let r=t.get("callee");if(!r.isMemberExpression())return null;let i=r.get("object");if(Array.isArray(i)||!i.isExpression())return null;let o=await Qt({currentFile:e.currentFile,expressionPath: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});if(!o||!Array.isArray(o.value))return null;let[s]=t.node.arguments;if(!x.isArrowFunctionExpression(s)&&!x.isFunctionExpression(s))return null;let a=s.params[0];if(!x.isIdentifier(a))return null;let l=jp(s);if(!l)return null;let u=[],c=[],d=[];for(let[p,h]of o.value.entries()){let k=$p(l,a.name,h);if(typeof k!="boolean")return null;if(k){u.push(h),c.push(o.collectionIndexMap?.[p]??p);let b=o.collectionPathMap?.[p];b&&d.push(b)}}return{...o,value:u,pathPrefix:o.pathPrefix,collectionIndexMap:c,...d.length>0?{collectionPathMap:d}:{}}}async function Op(e){let{callPath:t}=e,n=t.node.callee;if(!x.isMemberExpression(n)||!x.isIdentifier(n.property)||n.property.name!=="slice")return null;let r=t.get("callee");if(!r.isMemberExpression())return null;let i=r.get("object");if(Array.isArray(i)||!i.isExpression())return null;let o=await Qt({currentFile:e.currentFile,expressionPath: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});if(!o||!Array.isArray(o.value))return null;let[s,a]=t.node.arguments,l=Ka(s,0),u=Ka(a,o.value.length);if(l===null||u===null)return null;let c=Math.max(0,l<0?o.value.length+l:l),d=Math.max(0,u<0?o.value.length+u:u),p=o.value.map((k,b)=>o.collectionIndexMap?.[b]??b).slice(c,d),h=o.collectionPathMap?.slice(c,d);return{...o,value:o.value.slice(c,d),pathPrefix:o.pathPrefix,collectionIndexMap:p,...h?{collectionPathMap:h}:{}}}function Ka(e,t){return e?x.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}async function Dp(e){let{callPath:t}=e,n=t.node.callee;if(!x.isMemberExpression(n)||!x.isIdentifier(n.property)||n.property.name!=="sort"&&n.property.name!=="toSorted")return null;let r=t.get("callee");if(!r.isMemberExpression())return null;let i=r.get("object");if(Array.isArray(i)||!i.isExpression())return null;let o=await Qt({currentFile:e.currentFile,expressionPath: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});if(!o||!Array.isArray(o.value))return null;let[s]=t.node.arguments;if(!x.isArrowFunctionExpression(s)&&!x.isFunctionExpression(s))return null;let[a,l]=s.params;if(!x.isIdentifier(a)||!x.isIdentifier(l))return null;let u=o.value.map((d,p)=>({value:d,sourceIndex:o.collectionIndexMap?.[p]??p,originalIndex:p})),c=[...u];for(let d of u)for(let p of u)if(Va(s,a.name,l.name,d.value,p.value)===void 0)return null;return c.sort((d,p)=>{let h=Va(s,a.name,l.name,d.value,p.value)??0;return h===0?d.originalIndex-p.originalIndex:h}),{...o,value:c.map(d=>d.value),pathPrefix:o.pathPrefix,collectionIndexMap:c.map(d=>d.sourceIndex),...o.collectionPathMap?{collectionPathMap:c.map(d=>o.collectionPathMap?.[d.originalIndex]).filter(d=>!!d)}:{}}}function Va(e,t,n,r,i){let o=x.isExpression(e.body)?e.body:e.body.body.find(a=>x.isReturnStatement(a))?.argument;if(!o||!x.isExpression(o))return;let s=Di(o,t,n,r,i);return typeof s=="number"?s:void 0}function Di(e,t,n,r,i){if(x.isNumericLiteral(e)||x.isStringLiteral(e)||x.isBooleanLiteral(e))return e.value;if(x.isIdentifier(e))return e.name===t?r:e.name===n?i:void 0;if(x.isMemberExpression(e)){let o=ji(e,t);if(o)return Fe(r,o);let s=ji(e,n);return s?Fe(i,s):void 0}if(x.isBinaryExpression(e)&&e.operator==="-"){let o=x.isExpression(e.left)?Di(e.left,t,n,r,i):void 0,s=x.isExpression(e.right)?Di(e.right,t,n,r,i):void 0;return typeof o=="number"&&typeof s=="number"?o-s:void 0}}function jp(e){if(x.isExpression(e.body))return e.body;for(let t of e.body.body)if(x.isReturnStatement(t)&&t.argument&&x.isExpression(t.argument))return t.argument;return null}function $p(e,t,n){let r=ot(e,t,n);return typeof r=="boolean"?r:void 0}function ot(e,t,n){if(x.isStringLiteral(e)||x.isNumericLiteral(e)||x.isBooleanLiteral(e))return e.value;if(x.isNullLiteral(e))return null;if(x.isIdentifier(e))return e.name===t?n:void 0;if(x.isMemberExpression(e)){let r=ji(e,t);return r?Fe(n,r):void 0}if(x.isUnaryExpression(e)&&e.operator==="!"){let r=ot(e.argument,t,n);return r===void 0?void 0:!r}if(x.isLogicalExpression(e)){let r=ot(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&ot(e.right,t,n);if(e.operator==="||")return r||ot(e.right,t,n)}if(x.isBinaryExpression(e)){let r=x.isExpression(e.left)?ot(e.left,t,n):void 0,i=x.isExpression(e.right)?ot(e.right,t,n):void 0;if(r===void 0||i===void 0)return;switch(e.operator){case"===":return r===i;case"!==":return r!==i;case"==":return r==i;case"!=":return r!=i;default:return}}}function ji(e,t){let n=[],r=e;for(;x.isMemberExpression(r);){if(r.computed)if(x.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(x.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!x.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!x.isIdentifier(r)||r.name!==t?null:n}async function vt(e){let{currentFile:t,binding:n,readFile:r,exists:i,fileCache:o,visited:s}=e,a=`${t}::${n.kind}::${n.identifier.name}`;if(s.has(a))return null;s.add(a);try{let l=await Bp({currentFile:t,binding:n,readFile:r,exists:i,fileCache:o,visited:s});if(l)return l;if(n.path.isImportSpecifier()||n.path.isImportDefaultSpecifier())return await Qp({currentFile:t,binding:n,readFile:r,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,fileCache:o,visited:s});if(n.kind==="param")return null;if(n.path.isVariableDeclarator()){let u=n.path.node.init;if(!u||!x.isExpression(u))return null;let c=n.path.get("init");if(c&&!Array.isArray(c)&&c.isExpression()){let p=await Xi({currentFile:t,expressionPath:c,readFile:r,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:o,visited:s});if(p)return p;if(c.isCallExpression()){let h=await sl({currentFile:t,callPath:c,readFile:r,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:o,visited:s});if(h)return h}}let d=await Ce(u,n.path.scope,t,r,i,o,s);return d===void 0?null:{kind:"static",file:t,root:{kind:"binding",name:n.identifier.name},value:d,sourceKind:"binding"}}if(n.path.isIdentifier()&&n.path.parentPath?.isExportDefaultDeclaration()){let u=n.path.parentPath.node.declaration;if(!x.isExpression(u))return null;let c=await Ce(u,n.path.scope,t,r,i,o,s);return c===void 0?null:{kind:"static",file:t,root:{kind:"binding",name:n.identifier.name},value:c,sourceKind:"binding"}}return null}finally{s.delete(a)}}async function Bp(e){let{currentFile:t,binding:n,readFile:r,exists:i,fileCache:o,visited:s}=e;if(!n.path.isVariableDeclarator()||!n.path.get("id").isArrayPattern())return null;let a=n.path,l=a.node.init;if(!l||!x.isCallExpression(l))return null;let u=_p(l);if(!u||!x.isArrayPattern(a.node.id)||a.node.id.elements.findIndex(k=>x.isIdentifier(k)&&k.name===n.identifier.name)!==0)return null;let d=u==="useReducer"?1:0,p=l.arguments[d];if(!p||!x.isExpression(p))return null;let h=await Ce(p,a.scope,t,r,i,o,s);return h===void 0?null:{kind:"static",file:t,root:{kind:"hook-state",name:n.identifier.name,hook:u},value:h,sourceKind:"binding"}}function _p(e){return x.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:x.isMemberExpression(e.callee)&&x.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function Kp(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()||!x.isIdentifier(n.node.id))return null;let r=n.node.id.name,i=n.parentPath,o=i?.parentPath?.isExportDefaultDeclaration()?"default":(i?.parentPath?.isExportNamedDeclaration(),r);return{componentName:r,exportName:o}}function Vp(e,t){let n=Kp(e.path);if(!n)return null;let r=yt(e,t);return r?{...n,...r}:null}function Zn(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function Jp(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}async function Xp(e){let t=Up(e.expressionPath.node);if(!t||!zp(t.segments))return null;let n=await de({currentFile:e.currentFile,expressionPath:e.expressionPath,sourceInfo:{kind:"identifier",expression:t.base,base:t.base,path:[]},readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(!n||n.kind==="external")return n;let r=await Wp({...e,rootPath:n.path,segments:t.segments});return r?{...n,path:r.collectionPathMap[0]??n.path,sourceKind:"repeat-template",displayExpression:Zt(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:r.collectionPathMap}:null}async function Wp(e){let t=null,n,r=[];for(let o of e.segments){if(o.kind!=="dynamic")continue;let s=await Ee({expression:o.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=il(e.expressionPath,s.base);if(!a)return null;let l=await ol({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(!l||!Array.isArray(l.value))return null;let u=l.value.map((c,d)=>{let p=Fe(l.value,[{kind:"index",index:d},...a.basePath,...s.path]);return Hp(p)});if(u.some(c=>c===null)||t!==null&&t!==u.length)return null;t=u.length,n??=l.collectionIndexMap,r.push(u)}if(t===null||t===0)return null;let i=[];for(let o=0;o<t;o+=1){let s=[...e.rootPath],a=0;for(let l of e.segments){if(l.kind==="dynamic"){let u=r[a]?.[o];if(!u)return null;s.push(u),a+=1;continue}s.push({...l})}i.push(s)}return{...n?{collectionIndexMap:n}:{},collectionPathMap:i}}function Up(e){let t=[],n=e;for(;x.isMemberExpression(n)||x.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(x.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(x.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(x.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(x.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return x.isIdentifier(n)?{base:n.name,segments:t}:null}function zp(e){return e.some(t=>t.kind==="dynamic")}function Hp(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}async function Gp(e){let t=Vp(e.binding,e.sourceInfo);if(!t||!e.graph)return null;let n=[...e.graph.elements.values()].filter(u=>Jp(u,e.currentFile,t.componentName,t.exportName));if(n.length!==1)return null;let r=n[0],i=r.attributes?.find(u=>u.name===t.propName);if(i&&!i.source){let u=await Yp({caller:r,propName:t.propName,remainingPath:t.remainingPath,readFile:e.readFile,fileCache:e.fileCache});if(u)return Ti(u,{componentName:t.componentName,propName:t.propName,file:r.sourceFile})}if(!i?.source){let u=await Zp({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(u)return Ti(u,{componentName:t.componentName,propName:t.propName,file:r.sourceFile});let c=qs(e.binding,t.componentName,t.propName);if(!c||c.propName!==t.propName)return null;let d=await Ce(c.expressionPath.node,c.expressionPath.scope,e.currentFile,e.readFile,e.exists,e.fileCache,e.visited);if(d===void 0)return null;let p=t.remainingPath;return p.length>0&&Fe(d,p)===void 0?null:{kind:"value",file:e.currentFile,root:{kind:"binding",name:t.propName},path:p,sourceKind:"binding",semanticKind:"component-prop",displayExpression:c.displayPath,chainPrefix:[{kind:"component-prop",file:e.currentFile,displayName:c.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let o=await qt(r.sourceFile,e.readFile,e.fileCache);if(!o.ast)return null;let s=Ya(o.ast,o.source,i.source.expression,i.sourceRange)??Ji(o.ast,o.source,i.source.expression);if(!s)return null;let a={...i.source,expression:Zn(i.source.expression,t.remainingPath),path:[...i.source.path,...t.remainingPath]},l=await de({currentFile:r.sourceFile,expressionPath:s,sourceInfo:a,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return l?Ti(l.kind==="external"?l:{...l,displayExpression:a.expression},{componentName:t.componentName,propName:t.propName,file:r.sourceFile}):null}async function Yp(e){let t=await qt(e.caller.sourceFile,e.readFile,e.fileCache);if(!t.ast)return null;let n=Ha(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 i=r.get("value"),o=i.isStringLiteral()?i:i.isJSXExpressionContainer()?i.get("expression"):null;if(!o?.isExpression())return null;let s=Ga(o.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 Zp(e){let t=await qt(e.caller.sourceFile,e.readFile,e.fileCache);if(!t.ast)return null;let n=Ha(t.ast,e.caller.sourceRange);if(!n)return null;let r=n.get("openingElement");for(let i of r.get("attributes")){if(!i.isJSXSpreadAttribute())continue;let o=i.get("argument");if(!o.isExpression())continue;let s=await Ee({expression:o.node,scope:o.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],l={...s,expression:Zn(s.expression,a),path:[...s.path,...a]},u=await de({currentFile:e.caller.sourceFile,expressionPath:o,sourceInfo: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(u)return u.kind==="external"?u:{...u,displayExpression:l.expression}}return null}function Ti(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 Qp(e){let{currentFile:t,binding:n,readFile:r,exists:i,fileCache:o,visited:s}=e,a=n.path.parentPath;if(!a||!a.isImportDeclaration())return null;let l=a.node.source.value;if(typeof l!="string")return null;let u=await Tt(t,l,i);if(!u)return null;if(n.path.isImportDefaultSpecifier()){let h=await Ja({file:u,exportName:"default",readFile:r,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:o,visited:s});return!h||h.kind!=="static"?null:{kind:"static",file:u,root:{kind:"default-export"},value:h.value,sourceKind:"imported-binding"}}if(!n.path.isImportSpecifier())return null;let c=n.path.node.imported,d=x.isIdentifier(c)?c.name:c.value,p=await Ja({file:u,exportName:d,readFile:r,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:o,visited:s});return p?p.kind==="external"?p:{kind:"static",file:u,root:{kind:"named-export",name:d},value:p.value,sourceKind:"imported-binding"}:null}async function Ja(e){let{file:t,exportName:n,readFile:r,exists:i,fileCache:o,visited:s}=e,a=await qt(t,r,o);if(!a.ast)return;let l=em(a.ast,n);if(!l||l.kind==="default-expression")return;let u=l.name;if(!u)return;let c=qp(a.ast).getBinding(u);return c?await vt({currentFile:t,binding:c,readFile:r,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:o,visited:s})??void 0:void 0}function qp(e){let t=null;if(Et(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}function em(e,t){for(let n of e.program.body){if(t==="default"&&x.isExportDefaultDeclaration(n))return x.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:(x.isFunctionDeclaration(n.declaration)||x.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if(x.isExportNamedDeclaration(n)){if(n.declaration){if(x.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if(x.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if((x.isFunctionDeclaration(n.declaration)||x.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if((x.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&x.isExportSpecifier(r))return{kind:"local-binding",name:r.local.name}}}return null}async function Ce(e,t,n,r,i,o,s){if(x.isStringLiteral(e)||x.isNumericLiteral(e)||x.isBooleanLiteral(e))return e.value;if(x.isNullLiteral(e))return null;if(x.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(x.isTSAsExpression(e)||x.isTSSatisfiesExpression(e)||x.isTSNonNullExpression(e))return await Ce(e.expression,t,n,r,i,o,s);if(x.isIdentifier(e)){let a=t.getBinding(e.name);if(!a)return;let l=await vt({currentFile:n,binding:a,readFile:r,exists:i,fileCache:o,visited:s});return l?.kind==="static"?l.value:void 0}if(x.isArrayExpression(e)){let a=[];for(let l of e.elements){if(!l||x.isSpreadElement(l))return;let u=await Mi(l,t,n,r,i,o,s);if(u===void 0)return;a.push(u)}return a}if(x.isObjectExpression(e)){let a={};for(let l of e.properties){if(!x.isObjectProperty(l)||l.computed)return;let u=null;if(x.isIdentifier(l.key)?u=l.key.name:x.isStringLiteral(l.key)&&(u=l.key.value),!u)return;if(l.shorthand){if(!x.isIdentifier(l.value))return;let d=await Mi(l.value,t,n,r,i,o,s);if(d===void 0)return;a[u]=d;continue}if(!x.isExpression(l.value))return;let c=await Mi(l.value,t,n,r,i,o,s);c!==void 0&&(a[u]=c)}return a}if(x.isMemberExpression(e)){let a=await al(e,t,n,r,i,o,s);if(!a)return;let l=t.getBinding(a.base);if(!l)return;let u=await vt({currentFile:n,binding:l,readFile:r,exists:i,fileCache:o,visited:s});return!u||u.kind!=="static"?void 0:Fe(u.value,a.path)}}async function Mi(e,t,n,r,i,o,s){if(!x.isSpreadElement(e))return await Ce(e,t,n,r,i,o,s)}async function al(e,t,n,r,i,o,s){if(x.isIdentifier(e))return{base:e.name,path:[]};if(!x.isMemberExpression(e))return null;let a=[],l=e;for(;x.isMemberExpression(l);){if(l.computed){let u=l.property;if(x.isNumericLiteral(u))a.unshift({kind:"index",index:u.value});else if(x.isStringLiteral(u))a.unshift({kind:"property",name:u.value});else{let c=x.isExpression(u)?await Ce(u,t,n,r,i,o,s):void 0;if(typeof c=="string")a.unshift({kind:"property",name:c});else if(Number.isInteger(c))a.unshift({kind:"index",index:c});else return null}}else{if(!x.isIdentifier(l.property))return null;a.unshift({kind:"property",name:l.property.name})}l=l.object}return x.isIdentifier(l)?{base:l.name,path:a}:null}function tm(e){if(x.isIdentifier(e))return{base:e.name,path:[]};if(!x.isMemberExpression(e))return null;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))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return x.isIdentifier(n)?{base:n.name,path:t}:null}function Fe(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 nm(e,t){if(!Array.isArray(e.value))return null;let n=e.collectionPathMap?.length?e.collectionPathMap:e.value.map((r,i)=>[...e.pathPrefix??[],{kind:"index",index:e.collectionIndexMap?.[i]??i}]);return n.length>0?n.map(r=>[...r,...t]):null}function rm(e,t){let n=[],r=[];for(let i of t){let o=Fe(e,i);if(!Array.isArray(o))return null;for(let[s,a]of o.entries())n.push(a),r.push([...i,{kind:"index",index:s}])}return{value:n,collectionPathMap:r}}async function qt(e,t,n){let r=n.get(e);if(r)return r;let i=await t(e),o=za(i),s={source:i,ast:o};return n.set(e,s),s}var im=50,om=8*1024*1024;function cl(e,t={}){let n=[],r=[],i=t.externalAdapters??[],o=Math.max(0,t.maxUndoEntries??im),s=Math.max(0,t.maxUndoBytes??om);return{execute:a,executeFilePlan:l,undo:u,redo:c};async function a(C){let j=[...C.steps].sort((Y,he)=>Y.order-he.order),F=j.filter(Y=>Y.type!=="invoke-external-adapter"),A=j.filter(Y=>Y.type==="invoke-external-adapter"),z=new Set(F.map(Y=>Y.file));if(F.length>0&&A.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(F.length===0)return b(C,A);let Z=await P(z),te=new Map;for(let Y of Z)te.set(Y.file,Y.exists===!1?"":Y.content);let se;for(let Y of F){let he=te.get(Y.file)??"",Pe=am(Y,he);if(!Pe.ok)return{ok:!1,operationId:C.operationId,errorCode:Pe.errorCode,reason:Pe.reason,rolledBack:!1};te.set(Y.file,Pe.source),Pe.selectionRef&&(se=Pe.selectionRef)}let le=await I([...te].map(([Y,he])=>({file:Y,content:he,exists:!0,version:0,sha256:q(he)})),Z);return le.ok===!1?{ok:!1,operationId:C.operationId,errorCode:le.rolledBack?"writeback-failed":"rollback-failed",reason:le.reason,rolledBack:le.rolledBack}:(n.push({operationId:C.operationId,preSnapshots:Z,postSnapshots:le.snapshots,plan:C}),d(),r.length=0,{ok:!0,operationId:C.operationId,kind:C.kind,target:C.target,resultVersion:Math.max(...le.snapshots.map(Y=>Y.version)),affectedFiles:[...z],...se?{selectionRef:se}:{}})}async function l(C){let j=new Set(C.edits.map(te=>te.file)),F=await P(j),A=E(C,F);if(A)return{ok:!1,operationId:C.operationId,errorCode:"stale-version",reason:A.reason,affectedFiles:[A.file],rolledBack:!1};let z=C.edits.map(te=>te.operation==="delete"?{file:te.file,content:"",exists:!1,version:0}:{file:te.file,content:te.content,exists:!0,version:0,sha256:q(te.content)}),Z=await I(z,F);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:F,postSnapshots:Z.snapshots,plan:{operationId:C.operationId,kind:C.kind,target:C.target,documentVersion:C.documentVersion,steps:[],preSnapshots:F}}),d(),r.length=0,{ok:!0,operationId:C.operationId,kind:C.kind,target:C.target,resultVersion:Math.max(...Z.snapshots.map(te=>te.version)),affectedFiles:[...j]})}async function u(){let C=n.at(-1);if(!C)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let j=await I(C.preSnapshots,C.postSnapshots);return j.ok===!1?{ok:!1,operationId:C.operationId,errorCode:j.rolledBack?"writeback-failed":"rollback-failed",reason:j.reason,rolledBack:j.rolledBack}:(n.pop(),r.push(C),{ok:!0,operationId:C.operationId,kind:C.plan.kind,target:C.plan.target,resultVersion:Math.max(...j.snapshots.map(F=>F.version)),affectedFiles:C.preSnapshots.map(F=>F.file)})}async function c(){let C=r.at(-1);if(!C)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let j=await I(C.postSnapshots,C.preSnapshots);return j.ok===!1?{ok:!1,operationId:C.operationId,errorCode:j.rolledBack?"writeback-failed":"rollback-failed",reason:j.reason,rolledBack:j.rolledBack}:(r.pop(),n.push(C),d(),{ok:!0,operationId:C.operationId,kind:C.plan.kind,target:C.plan.target,resultVersion:Math.max(...j.snapshots.map(F=>F.version)),affectedFiles:C.postSnapshots.map(F=>F.file)})}function d(){for(;n.length>o;)n.shift();for(;n.length>0&&p()>s;)n.shift()}function p(){return n.reduce((C,j)=>C+h(j),0)}function h(C){return k(C.preSnapshots)+k(C.postSnapshots)}function k(C){return C.reduce((j,F)=>j+F.file.length+F.content.length,0)}async function b(C,j){let F=[];for(let A of j){let z=A.capability??"write-text",Z=i.find(se=>se.sourceType===A.sourceType&&(A.adapterId===void 0||se.adapterId===A.adapterId)&&(se.capabilities===void 0||se.capabilities.includes(z)));if(!Z)return{ok:!1,operationId:C.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${A.sourceType}`,rolledBack:!1};let te=await Z.execute(A);if(!te.ok)return{ok:!1,operationId:C.operationId,errorCode:"writeback-failed",reason:te.reason??`External adapter failed for ${A.sourceType}`,rolledBack:!1};F.push(A.file)}return{ok:!0,operationId:C.operationId,kind:C.kind,target:C.target,resultVersion:0,affectedFiles:F}}function E(C,j){if(C.conflictPolicy!=="compare-and-swap")return null;let F=new Map(j.map(A=>[A.file,A]));for(let A of C.edits){if(A.baseContentHash===void 0)return{file:A.file,reason:`Source file ${A.file} is missing baseContentHash. Reopen the file before saving.`};let z=F.get(A.file),Z=A.baseContentHash;if(Z===null){if(z?.exists!==!1)return{file:A.file,reason:`Source file ${A.file} was created or changed before save.`};continue}if(!Z)return{file:A.file,reason:`Source file ${A.file} is missing baseContentHash. Reopen the file before saving.`};if(z?.exists===!1||z?.sha256!==Z)return{file:A.file,reason:`Source file ${A.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function P(C){let j=[];for(let F of C)j.push(await R(F));return j}async function R(C){if(!await e.exists(C))return{file:C,content:"",version:0,exists:!1};let F=Math.max(1,e.getVersion(C)),A=await e.readFile(C);return{file:C,content:A,version:F,exists:!0,sha256:q(A)}}async function I(C,j){let F=[];try{for(let A of C){await B(A);let z=e.bumpVersion(A.file);F.push(A.file),A.version=z}}catch(A){let z=await G(j.filter(Z=>F.includes(Z.file)));return z.ok===!1?{ok:!1,reason:`Writeback failed, then rollback failed for ${z.failedFiles.join(", ")}: ${ll(A)}`,rolledBack:!1}:{ok:!1,reason:`Writeback failed and committed files were restored: ${ll(A)}`,rolledBack:!0}}return{ok:!0,snapshots:C.map(sm)}}async function B(C){if(C.exists===!1){await e.deleteFile(C.file);return}await e.writeFile(C.file,C.content)}async function G(C){let j=[];for(let F of C)try{await B(F),e.bumpVersion(F.file)}catch{j.push(F.file)}return j.length===0?{ok:!0}:{ok:!1,failedFiles:j}}}function sm(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:q(e.content)}:{}}}function ll(e){return e instanceof Error?e.message:String(e)}function am(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 ce(Ln({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return ce(On({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return ce(wn({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return ce(Fn({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return ce(Rn({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return ce(Kt({source:t,locator:e.locator,next:e.value}));case"update-array-item":return ce(Kt({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return ce(Dn({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return ce(An({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return ce(jn({source:t,locator:e.locator,index:e.index}));case"move-array-item":return ce($n({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return ce(Nn({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return ce(Tn({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 lm(e,t);case"set-props":{let n=e;return ce(Mn({source:t,locator:n.locator,props:n.props}))}default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function lm(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!ps(n.newAttrRaw))return{ok:!1,reason:"newAttrRaw must be a valid JSX className attribute.",errorCode:"invalid-params"};if(!(n.oldAttrRange!==null&&n.oldAttrRaw!==null)&&n.expectedVersion.contentHash!==q(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:fs({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function ce(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 ul(){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 cm}from"node:crypto";import Qn from"node:fs/promises";import Hi from"node:path";var um={async mkdir(e,t){await Qn.mkdir(e,t)},async writeFile(e,t,n){await Qn.writeFile(e,t,n)},async rename(e,t){await Qn.rename(e,t)},async rm(e,t){await Qn.rm(e,t)}};async function qn(e,t,n=um){let r=Hi.dirname(e),i=Hi.basename(e),o=Hi.join(r,`.${i}.${process.pid}.${cm()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(o,t,"utf8"),await n.rename(o,e),s=!0}finally{if(!s)try{await n.rm(o,{force:!0})}catch{}}}var gm=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,xm=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],dl=32,ym=256;function Sm(){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 qn(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 fl(e,t){return{routeId:e,entryFile:t,graph:null,topology:null,capabilities:null,document:null,documentIndex:null,dependencyFiles:new Set([t]),detailProjections:null,fileVersions:new Map,styleContext:null}}function km(e){let t=new Map,n=new Map,r=new Map;for(let i of e.entries){t.set(i.key,i);let o=Ie(i.key)??i.key;if(o===i.key)continue;let s=n.get(o)??0;r.set(i.key,s),n.set(o,s+1)}return{entriesByKey:t,repeatOccurrenceIndexByKey:r}}var bm=/\.(?:[cm]?[jt]sx?)$/i,vm=/\.json$/i,Em=/\.(?:css|scss|sass)$/i,Cm=/\.mdx$/i;function Im(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(i=>i.kind==="property"?i.name:i.index)}}function Pm(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function Rm(e,t){if(!e)return;let n=[...t];for(let i of n)if(i?.entries.some(o=>o.key===e.key))return e;let r=Ie(e.key)??e.key;for(let i of n){let o=i?.entries.find(s=>(Ie(s.key)??s.key)===r);if(o)return{...e,key:o.key}}return e}function wm(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 i=n.get(r);if(i){if(!i.exists)throw new Error(`Source file not found: ${r}`);return i.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 i=n.get(r);return i?i.exists:e.exists(r)},async getFileInfo(r){let i=n.get(r);return i?i.exists?{path:r,sizeBytes:Buffer.byteLength(i.content,"utf8")}:null:e.getFileInfo?.(r)??null},async listFiles(r={}){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let i=Am(await e.listFiles(r)),o=new Map(i.files.map(a=>[a.path,a]));for(let[a,l]of n)if(Fm(a,r.roots??[])){if(!l.exists){o.delete(a);continue}o.set(a,{path:a,sizeBytes:Buffer.byteLength(l.content,"utf8")})}let s=[...o.values()].sort((a,l)=>a.path.localeCompare(l.path));return i.truncated?{files:s,truncated:i.truncated}:s},getVersion(r){return e.getVersion(r)},bumpVersion(r){return e.getVersion(r)}}}function Fm(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function Am(e){return Array.isArray(e)?{files:e}:e}function Nm(e){if(!pm(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!==hm||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=fm(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(bm.test(e.path)){let t=Be({source:e.content,profile:Lt({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(vm.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${It(t)}`,details:{path:e.path}}}if(Em.test(e.path)){let t=pl({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(Cm.test(e.path)){let t=pl({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}return{ok:!0}}function pl({content:e,path:t,profile:n}){let r=[],i=null,o=!1,s=!1,a=!1,l=!1,u=!0;for(let d=0;d<e.length;d+=1){let p=e[d]??"",h=e[d+1]??"";if(n==="mdx"&&u&&e.startsWith("```",d)){l=!l;let k=e.indexOf(`
5
+ `,d);if(k===-1){u=!0;break}d=k,u=!0;continue}if(l){u=p===`
6
+ `||p==="\r";continue}if(s){p==="*"&&h==="/"&&(s=!1,d+=1),u=p===`
7
+ `||p==="\r";continue}if(a){p===`
8
+ `||p==="\r"?(a=!1,u=!0):u=!1;continue}if(i){if(o)o=!1;else if(p==="\\")o=!0;else if(p===i)i=null;else if(n==="css"&&(p===`
9
+ `||p==="\r"))return Ct(t,`Unterminated string literal in ${t}.`);u=p===`
10
+ `||p==="\r";continue}if(p==="/"&&h==="*"){s=!0,d+=1,u=!1;continue}if(n==="mdx"&&p==="/"&&h==="/"){a=!0,d+=1,u=!1;continue}if(p==="'"||p==='"'||n==="mdx"&&p==="`"){i=p,u=!1;continue}if(p==="{"||p==="("||p==="["){r.push({char:p,offset:d}),u=!1;continue}if(p==="}"||p===")"||p==="]"){let k=p==="}"?"{":p===")"?"(":"[",b=r.pop();if(!b||b.char!==k)return Ct(t,`Unexpected closing token "${p}" in ${t}.`);u=!1;continue}u=p===`
11
+ `||p==="\r"}if(s)return Ct(t,`Unterminated block comment in ${t}.`);if(i)return Ct(t,`Unterminated string literal in ${t}.`);if(l)return Ct(t,`Unterminated MDX code fence in ${t}.`);let c=r.at(-1);return c?Ct(t,`Unclosed token "${c.char}" in ${t}.`):{ok:!0}}function Ct(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function tn(e){let t="idle",n=e.fileSystem??Sm(),r=ul(),i=new Map,o=new Map,s=null,a=new Set,l=null,u=cl(n,{externalAdapters:e.externalAdapters}),c=new Map,d=0,p=0;function h(){return t==="disposed"}if(e.onEvent&&r.subscribe(e.onEvent),e.routes)for(let f of e.routes){let S=fl(f.routeId,f.entryFile);i.set(f.routeId,S),k(S,S.dependencyFiles)}function k(f,S){let y=new Set(S);b(f),f.dependencyFiles=y;for(let v of f.dependencyFiles){let w=o.get(v);w||(w=new Set,o.set(v,w)),w.add(f.routeId)}}function b(f){for(let S of f.dependencyFiles){let y=o.get(S);y&&(y.delete(f.routeId),y.size===0&&o.delete(S))}f.dependencyFiles.clear()}function E(f){let S=new Set;for(let y of f)for(let v of o.get(y)??[])S.add(v);return S}function P(f){for(let S of f)if(!o.has(S))return!1;return!0}async function R(f,S,y){let v=new Map,w=new Map,L=typeof n.exists=="function"?D=>n.exists(D):async()=>!1;for(let[D,N]of f.elements){let $=S.nodes.get(D);if(!$)continue;let V=y.get(N.sourceFile)??c.get(N.sourceFile),re=new Map,ie=new Map,Re=new Map,ge=[];for(let H of N.textSegments){if(!V){re.set(H.index,null);continue}let Ft=await Wa({file:N.sourceFile,source:V,segment:H,readFile:xe=>n.readFile(xe),exists:L,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:xe,adapterId:dr,capabilities:fr})=>({sourceType:xe,adapterId:dr,capabilities:fr})),functionCallContracts:e.functionCallContracts,fileCache:w}),oe=await $i({file:N.sourceFile,source:V,target:{kind:"text-segment",segment:H},readFile:xe=>n.readFile(xe),exists:L,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:xe,adapterId:dr,capabilities:fr})=>({sourceType:xe,adapterId:dr,capabilities:fr})),functionCallContracts:e.functionCallContracts,fileCache:w}),ct=Im(Ft);re.set(H.index,ct),ie.set(H.index,Ft),Re.set(H.index,oe),ge.push({editable:H.editable,source:ct})}let Rt=new Map;if(V)for(let H of N.attributes??[]){let Ft=await Ua({file:N.sourceFile,source:V,sourceRange:H.sourceRange,expression:H.source?.expression??H.value,sourceInfo:H.source,readFile:oe=>n.readFile(oe),exists:L,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:oe,adapterId:ct,capabilities:xe})=>({sourceType:oe,adapterId:ct,capabilities:xe})),functionCallContracts:e.functionCallContracts,fileCache:w});Rt.set(H.name,Ft)}let wt=No(Pm($.writeTarget),ge),fe=Mo({key:D,element:N,graph:f,provenances:Re}),cr=jo(N),Ll=$o(N),Ol=qo(N),on=f.regions.find(H=>H.kind==="conditional-region"&&H.childKeys.includes(D)),uo,ur=on?.sourceCandidates?.[0];if(V&&on&&ur?.kind==="conditional-branch"){let H=await $i({file:N.sourceFile,source:V,target:{kind:"conditional-branch",candidate:ur},readFile:oe=>n.readFile(oe),exists:L,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:oe,adapterId:ct,capabilities:xe})=>({sourceType:oe,adapterId:ct,capabilities:xe})),functionCallContracts:e.functionCallContracts,fileCache:w});uo={currentBranch:on.childKeys.indexOf(D)<=0?"then":"else",availableBranches:on.childKeys.length>1?["then","else"]:["then"],conditionExpression:ur.conditionExpression,provenance:{finalSource:H.finalSource?{kind:H.finalSource.kind,file:H.finalSource.file,displayPath:H.finalSource.displayPath}:null,chain:H.chain.map(oe=>({kind:oe.kind,file:oe.file,displayName:oe.displayName,canEditHere:oe.canEditHere})),confidence:H.confidence,editMode:H.editMode,diagnostics:H.diagnostics.map(oe=>({code:oe.code,message:oe.message}))}}}v.set(D,{textSources:re,textTargets:ie,elementPropertyTargets:Rt,provenances:Re,writeTarget:wt,componentSemantic:fe,contentModel:cr,mediaModel:Ll,styleSource:Ol,conditional:uo})}return v}function I(f){return typeof n.getVersion=="function"?n.getVersion(f):0}function B(f,S){let y=1;for(let v of S.values())y=Math.max(y,v);return Math.max(y,f.graph?.version??0)}async function G(f,S,y={}){let v=i.get(f);if(!v)return;let w=await C(v.entryFile),{graph:L,allSources:D}=await Io(v.entryFile,S,fe=>n.readFile(fe),typeof n.exists=="function"?fe=>n.exists(fe):async()=>!1,{additionalEntries:w,version:v.graph?.version??1}),N=new Map;for(let fe of D.keys())N.set(fe,I(fe));let $=Math.max(B(v,N),y.minimumVersion??0);y.changed&&$<=(v.graph?.version??0)&&($=(v.graph?.version??0)+1),L.version=$,d=Math.max(d,$);for(let[fe,cr]of D)A(fe,cr);let V=await j(v.entryFile,D,$);L.routeId=f;let re=Po(L),ie=wo(re,L),Re=await R(L,re,D),ge=Z(L,ie,Re),Rt=_m(Fo(L,re,ie,{canUpdateTextByKey:ge}),L,Re),wt=new Set([v.entryFile,...D.keys()]);if(V){wt.add(V.entryCss.path);for(let fe of V.stylesheets)wt.add(fe.path)}k(v,wt),v.graph=L,v.topology=re,v.capabilities=ie,v.document=Rt,v.documentIndex=km(Rt),v.detailProjections=Re,v.fileVersions=N,v.styleContext=V}async function C(f){let S=[];for(let y of Lm(f))typeof n.exists=="function"&&await n.exists(y)&&S.push({file:y,source:await n.readFile(y)});return S}async function j(f,S,y){let v=[];for(let[$,V]of S){if(Yi($)){v.push($);continue}for(let re of Dm(V)){let ie=hl($,re);ie&&v.push(ie)}}if(!v.length){for(let $ of Om(f))if(await z($)){v.push($);break}}let w=new Map,L=Sl(v).slice(0,dl);for(;L.length>0&&w.size<dl;){let $=L.shift();if(w.has($)||!Yi($))continue;let V=await F($);if(V!==null){w.set($,{path:$,content:V});for(let re of jm(V)){let ie=hl($,re);ie&&!w.has(ie)&&!L.includes(ie)&&L.push(ie)}}}let D=[...w.values()].map($=>({...$,hash:q($.content)})),N=D[0];return N?{revision:q(JSON.stringify({routeVersion:y,stylesheets:D.map(({path:$,hash:V})=>({path:$,hash:V}))})),entryCss:N,stylesheets:D.slice(1)}:null}async function F(f){let S=c.get(f);if(S!==void 0)return S;if(!await z(f))return null;let y=await n.readFile(f);return A(f,y),y}function A(f,S){if(!c.has(f)&&c.size>=ym){let y=c.keys().next().value;y&&c.delete(y)}c.set(f,S)}async function z(f){return typeof n.exists=="function"?n.exists(f):!1}function Z(f,S,y){let v=new Map;for(let[w,L]of f.elements){if(!S.get(w)?.canUpdateText){v.set(w,!1);continue}let N=y.get(w),$=L.textSegments.some(V=>{if(!V.editable)return!1;let re=N?.provenances.get(V.index)??null;return!re||te(re)});v.set(w,$)}return v}function te(f){return f.editMode==="direct"||f.editMode==="proxy"||f.editMode==="upstream"}async function se(f,S={}){let y=[...new Set(f)],v=E(y);if(v.size===0||!P(y))for(let D of i.values())Pe(D,y)&&v.add(D.routeId);let w=v.size===0&&y.some(ml),L={rebuiltRoutes:[],failedRoutes:[]};for(let D of i.values())if(v.has(D.routeId)||w)try{let $=!!D.graph,V=await n.readFile(D.entryFile);await G(D.routeId,V,S),D.graph&&L.rebuiltRoutes.push({documentChanged:$,routeId:D.routeId,version:D.graph.version})}catch($){L.failedRoutes.push({routeId:D.routeId,message:It($)})}return L}function le(f,S=0){let y=[...new Set(f)],v=S;for(let w of i.values())Pe(w,y)&&w.graph&&(v=Math.max(v,w.graph.version));return v}function Y(f){let S=[...new Set(f)],y=E(S);if(y.size>0&&P(S))return[...y];for(let v of i.values())Pe(v,S)&&y.add(v.routeId);return[...y]}function he(f,S){r.emit({type:"operation-completed",result:f});for(let{routeId:y,version:v}of S.rebuiltRoutes)r.emit({type:"document-changed",routeId:y,version:v});for(let{routeId:y,message:v}of S.failedRoutes)r.emit({type:"graph-error",routeId:y,message:v})}function Pe(f,S){return S.some(y=>f.dependencyFiles.has(y)||f.entryFile===y||f.graph?.fileIndex.has(y))}function io(f){for(let S of f)a.add(S);l||h()||(l=(async()=>{t="building";let S=!1;try{for(;a.size>0;){if(h())return;await wl();let y=[...a];a.clear();let v=await oo(y);if(v.length===0)continue;let w=Y(v);for(let N of w)r.emit({type:"graph-invalidated",routeId:N});let{rebuiltRoutes:L,failedRoutes:D}=await se(v,{changed:!0});for(let{documentChanged:N,routeId:$,version:V}of L)r.emit({type:"graph-ready",routeId:$,version:V}),N&&r.emit({type:"document-changed",routeId:$,version:V});for(let{routeId:N,message:$}of D)S=!0,r.emit({type:"graph-error",routeId:N,message:$})}}finally{if(l=null,t!=="disposed"){let y=s?i.get(s):null;t=!S&&y?.graph?"ready":"idle"}a.size>0&&io([])}})())}async function wl(){for(;p>0;)await new Promise(f=>setTimeout(f,0))}async function oo(f){let S=[];for(let y of new Set(f)){let v=c.get(y);if(v===void 0){S.push(y);continue}try{await n.readFile(y)!==v&&S.push(y)}catch{S.push(y)}}return S}async function so(f){let S=await oo(f);if(S.length===0)return;let y=Y(S);for(let L of y)r.emit({type:"graph-invalidated",routeId:L});let{rebuiltRoutes:v,failedRoutes:w}=await se(S,{changed:!0});for(let{documentChanged:L,routeId:D,version:N}of v)r.emit({type:"graph-ready",routeId:D,version:N}),L&&r.emit({type:"document-changed",routeId:D,version:N});for(let{routeId:L,message:D}of w)r.emit({type:"graph-error",routeId:L,message:D})}async function Fl(f,S){let y=rn(f,S);if(!y?.graph)return;let v=Ie(f)??f,w=y.graph.elements.get(v);w&&await so([w.sourceFile])}async function ao(f){let S=new Set;if(f.target.kind==="node"){let y=rn(f.target.key,f.routeId),v=Ie(f.target.key)??f.target.key,w=y?.graph?.elements.get(v);w&&S.add(w.sourceFile)}else if(f.target.kind==="route"){let y=i.get(f.target.routeId);y&&S.add(y.entryFile)}else if(f.target.kind==="source-file")S.add(f.target.path);else for(let y of f.target.paths)S.add(y);f.params.kind==="set-class-name-source"&&S.add(f.params.filePath),f.params.kind==="apply-style-draft"&&f.params.className&&S.add(f.params.className.filePath),await so(S)}async function Al(f){if(f.params.kind!=="source-edit")return nn(f,"invalid-params","source-edit requires source-edit params");for(let S of f.params.edits){let y=Nm(S);if(!y.ok)return nn(f,y.errorCode,y.message,y.details)}p+=1;try{let S=await Nl(f.params.edits);if(!S.ok)return nn(f,S.errorCode,S.message,S.details);let y={operationId:f.id,kind:"source-edit",target:f.target,documentVersion:f.documentVersion,conflictPolicy:f.params.conflictPolicy,edits:f.params.edits.map(N=>N.operation==="delete"?{operation:"delete",file:N.path,baseContentHash:N.baseContentHash??null}:{operation:"upsert",file:N.path,baseContentHash:N.baseContentHash??null,content:N.content})},v=await u.executeFilePlan(y);if(!v.ok){let N=nn(f,v.errorCode,v.reason);return v.affectedFiles?.length&&(N.affectedFiles=v.affectedFiles),N}Ml(v.affectedFiles);let w=await se(v.affectedFiles,{changed:!0,minimumVersion:v.resultVersion}),L=Math.max(v.resultVersion,le(v.affectedFiles,v.resultVersion));d=Math.max(d,L);let D={requestId:f.id,kind:f.kind,target:f.target,ok:!0,resultVersion:L,affectedFiles:v.affectedFiles};return he(D,w),D}catch(S){return{requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:d,error:{code:U.INTERNAL_ERROR,message:It(S)}}}finally{p-=1}}async function Nl(f){let S=Tl(f);if(S.length===0)return{ok:!0};let y=wm(n,f),v=tn({projectRoot:e.projectRoot,fileSystem:y,routes:[...i.values()].map(w=>({routeId:w.routeId,entryFile:w.entryFile})),externalAdapters:e.externalAdapters,externalSourceResolvers:e.externalSourceResolvers,functionCallContracts:e.functionCallContracts,dev:e.dev});try{for(let w of S)await v.setActiveRoute(w)}catch(w){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${It(w)}`,details:{routeIds:S}}}finally{v.dispose()}return{ok:!0}}function Tl(f){return f.map(y=>y.path).some(ml)?[...i.keys()]:[]}function Ml(f){for(let S of f)c.delete(S)}function nn(f,S,y,v){return{requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:d,error:{code:en(S),message:y,...v?{details:v}:{}}}}async function lo(f){let S=i.get(f);if(!S)throw new Error(`Route not found: ${f}`);if(S.graph)return;let y=await n.readFile(S.entryFile);await G(f,y)}function rn(f,S){if(S){let y=i.get(S)??null;return!y||!lr(y,f)?null:y}for(let y of i.values())if(lr(y,f))return y;return null}function lr(f,S){if(f.documentIndex?.entriesByKey.has(S)||f.graph?.elements.has(S))return!0;let y=Ie(S);return y&&y!==S?f.graph?.elements.has(y)===!0:!1}function Pt(f,S,y){return{requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:d,error:{code:S,message:y}}}async function co(f){if(f.target.kind==="route"){let y=i.get(f.target.routeId)??null;return y?(y.graph||await lo(y.routeId),y):Pt(f,U.ROUTE_NOT_FOUND,`Route not found: ${f.target.routeId}`)}if(f.target.kind!=="node")return Pt(f,U.UNSUPPORTED_OPERATION,`${f.kind} source target execution is not implemented yet.`);if(!f.routeId)return Pt(f,U.INVALID_TARGET,"routeId is required when executing a node target");let S=i.get(f.routeId)??null;return S?(S.graph||await lo(S.routeId),lr(S,f.target.key)?S:Pt(f,U.NODE_NOT_FOUND,`Target key not found: ${f.target.key}`)):Pt(f,U.ROUTE_NOT_FOUND,`Route not found: ${f.routeId}`)}return{get status(){return t},dispose(){t="disposed",a.clear(),i.clear(),o.clear(),c.clear(),s=null},registerRoute(f,S){let y=i.get(f);if(y?.entryFile===S)return;y&&b(y);let v=fl(f,S);i.set(f,v),k(v,v.dependencyFiles),r.emit({type:"graph-invalidated",routeId:f})},unregisterRoute(f){let S=i.get(f);S&&(b(S),i.delete(f),s===f&&(s=null,t="idle"),r.emit({type:"graph-invalidated",routeId:f}))},getRouteEntryFiles(){return[...i.values()].map(f=>f.entryFile)},async setActiveRoute(f){let S=i.get(f);if(!S)throw new Error(`Route not found: ${f}`);let y=s===f;if(s=f,!S.graph){t="building";try{let v=await n.readFile(S.entryFile);await G(f,v);let w=i.get(f)?.graph?.version??1;t="ready",r.emit({type:"graph-ready",routeId:f,version:w})}catch(v){throw t="idle",r.emit({type:"graph-error",routeId:f,message:It(v)}),v}return}t="ready",y||r.emit({type:"graph-ready",routeId:f,version:S.graph.version})},getDocument(f){let S=i.get(f);if(!S)throw new Error(`Route not found: ${f}`);if(!S.document)throw new Error(`Route not built: ${f}`);return S.document},getRenderDetail(f,S){let y=rn(f,S),v=Ie(f)??f;if(y?.graph&&y.topology&&y.capabilities&&y.detailProjections){let w=y.detailProjections.get(v);if(w){let L=Ao(v,y.graph,y.topology,y.capabilities,w.textSources,w.writeTarget,w.provenances,w.conditional,w.componentSemantic,w.contentModel,w.mediaModel,w.styleSource);return f===v?L:Wm(L,f,y.document??null,y.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${f}`)},getClassNameSource(f,S){let y=rn(f,S),v=Ie(f)??f;if(!y?.graph)throw new Error(`Key not found: ${f}`);let w=y.graph.elements.get(v);if(!w)throw new Error(`Key not found: ${f}`);let L=c.get(w.sourceFile);if(L===void 0)throw new Error(`Source not loaded: ${w.sourceFile}`);let D=ds({key:v,route:{routeId:y.routeId,graph:y.graph,source:L}});return y.styleContext?{...D,styleContext:y.styleContext}:D},refreshSourceForKey:Fl,async execute(f){if(f.kind==="source-edit")return await ao(f),Al(f);let S=await co(f);if("ok"in S)return S;await ao(f);let y=await co(f);if("ok"in y)return y;let v=y;if(!v.graph||!v.topology||!v.capabilities)return{requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:d,error:{code:f.target.kind==="route"?U.ROUTE_NOT_FOUND:U.NODE_NOT_FOUND,message:f.target.kind==="route"?`Route not ready: ${f.target.routeId}`:f.target.kind==="node"?`Target key not found: ${f.target.key}`:`${f.kind} source target execution is not implemented yet.`}};let w=Tm(v,v.graph,v.capabilities,c,i),L=await new Yn(w).plan(f);if(!L.ok)return{requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:d,error:{code:en(L.errorCode),message:L.reason}};let D=L.plan;if(D.steps.length===0)return{requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:d,error:{code:U.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};p+=1;try{let N=await u.execute(D);if(!N.ok)return{requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:d,error:{code:en(N.errorCode),message:N.reason}};let $=await se(N.affectedFiles,{changed:!0,minimumVersion:N.resultVersion});if($.failedRoutes.length>0){let ge=Math.max(N.resultVersion,le(N.affectedFiles,N.resultVersion));return d=Math.max(d,ge),{requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:ge,affectedFiles:N.affectedFiles,error:{code:U.AST_PARSE_ERROR,message:`Source committed but route rebuild failed: ${Gi($.failedRoutes)}`,details:{sourceCommitted:!0,failedRoutes:$.failedRoutes}}}}let V=le(N.affectedFiles,N.resultVersion);d=Math.max(d,V);let re=[v.document,...[...i.values()].filter(ge=>ge!==v).map(ge=>ge.document)],ie=Rm(N.selectionRef,re),Re={requestId:f.id,kind:f.kind,target:f.target,ok:!0,resultVersion:V,affectedFiles:N.affectedFiles,...ie?{selectionRef:ie}:{}};return he(Re,$),Re}catch(N){return{requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:d,error:{code:U.INTERNAL_ERROR,message:It(N)}}}finally{p-=1}},async undo(){p+=1;try{let f=await u.undo();if(!f.ok)return{requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:d,error:{code:en(f.errorCode),message:f.reason}};let S=await se(f.affectedFiles,{changed:!0,minimumVersion:f.resultVersion});if(S.failedRoutes.length>0){let w=le(f.affectedFiles,f.resultVersion);return d=Math.max(d,w),{requestId:"undo",kind:f.kind,target:f.target,ok:!1,resultVersion:w,affectedFiles:f.affectedFiles,error:{code:U.AST_PARSE_ERROR,message:`Undo committed but route rebuild failed: ${Gi(S.failedRoutes)}`,details:{sourceCommitted:!0,failedRoutes:S.failedRoutes}}}}let y=le(f.affectedFiles,f.resultVersion);d=Math.max(d,y);let v={requestId:"undo",kind:f.kind,target:f.target,ok:!0,resultVersion:y,affectedFiles:f.affectedFiles};return he(v,S),v}finally{p-=1}},async redo(){p+=1;try{let f=await u.redo();if(!f.ok)return{requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:d,error:{code:en(f.errorCode),message:f.reason}};let S=await se(f.affectedFiles,{changed:!0,minimumVersion:f.resultVersion});if(S.failedRoutes.length>0){let w=le(f.affectedFiles,f.resultVersion);return d=Math.max(d,w),{requestId:"redo",kind:f.kind,target:f.target,ok:!1,resultVersion:w,affectedFiles:f.affectedFiles,error:{code:U.AST_PARSE_ERROR,message:`Redo committed but route rebuild failed: ${Gi(S.failedRoutes)}`,details:{sourceCommitted:!0,failedRoutes:S.failedRoutes}}}}let y=le(f.affectedFiles,f.resultVersion);d=Math.max(d,y);let v={requestId:"redo",kind:f.kind,target:f.target,ok:!0,resultVersion:y,affectedFiles:f.affectedFiles};return he(v,S),v}finally{p-=1}},notifyFileChanged(f){io([f])},subscribe(f){return r.subscribe(f)}}}function Tm(e,t,n,r,i){let o=new Map,s=new Map,a=(c,d)=>{if(s.has(c))return;s.set(c,d);let p=t.elements.get(c);for(let h of p?.childKeys??[])a(h,d)};for(let c of t.regions)if(c.kind==="repeat-region")for(let d of c.childKeys)o.set(d,c.ownerKey),a(d,c.ownerKey);return{getNode(c){let d=l(c),p=t.elements.get(d.baseKey);return p?u(c,p):null},getChildNodes(c){let d=l(c),h=e.documentIndex?.entriesByKey.get(c)?.childKeys;if(h)return h.map(b=>{let E=Ie(b)??b,P=t.elements.get(E);return P?u(b,P):null}).filter(b=>b!==null);let k=t.elements.get(d.baseKey);return k?k.childKeys.map(b=>{let E=t.elements.get(b);return E?u(b,E):null}).filter(b=>b!==null):[]},getKnownSourceFiles(){return[...r.entries()].map(([c,d])=>({file:c,content:d}))},getRouteEntryFiles(){return[...i.values()].map(c=>c.entryFile)},getCapability(c){let d=l(c),p=n.get(d.baseKey);return p?{...p,key:c,constraints:p.constraints.map(h=>({...h})),...p.editModes?{editModes:{...p.editModes}}:{}}:{key:c,canUpdateText:!1,canRemove:!1,canInsertChild:!1,canMove:!1,constraints:[]}},getFileContent(c){return r.get(c)??""},getFileVersion(c){return Math.max(e.fileVersions.get(c)??0,t.version)},getRouteEntryFile(c){return e.routeId===c?e.entryFile:null},getComponentSemantic(c){let d=l(c);return e.detailProjections?.get(d.baseKey)?.componentSemantic??null},getEditableTextSegmentIndex(c){let d=l(c),h=e.detailProjections?.get(d.baseKey)?.textTargets.keys()?.next();return h&&!h.done?h.value:null},async getTextWriteTarget(c,d){let p=l(c);return gl(e.detailProjections?.get(p.baseKey)?.textTargets.get(d)??null,p.repeatIndex)},async getElementPropertyWriteTarget(c,d){let p=l(c);return gl(e.detailProjections?.get(p.baseKey)?.elementPropertyTargets.get(d)??null,p.repeatIndex)},getTextProvenance(c,d){let p=l(c);return e.detailProjections?.get(p.baseKey)?.provenances.get(d)??null}};function l(c){let d=mm(c);return d?{baseKey:d.baseKey,repeatIndex:Vm(e.document??null,c,d.baseKey,e.documentIndex)??Km(d)}:{baseKey:c,repeatIndex:null}}function u(c,d){let p=Ie(c)??c,h=e.documentIndex?.entriesByKey.get(c),k=e.detailProjections?.get(p);return{key:c,file:d.sourceFile,component:d.componentName,tag:d.tag,structuralPath:d.identity.structuralPath,sourceRange:d.sourceRange,parentKey:h?.parentKey??d.parentKey??void 0,isRepeatRegion:d.boundaryKind==="repeat-region"||s.has(p),isBoundary:!1,importedFrom:d.importedFrom,exportName:d.exportName,isRepeatItemRoot:o.has(p),repeatOwnerKey:o.get(p)??s.get(p),contentModel:k?.contentModel,attributes:d.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(E=>({...E}))}:null,resolvedValue:b.resolvedValue}))}}}var Mm={"stale-version":U.VERSION_STALE,"capability-denied":U.CAPABILITY_REJECTED,"invalid-params":U.INVALID_PARAMS,"locator-miss":U.LOCATOR_FAILED,"route-not-found":U.ROUTE_NOT_FOUND,"unsupported-operation":U.UNSUPPORTED_OPERATION,"invalid-target":U.INVALID_TARGET,"ast-error":U.AST_PARSE_ERROR,"writeback-failed":U.WRITE_IO_ERROR,"rollback-failed":U.ROLLBACK_FAILED,unknown:U.INTERNAL_ERROR};function en(e){return Mm[e]}function It(e){return e instanceof Error&&e.message?e.message:String(e)}function ml(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function Gi(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function Lm(e){let t=st(e);if(!gm.test(t))return[];let n=t.startsWith("src/app/")?"src/app":"app",r=t.slice(0,t.lastIndexOf("/")),i=[],o=r;for(;(o===n||o.startsWith(`${n}/`))&&(i.unshift(o),o!==n);)o=o.slice(0,o.lastIndexOf("/"));return i.flatMap(s=>xm.map(a=>`${s}/${a}`))}function Om(e){let n=st(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function Dm(e){return xl(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function jm(e){return xl(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function xl(e,t){let n=[];for(let r of e.matchAll(t)){let i=yl(r[1]??"");i&&n.push(i)}return n}function hl(e,t){let n=yl(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?st(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?st(`${$m(e)}/${n}`):n.startsWith("/")?st(n.slice(1)):Yi(n)?st(n):null}function yl(e){return e.split(/[?#]/,1)[0]?.trim()??""}function Yi(e){return/\.css$/i.test(e)}function $m(e){let t=st(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function Sl(e){return Array.from(new Set(e))}function st(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 Bm(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 er(e){return e?.map(t=>({...t}))}function gl(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=er(e.collectionPathMap?.[t])??er(e.locator?.path);if(r)for(let i=r.length-1;i>=0;i-=1){let o=r[i];if(o.kind==="index"){o.index=n;break}}return{...e,path:er(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(i=>er(i)??[])}}function _m(e,t,n){let r=new Set;for(let h of t.regions)if(h.kind==="repeat-region")for(let k of h.childKeys)r.add(k);if(r.size===0)return e;let i=new Map(e.entries.map(h=>[h.key,h])),o=[],s=new Map,a=(h,k)=>dm(h,k),l=(h,k,b)=>{let E=i.get(h);if(!E)return a(h,b);let P=a(h,b),R={...E,key:P,parentKey:k,childKeys:[]};return o.push(R),R.childKeys=E.childKeys.flatMap(I=>u(I,b,P)),P},u=(h,k,b)=>{if(!r.has(h))return[l(h,b,k)];let E=d(h,k),P=[];for(let R=0;R<E;R+=1)P.push(l(h,b,[...k,R]));return P},c=Sl([...e.rootKeys,...e.entries.filter(h=>h.parentKey===null).map(h=>h.key)]);for(let h of c){if(!r.has(h)){l(h,null,[]);continue}let k=d(h,[]);for(let b=0;b<k;b+=1)l(h,null,[b])}return{...e,rootKeys:[...e.rootKeys],entries:o};function d(h,k){let b=new Set;for(let E of p(h)){let P=n.get(E);if(P){for(let R of[...P.textTargets.values(),...P.elementPropertyTargets.values()])if(!(R?.kind!=="value-binding"||R.sourceKind!=="repeat-template"))for(let I of Jm(R))I.length<=k.length||Xm(I,k)&&b.add(I[k.length])}}return b.size>0?b.size:Bm(n.get(h))}function p(h){let k=s.get(h);if(k)return k;let b=[h],E=i.get(h);for(let P of E?.childKeys??[])b.push(...p(P));return s.set(h,b),b}}function Km(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function Vm(e,t,n,r){let i=r?.repeatOccurrenceIndexByKey.get(t);if(i!==void 0)return i;if(!e)return null;let o=0;for(let s of e.entries)if((Ie(s.key)??s.key)===n){if(s.key===t)return o;o+=1}return null}function Jm(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 Xm(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 Wm(e,t,n,r){if(!n)return{...e,key:t};let i=r??new Map(n.entries.map(c=>[c.key,c])),o=i.get(t);if(!o)return{...e,key:t};let s=[],a=o.parentKey;for(;a;){let c=i.get(a);if(!c)break;s.push({key:c.key,tag:c.tag,label:c.label}),a=c.parentKey}s.reverse();let l=o.childKeys.map(c=>i.get(c)).filter(c=>c!==void 0).map(c=>({key:c.key,tag:c.tag,label:c.label})),u=o.parentKey===null?[]:(i.get(o.parentKey)?.childKeys??[]).filter(c=>c!==o.key).map(c=>i.get(c)).filter(c=>c!==void 0).map(c=>({key:c.key,tag:c.tag,label:c.label}));return{...e,key:o.key,ancestors:s,children:l,siblings:u}}import to from"node:path";import{TextDecoder as Um}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as bl,SITE_EDIT_SOURCE_ALLOWED_DIRS as vl,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as El,SiteEditSourceFileResponseSchema as Zi,SiteEditSourceLocationSchema as zm,SiteEditSourcePathSchema as tr,SiteEditSourceTreeResponseSchema as Hm,isSiteEditTextSourcePath as Gm}from"@vcp-dev/contracts";var Ym=[...El,...bl,...vl],Qi=2e3,qi=12,eo=24*1024*1024,kl=512*1024,Zm=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),Qm={".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"},qm={".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"},eh=new Um("utf-8",{fatal:!0});async function nr(e,t={}){let{files:n,truncated:r}=await lh(e,t),i=dh(n.map(o=>o.metadata));return Hm.parse({nodes:i,defaultPath:fh(n.map(o=>o.metadata)),totalFiles:n.length,...r?{truncated:r}:{}})}async function rr(e,t,n={}){let r=tr.parse(t.path),i=await rh(e,r,n);if(!i)throw new Error(`Source file not found: ${r}`);if(no(r)){let s=Pl(r),a=await oh(e,{path:r,sizeBytes:i.sizeBytes,mimeType:s});return Zi.parse({path:r,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:s,readonly:!0,...a})}let o=await th(e,r);return o.ok?Zi.parse({path:r,kind:"text",language:Rl(r),sizeBytes:o.sizeBytes,contentHash:q(o.content),readonly:!1,content:o.content}):Zi.parse({path:r,kind:"binary",language:null,sizeBytes:o.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function th(e,t){if(e.readFileBytes){let i=await e.readFileBytes(t),o=nh(i);return o===null?{ok:!1,sizeBytes:i.byteLength}:{ok:!0,content:o,sizeBytes:i.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 nh(e){if(e.includes(0))return null;try{return eh.decode(e)}catch{return null}}async function rh(e,t,n){if(!sh(t,n))return null;let r=await ih(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function ih(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let i=Cl(await e.listFiles({roots:[t],maxFiles:1,maxDepth:t.split("/").length})).files.find(o=>o.path===t);if(i)return i}if(!await e.exists(t))return null;if(e.readFileBytes){let r=await e.readFileBytes(t);return{path:t,sizeBytes:r.byteLength}}if(no(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function oh(e,t){if(!Zm.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>kl)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>kl?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function sh(e,t){return El.some(n=>n===e)||bl.some(n=>n===e)||vl.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=tr.safeParse(n);return r.success&&r.data===e})}function ir(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return zm.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 Cl(e){return Array.isArray(e)?{files:e}:e}function ah(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function lh(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=Cl(await e.listFiles({roots:ch(t),maxFiles:Qi+1,maxDepth:qi,maxTotalBytes:eo+1})),r=new Map,i=new Set(n.truncated?.reasons),o=0;for(let a of[...n.files].sort((l,u)=>l.path.localeCompare(u.path))){let l=tr.safeParse(a.path);if(!l.success)continue;let u=l.data;if(u.split("/").length>qi){i.add("max-depth");continue}if(r.size>=Qi){i.add("max-files");break}if(o+a.sizeBytes>eo){i.add("max-total-bytes");break}r.set(u,{path:u,sizeBytes:a.sizeBytes,metadata:uh(u,a.sizeBytes)}),o+=a.sizeBytes}return{files:[...r.values()].sort((a,l)=>a.path.localeCompare(l.path)),...i.size>0?{truncated:{reasons:ah([...i]),maxFiles:Qi,maxDepth:qi,maxTotalBytes:eo}}:{}}}function ch(e){let t=new Set(Ym);for(let n of e.routeEntryFiles??[]){let r=tr.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function uh(e,t){return no(e)?{path:e,kind:"binary",language:null,sizeBytes:t,mimeType:Pl(e),readonly:!0}:{path:e,kind:"text",language:Rl(e),sizeBytes:t,readonly:!1}}function dh(e){let t=[];for(let n of e){let r=n.path.split("/"),i=t,o="";for(let[s,a]of r.entries()){o=o?`${o}/${a}`:a;let l=s===r.length-1,u=i.find(c=>c.name===a);if(u||(u=l?{kind:"file",name:a,path:o,file:n}:{kind:"directory",name:a,path:o,children:[]},i.push(u)),l){if(u.kind!=="file")throw new Error(`Source tree path collision: ${n.path}`);u.file=n}else{if(u.kind!=="directory")throw new Error(`Source tree path collision: ${n.path}`);i=u.children}}}return Il(t)}function Il(e){return e.map(t=>t.kind==="directory"?{...t,children:Il(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function fh(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 no(e){return!Gm(e)}function Pl(e){let t=to.posix.extname(e).toLowerCase();return!t&&to.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":Qm[t]??"application/octet-stream"}function Rl(e){let t=to.posix.extname(e).toLowerCase();return qm[t]??"plaintext"}var or=class{constructor(t){this.options=t,this.fileSystem=new jt(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 an(this.engine.getDocument(t),{siteId:this.options.siteId,snapshotId:this.options.snapshotId})}getObjectSummary(t,n){return ln(this.engine.getRenderDetail(t,n))}getObjectEditContext(t,n){return cn(this.engine.getRenderDetail(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(){return nr(this.fileSystem,{routeEntryFiles:this.options.routes.map(t=>t.entryFile)})}getSourceFile(t){return rr(this.fileSystem,t,{routeEntryFiles:this.options.routes.map(n=>n.entryFile)})}resolveSourceLocation(t){return ir(t,this.engine.getRenderDetail(t.key,t.routeId))}async planOperation(t){let n=mh.safeParse(t);if(!n.success)return{result:sn(t,n.error.issues.map(o=>o.message))};let r=new jt(this.options.files),i=this.createEngine(r,{emitEvents:!1});try{for(let c of this.getPlanningRouteIds(n.data))await i.setActiveRoute(c);let o=this.withInferredNodeRouteId(n.data,i),s=await i.execute(o);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:He(s)},l=r.getChangedFiles();if(l.length===0)return{result:a};let u=hh.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:l.map(c=>gh(c,t.kind==="source-edit")),changedRouteIds:this.getChangedRouteIds(l.map(c=>c.path)),diagnostics:[]});return this.options.onEvent?.({type:"site-edit.operation.planned",siteId:t.siteId,operationId:t.id,baseSnapshotId:t.baseSnapshotId,changedFiles:u.patches.map(c=>c.path),at:new Date().toISOString()}),{result:a,patchPlan:u}}finally{i.dispose()}}dispose(){this.engine.dispose()}getPlanningRouteIds(t){let n=this.getExplicitPlanningRouteId(t);if(n){let r=this.options.routes.find(i=>i.routeId===n);return r?[r.routeId]:this.options.routes.map(i=>i.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(o=>o.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 tn({projectRoot:"/snapshot",fileSystem:t,routes:this.options.routes.map(i=>({routeId:i.routeId,entryFile:i.entryFile})),onEvent:r&&this.options.onEvent?i=>{let o=un(i,{siteId:this.options.siteId,snapshotId:this.options.snapshotId});o&&this.options.onEvent?.(o)}:void 0,dev:this.options.dev})}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 o=this.options.routes.filter(s=>n.has(s.entryFile)).map(s=>s.routeId);return o.length>0?o:this.options.routes.map(s=>s.routeId)}};function gh(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:q(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:q(e.before)},fullContent:e.after}}function xh(e){return new or(e)}import{SiteEditOperationRequestSchema as kh}from"@vcp-dev/contracts";import at from"node:fs/promises";import lt from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as yh,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as Sh}from"@vcp-dev/contracts";var sr=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=tn({...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)}getRenderDetail(t,n){return this.engine.getRenderDetail(t,n)}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(){return nr(this.fileSystem,{routeEntryFiles:this.engine.getRouteEntryFiles()})}getSourceFile(t){return rr(this.fileSystem,t,{routeEntryFiles:this.engine.getRouteEntryFiles()})}resolveSourceLocation(t){return ir(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(){return this.engine.undo()}redo(){return this.engine.redo()}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 at.readFile(lt.join(n,r),"utf8")},async readFileBytes(r){return at.readFile(lt.join(n,r))},async getFileInfo(r){let i=lt.join(n,...r.split("/"));try{let o=await at.lstat(i);return!o.isFile()||o.isSymbolicLink()?null:{path:r,sizeBytes:o.size}}catch{return null}},async writeFile(r,i){await qn(lt.join(n,r),i)},async deleteFile(r){await at.rm(lt.join(n,r),{force:!0})},async exists(r){try{return await at.access(lt.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let i=r.roots??[...Sh,...yh],o=[],s=new Set,a=0;for(let c of i)await u(c,o,1);let l=o.sort((c,d)=>c.path.localeCompare(d.path));return s.size>0?{files:l,truncated:{reasons:[...s]}}:{files:l};async function u(c,d,p){if(r.maxFiles!==void 0&&d.length>=r.maxFiles){s.add("max-files");return}if(r.maxDepth!==void 0&&p>r.maxDepth){s.add("max-depth");return}let h=lt.join(n,...c.split("/")),k;try{k=await at.lstat(h)}catch{return}if(k.isSymbolicLink())return;if(k.isFile()){if(r.maxTotalBytes!==void 0&&a+k.size>r.maxTotalBytes){s.add("max-total-bytes");return}d.push({path:c,sizeBytes:k.size}),a+=k.size;return}if(!k.isDirectory())return;let b=await at.readdir(h,{withFileTypes:!0});for(let E of b)E.isSymbolicLink()||await u(`${c}/${E.name}`,d,p+1)}},getVersion(r){return t.get(r)??1},bumpVersion(r){let i=(t.get(r)??1)+1;return t.set(r,i),i}}}};function ro(e){return new sr(e)}var ar=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=ro({projectRoot:t.projectRoot,fileSystem:t.fileSystem,routes:t.routes.map(n=>({routeId:n.routeId,entryFile:n.entryFile})),onEvent:n=>{let r=un(n,{siteId:t.siteId,snapshotId:t.snapshotId});if(r){t.onEvent?.(r);for(let i of this.listeners)i(r)}},dev:t.dev})}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:an(this.engine.getDocument(t),{siteId:this.options.siteId,snapshotId:this.options.snapshotId})}}getObjectSummary(t,n){return{ok:!0,data:ln(this.engine.getRenderDetail(t,n))}}getObjectEditContext(t,n){return{ok:!0,data:cn(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){let n=kh.safeParse(t);if(!n.success)return sn(t,n.error.issues.map(i=>i.message));let r=await this.engine.execute(n.data);if(!r.ok){let i=r.error;if(!i)throw new Error("executeOperation failed without an error payload");return{ok:!1,error:{code:i.code,message:i.message},data:{requestId:r.requestId,kind:r.kind,target:r.target,resultVersion:r.resultVersion,...r.affectedFiles?.length?{affectedFiles:r.affectedFiles}:{}}}}return{ok:!0,data:He(r)}}async undo(){let t=await this.engine.undo();if(!t.ok){let n=t.error;if(!n)throw new Error("undo failed without an error payload");return{ok:!1,error:{code:n.code,message:n.message},data:{requestId:t.requestId,kind:t.kind,target:t.target,resultVersion:t.resultVersion}}}return{ok:!0,data:He(t)}}async redo(){let t=await this.engine.redo();if(!t.ok){let n=t.error;if(!n)throw new Error("redo failed without an error payload");return{ok:!1,error:{code:n.code,message:n.message},data:{requestId:t.requestId,kind:t.kind,target:t.target,resultVersion:t.resultVersion}}}return{ok:!0,data:He(t)}}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 bh(e){return new ar(e)}export{ar as PreviewFileSystemSiteEditEngineRuntime,or as SnapshotSiteEditEngineRuntime,bh as createPreviewSiteEditEngineRuntime,xh as createSiteEditEngineRuntime};