@vcp-dev/site-edit-engine 0.10.2 → 0.10.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,14 +1,14 @@
1
- import{SiteEditOperationRequestSchema as uR,SiteEditPatchPlanSchema as dR}from"@vcp-dev/contracts";function nn(e){return{requestId:e.requestId,kind:e.kind,composition:e.composition,target:e.target,resultVersion:e.resultVersion,affectedFiles:e.affectedFiles,...e.output?{output:e.output}:{},...e.selectionRef?{selectionRef:e.selectionRef}:{}}}function io(e,t){let n=t[0]??"Site edit operation request failed contract validation.";return{ok:!1,composition:{routeId:e.composition.routeId,...e.composition.templateId!==void 0?{effectiveTemplateId:e.composition.templateId}:{}},error:{code:"INVALID_PARAMS",message:n},data:{requestId:e.id,kind:e.kind,composition:{routeId:e.composition.routeId,...e.composition.templateId!==void 0?{effectiveTemplateId:e.composition.templateId}:{}},target:e.target,resultVersion:e.documentVersion}}}function so(e,t){if(!e.pageComposition)throw new Error("RenderDocument is missing the required Page Composition projection.");return{siteId:t.siteId,snapshotId:t.snapshotId,composition:e.composition,version:e.version,entries:e.entries.map(n=>({key:n.key,...n.pageCompositionUnitKey?{pageCompositionUnitKey:n.pageCompositionUnitKey}:{},operationSummary:{canUpdateText:n.operationSummary.canUpdateText,canInsertChild:n.operationSummary.canInsertChild,canMove:n.operationSummary.canMove,canRemove:n.operationSummary.canRemove},...n.dynamicDataSummary?{dynamicDataSummary:n.dynamicDataSummary}:{}})),pageComposition:e.pageComposition.status==="unsupported"?{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics}:{status:"supported",containerKey:e.pageComposition.container.key,hasBusinessMembers:e.pageComposition.businessMembers.length>0,placementUnitKeys:e.pageComposition.placementUnits.map(n=>n.key),placements:e.pageComposition.placements.map(n=>({placementKey:n.placementKey,placementUnitKey:n.placementUnitKey,relation:n.relation}))}}}function ao(e){return{composition:e.composition,key:e.key,tag:e.tag,label:e.label,sourceLocator:e.sourceLocator,isOpaque:e.isOpaque,ancestors:e.ancestors,componentName:e.componentName,sourceFile:e.sourceFile,capabilities:vg(e.capabilities),provenanceChain:e.provenanceChain?{editMode:e.provenanceChain.editMode,diagnostics:e.provenanceChain.diagnostics}:void 0,dynamicData:e.dynamicData,...e.properties?{properties:e.properties}:{},textSegments:e.textSegments.map(t=>({index:t.index,editable:t.editable,sourceKind:t.source?.kind??null})),boundaryKind:e.boundaryKind}}function co(e,t){let n=new Date().toISOString();return e.type==="document-changed"?{type:"site-edit.document.changed",siteId:t.siteId,snapshotId:t.snapshotId,composition:e.composition,version:e.version,at:n}:e.type==="operation-completed"?{type:"site-edit.operation.completed",siteId:t.siteId,composition:e.composition,result:nn(e.result),at:n}:e.type==="operation-failed"?{type:"site-edit.operation.failed",siteId:t.siteId,requestId:e.requestId,composition:e.composition,error:e.error,at:n}:e.type==="capability-changed"?{type:"site-edit.capability.changed",siteId:t.siteId,composition:e.composition,keys:e.keys,at:n}:e.type==="graph-invalidated"?{type:"site-edit.graph.invalidated",siteId:t.siteId,composition:e.composition,at:n}:e.type==="graph-ready"?{type:"site-edit.graph.ready",siteId:t.siteId,composition:e.composition,version:e.version,at:n}:e.type==="graph-error"?{type:"site-edit.graph.error",siteId:t.siteId,composition:e.composition,message:e.message,at:n}:null}function vg(e){return{composition:e.composition,key:e.key,canUpdateText:e.canUpdateText,canInsertChild:e.canInsertChild,canMove:e.canMove,canRemove:e.canRemove,editModes:e.editModes?{updateText:e.editModes.updateText?{mode:e.editModes.updateText.mode,reasonCode:e.editModes.updateText.reasonCode}:void 0,insertChild:e.editModes.insertChild?{mode:e.editModes.insertChild.mode,reasonCode:e.editModes.insertChild.reasonCode}:void 0,move:e.editModes.move?{mode:e.editModes.move.mode,reasonCode:e.editModes.move.reasonCode}:void 0,remove:e.editModes.remove?{mode:e.editModes.remove.mode,reasonCode:e.editModes.remove.reasonCode}:void 0}:void 0,constraints:e.constraints}}import{computeSiteEditCompositionKey as Gk,composeSiteEditRepeatInstanceKey as Yk,getSiteEditSourceDeleteProtectionReason as Zk,isSiteEditTextSourcePath as Qk,parseSiteEditRepeatInstanceKey as qk,SITE_EDIT_SOURCE_DELETE_CAPABILITY as eC,stripSiteEditRepeatInstanceKeys as Ve}from"@vcp-dev/contracts";import{parse as tC}from"yaml";import vi from"node:path";function er(e,t,n){return`${e}::${t}::${n}`}var D={NODE_NOT_FOUND:"NODE_NOT_FOUND",HOME_PAGE_LOCKED:"HOME_PAGE_LOCKED",ROUTE_NOT_FOUND:"ROUTE_NOT_FOUND",CAPABILITY_REJECTED:"CAPABILITY_REJECTED",CONSTRAINT_VIOLATED:"CONSTRAINT_VIOLATED",INVALID_PARAMS:"INVALID_PARAMS",PLAN_FAILED:"PLAN_FAILED",TRANSACTION_PREFLIGHT_FAILED:"TRANSACTION_PREFLIGHT_FAILED",ROUTE_REBUILD_FAILED:"ROUTE_REBUILD_FAILED",HISTORY_COMMIT_FAILED:"HISTORY_COMMIT_FAILED",MATERIALIZATION_CONFLICT:"MATERIALIZATION_CONFLICT",MATERIALIZATION_REJECTED:"MATERIALIZATION_REJECTED",MUTATION_ASSERTION_REQUIRED:"MUTATION_ASSERTION_REQUIRED",MUTATION_ASSERTION_INVALID:"MUTATION_ASSERTION_INVALID",VERSION_STALE:"VERSION_STALE",AST_PARSE_ERROR:"AST_PARSE_ERROR",UNSUPPORTED_OPERATION:"UNSUPPORTED_OPERATION",LOCATOR_FAILED:"LOCATOR_FAILED",INVALID_TARGET:"INVALID_TARGET",WRITE_IO_ERROR:"WRITE_IO_ERROR",CONCURRENT_MODIFIED:"CONCURRENT_MODIFIED",ROLLBACK_FAILED:"ROLLBACK_FAILED",RECOVERY_REQUIRED:"RECOVERY_REQUIRED",RECOVERY_PERSIST_FAILED:"RECOVERY_PERSIST_FAILED",MUTATION_SESSION_REQUIRED:"MUTATION_SESSION_REQUIRED",LEASE_ASSERTION_INVALID:"LEASE_ASSERTION_INVALID",LEASE_ASSERTION_EXPIRED:"LEASE_ASSERTION_EXPIRED",LEASE_ASSERTION_SCOPE_MISMATCH:"LEASE_ASSERTION_SCOPE_MISMATCH",CROSS_PAGE_MOVE_UNSUPPORTED:"CROSS_PAGE_MOVE_UNSUPPORTED",INTERNAL_ERROR:"INTERNAL_ERROR"};import ns from"@babel/traverse";import*as x from"@babel/types";import*as q from"@babel/types";function ht(e,t={}){if(q.isTSAsExpression(e)||q.isTSSatisfiesExpression(e)||q.isTSNonNullExpression(e)||q.isTypeCastExpression(e)||q.isParenthesizedExpression(e))return ht(e.expression,t);if(q.isStringLiteral(e))return{status:"resolved",value:e.value};if(q.isNumericLiteral(e))return Number.isFinite(e.value)?{status:"resolved",value:e.value}:{status:"unresolved"};if(q.isBooleanLiteral(e))return{status:"resolved",value:e.value};if(q.isNullLiteral(e))return{status:"resolved",value:null};if(q.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?{status:"resolved",value:e.quasis[0].value.cooked??e.quasis[0].value.raw}:{status:"unresolved"};if(q.isIdentifier(e))return e.name==="undefined"&&!t.resolveIdentifier?{status:"undefined"}:t.resolveIdentifier?.(e.name)??{status:"unresolved"};if(q.isUnaryExpression(e)&&e.operator==="void"&&q.isNumericLiteral(e.argument)&&e.argument.value===0)return{status:"undefined"};if(q.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||q.isSpreadElement(r))return{status:"unresolved"};let o=ht(r,t);if(o.status!=="resolved")return{status:"unresolved"};n.push(o.value)}return{status:"resolved",value:n}}if(q.isObjectExpression(e)){let n=Object.create(null);for(let r of e.properties){if(!q.isObjectProperty(r)||r.computed||!q.isExpression(r.value))return{status:"unresolved"};let o=Ig(r.key);if(o===null)return{status:"unresolved"};let i=ht(r.value,t);if(i.status!=="resolved")return{status:"unresolved"};Object.defineProperty(n,o,{configurable:!0,enumerable:!0,value:i.value,writable:!0})}return{status:"resolved",value:n}}return q.isMemberExpression(e)||q.isOptionalMemberExpression(e)?t.resolveMember?.(e)??{status:"unresolved"}:{status:"unresolved"}}function Ig(e){return q.isIdentifier(e)?e.name:q.isStringLiteral(e)?e.value:q.isNumericLiteral(e)?String(e.value):null}import{createHash as Ag}from"node:crypto";import*as gl from"@babel/parser";function rn(e,t,n,r){return{code:e,message:t,locatorKind:n,details:r}}function B(e,t,n,r,o){return{ok:!1,source:e,diagnostic:rn(t,n,r,o)}}function Yi(e,t,n,r,o){return{ok:!1,source:e,diagnostic:rn(t,n,r,o)}}var kg={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function yt(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:gl.parse(t,{sourceType:"module",plugins:kg[n]})}}catch(r){return{ok:!1,source:t,diagnostic:rn("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function Zi(e,t){return yt({source:e,profile:hl(t.kind)})}function Qi(e,t){return yt({source:e,profile:hl(t)})}function hl(e){return"next-app-entry"}function on(e){let{filePath:t,source:n}=e,r=t.toLowerCase().split(".").pop()??"";return r==="tsx"?"tsx-module":r==="ts"?"ts-module":r==="jsx"||r==="js"||r===""&&/<\w[\s\S]*>/.test(n)?"tsx-module":"next-app-entry"}import*as Cg from"@babel/parser";import*as wn from"@babel/types";import*as Mt from"node:path";var qi=[".tsx",".ts",".jsx",".js"],Rg=qi.map(e=>`/index${e}`),wg=new Set(["json","css","scss","sass","less","svg","png","jpg","jpeg","gif","webp","avif","ico","bmp","woff","woff2","ttf","otf","eot","mp4","webm","mp3","wav","ogg","pdf","txt","md","csv","xml","yaml","yml"]);function yl(e){let t=e.replace(/[?#].*$/,""),n=/\.([a-z0-9]+)$/i.exec(t);return n!==null&&wg.has(n[1].toLowerCase())}function xl(e){let t=[];for(let n of e.program.body)wn.isImportDeclaration(n)&&typeof n.source.value=="string"&&xt(n.source.value)&&t.push(n.source.value),wn.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&xt(n.source.value)&&t.push(n.source.value),wn.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&xt(n.source.value)&&t.push(n.source.value);return es(e.program,t),t}function es(e,t){if(!e||typeof e!="object")return;let n=e;if(n.type==="CallExpression"&&n.callee?.type==="Import"){let r=n.arguments?.[0];r?.type==="StringLiteral"&&typeof r.value=="string"&&xt(r.value)&&t.push(r.value)}for(let r of Object.values(n))if(Array.isArray(r))for(let o of r)es(o,t);else r&&typeof r=="object"&&es(r,t)}function xt(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function tr(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=Mt.dirname(e);return Mt.join(n,t).replace(/\\/g,"/")}async function Ng(e,t){if(qi.some(n=>e.endsWith(n))&&await t(e))return e;for(let n of qi){let r=`${e}${n}`;if(await t(r))return r}for(let n of Rg){let r=`${e}${n}`;if(await t(r))return r}return null}async function Nn(e,t,n){let r=await lo(e,t,n);return r.ok?r.path:null}async function lo(e,t,n){let r=tr(e,t);try{if(!Pg(e,t,r))return{ok:!1,diagnostic:{path:r,code:"import-not-found",message:`Local import not found: ${t}`,details:{fromFile:e,specifier:t}}};let o=await Ng(r,n);return o?{ok:!0,path:o}:{ok:!1,diagnostic:{path:r,code:"import-not-found",message:`Local import not found: ${t}`,details:{fromFile:e,specifier:t}}}}catch(o){return{ok:!1,diagnostic:{path:r,code:"import-resolve-failed",message:`Failed to resolve local import: ${t}`,details:{fromFile:e,specifier:t,reason:o instanceof Error?o.message:String(o)}}}}}function Pg(e,t,n){if(!xt(t)||t.includes("\0")||t.includes("\\")||Mt.posix.isAbsolute(n))return!1;let r=Mt.posix.normalize(n);if(r===".."||r.startsWith("../"))return!1;if(t.startsWith("@/")){let o=t.slice(2);return o.length>0&&!o.split("/").some(i=>i==="..")}return!Mt.posix.isAbsolute(e)}var nr=(e,t)=>{let n=yt({source:t,profile:on({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${Ag("sha256").update(t).digest("hex")}`,ast:n.ast,imports:xl(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};var uo="components/ui";function sn(e){if(!e)return!1;let t=ts(e);return t===uo||t.startsWith(`${uo}/`)||t.includes(`/${uo}/`)||t.endsWith(`/${uo}`)}function rr(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?sn(e.slice(2)):e.startsWith("./")||e.startsWith("../")?sn(ts(`${Tg(t)}/${e}`)):sn(e):!1}function ts(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 Tg(e){let t=ts(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}var _g=typeof ns=="function"?ns:ns.default;function Fe(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 Fg(e){return/^[A-Z]/.test(e)}function as(e){let t=e.openingElement;return x.isJSXIdentifier(t.name)?t.name.name==="Fragment":x.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function An(e){return x.isJSXFragment(e)}function Sl(e){return x.isJSXIdentifier(e.name)?e.name.name:x.isJSXMemberExpression(e.name)?El(e.name):x.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function El(e){return x.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:x.isJSXMemberExpression(e.object)?`${El(e.object)}.${e.property.name}`:e.property.name}function Og(e){return e.split(".")[0]??e}function Mg(e){let t=e;for(;t;){let n=t.node;if(x.isFunctionDeclaration(n)&&n.id||x.isVariableDeclarator(n)&&x.isIdentifier(n.id))return n.id.name;if(x.isExportDefaultDeclaration(n)){let r=n.declaration;if(x.isFunctionDeclaration(r)&&r.id)return r.id.name;if(x.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function Dg(){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 Lg(e){let t=new Map;for(let n of e.program.body){if(!x.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(x.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(x.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(x.isImportSpecifier(o)){let i=x.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function Ct(e,t=[]){if(x.isIdentifier(e))return t.push(e.name),t;if(x.isObjectPattern(e)){for(let n of e.properties)x.isObjectProperty(n)?Ct(n.value,t):x.isRestElement(n)&&Ct(n.argument,t);return t}if(x.isArrayPattern(e)){for(let n of e.elements)n&&(x.isRestElement(n)?Ct(n.argument,t):Ct(n,t));return t}return x.isAssignmentPattern(e)?(Ct(e.left,t),t):(x.isRestElement(e)&&Ct(e.argument,t),t)}function it(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function or(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 Bg(e,t,n){e.set(t,{resolved:!0,value:n})}function cs(e,t){e.set(t,{resolved:!1})}function vl(e,t){let n=e;for(let r of t){if(r.kind==="property"){if(n==null||Array.isArray(n)||typeof n!="object"||!(r.name in n))return{kind:"known-empty"};n=n[r.name];continue}if(!Array.isArray(n)||r.index<0||r.index>=n.length)return{kind:"known-empty"};n=n[r.index]}return{kind:"resolved",value:n}}function Ne(e,t,n){if(x.isTSAsExpression(e)||x.isTSSatisfiesExpression(e)||x.isTSNonNullExpression(e)||x.isTypeCastExpression(e)||x.isParenthesizedExpression(e))return Ne(e.expression,t,n);if(x.isLogicalExpression(e))return fo([Ne(e.left,t,n),Ne(e.right,t,n)]);if(x.isBinaryExpression(e))return fo([x.isExpression(e.left)?Ne(e.left,t,n):null,x.isExpression(e.right)?Ne(e.right,t,n):null]);if(x.isConditionalExpression(e))return fo([Ne(e.consequent,t,n),Ne(e.alternate,t,n)]);if(x.isTemplateLiteral(e))return fo(e.expressions.filter(x.isExpression).map(i=>Ne(i,t,n)));if(x.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!x.isMemberExpression(e)&&!x.isOptionalMemberExpression(e))return null;let r=[],o=e;for(;x.isMemberExpression(o)||x.isOptionalMemberExpression(o);){if(o.computed)if(x.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(x.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&x.isExpression(o.property)){let i=Lt(o.property,n);if(typeof i=="string")r.unshift({kind:"property",name:i});else if(Number.isInteger(i))r.unshift({kind:"index",index:i});else return null}else return null;else{if(!x.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return x.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:it(e,t),base:o.name,path:r}:null}function fo(e){let t=e.filter(r=>r!==null);if(t.length===0)return null;let n=t[0];return t.some(r=>r.base!==n.base||JSON.stringify(r.path)!==JSON.stringify(n.path))?null:{...n}}function Lt(e,t){if(x.isStringLiteral(e)||x.isNumericLiteral(e)||x.isBooleanLiteral(e))return e.value;if(x.isNullLiteral(e))return null;if(x.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(x.isIdentifier(e)){let n=or(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(x.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||x.isSpreadElement(r))return;let o=Lt(r,t);if(o===void 0)return;n.push(o)}return n}if(x.isObjectExpression(e)){let n={};for(let r of e.properties){if(!x.isObjectProperty(r)||r.computed||!x.isExpression(r.value))return;let o=null;if(x.isIdentifier(r.key)?o=r.key.name:x.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!x.isIdentifier(r.value))return;let s=or(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=Lt(r.value,t);if(i===void 0)return;n[o]=i}return n}if(x.isMemberExpression(e)){let n=Ne(e,"",t);if(!n)return;let r=or(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=vl(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(x.isCallExpression(e))return kl(e,t)??void 0}function Il(e,t,n){let r=Ne(e,n,t);if(!r)return x.isMemberExpression(e)||x.isBinaryExpression(e)||x.isLogicalExpression(e)||x.isConditionalExpression(e)||x.isCallExpression(e)?{value:it(e,n),source:null}:null;let o=or(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?vl(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 rs(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:Dg(),parentStack:[],valueScopes:i,importMap:o}}function is(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of Ct(o.id))cs(n,s);if(!x.isIdentifier(o.id)||!o.init||!x.isExpression(o.init))continue;let i=Lt(o.init,t);i!==void 0&&Bg(n,o.id.name,i)}}function jg(e){let t=[];for(let n of e){if(x.isVariableDeclaration(n)){t.push(n);continue}x.isExportNamedDeclaration(n)&&n.declaration&&x.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function $g(e,t,n){let r=[],o=0;for(let i of e)if(x.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:Fe(i),editable:!0,source:null})}else if(x.isJSXExpressionContainer(i)&&x.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:Fe(i),editable:!0,source:null});else if(x.isJSXExpressionContainer(i)&&x.isTemplateLiteral(i.expression)){let s=i.expression;s.expressions.length===0&&s.quasis.length===1?r.push({index:o++,value:s.quasis[0].value.cooked??s.quasis[0].value.raw,sourceRange:Fe(i),editable:!0,source:null}):r.push({index:o++,value:it(s,n),sourceRange:Fe(i),editable:!0,source:Ne(s,n,t)})}else if(x.isJSXExpressionContainer(i)&&x.isExpression(i.expression)){let s=Il(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:Fe(i),editable:!0,source:s.source})}return r}function Vg(e,t,n){let r=[];for(let[o,i]of e.attributes.entries()){if(!x.isJSXAttribute(i))continue;let s=Kg(i.name);if(!s)continue;let a=it(i,n);if(x.isStringLiteral(i.value)){r.push({name:s,value:i.value.value,sourceRange:Fe(i),source:null,syntaxKind:"literal",raw:a,order:o,resolution:{status:"resolved",value:i.value.value}});continue}if(i.value===null){r.push({name:s,value:"true",sourceRange:Fe(i),source:null,syntaxKind:"boolean-shorthand",raw:a,order:o,resolution:{status:"resolved",value:!0},resolvedValue:!0});continue}if(x.isJSXExpressionContainer(i.value)&&x.isExpression(i.value.expression)){let c=Lt(i.value.expression,t);if(s==="className"){let m=typeof c=="string"?c:c===void 0?kl(i.value.expression,t):null;if(m){r.push({name:s,value:m,sourceRange:Fe(i),source:null,resolvedValue:m,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:m}});continue}}let l=Il(i.value.expression,t,n);if(c!==void 0){r.push({name:s,value:Yg(c),sourceRange:Fe(i),source:Ne(i.value.expression,n,t),resolvedValue:c,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:c}});continue}let u=Jg(i.value.expression,t),d=Ne(i.value.expression,n,t),p=l?.value??it(i.value.expression,n);r.push({name:s,value:u.status==="undefined"?"undefined":p,sourceRange:Fe(i),source:l?.source??d,syntaxKind:"expression",raw:a,order:o,resolution:u})}}return r}function Ug(e,t,n){return e.attributes.flatMap((r,o)=>!x.isJSXSpreadAttribute(r)||!x.isExpression(r.argument)?[]:[{raw:it(r.argument,n),sourceRange:Fe(r),order:o,source:Ne(r.argument,n,t)}])}function Kg(e){return x.isJSXIdentifier(e)?e.name:x.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function Jg(e,t){return ht(e,{resolveIdentifier(n){let r=or(n,t.valueScopes);return r.kind==="resolved"?{status:"resolved",value:r.value}:n==="undefined"&&!t.valueScopes.some(o=>o.has(n))?{status:"undefined"}:{status:"unresolved"}},resolveMember(n){let r=Lt(n,t);return r===void 0?{status:"unresolved"}:{status:"resolved",value:r}}})}function kl(e,t){let n=Pn(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function Pn(e,t){if(x.isStringLiteral(e))return[e.value];if(x.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(x.isNullLiteral(e))return[];if(x.isBooleanLiteral(e))return e.value?null:[];if(x.isIdentifier(e)||x.isMemberExpression(e)){if(x.isIdentifier(e)&&e.name==="undefined")return[];let n=Lt(e,t);return typeof n=="string"?[n]:null}if(x.isConditionalExpression(e)){let n=Pn(e.consequent,t),r=Pn(e.alternate,t);return!n||!r?null:[...n,...r]}if(x.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=Lt(e.left,t);return n===!1||n===null?[]:Pn(e.right,t)}if(x.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||x.isSpreadElement(r))return null;let o=Pn(r,t);if(!o)return null;n.push(...o)}return n}if(x.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!x.isObjectProperty(r))return null;let o=zg(r.key);if(!o)return null;n.push(o)}return n}if(x.isCallExpression(e)){let n=Xg(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!x.isExpression(o))return null;let i=Pn(o,t);if(!i)return null;r.push(...i)}return r}return null}function Xg(e){return x.isIdentifier(e)?e.name:x.isMemberExpression(e)&&x.isIdentifier(e.property)?e.property.name:null}function zg(e){return x.isIdentifier(e)?e.name:x.isStringLiteral(e)?e.value:null}function Wg(e,t){let n=e.attributes.find(r=>x.isJSXAttribute(r)&&x.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!x.isJSXAttribute(n)||!x.isJSXExpressionContainer(n.value)?null:n.value.expression}function Hg(e,t){for(let n of t){let r=Wg(e,n);if(r)return r}return null}function Gg(e){return x.isJSXIdentifier(e.name)?e.name.name:null}function Yg(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function Zg(e){if(!x.isCallExpression(e)&&!x.isOptionalCallExpression(e))return null;let t=e.callee;return!x.isMemberExpression(t)&&!x.isOptionalMemberExpression(t)||!x.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!x.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function os(e){return x.isArrowFunctionExpression(e)||x.isFunctionExpression(e)}function Qg(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function qg(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function bl(e,t,n,r){if(!e||!x.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:it(e,n),collectionSource:Ne(e,n,r)};if(t){let i=t.params[0],s=t.params[1];x.isIdentifier(i)&&(o.itemParamName=i.name),x.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function Dt(e,t,n){if(!e)return[];if(x.isJSXElement(e)){if(as(e))return yo(e.children,t,n);let r=go(e,t,n);return r?[r]:[]}return An(e)?ho(e,t,n):x.isParenthesizedExpression(e)?Dt(e.expression,t,n):x.isExpression(e)?xo(e,t,n):[]}function po(e,t,n){let r=new Map;for(let o of e.params)for(let i of Ct(o))cs(r,i);t.valueScopes.push(r);try{if(!x.isBlockStatement(e.body))return Dt(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return Cl(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function Cl(e,t,n){let r=[];for(let o of e){if(x.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];i&&is([o],t,i);continue}r.push(...ss(o,t,n))}return r}function ss(e,t,n){if(x.isReturnStatement(e))return e.argument?Dt(e.argument,t,n):[];if(x.isBlockStatement(e))return an(e.body,t,n);if(x.isIfStatement(e)){let r=x.isBlockStatement(e.consequent)?an(e.consequent.body,t,n):ss(e.consequent,t,n),o=e.alternate?x.isBlockStatement(e.alternate)?an(e.alternate.body,t,n):ss(e.alternate,t,n):[];return[...r,...o]}if(x.isSwitchStatement(e))return an(e.cases.flatMap(r=>r.consequent),t,n);if(x.isTryStatement(e)){let r=an(e.block.body,t,n);return e.handler&&r.push(...an(e.handler.body.body,t,n)),e.finalizer&&r.push(...an(e.finalizer.body,t,n)),r}return[]}function an(e,t,n){let r=new Map;t.valueScopes.push(r);try{return Cl(e,t,n)}finally{t.valueScopes.pop()}}function mo(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:Fe(r),sourceCandidates:i&&i.length>0?i:void 0})}function eh(e,t,n,r){let o=Hg(e.openingElement,["items","dataSource","data"]),i={key:t,tag:Sl(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!x.isJSXAttribute(s))continue;let a=Gg(s);if(!a||!x.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!x.isJSXEmptyExpression(c)){if(Qg(a)&&os(c)){let l=po(c,n,r),u=bl(o,c,r,n);mo(n,"repeat-region",t,s,l,u?[u]:void 0);continue}if(qg(a)){let l=os(c)?po(c,n,r):Dt(c,n,r);mo(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!x.isJSXExpressionContainer(s)||!os(s.expression))continue;let a=po(s.expression,n,r),c=bl(o,s.expression,r,n);mo(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function go(e,t,n){let r=Sl(e.openingElement);if(r==="Fragment"||as(e))return yo(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=Fg(r),a;if(s){let O=t.ordinalTracker.getOrdinal(i,r);a=`component:${r}#${O}`}else{let O=t.ordinalTracker.getOrdinal(i,r);a=`${r}#${O}`}let c=o?t.elements.get(o.key)?.identity.structuralPath:void 0,l=c?`${c}/${a}`:a,u=er(t.file,t.componentName,l),d={file:t.file,component:t.componentName,structuralPath:l,key:u},p=s?"component-boundary":null,m=$g(e.children,t,n),g=Vg(e.openingElement,t,n),b=Ug(e.openingElement,t,n),C,I,w=!1;if(s){let O=t.importMap.get(r)??t.importMap.get(Og(r));O&&(C=O.specifier,I=O.exportName,w=rr(O.specifier,t.file))}let A={identity:d,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:Fe(e),parentKey:i,childKeys:[],textSegments:m,attributes:g.length>0?g:void 0,attributeSpreads:b.length>0?b:void 0,boundaryKind:p,isOpaque:s,...w?{isPublicUiComponent:!0}:{},importedFrom:C,exportName:I};return t.elements.set(u,A),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(u),eh(e,u,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:u,tag:r}),th(e.children,t,n),t.parentStack.pop()),u}function ho(e,t,n){return yo(e.children,t,n)}function yo(e,t,n){let r=[];for(let o of e)if(x.isJSXElement(o))if(as(o))r.push(...yo(o.children,t,n));else{let i=go(o,t,n);i&&r.push(i)}else An(o)?r.push(...ho(o,t,n)):x.isJSXExpressionContainer(o)&&r.push(...xo(o.expression,t,n));return r}function th(e,t,n){for(let r of e)x.isJSXElement(r)?go(r,t,n):An(r)?ho(r,t,n):x.isJSXExpressionContainer(r)&&xo(r.expression,t,n)}function nh(e){return e==="&&"||e==="||"||e==="??"}function xo(e,t,n){if(x.isJSXEmptyExpression(e))return[];let r=Zg(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,c={kind:"repeat-template",collectionExpression:it(r.collection,n),collectionSource:Ne(r.collection,n,t)};if(x.isArrowFunctionExpression(a)||x.isFunctionExpression(a)){let u=a.params[0],d=a.params[1];x.isIdentifier(u)&&(c.itemParamName=u.name),x.isIdentifier(d)&&(c.indexParamName=d.name)}s.push(c);let l={kind:"repeat-region",ownerKey:i?.key??"",childKeys:[],sourceRange:Fe(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(l),(x.isArrowFunctionExpression(a)||x.isFunctionExpression(a))&&l.childKeys.push(...po(a,t,n)),l.childKeys}if(x.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:it(e.test,n),conditionSource:Ne(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Fe(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Dt(e.consequent,t,n)),s.childKeys.push(...Dt(e.alternate,t,n)),s.childKeys}if(x.isLogicalExpression(e)&&nh(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:it(e.left,n),conditionSource:Ne(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Fe(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Dt(e.right,t,n)),s.childKeys}if(x.isParenthesizedExpression(e))return xo(e.expression,t,n);if(x.isJSXElement(e)){let o=go(e,t,n);return o?[o]:[]}return An(e)?ho(e,t,n):[]}function rh(e){let t=e.argument;return t&&(x.isExpression(t)||An(t))?t:null}function ir(e,t){let n=[];for(let r of e){if(x.isReturnStatement(r)){let o=rh(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(x.isIfStatement(r)){let o=x.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...ir(o,r.test)),r.alternate){let i=x.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...ir(i,r.test))}continue}if(x.isSwitchStatement(r))for(let o of r.cases){let i=o.test?x.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...ir(o.consequent,i))}}return n}function Rl(e){let{file:t,source:n,ast:r}=e,o=e.imports.map(d=>d.specifier),i=new Map,s=[],a=[],c=new Map,l=Lg(r);_g(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(d){let p=Mg(d);if(!p)return;let m=d.node,g=[];if(x.isArrowFunctionExpression(m))x.isExpression(m.body)||An(m.body)?g=[{argument:m.body,statement:x.returnStatement(x.isExpression(m.body)?m.body:null)}]:x.isBlockStatement(m.body)&&(g=ir(m.body.body));else{let O=m.body;x.isBlockStatement(O)&&(g=ir(O.body))}if(g.length===0){d.skip();return}let b=new Map;is(jg(r.program.body),rs(t,p,i,s,l,[b]),b);let C=new Map;for(let O of m.params)for(let ie of Ct(O))cs(C,ie);let I=x.isBlockStatement(m.body)?m.body.body:[],w=g[0]?.statement??null;for(let O of I){if(w&&O===w)break;x.isVariableDeclaration(O)&&is([O],rs(t,p,i,s,l,[b,C]),C)}let A=rs(t,p,i,s,l,[b,C]);for(let O of g){let ie=Dt(O.argument,A,n);for(let oe of ie)a.includes(oe)||a.push(oe);if(O.condition){let oe={kind:"conditional-branch",conditionExpression:it(O.condition,n),conditionSource:Ne(O.condition,n,A)};mo(A,"conditional-region","",O.statement,ie,[oe])}}d.skip()}});let u=[...i.keys()];return u.length>0&&c.set(t,u),{graph:{routeId:t,rootKeys:a,elements:i,regions:s,fileIndex:c,version:1,diagnostics:[]},localImports:o}}function ls(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function bo(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function wl(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??nr,c=new Map,l=new Map,u=new Map,d=[],p=new Set,m=I=>{let w=`${I.path}\0${I.code}\0${I.message}\0${JSON.stringify(I.details??{})}`;p.has(w)||(p.add(w),d.push(I))},g=[{file:e,source:t,depth:0,diagnosticEntryFile:e,importStack:[]},...(o.additionalEntries??[]).map(I=>({file:I.file,source:I.source,depth:0,diagnosticEntryFile:I.file,importStack:[]}))],b=new Set;for(;g.length>0;){let I=g.shift(),{file:w,source:A,depth:O,diagnosticEntryFile:ie,importStack:oe}=I;if(b.has(w))continue;b.add(w),c.set(w,A);let N=a(w,A);if(!N.ok){m(bo(N.diagnostic,ie,oe));continue}u.set(w,N.module);let{graph:W,localImports:M}=Rl(N.module);for(let j of W.elements.values())if(j.importedFrom&&xt(j.importedFrom)){let Q=j.importedFrom,re=await lo(w,Q,r);re.ok?(j.importedFrom=re.path,sn(re.path)&&(j.isPublicUiComponent=!0)):rr(Q,w)||m(bo(re.diagnostic,ie,ls(oe,w,Q,re.diagnostic.path)))}if(l.set(w,W),!(O>=i))for(let j of M){if(yl(j))continue;let Q=await lo(w,j,r);if(!Q.ok){rr(j,w)||m(bo(Q.diagnostic,ie,ls(oe,w,j,Q.diagnostic.path)));continue}let re=Q.path;if(b.has(re)||sn(re))continue;let be=ls(oe,w,j,re);try{let G=await n(re);g.push({file:re,source:G,depth:O+1,diagnosticEntryFile:ie,importStack:be})}catch(G){m(bo({path:re,code:"import-read-failed",message:`Failed to read imported file: ${re}`,details:{fromFile:w,specifier:j,reason:G instanceof Error?G.message:String(G)}},ie,be))}}}let C=oh(e,l,s,(o.additionalEntries??[]).map(I=>I.file));return C.diagnostics=d,{graph:C,allSources:c,diagnostics:d,parsedModules:u,entryModule:u.get(e)??null}}function oh(e,t,n,r=[]){let o=new Map,i=[],s=new Map,a=[];for(let[c,l]of t){for(let[u,d]of l.elements)o.set(u,d);for(let u of l.regions)i.push(u);for(let[u,d]of l.fileIndex){let p=s.get(u)??[];s.set(u,[...p,...d])}if(c===e){a=l.rootKeys;continue}r.includes(c)&&(a=[...a,...l.rootKeys])}return{routeId:e,rootKeys:a,elements:o,regions:i,fileIndex:s,version:n}}function Nl(e){let t=new Map;for(let[n,r]of e.elements){let o=/^[A-Z]/.test(r.tag),i={file:r.sourceFile,componentName:r.componentName,isProxy:o},s=r.boundaryKind,a=[];r.isOpaque&&a.push({kind:"opaque-region",reason:`Component '${r.tag}' is opaque: internal structure not editable`}),o&&!r.isOpaque&&a.push({kind:"component-boundary",reason:`Component '${r.tag}' boundary: editing requires source file access`});let c={key:n,writeTarget:i,boundaryKind:s,parentKey:r.parentKey,childKeys:[...r.childKeys],constraints:a};t.set(n,c)}for(let n of e.regions){let r=n.kind==="repeat-region"?"repeat-region":n.kind==="conditional-region"?"conditional-region":n.kind==="opaque-region"?"opaque-region":"component-boundary",o=n.kind==="repeat-region"?"Node is inside a repeat region: operations affect the template, not individual instances":n.kind==="conditional-region"?"Node is inside a conditional region: visibility depends on runtime condition":`Node is inside a ${n.kind}`;for(let i of n.childKeys){let s=t.get(i);s&&s.constraints.push({kind:r,reason:o}),Pl(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function Pl(e,t,n,r,o){let i=o.elements.get(e);if(i)for(let s of i.childKeys){let a=r.get(s);a&&!a.constraints.some(c=>c.kind===t)&&(a.constraints.push({kind:t,reason:n}),Pl(s,t,n,r,o))}}import{isSiteEditRuntimeContainerTag as ih,isSiteEditRuntimeVoidElementTag as sh}from"@vcp-dev/contracts/site-edit-runtime-capability";function Tn(e){if(!e.composition)throw new Error("Composition unavailable for render source graph.");return e.composition}function ah(e,t,n){let r=Tn(n),o=t.nodes.get(e),i=n.elements.get(e);if(!o||!i)return{composition:r,key:e,canUpdateText:!1,canInsertChild:!1,canMove:!1,canRemove:!1,constraints:[{kind:"opaque-region",message:"Node not found in graph"}]};let s=o.constraints.map(O=>({kind:O.kind,message:O.reason})),a=i.isOpaque,l=o.parentKey===null&&i.componentName==="Page",u=i.tag.toLowerCase(),d=i.tag!==u,p=!d&&sh(u),m=d||ih(u),g=d&&i.childKeys.length>0&&!i.isPublicUiComponent,b=i.textSegments.length>0&&i.textSegments.some(O=>O.editable);p&&!s.some(O=>O.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' is void: children cannot be inserted`}),!p&&!m&&!s.some(O=>O.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' cannot contain structured children`});let C=b&&(!a||i.importedFrom==="next/link"),I=!i.isPublicUiComponent&&!p&&m&&(!a||g);return{composition:r,key:e,canUpdateText:C,canInsertChild:I,canMove:!l,canRemove:!l,constraints:s}}function Al(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,ah(r,e,t));return n}import{createHash as Bs}from"node:crypto";import _s from"@babel/traverse";function us(e){let t=new Map,n=new Map;for(let s of e){if(t.has(s.placementKey))throw new Error(`Duplicate placement key in page composition projection: ${s.placementKey}`);t.set(s.placementKey,s);let a=n.get(s.placementUnitKey)??[];a.push(s),n.set(s.placementUnitKey,a)}let r=new Map,o=new Map,i=new Map;for(let[s,a]of n){let c=Object.freeze([...a]),l=c.find(u=>u.anchorSourceRange!==null&&u.members.length>0)??c.find(u=>u.members.length>0)??c[0];l&&(o.set(s,c),i.set(s,l),r.set(s,Object.freeze({placementUnitKey:s,placementKeys:Object.freeze(c.map(u=>u.placementKey)),sourcePlacementKey:l.placementKey})))}return{placementByKey:t,unitByKey:r,placementsByUnitKey:o,sourcePlacementByUnitKey:i}}import{createHash as Uy}from"node:crypto";import au from"node:path";import*as jo from"@babel/parser";import Rs from"@babel/generator";import ws from"@babel/traverse";import*as Ut from"@babel/types";import ds from"@babel/traverse";var jt=typeof ds=="function"?ds:ds.default,So=new WeakMap,Tl=new WeakMap;function wt(e,t){let n=Zi(e,t);if(!n.ok)return Yi(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=ne(n.ast,t);return r.ok?{ok:!0,match:{locatorKind:r.match.locatorKind,node:r.match.node,start:r.match.start,end:r.match.end}}:Yi(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function ne(e,t){return t.kind==="jsx-node"?Ml(e,t):t.kind==="jsx-attribute"?ph(e,t):t.kind==="value"?mh(e,t):t.kind==="expression"?gh(e,t):t.kind==="directive"?hh(e,t):t.kind==="export"?yh(e,t):{ok:!1,diagnostic:rn("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function Ml(e,t){return t.strategy==="source-range"?ch(e,t):lh(e,t)}function ch(e,t){let n=null;if(jt(e,{JSXElement(o){if(!_n(o.node,t.sourceRange))return;let i=Ce("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!_n(o.node,t.sourceRange))return;let i=Ce("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!_n(o.node,t.sourceRange))return;let i=Ce("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)}}),!n)return Re("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!Ph(r.path,t.expectedIdentity)?Re("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function lh(e,t){if(t.structuralPath===""){let r=dh(e,t.component);if(r){let o=fh(r);if(o)return o}}let n=null;return jt(e,{JSXElement(r){if(ar(r)!==t.component||ps(r)!==t.structuralPath)return;let i=Ce("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(ar(r)!==t.component||ps(r)!==t.structuralPath)return;let i=Ce("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=uh(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:Re("jsx-node","locator-miss","JSX node not found for structural-path locator")}function uh(e,t,n){let r=null;return jt(e,{JSXElement(o){if(ar(o)!==t||!_n(o.node,n))return;let i=Ce("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(ar(o)!==t||!_n(o.node,n))return;let i=Ce("jsx-node",o);i&&(r=i,o.stop())}}),r}function dh(e,t){let n=null;return jt(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 fh(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 Re("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?Re("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 Re("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function ph(e,t){let n=Ml(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>Ah(c,t.name));if(!s||!s.isJSXAttribute())return Re("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=Ce("jsx-attribute",s);return a?{ok:!0,match:a}:Re("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function mh(e,t){let n=xh(e,t);if(!n.ok)return n;let r=bh(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!Rt(r.match.path.node.loc,t.expectedRange)?Re("value","locator-miss","Resolved value does not match expected range"):{ok:!0,match:r.match}:r}function gh(e,t){let n=null;return jt(e,{Identifier(r){if(!Ch(r))return;let o=Fl(r);if(!o||!Ol(o,t))return;let i=Ce("expression",r);i&&(t.expectedRange&&!Rt(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=Fl(r);if(!o||!Ol(o,t))return;let i=Ce("expression",r);i&&(t.expectedRange&&!Rt(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Re("expression","locator-miss","Expression not found")}function hh(e,t){let n=null;return jt(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!Rt(i.node.loc,t.expectedRange))return;let s=Ce("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:Re("directive","locator-miss",`Directive '${t.value}' not found`)}function yh(e,t){let n=null;return jt(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let c=r.get("declaration");if(c.isFunctionDeclaration()&&c.node.id?.name==="generateMetadata"){let p=Ce("export",c);if(!p||t.expectedRange&&!Rt(c.node.loc,t.expectedRange))return;n=p,r.stop();return}if(!c.isVariableDeclaration())return;let l=ms(c,"generateMetadata");if(!l||!l.isVariableDeclarator())return;let u=l.get("init");if(!u.node)return;let d=Ce("export",u);if(!d||t.expectedRange&&!Rt(u.node.loc,t.expectedRange))return;n=d,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=ms(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!Rt(s.node.loc,t.expectedRange))return;let a=Ce("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=Ce("export",o);i&&(t.expectedRange&&!Rt(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Re("export","export-not-found",`Export '${Nh(t)}' not found`)}function xh(e,t){let n=null;return jt(e,{Expression(r){if(n||t.root.kind!=="expression"||!_n(r.node,t.root.sourceRange))return;let o=Ce("value",r);o&&(n=o,r.stop())},VariableDeclarator(r){if(n)return;if(t.root.kind==="binding"){if(r.node.id.type!=="Identifier"||r.node.id.name!==t.root.name)return;let m=r.get("init");if(!m.node)return;let g=Ce("value",m);if(!g)return;n=g,r.stop();return}if(t.root.kind!=="hook-state")return;let o=t.root,i=r.get("id"),s=r.get("init");if(!i.isArrayPattern()||!s.isCallExpression()||i.node.elements.findIndex(m=>m?.type==="Identifier"&&m.name===o.name)!==0)return;let c=s.node.callee;if((c.type==="Identifier"?c.name:c.type==="MemberExpression"&&c.property.type==="Identifier"?c.property.name:null)!==o.hook)return;let u=o.hook==="useReducer"?1:0,d=r.get(`init.arguments.${u}`);if(!d||Array.isArray(d)||!d.node)return;let p=Ce("value",d);p&&(n=p,r.stop())},ExportNamedDeclaration(r){if(n||t.root.kind!=="named-export")return;let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=ms(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=Ce("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=Ce("value",o);i&&(n=i,r.stop())}}),n?{ok:!0,match:n}:Re("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 bh(e,t){let n=fs(e);for(let o of t){if(n=fs(n),o.kind==="property"){if(!n.isObjectExpression())return Re("value","unsupported-syntax","Property path requires object expression");let a=n.get("properties");if(a.some(l=>!l.isObjectProperty()))return Re("value","unsupported-syntax","Spread properties are not supported");let c=a.find(l=>Th(l,o.name));if(!c||!c.isObjectProperty())return Re("value","property-not-found",`Property '${o.name}' not found`);n=c.get("value");continue}if(!n.isArrayExpression())return Re("value","unsupported-syntax","Array index path requires array expression");let i=n.get("elements");if(i.some(a=>a.node?.type==="SpreadElement"))return Re("value","unsupported-syntax","Spread array elements are not supported");let s=i[o.index];if(!s?.node)return Re("value","array-index-out-of-range",`Array index ${o.index} is out of range`);n=s}n=fs(n);let r=Ce("value",n);return r?{ok:!0,match:r}:Re("value","locator-miss","Resolved value has no source range")}function fs(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function Ce(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 _n(e,t){return Rt(e.loc,t)}function Rt(e,t){return e?e.start.line===t.startLine&&e.start.column===t.startColumn&&e.end.line===t.endLine&&e.end.column===t.endColumn:!1}function ps(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!Eo(n.node)){let o=Dl(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${_l(n,o)}`):t.unshift(`${o}#${_l(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||Ih(n.parentPath)&&!kh(n.parentPath))break;n=n.parentPath}return t.join("/")}function Eo(e){let t=e.openingElement.name;return t.type==="JSXIdentifier"?t.name==="Fragment":t.type==="JSXMemberExpression"&&t.property.name==="Fragment"}function _l(e,t){let n=Sh(e);if(!n)return 0;let r=So.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=So.get(n.node)?.get(t);if(!i){let s=So.get(n.node);s||(s=new Map,So.set(n.node,s)),i=new WeakMap,s.set(t,i)}for(let s of sr(n))if(Dl(s.node.openingElement)===t){if(i.set(s.node,o),s.node===e.node)return o;o++}return i.get(e.node)??0}function Sh(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Eo(t.node)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function sr(e){let t=Tl.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(Eo(o.node)){n.push(...sr(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...sr(o));continue}o.isJSXExpressionContainer()&&n.push(...Bt(o.get("expression")))}return Tl.set(e.node,n),n}function Bt(e){if(e.isJSXElement())return Eo(e.node)?sr(e):[e];if(e.isJSXFragment())return sr(e);if(e.isParenthesizedExpression())return Bt(e.get("expression"));if(e.isLogicalExpression()&&Eh(e.node.operator))return Bt(e.get("right"));if(e.isCallExpression()||e.isOptionalCallExpression()){let t=e.get("callee"),n=!Array.isArray(t)&&(t.isMemberExpression()||t.isOptionalMemberExpression())?t.get("property"):null;if(!Array.isArray(t)&&(t.isMemberExpression()||t.isOptionalMemberExpression())&&!t.node.computed&&n!==null&&!Array.isArray(n)&&n.isIdentifier()&&n.node.name==="map"){let r=e.get("arguments").find(o=>!Array.isArray(o)&&(o.isArrowFunctionExpression()||o.isFunctionExpression()));if(r&&!Array.isArray(r)){let o=r.get("body");if(!Array.isArray(o)){if(o.isBlockStatement()){let i=o.get("body").find(s=>!Array.isArray(s)&&s.isReturnStatement());if(i&&!Array.isArray(i)){let s=i.get("argument");if(!Array.isArray(s)&&s.node&&s.isExpression())return Bt(s)}}else if(o.node&&o.isExpression())return Bt(o)}}}}return e.isConditionalExpression()?[...Bt(e.get("consequent")),...Bt(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Bt(t)):[]}function Eh(e){return e==="&&"||e==="||"||e==="??"}function Dl(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?vh(e.name):null}function vh(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 ar(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 Ih(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function kh(e){let t=e.parentPath;if(!t||!t.isCallExpression()&&!t.isOptionalCallExpression())return!1;let n=t.get("callee"),r=!Array.isArray(n)&&(n.isMemberExpression()||n.isOptionalMemberExpression())?n.get("property"):null;if(Array.isArray(n)||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.computed||r===null||Array.isArray(r)||!r.isIdentifier()||r.node.name!=="map")return!1;let o=t.get("arguments");return Array.isArray(o)?o.some(i=>!Array.isArray(i)&&i.node===e.node):!1}function Ch(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function Fl(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 Ol(e,t){return e.base===t.base&&Rh(e.path,t.path??[])}function Rh(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 wh(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function Nh(e){return e.exportKind==="named"?e.name:e.exportKind}function Re(e,t,n,r){return{ok:!1,diagnostic:rn(t,n,e,r)}}function Ph(e,t){return ar(e)!==t.component?!1:ps(e)===t.structuralPath}function Ah(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function ms(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function Th(e,t){return e.isObjectProperty()?wh(e.node)===t:!1}import gs from"@babel/generator";var _h=typeof gs=="function"?gs:gs.default;function Fh(e){let t=e.split(`
2
- `),n=[],r=!1;for(let s of t){let a=s.match(/^(\s+)/);if(a){let c=a[1];c.includes(" ")?r=!0:c.length>0&&n.push(c.length)}}if(r&&t.every(a=>{let c=a.match(/^(\s+)/);return!c||c[1].includes(" ")}))return"tab";if(n.length===0)return"2";function o(s,a){return a===0?s:o(a,s%a)}let i=n[0];for(let s=1;s<n.length;s++)i=o(i,n[s]);return i>=4?"4":"2"}function Oh(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 Mh(e,t){return e.split(`
3
- `).map(r=>Oh(r,t)).join(`
4
- `)}function vo(e){let{ast:t,source:n}=e;try{let r=Fh(n),i=_h(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=Mh(i,r)),{ok:!0,source:i}}catch(r){return B(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}import*as Bl from"@babel/parser";import{arrayExpression as Dh,booleanLiteral as Lh,identifier as Bh,jsxAttribute as jh,jsxExpressionContainer as $h,jsxIdentifier as Vh,nullLiteral as Uh,numericLiteral as Kh,objectExpression as Jh,objectProperty as Xh,stringLiteral as hs}from"@babel/types";function Ll(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 cr(e,t,n){return{ok:!0,source:t,operation:{type:n.kind,nodeId:n.target,kind:n.kind,target:n.target,beforeSourceHash:Ll(e),afterSourceHash:Ll(t),inverse:n.inverse}}}function ae(e,t,n){let r=vo({ast:e,source:t});return r.ok?cr(t,r.source,n):r}function ge(e,t){let n=Qi(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function Io(e,t){return vo({ast:e,source:t})}function zh(e,t,n){let r=ne(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function ko(e,t,n){let r=zh(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:B(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function $t(e){return typeof e=="string"?hs(e):typeof e=="number"?Kh(e):typeof e=="boolean"?Lh(e):e===null?Uh():Array.isArray(e)?Dh(e.map(t=>$t(t))):Jh(Object.entries(e).map(([t,n])=>{let r=Xh(ys(t),$t(n));return t==="__proto__"&&(r.computed=!0),r}))}function Wh(e){return typeof e=="string"?hs(e):$h($t(e))}function lr(e,t){return jh(Vh(e),Wh(t))}function Co(e,t){try{let r=Bl.parse(`const __VD_NODE__ = (${t});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0];return r?.type!=="VariableDeclaration"||r.declarations[0]?.type!=="VariableDeclarator"||!r.declarations[0].init||r.declarations[0].init.type!=="JSXElement"&&r.declarations[0].init.type!=="JSXFragment"?{ok:!1,result:B(e,"unsupported-syntax","Provided JSX source does not resolve to a JSX node","jsx-node")}:{ok:!0,node:r.declarations[0].init}}catch(n){return{ok:!1,result:B(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function ys(e){return/^[$A-Z_][0-9A-Z_$]*$/i.test(e)?Bh(e):hs(e)}function Ro(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=ge(t,"jsx-node");if(!i.ok)return i.result;let s=ne(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let c=Hh(s.match.path)[r];if(!c)return B(t,"locator-miss",`Text segment ${r} not found`,"jsx-node");switch(c.kind){case"jsx-text":c.path.node.value=Gh(c.path.node.value,o);break;case"string-literal":c.path.node.value=o;break;case"template-literal":{let l=c.quasiIndex;c.path.node.quasis[l].value.raw=o,c.path.node.quasis[l].value.cooked=o;break}}return ae(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function Hh(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=Yh(r.get("expression"));o.length>0&&t.push(...o)}}return t}function Gh(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function Yh(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 xs}from"@babel/types";function Fn(e){let{source:t,locator:n}=e,r=ge(t,"jsx-node");if(!r.ok)return r.result;let o=ne(r.ast,n);return o.ok?(Zh(o.match.path),ae(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function Zh(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(xs());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(xs());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(xs());return}e.remove()}import{cloneNode as Qh}from"@babel/types";function wo(e){let t=ge(e.source,"jsx-node");if(!t.ok)return t.result;let n=ne(t.ast,e.locator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};let r=Co(e.source,e.node.jsx);return r.ok?(n.match.path.replaceWith(Qh(r.node,!0)),ae(t.ast,e.source,{kind:"replace-node",target:"jsx-node",inverse:"replace-node"})):r.result}import{cloneNode as ly}from"@babel/types";import bs from"@babel/traverse";import*as X from"@babel/types";var qh=typeof bs=="function"?bs:bs.default;function Qe(e,t,n,r){if(!e.ok)return e;let o=Ze(n);if(!o)return e;let i=ey(t,o,r);return i?{...e,selectionRef:i}:e}function ey(e,t,n){let r=ty(e,t);if(!r)return;let o=n.sourceLocator?jl(n.sourceLocator):void 0,i=n.targetParentLocator?jl(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??ry(r)??i?.component??o?.component;if(!(!s||!a))return{key:er(s,a,oy(r))}}function jl(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function ty(e,t){let n=null;return qh(e,{JSXElement(r){r.node===t&&(n=r,r.stop())}}),n}function Ze(e){if(!e)return null;if(X.isJSXElement(e))return On(e)?$l(e.children):e;if(X.isJSXFragment(e))return $l(e.children);if(X.isJSXExpressionContainer(e)||X.isParenthesizedExpression(e)||X.isTSAsExpression(e)||X.isTSSatisfiesExpression(e)||X.isTSTypeAssertion(e)||X.isTSNonNullExpression(e))return Ze(e.expression);if(X.isLogicalExpression(e))return Ze(e.right);if(X.isConditionalExpression(e))return Ze(e.consequent)??Ze(e.alternate);if(X.isCallExpression(e)||X.isOptionalCallExpression(e))return Xl(e)?ny(e.arguments[0]):null;if(X.isArrayExpression(e))for(let t of e.elements){if(!t)continue;let n=Ze(t);if(n)return n}return null}function $l(e){for(let t of e){let n=Ze(t);if(n)return n}return null}function ny(e){return!e||!X.isArrowFunctionExpression(e)&&!X.isFunctionExpression(e)?null:X.isBlockStatement(e.body)?ur(e.body.body):Ze(e.body)}function ur(e){for(let t of e){if(X.isReturnStatement(t)){let n=Ze(t.argument);if(n)return n;continue}if(X.isBlockStatement(t)){let n=ur(t.body);if(n)return n;continue}if(X.isIfStatement(t)){let n=Vl(t.consequent);if(n)return n;let r=t.alternate?Vl(t.alternate):null;if(r)return r;continue}if(X.isSwitchStatement(t))for(let n of t.cases){let r=ur(n.consequent);if(r)return r}}return null}function Vl(e){return X.isBlockStatement(e)?ur(e.body):ur([e])}function ry(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(X.isFunctionDeclaration(n))return n.id?.name??"default"}if(t.isVariableDeclarator()&&X.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 Ul=new WeakMap,Kl=new WeakMap,Ss=new WeakMap;function oy(e){let t=Ul.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=iy(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return Ul.set(e.node,o),o}function iy(e){let t=Es(e.node.openingElement.name);return!t||On(e.node)?null:/^[A-Z]/.test(t)?`component:${t}#${Jl(e,t)}`:`${t}#${Jl(e,t)}`}function Jl(e,t){let n=sy(e);if(!n)return 0;let r=Ss.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Ss.get(n.node);o||(o=new Map,Ss.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of cn(n))if(Es(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 sy(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(On(t.node)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function cn(e){let t=Kl.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(On(o.node)){n.push(...cn(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...cn(o));continue}o.isJSXExpressionContainer()&&n.push(...Nt(o.get("expression")))}return Kl.set(e.node,n),n}function Nt(e){if(e.isJSXElement())return On(e.node)?cn(e):[e];if(e.isJSXFragment())return cn(e);if(e.isParenthesizedExpression())return Nt(e.get("expression"));if(e.isLogicalExpression())return Nt(e.get("right"));if(e.isConditionalExpression())return[...Nt(e.get("consequent")),...Nt(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Nt(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&Xl(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?ay(n):[]}return[]}function ay(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return On(t.node)?cn(t):[t];if(t.isJSXFragment())return cn(t);if(t.isParenthesizedExpression())return Nt(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return Nt(t);if(!t.isBlockStatement())return[];for(let n of t.get("body")){if(!n.isReturnStatement())continue;let r=n.get("argument");return r.node?Nt(r):[]}return[]}function Xl(e){let t=e.callee;return(X.isMemberExpression(t)||X.isOptionalMemberExpression(t))&&X.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function On(e){let t=Es(e.openingElement.name);return t==="Fragment"||t==="React.Fragment"}function Es(e){return X.isJSXIdentifier(e)?e.name:X.isJSXMemberExpression(e)?zl(e):X.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function zl(e){return`${X.isJSXIdentifier(e.object)?e.object.name:zl(e.object)}.${e.property.name}`}function Vt(e,t){if(t.parentPath===e&&t.listKey==="children"&&Wl(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!Wl(n))return null;let r=n;for(;r&&r!==e;){if(!cy(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function Wl(e){return e.isJSXElement()||e.isJSXFragment()}function cy(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 Mn(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=ge(t,"jsx-node");if(!a.ok)return a.result;let c=ne(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return B(t,"unsupported-syntax","insert-child target must be a JSXElement or JSXFragment","jsx-node");let l=c.match.path;if(c.match.path.isJSXElement()){let A=c.match.path.node;if(!A.closingElement||A.openingElement.selfClosing)return B(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=Co(t,r.jsx);if(!u.ok)return u.result;let d=ly(u.node,!0),p=l.node.children,m={...s,targetParentLocator:n},g=A=>s?Qe(A,a.ast,d,m):A;if(o==="append")return p.push(d),g(ae(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return p.unshift(d),g(ae(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(!i)return B(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let b=ne(a.ast,i);if(!b.ok)return{ok:!1,source:t,diagnostic:b.diagnostic};let C=Vt(c.match.path,b.match.path);if(!C)return B(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");l=C;let I=l.node.children,w=I.findIndex(A=>A===b.match.path.node);return w===-1?B(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(I.splice(o==="before"?w:w+1,0,d),g(ae(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as Hl from"@babel/parser";import{cloneNode as uy}from"@babel/types";function No(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=ge(t,"jsx-node");if(!a.ok)return a.result;let c=dy(t,r);if(!c.ok)return c.result;let l=ne(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return B(t,"unsupported-syntax","insert-jsx-expression-child target must be a JSXElement or JSXFragment","jsx-node");if(l.match.path.isJSXElement()){let I=l.match.path.node;if(!I.closingElement||I.openingElement.selfClosing)return B(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=l.match.path,d=null;if(i){let I=ne(a.ast,i);if(!I.ok)return{ok:!1,source:t,diagnostic:I.diagnostic};let w=Vt(l.match.path,I.match.path);if(!w)return B(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=w,d=I.match.path.node}else if(o==="before"||o==="after")return B(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let p=uy(c.node,!0),m=u.node.children,g={...s,targetParentLocator:n},b=I=>s?Qe(I,a.ast,p,g):I;if(o==="append")return m.push(p),b(ae(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return m.unshift(p),b(ae(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let C=m.findIndex(I=>I===d);return C===-1?B(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(m.splice(o==="before"?C:C+1,0,p),b(ae(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function dy(e,t){try{let r=Hl.parse(`const __VD_EXPR__ = <>{${t}}</>;`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],o=r?.type==="VariableDeclaration"?r.declarations[0]?.init:null,i=o?.type==="JSXFragment"?o.children[0]:void 0;return i?.type!=="JSXExpressionContainer"?{ok:!1,result:B(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:B(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as fy,nullLiteral as vs}from"@babel/types";import*as Dn from"@babel/types";function Ln(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=ge(t,"jsx-node");if(!a.ok)return a.result;let c=ne(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let l=ne(a.ast,r);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return B(t,"unsupported-syntax","move-node target parent must be a JSXElement or JSXFragment","jsx-node");let u=l.match.path;if(l.match.path.isJSXElement()){let w=l.match.path.node;if(!w.closingElement||w.openingElement.selfClosing)return B(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let d=null;if(i){let w=ne(a.ast,i);if(!w.ok)return{ok:!1,source:t,diagnostic:w.diagnostic};let A=Vt(l.match.path,w.match.path);if(!A)return B(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=A,d=w.match.path}else if(o==="before"||o==="after")return B(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let p=d&&typeof d.key=="number"?d.key:-1;if(d&&p===-1)return B(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let m=fy(c.match.path.node,!0);if(!Dn.isJSXElement(m)&&!Dn.isJSXExpressionContainer(m)&&!Dn.isJSXFragment(m))return B(t,"unsupported-syntax","move-node source must resolve to a JSX child","jsx-node");let g=c.match.path.parentPath?.node===u.node&&typeof c.match.path.key=="number"?c.match.path.key:-1;if(d&&c.match.path.parentPath?.node===d.parentPath?.node&&c.match.path.key===d.key)return B(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");py(c.match.path);let b=u.node.children,C={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return b.push(m),Qe(Io(a.ast,t),a.ast,m,C);if(o==="prepend")return b.unshift(m),Qe(Io(a.ast,t),a.ast,m,C);let I=p-(g!==-1&&g<p?1:0);return b.splice(o==="before"?I:I+1,0,m),Qe(Io(a.ast,t),a.ast,m,C)}function py(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(vs());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(vs());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(vs());return}e.remove()}import*as Gl from"@babel/parser";import{cloneNode as my,nullLiteral as Is}from"@babel/types";function Po(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,c=ge(t,"jsx-node");if(!c.ok)return c.result;let l=gy(t,s);if(!l.ok)return l.result;let u=ne(c.ast,n);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};let d=ne(c.ast,r);if(!d.ok)return{ok:!1,source:t,diagnostic:d.diagnostic};if(!d.match.path.isJSXElement()&&!d.match.path.isJSXFragment())return B(t,"unsupported-syntax","move-repeat-template-child target parent must be a JSXElement or JSXFragment","jsx-node");if(d.match.path.isJSXElement()){let A=d.match.path.node;if(!A.closingElement||A.openingElement.selfClosing)return B(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let p=d.match.path,m=null;if(i){let A=ne(c.ast,i);if(!A.ok)return{ok:!1,source:t,diagnostic:A.diagnostic};let O=Vt(d.match.path,A.match.path);if(!O)return B(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");p=O,m=A.match.path.node}else if(o==="before"||o==="after")return B(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!u.match.path.isJSXElement())return B(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let g=p.node,b=my(l.node,!0);hy(u.match.path);let C={...a,sourceLocator:n,targetParentLocator:r},I=g.children;if(o==="append")return I.push(b),Qe(ae(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,b,C);if(o==="prepend")return I.unshift(b),Qe(ae(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,b,C);let w=I.findIndex(A=>A===m);return w===-1?B(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(I.splice(o==="before"?w:w+1,0,b),Qe(ae(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,b,C))}function gy(e,t){try{let r=Gl.parse(`const __VD_EXPR__ = <>{${t}}</>;`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],o=r?.type==="VariableDeclaration"?r.declarations[0]?.init:null,i=o?.type==="JSXFragment"?o.children[0]:void 0;return i?.type!=="JSXExpressionContainer"?{ok:!1,result:B(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:B(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function hy(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Is());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Is());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Is());return}e.remove()}import{SiteEditSetPropsParamsSchema as yy,classifySiteEditPropertyName as xy}from"@vcp-dev/contracts";import*as Bn from"@babel/types";function Ao(e){let t=yy.safeParse({kind:"set-props",scope:"selection",changes:e.changes});if(!t.success)return B(e.source,"unsupported-syntax","Invalid typed JSX property changes","jsx-node",{issues:t.error.issues});let n=ge(e.source,"jsx-node");if(!n.ok)return n.result;let r=ko(n.ast,e.locator,e.source);if(!r.ok)return r.result;for(let a of t.data.changes){let c=xy(a.name);if(c.owner!=="generic")return B(e.source,"unsupported-syntax",c.diagnostic?.message??`Property '${a.name}' is not owned by the generic JSX primitive`,"jsx-node")}let o=r.match.path.node.openingElement,i=o.attributes.filter(Bn.isJSXAttribute),s=new Map;for(let a of i){let c=by(a);if(!c)continue;let l=s.get(c)??[];l.push(a),s.set(c,l)}for(let a of t.data.changes)if((s.get(a.name)??[]).length>1)return B(e.source,"unsupported-syntax",`JSX attribute '${a.name}' has multiple sources`,"jsx-node");for(let a of t.data.changes){let c=s.get(a.name)?.[0];if(a.operation==="remove"){c&&(o.attributes=o.attributes.filter(u=>u!==c));continue}let l=lr(a.name,a.value).value;c?c.value=l:o.attributes.push(lr(a.name,a.value))}return ae(n.ast,e.source,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}function by(e){return Bn.isJSXIdentifier(e.name)?e.name.name:Bn.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import*as Pe from"@babel/types";import{classifySiteEditPropertyName as Yl}from"@vcp-dev/contracts";function To(e){let t=Yl(e.name),n=Yl(e.property);if(t.owner!=="generic"||n.owner!=="generic")return B(e.source,"unsupported-syntax","Property binding is only available for generic properties","jsx-node");if(!Zl(e.object))return B(e.source,"unsupported-syntax","Property binding object must be a single identifier","jsx-node");if(e.property.length===0)return B(e.source,"unsupported-syntax","Property binding requires a non-empty property name","jsx-node");let r=ge(e.source,"jsx-node");if(!r.ok)return r.result;let o=ko(r.ast,e.locator,e.source);if(!o.ok)return o.result;let i=o.match.path.node.openingElement,s=i.attributes.filter(l=>Pe.isJSXAttribute(l)&&Ey(l)===e.name);if(s.length>1)return B(e.source,"unsupported-syntax",`JSX attribute '${e.name}' has multiple sources`,"jsx-node");let a=Sy(e.object,e.property),c=s[0];if(c)c.value=Pe.jsxExpressionContainer(a);else{let l=lr(e.name,"");l.value=Pe.jsxExpressionContainer(a),i.attributes.push(l)}return ae(r.ast,e.source,{kind:"set-property-binding",target:"jsx-node",inverse:"restore-property-binding"})}function Sy(e,t){return Zl(t)?Pe.memberExpression(Pe.identifier(e),Pe.identifier(t)):Pe.memberExpression(Pe.identifier(e),Pe.stringLiteral(t),!0)}function Zl(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)}function Ey(e){return Pe.isJSXIdentifier(e.name)?e.name.name:Pe.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{getBindingIdentifiers as Iy,identifier as dr,importDeclaration as ky,importDefaultSpecifier as Cy,importNamespaceSpecifier as Ry,importSpecifier as wy,isImportDefaultSpecifier as Ql,isImportNamespaceSpecifier as ql,isImportSpecifier as eu,stringLiteral as Ny}from"@babel/types";function jn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(C=>!Ly(C));if(o!==-1){let C=r[o],I=C&&typeof C=="object"&&"kind"in C?C.kind:void 0;return B(t,"unsupported-syntax",`Unsupported import spec kind: ${String(I)}`)}let i=Oy(r);if(!i.ok)return B(t,"unsupported-syntax",i.message);let s=ge(t);if(!s.ok)return s.result;let{ast:a}=s,c=a.program,l=c.body.filter(C=>C.type==="ImportDeclaration"&&C.source.value===n),u=new Set(l.flatMap(C=>C.specifiers.flatMap(I=>{let w=By(C,I);return w?[w]:[]}))),d=i.imports.filter(C=>!u.has(su(C)));if(d.length===0)return cr(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let p=My(c.body),m=d.find(C=>p.has(ks(C)));if(m)return B(t,"unsupported-syntax",`Import local binding already exists: ${ks(m)}`);let g=Fy(d);if(g.reduce((C,I)=>C+I.length,0)!==d.length)return B(t,"unsupported-syntax","Unsupported import specifier grouping");for(let C of g){if(!ou(nu(C)))return B(t,"unsupported-syntax","Unsupported import specifier combination");let I=l.find(w=>Py(w,C));if(I)Ay(I,C);else{let w=ky(tu(C),Ny(n));Dy(c.body,w),l.push(w)}}return ae(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function Py(e,t){return e.importKind==="type"?!1:ou(_y(Ty(e),nu(t)))}function Ay(e,t){let n=!1,r=new Set(e.specifiers.map(o=>Cs(o)));for(let o of tu(t)){let i=Cs(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return iu(e.specifiers),{changed:n}}function tu(e){let t=e.map(n=>{switch(n.kind){case"named":return wy(n.local?dr(n.local):dr(n.imported),dr(n.imported));case"default":return Cy(dr(n.local));case"namespace":return Ry(dr(n.local));default:return n}});return iu(t),t}function nu(e){let t=ru();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 Ty(e){let t=ru();for(let n of e.specifiers)Ql(n)?t.defaultLocals.add(n.local.name):ql(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function ru(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function _y(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function ou(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function iu(e){let t=[...e.filter(n=>Ql(n)),...e.filter(n=>ql(n)),...e.filter(n=>eu(n))];e.splice(0,e.length,...t)}function Fy(e){let t=e.filter(i=>i.kind==="default"),n=e.filter(i=>i.kind==="namespace"),r=e.filter(i=>i.kind==="named"),o=[];if(n.length>0){let i=Math.max(t.length,n.length);for(let s=0;s<i;s+=1){let a=[],c=t[s],l=n[s];c&&a.push(c),l&&a.push(l),o.push(a)}return r.length>0&&o.push(r),o}if(t.length>0){o.push([t[0],...r]);for(let i of t.slice(1))o.push([i])}else r.length>0&&o.push(r);return o}function Oy(e){let t=new Map,n=new Map;for(let r of e){let o=su(r);if(t.has(o))continue;let i=ks(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 My(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(Iy(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 Dy(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 Ly(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 su(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 ks(e){return e.kind==="named"?e.local??e.imported:e.local}function By(e,t){return e.importKind==="type"||eu(t)&&t.importKind==="type"?null:Cs(t)}function Cs(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 $n(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(u=>!$y(u));if(o!==-1){let u=r[o],d=u&&typeof u=="object"&&"kind"in u?u.kind:void 0;return B(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(d)}`)}let i=ge(t);if(!i.ok)return i.result;let{ast:s}=i,a=s.program,c=a.body.findIndex(u=>u.type==="ImportDeclaration"&&u.source.value===n);if(c===-1)return cr(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let l=a.body[c];return r.length===0?(a.body.splice(c,1),ae(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(l.specifiers=l.specifiers.filter(u=>!r.some(d=>jy(u,d))),l.specifiers.length===0&&a.body.splice(c,1),ae(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function jy(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 $y(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 fr(e){let{source:t,locator:n,next:r}=e,o=Mo(t,n);return o.ok?(o.path.replaceWith($t(r)),ae(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function _o(e){let{source:t,locator:n,index:r,value:o}=e,i=Mo(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(s=>s?.type==="SpreadElement")?B(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>i.path.node.elements.length?B(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,0,$t(o)),ae(i.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):B(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function Fo(e){let{source:t,locator:n,index:r}=e,o=Mo(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(i=>i?.type==="SpreadElement")?B(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=o.path.node.elements.length?B(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(o.path.node.elements.splice(r,1),ae(o.ast,t,{kind:"remove-array-element",target:"value",inverse:"insert-array-element"})):B(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function Oo(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=Mo(t,n);if(!i.ok)return i.result;if(!i.path.isArrayExpression())return B(t,"unsupported-syntax","Array operations require array expression target","value");if(i.path.node.elements.some(c=>c?.type==="SpreadElement"))return B(t,"unsupported-syntax","Spread array elements are not supported","value");if(r<0||r>=i.path.node.elements.length||o<0||o>i.path.node.elements.length)return B(t,"array-index-out-of-range","Array move indices are out of range","value");let[s]=i.path.node.elements.splice(r,1),a=Math.min(o,i.path.node.elements.length);return i.path.node.elements.splice(a,0,s),ae(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function Mo(e,t){let n=ge(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=ne(n.ast,t);return r.ok?{ok:!0,ast:n.ast,path:r.match.path}:{ok:!1,result:{ok:!1,source:e,diagnostic:r.diagnostic}}}import*as Te from"@babel/types";function Do(e){let t=ge(e.source,"value");if(!t.ok)return t.result;let n=ne(t.ast,e.objectLocator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};if(!n.match.path.isObjectExpression())return B(e.source,"unsupported-syntax","Object property upsert requires an ObjectExpression parent","value");let r=n.match.path.node;if(r.properties.some(a=>Te.isSpreadElement(a)||Te.isObjectProperty(a)&&a.computed))return B(e.source,"unsupported-syntax","Object property upsert does not support spreads or computed keys","value");let o=r.properties.filter(a=>Te.isObjectProperty(a)&&Vy(a.key)===e.name);if(o.length>1)return B(e.source,"unsupported-syntax",`Object property '${e.name}' has multiple sources`,"value");let i=e.value.kind==="undefined"?Te.unaryExpression("void",Te.numericLiteral(0)):$t(e.value.value),s=o[0];if(s)s.value=i,s.shorthand=!1;else{let a=Te.objectProperty(ys(e.name),i);e.name==="__proto__"&&(a.computed=!0),r.properties.push(a)}return ae(t.ast,e.source,{kind:"upsert-object-property",target:"value",inverse:"restore-object-property"})}function Vy(e){return Te.isIdentifier(e)?e.name:Te.isStringLiteral(e)?e.value:Te.isNumericLiteral(e)?String(e.value):null}var Ky=typeof Rs=="function"?Rs:Rs.default;function Ps(e){let t=fu(e);if(t)return{ok:!1,error:t};let n=e.projection,r=Ts(n,e.placementKey,e.expectedDocumentVersion);if(!r.ok)return{ok:!1,error:{code:r.diagnostic.code==="DOCUMENT_VERSION_STALE"?"VERSION_STALE":"RUNTIME_ANCHOR_UNRESOLVED",message:r.diagnostic.message,diagnostics:[r.diagnostic]}};let o=r.placement.containerSourceRange??n.container.sourceRange,i=r.placement;if((n.container.kind==="virtual-route-root"||n.container.kind==="starter-placeholder")&&(n.container.sourceRange===null||n.container.sourceKind==="jsx-element"||n.container.sourceKind==="atomic-expression"||n.container.kind==="starter-placeholder"))return n.container.sourceKind==="atomic-expression"?{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"An indirect page expression does not expose a safe return boundary.",diagnostics:[]}}:{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:i.placementUnitKey,importStep:cu(e),returnStep:{kind:"insert-return",node:{jsx:`<${e.component.localName} />`},placement:i.relation,replaceOriginal:n.container.kind==="starter-placeholder"}}};if(!o)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition does not expose a safe placement boundary.",diagnostics:[]}};let a={kind:"jsx-node",strategy:"source-range",sourceRange:o},c=wt(e.source,a);if(!c.ok||!c.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:c.ok===!1?c.diagnostic.message:"Route page composition anchor could not be resolved.",diagnostics:c.ok?[]:[Lo(c.diagnostic)]}};let l=Bo(e.source,c.match.node.start??null,c.match.node.end??null);if(Hy(o,n.container.sourceRange)&&n.container.sourceHash&&l!==n.container.sourceHash)return{ok:!1,error:{code:"VERSION_STALE",message:"Route page composition container hash no longer matches the current source.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Route page composition container hash no longer matches the current source."}]}};let u=cu(e);return{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:r.placement.placementUnitKey,parentLocator:a,importStep:u,insertStep:{kind:"insert-child",parentLocator:a,node:{jsx:`<${e.component.localName} />`},placement:r.placement.relation,...r.placement.anchorSourceRange?{anchorLocator:{kind:"jsx-node",strategy:"source-range",sourceRange:r.placement.anchorSourceRange}}:{}}}}}function cu(e){let t=Wy(e.entryFile,e.component.source);return e.component.exportName==="default"?{kind:"add-import",moduleSpecifier:t,imports:[{kind:"default",local:e.component.localName}]}:{kind:"add-import",moduleSpecifier:t,imports:[{kind:"named",imported:e.component.exportName,local:e.component.localName===e.component.exportName?void 0:e.component.localName}]}}function du(e){let t;try{t=jo.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]})}catch(i){return{ok:!1,source:e.source,diagnostic:{message:i instanceof Error?i.message:String(i)}}}let n=jo.parseExpression(e.jsx,{plugins:["jsx","typescript"]}),r=!1;return(typeof ws=="function"?ws:ws.default)(t,{ExportDefaultDeclaration(i){let s=i.get("declaration"),a=Jy(i,s);if(a){if(a.isArrowFunctionExpression()&&!a.get("body").isBlockStatement()){let c=a.get("body");c.replaceWith(lu(c.node,n,e.placement,e.replaceOriginal===!0)),r=!0,i.stop();return}a.traverse({Function(c){c.node!==a.node&&c.skip()},ReturnStatement(c){if(r)return;let l=c.get("argument");l.node&&(l.replaceWith(lu(l.node,n,e.placement,e.replaceOriginal===!0)),r=!0,c.stop())}}),r&&i.stop()}}}),r?{ok:!0,source:Ky(t,{}).code}:{ok:!1,source:e.source,diagnostic:{message:"Route default return boundary could not be resolved."}}}function Jy(e,t){if(t.isFunctionDeclaration()||t.isFunctionExpression()||t.isArrowFunctionExpression())return t;if(!t.isIdentifier())return null;let n=e.scope.getBinding(t.node.name);if(!n)return null;let r=n.path;if(r.isFunctionDeclaration()||r.isFunctionExpression())return r;if(r.isVariableDeclarator()){let o=r.get("init");if(o.isArrowFunctionExpression()||o.isFunctionExpression())return o}return null}function lu(e,t,n,r){if(Ut.isNullLiteral(e)||r)return t;let s=n==="before"||n==="prepend"?[t,e]:[e,t];return Ut.jsxFragment(Ut.jsxOpeningFragment(),Ut.jsxClosingFragment(),s)}function As(e){let t=fu(e);if(t)return{ok:!1,error:t};let n=e.projection;if(n.container.sourceRange===null)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition does not expose a safe placement boundary.",diagnostics:[]}};let r=pu(n,e.placementUnitKey,e.expectedDocumentVersion);if(!r.ok)return{ok:!1,error:{code:r.diagnostic.code==="DOCUMENT_VERSION_STALE"?"VERSION_STALE":"NO_SAFE_PAGE_PLACEMENT",message:r.diagnostic.message,diagnostics:[r.diagnostic]}};let o=r.placement;if(!o.sourceRange||!o.sourceHash)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition source placement does not expose a safe boundary.",diagnostics:[]}};let i=Ns(o.sourceRange),s=wt(e.source,i);if(!s.ok||!s.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:s.ok===!1?s.diagnostic.message:"Route page composition source anchor could not be resolved.",diagnostics:s.ok?[]:[Lo(s.diagnostic)]}};if(Bo(e.source,s.match.node.start??null,s.match.node.end??null)!==o.sourceHash)return{ok:!1,error:{code:"VERSION_STALE",message:"Route page composition source placement hash no longer matches the current source.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Route page composition source placement hash no longer matches the current source."}]}};if(e.operation==="remove-node")return{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"remove-node",locator:i}}};if(!e.targetPlacement)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Page-unit move requires a target placement.",diagnostics:[]}};if(e.targetPlacement.composition.routeId!==e.routeId||!zy(e.targetPlacement.composition,e.composition))return{ok:!1,error:{code:"CROSS_PAGE_MOVE_UNSUPPORTED",message:"Page-unit move across routes or composition templates is not supported.",diagnostics:[]}};if(e.targetPlacement.documentVersion!==e.expectedDocumentVersion)return{ok:!1,error:{code:"VERSION_STALE",message:"Page-unit target placement belongs to a different document version.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Page-unit target placement belongs to a different document version."}]}};let c=Ts(n,e.targetPlacement.placementKey,e.expectedDocumentVersion);if(!c.ok)return{ok:!1,error:{code:c.diagnostic.code==="DOCUMENT_VERSION_STALE"?"VERSION_STALE":"NO_SAFE_PAGE_PLACEMENT",message:c.diagnostic.message,diagnostics:[c.diagnostic]}};let l=c.placement;if(l.placementUnitKey!==e.targetPlacement.placementUnitKey||l.relation!==e.targetPlacement.relation)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Page-unit target placement metadata does not match the cached projection.",diagnostics:[]}};let u=l.containerSourceRange;if(!u||!l.containerSourceHash)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable container boundary.",diagnostics:[]}};let d=Ns(u),p=wt(e.source,d);if(!p.ok||!p.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:p.ok===!1?p.diagnostic.message:"Route page composition target container could not be resolved.",diagnostics:p.ok?[]:[Lo(p.diagnostic)]}};if(Bo(e.source,p.match.node.start??null,p.match.node.end??null)!==l.containerSourceHash)return uu("Route page composition target container hash no longer matches the current source.");if(l.relation==="before"||l.relation==="after"){let g=l.anchorSourceRange,b=l.anchorSourceHash;if(!g||!b)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable anchor boundary.",diagnostics:[]}};let C=Ns(g),I=wt(e.source,C);return!I.ok||!I.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:I.ok===!1?I.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:I.ok?[]:[Lo(I.diagnostic)]}}:Bo(e.source,I.match.node.start??null,I.match.node.end??null)!==b?uu("Route page composition target anchor hash no longer matches the current source."):{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"move-node",locator:i,targetParentLocator:d,anchorLocator:C,placement:l.relation}}}}return{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"move-node",locator:i,targetParentLocator:d,placement:l.relation}}}}function uu(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Lo(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function fu(e){let{projection:t}=e;return t.route!==e.routeId||t.entryFile!==e.entryFile?{code:"VERSION_STALE",message:"Cached page composition projection belongs to a different route.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Cached page composition projection belongs to a different route.",details:{expectedRouteId:e.routeId,projectedRouteId:t.route,expectedEntryFile:e.entryFile,projectedEntryFile:t.entryFile}}]}:e.composition&&!Xy(t.composition,e.composition)?{code:"VERSION_STALE",message:"Cached page composition projection belongs to a different composition.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Cached page composition projection belongs to a different composition.",details:{expectedComposition:e.composition,projectedComposition:t.composition}}]}:e.currentDocumentVersion!==e.expectedDocumentVersion||t.documentVersion!==e.currentDocumentVersion?{code:"VERSION_STALE",message:"Route page composition version is stale.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Route page composition version is stale.",details:{expectedDocumentVersion:e.expectedDocumentVersion,currentDocumentVersion:e.currentDocumentVersion,projectedDocumentVersion:t.documentVersion}}]}:null}function Xy(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function zy(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function Wy(e,t){let n=au.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=au.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Ns(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function Bo(e,t,n){return t==null||n==null?null:`sha256:${Uy("sha256").update(e.slice(t,n)).digest("hex")}`}function Hy(e,t){return e===null||t===null?e===t:e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}var Gy=typeof _s=="function"?_s:_s.default;function gu(e){if(!e.ast)return bt(e,[$e("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=rx(e.ast);if(!t)return bt(e,[$e("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=ix(t);if(n.length===0)return bt(e,[$e("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")]);if(n.length>1)return bt(e,[$e("MULTIPLE_PAGE_RETURNS","Route default export contains multiple page-level return statements",{returnCount:n.length})]);let r=sx(n[0].argument);if(!r)return bt(e,[$e("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})]);if(r.isNullLiteral())return mu(e,t,"virtual-route-root");if(ax(r,t))return bt(e,[$e("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(cx(r,t)||lx(r)&&!e.source.includes("DESIGN_PLAN_REPLACE_ME"))return bt(e,[$e("UNSUPPORTED_PAGE_SHAPE","Route default export shape does not provide a single safe placement boundary",{reason:"ambiguous-placement"})]);if(r.isJSXFragment()){let i=Jt(r);if(i.unsupported)return bt(e,[$e("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);let s=Fs({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-fragment",source:e.source,containerPath:r,members:i.members});return $o(e,t,s,{kind:"virtual-route-root",sourceKind:"jsx-fragment"})}if(r.isJSXElement()&&!Vn(r)){let i=Ds(r),s=Fs({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[i]});return $o(e,t,s,{kind:"virtual-route-root",sourceKind:"jsx-element"})}if(r.isJSXElement()){let i=Jt(r);if(i.unsupported)return bt(e,[$e("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);let s=i.members;if(dx(e.source,r,s))return mu(e,t,"starter-placeholder");let a=Fs({input:e,containerKind:"jsx-container",sourceKind:"jsx-element",source:e.source,containerPath:r,members:s});return $o(e,t,a,{kind:"jsx-container",sourceKind:"jsx-element"})}if(ux(r))return bt(e,[$e("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);let o=px({input:e,source:e.source,expression:r});return $o(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"})}function Ts(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:$e("DOCUMENT_VERSION_STALE","Placement lookup is stale for the requested document version",{expectedDocumentVersion:e.documentVersion,requestedDocumentVersion:n})};let r=e.placementByKey.get(t)??null;return r?{ok:!0,placement:r}:{ok:!1,diagnostic:$e("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function pu(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:$e("DOCUMENT_VERSION_STALE","Placement lookup is stale for the requested document version",{expectedDocumentVersion:e.documentVersion,requestedDocumentVersion:n})};let r=e.placementUnitByKey.get(t)??null;return r?{ok:!0,placement:r}:{ok:!1,diagnostic:$e("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function hu(e){return e.ok?Yy(e.projection):Zy(e.projection)}function Yy(e){let t=new Map,n=[];for(let l of e.placements)l.members.length===0&&e.placements.length>1||l.members.length>0&&!l.anchorSourceRange||t.has(l.placementUnitKey)||t.set(l.placementUnitKey,l);let r=new Map,o=new Map;for(let[l,u]of t){let d=u.members.flatMap((b,C)=>yu(e,u,b,C,e.container.placementKey)),p=d.filter(({member:b})=>b.isBusinessMember).map(({sourceMember:b})=>qy(l,b,u.independent)),m=d.length>0?d:[{sourceMember:{key:`source:${l}:empty`,kind:e.container.kind==="starter-placeholder"?"starter-placeholder":"null-return",containerKey:e.container.placementKey,label:"empty-page",sourceFile:e.entryFile,isAtomic:!0},member:null}];r.set(l,m.map(({sourceMember:b})=>b)),o.set(l,p);let g=m[0]?.sourceMember.key??l;n.push({key:l,containerKey:g,businessMemberKeys:p.map(b=>b.key),isMultiMember:u.memberCount>1})}let i=[...r.values()].flat(),s=[...o.values()].flat(),a=i[0]?.key??null,c=e.placements.map(l=>({kind:"page-composition",placementKey:l.placementKey,documentVersion:e.documentVersion,composition:e.composition,placementUnitKey:l.placementUnitKey,relation:l.relation}));return{status:"supported",version:e.version,composition:e.composition,container:Qy(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function Zy(e){let t=e.diagnostics.map(ex);return{status:"unsupported",version:e.version,composition:e.composition,reason:tx(e.diagnostics),diagnostics:t}}function Qy(e,t){switch(e.container.kind){case"jsx-container":return{kind:"jsx-container",key:e.container.placementKey,sourceMemberKey:t??e.container.placementKey,sourceFile:e.entryFile,componentName:e.defaultExportName??void 0};case"starter-placeholder":return{kind:"starter-placeholder",key:e.container.placementKey,sourceFile:e.entryFile};case"virtual-route-root":return{kind:"virtual-route-root",key:e.container.placementKey}}}function yu(e,t,n,r,o){let i=`source:${t.placementUnitKey}:${r}:${n.memberKey}`;return[{sourceMember:{key:i,kind:n.kind==="jsx-element"?"jsx-element":"jsx-expression",containerKey:o,label:n.label,sourceFile:e.entryFile,isAtomic:n.kind!=="jsx-element"},member:n},...n.children.flatMap((a,c)=>yu(e,t,a,c,i))]}function qy(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function ex(e){return{code:nx(e),message:e.message}}function tx(e){let t=e[0];if(!t)return"UNSUPPORTED_ROUTE_STRUCTURE";switch(t.code){case"ROUTE_RETURN_NOT_FOUND":return"ROUTE_RETURN_NOT_FOUND";case"MULTIPLE_PAGE_RETURNS":return"MULTIPLE_PAGE_RETURNS";case"INDIRECT_RETURN_ONLY":return"INDIRECT_RETURN_ONLY";case"PLACEMENT_KEY_NOT_FOUND":return"RUNTIME_ANCHOR_UNRESOLVED";case"DOCUMENT_VERSION_STALE":return"VERSION_STALE";case"UNSUPPORTED_PAGE_SHAPE":return t.details?.reason==="ambiguous-placement"?"PAGE_CONTAINER_AMBIGUOUS":"UNSUPPORTED_ROUTE_STRUCTURE";default:return"UNSUPPORTED_ROUTE_STRUCTURE"}}function nx(e){switch(e.code){case"PLACEMENT_KEY_NOT_FOUND":return"RUNTIME_ANCHOR_UNRESOLVED";case"DOCUMENT_VERSION_STALE":return"VERSION_STALE";case"UNSUPPORTED_PAGE_SHAPE":return e.details?.reason==="ambiguous-placement"?"PAGE_CONTAINER_AMBIGUOUS":"UNSUPPORTED_ROUTE_STRUCTURE";default:return e.code}}function rx(e){let t=null;return Gy(e,{ExportDefaultDeclaration(n){let r=n.get("declaration");if(r.isArrowFunctionExpression()||r.isFunctionDeclaration()||r.isFunctionExpression()){t=r,n.stop();return}if(!r.isIdentifier())return;let o=n.scope.getBinding(r.node.name);if(!o)return;let i=ox(o.path);i&&(t=i,n.stop())}}),t}function ox(e){if(e.isArrowFunctionExpression()||e.isFunctionDeclaration()||e.isFunctionExpression())return e;if(e.isVariableDeclarator()){let t=e.get("init");if(t.isArrowFunctionExpression()||t.isFunctionExpression())return t}return null}function ix(e){if(e.isArrowFunctionExpression()){let r=e.get("body");if(!r.isBlockStatement())return[{argument:r}]}let t=e.get("body");if(!t.isBlockStatement())return[];let n=[];return t.traverse({Function(r){r.node!==e.node&&r.skip()},ReturnStatement(r){n.push({argument:r.get("argument")})}}),n}function sx(e){if(!e.node)return null;let t=e;for(;;){if(t.isParenthesizedExpression()){t=t.get("expression");continue}if(t.isTSAsExpression()||t.isTSTypeAssertion()){t=t.get("expression");continue}if(t.isTSNonNullExpression()||t.isTypeCastExpression()){t=t.get("expression");continue}break}return t.isExpression()?t:null}function ax(e,t){if(e.isIdentifier())return Vo(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return Vo(n.node.name,t)}return!1}function cx(e,t){return e.isConditionalExpression()?Kt(e.get("consequent"),t)||Kt(e.get("alternate"),t):e.isLogicalExpression()?Kt(e.get("left"),t)||Kt(e.get("right"),t):!1}function lx(e){if(!e.isJSXElement()||!Vn(e))return!1;let t=Jt(e).members;if(t.length!==1)return!1;let n=t[0];return n.kind==="jsx-element"&&!n.isBusinessMember&&n.businessMemberCount>0}function Kt(e,t){if(e.isIdentifier())return Vo(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return Vo(n.node.name,t)}return e.isConditionalExpression()?Kt(e.get("consequent"),t)||Kt(e.get("alternate"),t):e.isLogicalExpression()?Kt(e.get("left"),t)||Kt(e.get("right"),t):!1}function Vo(e,t){let n=t.scope.getBinding(e);if(!n)return!1;let r=n.path;if(r.isFunctionDeclaration()||r.isFunctionExpression()||r.isArrowFunctionExpression())return!0;if(r.isVariableDeclarator()){let o=r.get("init");return o.isFunctionExpression()||o.isArrowFunctionExpression()}return!1}function ux(e){return e.isJSXSpreadChild()}function dx(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&Ms(t)}function Ms(e){for(let t of e.get("children")){if(t.isJSXText()){if(t.node.value.trim())return!1;continue}if(t.isJSXExpressionContainer()){let n=t.get("expression");if(n.isJSXEmptyExpression()||n.isNullLiteral())continue;return!1}if(t.isJSXFragment()){if(!Ms(t))return!1;continue}if(t.isJSXElement()&&!Ms(t))return!1}return!0}function Jt(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:Ls(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:st(r.node.loc),businessMemberCount:0,parentSourceRange:st(e.node.loc),children:[],isBusinessMember:!1,label:"text"});continue}if(r.isJSXExpressionContainer()){let o=r.get("expression");if(o.isJSXEmptyExpression()||o.isNullLiteral())continue;if(o.isJSXFragment()){let i=Jt(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=Vn(o)?Jt(o):null;n||=i?.unsupported??!1,t.push({...Ds(o,i?.members),sourceRange:st(r.node.loc),parentSourceRange:st(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:Ls(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:st(r.node.loc),businessMemberCount:1,parentSourceRange:st(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&xu(r)){let o=Jt(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=Vn(r)?Jt(r):null;n||=o?.unsupported??!1,t.push({...Ds(r,o?.members),parentSourceRange:st(e.node.loc)})}}return{members:t,unsupported:n}}function Ds(e,t){let n=e.isJSXElement()&&Vn(e)?t??Jt(e).members:[],r=e.isJSXElement()&&!Vn(e)&&!xu(e);return{memberKey:Ls(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:st(e.node.loc),businessMemberCount:r?1:bu(n),parentSourceRange:st(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:fx(e)}}function xu(e){if(e.isJSXFragment())return!0;let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name==="Fragment"||t.type==="JSXMemberExpression"&&t.object.type==="JSXIdentifier"&&t.object.name==="React"&&t.property.name==="Fragment"}function Vn(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name!=="Fragment"&&t.name[0]===t.name[0]?.toLowerCase()}function fx(e){if(e.isJSXFragment())return"Fragment";let t=e.node.openingElement.name;if(t.type==="JSXIdentifier")return t.name;if(t.type==="JSXMemberExpression"){let n=t.object;return`${n.type==="JSXIdentifier"?n.name:"member"}.${t.property.name}`}return t.name.name}function bu(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function Uo(e){return e.length===0?0:Math.max(1,bu(e))}function Fs(e){let t=st(e.containerPath.node.loc),n=Eu(e.source,e.containerPath.node.start,e.containerPath.node.end),r=qe(e.input,e.containerKind,e.sourceKind,t),o=qe(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:Uo(e.members)<=1,memberCount:Uo(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function px(e){let t=st(e.expression.node.loc),n=Eu(e.source,e.expression.node.start,e.expression.node.end),r=qe(e.input,"virtual-route-root","atomic-expression",t),o=qe(e.input,"virtual-route-root","placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:!0,memberCount:1,sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:[{memberKey:qe(e.input,"virtual-route-root","atomic-member",t),kind:"atomic-expression",nodeType:e.expression.node.type,sourceRange:t,businessMemberCount:1,parentSourceRange:null,children:[],isBusinessMember:!0,label:e.expression.node.type}]}}function $o(e,t,n,r){let o=n.containerSourceRange??n.sourceRange,i=mx(e,n,o),s=us(i),a={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:vu(t),container:{kind:r.kind,placementKey:n.placementKey,placementUnitKey:n.placementUnitKey,version:e.version,isEmptyPage:n.memberCount===0,sourceKind:r.sourceKind,sourceRange:o,sourceHash:n.sourceHash},placements:i,diagnostics:[],placementByKey:new Map,unitByKey:new Map,placementsByUnitKey:new Map,placementUnitByKey:new Map};return Object.defineProperties(a,{placementByKey:{value:s.placementByKey,enumerable:!1},unitByKey:{value:s.unitByKey,enumerable:!1},placementsByUnitKey:{value:s.placementsByUnitKey,enumerable:!1},placementUnitByKey:{value:s.sourcePlacementByUnitKey,enumerable:!1}}),{ok:!0,projection:a}}function mx(e,t,n){if(t.members.length===0)return[t];let r=[],o=(l,u,d,p,m,g,b=n)=>({...t,placementKey:u,placementUnitKey:d,containerKey:t.placementKey,independent:Uo(g)<=1,memberCount:Uo(g),sourceRange:p,sourceHash:p?Os(e.source,p):null,relation:l,containerSourceRange:b,containerSourceHash:b?Os(e.source,b):null,anchorSourceRange:m,anchorSourceHash:m?Os(e.source,m):null,members:g}),i=t.placementKey,s=t.members.map(l=>qe(e,i,"placement-unit",l.sourceRange)),a=s[0]??t.placementUnitKey,c=s.at(-1)??t.placementUnitKey;r.push(o("prepend",qe(e,i,"prepend",n),a,n,null,[]));for(let l of t.members){let u=l.parentSourceRange??n,d=qe(e,i,"placement-unit",l.sourceRange);r.push(o("before",qe(e,d,"before",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u)),r.push(o("after",qe(e,d,"after",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u))}return r.push(o("append",i,c,n,null,[])),r}function mu(e,t,n){let r=qe(e,n,"empty-container",void 0),o=qe(e,n,"empty-unit",void 0),i={placementKey:r,placementUnitKey:o,version:e.version,containerKey:r,independent:!0,memberCount:0,sourceRange:null,sourceHash:null,relation:"append",containerSourceRange:null,containerSourceHash:null,anchorSourceRange:null,anchorSourceHash:null,members:[]},s=us([i]),a={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:vu(t),container:{kind:n,placementKey:r,placementUnitKey:o,version:e.version,isEmptyPage:!0,sourceKind:n==="starter-placeholder"?"starter-placeholder":"jsx-fragment",sourceRange:null,sourceHash:null},placements:[i],diagnostics:[],placementByKey:new Map,unitByKey:new Map,placementsByUnitKey:new Map,placementUnitByKey:new Map};return Object.defineProperties(a,{placementByKey:{value:s.placementByKey,enumerable:!1},unitByKey:{value:s.unitByKey,enumerable:!1},placementsByUnitKey:{value:s.placementsByUnitKey,enumerable:!1},placementUnitByKey:{value:s.sourcePlacementByUnitKey,enumerable:!1}}),{ok:!0,projection:a}}function bt(e,t){return{ok:!1,projection:{status:"unsupported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,diagnostics:t}}}function $e(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function qe(e,t,n,r){return Su([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function Ls(e,t,n){return Su(["member",e,String(t??-1),String(n??-1)])}function Su(e){return`pc_${Bs("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function Eu(e,t,n){return t==null||n==null?null:`sha256:${Bs("sha256").update(e.slice(t,n)).digest("hex")}`}function Os(e,t){let n=[0];for(let i=0;i<e.length;i+=1)e.charCodeAt(i)===10&&n.push(i+1);let r=n[t.startLine-1],o=n[t.endLine-1];return r===void 0||o===void 0?null:`sha256:${Bs("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function st(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function vu(e){if(e.isFunctionDeclaration())return e.node.id?.name??null;let t=e.parentPath;return t?.isVariableDeclarator()&&t.node.id.type==="Identifier"?t.node.id.name:null}function hx(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var yx=160;function Iu(e,t,n,r={}){let o=Tn(e),i=[];for(let[s,a]of e.elements){let c=n.get(s),l={canUpdateText:r.canUpdateTextByKey?.get(s)??c?.canUpdateText??!1,canInsertChild:c?.canInsertChild??!1,canMove:c?.canMove??!1,canRemove:c?.canRemove??!1};i.push({key:s,tag:a.tag,label:a.tag===a.componentName?a.tag:`${a.tag} (${a.componentName})`,parentKey:a.parentKey,childKeys:[...a.childKeys],operationSummary:l,...r.dynamicDataSummaryByKey?.get(s)?{dynamicDataSummary:r.dynamicDataSummaryByKey.get(s)}:{}})}return{composition:o,routeId:e.routeId,version:e.version,rootKeys:[...e.rootKeys],entries:i}}function ku(e,t,n,r,o,i,s,a,c,l,u,d,p){let m=Tn(t),g=t.elements.get(e),b=n.nodes.get(e),C=r.get(e);if(!g||!b||!C)throw new Error(`Node not found: ${e}`);let I=Pu(g.textSegments,s),w=Au(e,t,g,C,I),A=I?Sx(I):void 0,O=Ex(i,I),ie=g.textSegments.map(M=>({index:M.index,value:M.value,editable:Tu(M,C,s?.get(M.index)??null),source:o.get(M.index)??null})),oe=wu(g,t),N=g.childKeys.map(M=>{let j=t.elements.get(M);return j?{key:M,tag:j.tag,label:j.tag}:null}).filter(M=>M!==null),W=[];if(g.parentKey){let M=t.elements.get(g.parentKey);if(M)for(let j of M.childKeys){if(j===e)continue;let Q=t.elements.get(j);Q&&W.push({key:j,tag:Q.tag,label:Q.tag})}}return{composition:m,key:e,tag:g.tag,componentName:g.componentName,sourceFile:g.sourceFile,sourceLocator:Ru(g),label:g.tag,capabilities:w,writeTarget:i,effectiveWriteTarget:O,provenanceChain:A,componentSemantic:c,contentModel:l,mediaModel:u,styleSource:d,conditional:a,...p?{dynamicData:p}:{},textSegments:ie,boundaryKind:g.boundaryKind,isOpaque:g.isOpaque,ancestors:oe,children:N,siblings:W}}function Cu(e,t,n,r,o,i,s,a){let c=Tn(t),l=t.elements.get(e),u=n.nodes.get(e),d=r.get(e);if(!l||!u||!d)throw new Error(`Node not found: ${e}`);let p=Pu(l.textSegments,i);return{composition:c,key:e,tag:l.tag,componentName:l.componentName,sourceFile:l.sourceFile,sourceLocator:Ru(l),label:l.tag,capabilities:Au(e,t,l,d,p),provenanceChain:p?{editMode:p.editMode,diagnostics:p.diagnostics.map(m=>({code:m.code,message:m.message}))}:void 0,...s?{dynamicData:s}:{},...a?{properties:a}:{},textSegments:l.textSegments.map(m=>{let g=o.get(m.index);return{index:m.index,editable:Tu(m,d,i?.get(m.index)??null),source:g?{kind:g.kind}:null}}),boundaryKind:l.boundaryKind,isOpaque:l.isOpaque,ancestors:wu(l,t)}}function Ru(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:xx(e.sourceRange),structuralPath:e.identity.structuralPath,...bx(e.textSegments)}}function wu(e,t){let n=[],r=e.parentKey;for(;r;){let o=t.elements.get(r);if(!o)break;n.push({key:r,tag:o.tag,label:o.tag}),r=o.parentKey}return n.reverse(),n}function xx(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function bx(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,yx)}:{}}function Nu(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 Pu(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function Au(e,t,n,r,o){let i=n.identity.structuralPath.includes("#repeat:"),s=t.regions.some(u=>u.kind==="repeat-region"&&u.childKeys.includes(e)),a=o?.diagnostics.find(u=>u.code==="missing-adapter"||u.code==="external-source-readonly")?.code,c=r.canUpdateText?{mode:o?.editMode??"direct",reasonCode:a??(o?.editMode==="upstream"?"component-prop":o?.finalSource?.kind==="repeat-template"?"repeat-item-data":void 0)}:{mode:"unsupported",reasonCode:"capability-denied"},l=r.canUpdateText&&_u(c.mode);return{...r,canUpdateText:l,editModes:{updateText:c,insertChild:r.canInsertChild?{mode:"direct",reasonCode:i||s?"repeat-template":void 0}:{mode:"unsupported",reasonCode:"capability-denied"},move:r.canMove?{mode:s?"proxy":"direct",reasonCode:s?"repeat-collection":void 0}:{mode:"unsupported",reasonCode:"capability-denied"},remove:r.canRemove?{mode:s?"proxy":"direct",reasonCode:s?"repeat-collection":void 0}:{mode:"unsupported",reasonCode:"capability-denied"}}}}function Tu(e,t,n){return!e.editable||!t.canUpdateText?!1:n?_u(n.editMode):!0}function _u(e){return e==="direct"||e==="proxy"||e==="upstream"}function Sx(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 Ex(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}:hx(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 Fu(e){let{key:t,element:n,graph:r,provenances:o}=e,i=Ix(t,n,r),s=i?.tag??(ln(n.tag)?n.tag:n.componentName),a=i?.identity.key??Ou(n,r)??t,c=Rx(i),l=wx(t,n,r,o,i),u=vx(t,n,r,o,a);return{componentName:s,instanceKey:a,templateOwner:Cx(i??n,s),...c.length>0?{variantKeys:c}:{},...l.length>0?{slotKeys:l}:{},editableStrategy:u,impactScope:Nx(u),alternativeStrategies:Px(u)}}function vx(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return js(e,n)?"instance":!ln(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function Ou(e,t){if(ln(e.tag))return e.identity.key;let n=[...t.elements.values()].filter(r=>r.importedFrom===e.sourceFile&&kx(r,e.componentName));return n.length!==1?null:n[0].identity.key}function Ix(e,t,n){if(ln(t.tag))return t;let r=js(e,n);if(r)return r;let o=Ou(t,n);return o?n.elements.get(o)??null:null}function kx(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function Cx(e,t){return ln(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function Rx(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 wx(e,t,n,r,o){let i=new Set,s=js(e,n);s&&o?.identity.key===s.identity.key&&i.add("children");for(let a of r.values()){let c=a?.chain.find(u=>u.kind==="component-prop");if(!c)continue;let l=c.displayName.split(".").pop();l&&i.add(l)}return i.size===0&&ln(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function js(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(ln(r.tag))return r;n=r.parentKey}return null}function ln(e){return/^[A-Z]/.test(e)}function Nx(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function Px(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}var Ax=new Set(["markdown","body","content","value","document"]),Mu=[];function Lu(e){if(!(!Fx(e.tag)||!e.attributes))for(let t of e.attributes){if(!Ax.has(t.name))continue;if(_x(t))return{kind:"markdown",field:t.name,schema:"markdown",valuePath:t.source?.expression,operationBoundary:Mu};let n=Tx(t.resolvedValue);if(n==="prosemirror-doc"||n==="node-array")return{kind:"rich-text-json",field:t.name,valuePath:t.source?.expression,schema:n,operationBoundary:Mu};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 Tx(e){if(e){if(Array.isArray(e)&&e.every(t=>Du(t)))return"node-array";if(Du(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 Du(e){return!Array.isArray(e)&&typeof e=="object"&&e!==null}function _x(e){return e.name==="markdown"}function Fx(e){return/^[A-Z]/.test(e)}var Ox=["src","alt","poster","caption","width","height"];function Bu(e){let t=e.attributes?.filter(s=>Ox.includes(s.name))??[];if(t.length===0)return;let n=t.map(s=>s.name),r=t.filter(s=>s.resolution&&s.resolution.status!=="resolved"),o=Object.fromEntries(t.filter(s=>s.source?.expression).map(s=>[s.name,s.source.expression])),i=Dx(t.filter(s=>!s.resolution||s.resolution.status==="resolved").map(s=>s.value));return{kind:Mx(e.tag,n),sourceType:i,fields:n,editableFields:[],operationBoundary:[],...Object.keys(o).length>0?{valuePaths:o}:{},...r.length>0?{diagnostics:r.map(s=>({code:"unsupported-field",field:s.name,message:`Media attribute '${s.name}' has an unresolved source value`}))}:{}}}function Mx(e,t){return e==="img"?"image":e==="video"||t.includes("poster")?"video":"media"}function Dx(e){return e.some(t=>t.startsWith("cms:"))?"cms-media-field":e.some(t=>/^(\.?\/|\/)/.test(t))?"local-file-reference":"asset-id"}var $s=["set-class-name-source","apply-style-draft"];function ju(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:$s,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element"}]};if(t.resolution&&t.resolution.status!=="resolved")return{kind:"class-name-source",className:"",sourceKind:"dynamic-expression",editable:!1,operationBoundary:[],sourcePath:t.source?.expression,diagnostics:[{code:"dynamic-binding",message:"Style binding is unresolved and cannot be edited"}]};if(t.source?.expression){let n=t.source.expression,r=typeof t.resolvedValue=="string"?t.resolvedValue:t.value!==n?t.value:void 0;return typeof r!="string"?{kind:"class-name-source",className:"",sourceKind:"dynamic-expression",editable:!1,operationBoundary:[],sourcePath:n,diagnostics:[{code:t.resolvedValue===void 0?"dynamic-binding":"non-string-binding",message:t.resolvedValue===void 0?"Style binding is dynamic and cannot be edited":"Style binding must resolve to a static string before it can be edited"}]}:{kind:"class-name-source",className:r,sourceKind:"static-expression",editable:!0,operationBoundary:$s,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:$s}}import{createHash as Lx}from"node:crypto";var pr=class{constructor(t){this.original=new Map,this.files=new Map,this.versions=new Map;for(let n of t)this.original.set(n.path,n.content),this.files.set(n.path,n.content),this.versions.set(n.path,n.version??1)}async readFile(t){let n=this.files.get(t);if(n===void 0)throw new Error(`Snapshot file not found: ${t}`);return n}async readFileBytes(t){return Buffer.from(await this.readFile(t),"utf8")}async getFileInfo(t){let n=this.files.get(t);return n===void 0?null:{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async writeFile(t,n){this.files.set(t,n)}async createExclusive(t,n){if(this.files.has(t))throw Object.assign(new Error(`Snapshot file already exists: ${t}`),{code:"EEXIST"});this.files.set(t,n)}async deleteFile(t){this.files.delete(t)}async exists(t){return this.files.has(t)}async listFiles(t={}){let n=t.roots??[],r=[...this.files.keys()].filter(a=>n.length===0?!0:n.some(c=>a===c||a.startsWith(`${c}/`))),o=[],i=new Set,s=0;for(let a of r.sort()){let c=Buffer.byteLength(this.files.get(a)??"","utf8"),l=a.split("/").length;if(t.maxDepth!==void 0&&l>t.maxDepth){i.add("max-depth");continue}if(t.maxFiles!==void 0&&o.length>=t.maxFiles){i.add("max-files");break}if(t.maxTotalBytes!==void 0&&s+c>t.maxTotalBytes){i.add("max-total-bytes");break}o.push({path:a,sizeBytes:c}),s+=c}return i.size>0?{files:o,truncated:{reasons:[...i]}}:{files:o}}getVersion(t){return this.versions.get(t)??0}bumpVersion(t){let n=this.getVersion(t)+1;return this.versions.set(t,n),n}getChangedFiles(){let t=new Set([...this.original.keys(),...this.files.keys()]),n=[];for(let r of[...t].sort()){let o=this.original.get(r),i=this.files.get(r);o!==i&&n.push({path:r,before:o,after:i})}return n}};function fe(e){return`sha256:${Lx("sha256").update(e).digest("hex")}`}function Vs(e){let t=e.route.graph.elements.get(e.key);if(!t)return{key:e.key,composition:e.route.composition,filePath:"",componentName:"",sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,openingElementRange:{start:0,end:0},version:{documentVersion:e.route.graph.version,contentHash:fe(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=Bx(e.route.source,t);if(!n)return{key:e.key,composition:e.route.composition,filePath:t.sourceFile,componentName:t.componentName,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,openingElementRange:{start:0,end:0},version:{documentVersion:e.route.graph.version,contentHash:fe(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Unable to locate JSX element for key ${t.identity.key}`}]};let r=n.openingElement,o=r.attributes.find(c=>c.type==="JSXAttribute"&&c.name.type==="JSXIdentifier"&&c.name.name==="className"),i={key:e.key,composition:e.route.composition,filePath:t.sourceFile,componentName:t.componentName,openingElementRange:Vu(r),version:{documentVersion:e.route.graph.version,contentHash:fe(e.route.source)}};if(!o)return{...i,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element."}]};let s=o.value,a=s?.type==="StringLiteral"?"stringLiteral":"expression";return{...i,sourceKind:a,attrRaw:$u(e.route.source,o),valueRaw:s?$u(e.route.source,s):null,attrRange:Vu(o),diagnostics:[]}}function Uu(e){let{source:t,oldAttrRange:n,openingElementRange:r,newAttrRaw:o}=e;if(n){let a=n.start>0&&/\s/.test(t[n.start-1]??"")?n.start-1:n.start,c=o?`${a<n.start?" ":""}${o}`:"";return t.slice(0,a)+c+t.slice(n.end)}if(!o)return t;let i=r.end,s=t.slice(Math.max(0,i-2),i)==="/>"?i-2:i-1;return t.slice(0,s)+` ${o}`+t.slice(s)}function Bx(e,t){let n=yt({source:e,profile:on({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=ne(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:jx(t.sourceRange)});return!r.ok||r.match.node.type!=="JSXElement"?null:r.match.node}function Ku(e){let t=yt({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 $u(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function Vu(e){if(e.start==null||e.end==null)throw new Error("AST node does not include offsets.");return{start:e.start,end:e.end}}function jx(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}import*as sa from"@babel/parser";import Hs from"@babel/traverse";import*as S from"@babel/types";import*as Tt from"node:path";import*as Hu from"@babel/parser";import Js from"@babel/traverse";import*as Un from"@babel/types";import*as Y from"@babel/types";function Xo(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?Ko(n,t):null}if(e.isMemberExpression()){let n=Xx(e.node),r=$x(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?Ko(o,[...r,...t]):null}return e.isAwaitExpression()||Ks(e.node)?Xt(Wx(e.node),t,"awaited or fetched expression"):null}function $x(e){let t=[],n=e;for(;Y.isMemberExpression(n);){if(n.computed)if(Y.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(Y.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(Y.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return Y.isIdentifier(n)?t:null}function Ko(e,t=[]){let n=Vx(e,t);if(n)return n;let r=Ux(e,t);if(r)return r;let o=Kx(e,t);return o||null}function gr(e){return e?.kind==="api-source"}function Vx(e,t){if(e.path.isVariableDeclarator()&&Y.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&Us(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return Xt(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&Y.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(c=>Y.isObjectProperty(c)&&zu(c)==="data"&&mr(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&Us(a.node))return Xt(e.identifier.name,t,"query hook data binding")}let n=Jx(e);if(!n||zu(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()||!Us(i.node)?null:Xt(e.identifier.name,t,"query hook data binding")}function Ux(e,t){if(e.path.isVariableDeclarator()&&Y.isArrayPattern(e.path.node.id)){let a=e.path.get("init");if(!a?.isCallExpression()||!Xu(a.node))return null;let[c,l]=e.path.node.id.elements;return!Y.isIdentifier(c)||c.name!==e.identifier.name||!Y.isIdentifier(l)?null:Ju(e,l.name)?Xt(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()||!Xu(o.node)||n.node.elements.findIndex(a=>a===e.path.node)!==0)return null;let s=n.node.elements[1];return Y.isIdentifier(s)&&Ju(e,s.name)?Xt(e.identifier.name,t,"state setter is updated by API data"):null}function Kx(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()?Xt(e.identifier.name,t,"awaited binding result"):Ks(r.node)?Xt(e.identifier.name,t,"fetch-backed binding result"):null:null}function Jx(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 mr(e,t){return Y.isIdentifier(e)?e.name===t:Y.isAssignmentPattern(e)?mr(e.left,t):Y.isObjectPattern(e)?e.properties.some(n=>Y.isObjectProperty(n)?mr(n.value,t):mr(n.argument,t)):Y.isArrayPattern(e)?e.elements.some(n=>!!n&&mr(Y.isRestElement(n)?n.argument:n,t)):!1}function Ju(e,t){let n=!1,r=!1;return e.scope.path.traverse({CallExpression(i){Ks(i.node)&&(n=!0),(zx(i.node.callee,t)||i.node.arguments.some(s=>Y.isIdentifier(s)&&s.name===t))&&(r=!0)}}),n&&r}function Us(e){let t=zo(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function Xu(e){return zo(e.callee)==="useState"}function Ks(e){return Jo(e,t=>Y.isCallExpression(t)&&zo(t.callee)==="fetch")}function Xx(e){let t=e;for(;Y.isMemberExpression(t);)t=t.object;return Y.isIdentifier(t)?t.name:null}function zu(e){return e.computed?null:Y.isIdentifier(e.key)?e.key.name:Y.isStringLiteral(e.key)?e.key.value:null}function zo(e){return Y.isIdentifier(e)?e.name:Y.isMemberExpression(e)&&Y.isIdentifier(e.property)?e.property.name:null}function zx(e,t){return Jo(e,n=>Y.isIdentifier(n)&&n.name===t)}function Jo(e,t){if(t(e))return!0;let n=Y.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(Y.isNode(i)&&Jo(i,t))return!0;continue}if(Y.isNode(o)&&Jo(o,t))return!0}return!1}function Wx(e){return Y.isIdentifier(e)?e.name:Y.isCallExpression(e)?zo(e.callee)??"api":Y.isAwaitExpression(e)?"awaited-api":"api"}function Xt(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:Hx(e,t),reason:n}}function Hx(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var Gu=typeof Js=="function"?Js:Js.default;function Yu(e,t){let n=Qu(e);if(!n)return{allowed:!0};let r=!1;return Gu(n,{CallExpression(o){if(!qu(o.node,t.sourceRange)||!Gx(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||gr(Xo(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function Zu(e,t){let n=Qu(e);if(!n)return{allowed:!0};let r=!1;return Gu(n,{JSXExpressionContainer(o){qu(o.node,t.sourceRange)&&(Un.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 Qu(e){try{return Hu.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Gx(e){let t=e.callee;return Un.isMemberExpression(t)&&Un.isIdentifier(t.property)&&t.property.name==="map"}function qu(e,t){let n=e.loc;return n?Wu({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&Wu({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function Wu(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 le from"@babel/types";function ed(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 St(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return un(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(le.isObjectPattern(n)||le.isArrayPattern(n))return un(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(Zx(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function un(e,t,n=!1){return le.isIdentifier(e)?e.name===t&&n:le.isObjectPattern(e)?e.properties.some(r=>le.isObjectProperty(r)?un(r.value,t,n):un(r.argument,t,n)):le.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=le.isRestElement(r)?r.argument:r;return un(o,t,n)}):le.isAssignmentPattern(e)?un(e.left,t,!0):le.isRestElement(e)?un(e.argument,t,n):!1}function Kn(e,t){if(e.path.isObjectPattern()){if(t){let r=at(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:St(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:St(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=td(r),i=!1,s=o?o.initBinding&&Xs(o.initBinding)?(i=St(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=Kn(o.initBinding,{kind:"identifier",expression:o.initBinding.identifier.name,base:o.initBinding.identifier.name,path:[]});return i=c?.hasDefault??!1,c?[{kind:"property",name:c.propName},...c.remainingPath,...o.initPathPrefix]:null})():null:null,a=at(e.path.node.id,e.identifier.name);if(s&&a){let c=[...s,...a],[l,...u]=c;return!l||l.kind!=="property"?null:{propName:l.name,remainingPath:[...u,...t?.path??[]],hasDefault:i||St(e)}}}}let n=eb(e);if(n){let r=Yx(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||St(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=Qx(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:St(e)}}let i=hr(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:St(e)}:null}if(Xs(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:St(e)}}return null}function Yx(e,t){let n=e.findParent(u=>u.isVariableDeclarator());if(!n?.isVariableDeclarator())return null;let r=n.get("init");if(!r?.isExpression())return null;let o=td(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=Xs(i)?(a=St(i),[...s]):(()=>{let u=Kn(i,{kind:"identifier",expression:i.identifier.name,base:i.identifier.name,path:[]});return a=u?.hasDefault??!1,u?[{kind:"property",name:u.propName},...u.remainingPath,...s]:null})();if(!c)return null;let l=at(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||St(t)}:null}function td(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=tb(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function Xs(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function Zx(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Qx(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=at(i.node,t);if(a)return a}return null}function nd(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=Wo(a,e.identifier.name);if(c&&(!n||c.propName===n))return{propName:c.propName,componentName:t,expressionPath:c.expressionPath,displayPath:`${t}.${c.propName}.default`}}}if(e.path.isObjectPattern())for(let a of e.path.get("properties")){if(!a.isObjectProperty())continue;let c=hr(a.node);if(!c||n&&c!==n)continue;let l=a.get("value");if(!l.isAssignmentPattern())continue;let u=l.get("right");if(u.isExpression())return{propName:c,componentName:t,expressionPath:u,displayPath:`${t}.${c}.default`}}let r=qx(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=hr(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 Wo(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=hr(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&at(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=Wo(o,t);if(i)return i}}else if(n.isRestElement()){let r=n.get("argument");if(!Array.isArray(r)&&(r.isObjectPattern()||r.isArrayPattern())){let o=Wo(r,t);if(o)return o}}}if(e.isArrayPattern())for(let n of e.get("elements")){if(!n)continue;let r=n.isRestElement()&&!Array.isArray(n.get("argument"))?n.get("argument"):n;if(!Array.isArray(r)&&(r.isObjectPattern()||r.isArrayPattern())){let o=Wo(r,t);if(o)return o}}return null}function at(e,t,n=[]){if(le.isIdentifier(e))return e.name===t?n:null;if(le.isObjectPattern(e)){for(let r of e.properties)if(le.isObjectProperty(r)){let o=hr(r);if(!o)continue;let i=at(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(le.isRestElement(r)){let o=at(r.argument,t,n);if(o)return o}}if(le.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=le.isRestElement(o)?o.argument:o,s=at(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return le.isAssignmentPattern(e)?at(e.left,t,n):null}function qx(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function eb(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 hr(e){return e.computed?null:le.isIdentifier(e.key)?e.key.name:le.isStringLiteral(e.key)?e.key.value:null}function tb(e){let t=[],n=e;for(;le.isMemberExpression(n);){if(n.computed)if(le.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(le.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(le.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return le.isIdentifier(n)?{base:n.name,path:t}:null}import{SiteEditSetPropsParamsSchema as sb}from"@vcp-dev/contracts";import*as Et from"@babel/types";import{SiteEditSetPropsParamsSchema as nb}from"@vcp-dev/contracts";function rd(e){let t=e.changes??(e.change?[e.change]:[]);if(!nb.safeParse({kind:"set-props",scope:"selection",changes:t}).success)return yr("invalid-change","Repeat property changes are invalid");if(t.length!==1||t[0].name!==e.target.propertyName)return yr("target-mismatch","A repeat property plan must contain exactly one change for its target property");let r=t[0];if(r.operation==="remove"&&e.target.propertyState==="missing")return{ok:!0,steps:[]};let o=ge(e.source,"value");if(!o.ok)return yr("invalid-target","Repeat property source could not be parsed");let i=[{type:"set-property-binding",order:0,file:e.target.templateFile,locator:e.target.targetElementLocator,name:r.name,object:e.target.callbackItemName,property:r.name}];for(let[s,a]of e.target.parentObjectLocators.entries()){let c=ne(o.ast,a);if(!c.ok||!c.match.path.isObjectExpression())return yr("unsupported-object",`Repeat item ${s} is not a writable object expression`);let l=s===e.target.sourceItemIndex?rb(r):ob(c.match.path.node,r.name);if(!l)return yr("unsupported-property-value",`Repeat item ${s} has an unsupported value for '${r.name}'`);i.push({type:"upsert-object-property",order:i.length,file:e.target.sourceFile,locator:a,name:r.name,value:l})}return{ok:!0,steps:i}}function rb(e){return e.operation==="set"?{kind:"value",value:e.value}:{kind:"undefined"}}function ob(e,t){let n=e.properties.filter(i=>Et.isObjectProperty(i)&&ib(i.key)===t);if(n.length>1)return null;let r=n[0];if(!r)return{kind:"undefined"};if(!Et.isExpression(r.value))return null;let o=ht(r.value);return o.status==="undefined"?{kind:"undefined"}:o.status!=="resolved"?null:{kind:"value",value:o.value}}function ib(e){return Et.isIdentifier(e)?e.name:Et.isStringLiteral(e)?e.value:Et.isNumericLiteral(e)?String(e.value):null}function yr(e,t){return{ok:!1,errorCode:e,reason:t}}function od(e){if(e.change.name!=="className"&&e.change.name!=="class")return xr("unsupported-owner",`No specialized property owner is available for '${e.change.name}'`);let t=e.classNameSource;if(!t||t.filePath!==e.node.file)return xr("owner-source-unavailable","className source details are unavailable for the selected node");if(e.change.name==="class"&&t.sourceKind==="missing")return xr("owner-source-unavailable","The class alias requires an existing className source");if(t.sourceKind==="expression")return xr("owner-source-dynamic","Dynamic className expressions are not writable by the generic property owner");if(e.change.operation==="set"&&typeof e.change.value!="string")return xr("owner-value-invalid","The className owner accepts only string values");if(e.change.operation==="remove"&&t.sourceKind==="missing")return{ok:!0,steps:[]};let n=t.sourceKind==="missing",r=e.change.operation==="set"?`className=${JSON.stringify(e.change.value)}`:null,o=e.change.operation==="remove"?"remove-attribute":n?"create-attribute":"replace-static-classname";return{ok:!0,steps:[{type:"set-class-name-source",order:0,file:e.node.file,request:{kind:"set-class-name-source",key:e.node.key,filePath:e.node.file,expectedVersion:t.version,oldAttrRaw:t.attrRaw,oldAttrRange:t.attrRange,openingElementRange:t.openingElementRange,newAttrRaw:r,intent:{source:"style-panel",operation:o}}}]}}function xr(e,t){return{ok:!1,errorCode:e,reason:t}}async function ad(e){let t=sb.safeParse({kind:"set-props",scope:e.scope,changes:e.changes});if(!t.success)return Pt("invalid-change","Typed property changes are invalid");let n=[];for(let r of t.data.changes){let o=await ab(e,r);if(o){if(!o.ok)return Pt("owner-plan-failed",o.reason);id(n,o.steps);continue}let i=await e.getPropertyState(e.node.key,r.name,e.selectionRef);if(!i)return Pt("missing-property-state",`No authoritative property state is available for '${r.name}'`);if(i.status==="blocked")return Pt("readonly-property",i.diagnostic?.message??`Property '${r.name}' is not writable`);if(!db(i,r)&&!(r.operation==="remove"&&i.status==="missing")){if(i.status==="binding"){let s=i.target;if(s?.kind!=="value-binding"||!s.target.locator||e.scope!=="selection"||r.operation!=="set")return Pt("unsupported-binding",`Property '${r.name}' does not have a safe typed binding write target`);let a=s.target.locator;if(s.target.sourceKind==="repeat-template"&&e.selectionRef?.instanceIndex!==void 0){let c=ub(s.target,e.selectionRef.instanceIndex);if(!c)return Pt("unsupported-binding",`Property '${r.name}' could not resolve the selected repeat item`);a=c}zs(n,{type:"update-value",order:n.length,file:s.target.file,locator:a,value:r.value});continue}if(e.selectionRef?.instanceIndex!==void 0&&e.getRepeatPropertyTarget){let s=await e.getRepeatPropertyTarget(e.node.key,r.name,e.selectionRef);if(s.ok){let a=rd({source:e.getFileContent(s.sourceFile),target:s,changes:[r]});if(!a.ok)return Pt("repeat-target-failed",a.reason);id(n,a.steps);continue}if(i.status==="missing"||i.status==="direct")return Pt("repeat-target-failed",s.reason)}zs(n,{type:"set-property-changes",order:n.length,file:e.node.file,locator:cb(e.node),scope:e.scope,changes:[r]})}}return n.forEach((r,o)=>{r.order=o}),lb(n)?Pt("step-conflict","Property changes resolve to conflicting write steps"):{ok:!0,steps:n}}async function ab(e,t){return t.name!=="className"&&t.name!=="class"?null:od({node:e.node,change:t,classNameSource:e.classNameSource})}function cb(e){return e.structuralPath.includes("#repeat:")||e.key.includes("::repeat-item#")?{kind:"jsx-node",strategy:"source-range",sourceRange:e.sourceRange}:{kind:"jsx-node",strategy:"structural-path",file:e.file,component:e.component,structuralPath:e.structuralPath,expectedRange:e.sourceRange}}function lb(e){let t=new Set;for(let n of e){let{order:r,...o}=n,i=`${n.file}:${n.type}:${JSON.stringify(o)}`;if(t.has(i))return!0;t.add(i)}return!1}function id(e,t){for(let n of t)zs(e,{...n,order:e.length})}function zs(e,t){if(t.type==="set-property-changes"){let n=e.find(r=>r.type==="set-property-changes"&&r.file===t.file&&JSON.stringify(r.locator)===JSON.stringify(t.locator)&&r.scope===t.scope);if(n){n.changes.push(...t.changes);return}}e.push(t)}function ub(e,t){if(!e.locator)return null;let n=e.collectionPathMap?.length??e.collectionIndexMap?.length;if(n!==void 0&&t>=n)return null;let r=e.collectionPathMap?.[t];if(r)return sd(e.locator,r);let o=e.locator.path??[],i=o.findLastIndex(a=>a.kind==="index");if(i<0)return null;let s=o.map((a,c)=>c===i&&a.kind==="index"?{kind:"index",index:e.collectionIndexMap?.[t]??t}:a);return sd(e.locator,s)}function db(e,t){if(t.operation!=="set"||e.status!=="direct")return!1;let n=e.attribute?.resolution;return n?.status==="resolved"?Ws(n.value,t.value):e.attribute?.source===null&&e.attribute.value===t.value}function Ws(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((n,r)=>Ws(n,t[r]));if(e&&t&&typeof e=="object"&&typeof t=="object"){let n=e,r=t,o=Object.keys(n);return o.length===Object.keys(r).length&&o.every(i=>Ws(n[i],r[i]))}return!1}function sd(e,t){return{kind:"value",root:e.root,path:t,expectedRange:e.expectedRange}}function Pt(e,t){return{ok:!1,errorCode:e,reason:t}}var Yt=typeof Hs=="function"?Hs:Hs.default;function he(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 Jn(e){return{file:e.file,component:e.component}}function fb(e){return e.target.kind==="node"?e.target.key:null}function pb(e){return"kind"in e}function Ho(e){return!pb(e)}function ea(e,t){let n=Tt.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Tt.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Gs(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=wt(n,he(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function aa(e){if(!e.component)return"Component";if(e.component.exportName!=="default")return e.component.exportName;let t=e.component.source.replace(/\\/g,"/").replace(/\/$/,""),n=t.split("/").pop()||"Component",i=(n==="index"?t.split("/").slice(-2,-1)[0]||"Component":n).replace(/\.[^.]+$/,"").split(/[^A-Za-z0-9]+/).filter(Boolean);return i.length===0?"Component":i.map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join("")}function et(e){try{return sa.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function mb(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function gb(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 pe(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function pn(e,t){let n=pe(e);return!!(n&&ct(t,n))}function ct(e,t){return t.start>=e.start&&t.end<=e.end}function Id(e){if(S.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(S.isJSXMemberExpression(e)){let t=e;for(;S.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function hb(e,t){let n=pe(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);if(!a||pn(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=Id(i.node.name);s&&o(s,i)}}),[...r].sort()}function cd(e,t,n){let r=et(e);if(!r)return{ok:!0};let o=ne(r,he(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=ne(r,he(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};if(Bd(o.match.path,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let s=hb(o.match.path,i.match.path);return s.length>0?{ok:!1,bindingNames:s}:{ok:!0}}function ld(e,t,n){let r=zt(t,n);return r?At(e,r):null}function zt(e,t){let n=ne(e,he(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:ia(e,t)}function At(e,t){let n=t.findParent(b=>b.isArrowFunctionExpression()||b.isFunctionExpression());if(!n||!n.isArrowFunctionExpression()&&!n.isFunctionExpression())return null;let r=n,o=r.parentPath;if(!o||!o.isCallExpression()&&!o.isOptionalCallExpression())return null;let i=o;if(i.node.arguments.findIndex(b=>b===r.node)!==0)return null;let a=i.get("callee");if(!a.isMemberExpression()&&!a.isOptionalMemberExpression())return null;let c=a.node,l=c.property;if(!S.isIdentifier(l)||l.name!=="map"||c.computed)return null;let u=a.get("object"),d=Qo(e,u.node),p=r.node.params.map(b=>Qo(e,b)),m=pe(i.node),g=pe(r.node);return!d||p.some(b=>b.length===0)||!m||!g?null:{callStart:m.start,callEnd:m.end,callbackStart:g.start,callbackEnd:g.end,collectionExpression:d,callbackParams:p,mapOperator:S.isOptionalMemberExpression(c)&&c.optional?"?.map":".map",collectionNeedsParens:da(u.node),callbackPath:r,collectionPath:u}}function Qo(e,t){let n=pe(t);return n?e.slice(n.start,n.end):""}function Go(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function yb(e,t){let n=pe(e.node);return n?xb(t).some(r=>{let o=pe(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function xb(e){let t=e.callbackPath.node.body;return S.isBlockStatement(t)?Wt(t.body):Gt(t)}function Wt(e){let t=[];for(let n of e){if(S.isReturnStatement(n)){n.argument&&t.push(...Gt(n.argument));continue}if(S.isBlockStatement(n)){t.push(...Wt(n.body));continue}if(S.isIfStatement(n)){let r=S.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...Wt(r)),n.alternate){let o=S.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...Wt(o))}continue}if(S.isSwitchStatement(n)){for(let r of n.cases)t.push(...Wt(r.consequent));continue}S.isTryStatement(n)&&(t.push(...Wt(n.block.body)),n.handler&&t.push(...Wt(n.handler.body.body)),n.finalizer&&t.push(...Wt(n.finalizer.body)))}return t}function Gt(e){return S.isJSXElement(e)?bb(e)?ud(e.children):[e]:S.isJSXFragment(e)?ud(e.children):S.isParenthesizedExpression(e)||S.isTSAsExpression(e)||S.isTSSatisfiesExpression(e)||S.isTSNonNullExpression(e)||S.isTSTypeAssertion(e)?Gt(e.expression):S.isConditionalExpression(e)?[...Gt(e.consequent),...Gt(e.alternate)]:S.isLogicalExpression(e)&&$d(e.operator)?Gt(e.right):[]}function ud(e){return e.flatMap(t=>S.isJSXElement(t)||S.isJSXFragment(t)?Gt(t):S.isJSXExpressionContainer(t)&&(S.isJSXElement(t.expression)||S.isJSXFragment(t.expression)||S.isConditionalExpression(t.expression)||S.isLogicalExpression(t.expression))?Gt(t.expression):[])}function bb(e){let t=e.openingElement.name;return S.isJSXIdentifier(t)?t.name==="Fragment":S.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function Sb(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function Ys(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function dd(e,t,n,r={}){if(!r.preserveConditionalBoundary&&Bd(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=pe(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(c=>ua(c)).map(c=>n.callbackPath.scope.getBinding(c)?.path.node).filter(Boolean)),s=new Set,a=(c,l)=>{let u=l.scope.getBinding(c);if(!u||pn(u.path.node,o)||i.has(u.path.node))return;t.scope.getBinding(c)!==u&&s.add(c)};return e.traverse({ReferencedIdentifier(c){a(c.node.name,c)},JSXOpeningElement(c){let l=Id(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function fd(e,t,n){let r=pe(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>ua(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return ca(e,s=>{let a=s.scope.getBinding(s.node.name);if(!a||pn(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 Eb(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>ua(a)).map(a=>e.callbackPath.scope.getBinding(a)?.path.node).filter(Boolean)),r=new Set,o=(a,c)=>{let l=c.scope.getBinding(a);if(!l||n.has(l.path.node))return;t.scope.getBinding(a)!==l&&r.add(a)},i=e.callbackPath.get("params"),s=Array.isArray(i)?i:[i];for(let a of s)a.traverse({ReferencedIdentifier(c){o(c.node.name,c)},TSTypeReference(c){let l=c.node.typeName;if(S.isIdentifier(l))o(l.name,c);else{let u=vb(l);u&&o(u,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function vb(e){let t=e;for(;S.isTSQualifiedName(t);)t=t.left;return S.isIdentifier(t)?t.name:null}function kd(e,t){let n=pe(e.node),r=new Set;return ca(e,o=>{let i=o.scope.getBinding(o.node.name);if(!i||n&&pn(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 ca(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function Ib(e){let t=kb(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=Vd(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=Lb({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=Ld(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?da(o):!0}}}function kb(e,t,n){let r=wd(e,t);if(Nd(e,r),Pd(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 Yt(e,{JSXElement(s){Md(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:la(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 Cb(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=>Sr(a.file)));if(!t.has(Sr(e.sourceFile))||!t.has(Sr(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(Sr(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=Pb(e.sourceAst,e.sourceComponent);if(!n)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without an exported source component identity"};let r=[];for(let a of e.knownSourceFiles){let c=et(a.content);if(!c)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component because a loaded source file cannot be parsed"};r.push({file:a.file,ast:c})}let o=Rb(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=Cd({ast:a.ast,file:a.file,sourceFile:e.sourceFile,sourceComponent:e.sourceComponent,componentIdentities:o});if(c.hasUnsafeReference)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component because the component has unsupported value usages"};i.push(...c.callSites)}if(i.length!==1)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without a single project-wide component call site"};let[s]=i;return!lt(s.file,e.targetFile)||la(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 Rb(e,t){let n=new Map,r=i=>{let s=Xn(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 wb(i,n))o=r(s)||o}return[...n.values()]}function wb(e,t){let n=[],r=Nb(e,t);for(let o of e.ast.program.body){if(S.isExportDefaultDeclaration(o)&&S.isIdentifier(o.declaration)&&(r.get(o.declaration.name)?.length??0)>0){let i=r.get(o.declaration.name)??[];for(let s of i){if(s.namespace){let a=vr(s.namespace,o.declaration.name,"default");a&&n.push({file:e.file,namespace:a,exportName:s.exportName});continue}n.push({file:e.file,exportName:"default"})}continue}if(S.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=Ir(e.file,o.source.value);for(let s of o.specifiers){if(S.isExportNamespaceSpecifier(s)){let l=Ht(s.exported);for(let u of t.values())lt(u.file,i)&&n.push({file:e.file,namespace:ta(l,u.namespace),exportName:u.exportName});continue}if(!S.isExportSpecifier(s))continue;let a=Ht(s.local),c=[...t.values()].filter(l=>lt(l.file,i)&&dn(l.namespace,a));if(c.length>0){let l=Ht(s.exported);for(let u of c){let d=vr(u.namespace,a,l);d&&n.push({file:e.file,namespace:d,exportName:u.exportName})}continue}t.has(Xn({file:i,exportName:a}))&&n.push({file:e.file,exportName:Ht(s.exported)})}continue}if(S.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!S.isExportSpecifier(i))continue;let s=Ht(i.local),a=r.get(s)??[];if(a.length>0){let c=Ht(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let u=vr(l.namespace,s,c);u&&n.push({file:e.file,namespace:u,exportName:l.exportName})}}}continue}if(S.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=Ir(e.file,o.source.value),s=o.exported;if(s){let a=Ht(s);for(let c of t.values())lt(c.file,i)&&n.push({file:e.file,namespace:ta(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())lt(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function ta(e,t){return t?`${e}.${t}`:e}function dn(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function vr(e,t,n){return!dn(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function Nb(e,t){let n=new Map,r=(i,s)=>{let a=n.get(i)??[];a.push(s),n.set(i,a)};for(let i of e.ast.program.body){if(!S.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=Ir(e.file,i.source.value);for(let a of i.specifiers){if(S.isImportDefaultSpecifier(a)){let c=t.get(Xn({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(u=>lt(u.file,s)&&dn(u.namespace,"default"));for(let u of l){let d=vr(u.namespace,"default",a.local.name);d&&r(a.local.name,{...u,namespace:d})}continue}if(S.isImportSpecifier(a)){let c=Ht(a.imported),l=[...t.values()].filter(d=>lt(d.file,s)&&dn(d.namespace,c));for(let d of l)r(a.local.name,d);let u=t.get(Xn({file:s,exportName:c}));u&&r(a.local.name,u);continue}if(S.isImportNamespaceSpecifier(a))for(let c of t.values())lt(c.file,s)&&r(a.local.name,{...c,namespace:ta(a.local.name,c.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(S.isVariableDeclaration(i))for(let s of i.declarations){if(!S.isIdentifier(s.id)||!s.init)continue;let a=zn(s.init);if(!a||!S.isIdentifier(a))continue;let c=n.get(a.name)??[];if(c.length===0)continue;let l=n.get(s.id.name)??[],u=new Set(l.map(Xn));for(let d of c){let p=vr(d.namespace,a.name,s.id.name),m=p?{...d,namespace:p}:d,g=Xn(m);u.has(g)||(r(s.id.name,m),u.add(g),o=!0)}}}return n}function Xn(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${ra(e.file)}#${t}`}function Ht(e){return S.isIdentifier(e)?e.name:e.value}function Pb(e,t){for(let n of e.program.body){if(S.isExportDefaultDeclaration(n)){let o=n.declaration;if((S.isFunctionDeclaration(o)||S.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(S.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!S.isExportNamedDeclaration(n))continue;let r=n.declaration;if((S.isFunctionDeclaration(r)||S.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(S.isVariableDeclaration(r)){for(let o of r.declarations)if(S.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!S.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:S.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function Cd(e){let t=Ab(e),n=[],r=Pd(e.ast,t);return Yt(e.ast,{JSXElement(o){lt(e.file,e.sourceFile)&&la(o)===e.sourceComponent||Md(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function Rd(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function wd(e,t){let n=Rd();return Yt(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function Ab(e){let t=Rd();return lt(e.file,e.sourceFile)&&Tb(t,wd(e.ast,e.sourceComponent)),Yt(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=Ir(e.file,o),s=e.componentIdentities.filter(a=>lt(a.file,i));if(s.length!==0)for(let a of r.specifiers){let c=n.scope.getBinding(a.local.name);if(c){if(S.isImportDefaultSpecifier(a)&&s.some(l=>l.exportName==="default")&&t.localBindings.add(c),S.isImportDefaultSpecifier(a)){let l=s.filter(u=>dn(u.namespace,"default"));if(l.length>0){let u=t.namespaceMembers.get(c)??new Set;for(let d of l){let p=md(d,"default");p&&u.add(p)}t.namespaceMembers.set(c,u)}continue}if(S.isImportSpecifier(a)){let l=S.isIdentifier(a.imported)?a.imported.name:a.imported.value,u=s.filter(d=>dn(d.namespace,l));if(u.length>0){let d=t.namespaceMembers.get(c)??new Set;for(let p of u){let m=md(p,l);m&&d.add(m)}t.namespaceMembers.set(c,d);continue}s.some(d=>!d.namespace&&d.exportName===l)&&t.localBindings.add(c);continue}if(S.isImportNamespaceSpecifier(a))for(let l of s){let u=l.namespace?`${l.namespace}.${l.exportName}`:l.exportName,d=t.namespaceMembers.get(c)??new Set;d.add(u),t.namespaceMembers.set(c,d)}}}}}),Nd(e.ast,t),t}function Tb(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 Nd(e,t){Yt(e,{VariableDeclarator(n){if(!n.node.init)return;let r=zn(n.node.init);if(r){if(S.isIdentifier(n.node.id)){let o=fn(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&na(t,i,o);return}if(S.isObjectPattern(n.node.id)){let o=fn(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&_d(n.node.id,o.namespaceMembers,t,n)}}}})}function Pd(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return Yt(e,{ReferencedIdentifier(r){if(n){r.stop();return}_b(r)||!r.isIdentifier()||!Ad(r,t)||Fb(r,t)||Ob(r)||(n=!0,r.stop())}}),n}function _b(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 Ad(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)&&fn(r.node,t,r)?r:null}function Fb(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!pd(e,r))return!1;let o=Ad(e,t);if(!o)return!1;if(zn(r.node)===o.node)return!!fn(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&pd(e,a)&&!!fn(a.node,t,a)}function Ob(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function pd(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function fn(e,t,n){let r=zn(e);if(!r)return null;if(S.isIdentifier(r)){let a=n.scope.getBinding(r.name);if(!a)return null;let c=t.namespaceMembers.get(a);return t.localBindings.has(a)?{local:!0,namespaceMembers:new Set,unsupported:!1}:c?{local:!1,namespaceMembers:new Set(c),unsupported:!1}:null}if(S.isObjectExpression(r))return Mb(r,t,n);let o=Od(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?Td(s,o.slice(1).join(".")):null}function Mb(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!S.isObjectProperty(i))continue;let s=Fd(i);if(!s||!S.isExpression(i.value)){S.isExpression(i.value)&&(o||=fn(i.value,t,n)!==null);continue}let a=fn(i.value,t,n);if(a){o||=a.unsupported,a.local&&r.add(s);for(let c of a.namespaceMembers)r.add(`${s}.${c}`)}}return r.size>0||o?{local:!1,namespaceMembers:r,unsupported:o}:null}function Td(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 na(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 _d(e,t,n,r){for(let o of e.properties){if(S.isRestElement(o)){if(S.isIdentifier(o.argument)){let c=r.scope.getBinding(o.argument.name);c&&na(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!S.isObjectProperty(o))continue;let i=Fd(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=Td(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=S.isAssignmentPattern(o.value)?o.value.left:o.value;if(S.isIdentifier(a)){let c=r.scope.getBinding(a.name);c&&na(n,c,s);continue}if(S.isObjectPattern(a)&&s.namespaceMembers.size>0){_d(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function Fd(e){return e.computed?S.isStringLiteral(e.key)||S.isNumericLiteral(e.key)?String(e.key.value):null:Db(e.key)}function Db(e){return S.isIdentifier(e)?e.name:S.isStringLiteral(e)||S.isNumericLiteral(e)?String(e.value):null}function zn(e){return S.isParenthesizedExpression(e)||S.isTSAsExpression(e)||S.isTSSatisfiesExpression(e)||S.isTSNonNullExpression(e)||S.isTSTypeAssertion(e)?zn(e.expression):S.isExpression(e)?e:null}function Od(e){if(S.isIdentifier(e))return[e.name];if((S.isMemberExpression(e)||S.isOptionalMemberExpression(e))&&!e.computed&&S.isIdentifier(e.property)){let t=zn(e.object),n=t?Od(t):null;return n?[...n,e.property.name]:null}return null}function md(e,t){if(!dn(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 Md(e,t){let n=e.node.openingElement.name;if(S.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=Dd(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 Dd(e){if(S.isJSXIdentifier(e))return[e.name];if(S.isJSXMemberExpression(e)){let t=Dd(e.object);return t?[...t,e.property.name]:null}return null}function la(e){let t=e.getFunctionParent();if(!t)return null;if(t.isFunctionDeclaration())return t.node.id?.name??null;if(t.isArrowFunctionExpression()||t.isFunctionExpression()){let n=t.parentPath;if(n?.isVariableDeclarator()&&S.isIdentifier(n.node.id))return n.node.id.name}return null}function Lb(e){let t=pe(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||pn(a.path.node,t))return;let c=$b(s,a,t);if(c){if(c.hasDefault){o="Cannot move prop-backed repeat child because the collection prop has a default value that cannot be preserved safely";return}let u=Ub(e.callSitePath,c.propName,e.source);if(!u.ok){o=u.reason;return}let d=Bb(u.expression,c.remainingPath);if(!d){o="Cannot move prop-backed repeat child because the mapped prop path is not a portable expression";return}let p=kd(u.expressionPath,e.targetParentPath);if(!p.ok){o=p.reason??`Cannot move prop-backed repeat child because the mapped prop source is not visible at the target: ${p.bindingNames.join(", ")}`;return}n.set(`${c.range.start}:${c.range.end}`,{...c.range,text:d});return}e.targetParentPath.scope.getBinding(s.node.name)!==a&&r.add(s.node.name)};return e.sourceContext.collectionPath.isIdentifier()&&e.sourceContext.collectionPath.isReferencedIdentifier()&&i(e.sourceContext.collectionPath),e.sourceContext.collectionPath.traverse({ReferencedIdentifier(s){s.isIdentifier()&&i(s)}}),o?{ok:!1,reason:o}:r.size>0?{ok:!1,reason:`Cannot move prop-backed repeat child because the collection depends on bindings outside the target scope: ${[...r].sort().join(", ")}`}:n.size===0?{ok:!1,reason:"Cannot move repeat-backed child out of its component without an explicit prop mapping"}:{ok:!0,collectionExpression:Kb(e.source,t,[...n.values()])}}function Bb(e,t){if(t.length===0)return e;let n=Ld(e);if(!n)return null;let r=da(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=jb(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function jb(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function $b(e,t,n){let r=Vb(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=Kn(t,o);if(!i)return null;let s=r?.range??pe(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function Vb(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!pn(n.node,t)||n.node.computed||!S.isIdentifier(n.node.property))return null;let r=pe(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function Ub(e,t,n){let r=e.get("openingElement").get("attributes");if(r.some(c=>c.isJSXSpreadAttribute()))return{ok:!1,reason:"Cannot move prop-backed repeat child through spread props; use an explicit prop mapping"};let o=r.find(c=>c.isJSXAttribute()&&S.isJSXIdentifier(c.node.name)&&c.node.name.name===t);if(!o?.isJSXAttribute())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not passed explicitly`};let i=o.get("value");if(!i.isJSXExpressionContainer())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not an expression`};let s=i.get("expression");if(!s.isExpression())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not a usable expression`};let a=Qo(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 Kb(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 Ld(e){try{let n=sa.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=S.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&S.isExpression(r)?r:null}catch{return null}}function Jb(e){let t=pe(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||pn(s.path.node,t))return;let a=gd(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let u=gd(c,e.targetFile,e.targetFile);(!u||u.moduleFile!==a.moduleFile||!Xb(u.importSpec,a.importSpec))&&r.add(a.localName);return}let l=n.get(a.moduleSpecifier)??[];l.some(u=>JSON.stringify(u)===JSON.stringify(a.importSpec))||l.push(a.importSpec),n.set(a.moduleSpecifier,l);return}r.add(i.node.name)};return ca(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 Xb(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 gd(e,t,n){let r=zb(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=Ir(t,i),a=i.startsWith(".")?ea(n,s):i;if(r.isImportDefaultSpecifier()){let c=r.node.local.name;return{localName:c,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"default",local:c}}}if(r.isImportNamespaceSpecifier()){let c=r.node.local.name;return{localName:c,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"namespace",local:c}}}if(r.isImportSpecifier()){let c=S.isIdentifier(r.node.imported)?r.node.imported.name:r.node.imported.value,l=r.node.local.name;return{localName:l,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"named",imported:c,local:l===c?void 0:l}}}return null}function zb(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function Ir(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?Tt.normalize(Tt.join(Tt.dirname(e),t)).replace(/\\/g,"/"):t}function lt(e,t){return ra(e)===ra(t)}function ra(e){let t=Sr(e);return t.endsWith("/index")?t.slice(0,-6):t}function Sr(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function ua(e){let t=[],n=r=>{if(r){if(S.isIdentifier(r)){t.push(r.name);return}if(S.isObjectPattern(r)){for(let o of r.properties){if(S.isRestElement(o)){n(o.argument);continue}S.isObjectProperty(o)&&n(o.value)}return}if(S.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(S.isAssignmentPattern(r)){n(r.left);return}if(S.isRestElement(r)){n(r.argument);return}S.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function Wb(e){let t=[];for(let n of e.callbackPath.node.params){if(S.isIdentifier(n)){t.push(n.name);continue}if(S.isRestElement(n)&&S.isIdentifier(n.argument)){t.push(`...${n.argument.name}`);continue}return{ok:!1,reason:"Cannot move cross-file repeat child because the callback parameters are not portable to the target file"}}return{ok:!0,callbackParams:t}}function Hb(e,t){return{...e,callbackParams:t}}function hd(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function da(e){return!(S.isIdentifier(e)||S.isThisExpression(e)||S.isMemberExpression(e)||S.isOptionalMemberExpression(e)||S.isCallExpression(e)||S.isOptionalCallExpression(e))}function Bd(e,t){return jd(e,t).length>0}function Zs(e,t){let n=pe(e.node),r=pe(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()&&!Gb(o,n,r)))return!0;o=o.parentPath}return!1}function Gb(e,t,n){let r=pe(e.node.consequent);if(r&&ct(r,t)&&!ct(r,n))return!1;let o=e.node.alternate?pe(e.node.alternate):null;return!(o&&ct(o,t)&&!ct(o,n))}function jd(e,t){let n=pe(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=pe(o.node.consequent),a=pe(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()&&$d(o.node.operator)){let s=pe(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 yd(e,t,n,r){let o=jd(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=Qo(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=Yb(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${Qb(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function Yb(e,t){return Zb(e.node)?t:`(${t})`}function Zb(e){return S.isIdentifier(e)||S.isThisExpression(e)||S.isSuper(e)||S.isMemberExpression(e)||S.isOptionalMemberExpression(e)||S.isCallExpression(e)||S.isOptionalCallExpression(e)||S.isBooleanLiteral(e)||S.isNumericLiteral(e)||S.isStringLiteral(e)||S.isNullLiteral(e)||S.isUnaryExpression(e)}function $d(e){return e==="&&"||e==="||"||e==="??"}function Qb(e){return e.trim().startsWith("<")?e:`(${e})`}function Vd(e,t){let n=pe(e.node),r=pe(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=xd(e),i=xd(t);if(!o||!i||!qb(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=eS(s.node,n);if(a&&!ct(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=pe(s.node.right);if(a&&ct(a,n)&&!ct(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())&&tS(s)){let a=pe(s.node.body)??pe(s.node);if(a&&!ct(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 xd(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?pe(t.node.argument):null;if(t.isArrowFunctionExpression()&&(S.isJSXElement(t.node.body)||S.isJSXFragment(t.node.body)||S.isConditionalExpression(t.node.body)||S.isLogicalExpression(t.node.body)))return pe(t.node.body);t=t.parentPath}return null}function qb(e,t){return e.start===t.start&&e.end===t.end}function eS(e,t){let n=pe(e.consequent);if(n&&ct(n,t))return n;let r=pe(e.alternate);return r&&ct(r,t)?r:null}function tS(e){let t=e.parentPath;if(!t||!t.isCallExpression()&&!t.isOptionalCallExpression()||t.node.arguments[0]!==e.node)return!1;let n=t.node.callee;return(S.isMemberExpression(n)||S.isOptionalMemberExpression(n))&&S.isIdentifier(n.property)&&n.property.name==="map"&&!n.computed}var nS={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 Yo(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=nS[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 rS(e,t){for(let n of e.program.body){if(!S.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>S.isImportDefaultSpecifier(o));if(r&&S.isImportDefaultSpecifier(r))return r.local.name}return null}function oS(e,t,n){for(let r of e.program.body){if(!S.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>S.isImportSpecifier(i)&&(S.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&S.isImportSpecifier(o))return o.local.name}return null}function bd(e){let t=new Set;return Yt(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function Sd(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function iS(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=aa(e),o=et(t);if(n.exportName!=="default"){let a=o?oS(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?Sd(r,bd(o)):r;return{localName:c,importStep:Qs(e,c)}}if(!o)return{localName:r,importStep:Qs(e,r)};let i=rS(o,n.source);if(i)return{localName:i};let s=Sd(r,bd(o));return{localName:s,importStep:Qs(e,s)}}function sS(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??aa(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 aS(e){if(e.kind==="native-tag")return e.text===void 0?{kind:e.kind,tag:e.tag}:{kind:e.kind,tag:e.tag,text:e.text};if(!e.component)return{kind:e.kind};let t=e.props?cS(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function cS(e){return Object.fromEntries(Object.entries(e).filter(t=>oa(t[1])))}function oa(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(oa):typeof e=="object"?Object.values(e).every(oa):!1}function lS(e,t){let n=et(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=Cd({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 Qs(e,t=aa(e)){if(!e.component)throw new Error("Materialized component calls do not have a component import");return{moduleSpecifier:e.component.source,imports:e.component.exportName==="default"?[{kind:"default",local:t}]:[{kind:"named",imported:e.component.exportName,...t!==e.component.exportName?{local:t}:{}}]}}function Ed(e,t){if("kind"in e)return{parentNode:null,anchorNode:null,placement:e.relation};if("parentKey"in e)return{parentNode:t.getNode(e.parentKey),anchorNode:null,placement:e.relation};let n=t.getNode(e.anchorKey);return{parentNode:n?.parentKey?t.getNode(n.parentKey)??n:n,anchorNode:n,placement:e.relation}}function uS(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function br(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function fa(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function Er(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:fa(e,t.slice(0,n)),index:r.index}}return null}function qs(e,t){return e.locator?e.collectionPathMap?.[t]?fa(e.locator,e.collectionPathMap[t]):Er(e.locator)?fS(e.locator,pS(t,e.collectionIndexMap)):null:null}function dS(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:Ud(o,t)}function Ud(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=Ud(r,t);return o===void 0?void 0:{[n.name]:o}}function Zo(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 fS(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},fa(e,i)}return null}function pS(e,t){return t?.[e]??e}function vd(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 mS(e,t){return gS(e.root,t.root)&&yS(e.path??[],t.path??[])}function gS(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&&hS(e.sourceRange,t.sourceRange)}}function hS(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function ia(e,t){let n=null;return Yt(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 yS(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 qo=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:br(t.kind,t.params.kind)};let r=t,o=this.resolveNodeRequest(t);if(!o.ok)return o.result;let i=o.node,s=this.graph.getFileVersion(i.file);return t.documentVersion!==s?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${s})`}:this.planUpdateText(n,r,i,this.graph.getCapability(i.key),await this.graph.getTextWriteTarget(i.key,r.params.segmentIndex))}case"update-array-item":{if(t.params.kind!=="update-array-item")return{ok:!1,errorCode:"unknown",reason:br(t.kind,t.params.kind)};let r=t,o=this.resolveNodeRequest(t);if(!o.ok)return o.result;let i=o.node,s=this.graph.getFileVersion(i.file);return t.documentVersion!==s?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${s})`}:this.planUpdateArrayItem(n,r,this.graph.getCapability(i.key),await this.graph.getTextWriteTarget(i.key,r.params.segmentIndex))}case"remove-node":{if(t.params.kind!=="remove-node")return{ok:!1,errorCode:"unknown",reason:br(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:br(t.kind,t.params.kind)};let r=t;if(!Ho(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=Ed(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:br(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=fb(t);if(!n)return{ok:!1,result:{ok:!1,errorCode:"invalid-target",reason:`Operation '${t.kind}' requires a node target`}};let r=this.graph.getNode(n);return r?{ok:!0,node:r}:{ok:!1,result:{ok:!1,errorCode:"locator-miss",reason:`Target key '${n}' not found in graph`}}}planNodeAttributeOperation(t,n,r){let o=r.file,i=this.graph.getCapability(r.key);return n.params.filePath!==o?{ok:!1,errorCode:"stale-version",reason:"The className source file changed before save."}:this.buildPlan(t,n,[{order:0,file:o,type:"set-class-name-source",request:{...n.params,key:r.key}}],i)}async planSetProps(t,n,r){let o=this.graph.getCapability(r.key),i=await this.buildTypedPropertySteps({node:r,scope:n.params.scope,changes:n.params.changes,selectionRef:n.selectionRef});return i.ok?this.buildPlan(t,n,i.steps,o):xS(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.buildStyleDraftPropertySteps({initialOrder:s.length,node:r,props:n.params.props,selectionRef:n.selectionRef});if(!a.ok)return a;s.push(...a.steps)}return this.buildPlan(t,n,s,i)}async buildTypedPropertySteps(t){let n=this.graph.getPropertyState;return n?ad({node:t.node,scope:t.scope,changes:t.changes,selectionRef:t.selectionRef,getPropertyState:n,getRepeatPropertyTarget:this.graph.getRepeatPropertyTarget,getFileContent:r=>this.graph.getFileContent(r),getFileVersion:r=>this.graph.getFileVersion(r),classNameSource:this.graph.getClassNameSource?.(t.node.key)??void 0}):{ok:!1,errorCode:"missing-property-state",reason:"Typed property planning requires authoritative property provenance"}}async buildStyleDraftPropertySteps(t){let{initialOrder:n,node:r,props:o,selectionRef:i}=t,s=[],a=[];for(let[c,l]of Object.entries(o)){if(l===void 0)continue;let u=await this.graph.getElementPropertyWriteTarget?.(r.key,c),d=r.attributes?.find(p=>p.name===c);if(!(typeof d?.resolvedValue=="string"&&d.resolvedValue===l||d?.source===null&&d.value===l)){if(u?.kind==="external-entry")return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite readonly external property '${c}'`};if(u?.kind==="value-binding"&&u.locator){let p=u.locator;if(u.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let m=qs(u,i.instanceIndex);if(!m)return{ok:!1,errorCode:"invalid-params",reason:"apply-style-draft could not resolve the selected repeat item"};p=m}s.push({order:n+s.length,file:u.file,type:"update-value",locator:p,value:l});continue}a.push({operation:"set",name:c,value:l})}}return a.length>0&&s.push({order:n+s.length,file:r.file,type:"set-property-changes",locator:he(r),scope:"selection",changes:a}),{ok:!0,steps:s}}buildTextRewriteSteps(t,n,r,o,i){if(o?.kind==="value-binding"&&o.locator){if(o.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let a=qs(o,i.instanceIndex);if(!a)return{ok:!1,errorCode:"invalid-params",reason:"update-text could not resolve the selected repeat item"};let c=this.coerceTextValueForValueTarget(o.file,a,r);return c.ok?{ok:!0,steps:[{order:0,file:o.file,type:"update-array-item",locator:a,value:c.value}]}:c}let s=this.coerceTextValueForValueTarget(o.file,o.locator,r);return s.ok?{ok:!0,steps:[{order:0,file:o.file,type:"update-value",locator:o.locator,value:s.value}]}:s}return{ok:!0,steps:o?.kind==="external-entry"?[{order:0,file:`external:${o.sourceId}`,type:"invoke-external-adapter",sourceType:o.sourceType,sourceId:o.sourceId,adapterId:o.adapterId,capability:"write-text",value:r}]:[{order:0,file:t.file,type:"update-text",locator:he(t),segmentIndex:n,newText:r}]}}coerceTextValueForValueTarget(t,n,r,o="update-text"){let i=this.graph.getFileContent(t),s=et(i);if(!s)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not inspect the value source`};let a=ne(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!mb(a.match.path))return{ok:!0,value:r};let c=gb(r);return c===null?{ok:!1,errorCode:"invalid-params",reason:`${o} value must be a valid number for numeric source`}:{ok:!0,value:c}}planUpdateArrayItem(t,n,r,o){if(!r.canUpdateText)return{ok:!1,errorCode:"capability-denied",reason:"Cannot update repeated text on this node"};if(o?.kind!=="value-binding"||o.sourceKind!=="repeat-template"||!o.locator)return{ok:!1,errorCode:"invalid-params",reason:"update-array-item requires a writable repeat-template source"};let{index:i,value:s}=n.params,a=o.collectionPathMap?.length??o.collectionIndexMap?.length;if(a!==void 0&&i>=a)return{ok:!1,errorCode:"invalid-params",reason:`update-array-item index ${i} is outside the repeated source`};let c=qs(o,i);if(!c)return{ok:!1,errorCode:"invalid-params",reason:"update-array-item could not resolve the selected repeat item"};let l=this.coerceTextValueForValueTarget(o.file,c,s,"update-array-item");return l.ok?this.isValueTargetUnchanged(o.file,c,l.value)?{ok:!1,errorCode:"invalid-params",reason:"update-array-item value is unchanged"}:this.buildPlan(t,n,[{order:0,file:o.file,type:"update-array-item",locator:c,value:l.value}],r):l}isValueTargetUnchanged(t,n,r){let o=et(this.graph.getFileContent(t));if(!o)return!1;let i=ne(o,n);if(!i.ok)return!1;let s=i.match.path;if(s.isStringLiteral())return typeof r=="string"&&s.node.value===r;if(s.isNumericLiteral())return typeof r=="number"&&Object.is(s.node.value,r);if(s.isBooleanLiteral())return typeof r=="boolean"&&s.node.value===r;if(s.isNullLiteral())return r===null;if(s.isUnaryExpression({operator:"-"})){let a=s.get("argument");return typeof r=="number"&&!Array.isArray(a)&&a.isNumericLiteral()&&Object.is(-a.node.value,r)}return!1}planUpdateText(t,n,r,o,i){if(!o.canUpdateText)return{ok:!1,errorCode:"capability-denied",reason:"Cannot update text on this node"};let s=this.buildTextRewriteSteps(r,n.params.segmentIndex,n.params.value,i,n.selectionRef);return s.ok?this.buildPlan(t,n,s.steps,o):s}async planRemoveNode(t,n,r,o){if(!o.canRemove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot remove this node"};let i=await this.graph.getTextWriteTarget(r.key,0);if(i?.kind==="external-entry")return this.buildPlan(t,n,[{order:0,file:`external:${i.sourceId}`,type:"invoke-external-adapter",sourceType:i.sourceType,sourceId:i.sourceId,adapterId:i.adapterId,capability:"remove-node",value:{operation:"remove-node"}}],o);if(r.isRepeatItemRoot){let d=i;if(d?.kind==="value-binding"&&d.locator){let p=Er(d.locator);if(p)return this.buildPlan(t,n,[{order:0,file:d.file,type:"remove-bound-array-item",locator:p.locator,index:p.index}],o)}return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed node removal requires a writable array target"}}let s=Zo(r,i,this.graph.getTextProvenance?.(r.key,0)??null);if(s)return{ok:!1,errorCode:"unsupported-operation",reason:s};let a=this.getRepeatBackedTemplateStructureReason(r);if(a)return{ok:!1,errorCode:"unsupported-operation",reason:a};let c=await this.getUpstreamBackedDescendantReason(r);if(c)return{ok:!1,errorCode:"unsupported-operation",reason:c};let l=[{order:0,file:r.file,type:"remove-node",locator:he(r),removeWhitespace:!0}],u=this.buildRemoveComponentImportStep(r);return u&&l.push({...u,order:l.length}),this.buildPlan(t,n,l,o)}buildRemoveComponentImportStep(t,n=this.graph.getFileContent(t.file)){if(!t.importedFrom||!t.exportName||!t.tag||lS(n,t)>1)return null;let r=ea(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(!Ho(n.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};if(n.params.node.kind==="component-call"&&!n.params.node.component)return{ok:!1,errorCode:"unsupported-operation",reason:"Materialized component insertion requires the materialization transaction planner"};if(!o.canInsertChild)return{ok:!1,errorCode:"capability-denied",reason:"Cannot insert child into this node"};let s=this.graph.getEditableTextSegmentIndex(r.key),a=s!==null?await this.graph.getTextWriteTarget(r.key,s):null,c=Zo(r,a,s!==null?this.graph.getTextProvenance?.(r.key,s)??null:null);if(c)return{ok:!1,errorCode:"unsupported-operation",reason:c};let l=await this.getUpstreamBackedDescendantReason(r);if(l)return{ok:!1,errorCode:"unsupported-operation",reason:l};let u=await this.planExternalBackedInsertChild(t,n,r,o,i,a);if(u)return u;let d=await this.planRepeatBackedInsertChild(t,n,r,o);if(d)return d;let p=this.getRepeatBackedTemplateStructureReason(r);if(p)return{ok:!1,errorCode:"unsupported-operation",reason:p};let m=Yu(this.graph.getFileContent(r.file),r);if(!m.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:m.reason??"Cannot insert child into this node"};let g=Yo(r,n.params.node);if(g)return{ok:!1,errorCode:"unsupported-operation",reason:g};let b=[],C=0,I=n.params.node.kind==="component-call"?iS(n.params.node,this.graph.getFileContent(r.file)):void 0,w=I?.importStep;return w&&b.push({order:C++,file:r.file,type:"add-import",moduleSpecifier:w.moduleSpecifier,imports:w.imports}),b.push({order:C++,file:r.file,type:"insert-child",parentLocator:he(r),node:{jsx:sS(n.params.node,I?.localName)},placement:n.params.position.relation,anchorLocator:i?he(i):void 0}),this.buildPlan(t,n,b,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!Ho(n.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let a=s?.kind==="external-entry"?s:await this.findExternalInsertContext(r,i);if(!a)return null;let c=i?await this.graph.getTextWriteTarget(i.key,0):null;return this.buildPlan(t,n,[{order:0,file:`external:${a.sourceId}`,type:"invoke-external-adapter",sourceType:a.sourceType,sourceId:a.sourceId,adapterId:a.adapterId,capability:"insert-child",value:{operation:"insert-child",relation:n.params.position.relation,parentKey:r.key,anchorSourceId:c?.kind==="external-entry"?c.sourceId:null,node:aS(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(!Ho(n.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};if(n.params.position.relation!=="append"&&n.params.position.relation!=="prepend")return null;let i=n.params.node;if(i.kind!=="native-tag"||i.text===void 0||!this.graph.getChildNodes)return null;let s=this.graph.getChildNodes(r.key).find(d=>d.isRepeatItemRoot&&d.tag?.toLowerCase()===i.tag.toLowerCase());if(!s)return null;let a=await this.graph.getTextWriteTarget(s.key,0);if(!a||a.kind!=="value-binding"||!a.locator)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires a writable value target"};let c=Er(a.locator);if(!c)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let l=dS(a.locator,i.text);if(l===void 0)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child could not infer an item shape from the template"};let u=n.params.position.relation==="prepend"?vd(0,a.collectionIndexMap):vd(a.collectionIndexMap?.length??c.index+1,a.collectionIndexMap);return this.buildPlan(t,n,[{order:0,file:a.file,type:"insert-bound-array-item",locator:c.locator,index:u,value:l}],o)}async getUpstreamBackedDescendantReason(t){if(!this.graph.getChildNodes)return null;let n=[...this.graph.getChildNodes(t.key)];for(;n.length>0;){let r=n.shift();if(!r)continue;let o=this.graph.getEditableTextSegmentIndex(r.key),i=o!==null?await this.graph.getTextWriteTarget(r.key,o):null,s=Zo(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=et(this.graph.getFileContent(t.file));if(!n)return t.isRepeatItemRoot===!0;let r=ne(n,he(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:ia(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=At(this.graph.getFileContent(t.file),o);return i?yb(o,i):t.isRepeatItemRoot===!0}isInsideMapCallback(t){let n=et(this.graph.getFileContent(t.file));if(!n)return!1;let r=ne(n,he(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:ia(n,t);return o?!!o.findParent(i=>{if(!i.isCallExpression()&&!i.isOptionalCallExpression())return!1;let s=i.node.callee;return(S.isMemberExpression(s)||S.isOptionalMemberExpression(s))&&S.isIdentifier(s.property)&&s.property.name==="map"}):!1}planRepeatTemplateInternalMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&this.isRepeatTemplateRootNode(r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=et(c);if(!l)return null;let u=zt(l,r),d=zt(l,o);if(!u||!d)return null;let p=At(c,u),m=At(c,d);if(!Go(p,m))return null;if(a&&(s==="before"||s==="after")){let b=zt(l,a),C=b?At(c,b):null;if(!Go(p,C))return null}if(Zs(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let g=cd(c,r,o);return g.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:he(r),targetParentLocator:he(o),placement:s,anchorLocator:a?he(a):void 0,selectionContext:Jn(o)}],i):{ok:!1,errorCode:"unsupported-operation",reason:g.reason??`Cannot move node because it depends on bindings outside the target scope: ${g.bindingNames.join(", ")}`}}planRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&this.isRepeatTemplateRootNode(r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=et(c);if(!l)return null;let u=zt(l,r),d=zt(l,o);if(!u||!d)return null;let p=At(c,u);if(!p)return null;let m=At(c,d);if(Go(p,m))return null;if(m&&!Sb(m,p))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")){let A=ld(c,l,a);if(m&&!Go(m,A)||!m&&A)return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child relative to a repeat-template anchor outside the target scope"}}if(r.tag&&r.tag.toLowerCase()===r.tag){let A=Yo(o,{kind:"native-tag",tag:r.tag});if(A)return{ok:!1,errorCode:"unsupported-operation",reason:A}}let g=Gs(this.graph,r);if(!g)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Zs(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let b=yd(c,u,d,g);for(let A of b.conditionPaths){let O=fd(A,d,p);if(!O.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${O.bindingNames.join(", ")}`}}let C=dd(u,d,p,{preserveConditionalBoundary:b.conditionPaths.length>0});if(!C.ok)return{ok:!1,errorCode:"unsupported-operation",reason:C.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${C.bindingNames.join(", ")}`};let I=Eb(p,d);if(!I.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its callback parameters depend on bindings outside the target scope: ${I.bindingNames.join(", ")}`};let w=p;if(r.component!==o.component){let A=Ib({source:c,ast:l,sourceContext:p,sourceNode:r,targetParent:o,targetParentPath:d});if(!A.ok)return{ok:!1,errorCode:"unsupported-operation",reason:A.reason};w=A.context}else{let A=kd(p.collectionPath,d);if(!A.ok)return{ok:!1,errorCode:"unsupported-operation",reason:A.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${A.bindingNames.join(", ")}`}}return this.buildPlan(t,n,[{order:0,file:r.file,type:"move-repeat-template-child",locator:he(r),targetParentLocator:he(o),placement:s,anchorLocator:a?he(a):void 0,repeatExpression:hd(w,b.sourceJsx),selectionContext:Jn(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&this.isRepeatTemplateRootNode(r)||r.file===o.file)return null;let c=this.graph.getFileContent(r.file),l=this.graph.getFileContent(o.file),u=et(c),d=et(l);if(!u||!d)return null;let p=Cb({knownSourceFiles:this.graph.getKnownSourceFiles?.(),routeEntryFiles:this.graph.getRouteEntryFiles?.(),sourceAst:u,sourceFile:r.file,targetFile:o.file,sourceComponent:r.component,targetComponent:o.component});if(!p.ok)return{ok:!1,errorCode:"unsupported-operation",reason:p.reason};let m=zt(u,r),g=zt(d,o);if(!m||!g)return null;let b=Vd(p.callSitePath,g);if(!b.ok)return{ok:!1,errorCode:"unsupported-operation",reason:b.reason};let C=At(c,m);if(!C)return null;if(At(l,g))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")&&ld(l,d,a))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child relative to a repeat-template anchor outside the target scope"};if(r.tag&&r.tag.toLowerCase()===r.tag){let M=Yo(o,{kind:"native-tag",tag:r.tag});if(M)return{ok:!1,errorCode:"unsupported-operation",reason:M}}let w=Gs(this.graph,r);if(!w)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Zs(m,g))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let A=yd(c,m,g,w);for(let M of A.conditionPaths){let j=fd(M,g,C);if(!j.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${j.bindingNames.join(", ")}`}}let O=dd(m,g,C,{preserveConditionalBoundary:A.conditionPaths.length>0});if(!O.ok)return{ok:!1,errorCode:"unsupported-operation",reason:O.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${O.bindingNames.join(", ")}`};let ie=Jb({sourceFile:r.file,targetFile:o.file,sourceContext:C,targetParentPath:g});if(!ie.ok)return{ok:!1,errorCode:"unsupported-operation",reason:ie.reason};let oe=Wb(C);if(!oe.ok)return{ok:!1,errorCode:"unsupported-operation",reason:oe.reason};let N=Hb(C,oe.callbackParams),W=[{order:0,file:r.file,type:"remove-node",locator:he(r),removeWhitespace:!0}];for(let M of ie.imports)W.push({order:W.length,file:o.file,type:"add-import",moduleSpecifier:M.moduleSpecifier,imports:M.imports});return W.push({order:W.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:he(o),expression:hd(N,A.sourceJsx),placement:s,anchorLocator:a?he(a):void 0,selectionContext:Jn(o)}),this.buildPlan(t,n,W,i)}async planMoveNode(t,n,r,o){if(!o.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};let i=Ed(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(uS(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 I=n.params.target.relation,w=i.anchorNode&&(I==="before"||I==="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:I,anchorSourceId:w?.kind==="external-entry"?w.sourceId:null,parentKey:"parentKey"in n.params.target?n.params.target.parentKey:null}}],o)}let c=r.file!==s.file,l=n.params.target.relation,u=i.anchorNode,d=Zo(r,a,this.graph.getTextProvenance?.(r.key,0)??null);if(d&&!Ys(d))return{ok:!1,errorCode:"unsupported-operation",reason:d};if(r.isRepeatItemRoot&&u?.isRepeatItemRoot&&r.repeatOwnerKey&&r.repeatOwnerKey===u.repeatOwnerKey&&(l==="before"||l==="after")){let I=a,w=await this.graph.getTextWriteTarget(u.key,0);if(I?.kind==="value-binding"&&w?.kind==="value-binding"&&I.locator&&w.locator){let A=Er(I.locator),O=Er(w.locator);if(A&&O&&I.file===w.file&&mS(A.locator,O.locator)){let ie=A.index,oe=O.index,N=l==="before"?oe-(ie<oe?1:0):oe+(ie<oe?0:1);return this.buildPlan(t,n,[{order:0,file:I.file,type:"move-array-item",locator:A.locator,fromIndex:ie,toIndex:N}],o)}}}if(r.isRepeatItemRoot&&this.isRepeatTemplateRootNode(r))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed item outside its collection"};let p=this.getRepeatBackedTemplateStructureReason(r),m=Ys(d)?d:p;if(m&&Ys(m)){let I=this.planRepeatTemplateInternalMove(t,n,r,s,o,l,u);if(I)return I;let w=this.planRepeatTemplateHoistMove(t,n,r,s,o,l,u);if(w)return w;let A=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,l,u);return A||{ok:!1,errorCode:"unsupported-operation",reason:m}}if(p)return{ok:!1,errorCode:"unsupported-operation",reason:p};let g=await this.getUpstreamBackedDescendantReason(r);if(g)return{ok:!1,errorCode:"unsupported-operation",reason:g};if(r.tag&&r.tag.toLowerCase()===r.tag){let I=Yo(s,{kind:"native-tag",tag:r.tag});if(I)return{ok:!1,errorCode:"unsupported-operation",reason:I}}if(c)return this.planCrossFileMove(t,n,r,s,o,l,u);let b=cd(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 C=[{order:0,file:r.file,type:"move-node",locator:he(r),targetParentLocator:he(s),placement:l,anchorLocator:u?he(u):void 0,selectionContext:Jn(s)}];return this.buildPlan(t,n,C,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,u=this.graph.getFileContent(r.file),d=Gs(this.graph,r)??`<${r.component} />`,p=Zu(u,r);if(!p.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:p.reason??"Cannot move subtree across files"};if(c.push({order:l++,file:r.file,type:"remove-node",locator:he(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let g=r.tag??r.component,C={moduleSpecifier:ea(o.file,r.importedFrom),imports:r.exportName==="default"?[{kind:"default",local:g}]:[{kind:"named",imported:r.exportName,local:g===r.exportName?void 0:g}]};c.push({order:l++,file:o.file,type:"add-import",moduleSpecifier:C.moduleSpecifier,imports:C.imports}),c.push({order:l++,file:o.file,type:"insert-child",parentLocator:he(o),node:{jsx:d},placement:s,anchorLocator:a?he(a):void 0,selectionContext:Jn(o)})}else c.push({order:l++,file:o.file,type:"insert-child",parentLocator:he(o),node:{jsx:d},placement:s,anchorLocator:a?he(a):void 0,selectionContext:Jn(o)});let m=this.buildRemoveComponentImportStep(r,u);return m&&c.push({...m,order:l++}),this.buildPlan(t,n,c,i)}buildPlan(t,n,r,o){let s=[...new Set(r.map(a=>a.file))].map(a=>({file:a,content:this.graph.getFileContent(a),version:this.graph.getFileVersion(a),exists:!0,sha256:fe(this.graph.getFileContent(a))}));return{ok:!0,plan:{operationId:t,kind:n.kind,target:n.target,documentVersion:n.documentVersion,steps:r,preSnapshots:s,validatedCapability:o}}}};function xS(e){return{ok:!1,errorCode:e.errorCode==="readonly-property"?"capability-denied":e.errorCode==="missing-property-state"||e.errorCode==="repeat-target-failed"||e.errorCode==="unsupported-binding"?"unsupported-operation":"invalid-params",reason:e.reason}}import kr from"node:path";import*as qd from"@babel/parser";import pa from"@babel/traverse";import*as v from"@babel/types";var ef=typeof pa=="function"?pa:pa.default;function tf(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}var Kd=new WeakMap;function Jd(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 nf(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=Ca(s,t,n);if(!a)return null;let c=Ra(a,r.sourceRange);if(!c)return null;let l=r.source??await ft({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!l){let m=await Fa({currentFile:t,expressionPath:c,readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:new Set});if(!m)return null;if(m.kind==="external")return{kind:"external-entry",file:m.file,sourceType:m.sourceType,sourceId:m.sourceId,adapterId:m.adapterId,displayExpression:m.displayPath};let g={kind:"value",root:m.root,path:m.path.length>0?m.path:[]};return{kind:"value-binding",file:m.file,locator:g,root:m.root,path:m.path,displayExpression:m.displayExpression??wr(c.node,n),sourceKind:m.sourceKind,...m.collectionIndexMap?{collectionIndexMap:m.collectionIndexMap}:{},...m.collectionPathMap?{collectionPathMap:m.collectionPathMap}:{}}}let u=new Set,d=await zS({currentFile:t,expressionPath:c,segment:{...r,source:l},readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:u});if(!d)return null;if(d.kind==="external")return{kind:"external-entry",file:d.file,sourceType:d.sourceType,sourceId:d.sourceId,adapterId:d.adapterId,displayExpression:d.displayPath};let p={kind:"value",root:d.root,path:d.path.length>0?d.path:[]};return{kind:"value-binding",file:d.file,locator:p,root:d.root,path:d.path,displayExpression:d.displayExpression??l.expression,sourceKind:d.sourceKind,...d.collectionIndexMap?{collectionIndexMap:d.collectionIndexMap}:{},...d.collectionPathMap?{collectionPathMap:d.collectionPathMap}:{}}}async function Wn(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Ca(i,t,n);if(!s)return null;let a=e.expression!==void 0?(e.sourceRange?af(s,n,e.expression,e.sourceRange):null)??Pa(s,n,e.expression):e.sourceRange?Ra(s,e.sourceRange):null;if(!a)return null;let c=vS(a),l=new Set,u=e.sourceInfo??await ft({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:l}),d=u?await Xe({currentFile:t,expressionPath:c,sourceInfo:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:l}):await sE({currentFile:t,expressionPath:c,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:l});return ES(d,e.expression??wr(c.node,n))}async function ka(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Ca(i,t,n);if(!s)return Je("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?IS({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}):kS({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}function rf(e){try{return qd.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Ca(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=rf(n);return e.set(t,{source:n,ast:o}),o}function Ra(e,t){let n=null,r=-1;for(let o of Rr(e).expressions){let i=o.node.loc;if(!i||!wa(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s>=r&&(n=o,r=s)}return n}function bS(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of Rr(e).expressions){if(!SS(o.node.loc,t))continue;let i=(o.node.end??0)-(o.node.start??0);i<=r&&(n=o,r=i)}return n}function of(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of Rr(e).jsxElements){let i=o.node.loc;if(!i||!wa(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s<=r&&(n=o,r=s)}return n}function Rr(e){let t=Kd.get(e);if(t)return t;let n={expressions:[],jsxElements:[]};return ef(e,{Expression(r){n.expressions.push(r)},JSXElement(r){n.jsxElements.push(r)}}),Kd.set(e,n),n}function SS(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 wa(e,t){let n=Xd({line:e.start.line,column:e.start.column},{line:t.startLine,column:t.startColumn}),r=Xd({line:e.end.line,column:e.end.column},{line:t.endLine,column:t.endColumn});return n>=0&&r<=0}function sf(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 Xd(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 ft(e){if(v.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!v.isMemberExpression(e.expression))return null;let t=await xf(e.expression,e.scope,e.currentFile,e.readFile,e.exists,e.fileCache,e.visited);return t?{kind:t.path.some(n=>n.kind==="index")?"index-expression":"member-expression",expression:wr(e.expression,e.source),base:t.base,path:t.path}:null}function ES(e,t){if(!e)return null;if(e.kind==="external")return{kind:"external-entry",file:e.file,sourceType:e.sourceType,sourceId:e.sourceId,adapterId:e.adapterId,displayExpression:e.displayPath};let n={kind:"value",root:e.root,path:e.path.length>0?e.path:[]};return{kind:"value-binding",file:e.file,locator:n,root:e.root,path:e.path,displayExpression:e.displayExpression??t,sourceKind:e.sourceKind,...e.collectionIndexMap?{collectionIndexMap:e.collectionIndexMap}:{},...e.collectionPathMap?{collectionPathMap:e.collectionPathMap}:{}}}function vS(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 wr(e,t){if(t)return Na(e,t);let n=gE(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function Na(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Pa(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of Rr(e).expressions){if(Na(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function af(e,t,n,r){let o=null,i=Number.POSITIVE_INFINITY;for(let s of Rr(e).expressions){if(Na(s.node,t)!==n)continue;let a=s.node.loc;if(!a||!wa(a,r))continue;let c=(s.node.end??0)-(s.node.start??0);c<=i&&(o=s,i=c)}return o}async function IS(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=Ra(r,o.sourceRange),u=o.source??(l?await ft({expression:l.node,scope:l.scope,source:n,currentFile:t,readFile:i,exists:s,fileCache:a,visited:c}):null);if(!u){if(!l)return CS(t,o.value);let p=await Fa({currentFile:t,expressionPath:l,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});return p?p.kind==="external"?Yd(t,p):ba(t,wr(l.node,n),p):RS({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return Je("unsupported-expression","Unable to locate text expression for provenance resolution");let d=await Xe({currentFile:t,expressionPath:l,sourceInfo:u,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});if(!d){let p=xa(l.node);if(p)return Je(p.code,p.message);let m=l.scope.getBinding(u.base);if(m?.path.isVariableDeclarator()){let g=xa(m.path.node.init);if(g)return Je(g.code,g.message)}return m?.path.isVariableDeclarator()&&v.isCallExpression(m.path.node.init)?wS("unsupported-expression",ff(m.path.node.init,e.functionCallContracts)):Je("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return d.kind==="external"?Yd(t,d):ba(t,u.expression,d)}async function kS(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return Je("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=Pa(r,n,o.conditionExpression);if(!l)return Je("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await Xe({currentFile:t,expressionPath:l,sourceInfo:o.conditionSource,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});if(!u)return Je("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(u.kind==="external")return Je("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let d=ba(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 CS(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 RS(e){let t=await lf(e);if(t.length===0)return Je("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(NS(e.expression))return cf(t);if(df(e.expression))return Je("unsupported-expression","i18n helpers require a static message id string");if(v.isMemberExpression(e.expression)&&e.expression.computed&&!v.isNumericLiteral(e.expression.property)&&!v.isStringLiteral(e.expression.property))return Je("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return Je(n.code,n.message)}function Je(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function wS(e,t){return cf([{code:e,message:t}])}function cf(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function NS(e){return v.isCallExpression(e)||v.isConditionalExpression(e)||v.isLogicalExpression(e)||v.isBinaryExpression(e)}function Cr(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 lf(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=xa(t);if(l)return[l];if(v.isCallExpression(t))return[{code:"unsupported-expression",message:ff(t,c)}];if(v.isMemberExpression(t)&&t.computed){let u=t.property;if(!v.isNumericLiteral(u)&&!v.isStringLiteral(u)){if(!v.isExpression(u))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let p=await pt(u,n,r,o,i,s,a);if(typeof p!="string"&&!Number.isInteger(p))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}]}}return v.isBinaryExpression(t)?Cr([...await ma(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):v.isLogicalExpression(t)?Cr([...await ma(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"}]):v.isConditionalExpression(t)?Cr([...await ma(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 xa(e){return df(e)?zd("i18n helpers require a static message id string"):FS(e)?zd("CMS helpers require static entry id and field path string arguments"):null}async function ma(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await lf({...t,expression:o}));return r}function PS(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:[AS(e.sourceType)]}}async function Aa(e){for(let n of LS){if(!Wd(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return Gd(Hd(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(!Wd(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return Gd(Hd(r),e.externalAdapters)}return null}function AS(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function TS(e){return{code:"external-source-readonly",message:e}}function zd(e){return{code:"unsupported-expression",message:e}}function Ta(e){return!e||!v.isCallExpression(e)?null:v.isIdentifier(e.callee)?e.callee.name:v.isMemberExpression(e.callee)&&!e.callee.computed&&v.isIdentifier(e.callee.object)&&v.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function Wd(e,t){if(!t||t.length===0)return!0;let n=Ta(e.node);return n?t.includes(n):!1}function Hd(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:Cr(e.diagnostics??[])}:{match:e,diagnostics:[]}}function Gd(e,t){let n=PS(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:Cr([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function _S(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!v.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!v.isStringLiteral(n)||!v.isStringLiteral(r))return null;let o=n.value,i=r.value;return{sourceType:"cms-field",sourceId:`${o}:${i}`,file:`cms://${o}/${i.replace(/\./g,"/")}`,displayPath:`${o}.${i}`}}function FS(e){return!!e&&v.isCallExpression(e)&&v.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!v.isStringLiteral(e.arguments[0])||!v.isStringLiteral(e.arguments[1]))}function uf(e){if(!(!e||!v.isCallExpression(e))){if(v.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&v.isStringLiteral(t)?t.value:null}if(v.isMemberExpression(e.callee)&&!e.callee.computed&&v.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&v.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!v.isObjectExpression(t))return null;for(let n of t.properties)if(v.isObjectProperty(n)&&!n.computed&&(v.isIdentifier(n.key)&&n.key.name==="id"||v.isStringLiteral(n.key)&&n.key.value==="id")&&v.isStringLiteral(n.value))return n.value.value;return null}}}function df(e){return uf(e)===null}async function OS(e,t,n){let r=new Set,o=kr.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=kr.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"]:[kr.posix.join(i,"locales"),kr.posix.join(i,"messages")];for(let a of s){let c=kr.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function MS(e){let t=uf(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await OS(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function DS(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!v.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!v.isExpression(n))return null;let o=await pt(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:[TS("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var LS=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>_S(e)},{helperNames:["apiField"],resolve:e=>DS(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>MS({currentFile:e,expressionPath:t,exists:n})}];function Yd(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 ba(e,t,n){let r={kind:"value",root:n.root,path:n.path.length>0?n.path:[]},o=n.path.some(l=>l.kind==="index"),i=XS(n),s;n.semanticKind?s=n.semanticKind:i?s="config-entry":n.sourceKind==="repeat-template"?s="repeat-template":n.path.length===0?s=n.sourceKind==="imported-binding"?"imported-binding":"binding":s=o?"array-item":"object-field";let a=n.displayExpression??t,c=[...n.chainPrefix??[]];return n.sourceKind==="binding"?c.push({kind:"binding",file:n.file,displayName:n.root.kind==="binding"?n.root.name:a,canEditHere:!0}):n.sourceKind==="imported-binding"?c.push({kind:"imported-binding",file:n.file,displayName:n.root.kind==="named-export"?n.root.name:"default",canEditHere:!0}):n.sourceKind==="repeat-template"&&c.push({kind:"repeat-template",file:n.file,displayName:t,canEditHere:!0}),n.path.length>0&&n.sourceKind!=="repeat-template"&&c.push({kind:o?"array-item":"object-field",file:n.file,displayName:a,canEditHere:!0}),i&&c.push({kind:"config-entry",file:n.file,displayName:i.displayPath,canEditHere:!0}),{finalSource:{kind:s,file:n.file,locator:r,root:n.root,path:n.path,displayPath:a,externalSource:i?{sourceType:"config-entry",sourceId:i.sourceId}:void 0},chain:c,confidence:n.sourceKind==="repeat-template"?"safe-derived":"exact",editMode:n.editMode??(n.file===e?"direct":"proxy"),diagnostics:n.diagnostics??[]}}var BS=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function _a(e,t){let n=[...BS,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function ff(e,t){let n=e.callee;return v.isIdentifier(n)&&_a(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 Fa(e){let t=await Aa(e);if(t)return t;let n=await pf({...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 ft({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 Xe({...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 KS(e)}async function pf(e){let t=await ut({...e,allowComposed:!1});return t?.kind==="source"?t.provenance:null}async function ut(e){let t=jS(e.expressionPath),n=US(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 ft({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 Xe({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 ft({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 Xe({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 ut({...e,expressionPath:r,allowComposed:!0}),a=await ut({...e,expressionPath:o,allowComposed:!1}),c=await ut({...e,expressionPath:i,allowComposed:!1});return ga(s,a,c)}if(t.isCallExpression())return $S({...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 ut({...e,expressionPath:r,allowComposed:!0}),s=await ut({...e,expressionPath:o,allowComposed:!0});return ga(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 ut({...e,expressionPath:r,allowComposed:!0}),s=await ut({...e,expressionPath:o,allowComposed:!0});return ga(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:ut({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function jS(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 $S(e){let t=Ta(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:ut({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(v.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:ut({...e,expressionPath:o,allowComposed:!1})}}return null}function ga(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!VS(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function VS(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 US(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function KS(e){if(!e.expressionPath.isCallExpression())return null;let t=Ta(e.expressionPath.node);if(!t)return null;let n=_a(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 mf({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 mf(e){let t=await Aa({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 ft({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 Xe({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 Fa({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 JS(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!v.isCallExpression(t))return null;let n=t.callee;if(!v.isIdentifier(n))return null;let r=_a(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 mf({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 XS(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=ti(t,e.path);return{sourceId:o,displayPath:o}}async function zS(e){let t=e.segment.source;return t?Xe({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 Xe(e){let t=e.sourceInfo,n=gf(e.expressionPath,t.base);if(n){let l=await hf({currentFile:e.currentFile,callPath:n.callPath,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,fileCache:e.fileCache,visited:e.visited});if(!l){let b=HS(n.callPath,[...n.basePath,...t.path]);return gr(b)?Jd(e.currentFile,b.sourceId,b.displayPath):null}let u=hE(l,[...n.basePath,...t.path]),d=l.collectionIndexMap?.[0]??0,p=[...l.pathPrefix??[],{kind:"index",index:d},...n.basePath,...t.path],m=[{kind:"index",index:0},...n.basePath,...t.path];return dt(l.value,m)===void 0?null:{kind:"value",file:l.file,root:l.root,path:u?.[0]??p,sourceKind:"repeat-template",collectionIndexMap:l.collectionIndexMap,...u?{collectionPathMap:u}:{}}}let r=e.expressionPath.scope.getBinding(t.base);if(!r)return null;if(r.path.isImportNamespaceSpecifier()){let l=t.path[0],u=r.path.parentPath;if(!l||l.kind!=="property"||!u?.isImportDeclaration())return null;let d=await Nn(e.currentFile,u.node.source.value,e.exists);if(!d)return null;let p=await ei({file:d,exportName:l.name,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(!p||p.kind==="external")return null;let m=t.path.slice(1);return dt(p.value,m)===void 0?null:{kind:"value",file:p.file,root:p.root,path:m,sourceKind:"imported-binding",collectionIndexMap:p.collectionIndexMap}}let o=ed(r);if(o){let l=o.expressionPath,u=await ft({expression:l.node,scope:l.scope,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(u){let d=await Xe({...e,expressionPath:l,sourceInfo:{...u,expression:ti(u.expression,t.path),path:[...u.path,...t.path]}});if(d)return d}if(t.path.length===0){let d=await pf({currentFile:e.currentFile,expressionPath:l,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(d)return d}}if(r.kind==="param")return dE({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 JS({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=Ko(r,t.path);if(gr(s))return Jd(e.currentFile,s.sourceId,s.displayPath);let a=await gn({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:dt(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 gf(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=at(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!WS(s,r)?null:{callPath:s,basePath:i}}function WS(e,t){let n=e.node.callee;return!v.isMemberExpression(n)||!v.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}async function hf(e){let{currentFile:t,callPath:n,readFile:r,exists:o,fileCache:i,visited:s}=e,a=n.node.callee;if(!v.isMemberExpression(a)||!v.isIdentifier(a.property)||a.property.name!=="map")return null;let c=n.get("callee");if(!c.isMemberExpression())return null;let l=c.get("object");if(Array.isArray(l)||!l.isExpression())return null;let u=await Nr({currentFile:t,expressionPath:l,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});return!u||!Array.isArray(u.value)||u.value.length===0?null:u}function HS(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:Xo(r,t)}async function Nr(e){let{currentFile:t,expressionPath:n,readFile:r,exists:o,fileCache:i,visited:s}=e;if(n.isIdentifier()){let a=n.scope.getBinding(n.node.name);if(!a)return null;let c=await gn({currentFile:t,binding:a,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});return c?.kind==="static"?c:null}if(n.isCallExpression())return yf({currentFile:t,callPath:n,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(n.isTSAsExpression()||n.isTSSatisfiesExpression()||n.isTSNonNullExpression()){let a=n.get("expression");if(!Array.isArray(a)&&a.isExpression())return Nr({...e,expressionPath:a})}if(n.isArrayExpression()){let a=sf(n.node);if(!a)return null;let c=await pt(n.node,n.scope,t,r,o,i,s);return Array.isArray(c)?{kind:"static",file:t,root:{kind:"expression",sourceRange:a},value:c,sourceKind:"binding"}:null}if(n.isMemberExpression()){let a=await ft({expression:n.node,scope:n.scope,currentFile:t,readFile:r,exists:o,fileCache:i,visited:s});if(!a)return null;let c=await Xe({currentFile:t,expressionPath:n,sourceInfo:a,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(!c||c.kind==="external")return null;let l=await GS({currentFile:t,expressionPath:n,provenance:c,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(!l||l.kind!=="static")return null;if(c.collectionPathMap?.length){let d=yE(l.value,c.collectionPathMap);if(d)return{kind:"static",file:c.file,root:c.root,value:d.value,sourceKind:c.sourceKind,collectionPathMap:d.collectionPathMap}}let u=dt(l.value,c.path);return Array.isArray(u)?{kind:"static",file:c.file,root:c.root,value:u,sourceKind:c.sourceKind,pathPrefix:c.path,collectionIndexMap:c.collectionIndexMap,collectionPathMap:c.collectionPathMap}:null}return null}async function GS(e){let{provenance:t}=e;if(t.root.kind==="binding"){let i=e.expressionPath.scope.getBinding(t.root.name);if(!i&&t.file!==e.currentFile){let s=await Zt(t.file,e.readFile,e.fileCache);i=s.ast?va(s.ast).getBinding(t.root.name):void 0}return i?await gn({currentFile:t.file,binding:i,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited}):null}if(t.root.kind!=="expression")return null;let n=await Zt(t.file,e.readFile,e.fileCache);if(!n.ast)return null;let r=bS(n.ast,t.root.sourceRange);if(!r)return null;let o=await pt(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 yf(e){return await YS(e)??await ZS(e)??await QS(e)}async function YS(e){let{callPath:t}=e,n=t.node.callee;if(!v.isMemberExpression(n)||!v.isIdentifier(n.property)||n.property.name!=="filter")return null;let r=t.get("callee");if(!r.isMemberExpression())return null;let o=r.get("object");if(Array.isArray(o)||!o.isExpression())return null;let i=await Nr({currentFile:e.currentFile,expressionPath:o,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(!i||!Array.isArray(i.value))return null;let[s]=t.node.arguments;if(!v.isArrowFunctionExpression(s)&&!v.isFunctionExpression(s))return null;let a=s.params[0];if(!v.isIdentifier(a))return null;let c=qS(s);if(!c)return null;let l=[],u=[],d=[];for(let[p,m]of i.value.entries()){let g=eE(c,a.name,m);if(typeof g!="boolean")return null;if(g){l.push(m),u.push(i.collectionIndexMap?.[p]??p);let b=i.collectionPathMap?.[p];b&&d.push(b)}}return{...i,value:l,pathPrefix:i.pathPrefix,collectionIndexMap:u,...d.length>0?{collectionPathMap:d}:{}}}async function ZS(e){let{callPath:t}=e,n=t.node.callee;if(!v.isMemberExpression(n)||!v.isIdentifier(n.property)||n.property.name!=="slice")return null;let r=t.get("callee");if(!r.isMemberExpression())return null;let o=r.get("object");if(Array.isArray(o)||!o.isExpression())return null;let i=await Nr({currentFile:e.currentFile,expressionPath:o,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(!i||!Array.isArray(i.value))return null;let[s,a]=t.node.arguments,c=Zd(s,0),l=Zd(a,i.value.length);if(c===null||l===null)return null;let u=Math.max(0,c<0?i.value.length+c:c),d=Math.max(0,l<0?i.value.length+l:l),p=i.value.map((g,b)=>i.collectionIndexMap?.[b]??b).slice(u,d),m=i.collectionPathMap?.slice(u,d);return{...i,value:i.value.slice(u,d),pathPrefix:i.pathPrefix,collectionIndexMap:p,...m?{collectionPathMap:m}:{}}}function Zd(e,t){return e?v.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}async function QS(e){let{callPath:t}=e,n=t.node.callee;if(!v.isMemberExpression(n)||!v.isIdentifier(n.property)||n.property.name!=="sort"&&n.property.name!=="toSorted")return null;let r=t.get("callee");if(!r.isMemberExpression())return null;let o=r.get("object");if(Array.isArray(o)||!o.isExpression())return null;let i=await Nr({currentFile:e.currentFile,expressionPath:o,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(!i||!Array.isArray(i.value))return null;let[s]=t.node.arguments;if(!v.isArrowFunctionExpression(s)&&!v.isFunctionExpression(s))return null;let[a,c]=s.params;if(!v.isIdentifier(a)||!v.isIdentifier(c))return null;let l=i.value.map((d,p)=>({value:d,sourceIndex:i.collectionIndexMap?.[p]??p,originalIndex:p})),u=[...l];for(let d of l)for(let p of l)if(Qd(s,a.name,c.name,d.value,p.value)===void 0)return null;return u.sort((d,p)=>{let m=Qd(s,a.name,c.name,d.value,p.value)??0;return m===0?d.originalIndex-p.originalIndex:m}),{...i,value:u.map(d=>d.value),pathPrefix:i.pathPrefix,collectionIndexMap:u.map(d=>d.sourceIndex),...i.collectionPathMap?{collectionPathMap:u.map(d=>i.collectionPathMap?.[d.originalIndex]).filter(d=>!!d)}:{}}}function Qd(e,t,n,r,o){let i=v.isExpression(e.body)?e.body:e.body.body.find(a=>v.isReturnStatement(a))?.argument;if(!i||!v.isExpression(i))return;let s=Sa(i,t,n,r,o);return typeof s=="number"?s:void 0}function Sa(e,t,n,r,o){if(v.isNumericLiteral(e)||v.isStringLiteral(e)||v.isBooleanLiteral(e))return e.value;if(v.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(v.isMemberExpression(e)){let i=Ea(e,t);if(i)return dt(r,i);let s=Ea(e,n);return s?dt(o,s):void 0}if(v.isBinaryExpression(e)&&e.operator==="-"){let i=v.isExpression(e.left)?Sa(e.left,t,n,r,o):void 0,s=v.isExpression(e.right)?Sa(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function qS(e){if(v.isExpression(e.body))return e.body;for(let t of e.body.body)if(v.isReturnStatement(t)&&t.argument&&v.isExpression(t.argument))return t.argument;return null}function eE(e,t,n){let r=mn(e,t,n);return typeof r=="boolean"?r:void 0}function mn(e,t,n){if(v.isStringLiteral(e)||v.isNumericLiteral(e)||v.isBooleanLiteral(e))return e.value;if(v.isNullLiteral(e))return null;if(v.isIdentifier(e))return e.name===t?n:void 0;if(v.isMemberExpression(e)){let r=Ea(e,t);return r?dt(n,r):void 0}if(v.isUnaryExpression(e)&&e.operator==="!"){let r=mn(e.argument,t,n);return r===void 0?void 0:!r}if(v.isLogicalExpression(e)){let r=mn(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&mn(e.right,t,n);if(e.operator==="||")return r||mn(e.right,t,n)}if(v.isBinaryExpression(e)){let r=v.isExpression(e.left)?mn(e.left,t,n):void 0,o=v.isExpression(e.right)?mn(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 Ea(e,t){let n=[],r=e;for(;v.isMemberExpression(r);){if(r.computed)if(v.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(v.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!v.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!v.isIdentifier(r)||r.name!==t?null:n}async function gn(e){let{currentFile:t,binding:n,readFile:r,exists:o,fileCache:i,visited:s}=e,a=`${t}::${n.kind}::${n.identifier.name}`;if(s.has(a))return null;s.add(a);try{let c=await tE({currentFile:t,binding:n,readFile:r,exists:o,fileCache:i,visited:s});if(c)return c;if(n.path.isImportSpecifier()||n.path.isImportDefaultSpecifier())return await mE({currentFile:t,binding:n,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,fileCache:i,visited:s});if(n.kind==="param")return null;if(n.path.isVariableDeclarator()){let l=n.path.node.init;if(!l||!v.isExpression(l))return null;let u=n.path.get("init");if(u&&!Array.isArray(u)&&u.isExpression()){let p=await Aa({currentFile:t,expressionPath:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(p)return p;if(u.isCallExpression()){let m=await yf({currentFile:t,callPath:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(m)return m}}let d=await pt(l,n.path.scope,t,r,o,i,s);return d===void 0?null:{kind:"static",file:t,root:{kind:"binding",name:n.identifier.name},value:d,sourceKind:"binding"}}if(n.path.isIdentifier()&&n.path.parentPath?.isExportDefaultDeclaration()){let l=n.path.parentPath.node.declaration;if(!v.isExpression(l))return null;let u=await pt(l,n.path.scope,t,r,o,i,s);return u===void 0?null:{kind:"static",file:t,root:{kind:"binding",name:n.identifier.name},value:u,sourceKind:"binding"}}return null}finally{s.delete(a)}}async function tE(e){let{currentFile:t,binding:n,readFile:r,exists:o,fileCache:i,visited:s}=e;if(!n.path.isVariableDeclarator()||!n.path.get("id").isArrayPattern())return null;let a=n.path,c=a.node.init;if(!c||!v.isCallExpression(c))return null;let l=nE(c);if(!l||!v.isArrayPattern(a.node.id)||a.node.id.elements.findIndex(g=>v.isIdentifier(g)&&g.name===n.identifier.name)!==0)return null;let d=l==="useReducer"?1:0,p=c.arguments[d];if(!p||!v.isExpression(p))return null;let m=await pt(p,a.scope,t,r,o,i,s);return m===void 0?null:{kind:"static",file:t,root:{kind:"hook-state",name:n.identifier.name,hook:l},value:m,sourceKind:"binding"}}function nE(e){return v.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:v.isMemberExpression(e.callee)&&v.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function rE(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()||!v.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 oE(e,t){let n=rE(e.path);if(!n)return null;let r=Kn(e,t);return r?{...n,...r}:null}function ti(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function iE(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}async function sE(e){let t=cE(e.expressionPath.node);if(!t||!lE(t.segments))return null;let n=await Xe({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 aE({...e,rootPath:n.path,segments:t.segments});return r?{...n,path:r.collectionPathMap[0]??n.path,sourceKind:"repeat-template",displayExpression:wr(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:r.collectionPathMap}:null}async function aE(e){let t=null,n,r=[];for(let i of e.segments){if(i.kind!=="dynamic")continue;let s=await ft({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=gf(e.expressionPath,s.base);if(!a)return null;let c=await hf({currentFile:e.currentFile,callPath:a.callPath,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(!c||!Array.isArray(c.value))return null;let l=c.value.map((u,d)=>{let p=dt(c.value,[{kind:"index",index:d},...a.basePath,...s.path]);return uE(p)});if(l.some(u=>u===null)||t!==null&&t!==l.length)return null;t=l.length,n??=c.collectionIndexMap,r.push(l)}if(t===null||t===0)return null;let o=[];for(let i=0;i<t;i+=1){let s=[...e.rootPath],a=0;for(let c of e.segments){if(c.kind==="dynamic"){let l=r[a]?.[i];if(!l)return null;s.push(l),a+=1;continue}s.push({...c})}o.push(s)}return{...n?{collectionIndexMap:n}:{},collectionPathMap:o}}function cE(e){let t=[],n=e;for(;v.isMemberExpression(n)||v.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(v.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(v.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(v.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(v.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return v.isIdentifier(n)?{base:n.name,segments:t}:null}function lE(e){return e.some(t=>t.kind==="dynamic")}function uE(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}async function dE(e){let t=oE(e.binding,e.sourceInfo);if(!t||!e.graph)return null;let n=[...e.graph.elements.values()].filter(l=>iE(l,e.currentFile,t.componentName,t.exportName));if(n.length!==1)return null;let r=n[0],o=r.attributes?.find(l=>l.name===t.propName);if(o&&!o.source){let l=await fE({caller:r,propName:t.propName,remainingPath:t.remainingPath,readFile:e.readFile,fileCache:e.fileCache});if(l)return ha(l,{componentName:t.componentName,propName:t.propName,file:r.sourceFile})}if(!o?.source){let l=await pE({caller:r,propName:t.propName,remainingPath:t.remainingPath,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(l)return ha(l,{componentName:t.componentName,propName:t.propName,file:r.sourceFile});let u=nd(e.binding,t.componentName,t.propName);if(!u||u.propName!==t.propName)return null;let d=await pt(u.expressionPath.node,u.expressionPath.scope,e.currentFile,e.readFile,e.exists,e.fileCache,e.visited);if(d===void 0)return null;let p=t.remainingPath;return p.length>0&&dt(d,p)===void 0?null:{kind:"value",file:e.currentFile,root:{kind:"binding",name:t.propName},path:p,sourceKind:"binding",semanticKind:"component-prop",displayExpression:u.displayPath,chainPrefix:[{kind:"component-prop",file:e.currentFile,displayName:u.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let i=await Zt(r.sourceFile,e.readFile,e.fileCache);if(!i.ast)return null;let s=af(i.ast,i.source,o.source.expression,o.sourceRange)??Pa(i.ast,i.source,o.source.expression);if(!s)return null;let a={...o.source,expression:ti(o.source.expression,t.remainingPath),path:[...o.source.path,...t.remainingPath]},c=await Xe({currentFile:r.sourceFile,expressionPath:s,sourceInfo:a,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return c?ha(c.kind==="external"?c:{...c,displayExpression:a.expression},{componentName:t.componentName,propName:t.propName,file:r.sourceFile}):null}async function fE(e){let t=await Zt(e.caller.sourceFile,e.readFile,e.fileCache);if(!t.ast)return null;let n=of(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=sf(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 pE(e){let t=await Zt(e.caller.sourceFile,e.readFile,e.fileCache);if(!t.ast)return null;let n=of(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 ft({expression:i.node,scope:i.scope,source:t.source,currentFile:e.caller.sourceFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(!s)continue;let a=[{kind:"property",name:e.propName},...e.remainingPath],c={...s,expression:ti(s.expression,a),path:[...s.path,...a]},l=await Xe({currentFile:e.caller.sourceFile,expressionPath:i,sourceInfo:c,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(l)return l.kind==="external"?l:{...l,displayExpression:c.expression}}return null}function ha(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 mE(e){let{currentFile:t,binding:n,readFile:r,exists:o,fileCache:i,visited:s}=e,a=n.path.parentPath;if(!a||!a.isImportDeclaration())return null;let c=a.node.source.value;if(typeof c!="string")return null;let l=await Nn(t,c,o);if(!l)return null;if(n.path.isImportDefaultSpecifier()){let b=await Zt(l,r,i),C=b.ast?Ia(b.ast,"default"):null,I=await ei({file:l,exportName:"default",readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});return!I||I.kind!=="static"?null:{kind:"static",file:C?.kind==="default-expression"?I.file:l,root:C?.kind==="default-expression"?I.root:{kind:"default-export"},value:I.value,sourceKind:"imported-binding"}}if(!n.path.isImportSpecifier())return null;let u=n.path.node.imported,d=v.isIdentifier(u)?u.name:u.value,p=await Zt(l,r,i),m=p.ast?Ia(p.ast,d):null,g=await ei({file:l,exportName:d,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});return g?g.kind==="external"?g:{kind:"static",file:m?.kind==="re-export"?g.file:l,root:m?.kind==="re-export"?g.root:{kind:"named-export",name:d},value:g.value,sourceKind:"imported-binding"}:null}async function ei(e){let{file:t,exportName:n,readFile:r,exists:o,fileCache:i,visited:s}=e,a=`export::${t}::${n}`;if(!s.has(a)){s.add(a);try{let c=await Zt(t,r,i);if(!c.ast)return;let l=Ia(c.ast,n);if(!l)return;if(l.kind==="default-expression"){let m=l.expression;if(!m||!v.isIdentifier(m))return;let g=va(c.ast).getBinding(m.name);return g?await gn({currentFile:t,binding:g,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s})??void 0:void 0}if(l.kind==="re-export"){if(!l.source||!l.name)return;let m=await Nn(t,l.source,o);return m?ei({...e,file:m,exportName:l.name}):void 0}let u=l.name;if(!u)return;let d=va(c.ast).getBinding(u);return d?await gn({currentFile:t,binding:d,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s})??void 0:void 0}finally{s.delete(a)}}}function va(e){let t=null;if(ef(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}function Ia(e,t){for(let n of e.program.body){if(t==="default"&&v.isExportDefaultDeclaration(n))return v.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:(v.isFunctionDeclaration(n.declaration)||v.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if(v.isExportNamedDeclaration(n)){if(n.declaration){if(v.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if(v.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if((v.isFunctionDeclaration(n.declaration)||v.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if((v.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&v.isExportSpecifier(r))return n.source?{kind:"re-export",name:r.local.name,source:n.source.value}:{kind:"local-binding",name:r.local.name}}}return null}async function pt(e,t,n,r,o,i,s){if(v.isStringLiteral(e)||v.isNumericLiteral(e)||v.isBooleanLiteral(e))return e.value;if(v.isNullLiteral(e))return null;if(v.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(v.isTSAsExpression(e)||v.isTSSatisfiesExpression(e)||v.isTSNonNullExpression(e))return await pt(e.expression,t,n,r,o,i,s);if(v.isIdentifier(e)){let a=t.getBinding(e.name);if(!a)return;let c=await gn({currentFile:n,binding:a,readFile:r,exists:o,fileCache:i,visited:s});return c?.kind==="static"?c.value:void 0}if(v.isArrayExpression(e)){let a=[];for(let c of e.elements){if(!c||v.isSpreadElement(c))return;let l=await ya(c,t,n,r,o,i,s);if(l===void 0)return;a.push(l)}return a}if(v.isObjectExpression(e)){let a={};for(let c of e.properties){if(!v.isObjectProperty(c)||c.computed)return;let l=null;if(v.isIdentifier(c.key)?l=c.key.name:v.isStringLiteral(c.key)&&(l=c.key.value),!l)return;if(c.shorthand){if(!v.isIdentifier(c.value))return;let d=await ya(c.value,t,n,r,o,i,s);if(d===void 0)return;a[l]=d;continue}if(!v.isExpression(c.value))return;let u=await ya(c.value,t,n,r,o,i,s);u!==void 0&&(a[l]=u)}return a}if(v.isMemberExpression(e)){let a=await xf(e,t,n,r,o,i,s);if(!a)return;let c=t.getBinding(a.base);if(!c)return;let l=await gn({currentFile:n,binding:c,readFile:r,exists:o,fileCache:i,visited:s});return!l||l.kind!=="static"?void 0:dt(l.value,a.path)}}async function ya(e,t,n,r,o,i,s){if(!v.isSpreadElement(e))return await pt(e,t,n,r,o,i,s)}async function xf(e,t,n,r,o,i,s){if(v.isIdentifier(e))return{base:e.name,path:[]};if(!v.isMemberExpression(e))return null;let a=[],c=e;for(;v.isMemberExpression(c);){if(c.computed){let l=c.property;if(v.isNumericLiteral(l))a.unshift({kind:"index",index:l.value});else if(v.isStringLiteral(l))a.unshift({kind:"property",name:l.value});else{let u=v.isExpression(l)?await pt(l,t,n,r,o,i,s):void 0;if(typeof u=="string")a.unshift({kind:"property",name:u});else if(Number.isInteger(u))a.unshift({kind:"index",index:u});else return null}}else{if(!v.isIdentifier(c.property))return null;a.unshift({kind:"property",name:c.property.name})}c=c.object}return v.isIdentifier(c)?{base:c.name,path:a}:null}function gE(e){if(v.isIdentifier(e))return{base:e.name,path:[]};if(!v.isMemberExpression(e))return null;let t=[],n=e;for(;v.isMemberExpression(n);){if(n.computed)if(v.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(v.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!v.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return v.isIdentifier(n)?{base:n.name,path:t}:null}function dt(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 hE(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 yE(e,t){let n=[],r=[];for(let o of t){let i=dt(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 Zt(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=rf(o),s={source:o,ast:i};return n.set(e,s),s}import Ba from"@babel/generator";import{parse as _E}from"@babel/parser";import ja from"@babel/traverse";import*as k from"@babel/types";import*as It from"@babel/types";import Oa from"@babel/generator";import*as ue from"@babel/types";var xE=typeof Oa=="function"?Oa:Oa.default,bE=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,SE=/^((?:https?:)?\/\/)[^/@\s]+@/i,EE=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function Sf(e,t){let n=vt(e.callee);if(!n)return null;if(n==="fetch")return Ma(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(bf(r))return Ma(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(bf(r))return Ma(e.arguments[0],r,t,["ky client contract"])}return null}function Ma(e,t,n,r){if(!e||ue.isSpreadElement(e)||ue.isJSXNamespacedName(e))return CE(t,n,r,"missing url argument");let o=Pr(e);return{sourceKind:kE(o),...o?{endpointPattern:o}:{},method:t,confidence:o?"exact":"partial",evidence:[{file:n.file,reason:[...r,o?"endpoint pattern resolved":"endpoint pattern unresolved"].join("; ")}]}}function Pr(e){if(ue.isStringLiteral(e))return ni(e.value);if(ue.isTemplateLiteral(e))return ni(vE(e));if(ue.isBinaryExpression(e)&&e.operator==="+"){let t=Pr(e.left),n=Pr(e.right);return!t&&!n?void 0:ni(`${t??Da(e.left)}${n??Da(e.right)}`)}if(ue.isMemberExpression(e)){let t=Ef(e);if(t)return`env:${t}`}if(!(ue.isCallExpression(e)&&vt(e.callee)==="new URL")){if(ue.isNewExpression(e)&&ue.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!ue.isSpreadElement(t)?Pr(t):void 0,o=n&&!ue.isSpreadElement(n)?Pr(n):void 0;return o&&r?ni(`${o} + ${r}`):r??o}if(ue.isIdentifier(e))return`:${e.name}`}}function vE(e){let t="";for(let n=0;n<e.quasis.length;n+=1){t+=e.quasis[n]?.value.cooked??e.quasis[n]?.value.raw??"";let r=e.expressions[n];r&&(t+=Da(r))}return t}function Da(e){if(ue.isIdentifier(e))return`:${e.name}`;if(ue.isMemberExpression(e)){let t=Ef(e);if(t)return`env:${t}`}return`:${IE(e)}`}function IE(e){return xE(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function ni(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(SE,"$1<redacted>@").replace(EE,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?bE.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function kE(e){return e?e.startsWith("/api/")?"site-api-route":/^(?:https?:)?\/\//.test(e)||e.startsWith("env:")?"external-api":e.startsWith("/")?"site-api-route":"unknown-api":"unknown-api"}function CE(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function bf(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function Ef(e){return!ue.isMemberExpression(e.object)||!ue.isIdentifier(e.object.object,{name:"process"})||!RE(e.object.property,"env")?null:ue.isIdentifier(e.property)?e.property.name:ue.isStringLiteral(e.property)?e.property.value:null}function RE(e,t){return ue.isIdentifier(e)&&e.name===t}function vt(e){if(ue.isIdentifier(e))return e.name;if(ue.isMemberExpression(e)){let t=vt(e.object),n=ue.isIdentifier(e.property)?e.property.name:ue.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var wE=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),NE=new Set(["getConfig","submit"]);function vf(e,t){let n=PE(vt(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!wE.has(i))return null;let s=La(e,0),a=i==="getByUrl"||i==="getByUrlStrict",c=a?void 0:s,l=a?s??"/:record-url":c?`/collections/${c}`:"/collections/:collection";return{sourceKind:"vcp-cms-collection",sourceType:"cms-field",operation:i,...c?{collection:c}:{},endpointPattern:l,confidence:s?"exact":"partial",evidence:[{file:t.file,symbol:n,reason:"VCP CMS collection facade"}]}}let o="cms.forms.";if(n.startsWith(o)){let i=n.slice(o.length);if(!NE.has(i))return null;let s=La(e,0);return{sourceKind:"vcp-cms-form",sourceType:"cms-field",operation:i,...s?{collection:s}:{},endpointPattern:s?`/forms/${s}`:"/forms/:form",confidence:s?"exact":"partial",evidence:[{file:t.file,symbol:n,reason:"VCP CMS form facade"}]}}if(n==="cmsFetch"||n==="cmsFetchResult"||n==="cmsFetchEnvelope"){let i=La(e,0)??AE(e,0,"path")??"/cms/:path",s=TE(i);return{sourceKind:"vcp-cms-collection",sourceType:"cms-field",operation:n,...s?{collection:s}:{},endpointPattern:i,confidence:i==="/cms/:path"?"partial":"safe-derived",evidence:[{file:t.file,symbol:n,reason:"VCP CMS fetch helper"}]}}return null}function PE(e,t){let n=e?.indexOf(".")??-1;if(!e||n<1)return e;let r=t.imports?.get(e.slice(0,n));return r?.importedName==="collections"&&/(?:^|\/)lib\/cms\/collections(?:\.js)?$/.test(r.source)?`cms.collections${e.slice(n)}`:e}function If(e,t){let n=vt(e);return n==="cms.settings"?{sourceKind:"vcp-cms-settings",sourceType:"cms-field",operation:"settings",endpointPattern:"/settings",confidence:"exact",evidence:[{file:t.file,symbol:n,reason:"VCP CMS settings facade"}]}:n==="cms.navigation"?{sourceKind:"vcp-cms-navigation",sourceType:"cms-field",operation:"navigation",endpointPattern:"/navigation",confidence:"exact",evidence:[{file:t.file,symbol:n,reason:"VCP CMS navigation facade"}]}:null}function kf(e){let t=vt(e.callee);return typeof t=="string"&&t.startsWith("cms.field.")}function La(e,t){let n=e.arguments[t];return It.isStringLiteral(n)?n.value:null}function AE(e,t,n){let r=e.arguments[t];if(!It.isObjectExpression(r))return null;for(let o of r.properties)if(It.isObjectProperty(o)&&!o.computed&&(It.isIdentifier(o.key)&&o.key.name===n||It.isStringLiteral(o.key)&&o.key.value===n)&&It.isStringLiteral(o.value))return o.value.value;return null}function TE(e){return/^\/collections\/([^/]+)(?:\/|$)/.exec(e)?.[1]??null}var Va=typeof ja=="function"?ja:ja.default,rT=typeof Ba=="function"?Ba:Ba.default,FE={maxFunctionDepth:8,maxImportDepth:6},OE=new Set(["src","href","alt","poster","content","title","aria-label"]);async function Af(e){let t=e.fileCache??new Map,n=Ja(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...FE,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:Jf(n,e.element.componentName)};await Tf(e.element.componentName,e.graph,r);let o=[];o.push(...await jE(e.element,e.graph,r),...await $E(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await VE(s,e.element,e.graph,r);a&&o.push(ii(a,"text","children"))}for(let s of e.element.attributes??[]){let a=BE(s,e.element);if(!a)continue;let c=await Of(s.source,e.element,e.graph,r);c&&o.push(ii(c,a,s.name))}let i=nv(o).sort(Uf);return{hasDynamicData:i.length>0,bindings:i}}async function Tf(e,t,n){if(n.importDepth>=n.options.maxImportDepth)return;let r=n.analysis.functions.get(e)??n.analysis.functions.get("default"),o=r?.params[0];if(!r||!o)return;let i=n.analysis.functions.get("default")===r?"default":e,s=[];for(let l of t.elements.values()){if(l.sourceFile===n.file&&l.tag===e){s.push(l);continue}!l.importedFrom||!l.exportName||l.importedFrom===n.file&&l.exportName!==i||(l.importedFrom===n.file||await _f(l.importedFrom,l.exportName,n.file,n))&&s.push(l)}if(s.length===0)return;let a=new Map;for(let l of s){let u=`${n.file}#${e}<-${l.identity.key}`;if(!n.resolvingComponentProps.has(u)){n.resolvingComponentProps.add(u);try{let d=await Ff(l.sourceFile,n);if(!d)continue;let p=ai(d,n,{importDepth:n.importDepth+1});p.paramSources.clear(),p.scopeVariables=Jf(d,l.componentName),await Tf(l.componentName,t,p);let m=await ME(l,p);for(let[g,b]of m){if(!b)continue;let C=a.get(g)??[];C.push(b),a.set(g,C)}}finally{n.resolvingComponentProps.delete(u)}}}let c=new Map;for(let[l,u]of a){let d=$f(u);d.length===1&&c.set(l,d[0])}LE(o,c,n)}async function _f(e,t,n,r,o=new Set){if(e===n)return!0;if(o.size>=r.options.maxImportDepth||o.has(`${e}#${t}`))return!1;o.add(`${e}#${t}`);let s=(await Ff(e,r))?.imports.get(t);if(!s||!xt(s.source))return!1;let a=await Wf(e,s.source,r.exists);return a?a===n?!0:_f(a,s.importedName,n,r,o):!1}async function ME(e,t){let n=new Map;Va(t.analysis.ast,{JSXElement(o){if(DE(o.node,e.sourceRange)){for(let i of o.node.openingElement.attributes)!k.isJSXAttribute(i)||!k.isJSXIdentifier(i.name)||!k.isJSXExpressionContainer(i.value)||!k.isExpression(i.value.expression)||n.set(i.name.name,i.value.expression);o.stop()}}});let r=new Map;for(let[o,i]of n){let s=await we(i,t);s&&r.set(o,s)}return r}function DE(e,t){return e.loc?.start.line===t.startLine&&e.loc.start.column===t.startColumn&&e.loc.end.line===t.endLine&&e.loc.end.column===t.endColumn}async function Ff(e,t){let n=t.fileCache.get(e);if(n)return n;if(!await t.exists(e))return null;let r=await t.readFile(e);return Ja(e,r,t.fileCache)}function LE(e,t,n){if(k.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,Ka(Object.fromEntries(t),n.file));return}if(k.isObjectPattern(e))for(let r of e.properties){if(!k.isObjectProperty(r)||r.computed||!k.isIdentifier(r.key))continue;let o=t.get(r.key.name);if(!o)continue;let i=k.isAssignmentPattern(r.value)?r.value.left:r.value;k.isIdentifier(i)&&n.paramSources.set(i.name,_e(o))}}function BE(e,t){return e.name==="dangerouslySetInnerHTML"?"richtext":OE.has(e.name)?"attribute":t.importedFrom||/^[A-Z]/.test(t.tag)?"component-prop":null}async function jE(e,t,n){let r=[];for(let o of t.regions){if(o.kind!=="repeat-region"||o.ownerKey!==e.identity.key)continue;let i=o.sourceCandidates?.find(a=>a.kind==="repeat-template");if(!i)continue;let s=await si(i.collectionSource,n);s&&r.push(ii(hn(s),"repeat-region",i.collectionExpression))}return r}async function $E(e,t,n){let r=[];for(let o of t.regions){if(o.kind!=="conditional-region"||o.ownerKey!==e.identity.key)continue;let i=o.sourceCandidates?.find(a=>a.kind==="conditional-branch");if(!i)continue;let s=await si(i.conditionSource,n);s&&r.push(ii(hn(s),"conditional-region",i.conditionExpression))}return r}async function VE(e,t,n,r){return Of(e.source,t,n,r)}async function Of(e,t,n,r){let o=await UE(e,t,n,r);return o||si(e,r)}async function UE(e,t,n,r){if(!e)return null;let o=KE(e.base,t,n);if(!o)return null;let i=await si(o.collectionSource,r);return i?Fr(i,e.path,!0):null}function KE(e,t,n){let r=t.identity.key;for(;r;){for(let o of n.regions){if(o.kind!=="repeat-region"||!o.childKeys.includes(r))continue;let i=o.sourceCandidates?.find(s=>s.kind==="repeat-template"&&s.itemParamName===e);if(i)return i}r=n.elements.get(r)?.parentKey??null}return null}async function si(e,t){if(!e)return null;let n=await Mf(e.base,t);return n?Fr(n,e.path,!1):null}async function Mf(e,t){let n=t.paramSources.get(e);if(n)return _e(n);if(t.variableCache.has(e))return rv(t.variableCache.get(e)??null);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let r=await JE(e,t);if(r)return t.variableCache.set(e,_e(r)),t.resolvingVariables.delete(e),r;let o=t.scopeVariables?.get(e)??t.analysis.variables.get(e);if(o){let s=await we(o,t);return t.variableCache.set(e,s?_e(s):null),t.resolvingVariables.delete(e),s}let i=t.analysis.imports.get(e);if(i&&t.importDepth<t.options.maxImportDepth){let s=await Xf(i,t);if(s){let a=ai(s,t,{importDepth:t.importDepth+1}),c=zf(i,s);if(c){let d=(await yn(c,[],a)).returnSource;return t.variableCache.set(e,d?_e(d):null),t.resolvingVariables.delete(e),d}let l=s.variables.get(i.importedName);if(l){let u=await we(l,a);return t.variableCache.set(e,u?_e(u):null),t.resolvingVariables.delete(e),u}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}async function JE(e,t){let n=t.analysis.stateSetters.get(e);if(!n)return null;let r=[];Va(t.analysis.ast,{CallExpression(o){if(k.isIdentifier(o.node.callee,{name:n})){let i=o.node.arguments[0];k.isExpression(i)&&r.push(i);return}o.node.arguments.some(i=>k.isIdentifier(i)&&i.name===n)&&r.push(o.node)}});for(let o of r){let i=await we(o,t);if(i)return i}return null}async function we(e,t){if(k.isIdentifier(e))return Mf(e.name,t);if(k.isMemberExpression(e)||k.isOptionalMemberExpression(e)){let n=k.isMemberExpression(e)?If(e,{file:t.file}):null;if(n)return jf(n);let r=await XE(e,t);if(!r)return null;let o=ev(e);return Fr(r,o,!1)}if(k.isAwaitExpression(e))return k.isExpression(e.argument)?we(e.argument,t):null;if(k.isCallExpression(e))return Df(e,t);if(k.isObjectExpression(e)){let n=await Lf(e,t);return Object.keys(n).length>0?Ka(n,t.file):null}if(k.isConditionalExpression(e)){let n=await we(e.consequent,t),r=await we(e.alternate,t);return _r(Rf(n,r))}if(k.isLogicalExpression(e)){let n=await we(e.left,t),r=await we(e.right,t);return _r(Rf(n,r))}return k.isTSAsExpression(e)||k.isTSSatisfiesExpression(e)||k.isTSNonNullExpression(e)||k.isTypeCastExpression(e)||k.isParenthesizedExpression(e)?we(e.expression,t):null}async function XE(e,t){let n=e;for(;k.isMemberExpression(n)||k.isOptionalMemberExpression(n);)n=n.object;return k.isExpression(n)?we(n,t):null}async function Df(e,t){let n=vf(e,{file:t.file,imports:t.analysis.imports});if(n)return jf(n);if(kf(e)){let d=e.arguments[0];if(d&&k.isExpression(d))return _r(await we(d,t))}let r=await zE(e,t);if(r)return r;let o=Sf(e,{file:t.file});if(o)return{sourceKind:o.sourceKind,sourceType:"api-field",endpointPattern:o.endpointPattern,valuePath:o.valuePath,confidence:o.confidence,readonly:!0,evidence:o.evidence};let i=await GE(e,t);if(i)return i;let s=await YE(e,t);if(s)return s;let a=await ZE(e,t);if(a)return a;let c=await QE(e,t);if(c)return c;let l=[];for(let d of e.arguments)if(k.isExpression(d)){let p=await we(d,t);p&&l.push(p)}let u=$f(l);return u.length===1?_r(u[0]):null}async function zE(e,t){let n=vt(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=HE(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(k.isIdentifier(s)){let a=await Tr(s.name,t);if(a)return(await yn(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!k.isObjectExpression(r))return ri(t.file,`${n} without static options`);let o=WE(r,"queryFn");if(!o)return ri(t.file,`${n} without queryFn`);if(k.isIdentifier(o)){let i=await Tr(o.name,t);return i?(await yn(i.node,[],i.context)).returnSource:ri(t.file,`${n} queryFn unresolved`)}return k.isArrowFunctionExpression(o)||k.isFunctionExpression(o)?(await yn(o,[],t)).returnSource:k.isCallExpression(o)?Df(o,t):null}function WE(e,t){for(let n of e.properties){if(!k.isObjectProperty(n)||!k.isExpression(n.value))continue;if(Bf(n)===t)return n.value}return null}function HE(e,t,n){return k.isStringLiteral(e)?{sourceKind:e.value.startsWith("/api/")?"site-api-route":"external-api",sourceType:"api-field",endpointPattern:e.value,confidence:"exact",readonly:!0,evidence:[{file:t,reason:n}]}:null}async function GE(e,t){if(!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property))return null;let n=e.callee.property.name;if(!["map","filter","slice","sort","toSorted"].includes(n))return null;let r=k.isExpression(e.callee.object)?await we(e.callee.object,t):null;if(!r)return null;if(n!=="map")return hn(r);let o=e.arguments[0];if(k.isIdentifier(o)){let i=await Tr(o.name,t);if(!i)return hn(r);let s=await yn(i.node,[r],i.context);return{...hn(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(k.isArrowFunctionExpression(o)||k.isFunctionExpression(o)){let i=await yn(o,[r],t);return{...hn(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return hn(r)}async function YE(e,t){return!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property,{name:"json"})||!k.isExpression(e.callee.object)?null:we(e.callee.object,t)}async function ZE(e,t){return!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property,{name:"then"})||!k.isExpression(e.callee.object)?null:_r(await we(e.callee.object,t))}async function QE(e,t){if(!k.isIdentifier(e.callee))return null;let n=await Tr(e.callee.name,t);if(!n)return null;let r=[];for(let i of e.arguments){if(!k.isExpression(i)){r.push(ri(t.file,`unsupported argument for ${e.callee.name}`));continue}let s=await we(i,t);r.push(s)}return(await yn(n.node,r,n.context)).returnSource}async function Tr(e,t){let n=t.analysis.functions.get(e);if(n)return{node:n,context:t};let r=t.analysis.imports.get(e);if(!r||t.importDepth>=t.options.maxImportDepth)return null;let o=await Xf(r,t);if(!o)return null;let i=ai(o,t,{importDepth:t.importDepth+1}),s=zf(r,o);return s?{node:s,context:i}:Tr(r.importedName,i)}async function yn(e,t,n){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let r=ai(n.analysis,n,{functionDepth:n.functionDepth+1});r.scopeVariables=n.analysis.functionVariables.get(e),e.params.forEach((c,l)=>{let u=t[l];u&&$a(c,tv(u),r)});let o=qE(e),i=null,s,a=!1;for(let c of o){if(k.isObjectExpression(c)){s={...s??{},...await Lf(c,r)},i=i??Ka(s,n.file);continue}let l=await we(c,r);if(l){if(!i){i=l;continue}let u=Ua(i,l);if(!u){a=!0,i=null;continue}i=u}}return{returnSource:a?null:i,...s?{objectReturnMap:s}:{}}}function $a(e,t,n){if(k.isIdentifier(e)){n.paramSources.set(e.name,_e(t));return}if(k.isAssignmentPattern(e)){$a(e.left,t,n);return}if(k.isObjectPattern(e))for(let r of e.properties){if(!k.isObjectProperty(r)||r.computed||!k.isIdentifier(r.key))continue;let o=Fr(t,[{kind:"property",name:r.key.name}],!0),i=k.isAssignmentPattern(r.value)?r.value.left:r.value;$a(i,o,n)}}function qE(e){if(k.isArrowFunctionExpression(e)&&k.isExpression(e.body))return[e.body];let t=[],n=e.body;if(!k.isBlockStatement(n))return t;let r=o=>{if(k.isFunction(o)&&o!==e)return;if(k.isReturnStatement(o)){o.argument&&k.isExpression(o.argument)&&t.push(o.argument);return}let i=k.VISITOR_KEYS[o.type];for(let s of i??[]){let a=o[s];if(Array.isArray(a))for(let c of a)k.isNode(c)&&r(c);else k.isNode(a)&&r(a)}};return r(n),t}async function Lf(e,t){let n={};for(let r of e.properties){if(!k.isObjectProperty(r))continue;let o=Bf(r);if(!o||!k.isExpression(r.value))continue;let i=await we(r.value,t);i&&(n[o]=i)}return n}function Bf(e){return k.isIdentifier(e.key)&&!e.computed?e.key.name:k.isStringLiteral(e.key)?e.key.value:null}function ev(e){let t=[],n=e;for(;k.isMemberExpression(n)||k.isOptionalMemberExpression(n);){let r=n.property;n.computed?k.isStringLiteral(r)?t.unshift({kind:"property",name:r.value}):k.isNumericLiteral(r)&&t.unshift({kind:"index",index:r.value}):k.isIdentifier(r)&&t.unshift({kind:"property",name:r.name}),n=n.object}return k.isIdentifier(n),t}function Fr(e,t,n){if(t.length===0)return _e(e);let r=t[0];if(r?.kind==="property"&&e.fieldMap?.[r.name])return Fr(e.fieldMap[r.name],t.slice(1),n);let o=_e(e);if(o.sourceType==="cms-field"){let i=t.filter(s=>s.kind==="property").map(s=>s.name);return i[0]==="data"&&i[1]==="items"?(o.valuePath=Ar(o.valuePath,"data.items[]"),o.cmsFieldRoot=!1,o):i[0]==="fields"?(o.fieldPath=Ar(o.fieldPath,i.slice(1).join(".")),o.cmsFieldRoot=!0,o):o.cmsFieldRoot||n||o.fieldMap?(o.fieldPath=Ar(o.fieldPath,i.join(".")),o):(o.valuePath=Ar(o.valuePath,Cf(t)),o)}return o.valuePath=Ar(o.valuePath,Cf(t)),o}function Cf(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function Ar(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function jf(e){return{sourceKind:e.sourceKind,sourceType:e.sourceType,operation:e.operation,collection:e.collection,endpointPattern:e.endpointPattern,valuePath:e.valuePath,confidence:e.confidence,readonly:!0,evidence:e.evidence}}function hn(e){let t=_e(e);return t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function tv(e){let t=_e(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&(t.cmsFieldRoot=!1),t}function _r(e){return e?{..._e(e),confidence:e.confidence==="unknown"?"unknown":"safe-derived",evidence:[...e.evidence,{file:e.evidence[0]?.file??"unknown",reason:"safe derived expression"}]}:null}function Rf(e,t){return e?t?Ua(e,t):_e(e):t?_e(t):null}function Ua(e,t){if(oi(e)!==oi(t))return null;let n=Kf(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function $f(e){let t=new Map;for(let n of e){let r=oi(n),o=t.get(r);t.set(r,o?Ua(o,n):_e(n))}return[...t.values()]}function oi(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,oi(r)])):void 0;return JSON.stringify({sourceKind:e.sourceKind,sourceType:e.sourceType,endpointPattern:e.endpointPattern,operation:e.operation,collection:e.collection,fieldPath:e.fieldPath,valuePath:e.valuePath,cmsFieldRoot:e.cmsFieldRoot,fieldMap:t})}function Ka(e,t){let n=Object.values(e)[0];return{sourceKind:n?.sourceKind??"unknown-api",sourceType:n?.sourceType??"api-field",endpointPattern:n?.endpointPattern,operation:n?.operation,collection:n?.collection,confidence:n?.confidence??"partial",readonly:!0,evidence:n?.evidence??[{file:t,reason:"object return map"}],fieldMap:e}}function ri(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function ii(e,t,n){return{sourceKind:e.sourceKind,sourceType:e.sourceType,...e.endpointPattern?{endpointPattern:e.endpointPattern}:{},...e.operation?{operation:e.operation}:{},...e.collection?{collection:e.collection}:{},...e.fieldPath?{fieldPath:e.fieldPath}:{},...e.valuePath?{valuePath:e.valuePath}:{},targetKind:t,targetName:n,confidence:e.confidence,readonly:!0,evidence:e.evidence.map(r=>({...r}))}}function Vf(e){let t=[...e].sort(Uf),n=t[0];return{hasDynamicData:t.length>0,sourceKinds:[...new Set(t.map(r=>r.sourceKind))],...n?.endpointPattern?{primaryEndpoint:n.endpointPattern}:{},...n?.collection?{primaryCollection:n.collection}:{},...n?.fieldPath?{primaryFieldPath:n.fieldPath}:{}}}function nv(e){let t=new Set,n=[];for(let r of e){let o=JSON.stringify({sourceKind:r.sourceKind,endpointPattern:r.endpointPattern,collection:r.collection,fieldPath:r.fieldPath,valuePath:r.valuePath,targetKind:r.targetKind,targetName:r.targetName});t.has(o)||(t.add(o),n.push(r))}return n}function Uf(e,t){return wf(e.targetKind)-wf(t.targetKind)||Kf(e.confidence,t.confidence)||Nf(e.sourceKind)-Nf(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function wf(e){return{"repeat-region":0,"conditional-region":1,text:2,richtext:3,attribute:4,"component-prop":5}[e]}function Nf(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function Kf(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function Ja(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=_E(t,{sourceType:"module",plugins:["jsx","typescript"]}),i={file:e,source:t,ast:o,variables:new Map,functions:new Map,imports:new Map,stateSetters:new Map,functionVariables:new WeakMap};return Va(o,{ImportDeclaration(s){let a=s.node.source.value;for(let c of s.node.specifiers)k.isImportSpecifier(c)&&k.isIdentifier(c.local)?i.imports.set(c.local.name,{source:a,importedName:k.isIdentifier(c.imported)?c.imported.name:c.imported.value,localName:c.local.name,isDefault:!1}):k.isImportDefaultSpecifier(c)&&i.imports.set(c.local.name,{source:a,importedName:"default",localName:c.local.name,isDefault:!0})},FunctionDeclaration(s){s.node.id?.name&&i.functions.set(s.node.id.name,s.node)},VariableDeclarator(s){let a=s.getFunctionParent(),c=a&&(k.isFunctionDeclaration(a.node)||k.isFunctionExpression(a.node)||k.isArrowFunctionExpression(a.node))?a.node:null,l=c?i.functionVariables.get(c)??new Map:i.variables;c&&!i.functionVariables.has(c)&&i.functionVariables.set(c,l);for(let u of Hn(s.node.id))l.set(u,k.isExpression(s.node.init)?s.node.init:null);if(k.isArrayPattern(s.node.id)&&k.isCallExpression(s.node.init)&&vt(s.node.init.callee)==="useState"){let[u,d]=s.node.id.elements;k.isIdentifier(u)&&k.isIdentifier(d)&&i.stateSetters.set(u.name,d.name)}k.isIdentifier(s.node.id)&&Pf(s.node.init)&&i.functions.set(s.node.id.name,s.node.init)},ExportNamedDeclaration(s){let a=s.node.declaration,c=s.node.source?.value;if(c)for(let l of s.node.specifiers){if(!k.isExportSpecifier(l))continue;let u=k.isIdentifier(l.exported)?l.exported.name:l.exported.value,d=l.local.name;i.imports.set(u,{source:c,importedName:d,localName:u,isDefault:d==="default"})}if(k.isFunctionDeclaration(a)&&a.id?.name&&i.functions.set(a.id.name,a),k.isVariableDeclaration(a))for(let l of a.declarations)k.isIdentifier(l.id)&&Pf(l.init)&&i.functions.set(l.id.name,l.init)},ExportDefaultDeclaration(s){let a=s.node.declaration;if((k.isFunctionDeclaration(a)||k.isFunctionExpression(a)||k.isArrowFunctionExpression(a))&&i.functions.set("default",a),k.isIdentifier(a)){let c=i.functions.get(a.name);c&&i.functions.set("default",c)}}}),n.set(e,i),i}function Hn(e){return!e||k.isVoidPattern(e)?[]:k.isIdentifier(e)?[e.name]:k.isObjectPattern(e)?e.properties.flatMap(t=>k.isObjectProperty(t)?Hn(t.value):Hn(t.argument)):k.isArrayPattern(e)?e.elements.flatMap(t=>t?Hn(k.isRestElement(t)?t.argument:t):[]):k.isAssignmentPattern(e)?Hn(e.left):k.isRestElement(e)?Hn(e.argument):[]}function Pf(e){return k.isFunctionExpression(e)||k.isArrowFunctionExpression(e)}function Jf(e,t){let n=e.functions.get(t)??e.functions.get("default");return n?e.functionVariables.get(n):void 0}async function Xf(e,t){let n=await Wf(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return Ja(n,r,t.fileCache)}function zf(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function Wf(e,t,n){return xt(t)?Nn(e,t,n):null}function ai(e,t,n={}){return{file:e.file,analysis:e,readFile:t.readFile,exists:t.exists,fileCache:t.fileCache,options:t.options,variableCache:new Map,functionDepth:n.functionDepth??t.functionDepth,importDepth:n.importDepth??t.importDepth,paramSources:new Map(t.paramSources),resolvingVariables:new Set,resolvingComponentProps:t.resolvingComponentProps,scopeVariables:e===t.analysis?t.scopeVariables:void 0}}function rv(e){return e?_e(e):null}function _e(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,_e(n)]))}:{}}}var ov=50,iv=8*1024*1024;function Zf(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??ov),s=Math.max(0,t.maxUndoBytes??iv);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:u,redo:d};async function a(N){let W=[...N.steps].sort((G,ee)=>G.order-ee.order),M=W.filter(G=>G.type!=="invoke-external-adapter");if(M.length!==W.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let j=new Set(M.map(G=>G.file)),Q=await w(j),re=new Map(Q.map(G=>[G.file,G.exists===!1?"":G.content])),be;for(let G of M){let ee=Yf(G,re.get(G.file)??"");if(!ee.ok)return{ok:!1,errorCode:ee.errorCode,reason:ee.reason};re.set(G.file,ee.source),be=ee.selectionRef??be}return{ok:!0,filePlan:{operationId:N.operationId,kind:"source-edit",target:N.target,documentVersion:N.documentVersion,conflictPolicy:"compare-and-swap",edits:[...re].map(([G,ee])=>({operation:"upsert",file:G,content:ee,baseContentHash:Q.find(Ie=>Ie.file===G)?.sha256??null}))},...be?{selectionRef:be}:{}}}async function c(N){let W=[...N.steps].sort((Ie,Ft)=>Ie.order-Ft.order),M=W.filter(Ie=>Ie.type!=="invoke-external-adapter"),j=W.filter(Ie=>Ie.type==="invoke-external-adapter"),Q=new Set(M.map(Ie=>Ie.file));if(M.length>0&&j.length>0)return{ok:!1,operationId:N.operationId,errorCode:"unsupported-operation",reason:"Mixed local file rewrites and external adapter writes require an explicit compensation contract.",rolledBack:!1};if(M.length===0)return C(N,j);let re=await w(Q),be=new Map;for(let Ie of re)be.set(Ie.file,Ie.exists===!1?"":Ie.content);let G;for(let Ie of M){let Ft=be.get(Ie.file)??"",Ot=Yf(Ie,Ft);if(!Ot.ok)return{ok:!1,operationId:N.operationId,errorCode:Ot.errorCode,reason:Ot.reason,rolledBack:!1};be.set(Ie.file,Ot.source),Ot.selectionRef&&(G=Ot.selectionRef)}let ee=await O([...be].map(([Ie,Ft])=>({file:Ie,content:Ft,exists:!0,version:0,sha256:fe(Ft)})),re);return ee.ok===!1?{ok:!1,operationId:N.operationId,errorCode:ee.rolledBack?"writeback-failed":"rollback-failed",reason:ee.reason,rolledBack:ee.rolledBack}:(n.push({operationId:N.operationId,preSnapshots:re,postSnapshots:ee.snapshots,plan:N}),p(),r.length=0,{ok:!0,operationId:N.operationId,kind:N.kind,target:N.target,resultVersion:Math.max(...ee.snapshots.map(Ie=>Ie.version)),affectedFiles:[...Q],...G?{selectionRef:G}:{}})}async function l(N){let W=new Set(N.edits.map(ee=>ee.file)),M=await w(W),j=I(N,M);if(j)return{ok:!1,operationId:N.operationId,errorCode:"stale-version",reason:j.reason,affectedFiles:[j.file],rolledBack:!1};let Q=new Map(M.map(ee=>[ee.file,ee])),re=N.edits.find(ee=>ee.operation==="create-only"&&Q.get(ee.file)?.exists!==!1);if(re)return{ok:!1,operationId:N.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${re.file}`,affectedFiles:[re.file],rolledBack:!1};let be=N.edits.map(ee=>ee.operation==="delete"?{file:ee.file,content:"",exists:!1,version:0}:{file:ee.file,content:ee.content,exists:!0,version:0,sha256:fe(ee.content)}),G=await O(be,M,new Set(N.edits.filter(ee=>ee.operation==="create-only").map(ee=>ee.file)));return G.ok===!1?{ok:!1,operationId:N.operationId,errorCode:G.rolledBack?"writeback-failed":"rollback-failed",reason:G.reason,rolledBack:G.rolledBack}:(n.push({operationId:N.operationId,preSnapshots:M,postSnapshots:G.snapshots,plan:{operationId:N.operationId,kind:N.kind,target:N.target,documentVersion:N.documentVersion,steps:[],preSnapshots:M}}),p(),r.length=0,{ok:!0,operationId:N.operationId,kind:N.kind,target:N.target,resultVersion:Math.max(...G.snapshots.map(ee=>ee.version)),affectedFiles:[...W]})}async function u(){let N=n.at(-1);if(!N)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let W=await O(N.preSnapshots,N.postSnapshots);return W.ok===!1?{ok:!1,operationId:N.operationId,errorCode:W.rolledBack?"writeback-failed":"rollback-failed",reason:W.reason,rolledBack:W.rolledBack}:(n.pop(),r.push(N),{ok:!0,operationId:N.operationId,kind:N.plan.kind,target:N.plan.target,resultVersion:Math.max(...W.snapshots.map(M=>M.version)),affectedFiles:N.preSnapshots.map(M=>M.file)})}async function d(){let N=r.at(-1);if(!N)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let W=await O(N.postSnapshots,N.preSnapshots);return W.ok===!1?{ok:!1,operationId:N.operationId,errorCode:W.rolledBack?"writeback-failed":"rollback-failed",reason:W.reason,rolledBack:W.rolledBack}:(r.pop(),n.push(N),p(),{ok:!0,operationId:N.operationId,kind:N.plan.kind,target:N.plan.target,resultVersion:Math.max(...W.snapshots.map(M=>M.version)),affectedFiles:N.postSnapshots.map(M=>M.file)})}function p(){for(;n.length>i;)n.shift();for(;n.length>0&&m()>s;)n.shift()}function m(){return n.reduce((N,W)=>N+g(W),0)}function g(N){return b(N.preSnapshots)+b(N.postSnapshots)}function b(N){return N.reduce((W,M)=>W+M.file.length+M.content.length,0)}async function C(N,W){let M=[];for(let j of W){let Q=j.capability??"write-text",re=o.find(G=>G.sourceType===j.sourceType&&(j.adapterId===void 0||G.adapterId===j.adapterId)&&(G.capabilities===void 0||G.capabilities.includes(Q)));if(!re)return{ok:!1,operationId:N.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${j.sourceType}`,rolledBack:!1};let be=await re.execute(j);if(!be.ok)return{ok:!1,operationId:N.operationId,errorCode:"writeback-failed",reason:be.reason??`External adapter failed for ${j.sourceType}`,rolledBack:!1};M.push(j.file)}return{ok:!0,operationId:N.operationId,kind:N.kind,target:N.target,resultVersion:0,affectedFiles:M}}function I(N,W){if(N.conflictPolicy!=="compare-and-swap")return null;let M=new Map(W.map(j=>[j.file,j]));for(let j of N.edits){if(j.operation==="create-only")continue;if(j.baseContentHash===void 0)return{file:j.file,reason:`Source file ${j.file} is missing baseContentHash. Reopen the file before saving.`};let Q=M.get(j.file),re=j.baseContentHash;if(re===null){if(Q?.exists!==!1)return{file:j.file,reason:`Source file ${j.file} was created or changed before save.`};continue}if(!re)return{file:j.file,reason:`Source file ${j.file} is missing baseContentHash. Reopen the file before saving.`};if(Q?.exists===!1||Q?.sha256!==re)return{file:j.file,reason:`Source file ${j.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function w(N){let W=[];for(let M of N)W.push(await A(M));return W}async function A(N){if(!await e.exists(N))return{file:N,content:"",version:0,exists:!1};let M=Math.max(1,e.getVersion(N)),j=await e.readFile(N);return{file:N,content:j,version:M,exists:!0,sha256:fe(j)}}async function O(N,W,M=new Set){let j=[];try{for(let Q of N){if(M.has(Q.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive(Q.file,Q.content)}else await ie(Q);let re=e.bumpVersion(Q.file);j.push(Q.file),Q.version=re}}catch(Q){let re=await oe(W.filter(G=>j.includes(G.file)));if(re.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${re.failedFiles.join(", ")}: ${Gf(Q)}`,rolledBack:!1,instanceConflict:Hf(Q)};let be=Hf(Q);return{ok:!1,reason:`${be?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${Gf(Q)}`,rolledBack:!0,instanceConflict:be}}return{ok:!0,snapshots:N.map(sv)}}async function ie(N){if(N.exists===!1){await e.deleteFile(N.file);return}await e.writeFile(N.file,N.content)}async function oe(N){let W=[];for(let M of N)try{await ie(M),e.bumpVersion(M.file)}catch{W.push(M.file)}return W.length===0?{ok:!0}:{ok:!1,failedFiles:W}}}function Hf(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function sv(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:fe(e.content)}:{}}}function Gf(e){return e instanceof Error?e.message:String(e)}function Yf(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 Oe(jn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return Oe($n({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return Oe(Fn({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return Oe(Mn({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return Oe(Ro({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return Oe(fr({source:t,locator:e.locator,next:e.value}));case"update-array-item":return Oe(fr({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return Oe(_o({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return Oe(No({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return Oe(Fo({source:t,locator:e.locator,index:e.index}));case"move-array-item":return Oe(Oo({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return Oe(Ln({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return Oe(Po({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 av(e,t);case"set-property-changes":return Oe(Ao({source:t,locator:e.locator,changes:e.changes}));case"set-property-binding":return Oe(To({source:t,locator:e.locator,name:e.name,object:e.object,property:e.property}));case"upsert-object-property":return Oe(Do({source:t,objectLocator:e.locator,name:e.name,value:e.value}));default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function av(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!Ku(n.newAttrRaw))return{ok:!1,reason:"newAttrRaw must be a valid JSX className attribute.",errorCode:"invalid-params"};let r=n.oldAttrRange!==null&&n.oldAttrRaw!==null,o=n.openingElementRange.start,i=n.openingElementRange.end,s=t.slice(o,i);if(!(Number.isInteger(o)&&Number.isInteger(i)&&o>=0&&i>o&&i<=t.length&&s.startsWith("<")&&s.endsWith(">")&&!s.startsWith("</")&&(n.oldAttrRange===null||n.oldAttrRange.start>=o&&n.oldAttrRange.end<=i)))return{ok:!1,reason:"The opening element range changed before className save.",errorCode:"stale-version"};if(!r&&n.expectedVersion.contentHash!==fe(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:Uu({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function Oe(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 Qf(){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{classifySiteEditPropertyName as cv}from"@vcp-dev/contracts";async function qf(e){let t=cv(e.propertyName);if(t.owner==="blocked")return Qt(t.owner,t.diagnostic);if(t.owner==="class-name-source"||t.owner==="style")return Qt(t.owner,{code:"owner-delegated",message:`Property '${e.propertyName}' is owned by ${t.owner}`});let n=e.element.attributes?.filter(l=>l.name===e.propertyName)??[];if(n.length>1)return Qt("generic",{code:"duplicate-property-source",message:`Property '${e.propertyName}' has multiple explicit sources`});let r=n[0],o=[];r&&o.push({kind:"attribute",order:r.order??e.element.attributes.indexOf(r),attribute:r});let i=e.element.attributeSpreads??[];for(let l of i)o.push({kind:"spread",order:l.order,spread:l,target:await uv(e,l)});o.sort((l,u)=>l.order-u.order);let s=o.at(-1);if(!s)return{status:"missing",owner:"generic"};if(o.filter(l=>l.kind==="spread"&&l.order>s.order).some(l=>!l.target))return Qt("generic",{code:"ambiguous-property-source",message:`A spread may provide or override property '${e.propertyName}'`});if(s.kind==="spread")return s.target?{status:"binding",owner:"generic",target:s.target}:Qt("generic",{code:"ambiguous-property-source",message:`The final spread source for '${e.propertyName}' is not provably writable`});let c=o.filter(l=>l.kind==="spread"&&l.order<s.order);return e.operation==="remove"&&c.length>0?Qt("generic",{code:"remove-exposes-spread",message:`Removing '${e.propertyName}' would expose an earlier spread source`}):lv(e,s.attribute)}async function lv(e,t){if(t.resolution&&t.resolution.status!=="resolved"&&!t.source){let r=await Wn({file:e.file,source:e.source,sourceRange:t.sourceRange,expression:t.value,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache});return r&&r.kind!=="external-entry"?{status:"binding",owner:"generic",attribute:t,target:{kind:"value-binding",target:r}}:Qt("generic",{code:"unsupported-property-source",message:`Property '${e.propertyName}' has an unresolved value source`})}if(!t.source?.expression)return{status:"direct",owner:"generic",attribute:t,target:{kind:"jsx-attribute",file:e.file,sourceRange:t.sourceRange}};let n=await Wn({file:e.file,source:e.source,sourceRange:t.sourceRange,expression:t.source.expression,sourceInfo:t.source,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache});return!n||n.kind==="external-entry"?Qt("generic",{code:"unsupported-property-source",message:`Property '${e.propertyName}' does not have a local writable source`}):{status:"binding",owner:"generic",attribute:t,target:{kind:"value-binding",target:n}}}async function uv(e,t){let n=t.source?.expression;if(!n)return;let r=await Wn({file:e.file,source:e.source,sourceRange:t.sourceRange,expression:n,sourceInfo:t.source,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache});if(!(!r||r.kind==="external-entry"))return{kind:"value-binding",target:dv(r,e.propertyName)}}function dv(e,t){let n=[...e.path??[],{kind:"property",name:t}];return{...e,path:n,locator:e.locator?{...e.locator,path:n}:{kind:"value",root:e.root??{kind:"binding",name:t},path:n}}}function Qt(e,t){return{status:"blocked",owner:e,...t?{diagnostic:t}:{}}}import*as za from"@babel/parser";import Xa from"@babel/traverse";import*as K from"@babel/types";import{classifySiteEditPropertyName as fv}from"@vcp-dev/contracts";var Wa=typeof Xa=="function"?Xa:Xa.default;function Ha(e){let t=fv(e.propertyName);if(t.owner!=="generic")return ze("invalid-property",t.diagnostic?.message??`Property '${e.propertyName}' is not a generic property`);let n=e.selectionRef;if(!n)return ze("missing-selection-ref","A repeat property target requires a complete selection reference");if(n.key!==e.element.identity.key)return ze("selection-mismatch","Selection reference does not identify the requested element");if(n.instanceIndex===void 0)return ze("missing-instance-index","A repeat property target requires an instance index");let r;try{r=za.parse(e.source,{sourceType:"module",plugins:["typescript","jsx"]})}catch(C){return ze("repeat-not-found",`Unable to parse repeat source: ${C instanceof Error?C.message:String(C)}`)}let o=pv(r,e.element.sourceRange);if(!o)return ze("repeat-not-found","The selected element is not inside a supported map repeat");if(!K.isIdentifier(o.callback.params[0]))return ze("unsupported-callback","Repeat property materialization requires an identifier callback item");let i=mv(r,o.collection,e.file,e.sources);if(!i)return ze("collection-not-found","The repeat collection is not a visible local static array");let{array:s,locator:a,sourceFile:c}=i,l=[],u=[];for(let[C,I]of s.elements.entries()){if(!I||!K.isObjectExpression(I)||!ip(I))return ze("unsafe-collection","Repeat materialization requires an array of local static objects without spreads");let w=[{kind:"index",index:C}];l.push(w),u.push({kind:"value",root:a.root,path:w})}let d=u.length;if(n.instanceCount!==void 0&&n.instanceCount!==d)return ze("count-mismatch",`Selection reports ${n.instanceCount} instances but the source collection has ${d}`);let p=n.instanceIndex;if(p>=d)return ze("index-out-of-range",`Selected repeat instance ${p} is outside the source collection`);let m=s.elements[p];if(!m||!K.isObjectExpression(m))return ze("unsafe-collection","Selected repeat item is not an object");let g=Sv(e.element,e.propertyName),b=xv(m,e.propertyName);return b?{ok:!0,sourceFile:c,templateFile:e.file,collectionLocator:a,parentObjectLocators:u,selectedParentObjectLocator:u[p],sourceItemIndex:p,sourceItemPath:l[p],collectionIndexMap:Array.from({length:d},(C,I)=>I),callbackItemName:o.callback.params[0].name,targetElementLocator:{kind:"jsx-node",strategy:"structural-path",file:e.element.identity.file,component:e.element.identity.component,structuralPath:e.element.identity.structuralPath,expectedRange:e.element.sourceRange},propertyName:e.propertyName,propertyState:b,selectedResolution:bv(m,e.propertyName),...g?{property:g}:{},selectionRef:n}:ze("unsafe-property-source",`Property '${e.propertyName}' has a dynamic or unsupported source in the repeat item`)}function pv(e,t){let n=[];return Wa(e,{CallExpression(r){let o=ep(r.node);o&&np(o.callback,t)&&n.push({...o,span:tp(r.node)})},OptionalCallExpression(r){let o=ep(r.node);o&&np(o.callback,t)&&n.push({...o,span:tp(r.node)})}}),n.sort((r,o)=>r.span-o.span),n[0]??null}function ep(e){let t=e.callee;if(!K.isMemberExpression(t)&&!K.isOptionalMemberExpression(t)||t.computed||!K.isIdentifier(t.property)||t.property.name!=="map"||!K.isExpression(t.object))return null;let n=e.arguments[0];return!n||!K.isExpression(n)||!K.isArrowFunctionExpression(n)&&!K.isFunctionExpression(n)?null:{collection:t.object,callback:n}}function mv(e,t,n,r){let o=Or(t);if(o&&K.isArrayExpression(o))return{array:o,locator:{kind:"value",root:{kind:"expression",sourceRange:ap(o)}},sourceFile:n};if(!K.isIdentifier(t))return null;let i=[];if(Wa(e,{VariableDeclarator(s){K.isIdentifier(s.node.id)&&s.node.id.name===t.name&&s.node.init&&i.push(s.node)}}),i.length===1){let s=Or(i[0].init);return!s||!K.isArrayExpression(s)?null:{array:s,locator:{kind:"value",root:{kind:"binding",name:t.name}},sourceFile:n}}return gv(e,t.name,n,r)}function gv(e,t,n,r){if(!r)return null;for(let o of e.program.body){if(!K.isImportDeclaration(o))continue;let i=o.specifiers.find(p=>p.local.name===t);if(!i||!K.isStringLiteral(o.source)||!K.isImportSpecifier(i))continue;let s=yv(n,o.source.value,r);if(!s)return null;let a=K.isIdentifier(i.imported)?i.imported.name:i.imported.value,c=r.get(s);if(c===void 0)return null;let l;try{l=za.parse(c,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}let u=hv(l,a),d=u?Or(u):null;return!d||!K.isArrayExpression(d)?null:{array:d,locator:{kind:"value",root:{kind:"binding",name:a}},sourceFile:s}}return null}function hv(e,t){let n=null;return Wa(e,{VariableDeclarator(r){n||!K.isIdentifier(r.node.id)||r.node.id.name!==t||!r.node.init||!K.isExpression(r.node.init)||(n=r.node.init)}}),n}function yv(e,t,n){let r=tr(e,t);return[r,r+".tsx",r+".ts",r+".jsx",r+".js",r+"/index.tsx",r+"/index.ts",r+"/index.jsx",r+"/index.js"].find(i=>n.has(i))??null}function Or(e){return K.isParenthesizedExpression(e)?Or(e.expression):K.isTSAsExpression(e)?op(e.typeAnnotation)?Or(e.expression):null:K.isTSSatisfiesExpression(e)?null:e}function op(e){return K.isTSTypeReference(e)&&K.isIdentifier(e.typeName)&&e.typeName.name==="const"}function ip(e){return e.properties.every(t=>!K.isObjectProperty(t)||t.computed||!K.isExpression(t.value)?!1:ci(t.value))}function ci(e){if(K.isTSAsExpression(e)&&op(e.typeAnnotation))return ci(e.expression);if(K.isTSSatisfiesExpression(e))return!1;if(K.isArrayExpression(e))return e.elements.every(n=>!n||K.isSpreadElement(n)||!K.isExpression(n)?!1:ci(n));if(K.isObjectExpression(e))return ip(e);let t=ht(e);return t.status==="resolved"||t.status==="undefined"}function xv(e,t){let n=e.properties.filter(o=>K.isObjectProperty(o)&&sp(o.key)===t);if(n.length>1)return null;let r=n[0];return r?K.isExpression(r.value)?ci(r.value)?"static":K.isIdentifier(r.value)||K.isMemberExpression(r.value)?"binding":null:null:"missing"}function bv(e,t){let n=e.properties.filter(o=>K.isObjectProperty(o)&&sp(o.key)===t);if(n.length>1)return{status:"unresolved"};let r=n[0];return!r||!K.isExpression(r.value)?{status:"undefined"}:ht(r.value)}function Sv(e,t){let n=e.attributes?.filter(r=>r.name===t)??[];return n.length===1?n[0]:void 0}function sp(e){return K.isIdentifier(e)?e.name:K.isStringLiteral(e)?e.value:K.isNumericLiteral(e)?String(e.value):null}function ap(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 tp(e){return e.start==null||e.end==null?Number.MAX_SAFE_INTEGER:e.end-e.start}function np(e,t){let n=ap(e);return rp(n.startLine,n.startColumn,t.startLine,t.startColumn)<=0&&rp(n.endLine,n.endColumn,t.endLine,t.endColumn)>=0}function rp(e,t,n,r){return e===n?t-r:e-n}function ze(e,t){return{ok:!1,errorCode:e,reason:t}}function up(e){let t=e.isRepeat??(e.graph?Pv(e.element,e.graph):!1),n=e.propertyProvenance??new Map,r=e.repeatTargets??new Map,o=Nv(e.element.attributes??[]),i=[...r.values()].some(u=>u.ok),s=o.map(u=>Ev({attribute:u,element:e.element,isRepeat:t,selectionRef:e.selectionRef,provenance:n.get(u.name),repeatTarget:r.get(u.name)})),a=(e.element.attributeSpreads?.length??0)>0,c=(e.element.attributeSpreads??[]).slice().sort((u,d)=>u.order-d.order).map(u=>({raw:u.raw,sourceRange:Tv(u.sourceRange,e.source),order:u.order,diagnostics:u.source?[]:[{code:"unsupported-spread-source",message:"The spread source cannot be resolved safely, so property ownership is conservative."}]})),l=t&&e.selectionRef?.instanceIndex!==void 0&&i;return{documentVersion:e.documentVersion,...e.selectionRef?{selectionRef:e.selectionRef}:{},items:s,spreads:c,creation:t?{selection:l?"materialize":"unsupported",template:"unsupported"}:{selection:a?"unsupported":"direct",template:a?"unsupported":"direct"}}}function Ev(e){let{attribute:t,provenance:n,repeatTarget:r}=e,o=e.selectionRef?.instanceIndex!==void 0&&r?.ok===!0?r:null,i=vv(t,n,e.isRepeat),s=Iv(t,n,o,e.isRepeat),a=Cv(n,o,e.element),c=o?"repeat-item":e.isRepeat?"repeat-template":"node",l=wv(t,n,r);return{name:t.name,source:i,resolution:s,editMode:a,sourceScope:c,allowedWriteScopes:Rv(a,c,n),...lp(n,o,e.element)?{effectiveWriteTarget:lp(n,o,e.element)}:{},diagnostics:l}}function vv(e,t,n){let r;if(n&&t?.status==="binding"){let o=t.target;r=o?.kind==="value-binding"&&o.target.sourceKind==="repeat-template"?"repeat-template":"binding"}else e.syntaxKind==="boolean-shorthand"?r="boolean-shorthand":e.syntaxKind==="literal"||!e.source?r="literal":r="expression";return{kind:r,...e.raw!==void 0?{raw:e.raw}:{}}}function Iv(e,t,n,r){return n?cp(n.selectedResolution):t?.status==="blocked"?{status:"unresolved"}:r&&t?.status==="binding"?{status:"unresolved"}:cp(kv(e))}function kv(e){return e.resolution?e.resolution:e.syntaxKind==="boolean-shorthand"?{status:"resolved",value:!0}:e.resolvedValue!==void 0?{status:"resolved",value:e.resolvedValue}:e.source?{status:"unresolved"}:{status:"resolved",value:e.value}}function cp(e){return!e||e.status==="unresolved"?{status:"unresolved"}:e.status==="undefined"?{status:"undefined"}:{status:"resolved",value:e.value}}function Cv(e,t,n){if(t)return"direct";if(!e||e.status==="blocked")return"unsupported";if(e.status==="missing"||e.status==="direct")return"direct";let r=e.target;return r?.kind!=="value-binding"?"unsupported":r.target.file===n.sourceFile?"direct":"proxy"}function Rv(e,t,n){return e==="readonly"||e==="unsupported"?[]:n?.status==="binding"?t==="repeat-template"?["template"]:["selection"]:t==="repeat-template"?["template"]:["selection","template"]}function lp(e,t,n){if(t)return{kind:"value-path",file:t.sourceFile,isProxy:t.sourceFile!==n.sourceFile,displayPath:`${Av(t.selectedParentObjectLocator)}.${t.propertyName}`};if(e?.target?.kind==="jsx-attribute")return{kind:"jsx-node",file:e.target.file,isProxy:e.target.file!==n.sourceFile,displayPath:`${n.componentName} > ${e.attribute?.name??"attribute"}`};if(e?.target?.kind==="value-binding")return{kind:"value-path",file:e.target.target.file,isProxy:e.target.target.file!==n.sourceFile,displayPath:e.target.target.displayExpression}}function wv(e,t,n){let r=[];return t?.diagnostic&&r.push({code:t.diagnostic.code,message:t.diagnostic.message}),n&&!n.ok&&t?.status!=="missing"&&r.push({code:`repeat-${n.errorCode}`,message:n.reason}),e.resolution?.status==="unresolved"&&r.length===0&&r.push({code:"unsupported-property-source",message:`Property '${e.name}' has an unresolved value source`}),r}function Nv(e){let t=new Set;return e.filter(n=>t.has(n.name)?!1:(t.add(n.name),!0))}function Pv(e,t){let n=t.regions.filter(r=>r.kind==="repeat-region");for(let r of n){let o=e;for(;o;){if(r.childKeys.includes(o.identity.key))return!0;o=o.parentKey?t.elements.get(o.parentKey):void 0}}return!1}function Av(e){return`${e.root.kind==="binding"?e.root.name:e.root.kind==="expression"?e.root.sourceRange?"expression":"value":e.root.kind}${(e.path??[]).map(n=>n.kind==="index"?`[${n.index}]`:`.${n.name}`).join("")}`}function Tv(e,t){if(!t)return{start:e.startColumn,end:e.endColumn};let n=t.split(`
5
- `),r=(o,i)=>n.slice(0,Math.max(0,o-1)).reduce((s,a)=>s+a.length+1,0)+i;return{start:r(e.startLine,e.startColumn),end:r(e.endLine,e.endColumn)}}import{randomUUID as _v}from"node:crypto";import li from"node:fs/promises";import Ga from"node:path";import{setTimeout as Fv}from"node:timers/promises";var Ov={async mkdir(e,t){await li.mkdir(e,t)},async writeFile(e,t,n){await li.writeFile(e,t,n)},async rename(e,t){await li.rename(e,t)},async rm(e,t){await li.rm(e,t)}},Mv=new Set(["EACCES","EBUSY","EPERM"]),Dv=[10,20,40,80,160];async function Lv(e,t,n){for(let r of Dv)try{await e.rename(t,n);return}catch(o){if(!Bv(o))throw o;await Fv(r)}await e.rename(t,n)}function Bv(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&Mv.has(e.code)}async function ui(e,t,n=Ov){let r=Ga.dirname(e),o=Ga.basename(e),i=Ga.join(r,`.${o}.${process.pid}.${_v()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await Lv(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import{randomBytes as qv}from"node:crypto";import _t from"node:path";import{parse as eI}from"@babel/parser";import tI from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as fi,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as mp,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as nI,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as rI,SiteEditMaterializationSchema as oI,parseComponentI18nResourcesJson as iI}from"@vcp-dev/contracts";var fp=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,pp=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,jv=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,$v=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,Vv=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,Uv=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,Kv=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,Jv=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,Xv=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,zv=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,Wv=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,Hv=/\b(?:bg|text|border|ring|outline|fill|stroke)-(?:black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)(?:-\d{2,3})?(?:\b|\/)/g,Gv=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,Yv=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function Mr(e,t){let n=di([...tt(e,jv),...tt(e,$v),...tt(e,Vv),...tt(e,t.includeRgbBackgroundImage?Uv:Kv),...t.includeExtendedColorFunctions?[...tt(e,Jv),...tt(e,Xv)]:[]]),r=di([...tt(e,zv),...tt(e,Wv)]).filter(o=>t.colorMixPolicy==="always"||fp.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...tt(e,Hv).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...tt(e,Yv).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:di(tt(e,pp)),hardCodedSurfaceOccurrences:Qv(e),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?di(tt(e,Gv)):[]}}function tt(e,t){return e.match(new RegExp(t.source,t.flags))??[]}var dp=160,Zv=/((?:[a-z][a-z0-9-]*(?:\[[^\]]*\])?:)+)$/;function Qv(e){let t=new RegExp(pp.source,"g"),n=[0];for(let s=0;s<e.length;s+=1)e[s]===`
6
- `&&n.push(s+1);let r=s=>{let a=0,c=n.length-1;for(;a<c;){let l=Math.ceil((a+c)/2);(n[l]??0)<=s?a=l:c=l-1}return a},o=[],i;for(;(i=t.exec(e))!==null;){let s=i[0],a=s.endsWith("/")?s.slice(0,-1):s,c=/^\/(\d+)/.exec(e.slice(i.index+a.length)),l=e.slice(Math.max(0,i.index-64),i.index),u=Zv.exec(l),d=r(i.index),p=e.indexOf(`
7
- `,i.index),m=e.slice(n[d]??0,p===-1?void 0:p).trim();o.push({token:a,variant:u?.[1]??"",alpha:c?Number(c[1]):null,line:d+1,snippet:m.length>dp?`${m.slice(0,dp-1)}\u2026`:m})}return o}function di(e){return[...new Set(e)]}var Qa="components/site/generated",gp="{{$INSTANCE}}",pi=5,sI=/^[a-z][a-z0-9-]{0,48}$/,aI=/^[a-f0-9]{8}$/,hp=/\.tsx?$/,cI=/\.json$/,lI=/\.(?:tsx?|json)$/,uI=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,dI=["react","react/","next","next/","lucide-react","react-i18next","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],Ya=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Za=tI,fI=typeof Za=="function"?Za:Za.default;function pI(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>mp)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=kI(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=oI.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=EI(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${Qa}.`,path:e.generatedRoot}};if(!vp(r.data.instanceBaseName))return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_INVALID",message:"Static prefab instanceBaseName must contain at least one safe word.",path:r.data.instanceBaseName}};let i=bp(r.data.files),s=bp(e.controlledFiles);if(!CI(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>mp)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let a=0;for(let[c,l]of r.data.files.entries()){let u=Buffer.byteLength(l.content,"utf8");if(u>nI)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file exceeds the per-file content limit.",file:l.pathTemplate,path:`files[${c}]`}};a+=u}return a>rI?{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab exceeds the reusable total content limit."}}:{ok:!0,data:{kind:"static-prefab-materialization",instanceName:"",generatedRoot:o,instanceRoot:"",entry:{path:"",export:r.data.entry.export},files:[]}}}async function mI(e){let t=pI(e);if(!t.ok)return t;let n=t.data.generatedRoot,r=vp(e.manifest.instanceBaseName),o=Math.max(1,Math.min(pi,e.maxAttempts??pi));for(let i=0;i<o;i+=1){let s=vI(e.instanceNameGenerator?.()??qv(4).toString("hex"));if(!s)return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_INVALID",message:"Static prefab instance suffix must be 8 lowercase hex chars."}};let a=`${r}-${s}`,c=kp(n,a),l=gI({manifest:e.manifest,generatedRoot:n,instanceName:a,instanceRoot:c,allowedExternalImports:e.allowedExternalImports??dI});if(!l.ok)return l;if(!await hI(e.exists,c,l.data.files))return{ok:!0,data:l.data}}return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:"Unable to allocate a create-only static prefab instance after repeated conflicts."}}}async function Ep(e){let t=Math.max(1,Math.min(pi,e.maxAttempts??pi));for(let n=0;n<t;n+=1){let r=await mI({...e,maxAttempts:1});if(!r.ok){if(r.error.code==="MATERIALIZATION_INSTANCE_CONFLICT")continue;return r}let o=await e.commit(r.data);if(o.ok)return{ok:!0,plan:r.data,data:o.data};if(o.error.code!=="MATERIALIZATION_INSTANCE_CONFLICT")return o}return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:"Unable to commit a complete static prefab instance after repeated conflicts."}}}function gI(e){let t=[],n=new Set;for(let i of e.manifest.files){let s=yp({pathTemplate:i.pathTemplate,generatedRoot:e.generatedRoot,instanceName:e.instanceName,instanceRoot:e.instanceRoot});if(!s.ok)return s;if(n.has(s.data))return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${s.data}`,path:s.data}};n.add(s.data),t.push({kind:"create-only",path:s.data,content:i.content,...i.role?{role:i.role}:{},sourcePathTemplate:i.pathTemplate})}t.sort((i,s)=>i.path.localeCompare(s.path));let r=yp({pathTemplate:e.manifest.entry.pathTemplate,generatedRoot:e.generatedRoot,instanceName:e.instanceName,instanceRoot:e.instanceRoot});if(!r.ok)return r;if(!t.some(i=>i.path===r.data))return{ok:!1,error:{code:"MATERIALIZATION_ENTRY_INVALID",message:"Entry path must match one of the static prefab files.",path:r.data}};let o=yI(t,e.instanceRoot,r.data,e.manifest.entry.export,e.allowedExternalImports);return o.ok?{ok:!0,data:{kind:"static-prefab-materialization",instanceName:e.instanceName,generatedRoot:e.generatedRoot,instanceRoot:e.instanceRoot,entry:{path:r.data,export:e.manifest.entry.export},files:t}}:o}async function hI(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function yp(e){if(e.pathTemplate.split(gp).length!==2)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab path templates must include the instance placeholder exactly once.",path:e.pathTemplate}};let t=e.pathTemplate.replaceAll(gp,e.instanceName),n=II(t);return n?kp(e.generatedRoot,e.instanceName)!==e.instanceRoot?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab instance root normalization failed.",path:e.pathTemplate}}:n!==e.instanceRoot&&!n.startsWith(`${e.instanceRoot}/`)?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab path must stay under components/site/generated/<instance>.",path:n}}:n!==t?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab path template cannot rely on path normalization semantics.",path:e.pathTemplate}}:n===e.instanceRoot||!lI.test(n)||uI.test(n)?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab files must be .ts/.tsx/.json files and cannot be config, layout, provider, or global source files.",path:n}}:{ok:!0,data:n}:{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab path template resolves to an unsafe path.",path:e.pathTemplate}}}function yI(e,t,n,r,o){let i=new Set(e.map(d=>d.path)),s=new Map,a=new Map(e.map(d=>[d.path,new Set])),c=new Map;for(let d of e){if(cI.test(d.path)){if(d.path.endsWith(fi)){let g=iI(d.content);if(!g.success)return xn("MATERIALIZATION_DATA_UNSUPPORTED",g.error.message,d.path);c.set(d.path,new Set)}else try{JSON.parse(d.content)}catch{return xn("MATERIALIZATION_DATA_UNSUPPORTED","Static prefab JSON file must contain valid JSON.",d.path)}continue}let p;try{p=eI(d.content,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files must parse as plain module source.",file:d.path}}}let m=Mr(d.content,{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0});if(m.hardCodedSurfaceHits.length>0||m.rawColorHits.length>0||m.privateTokenHits.length>0)return{ok:!1,error:{code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source must use public semantic design tokens instead of raw colors or private tokens.",file:d.path}};s.set(d.path,p)}for(let d of e){if(!hp.test(d.path))continue;let p=s.get(d.path),m=null;if(fI(p,{ImportDeclaration(g){let b=xp({importer:d.path,source:g.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});if(!b.allowed)m??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab imports must resolve within the controlled instance or match the starter allowlist.",file:d.path},g.stop();else if(b.internalPath&&(a.get(d.path).add(b.internalPath),b.internalPath.endsWith(fi))){let C=xI({importer:d.path,imported:b.internalPath,source:g.node.source.value,ast:p});C.ok?c.get(b.internalPath).add(d.path):(m??=C.error,g.stop())}},ExportAllDeclaration(g){m??={code:"MATERIALIZATION_ENTRY_INVALID",message:"Static prefab files cannot use export-star declarations.",file:d.path},g.stop()},ExportNamedDeclaration(g){if(g.node.source){let b=xp({importer:d.path,source:g.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});!b.allowed||!b.internalPath?(m??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab re-exports must resolve within the controlled instance.",file:d.path},g.stop()):a.get(d.path).add(b.internalPath)}},CallExpression(g){if(g.node.callee.type==="Import"){m??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use dynamic import().",file:d.path},g.stop();return}g.node.callee.type==="Identifier"&&g.node.callee.name==="require"&&(m??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use require().",file:d.path},g.stop())},NewExpression(g){g.node.callee.type==="Identifier"&&g.node.callee.name==="Function"&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot construct functions dynamically.",file:d.path},g.stop())},MetaProperty(g){g.node.meta.type==="Identifier"&&g.node.meta.name==="import"&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot use import.meta.",file:d.path},g.stop())},MemberExpression(g){let b=Sp(g.node);b&&Ya.has(b)&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${b}.`,file:d.path},g.stop())},OptionalMemberExpression(g){let b=Sp(g.node);b&&Ya.has(b)&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${b}.`,file:d.path},g.stop())},Identifier(g){g.isReferencedIdentifier()&&Ya.has(g.node.name)&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${g.node.name}.`,file:d.path},g.stop())},JSXAttribute(g){g.node.name.type==="JSXIdentifier"&&g.node.name.name==="style"&&(m??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot use inline style attributes.",file:d.path},g.stop())},JSXOpeningElement(g){g.node.name.type==="JSXIdentifier"&&g.node.name.name.toLowerCase()==="style"&&(m??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot declare style elements.",file:d.path},g.stop())}}),m)return{ok:!1,error:m}}if(!hp.test(n))return xn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must be a .ts/.tsx source module.",n);let l=s.get(n);if(!l)return xn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",n);if(!bI(l,r))return xn("MATERIALIZATION_EXPORT_MISSING","Static prefab entry does not declare the manifest export.",n);for(let[d,p]of c)if(p.size!==1)return xn("MATERIALIZATION_IMPORT_FORBIDDEN","Each component .i18n.json file must have exactly one same-name Client Component static importer.",d);return SI(n,a).size!==e.length?xn("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",n):{ok:!0,data:{kind:"static-prefab-materialization",instanceName:"",generatedRoot:Qa,instanceRoot:"",entry:{path:"",export:{kind:"default"}},files:[]}}}function xp(e){if(!e.source.startsWith("./")&&!e.source.startsWith("../"))return e.source.startsWith("@/components/site/generated/")?{allowed:!1}:{allowed:e.allowedExternalImports.some(o=>o.endsWith("/")?e.source.startsWith(o):e.source===o)};if(e.source.includes("\\")||e.source.includes("\0"))return{allowed:!1};let t=_t.posix.normalize(_t.posix.join(_t.posix.dirname(e.importer),e.source));if(t===e.instanceRoot||!t.startsWith(`${e.instanceRoot}/`))return{allowed:!1};let r=[t,`${t}.ts`,`${t}.tsx`,`${t}.json`,...["ts","tsx","json"].map(o=>`${t}/index.${o}`)].find(o=>e.filePaths.has(o));return r?{allowed:!0,internalPath:r}:{allowed:!1}}function xI(e){let t=_t.posix.dirname(e.importer),n=_t.posix.dirname(e.imported),r=_t.posix.basename(e.importer).replace(/\.tsx?$/,""),o=_t.posix.basename(e.imported).slice(0,-fi.length),i=`./${r}${fi}`;return!e.importer.endsWith(".tsx")||t!==n||r!==o||e.source!==i?{ok:!1,error:{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Component i18n resources must use an explicit same-directory, same-name import from a .tsx file.",file:e.importer}}:e.ast.program.directives.some(a=>a.value.value==="use client")?{ok:!0}:{ok:!1,error:{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:'A component that imports .i18n.json must declare the top-level "use client" directive.',file:e.importer}}}function bI(e,t){for(let n of e.program.body){if(t.kind==="default"&&n.type==="ExportDefaultDeclaration")return!0;if(t.kind!=="named"||n.type!=="ExportNamedDeclaration")continue;if(n.specifiers.some(o=>o.exported.type==="Identifier"&&o.exported.name===t.name))return!0;let r=n.declaration;if((r?.type==="FunctionDeclaration"||r?.type==="ClassDeclaration")&&r.id?.name===t.name||r?.type==="VariableDeclaration"&&r.declarations.some(o=>o.id.type==="Identifier"&&o.id.name===t.name))return!0}return!1}function SI(e,t){let n=new Set,r=[e];for(;r.length>0;){let o=r.pop();n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function xn(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function EI(e){let t=Ip(e);return t===Qa?t:null}function vI(e){let t=e.trim().toLowerCase();return aI.test(t)?t:null}function vp(e){let t=e.trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,49).replace(/-+$/g,"");return sI.test(t)?t:null}function Ip(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=_t.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function II(e){let t=Ip(e);return!t||t!==e?null:t}function kp(...e){return _t.posix.join(...e)}function bp(e){return new Set(e.map(t=>t.pathTemplate))}function kI(e){let t=new Set;for(let n of e){if(t.has(n.pathTemplate))return n.pathTemplate;t.add(n.pathTemplate)}return null}function CI(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Sp(e){let t=e;for(;;){if(!t||typeof t!="object"||!("type"in t))return null;if(t.type==="Identifier"&&"name"in t&&typeof t.name=="string")return t.name;if(t.type==="MemberExpression"||t.type==="OptionalMemberExpression"){t=t.object;continue}return null}}import{randomBytes as RI}from"node:crypto";import mi from"node:path";import{parse as rc}from"@babel/parser";import wI from"@babel/traverse";import*as Ap from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as ec,PageResourceArtifactSchema as NI,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as PI,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as AI,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as TI,parseComponentI18nResourcesJson as _I}from"@vcp-dev/contracts";var tc="{{$INSTANCE}}",FI=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,OI=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,nc="components/site/generated",MI=/\.(?:tsx?|json)$/,DI=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,LI=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],BI=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),qa=wI,jI=typeof qa=="function"?qa:qa.default;async function oc(e){let t=NI.safeParse(e.artifact);if(!t.success)return ce("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>RI(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=YI(r());if(!i)return ce("Random instance suffix must be 8 lowercase hex chars.");let s=`${ZI(n.resource_id)}-${i}`,a=new Map,c=new Map,l=[];for(let A of n.pages){let O=A.final_route.slice(1);a.set(A.template_page_id,A.final_route),c.set(A.template_page_id,A.title),l.push({template_page_id:A.template_page_id,title:A.title,final_route:A.final_route,route_file_path:`app/${O}/page.tsx`})}let u=[],d=new Set,p=new Set,m=new Map,g=new Map,b=[],C=new Set(n.pages.flatMap(A=>A.components.map(O=>O.component_id)));for(let A of n.components){if(!C.has(A.component_id))continue;let O=Cp({materialization:A.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c});if(!O.ok)return O;for(let ie of O.files){let oe=wp(ie,d,u);if(oe)return oe}p.add(O.entry),g.set(O.entry,O.entryExport),m.set(A.component_id,O.entry)}for(let[A,O]of n.pages.entries()){let ie=l[A],oe=Cp({materialization:O.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c,pageEntryTarget:ie.route_file_path,pageTitle:ie.title});if(!oe.ok)return oe;for(let M of oe.files){let j=wp(M,d,u);if(j)return j}p.add(oe.entry),g.set(oe.entry,oe.entryExport),b.push({entry:oe.entry,declaredComponentIds:new Set(O.components.map(M=>M.component_id))});let N=u.find(M=>M.file===ie.route_file_path);if(!N)return ce("Page materialization entry did not resolve to its final route file.",ie.route_file_path);if(JI(N.content,ie.route_file_path)!==ie.final_route)return ce(`Page ${O.template_page_id} requires a static PAGE_SEO.path equal to ${ie.final_route}.`,ie.route_file_path)}let I=VI(u,p,s,m,b,g);if(!I.ok)return I;for(let A of u)if(await e.exists(A.file))return!A.file.startsWith("app/")&&o>1?oc({...e,randomHex:r,maxAttempts:o-1}):{ok:!1,code:"MATERIALIZATION_CONFLICT",message:`Page resource create-only target already exists: ${A.file}`,path:A.file};let w=UI(u);return w||(u.sort((A,O)=>A.file.localeCompare(O.file)),{ok:!0,packageInstanceId:s,pages:l,files:u})}function Cp(e){let t=e.materialization.entry.pathTemplate,n=[];for(let o of e.materialization.files){let i=o.pathTemplate===t,s=i&&e.pageEntryTarget?e.pageEntryTarget:Rp(o.pathTemplate,e.packageInstanceId);if(!s)return ce("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=$I(o.content,e.packageInstanceId,e.routeByPage,e.titleByPage);if(!a.ok)return a;let c=i&&e.pageTitle!==void 0?XI(a.data,e.pageTitle,s):a;if(!c.ok)return c;n.push({operation:"create-only",file:s,content:c.data})}let r=e.pageEntryTarget??Rp(t,e.packageInstanceId);return!r||!n.some(o=>o.file===r)?ce("Materialization entry must match one controlled source file.",t):{ok:!0,files:n,entry:r,entryExport:e.materialization.entry.export}}function $I(e,t,n,r){let o,i=e.replace(FI,(c,l)=>{let u=n.get(l);return u||(o=l,c)});if(o)return ce(`Page route placeholder references unknown template page: ${o}`);let s=i.replace(OI,(c,l)=>{let u=r.get(l);return u?JSON.stringify(u):(o=l,c)});if(o)return ce(`Page title placeholder references unknown template page: ${o}`);let a=s.replaceAll(tc,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?ce("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function Rp(e,t){let n=`${nc}/${t}`;if(e.split(tc).length>2)return null;let o=e.replace(tc,t),i=`${nc}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=mi.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!MI.test(a)||DI.test(a)?null:a}function wp(e,t,n){return t.has(e.file)?ce(`Page resource materializations resolve duplicate target: ${e.file}`,e.file):(t.add(e.file),n.push(e),null)}function VI(e,t,n,r,o,i){let s=new Set(e.map(m=>m.file)),a=`${nc}/${n}`,c=new Map(e.map(m=>[m.file,new Set])),l=new Map;for(let m of e){if(m.file.endsWith(".json")){try{JSON.parse(m.content)}catch{return ce("Materialization JSON file must contain valid JSON.",m.file)}if(m.file.endsWith(ec)&&!_I(m.content).success)return ce("Materialization component i18n resources are invalid.",m.file);continue}try{let b=rc(m.content,{sourceType:"module",plugins:["jsx","typescript"]});l.set(m.file,b);for(let I of b.program.body)if((I.type==="ImportDeclaration"||I.type==="ExportAllDeclaration"||I.type==="ExportNamedDeclaration"&&I.source)&&I.source){let w=I.source.value,A=HI(m.file,w,s,a);if(!A.allowed)return ce(`Materialization import is outside the controlled package: ${w}`,m.file);A.internalPath&&c.get(m.file).add(A.internalPath)}let C;if(jI(b,{Identifier(I){I.isReferencedIdentifier()&&BI.has(I.node.name)&&(C??=I.node.name,I.stop())},JSXAttribute(I){I.node.name.type==="JSXIdentifier"&&I.node.name.name==="style"&&(C??="inline style",I.stop())},JSXOpeningElement(I){I.node.name.type==="JSXIdentifier"&&I.node.name.name.toLowerCase()==="style"&&(C??="style element",I.stop())}}),C)return ce(`Materialization source uses forbidden capability: ${C}`,m.file)}catch{return ce("Materialization source must parse as TS/TSX.",m.file)}let g=Mr(m.content,{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0});if(g.hardCodedSurfaceHits.length>0||g.rawColorHits.length>0||g.privateTokenHits.length>0)return ce("Materialization source violates the public theme token policy.",m.file)}if([...t].some(m=>!s.has(m)))return ce("Materialization entry is outside the controlled package.");for(let m of t)if(m.endsWith(".json"))return ce("Materialization JSON files cannot be package entries.");for(let[m,g]of i){let b=l.get(m);if(!b||!KI(b,g))return ce("Materialization entry does not declare its contracted export.",m)}let u=new Map([...r].map(([m,g])=>[g,m]));for(let m of o){let g=Pp(m.entry,c);for(let b of m.declaredComponentIds){let C=r.get(b);if(!C||!g.has(C))return ce(`Page entry does not reach declared component: ${b}`,m.entry)}for(let b of g){let C=u.get(b);if(C&&!m.declaredComponentIds.has(C))return ce(`Page entry imports undeclared component: ${C}`,m.entry)}}let d=new Set;for(let m of t)for(let g of Pp(m,c))d.add(g);if(d.size!==e.length)return ce("Every materialization file must be reachable from a package entry.");let p=GI(e,l,c);return p||{ok:!0}}function UI(e){if(e.length>PI)return ce("Page resource exceeds the aggregate source file limit.");let t=0;for(let n of e){let r=Buffer.byteLength(n.content,"utf8");if(r>AI)return ce("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>TI?ce("Page resource exceeds the aggregate content byte limit."):null}function KI(e,t){for(let n of e.program.body){if(t.kind==="default"){if(n.type==="ExportDefaultDeclaration")return!0;continue}if(n.type==="ExportNamedDeclaration"&&(n.declaration?.type==="VariableDeclaration"&&n.declaration.declarations.some(r=>r.id.type==="Identifier"&&r.id.name===t.name)||(n.declaration?.type==="FunctionDeclaration"||n.declaration?.type==="ClassDeclaration")&&n.declaration.id?.name===t.name||n.specifiers.some(r=>r.exported.type==="Identifier"&&r.exported.name===t.name)))return!0}return!1}function JI(e,t){let n;try{n=rc(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return null}for(let r of n.program.body){let o=r.type==="VariableDeclaration"?r:r.type==="ExportNamedDeclaration"&&r.declaration?.type==="VariableDeclaration"?r.declaration:null;if(o)for(let i of o.declarations){if(i.id.type!=="Identifier"||i.id.name!=="PAGE_SEO")continue;let s=gi(i.init);if(s?.type!=="ObjectExpression")return null;for(let a of s.properties){if(a.type!=="ObjectProperty"||a.computed||!zI(a.key))continue;let c=gi(a.value);return c?.type==="StringLiteral"?c.value:c?.type==="TemplateLiteral"&&c.expressions.length===0?c.quasis[0]?.value.cooked??null:null}return null}}return null}function XI(e,t,n){let r;try{r=rc(e,{sourceType:"module",sourceFilename:n,plugins:["jsx","typescript"]})}catch{return ce("Page materialization PAGE_SEO must parse as TS/TSX.",n)}for(let o of r.program.body){let i=o.type==="VariableDeclaration"?o:o.type==="ExportNamedDeclaration"&&o.declaration?.type==="VariableDeclaration"?o.declaration:null;if(i)for(let s of i.declarations){if(s.id.type!=="Identifier"||s.id.name!=="PAGE_SEO")continue;let a=gi(s.init);if(a?.type!=="ObjectExpression")return ce("Page materialization PAGE_SEO must be a static object.",n);let c=a.properties.find(u=>u.type==="ObjectProperty"&&!u.computed&&WI(u.key));if(!c||c.type!=="ObjectProperty")return ce("Page materialization PAGE_SEO must declare a static title.",n);let l=gi(c.value);return!l||l.type!=="StringLiteral"&&l.type!=="TemplateLiteral"||l.type==="TemplateLiteral"&&l.expressions.length>0||typeof l.start!="number"||typeof l.end!="number"?ce("Page materialization PAGE_SEO.title must be a static string.",n):{ok:!0,data:e.slice(0,l.start)+JSON.stringify(t)+e.slice(l.end)}}}return ce("Page materialization must declare a top-level PAGE_SEO object.",n)}function gi(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&Ap.isExpression(t)?t:null}function zI(e){return e.type==="Identifier"&&e.name==="path"||e.type==="StringLiteral"&&e.value==="path"}function WI(e){return e.type==="Identifier"&&e.name==="title"||e.type==="StringLiteral"&&e.value==="title"}function HI(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=Np(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:LI.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=mi.posix.normalize(mi.posix.join(mi.posix.dirname(e),t)),i=Np(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function Np(e,t){return[e,`${e}.ts`,`${e}.tsx`,`${e}.json`,`${e}/index.ts`,`${e}/index.tsx`,`${e}/index.json`].find(n=>t.has(n))}function GI(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(ec))continue;let i=o.file.slice(0,-ec.length),s=[`${i}.tsx`,`${i}.ts`].find(u=>r.has(u));if(!s)return ce("Component i18n resources require a same-name TS/TSX companion.",o.file);let c=t.get(s)?.program.directives.some(u=>u.value.value==="use client"),l=[...n].filter(([,u])=>u.has(o.file));if(!c||l.length!==1||l[0]?.[0]!==s)return ce("Component i18n resources must have exactly one same-name Client Component static importer.",s)}return null}function Pp(e,t){let n=new Set,r=[e];for(;r.length>0;){let o=r.pop();if(!n.has(o)){n.add(o);for(let i of t.get(o)??[])r.push(i)}}return n}function YI(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function ZI(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"page-resource"}function ce(e,t){return{ok:!1,code:"MATERIALIZATION_REJECTED",message:e,...t?{path:t}:{}}}import{COMPONENT_I18N_FILE_SUFFIX as QI,parseComponentI18nResourcesJson as qI,resolveSiteTextDirection as ek,SiteLocaleSchema as tk}from"@vcp-dev/contracts";var nk=["i18next","react-i18next"],rk="components/ui/site-locale-provider.tsx",ok="components/ui/component-i18n-provider.tsx",Tp="app/layout.tsx";async function sc(e){let t=e.files.filter(p=>p.path.endsWith(QI));if(t.length===0)return{ok:!0};for(let p of["package.json",Tp,rk,ok])if(!await e.exists(p))return bn(`Target snapshot is missing required i18n host file: ${p}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return bn("Target snapshot package.json is invalid.")}let r=_p(n)&&_p(n.dependencies)?n.dependencies:{},o=nk.filter(p=>typeof r[p]!="string"||r[p].trim().length===0);if(o.length>0)return bn(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile(Tp),s=ic(i,"html","lang"),a=ic(i,"html","dir"),c=ic(i,"SiteLocaleProvider","locale"),l=tk.safeParse(s);if(!l.success||!a||!c||s!==c||a!==ek(l.data))return bn("Target snapshot app/layout.tsx must keep html lang/dir and SiteLocaleProvider locale consistent.");if(!i.includes('from "@/components/ui/site-locale-provider"')||!/<SiteLocaleProvider\b/.test(i)||!/<\/SiteLocaleProvider>/.test(i))return bn("Target snapshot root layout is not wired to SiteLocaleProvider.");let u=l.data,d=u.split("-")[0];for(let p of t){let m=qI(p.content);if(!m.success)return bn(`Component i18n resource is invalid: ${p.path}.`);if(!Object.hasOwn(m.data,u)&&!Object.hasOwn(m.data,d))return bn(`Component i18n resource ${p.path} has no locale for ${u} or ${d}.`)}return{ok:!0}}function ic(e,t,n){let r=e.match(new RegExp(`<${t}\\b[^>]*>`))?.[0];if(!r)return null;let o=[...r.matchAll(new RegExp(`\\b${n}=(?:"([^"]+)"|\\{"([^"]+)"\\})`,"g"))];return o.length!==1?null:o[0]?.[1]??o[0]?.[2]??null}function _p(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bn(e){return{ok:!1,message:e}}import{HOME_PAGE_URL_PATH as wk}from"@vcp-dev/contracts";import{parse as E_}from"@babel/parser";import{parse as UT}from"@babel/parser";import{FormBlockIdSchema as JT,FormSpecV1Schema as XT}from"@vcp-dev/contracts";var Dr="components/site/generated/forms",zT=`${Dr}/vcp-form-runtime.tsx`,hi="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",WT=new RegExp(`^${Dr}/form-(${hi})\\.spec\\.ts$`),HT=new RegExp(`^${Dr}/form-(${hi})\\.tsx$`),GT=new RegExp(`^@/${Dr}/form-(${hi})$`),YT=new RegExp(`(?:^|/)${Dr}/form-(${hi})(?:\\.tsx?)?$`);var ZT=Symbol("invalid-literal");import{createHash as e_}from"node:crypto";import{posix as n_}from"node:path";import{parse as o_}from"@babel/parser";import{FormSpecV1Schema as s_}from"@vcp-dev/contracts";var a_=Symbol("dynamic");import{parse as ik}from"@babel/parser";function yi(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.type=="string"):[]}var sk=/^(?:src\/)?app\/(.*)page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function ak(e){let t=sk.exec(e);if(!t)return null;let r=(t[1]??"").split("/").filter(o=>o.length>0&&!/^\(.+\)$/.test(o));return r.length===0?"/":`/${r.join("/")}`}function ck(e){let t=e;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Fp(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function lk(e){let t=e;for(;t&&(t.type==="TSAsExpression"||t.type==="TSSatisfiesExpression"||t.type==="ParenthesizedExpression");)t=t.expression??null;return t}function ac(e){let t=e;if(t?.type==="StringLiteral"||t?.type==="NumericLiteral"||t?.type==="BooleanLiteral")return t.value;if(t?.type==="NullLiteral")return null;if(t?.type==="ArrayExpression")return(t.elements??[]).map(ac);if(t?.type==="ObjectExpression"){let n={};for(let r of yi(t.properties)){if(r.type!=="ObjectProperty"||r.computed)throw new Error("dynamic object property");let o=Fp(r.key);if(!o)throw new Error("unsupported object key");n[o]=ac(r.value)}return n}throw new Error(`unsupported static value: ${t?.type??"unknown"}`)}function cc(e,t){let n=[],r=ak(t);if(r===null)return{found:!1,seo:null,diagnostics:n};let o;try{o=ik(e,{sourceType:"module",plugins:["typescript","jsx"]})}catch(l){return n.push({code:"page-seo.parse-failed",message:l instanceof Error?l.message:String(l)}),{found:!1,seo:null,diagnostics:n}}let i;for(let l of yi(o.program.body)){let u=l.type==="ExportNamedDeclaration"?l.declaration:l;if(u?.type==="VariableDeclaration")for(let d of yi(u.declarations)){let p=d.id;p?.type==="Identifier"&&p.name==="PAGE_SEO"&&(i=d.init)}}if(i==null)return{found:!1,seo:null,diagnostics:n};let s=lk(i);if(!s)return{found:!1,seo:null,diagnostics:n};if(s.type!=="ObjectExpression")return n.push({code:"page-seo.dynamic-declaration",message:"PAGE_SEO is not a static object literal"}),{found:!1,seo:null,diagnostics:n};let a={};for(let l of yi(s.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=Fp(l.key);if(!(u!=="path"&&u!=="title"&&u!=="description"&&u!=="keywords"&&u!=="meta_tags_json"&&u!=="schema_json"&&u!=="breadcrumbs_json")){if(u==="path"||u==="title"||u==="description"||u==="keywords"){let d=ck(l.value);if(d===void 0){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} is not a static string; skipped`});continue}a[u]=d;continue}try{let d=ac(l.value);u==="meta_tags_json"&&d!==null&&typeof d=="object"&&!Array.isArray(d)?a.meta_tags_json=d:u==="schema_json"&&d!==null&&typeof d=="object"?a.schema_json=d:u==="breadcrumbs_json"&&Array.isArray(d)?a.breadcrumbs_json=d:n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} has unsupported static shape; skipped`})}catch(d){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} is not a static JSON-like value; skipped: ${d instanceof Error?d.message:String(d)}`})}}}let c=r;return a.path!==void 0&&(a.path!==r&&n.push({code:"page-seo.path-mismatch",message:`PAGE_SEO.path "${a.path}" != derived "${r}"; using PAGE_SEO.path`}),c=a.path),{found:!0,seo:{path:c,...a.title!==void 0?{title:a.title}:{},...a.description!==void 0?{description:a.description}:{},...a.keywords!==void 0?{keywords:a.keywords}:{},...a.meta_tags_json!==void 0?{meta_tags_json:a.meta_tags_json}:{},...a.schema_json!==void 0?{schema_json:a.schema_json}:{},...a.breadcrumbs_json!==void 0?{breadcrumbs_json:a.breadcrumbs_json}:{}},diagnostics:n}}import{parse as uk}from"@babel/parser";var Op=["page","anchor","external","email","phone","group","file"],dk=["link","cta"],Dp=["description","badge","iconKey"],lc=["label","targetType","href","role","openInNewTab","nofollow","children",...Dp],fk=new Set(lc);function Br(e){return Array.isArray(e)?e:[]}function Lr(e){let t=e;return t?.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function pk(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Mp(e){let t=e;return t?.type==="BooleanLiteral"&&typeof t.value=="boolean"?t.value:void 0}function uc(e){let t=[],n;try{n=uk(e,{sourceType:"module",plugins:["typescript","jsx"]})}catch(i){return{items:[],diagnostics:[{severity:"fatal",path:"NAV_ITEMS",message:`parse failed: ${String(i)}`}]}}let r;for(let i of Br(n.program.body)){let s=i.type==="ExportNamedDeclaration"?i.declaration:i;if(s?.type==="VariableDeclaration")for(let a of Br(s.declarations)){let c=a.id;c?.type==="Identifier"&&c.name==="NAV_ITEMS"&&(r=a.init)}}for(;r&&(r.type==="TSAsExpression"||r.type==="TSSatisfiesExpression"||r.type==="TSInstantiationExpression");)r=r.expression;if(!r||r.type!=="ArrayExpression")return{items:[],diagnostics:[{severity:"fatal",path:"NAV_ITEMS",message:"missing top-level NAV_ITEMS array literal"}]};let o=[];return Br(r.elements).forEach((i,s)=>{let a=Lp(i,`NAV_ITEMS[${s}]`,t);a&&o.push(a)}),{items:o,diagnostics:t}}function Lp(e,t,n){if(e?.type!=="ObjectExpression")return n.push({severity:"fatal",path:t,message:"nav item must be an object literal"}),null;let r={};for(let l of Br(e.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=pk(l.key);u&&(r[u]=l.value)}let o=Lr(r.label),i=Lr(r.targetType);if(!o)return n.push({severity:"fatal",path:`${t}.label`,message:"label must be a static string"}),null;if(!i||!Op.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${Op.join("/")}`}),null;r.group!==void 0&&n.push({severity:"warning",code:"leaf-group-field",path:`${t}.group`,message:'unsupported leaf group field ignored; use a canonical targetType: "group" node with children'});let s={label:o,targetType:i};for(let l of Dp){if(r[l]===void 0)continue;let u=Lr(r[l]);u!==void 0?s[l]=u:n.push({severity:"warning",path:`${t}.${l}`,message:`${l} ignored: not a static string`})}r.icon!==void 0&&n.push({severity:"warning",path:`${t}.icon`,message:"icon component ref ignored; use static iconKey"});for(let l of Object.keys(r))fk.has(l)||l==="group"||l==="icon"||n.push({severity:"warning",code:"unknown-field",path:`${t}.${l}`,message:`unsupported field \`${l}\` ignored; NAV_ITEMS only carries ${lc.join("/")}`});if(r.children!==void 0){if(r.children.type!=="ArrayExpression")return n.push({severity:"fatal",path:`${t}.children`,message:"children must be a static array"}),null;let l=[];Br(r.children.elements).forEach((u,d)=>{let p=Lp(u,`${t}.children[${d}]`,n);p&&l.push(p)}),s.children=l}if(i==="group")return s.children?s:(n.push({severity:"fatal",path:`${t}.children`,message:"group item requires children"}),null);let a=Lr(r.href);if(!a)return n.push({severity:"fatal",path:`${t}.href`,message:"href must be a static string for non-group item"}),null;s.href=a;let c=Lr(r.role);if(c!==void 0&&(dk.includes(c)?s.role=c:n.push({severity:"warning",path:`${t}.role`,message:"role ignored: not link/cta"})),r.openInNewTab!==void 0){let l=Mp(r.openInNewTab);l!==void 0?s.openInNewTab=l:n.push({severity:"warning",path:`${t}.openInNewTab`,message:"openInNewTab ignored: not a static boolean"})}if(r.nofollow!==void 0){let l=Mp(r.nofollow);l!==void 0?s.nofollow=l:n.push({severity:"warning",path:`${t}.nofollow`,message:"nofollow ignored: not a static boolean"})}return s}import{parse as mk}from"@babel/parser";function jr(e){return Array.isArray(e)?e:[]}function Bp(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function dc(e,t){let n=jp(t);if(!n)return{status:"unsupported",source:e};let r;try{r=mk(e,{sourceType:"module",plugins:["typescript","jsx"],tokens:!0})}catch{return{status:"unsupported",source:e}}let o=[];for(let u of jr(r.program.body)){let d=u.type==="ExportNamedDeclaration"?u.declaration:u;if(d?.type==="VariableDeclaration")for(let p of jr(d.declarations)){let m=p.id;m?.type==="Identifier"&&m.name==="NAV_ITEMS"&&o.push(p)}}if(o.length===0)return{status:"navigation_not_found",source:e};if(o.length!==1)return{status:"unsupported",source:e};let i=Bp(o[0]?.init);if(!i)return{status:"unsupported",source:e};if(uc(e).diagnostics.some(({severity:u})=>u==="fatal"))return{status:"unsupported",source:e};let a=[],c=u=>{let d=jr(u.elements);for(let[p,m]of d.entries()){if(hk(m,n)){let b=d[p+1],C=d[p-1],I=m.start,w=m.end;if(typeof I!="number"||typeof w!="number")continue;b&&typeof b.start=="number"?a.push({start:I,end:b.start}):C&&typeof C.end=="number"?a.push({start:C.end,end:w}):a.push({start:I,end:w});continue}let g=gk(m);g&&c(g)}};if(c(i),a.length===0)return{status:"not_found",source:e};let l=e;for(let u of a.sort((d,p)=>p.start-d.start))l=l.slice(0,u.start)+l.slice(u.end);return{status:"removed",source:l,removedCount:a.length}}function gk(e){if(e.type==="ObjectExpression")for(let t of jr(e.properties)){if(t.type!=="ObjectProperty")continue;let n=t.key;if((n?.name??n?.value)==="children")return Bp(t.value)}}function jp(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function hk(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of jr(e.properties)){if(o.type!=="ObjectProperty")continue;let i=o.key,s=o.value,a=i?.name??i?.value;s?.type==="StringLiteral"&&(a==="href"&&(n=String(s.value)),a==="targetType"&&(r=String(s.value)))}return r==="page"&&jp(n??"")===t}import A_ from"node:fs";import __ from"node:path";var yk=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function $r(e){let t=e.map(r=>Rk(r.path)),n=xk(t);return n?t.filter(r=>Sk(n,r)).map(r=>({routeId:Ek(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function xi(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=Ck(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function xk(e){return e.some(r=>r.startsWith("app/")&&!bk(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function bk(e){return e.startsWith("app/_vcp/")||e.startsWith("src/app/_vcp/")}function Sk(e,t){if(!t.startsWith(`${e}/`))return!1;let n=t.slice(t.lastIndexOf("/")+1);return yk.test(n)?t.slice(e.length+1,-n.length-1).split("/").filter(Boolean).every(r=>!r.startsWith("_")):!1}function Ek(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(Ik).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function vk(e){return e.startsWith("(")&&e.endsWith(")")}function Ik(e){return!e||e.startsWith("@")||e.startsWith("_")||vk(e)?null:kk(e)}function kk(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function Ck(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function Rk(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var Nk="components/site/generated/",Vr=[".tsx",".ts",".jsx",".js"];function $p(e){if(e.expectedUrlPath===wk)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set($r(Object.keys(e.files).map(p=>({path:p}))).map(p=>p.entryFile)),n=Object.entries(e.files).filter(([p,m])=>{let g=p.replace(/\\/g,"/");if(!t.has(g))return!1;let b=cc(m,g);return b.found&&b.seo?.path===e.expectedUrlPath});if(n.length===0)return{ok:!1,code:"ROUTE_NOT_FOUND",message:"No route uniquely matches the requested page identity."};if(n.length>1)return{ok:!1,code:"ROUTE_AMBIGUOUS",message:"Multiple routes match the requested page identity."};let[r]=n[0],o=Pk(e.files);if(!o.ok)return o.error;let i=o.graph,s=Fk(r,i),a=Ok(r,s,i),c=[...s].filter(p=>!a.has(p)).sort((p,m)=>p.localeCompare(m)),l=[{operation:"delete",file:r},...[...a].sort((p,m)=>p.localeCompare(m)).map(p=>({operation:"delete",file:p}))],u=[],d=[];for(let[p,m]of Object.entries(e.files))if(p!==r){if(m.includes("NAV_ITEMS")){let g=dc(m,e.expectedUrlPath);g.status==="removed"?(l.push({operation:"upsert",file:p,content:g.source}),u.push(p)):g.status==="unsupported"&&d.push(`unsupported_navigation:${p}`)}m.includes(e.expectedUrlPath)&&!m.includes("NAV_ITEMS")&&d.push(`preserved_link:${p}`)}return{ok:!0,edits:l,deletedFiles:[r,...[...a].sort((p,m)=>p.localeCompare(m))],updatedFiles:u,preservedSharedFiles:c,warnings:d}}function Pk(e){let t=new Set(Object.keys(e)),n=new Map;for(let[r,o]of Object.entries(e)){let i=r.replace(/\\/g,"/");if(i==="next-env.d.ts"||i.endsWith("/next-env.d.ts")||!Ak(r))continue;let s=nr(r,o);if(!s.ok)return{ok:!1,error:{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:`Page source dependencies could not be proven safe: ${r} (parse-failed).`}};let a=new Set;for(let{specifier:c}of s.module.imports){if(Tk(c))continue;let l=tr(r,c),u=_k(l,t);if(!u)return{ok:!1,error:{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:`Page source dependencies could not be proven safe: ${r} -> ${c} (import-not-found).`}};a.add(u)}n.set(r,a)}return{ok:!0,graph:n}}function Ak(e){let t=e.toLowerCase();return Vr.some(n=>t.endsWith(n))}function Tk(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!Vr.some(n=>e.endsWith(n)))}function _k(e,t){let n=e.replace(/\\/g,"/");return(Vr.some(o=>n.endsWith(o))?[n]:[...Vr.map(o=>`${n}${o}`),...Vr.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function Fk(e,t){let n=new Set,r=[...t.get(e)??[]];for(;r.length>0;){let o=r.pop();!o.startsWith(Nk)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function Ok(e,t,n){let r=new Set(t),o=!0;for(;o;){o=!1;for(let i of[...r])[...n].some(([a,c])=>a!==e&&!r.has(a)&&c.has(i))&&(r.delete(i),o=!0)}return r}import{SiteEditHistoryProvenanceSchema as Mk}from"@vcp-dev/contracts";var Dk={affectedCompositions:[]};function zp(e){let t=null,n=new WeakMap;async function r(){return t??=Lk(e),t}return{async prepareAppend(o){let i=await e.readIndex(),s=await e.stageAppend(Jp(o),{durableManifest:!1}),a;try{a=await e.previewStagedAppend(s.entryId,i.digest)}catch(l){throw await e.discardStage(s.stageId),l}let c={kind:"append",entry:o,historyTransition:a};return n.set(c,{expectedDigest:i.digest,stageId:s.stageId,entryId:s.entryId}),c},async prepareUndo(){let i=(await r()).undo.at(-1);if(!i?.historyId)return null;let s=await e.readIndex(),a=s.entryIds.indexOf(i.historyId);if(a<0)throw new Error("undo entry is missing from index");let c=a-1,l=await e.previewCursor(c,s.digest),u={kind:"undo",entry:i,historyTransition:l};return n.set(u,{expectedDigest:s.digest,cursor:c}),u},async prepareRedo(){let i=(await r()).redo.at(-1);if(!i?.historyId)return null;let s=await e.readIndex(),a=s.entryIds.indexOf(i.historyId);if(a<0)throw new Error("redo entry is missing from index");let c=a,l=await e.previewCursor(c,s.digest),u={kind:"redo",entry:i,historyTransition:l};return n.set(u,{expectedDigest:s.digest,cursor:c}),u},async publishPrepared(o){let i=n.get(o);if(!i)throw new Error("history mutation was not prepared");let s=await r();if(o.kind==="append"){if(!i.entryId)throw new Error("staged entry id is missing");let a=await e.publishStagedAppend(i.entryId,i.expectedDigest,i.stageId);Vp(a,o.historyTransition),o.entry.historyId=i.entryId,s.entryIds=[...a.entryIds],s.cursor=a.cursor,s.undo.push(o.entry),s.redo.length=0}else{if(i.cursor===void 0)throw new Error("prepared cursor is missing");let a=await e.setCursor(i.cursor,i.expectedDigest);if(Vp(a,o.historyTransition),o.kind==="undo"){if(s.undo.at(-1)!==o.entry)throw new Error("undo state changed before publish");s.undo.pop(),s.redo.push(o.entry)}else{if(s.redo.at(-1)!==o.entry)throw new Error("redo state changed before publish");s.redo.pop(),s.undo.push(o.entry)}s.cursor=i.cursor}n.delete(o)},async discardPrepared(o){let i=n.get(o);if(!i)return;let s=o.historyTransition;if(s){let a=await e.readIndex();if(a.digest===s.publishedIndexDigest&&a.cursor===s.publishedCursor&&a.currentId===s.publishedCurrentId)throw new Error("cannot discard a history mutation whose index was published")}i.stageId&&await e.discardStage(i.stageId),n.delete(o)},async peekUndo(){return(await r()).undo.at(-1)??null},async pushUndo(o){let i=await r(),s=o;if(s.historyId){let l=i.entryIds.indexOf(s.historyId);if(l>=0)try{await e.setCursor(l),i.undo.push(o),i.cursor=l;return}catch(u){throw i.redo.push(o),u}}let a=await e.append(Jp(o)),c=a.currentId;if(!c)throw new Error("history store did not publish an entry");o.historyId=c,i.entryIds=[...a.entryIds],i.cursor=a.cursor,i.undo.push(o),i.redo.length=0},async popUndo(){return(await r()).undo.pop()??null},async peekRedo(){return(await r()).redo.at(-1)??null},async pushRedo(o){let i=await r(),s=o;if(!s.historyId)throw i.undo.push(o),new Error("cannot move an unpersisted history entry to redo");let a=i.entryIds.indexOf(s.historyId);if(a<0)throw i.undo.push(o),new Error("history entry is missing from the durable index");try{await e.setCursor(a-1),i.cursor=a-1,i.redo.push(o)}catch(c){throw i.undo.push(o),c}},async popRedo(){return(await r()).redo.pop()??null},async clearRedo(){(await r()).redo.length=0},async getStatus(){let o=await e.readStatus();return{canUndo:o.canUndo,canRedo:o.canRedo,undoDepth:o.undoDepth,redoDepth:o.redoDepth,recoveryRequired:o.recoveryRequired}},async markRecoveryRequired(o){await e.markRecoveryRequired(o)}}}function Vp(e,t){if(!t)throw new Error("durable history transition is missing");if(e.digest!==t.publishedIndexDigest||e.cursor!==t.publishedCursor||e.currentId!==t.publishedCurrentId)throw new Error("durable history published an unexpected index state")}async function Lk(e){let t=await e.readIndex(),n=await Promise.all(t.undoIds.map(async o=>Up(e,o))),r=await Promise.all(t.redoIds.map(async o=>Up(e,o)));return{undo:n.reverse(),redo:r.reverse(),entryIds:[...t.entryIds],cursor:t.cursor}}async function Up(e,t){let n=await e.readEntry(t),r=Bk(n),o=r.provenance??Dk;return{historyId:t,...o.initiatingComposition?{composition:o.initiatingComposition}:{},operationId:r.operationId,kind:r.kind,target:r.target,provenance:o,...r.selectionRef?{selectionRef:r.selectionRef}:{},...r.output?{output:r.output}:{},preSnapshots:await Kp(e,n,r.preSnapshots),postSnapshots:await Kp(e,n,r.postSnapshots)}}async function Kp(e,t,n){let r=new Map(t.blobs.map(o=>[o.name,o.digest]));return Promise.all(n.map(async o=>{let i=o.exists&&o.blobName?Buffer.from(await e.readBlob(Vk(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function Jp(e){let t=[],n=(i,s)=>i.map((a,c)=>{let l={file:a.file,exists:a.exists!==!1,version:a.version,...a.sha256?{sha256:a.sha256}:{}};if(l.exists){let u=`${s}-${c}`;l.blobName=u,t.push({name:u,data:a.content})}return l}),r=jk(e),o={operationId:e.operationId,kind:e.kind,target:e.target,...r?{provenance:r}:{},...e.selectionRef?{selectionRef:e.selectionRef}:{},...e.output?{output:e.output}:{},preSnapshots:n(e.preSnapshots,"pre"),postSnapshots:n(e.postSnapshots,"post")};return{kind:"site-edit-operation",manifest:JSON.parse(JSON.stringify(o)),blobs:t}}function Bk(e){if(!Hp(e.manifest))throw new Error("durable history manifest is not an object");let t=e.manifest,n=new Set(["operationId","kind","target","selectionRef","output","provenance","preSnapshots","postSnapshots"]);if(Object.keys(t).some(r=>!n.has(r)))throw new Error("durable history manifest contains unknown fields");if(typeof t.operationId!="string"||t.operationId.length===0||typeof t.kind!="string"||t.kind.length===0||!Array.isArray(t.preSnapshots)||!Array.isArray(t.postSnapshots))throw new Error("durable history manifest has an invalid shape");return{operationId:t.operationId,kind:t.kind,target:t.target,...t.selectionRef!==void 0?{selectionRef:t.selectionRef}:{},...t.output!==void 0?{output:t.output}:{},...t.provenance!==void 0?{provenance:Wp(t.provenance)}:{},preSnapshots:Xp(t.preSnapshots,"preSnapshots"),postSnapshots:Xp(t.postSnapshots,"postSnapshots")}}function jk(e){if(e.provenance!==void 0)return Wp(e.provenance);if(e.composition)return{initiatingComposition:e.composition,affectedCompositions:[]}}function Wp(e){let t=Mk.safeParse(e);if(!t.success)throw new Error("durable history provenance is invalid");return{...t.data.initiatingComposition?{initiatingComposition:t.data.initiatingComposition}:{},affectedCompositions:t.data.affectedCompositions.map(n=>({routeId:n.routeId,...n.effectiveTemplateId?{effectiveTemplateId:n.effectiveTemplateId}:{}}))}}function Xp(e,t){return e.map((n,r)=>{if(!Hp(n))throw new Error(`durable history ${t}[${r}] is invalid`);if(typeof n.file!="string"||n.file.length===0||!Number.isInteger(n.version)||n.exists!==void 0&&typeof n.exists!="boolean"||n.sha256!==void 0&&!$k(n.sha256)||n.blobName!==void 0&&typeof n.blobName!="string")throw new Error(`durable history ${t}[${r}] is invalid`);return{file:n.file,exists:n.exists!==!1,version:n.version,...n.sha256?{sha256:n.sha256}:{},...n.blobName?{blobName:n.blobName}:{}}})}function $k(e){return/^sha256:[0-9a-f]{64}$/.test(e)}function Vk(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function Hp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import Gp from"node:path";function pc(){let e=Promise.resolve();return{async runExclusive(t){let n,r=new Promise(i=>{n=i}),o=e;e=o.then(()=>r,()=>r),await o;try{return await t()}finally{n()}}}}async function Zp(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=Xk(i.path);if(!s.ok)return s;let a=s.path;if(o.has(a))return{ok:!1,code:"duplicate-target",path:a,reason:`Duplicate file target: ${a}`};if(o.add(a),i.kind==="create-only"){let c=t.has(a),l=n?await n(a):!1;if(c||l)return{ok:!1,code:"create-only-exists",path:a,reason:`Create-only file already exists: ${a}`}}r.push({...i,path:a})}return{ok:!0,plan:{operationId:e.operationId,intents:r}}}async function bi(e){let t=()=>Uk(e);return e.mutex?e.mutex.runExclusive(t):t()}async function Uk(e){let t=await Zp(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=Kk(e.overlay,t.plan),r;try{r=await e.buildCandidate({overlay:n,plan:t.plan})}catch(l){return{ok:!1,stage:"build",reason:"Candidate build failed.",error:l,recoveryRequired:!1}}let o,i;try{o=await e.prepareHistory?.({candidate:r,plan:t.plan}),await e.reverify?.({candidate:r,plan:t.plan,history:o}),i=await e.writeCandidate({candidate:r,plan:t.plan}),await e.markCandidateWritten?.({candidate:r,plan:t.plan,history:o,receipt:i})}catch(l){return fc({candidate:r,plan:t.plan,failedStage:"commit",error:l,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let s=r;try{let l=await e.validateCandidate({candidate:r,plan:t.plan,receipt:i});l!==void 0&&(s=l)}catch(l){return fc({candidate:r,plan:t.plan,failedStage:"validate",error:l,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let a;try{a=await e.publishCandidate({candidate:s,plan:t.plan,history:o,receipt:i})}catch(l){return fc({candidate:s,plan:t.plan,failedStage:"publish",error:l,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let c={candidate:s,plan:t.plan,history:o,receipt:i,published:a};try{await e.swapCandidate?.(c)}catch(l){return Yp("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return Yp("finalize",l,"Transaction finalization failed after live state swap.")}try{e.emitCommitted?.({candidate:s,plan:t.plan,published:a})}catch{}return{ok:!0,stage:"publish",published:a,plan:t.plan}}function Kk(e,t){let n=new Map(e);for(let r of t.intents)r.kind==="delete"?n.delete(r.path):n.set(r.path,r.content);return n}function fc(e){return e.rollbackCandidate({candidate:e.candidate,plan:e.plan,failedStage:e.failedStage,error:e.error,...e.history===void 0?{}:{history:e.history},...e.receipt===void 0?{}:{receipt:e.receipt}}).then(()=>({ok:!1,stage:e.failedStage,reason:Jk(e.failedStage),error:e.error,recoveryRequired:!1})).catch(t=>({ok:!1,stage:"rollback",reason:"Rollback failed after candidate commit/validation/publish failure.",error:t,recoveryRequired:!0,cause:e.error}))}function Yp(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function Jk(e){switch(e){case"commit":return"Candidate write or commit verification failed.";case"validate":return"Candidate validation failed.";case"publish":return"Candidate publish failed."}}function Xk(e){if(e.length===0)return{ok:!1,code:"unsafe-path",path:e,reason:"File path must not be empty."};if(e.includes("\0")||e.includes("\\"))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};if(/^[a-zA-Z]:/.test(e)||Gp.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=Gp.posix.normalize(e);return t==="."||t===".."||t.startsWith("../")||t.includes("/../")?{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`}:t.startsWith("./")||t.includes("/./")?{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`}:{ok:!0,path:t}}function mc(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function Gn(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function Qp(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function gc(e,t,n,r){if(!e.has(t)&&e.size>=r){let o=e.keys().next().value;o&&e.delete(o)}e.set(t,n)}function qp(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function zk(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var Ur=class extends Error{constructor(t){let n=t.map(qp);super(zk(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function em(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof Ur?{routeId:e,message:n,diagnostics:t.diagnostics.map(qp)}:{routeId:e,message:n}}function hc(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function tm(e){let{journal:t,index:n,observedFileDigests:r}=e;if(r.length!==t.files.length)return"ambiguous";let o=t.files.every((l,u)=>l.preDigest===r[u]),i=t.files.every((l,u)=>l.postDigest===r[u]),s=t.historyTransition,a=n.digest===s.expectedIndexDigest,c=n.digest===s.publishedIndexDigest&&n.cursor===s.publishedCursor&&n.currentId===s.publishedCurrentId;return o&&a?"safely-uncommitted":i&&c?"durably-committed":"ambiguous"}import{computeSiteEditCompositionKey as Si,SiteEditCompositionContextSchema as Wk,SiteEditCompositionSelectorSchema as Hk}from"@vcp-dev/contracts";var Me=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="SiteEditCompositionError"}};function nm(e,t){throw new Me("INVALID_COMPOSITION",e,{value:t})}function Ei(e){let t=Wk.safeParse(e);return t.success?t.data:nm("Invalid SiteEditCompositionContext.",e)}function rm(e){let t=[],n=new Map,r=new Map;for(let l of e.compositions){let u=Ei(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new Me("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=Si(u);if(n.has(d))throw new Me("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u});let p=r.get(l.entryFile);if(p)throw new Me("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:p});let m={context:u,entryFile:l.entryFile,key:d};t.push(m),n.set(d,m),r.set(l.entryFile,d)}if(t.length===0)throw new Me("INVALID_COMPOSITION","At least one composition must be registered.");let o=new Map;for(let l of e.initialDocumentVersions??[]){let u=Ei(l?.composition);if(!Number.isInteger(l?.version)||(l?.version??-1)<0)throw new Me("INVALID_INITIAL_DOCUMENT_VERSION","Initial document version must be a non-negative integer.",{context:u,version:l?.version});let d=Si(u);if(!n.has(d))throw new Me("UNKNOWN_COMPOSITION","Initial document version references an unregistered composition.",{context:u,key:d});if(o.has(d))throw new Me("DUPLICATE_COMPOSITION","Initial document versions must contain each composition at most once.",{context:u,key:d});o.set(d,l.version)}function i(l){let u=Hk.safeParse(l);if(!u.success)return nm("Invalid SiteEditCompositionSelector.",l);let d=t.filter(({context:p})=>p.routeId===u.data.routeId&&(u.data.templateId===void 0?p.effectiveTemplateId===void 0:p.effectiveTemplateId===u.data.templateId));if(d.length===1)return d[0];throw d.length>1?new Me("AMBIGUOUS_COMPOSITION","The composition selector matches multiple registered contexts.",{selector:u.data}):new Me("UNKNOWN_COMPOSITION","The composition selector is not registered.",{selector:u.data})}function s(l){let u=Ei(l),d=Si(u),p=n.get(d);if(!p)throw new Me("UNKNOWN_COMPOSITION","The composition context is not registered.",{context:u,key:d});return p}function a(l){let u=Ei(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new Me("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=Si(u),p=n.get(d);if(p){if(p.entryFile===l.entryFile)return p;throw new Me("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u})}let m=[...n.values()].find(b=>b.entryFile===l.entryFile);if(m)throw new Me("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:m.context});let g={context:u,entryFile:l.entryFile,key:d};return t.push(g),n.set(d,g),g}function c(l){let u=n.get(l);if(!u)return;n.delete(l);let d=t.findIndex(p=>p.key===l);return d>=0&&t.splice(d,1),o.delete(l),u}return{entries:t,byKey:n,initialVersions:o,register:a,unregister:c,resolveSelector:i,resolveContext:s,getByKey:l=>n.get(l),routeIds:()=>[...new Set(t.map(({context:l})=>l.routeId))]}}var nC=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,rC=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],om=32,im=256;function oC(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var sm={maxEntries:50,maxBytes:8*1024*1024};function iC(){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 ui(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 sC(){let e=[],t=[];return{prepareAppend(r){return{kind:"append",entry:r}},prepareUndo(){let r=e.at(-1);return r?{kind:"undo",entry:r}:null},prepareRedo(){let r=t.at(-1);return r?{kind:"redo",entry:r}:null},publishPrepared(r){if(r.kind==="append"){e.push(r.entry),n(),t.length=0;return}if(r.kind==="undo"){if(e.at(-1)!==r.entry)throw new Error("undo history changed before publish");e.pop(),t.push(r.entry);return}if(t.at(-1)!==r.entry)throw new Error("redo history changed before publish");t.pop(),e.push(r.entry),n()},peekUndo(){return e.at(-1)??null},pushUndo(r){e.push(r),n(),t.length=0},popUndo(){return e.pop()??null},peekRedo(){return t.at(-1)??null},pushRedo(r){t.push(r)},popRedo(){return t.pop()??null},clearRedo(){t.length=0},getStatus(){return{canUndo:e.length>0,canRedo:t.length>0,undoDepth:e.length,redoDepth:t.length,recoveryRequired:!1}}};function n(){for(;e.length>sm.maxEntries||aC(e)>sm.maxBytes;)e.shift()}}function aC(e){return e.reduce((t,n)=>t+cC(n),0)}function cC(e){return am(e.preSnapshots)+am(e.postSnapshots)+lC(e.provenance)}function lC(e){return e?new TextEncoder().encode(JSON.stringify(e)).byteLength:0}function am(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function cm(e,t){return{key:Gk(e),composition:e,routeId:e.routeId,entryFile:t,graph:null,topology:null,capabilities:null,document:null,pageComposition:null,pageCompositionProjection:null,documentIndex:null,pagePlacementByKey:null,pagePlacementUnitByKey:null,pageUnitByKey:null,pagePlacementsByUnitKey:null,dependencyFiles:new Set([t]),detailProjections:null,fileVersions:new Map,styleContext:null}}function uC(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=Ve(o.key)??o.key;if(i===o.key)continue;let s=n.get(i)??0;r.set(o.key,s),n.set(i,s+1)}return{entriesByKey:t,repeatOccurrenceIndexByKey:r}}var ki=class extends Error{constructor(t){super(t.reason),this.result=t}},Sn=class extends Error{constructor(t){super(hc(t)),this.failedRoutes=t}};function lm(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=Ve(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(Ve(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}function dC(e,t,n){if(!n)return;let r=Ve(n.key)??n.key;if(n.key!==e&&n.key!==t&&r!==t)throw new Error(`Selection reference '${n.key}' does not match selected key '${e}'`);if(n.instanceIndex!==void 0&&(!Number.isInteger(n.instanceIndex)||n.instanceIndex<0))throw new Error("Selection reference instanceIndex must be non-negative");if(n.instanceCount!==void 0&&(!Number.isInteger(n.instanceCount)||n.instanceCount<=0))throw new Error("Selection reference instanceCount must be positive");if(n.instanceIndex!==void 0&&n.instanceCount!==void 0&&n.instanceIndex>=n.instanceCount)throw new Error("Selection reference instanceIndex must be smaller than instanceCount");return{...n,key:t}}var fC=/\.(?:[cm]?[jt]sx?)$/i,pC=/\.json$/i,mC=/\.(?:css|scss|sass)$/i,gC=/\.mdx$/i,hC=/\.ya?ml$/i;function yC(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 xC(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function bC(e,t){let n=new Map;for(let r of t)n.set(r.path,r.operation==="delete"?{exists:!1}:{exists:!0,content:r.content});return{async readFile(r){let o=n.get(r);if(o){if(!o.exists)throw new Error(`Source file not found: ${r}`);return o.content}return e.readFile(r)},async writeFile(){throw new Error("Source edit preflight overlay is read-only.")},async deleteFile(){throw new Error("Source edit preflight overlay is read-only.")},async exists(r){let o=n.get(r);return o?o.exists:e.exists(r)},async getFileInfo(r){let o=n.get(r);return o?o.exists?{path:r,sizeBytes:Buffer.byteLength(o.content,"utf8")}:null:e.getFileInfo?.(r)??null},async listFiles(r={}){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let o=gm(await e.listFiles(r)),i=new Map(o.files.map(a=>[a.path,a]));for(let[a,c]of n)if(SC(a,r.roots??[])){if(!c.exists){i.delete(a);continue}i.set(a,{path:a,sizeBytes:Buffer.byteLength(c.content,"utf8")})}let s=[...i.values()].sort((a,c)=>a.path.localeCompare(c.path));return o.truncated?{files:s,truncated:o.truncated}:s},getVersion(r){return e.getVersion(r)},bumpVersion(r){return e.getVersion(r)}}}function SC(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function gm(e){return Array.isArray(e)?{files:e}:e}function EC(e){if(!Qk(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!==eC||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=Zk(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(fC.test(e.path)){let t=yt({source:e.content,profile:on({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(pC.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${Be(t)}`,details:{path:e.path}}}if(mC.test(e.path)){let t=um({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(gC.test(e.path)){let t=um({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(hC.test(e.path))try{tC(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${Be(t)}`,details:{path:e.path}}}return{ok:!0}}function um({content:e,path:t,profile:n}){let r=[],o=null,i=!1,s=!1,a=!1,c=!1,l=!0;for(let d=0;d<e.length;d+=1){let p=e[d]??"",m=e[d+1]??"";if(n==="mdx"&&l&&e.startsWith("```",d)){c=!c;let g=e.indexOf(`
1
+ import{SiteEditOperationRequestSchema as mR,SiteEditPatchPlanSchema as gR}from"@vcp-dev/contracts";function tn(e){return{requestId:e.requestId,kind:e.kind,composition:e.composition,target:e.target,resultVersion:e.resultVersion,affectedFiles:e.affectedFiles,...e.output?{output:e.output}:{},...e.selectionRef?{selectionRef:e.selectionRef}:{}}}function no(e,t){let n=t[0]??"Site edit operation request failed contract validation.";return{ok:!1,composition:{routeId:e.composition.routeId,...e.composition.templateId!==void 0?{effectiveTemplateId:e.composition.templateId}:{}},error:{code:"INVALID_PARAMS",message:n},data:{requestId:e.id,kind:e.kind,composition:{routeId:e.composition.routeId,...e.composition.templateId!==void 0?{effectiveTemplateId:e.composition.templateId}:{}},target:e.target,resultVersion:e.documentVersion}}}function ro(e,t){if(!e.pageComposition)throw new Error("RenderDocument is missing the required Page Composition projection.");return{siteId:t.siteId,snapshotId:t.snapshotId,composition:e.composition,version:e.version,entries:e.entries.map(n=>({key:n.key,...n.pageCompositionUnitKey?{pageCompositionUnitKey:n.pageCompositionUnitKey}:{},operationSummary:{canUpdateText:n.operationSummary.canUpdateText,canInsertChild:n.operationSummary.canInsertChild,canMove:n.operationSummary.canMove,canRemove:n.operationSummary.canRemove},...n.dynamicDataSummary?{dynamicDataSummary:n.dynamicDataSummary}:{}})),pageComposition:e.pageComposition.status==="unsupported"?{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics}:{status:"supported",containerKey:e.pageComposition.container.key,hasBusinessMembers:e.pageComposition.businessMembers.length>0,placementUnitKeys:e.pageComposition.placementUnits.map(n=>n.key),placements:e.pageComposition.placements.map(n=>({placementKey:n.placementKey,placementUnitKey:n.placementUnitKey,relation:n.relation}))}}}function oo(e){return{composition:e.composition,key:e.key,tag:e.tag,label:e.label,sourceLocator:e.sourceLocator,isOpaque:e.isOpaque,ancestors:e.ancestors,componentName:e.componentName,sourceFile:e.sourceFile,capabilities:bg(e.capabilities),provenanceChain:e.provenanceChain?{editMode:e.provenanceChain.editMode,diagnostics:e.provenanceChain.diagnostics}:void 0,dynamicData:e.dynamicData,...e.properties?{properties:e.properties}:{},textSegments:e.textSegments.map(t=>({index:t.index,editable:t.editable,sourceKind:t.source?.kind??null})),boundaryKind:e.boundaryKind}}function io(e,t){let n=new Date().toISOString();return e.type==="document-changed"?{type:"site-edit.document.changed",siteId:t.siteId,snapshotId:t.snapshotId,composition:e.composition,version:e.version,at:n}:e.type==="operation-completed"?{type:"site-edit.operation.completed",siteId:t.siteId,composition:e.composition,result:tn(e.result),at:n}:e.type==="operation-failed"?{type:"site-edit.operation.failed",siteId:t.siteId,requestId:e.requestId,composition:e.composition,error:e.error,at:n}:e.type==="capability-changed"?{type:"site-edit.capability.changed",siteId:t.siteId,composition:e.composition,keys:e.keys,at:n}:e.type==="graph-invalidated"?{type:"site-edit.graph.invalidated",siteId:t.siteId,composition:e.composition,at:n}:e.type==="graph-ready"?{type:"site-edit.graph.ready",siteId:t.siteId,composition:e.composition,version:e.version,at:n}:e.type==="graph-error"?{type:"site-edit.graph.error",siteId:t.siteId,composition:e.composition,message:e.message,at:n}:null}function bg(e){return{composition:e.composition,key:e.key,canUpdateText:e.canUpdateText,canInsertChild:e.canInsertChild,canMove:e.canMove,canRemove:e.canRemove,editModes:e.editModes?{updateText:e.editModes.updateText?{mode:e.editModes.updateText.mode,reasonCode:e.editModes.updateText.reasonCode}:void 0,insertChild:e.editModes.insertChild?{mode:e.editModes.insertChild.mode,reasonCode:e.editModes.insertChild.reasonCode}:void 0,move:e.editModes.move?{mode:e.editModes.move.mode,reasonCode:e.editModes.move.reasonCode}:void 0,remove:e.editModes.remove?{mode:e.editModes.remove.mode,reasonCode:e.editModes.remove.reasonCode}:void 0}:void 0,constraints:e.constraints}}import{computeSiteEditCompositionKey as qk,composeSiteEditRepeatInstanceKey as eC,getSiteEditSourceDeleteProtectionReason as tC,isSiteEditTextSourcePath as nC,parseSiteEditRepeatInstanceKey as rC,SITE_EDIT_SOURCE_DELETE_CAPABILITY as oC,stripSiteEditRepeatInstanceKeys as Ve}from"@vcp-dev/contracts";import{parse as iC}from"yaml";import Ei from"node:path";function Zn(e,t,n){return`${e}::${t}::${n}`}var D={NODE_NOT_FOUND:"NODE_NOT_FOUND",HOME_PAGE_LOCKED:"HOME_PAGE_LOCKED",ROUTE_NOT_FOUND:"ROUTE_NOT_FOUND",CAPABILITY_REJECTED:"CAPABILITY_REJECTED",CONSTRAINT_VIOLATED:"CONSTRAINT_VIOLATED",INVALID_PARAMS:"INVALID_PARAMS",PLAN_FAILED:"PLAN_FAILED",TRANSACTION_PREFLIGHT_FAILED:"TRANSACTION_PREFLIGHT_FAILED",ROUTE_REBUILD_FAILED:"ROUTE_REBUILD_FAILED",HISTORY_COMMIT_FAILED:"HISTORY_COMMIT_FAILED",MATERIALIZATION_CONFLICT:"MATERIALIZATION_CONFLICT",MATERIALIZATION_REJECTED:"MATERIALIZATION_REJECTED",MUTATION_ASSERTION_REQUIRED:"MUTATION_ASSERTION_REQUIRED",MUTATION_ASSERTION_INVALID:"MUTATION_ASSERTION_INVALID",VERSION_STALE:"VERSION_STALE",AST_PARSE_ERROR:"AST_PARSE_ERROR",UNSUPPORTED_OPERATION:"UNSUPPORTED_OPERATION",LOCATOR_FAILED:"LOCATOR_FAILED",INVALID_TARGET:"INVALID_TARGET",WRITE_IO_ERROR:"WRITE_IO_ERROR",CONCURRENT_MODIFIED:"CONCURRENT_MODIFIED",ROLLBACK_FAILED:"ROLLBACK_FAILED",RECOVERY_REQUIRED:"RECOVERY_REQUIRED",RECOVERY_PERSIST_FAILED:"RECOVERY_PERSIST_FAILED",MUTATION_SESSION_REQUIRED:"MUTATION_SESSION_REQUIRED",LEASE_ASSERTION_INVALID:"LEASE_ASSERTION_INVALID",LEASE_ASSERTION_EXPIRED:"LEASE_ASSERTION_EXPIRED",LEASE_ASSERTION_SCOPE_MISMATCH:"LEASE_ASSERTION_SCOPE_MISMATCH",CROSS_PAGE_MOVE_UNSUPPORTED:"CROSS_PAGE_MOVE_UNSUPPORTED",INTERNAL_ERROR:"INTERNAL_ERROR"};import qi from"@babel/traverse";import*as x from"@babel/types";import*as q from"@babel/types";function ht(e,t={}){if(q.isTSAsExpression(e)||q.isTSSatisfiesExpression(e)||q.isTSNonNullExpression(e)||q.isTypeCastExpression(e)||q.isParenthesizedExpression(e))return ht(e.expression,t);if(q.isStringLiteral(e))return{status:"resolved",value:e.value};if(q.isNumericLiteral(e))return Number.isFinite(e.value)?{status:"resolved",value:e.value}:{status:"unresolved"};if(q.isBooleanLiteral(e))return{status:"resolved",value:e.value};if(q.isNullLiteral(e))return{status:"resolved",value:null};if(q.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?{status:"resolved",value:e.quasis[0].value.cooked??e.quasis[0].value.raw}:{status:"unresolved"};if(q.isIdentifier(e))return e.name==="undefined"&&!t.resolveIdentifier?{status:"undefined"}:t.resolveIdentifier?.(e.name)??{status:"unresolved"};if(q.isUnaryExpression(e)&&e.operator==="void"&&q.isNumericLiteral(e.argument)&&e.argument.value===0)return{status:"undefined"};if(q.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||q.isSpreadElement(r))return{status:"unresolved"};let o=ht(r,t);if(o.status!=="resolved")return{status:"unresolved"};n.push(o.value)}return{status:"resolved",value:n}}if(q.isObjectExpression(e)){let n=Object.create(null);for(let r of e.properties){if(!q.isObjectProperty(r)||r.computed||!q.isExpression(r.value))return{status:"unresolved"};let o=Sg(r.key);if(o===null)return{status:"unresolved"};let i=ht(r.value,t);if(i.status!=="resolved")return{status:"unresolved"};Object.defineProperty(n,o,{configurable:!0,enumerable:!0,value:i.value,writable:!0})}return{status:"resolved",value:n}}return q.isMemberExpression(e)||q.isOptionalMemberExpression(e)?t.resolveMember?.(e)??{status:"unresolved"}:{status:"unresolved"}}function Sg(e){return q.isIdentifier(e)?e.name:q.isStringLiteral(e)?e.value:q.isNumericLiteral(e)?String(e.value):null}import{createHash as wg}from"node:crypto";import*as fl from"@babel/parser";function nn(e,t,n,r){return{code:e,message:t,locatorKind:n,details:r}}function B(e,t,n,r,o){return{ok:!1,source:e,diagnostic:nn(t,n,r,o)}}function Wi(e,t,n,r,o){return{ok:!1,source:e,diagnostic:nn(t,n,r,o)}}var Eg={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function yt(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:fl.parse(t,{sourceType:"module",plugins:Eg[n]})}}catch(r){return{ok:!1,source:t,diagnostic:nn("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function Hi(e,t){return yt({source:e,profile:pl(t.kind)})}function Gi(e,t){return yt({source:e,profile:pl(t)})}function pl(e){return"next-app-entry"}function rn(e){let{filePath:t,source:n}=e,r=t.toLowerCase().split(".").pop()??"";return r==="tsx"?"tsx-module":r==="ts"?"ts-module":r==="jsx"||r==="js"||r===""&&/<\w[\s\S]*>/.test(n)?"tsx-module":"next-app-entry"}import*as vg from"@babel/parser";import*as Cn from"@babel/types";import*as Ot from"node:path";var Yi=[".tsx",".ts",".jsx",".js"],Ig=Yi.map(e=>`/index${e}`),kg=new Set(["json","css","scss","sass","less","svg","png","jpg","jpeg","gif","webp","avif","ico","bmp","woff","woff2","ttf","otf","eot","mp4","webm","mp3","wav","ogg","pdf","txt","md","csv","xml","yaml","yml"]);function ml(e){let t=e.replace(/[?#].*$/,""),n=/\.([a-z0-9]+)$/i.exec(t);return n!==null&&kg.has(n[1].toLowerCase())}function gl(e){let t=[];for(let n of e.program.body)Cn.isImportDeclaration(n)&&typeof n.source.value=="string"&&xt(n.source.value)&&t.push(n.source.value),Cn.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&xt(n.source.value)&&t.push(n.source.value),Cn.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&xt(n.source.value)&&t.push(n.source.value);return Zi(e.program,t),t}function Zi(e,t){if(!e||typeof e!="object")return;let n=e;if(n.type==="CallExpression"&&n.callee?.type==="Import"){let r=n.arguments?.[0];r?.type==="StringLiteral"&&typeof r.value=="string"&&xt(r.value)&&t.push(r.value)}for(let r of Object.values(n))if(Array.isArray(r))for(let o of r)Zi(o,t);else r&&typeof r=="object"&&Zi(r,t)}function xt(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function Qn(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 Cg(e,t){if(Yi.some(n=>e.endsWith(n))&&await t(e))return e;for(let n of Yi){let r=`${e}${n}`;if(await t(r))return r}for(let n of Ig){let r=`${e}${n}`;if(await t(r))return r}return null}async function Rn(e,t,n){let r=await so(e,t,n);return r.ok?r.path:null}async function so(e,t,n){let r=Qn(e,t);try{if(!Rg(e,t,r))return{ok:!1,diagnostic:{path:r,code:"import-not-found",message:`Local import not found: ${t}`,details:{fromFile:e,specifier:t}}};let o=await Cg(r,n);return o?{ok:!0,path:o}:{ok:!1,diagnostic:{path:r,code:"import-not-found",message:`Local import not found: ${t}`,details:{fromFile:e,specifier:t}}}}catch(o){return{ok:!1,diagnostic:{path:r,code:"import-resolve-failed",message:`Failed to resolve local import: ${t}`,details:{fromFile:e,specifier:t,reason:o instanceof Error?o.message:String(o)}}}}}function Rg(e,t,n){if(!xt(t)||t.includes("\0")||t.includes("\\")||Ot.posix.isAbsolute(n))return!1;let r=Ot.posix.normalize(n);if(r===".."||r.startsWith("../"))return!1;if(t.startsWith("@/")){let o=t.slice(2);return o.length>0&&!o.split("/").some(i=>i==="..")}return!Ot.posix.isAbsolute(e)}var qn=(e,t)=>{let n=yt({source:t,profile:rn({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${wg("sha256").update(t).digest("hex")}`,ast:n.ast,imports:gl(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};var ao="components/ui";function on(e){if(!e)return!1;let t=Qi(e);return t===ao||t.startsWith(`${ao}/`)||t.includes(`/${ao}/`)||t.endsWith(`/${ao}`)}function er(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?on(e.slice(2)):e.startsWith("./")||e.startsWith("../")?on(Qi(`${Ng(t)}/${e}`)):on(e):!1}function Qi(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 Ng(e){let t=Qi(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}var Pg=typeof qi=="function"?qi:qi.default;function _e(e){return{startLine:e.loc?.start.line??0,startColumn:e.loc?.start.column??0,endLine:e.loc?.end.line??0,endColumn:e.loc?.end.column??0}}function Ag(e){return/^[A-Z]/.test(e)}function os(e){let t=e.openingElement;return x.isJSXIdentifier(t.name)?t.name.name==="Fragment":x.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function Nn(e){return x.isJSXFragment(e)}function yl(e){return x.isJSXIdentifier(e.name)?e.name.name:x.isJSXMemberExpression(e.name)?xl(e.name):x.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function xl(e){return x.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:x.isJSXMemberExpression(e.object)?`${xl(e.object)}.${e.property.name}`:e.property.name}function Tg(e){return e.split(".")[0]??e}function Fg(e){let t=e;for(;t;){let n=t.node;if(x.isFunctionDeclaration(n)&&n.id||x.isVariableDeclarator(n)&&x.isIdentifier(n.id))return n.id.name;if(x.isExportDefaultDeclaration(n)){let r=n.declaration;if(x.isFunctionDeclaration(r)&&r.id)return r.id.name;if(x.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function _g(){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 Og(e){let t=new Map;for(let n of e.program.body){if(!x.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(x.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(x.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(x.isImportSpecifier(o)){let i=x.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function kt(e,t=[]){if(x.isIdentifier(e))return t.push(e.name),t;if(x.isObjectPattern(e)){for(let n of e.properties)x.isObjectProperty(n)?kt(n.value,t):x.isRestElement(n)&&kt(n.argument,t);return t}if(x.isArrayPattern(e)){for(let n of e.elements)n&&(x.isRestElement(n)?kt(n.argument,t):kt(n,t));return t}return x.isAssignmentPattern(e)?(kt(e.left,t),t):(x.isRestElement(e)&&kt(e.argument,t),t)}function it(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function tr(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 Mg(e,t,n){e.set(t,{resolved:!0,value:n})}function is(e,t){e.set(t,{resolved:!1})}function bl(e,t){let n=e;for(let r of t){if(r.kind==="property"){if(n==null||Array.isArray(n)||typeof n!="object"||!(r.name in n))return{kind:"known-empty"};n=n[r.name];continue}if(!Array.isArray(n)||r.index<0||r.index>=n.length)return{kind:"known-empty"};n=n[r.index]}return{kind:"resolved",value:n}}function Ne(e,t,n){if(x.isTSAsExpression(e)||x.isTSSatisfiesExpression(e)||x.isTSNonNullExpression(e)||x.isTypeCastExpression(e)||x.isParenthesizedExpression(e))return Ne(e.expression,t,n);if(x.isLogicalExpression(e))return co([Ne(e.left,t,n),Ne(e.right,t,n)]);if(x.isBinaryExpression(e))return co([x.isExpression(e.left)?Ne(e.left,t,n):null,x.isExpression(e.right)?Ne(e.right,t,n):null]);if(x.isConditionalExpression(e))return co([Ne(e.consequent,t,n),Ne(e.alternate,t,n)]);if(x.isTemplateLiteral(e))return co(e.expressions.filter(x.isExpression).map(i=>Ne(i,t,n)));if(x.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!x.isMemberExpression(e)&&!x.isOptionalMemberExpression(e))return null;let r=[],o=e;for(;x.isMemberExpression(o)||x.isOptionalMemberExpression(o);){if(o.computed)if(x.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(x.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&x.isExpression(o.property)){let i=Dt(o.property,n);if(typeof i=="string")r.unshift({kind:"property",name:i});else if(Number.isInteger(i))r.unshift({kind:"index",index:i});else return null}else return null;else{if(!x.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return x.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:it(e,t),base:o.name,path:r}:null}function co(e){let t=e.filter(r=>r!==null);if(t.length===0)return null;let n=t[0];return t.some(r=>r.base!==n.base||JSON.stringify(r.path)!==JSON.stringify(n.path))?null:{...n}}function Dt(e,t){if(x.isStringLiteral(e)||x.isNumericLiteral(e)||x.isBooleanLiteral(e))return e.value;if(x.isNullLiteral(e))return null;if(x.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(x.isIdentifier(e)){let n=tr(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(x.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||x.isSpreadElement(r))return;let o=Dt(r,t);if(o===void 0)return;n.push(o)}return n}if(x.isObjectExpression(e)){let n={};for(let r of e.properties){if(!x.isObjectProperty(r)||r.computed||!x.isExpression(r.value))return;let o=null;if(x.isIdentifier(r.key)?o=r.key.name:x.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!x.isIdentifier(r.value))return;let s=tr(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=Dt(r.value,t);if(i===void 0)return;n[o]=i}return n}if(x.isMemberExpression(e)){let n=Ne(e,"",t);if(!n)return;let r=tr(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=bl(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(x.isCallExpression(e))return El(e,t)??void 0}function Sl(e,t,n){let r=Ne(e,n,t);if(!r)return x.isMemberExpression(e)||x.isBinaryExpression(e)||x.isLogicalExpression(e)||x.isConditionalExpression(e)||x.isCallExpression(e)?{value:it(e,n),source:null}:null;let o=tr(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?bl(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 es(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:_g(),parentStack:[],valueScopes:i,importMap:o}}function ns(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of kt(o.id))is(n,s);if(!x.isIdentifier(o.id)||!o.init||!x.isExpression(o.init))continue;let i=Dt(o.init,t);i!==void 0&&Mg(n,o.id.name,i)}}function Dg(e){let t=[];for(let n of e){if(x.isVariableDeclaration(n)){t.push(n);continue}x.isExportNamedDeclaration(n)&&n.declaration&&x.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function Lg(e,t,n){let r=[],o=0;for(let i of e)if(x.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:_e(i),editable:!0,source:null})}else if(x.isJSXExpressionContainer(i)&&x.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:_e(i),editable:!0,source:null});else if(x.isJSXExpressionContainer(i)&&x.isTemplateLiteral(i.expression)){let s=i.expression;s.expressions.length===0&&s.quasis.length===1?r.push({index:o++,value:s.quasis[0].value.cooked??s.quasis[0].value.raw,sourceRange:_e(i),editable:!0,source:null}):r.push({index:o++,value:it(s,n),sourceRange:_e(i),editable:!0,source:Ne(s,n,t)})}else if(x.isJSXExpressionContainer(i)&&x.isExpression(i.expression)){let s=Sl(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:_e(i),editable:!0,source:s.source})}return r}function Bg(e,t,n){let r=[];for(let[o,i]of e.attributes.entries()){if(!x.isJSXAttribute(i))continue;let s=$g(i.name);if(!s)continue;let a=it(i,n);if(x.isStringLiteral(i.value)){r.push({name:s,value:i.value.value,sourceRange:_e(i),source:null,syntaxKind:"literal",raw:a,order:o,resolution:{status:"resolved",value:i.value.value}});continue}if(i.value===null){r.push({name:s,value:"true",sourceRange:_e(i),source:null,syntaxKind:"boolean-shorthand",raw:a,order:o,resolution:{status:"resolved",value:!0},resolvedValue:!0});continue}if(x.isJSXExpressionContainer(i.value)&&x.isExpression(i.value.expression)){let c=Dt(i.value.expression,t);if(s==="className"){let m=typeof c=="string"?c:c===void 0?El(i.value.expression,t):null;if(m){r.push({name:s,value:m,sourceRange:_e(i),source:null,resolvedValue:m,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:m}});continue}}let l=Sl(i.value.expression,t,n);if(c!==void 0){r.push({name:s,value:Wg(c),sourceRange:_e(i),source:Ne(i.value.expression,n,t),resolvedValue:c,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:c}});continue}let u=Vg(i.value.expression,t),d=Ne(i.value.expression,n,t),p=l?.value??it(i.value.expression,n);r.push({name:s,value:u.status==="undefined"?"undefined":p,sourceRange:_e(i),source:l?.source??d,syntaxKind:"expression",raw:a,order:o,resolution:u})}}return r}function jg(e,t,n){return e.attributes.flatMap((r,o)=>!x.isJSXSpreadAttribute(r)||!x.isExpression(r.argument)?[]:[{raw:it(r.argument,n),sourceRange:_e(r),order:o,source:Ne(r.argument,n,t)}])}function $g(e){return x.isJSXIdentifier(e)?e.name:x.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function Vg(e,t){return ht(e,{resolveIdentifier(n){let r=tr(n,t.valueScopes);return r.kind==="resolved"?{status:"resolved",value:r.value}:n==="undefined"&&!t.valueScopes.some(o=>o.has(n))?{status:"undefined"}:{status:"unresolved"}},resolveMember(n){let r=Dt(n,t);return r===void 0?{status:"unresolved"}:{status:"resolved",value:r}}})}function El(e,t){let n=wn(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function wn(e,t){if(x.isStringLiteral(e))return[e.value];if(x.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(x.isNullLiteral(e))return[];if(x.isBooleanLiteral(e))return e.value?null:[];if(x.isIdentifier(e)||x.isMemberExpression(e)){if(x.isIdentifier(e)&&e.name==="undefined")return[];let n=Dt(e,t);return typeof n=="string"?[n]:null}if(x.isConditionalExpression(e)){let n=wn(e.consequent,t),r=wn(e.alternate,t);return!n||!r?null:[...n,...r]}if(x.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=Dt(e.left,t);return n===!1||n===null?[]:wn(e.right,t)}if(x.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||x.isSpreadElement(r))return null;let o=wn(r,t);if(!o)return null;n.push(...o)}return n}if(x.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!x.isObjectProperty(r))return null;let o=Kg(r.key);if(!o)return null;n.push(o)}return n}if(x.isCallExpression(e)){let n=Ug(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!x.isExpression(o))return null;let i=wn(o,t);if(!i)return null;r.push(...i)}return r}return null}function Ug(e){return x.isIdentifier(e)?e.name:x.isMemberExpression(e)&&x.isIdentifier(e.property)?e.property.name:null}function Kg(e){return x.isIdentifier(e)?e.name:x.isStringLiteral(e)?e.value:null}function Jg(e,t){let n=e.attributes.find(r=>x.isJSXAttribute(r)&&x.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!x.isJSXAttribute(n)||!x.isJSXExpressionContainer(n.value)?null:n.value.expression}function Xg(e,t){for(let n of t){let r=Jg(e,n);if(r)return r}return null}function zg(e){return x.isJSXIdentifier(e.name)?e.name.name:null}function Wg(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function Hg(e){if(!x.isCallExpression(e)&&!x.isOptionalCallExpression(e))return null;let t=e.callee;return!x.isMemberExpression(t)&&!x.isOptionalMemberExpression(t)||!x.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!x.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function ts(e){return x.isArrowFunctionExpression(e)||x.isFunctionExpression(e)}function Gg(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function Yg(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function hl(e,t,n,r){if(!e||!x.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:it(e,n),collectionSource:Ne(e,n,r)};if(t){let i=t.params[0],s=t.params[1];x.isIdentifier(i)&&(o.itemParamName=i.name),x.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function Mt(e,t,n){if(!e)return[];if(x.isJSXElement(e)){if(os(e))return mo(e.children,t,n);let r=fo(e,t,n);return r?[r]:[]}return Nn(e)?po(e,t,n):x.isParenthesizedExpression(e)?Mt(e.expression,t,n):x.isExpression(e)?go(e,t,n):[]}function lo(e,t,n){let r=new Map;for(let o of e.params)for(let i of kt(o))is(r,i);t.valueScopes.push(r);try{if(!x.isBlockStatement(e.body))return Mt(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return vl(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function vl(e,t,n){let r=[];for(let o of e){if(x.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];i&&ns([o],t,i);continue}r.push(...rs(o,t,n))}return r}function rs(e,t,n){if(x.isReturnStatement(e))return e.argument?Mt(e.argument,t,n):[];if(x.isBlockStatement(e))return sn(e.body,t,n);if(x.isIfStatement(e)){let r=x.isBlockStatement(e.consequent)?sn(e.consequent.body,t,n):rs(e.consequent,t,n),o=e.alternate?x.isBlockStatement(e.alternate)?sn(e.alternate.body,t,n):rs(e.alternate,t,n):[];return[...r,...o]}if(x.isSwitchStatement(e))return sn(e.cases.flatMap(r=>r.consequent),t,n);if(x.isTryStatement(e)){let r=sn(e.block.body,t,n);return e.handler&&r.push(...sn(e.handler.body.body,t,n)),e.finalizer&&r.push(...sn(e.finalizer.body,t,n)),r}return[]}function sn(e,t,n){let r=new Map;t.valueScopes.push(r);try{return vl(e,t,n)}finally{t.valueScopes.pop()}}function uo(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:_e(r),sourceCandidates:i&&i.length>0?i:void 0})}function Zg(e,t,n,r){let o=Xg(e.openingElement,["items","dataSource","data"]),i={key:t,tag:yl(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!x.isJSXAttribute(s))continue;let a=zg(s);if(!a||!x.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!x.isJSXEmptyExpression(c)){if(Gg(a)&&ts(c)){let l=lo(c,n,r),u=hl(o,c,r,n);uo(n,"repeat-region",t,s,l,u?[u]:void 0);continue}if(Yg(a)){let l=ts(c)?lo(c,n,r):Mt(c,n,r);uo(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!x.isJSXExpressionContainer(s)||!ts(s.expression))continue;let a=lo(s.expression,n,r),c=hl(o,s.expression,r,n);uo(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function fo(e,t,n){let r=yl(e.openingElement);if(r==="Fragment"||os(e))return mo(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=Ag(r),a;if(s){let O=t.ordinalTracker.getOrdinal(i,r);a=`component:${r}#${O}`}else{let O=t.ordinalTracker.getOrdinal(i,r);a=`${r}#${O}`}let c=o?t.elements.get(o.key)?.identity.structuralPath:void 0,l=c?`${c}/${a}`:a,u=Zn(t.file,t.componentName,l),d={file:t.file,component:t.componentName,structuralPath:l,key:u},p=s?"component-boundary":null,m=Lg(e.children,t,n),g=Bg(e.openingElement,t,n),b=jg(e.openingElement,t,n),C,I,w=!1;if(s){let O=t.importMap.get(r)??t.importMap.get(Tg(r));O&&(C=O.specifier,I=O.exportName,w=er(O.specifier,t.file))}let A={identity:d,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:_e(e),parentKey:i,childKeys:[],textSegments:m,attributes:g.length>0?g:void 0,attributeSpreads:b.length>0?b:void 0,boundaryKind:p,isOpaque:s,...w?{isPublicUiComponent:!0}:{},importedFrom:C,exportName:I};return t.elements.set(u,A),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(u),Zg(e,u,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:u,tag:r}),Qg(e.children,t,n),t.parentStack.pop()),u}function po(e,t,n){return mo(e.children,t,n)}function mo(e,t,n){let r=[];for(let o of e)if(x.isJSXElement(o))if(os(o))r.push(...mo(o.children,t,n));else{let i=fo(o,t,n);i&&r.push(i)}else Nn(o)?r.push(...po(o,t,n)):x.isJSXExpressionContainer(o)&&r.push(...go(o.expression,t,n));return r}function Qg(e,t,n){for(let r of e)x.isJSXElement(r)?fo(r,t,n):Nn(r)?po(r,t,n):x.isJSXExpressionContainer(r)&&go(r.expression,t,n)}function qg(e){return e==="&&"||e==="||"||e==="??"}function go(e,t,n){if(x.isJSXEmptyExpression(e))return[];let r=Hg(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,c={kind:"repeat-template",collectionExpression:it(r.collection,n),collectionSource:Ne(r.collection,n,t)};if(x.isArrowFunctionExpression(a)||x.isFunctionExpression(a)){let u=a.params[0],d=a.params[1];x.isIdentifier(u)&&(c.itemParamName=u.name),x.isIdentifier(d)&&(c.indexParamName=d.name)}s.push(c);let l={kind:"repeat-region",ownerKey:i?.key??"",childKeys:[],sourceRange:_e(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(l),(x.isArrowFunctionExpression(a)||x.isFunctionExpression(a))&&l.childKeys.push(...lo(a,t,n)),l.childKeys}if(x.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:it(e.test,n),conditionSource:Ne(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:_e(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Mt(e.consequent,t,n)),s.childKeys.push(...Mt(e.alternate,t,n)),s.childKeys}if(x.isLogicalExpression(e)&&qg(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:it(e.left,n),conditionSource:Ne(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:_e(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Mt(e.right,t,n)),s.childKeys}if(x.isParenthesizedExpression(e))return go(e.expression,t,n);if(x.isJSXElement(e)){let o=fo(e,t,n);return o?[o]:[]}return Nn(e)?po(e,t,n):[]}function eh(e){let t=e.argument;return t&&(x.isExpression(t)||Nn(t))?t:null}function nr(e,t){let n=[];for(let r of e){if(x.isReturnStatement(r)){let o=eh(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(x.isIfStatement(r)){let o=x.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...nr(o,r.test)),r.alternate){let i=x.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...nr(i,r.test))}continue}if(x.isSwitchStatement(r))for(let o of r.cases){let i=o.test?x.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...nr(o.consequent,i))}}return n}function Il(e){let{file:t,source:n,ast:r}=e,o=e.imports.map(d=>d.specifier),i=new Map,s=[],a=[],c=new Map,l=Og(r);Pg(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(d){let p=Fg(d);if(!p)return;let m=d.node,g=[];if(x.isArrowFunctionExpression(m))x.isExpression(m.body)||Nn(m.body)?g=[{argument:m.body,statement:x.returnStatement(x.isExpression(m.body)?m.body:null)}]:x.isBlockStatement(m.body)&&(g=nr(m.body.body));else{let O=m.body;x.isBlockStatement(O)&&(g=nr(O.body))}if(g.length===0){d.skip();return}let b=new Map;ns(Dg(r.program.body),es(t,p,i,s,l,[b]),b);let C=new Map;for(let O of m.params)for(let ie of kt(O))is(C,ie);let I=x.isBlockStatement(m.body)?m.body.body:[],w=g[0]?.statement??null;for(let O of I){if(w&&O===w)break;x.isVariableDeclaration(O)&&ns([O],es(t,p,i,s,l,[b,C]),C)}let A=es(t,p,i,s,l,[b,C]);for(let O of g){let ie=Mt(O.argument,A,n);for(let oe of ie)a.includes(oe)||a.push(oe);if(O.condition){let oe={kind:"conditional-branch",conditionExpression:it(O.condition,n),conditionSource:Ne(O.condition,n,A)};uo(A,"conditional-region","",O.statement,ie,[oe])}}d.skip()}});let u=[...i.keys()];return u.length>0&&c.set(t,u),{graph:{routeId:t,rootKeys:a,elements:i,regions:s,fileIndex:c,version:1,diagnostics:[]},localImports:o}}function ss(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function ho(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function kl(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??qn,c=new Map,l=new Map,u=new Map,d=[],p=new Set,m=I=>{let w=`${I.path}\0${I.code}\0${I.message}\0${JSON.stringify(I.details??{})}`;p.has(w)||(p.add(w),d.push(I))},g=[{file:e,source:t,depth:0,diagnosticEntryFile:e,importStack:[]},...(o.additionalEntries??[]).map(I=>({file:I.file,source:I.source,depth:0,diagnosticEntryFile:I.file,importStack:[]}))],b=new Set;for(;g.length>0;){let I=g.shift(),{file:w,source:A,depth:O,diagnosticEntryFile:ie,importStack:oe}=I;if(b.has(w))continue;b.add(w),c.set(w,A);let N=a(w,A);if(!N.ok){m(ho(N.diagnostic,ie,oe));continue}u.set(w,N.module);let{graph:W,localImports:M}=Il(N.module);for(let j of W.elements.values())if(j.importedFrom&&xt(j.importedFrom)){let Q=j.importedFrom,re=await so(w,Q,r);re.ok?(j.importedFrom=re.path,on(re.path)&&(j.isPublicUiComponent=!0)):er(Q,w)||m(ho(re.diagnostic,ie,ss(oe,w,Q,re.diagnostic.path)))}if(l.set(w,W),!(O>=i))for(let j of M){if(ml(j))continue;let Q=await so(w,j,r);if(!Q.ok){er(j,w)||m(ho(Q.diagnostic,ie,ss(oe,w,j,Q.diagnostic.path)));continue}let re=Q.path;if(b.has(re)||on(re))continue;let be=ss(oe,w,j,re);try{let G=await n(re);g.push({file:re,source:G,depth:O+1,diagnosticEntryFile:ie,importStack:be})}catch(G){m(ho({path:re,code:"import-read-failed",message:`Failed to read imported file: ${re}`,details:{fromFile:w,specifier:j,reason:G instanceof Error?G.message:String(G)}},ie,be))}}}let C=th(e,l,s,(o.additionalEntries??[]).map(I=>I.file));return C.diagnostics=d,{graph:C,allSources:c,diagnostics:d,parsedModules:u,entryModule:u.get(e)??null}}function th(e,t,n,r=[]){let o=new Map,i=[],s=new Map,a=[];for(let[c,l]of t){for(let[u,d]of l.elements)o.set(u,d);for(let u of l.regions)i.push(u);for(let[u,d]of l.fileIndex){let p=s.get(u)??[];s.set(u,[...p,...d])}if(c===e){a=l.rootKeys;continue}r.includes(c)&&(a=[...a,...l.rootKeys])}return{routeId:e,rootKeys:a,elements:o,regions:i,fileIndex:s,version:n}}function Cl(e){let t=new Map;for(let[n,r]of e.elements){let o=/^[A-Z]/.test(r.tag),i={file:r.sourceFile,componentName:r.componentName,isProxy:o},s=r.boundaryKind,a=[];r.isOpaque&&a.push({kind:"opaque-region",reason:`Component '${r.tag}' is opaque: internal structure not editable`}),o&&!r.isOpaque&&a.push({kind:"component-boundary",reason:`Component '${r.tag}' boundary: editing requires source file access`});let c={key:n,writeTarget:i,boundaryKind:s,parentKey:r.parentKey,childKeys:[...r.childKeys],constraints:a};t.set(n,c)}for(let n of e.regions){let r=n.kind==="repeat-region"?"repeat-region":n.kind==="conditional-region"?"conditional-region":n.kind==="opaque-region"?"opaque-region":"component-boundary",o=n.kind==="repeat-region"?"Node is inside a repeat region: operations affect the template, not individual instances":n.kind==="conditional-region"?"Node is inside a conditional region: visibility depends on runtime condition":`Node is inside a ${n.kind}`;for(let i of n.childKeys){let s=t.get(i);s&&s.constraints.push({kind:r,reason:o}),Rl(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function Rl(e,t,n,r,o){let i=o.elements.get(e);if(i)for(let s of i.childKeys){let a=r.get(s);a&&!a.constraints.some(c=>c.kind===t)&&(a.constraints.push({kind:t,reason:n}),Rl(s,t,n,r,o))}}import{isSiteEditRuntimeContainerTag as nh,isSiteEditRuntimeVoidElementTag as rh}from"@vcp-dev/contracts/site-edit-runtime-capability";function Pn(e){if(!e.composition)throw new Error("Composition unavailable for render source graph.");return e.composition}function oh(e,t,n){let r=Pn(n),o=t.nodes.get(e),i=n.elements.get(e);if(!o||!i)return{composition:r,key:e,canUpdateText:!1,canInsertChild:!1,canMove:!1,canRemove:!1,constraints:[{kind:"opaque-region",message:"Node not found in graph"}]};let s=o.constraints.map(O=>({kind:O.kind,message:O.reason})),a=i.isOpaque,l=o.parentKey===null&&i.componentName==="Page",u=i.tag.toLowerCase(),d=i.tag!==u,p=!d&&rh(u),m=d||nh(u),g=d&&i.childKeys.length>0&&!i.isPublicUiComponent,b=i.textSegments.length>0&&i.textSegments.some(O=>O.editable);p&&!s.some(O=>O.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' is void: children cannot be inserted`}),!p&&!m&&!s.some(O=>O.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' cannot contain structured children`});let C=b&&(!a||i.importedFrom==="next/link"),I=!i.isPublicUiComponent&&!p&&m&&(!a||g);return{composition:r,key:e,canUpdateText:C,canInsertChild:I,canMove:!l,canRemove:!l,constraints:s}}function wl(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,oh(r,e,t));return n}import{createHash as Ms}from"node:crypto";import Ps from"@babel/traverse";function as(e){let t=new Map,n=new Map;for(let s of e){if(t.has(s.placementKey))throw new Error(`Duplicate placement key in page composition projection: ${s.placementKey}`);t.set(s.placementKey,s);let a=n.get(s.placementUnitKey)??[];a.push(s),n.set(s.placementUnitKey,a)}let r=new Map,o=new Map,i=new Map;for(let[s,a]of n){let c=Object.freeze([...a]),l=c.find(u=>u.anchorSourceRange!==null&&u.members.length>0)??c.find(u=>u.members.length>0)??c[0];l&&(o.set(s,c),i.set(s,l),r.set(s,Object.freeze({placementUnitKey:s,placementKeys:Object.freeze(c.map(u=>u.placementKey)),sourcePlacementKey:l.placementKey})))}return{placementByKey:t,unitByKey:r,placementsByUnitKey:o,sourcePlacementByUnitKey:i}}import{createHash as jy}from"node:crypto";import ou from"node:path";import*as Do from"@babel/parser";import Is from"@babel/generator";import ks from"@babel/traverse";import*as Vt from"@babel/types";import cs from"@babel/traverse";var Bt=typeof cs=="function"?cs:cs.default,yo=new WeakMap,Nl=new WeakMap;function Rt(e,t){let n=Hi(e,t);if(!n.ok)return Wi(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=ne(n.ast,t);return r.ok?{ok:!0,match:{locatorKind:r.match.locatorKind,node:r.match.node,start:r.match.start,end:r.match.end}}:Wi(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function ne(e,t){return t.kind==="jsx-node"?Fl(e,t):t.kind==="jsx-attribute"?uh(e,t):t.kind==="value"?dh(e,t):t.kind==="expression"?fh(e,t):t.kind==="directive"?ph(e,t):t.kind==="export"?mh(e,t):{ok:!1,diagnostic:nn("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function Fl(e,t){return t.strategy==="source-range"?ih(e,t):sh(e,t)}function ih(e,t){let n=null;if(Bt(e,{JSXElement(o){if(!An(o.node,t.sourceRange))return;let i=Ce("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!An(o.node,t.sourceRange))return;let i=Ce("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!An(o.node,t.sourceRange))return;let i=Ce("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)}}),!n)return Re("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!Rh(r.path,t.expectedIdentity)?Re("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function sh(e,t){if(t.structuralPath===""){let r=ch(e,t.component);if(r){let o=lh(r);if(o)return o}}let n=null;return Bt(e,{JSXElement(r){if(or(r)!==t.component||us(r)!==t.structuralPath)return;let i=Ce("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(or(r)!==t.component||us(r)!==t.structuralPath)return;let i=Ce("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=ah(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:Re("jsx-node","locator-miss","JSX node not found for structural-path locator")}function ah(e,t,n){let r=null;return Bt(e,{JSXElement(o){if(or(o)!==t||!An(o.node,n))return;let i=Ce("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(or(o)!==t||!An(o.node,n))return;let i=Ce("jsx-node",o);i&&(r=i,o.stop())}}),r}function ch(e,t){let n=null;return Bt(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 lh(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 Re("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?Re("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 Re("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function uh(e,t){let n=Fl(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>wh(c,t.name));if(!s||!s.isJSXAttribute())return Re("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=Ce("jsx-attribute",s);return a?{ok:!0,match:a}:Re("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function dh(e,t){let n=gh(e,t);if(!n.ok)return n;let r=hh(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!Ct(r.match.path.node.loc,t.expectedRange)?Re("value","locator-miss","Resolved value does not match expected range"):{ok:!0,match:r.match}:r}function fh(e,t){let n=null;return Bt(e,{Identifier(r){if(!vh(r))return;let o=Al(r);if(!o||!Tl(o,t))return;let i=Ce("expression",r);i&&(t.expectedRange&&!Ct(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=Al(r);if(!o||!Tl(o,t))return;let i=Ce("expression",r);i&&(t.expectedRange&&!Ct(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Re("expression","locator-miss","Expression not found")}function ph(e,t){let n=null;return Bt(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!Ct(i.node.loc,t.expectedRange))return;let s=Ce("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:Re("directive","locator-miss",`Directive '${t.value}' not found`)}function mh(e,t){let n=null;return Bt(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let c=r.get("declaration");if(c.isFunctionDeclaration()&&c.node.id?.name==="generateMetadata"){let p=Ce("export",c);if(!p||t.expectedRange&&!Ct(c.node.loc,t.expectedRange))return;n=p,r.stop();return}if(!c.isVariableDeclaration())return;let l=ds(c,"generateMetadata");if(!l||!l.isVariableDeclarator())return;let u=l.get("init");if(!u.node)return;let d=Ce("export",u);if(!d||t.expectedRange&&!Ct(u.node.loc,t.expectedRange))return;n=d,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=ds(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!Ct(s.node.loc,t.expectedRange))return;let a=Ce("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=Ce("export",o);i&&(t.expectedRange&&!Ct(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Re("export","export-not-found",`Export '${Ch(t)}' not found`)}function gh(e,t){let n=null;return Bt(e,{Expression(r){if(n||t.root.kind!=="expression"||!An(r.node,t.root.sourceRange))return;let o=Ce("value",r);o&&(n=o,r.stop())},VariableDeclarator(r){if(n)return;if(t.root.kind==="binding"){if(r.node.id.type!=="Identifier"||r.node.id.name!==t.root.name)return;let m=r.get("init");if(!m.node)return;let g=Ce("value",m);if(!g)return;n=g,r.stop();return}if(t.root.kind!=="hook-state")return;let o=t.root,i=r.get("id"),s=r.get("init");if(!i.isArrayPattern()||!s.isCallExpression()||i.node.elements.findIndex(m=>m?.type==="Identifier"&&m.name===o.name)!==0)return;let c=s.node.callee;if((c.type==="Identifier"?c.name:c.type==="MemberExpression"&&c.property.type==="Identifier"?c.property.name:null)!==o.hook)return;let u=o.hook==="useReducer"?1:0,d=r.get(`init.arguments.${u}`);if(!d||Array.isArray(d)||!d.node)return;let p=Ce("value",d);p&&(n=p,r.stop())},ExportNamedDeclaration(r){if(n||t.root.kind!=="named-export")return;let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=ds(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=Ce("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=Ce("value",o);i&&(n=i,r.stop())}}),n?{ok:!0,match:n}:Re("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 hh(e,t){let n=ls(e);for(let o of t){if(n=ls(n),o.kind==="property"){if(!n.isObjectExpression())return Re("value","unsupported-syntax","Property path requires object expression");let a=n.get("properties");if(a.some(l=>!l.isObjectProperty()))return Re("value","unsupported-syntax","Spread properties are not supported");let c=a.find(l=>Nh(l,o.name));if(!c||!c.isObjectProperty())return Re("value","property-not-found",`Property '${o.name}' not found`);n=c.get("value");continue}if(!n.isArrayExpression())return Re("value","unsupported-syntax","Array index path requires array expression");let i=n.get("elements");if(i.some(a=>a.node?.type==="SpreadElement"))return Re("value","unsupported-syntax","Spread array elements are not supported");let s=i[o.index];if(!s?.node)return Re("value","array-index-out-of-range",`Array index ${o.index} is out of range`);n=s}n=ls(n);let r=Ce("value",n);return r?{ok:!0,match:r}:Re("value","locator-miss","Resolved value has no source range")}function ls(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function Ce(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 An(e,t){return Ct(e.loc,t)}function Ct(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 us(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!xo(n.node)){let o=_l(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${Pl(n,o)}`):t.unshift(`${o}#${Pl(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||Sh(n.parentPath)&&!Eh(n.parentPath))break;n=n.parentPath}return t.join("/")}function xo(e){let t=e.openingElement.name;return t.type==="JSXIdentifier"?t.name==="Fragment":t.type==="JSXMemberExpression"&&t.property.name==="Fragment"}function Pl(e,t){let n=yh(e);if(!n)return 0;let r=yo.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=yo.get(n.node)?.get(t);if(!i){let s=yo.get(n.node);s||(s=new Map,yo.set(n.node,s)),i=new WeakMap,s.set(t,i)}for(let s of rr(n))if(_l(s.node.openingElement)===t){if(i.set(s.node,o),s.node===e.node)return o;o++}return i.get(e.node)??0}function yh(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(xo(t.node)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function rr(e){let t=Nl.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(xo(o.node)){n.push(...rr(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...rr(o));continue}o.isJSXExpressionContainer()&&n.push(...Lt(o.get("expression")))}return Nl.set(e.node,n),n}function Lt(e){if(e.isJSXElement())return xo(e.node)?rr(e):[e];if(e.isJSXFragment())return rr(e);if(e.isParenthesizedExpression())return Lt(e.get("expression"));if(e.isLogicalExpression()&&xh(e.node.operator))return Lt(e.get("right"));if(e.isCallExpression()||e.isOptionalCallExpression()){let t=e.get("callee"),n=!Array.isArray(t)&&(t.isMemberExpression()||t.isOptionalMemberExpression())?t.get("property"):null;if(!Array.isArray(t)&&(t.isMemberExpression()||t.isOptionalMemberExpression())&&!t.node.computed&&n!==null&&!Array.isArray(n)&&n.isIdentifier()&&n.node.name==="map"){let r=e.get("arguments").find(o=>!Array.isArray(o)&&(o.isArrowFunctionExpression()||o.isFunctionExpression()));if(r&&!Array.isArray(r)){let o=r.get("body");if(!Array.isArray(o)){if(o.isBlockStatement()){let i=o.get("body").find(s=>!Array.isArray(s)&&s.isReturnStatement());if(i&&!Array.isArray(i)){let s=i.get("argument");if(!Array.isArray(s)&&s.node&&s.isExpression())return Lt(s)}}else if(o.node&&o.isExpression())return Lt(o)}}}}return 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 xh(e){return e==="&&"||e==="||"||e==="??"}function _l(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?bh(e.name):null}function bh(e){let t=[],n=e;for(;n.type==="JSXMemberExpression";)t.unshift(n.property.name),n=n.object;return t.unshift(n.name),t.join(".")}function or(e){let t=e;for(;t;){if(t.isFunctionDeclaration())return t.node.id?.name??null;if((t.isArrowFunctionExpression()||t.isFunctionExpression())&&t.parentPath?.isVariableDeclarator()){let n=t.parentPath.node.id;return n.type==="Identifier"?n.name:null}t=t.parentPath}return null}function Sh(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function Eh(e){let t=e.parentPath;if(!t||!t.isCallExpression()&&!t.isOptionalCallExpression())return!1;let n=t.get("callee"),r=!Array.isArray(n)&&(n.isMemberExpression()||n.isOptionalMemberExpression())?n.get("property"):null;if(Array.isArray(n)||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.computed||r===null||Array.isArray(r)||!r.isIdentifier()||r.node.name!=="map")return!1;let o=t.get("arguments");return Array.isArray(o)?o.some(i=>!Array.isArray(i)&&i.node===e.node):!1}function vh(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function Al(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 Tl(e,t){return e.base===t.base&&Ih(e.path,t.path??[])}function Ih(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 kh(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function Ch(e){return e.exportKind==="named"?e.name:e.exportKind}function Re(e,t,n,r){return{ok:!1,diagnostic:nn(t,n,e,r)}}function Rh(e,t){return or(e)!==t.component?!1:us(e)===t.structuralPath}function wh(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function ds(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function Nh(e,t){return e.isObjectProperty()?kh(e.node)===t:!1}import fs from"@babel/generator";var Ph=typeof fs=="function"?fs:fs.default;function Ah(e){let t=e.split(`
2
+ `),n=[],r=!1;for(let s of t){let a=s.match(/^(\s+)/);if(a){let c=a[1];c.includes(" ")?r=!0:c.length>0&&n.push(c.length)}}if(r&&t.every(a=>{let c=a.match(/^(\s+)/);return!c||c[1].includes(" ")}))return"tab";if(n.length===0)return"2";function o(s,a){return a===0?s:o(a,s%a)}let i=n[0];for(let s=1;s<n.length;s++)i=o(i,n[s]);return i>=4?"4":"2"}function Th(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 Fh(e,t){return e.split(`
3
+ `).map(r=>Th(r,t)).join(`
4
+ `)}function bo(e){let{ast:t,source:n}=e;try{let r=Ah(n),i=Ph(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=Fh(i,r)),{ok:!0,source:i}}catch(r){return B(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}import*as Ml from"@babel/parser";import{arrayExpression as _h,booleanLiteral as Oh,identifier as Mh,jsxAttribute as Dh,jsxExpressionContainer as Lh,jsxIdentifier as Bh,nullLiteral as jh,numericLiteral as $h,objectExpression as Vh,objectProperty as Uh,stringLiteral as ps}from"@babel/types";function Ol(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 ir(e,t,n){return{ok:!0,source:t,operation:{type:n.kind,nodeId:n.target,kind:n.kind,target:n.target,beforeSourceHash:Ol(e),afterSourceHash:Ol(t),inverse:n.inverse}}}function ae(e,t,n){let r=bo({ast:e,source:t});return r.ok?ir(t,r.source,n):r}function ge(e,t){let n=Gi(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function So(e,t){return bo({ast:e,source:t})}function Kh(e,t,n){let r=ne(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function Eo(e,t,n){let r=Kh(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:B(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function jt(e){return typeof e=="string"?ps(e):typeof e=="number"?$h(e):typeof e=="boolean"?Oh(e):e===null?jh():Array.isArray(e)?_h(e.map(t=>jt(t))):Vh(Object.entries(e).map(([t,n])=>{let r=Uh(ms(t),jt(n));return t==="__proto__"&&(r.computed=!0),r}))}function Jh(e){return typeof e=="string"?ps(e):Lh(jt(e))}function sr(e,t){return Dh(Bh(e),Jh(t))}function vo(e,t){try{let r=Ml.parse(`const __VD_NODE__ = (${t});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0];return r?.type!=="VariableDeclaration"||r.declarations[0]?.type!=="VariableDeclarator"||!r.declarations[0].init||r.declarations[0].init.type!=="JSXElement"&&r.declarations[0].init.type!=="JSXFragment"?{ok:!1,result:B(e,"unsupported-syntax","Provided JSX source does not resolve to a JSX node","jsx-node")}:{ok:!0,node:r.declarations[0].init}}catch(n){return{ok:!1,result:B(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function ms(e){return/^[$A-Z_][0-9A-Z_$]*$/i.test(e)?Mh(e):ps(e)}function Io(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=ge(t,"jsx-node");if(!i.ok)return i.result;let s=ne(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let c=Xh(s.match.path)[r];if(!c)return B(t,"locator-miss",`Text segment ${r} not found`,"jsx-node");switch(c.kind){case"jsx-text":c.path.node.value=zh(c.path.node.value,o);break;case"string-literal":c.path.node.value=o;break;case"template-literal":{let l=c.quasiIndex;c.path.node.quasis[l].value.raw=o,c.path.node.quasis[l].value.cooked=o;break}}return ae(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function Xh(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=Wh(r.get("expression"));o.length>0&&t.push(...o)}}return t}function zh(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function Wh(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 gs}from"@babel/types";function Tn(e){let{source:t,locator:n}=e,r=ge(t,"jsx-node");if(!r.ok)return r.result;let o=ne(r.ast,n);return o.ok?(Hh(o.match.path),ae(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function Hh(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(gs());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(gs());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(gs());return}e.remove()}import{cloneNode as Gh}from"@babel/types";function ko(e){let t=ge(e.source,"jsx-node");if(!t.ok)return t.result;let n=ne(t.ast,e.locator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};let r=vo(e.source,e.node.jsx);return r.ok?(n.match.path.replaceWith(Gh(r.node,!0)),ae(t.ast,e.source,{kind:"replace-node",target:"jsx-node",inverse:"replace-node"})):r.result}import{cloneNode as sy}from"@babel/types";import hs from"@babel/traverse";import*as X from"@babel/types";var Yh=typeof hs=="function"?hs:hs.default;function Qe(e,t,n,r){if(!e.ok)return e;let o=Ze(n);if(!o)return e;let i=Zh(t,o,r);return i?{...e,selectionRef:i}:e}function Zh(e,t,n){let r=Qh(e,t);if(!r)return;let o=n.sourceLocator?Dl(n.sourceLocator):void 0,i=n.targetParentLocator?Dl(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??ey(r)??i?.component??o?.component;if(!(!s||!a))return{key:Zn(s,a,ty(r))}}function Dl(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function Qh(e,t){let n=null;return Yh(e,{JSXElement(r){r.node===t&&(n=r,r.stop())}}),n}function Ze(e){if(!e)return null;if(X.isJSXElement(e))return Fn(e)?Ll(e.children):e;if(X.isJSXFragment(e))return Ll(e.children);if(X.isJSXExpressionContainer(e)||X.isParenthesizedExpression(e)||X.isTSAsExpression(e)||X.isTSSatisfiesExpression(e)||X.isTSTypeAssertion(e)||X.isTSNonNullExpression(e))return Ze(e.expression);if(X.isLogicalExpression(e))return Ze(e.right);if(X.isConditionalExpression(e))return Ze(e.consequent)??Ze(e.alternate);if(X.isCallExpression(e)||X.isOptionalCallExpression(e))return Ul(e)?qh(e.arguments[0]):null;if(X.isArrayExpression(e))for(let t of e.elements){if(!t)continue;let n=Ze(t);if(n)return n}return null}function Ll(e){for(let t of e){let n=Ze(t);if(n)return n}return null}function qh(e){return!e||!X.isArrowFunctionExpression(e)&&!X.isFunctionExpression(e)?null:X.isBlockStatement(e.body)?ar(e.body.body):Ze(e.body)}function ar(e){for(let t of e){if(X.isReturnStatement(t)){let n=Ze(t.argument);if(n)return n;continue}if(X.isBlockStatement(t)){let n=ar(t.body);if(n)return n;continue}if(X.isIfStatement(t)){let n=Bl(t.consequent);if(n)return n;let r=t.alternate?Bl(t.alternate):null;if(r)return r;continue}if(X.isSwitchStatement(t))for(let n of t.cases){let r=ar(n.consequent);if(r)return r}}return null}function Bl(e){return X.isBlockStatement(e)?ar(e.body):ar([e])}function ey(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(X.isFunctionDeclaration(n))return n.id?.name??"default"}if(t.isVariableDeclarator()&&X.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 jl=new WeakMap,$l=new WeakMap,ys=new WeakMap;function ty(e){let t=jl.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=ny(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return jl.set(e.node,o),o}function ny(e){let t=xs(e.node.openingElement.name);return!t||Fn(e.node)?null:/^[A-Z]/.test(t)?`component:${t}#${Vl(e,t)}`:`${t}#${Vl(e,t)}`}function Vl(e,t){let n=ry(e);if(!n)return 0;let r=ys.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=ys.get(n.node);o||(o=new Map,ys.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of an(n))if(xs(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 ry(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Fn(t.node)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function an(e){let t=$l.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(Fn(o.node)){n.push(...an(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...an(o));continue}o.isJSXExpressionContainer()&&n.push(...wt(o.get("expression")))}return $l.set(e.node,n),n}function wt(e){if(e.isJSXElement())return Fn(e.node)?an(e):[e];if(e.isJSXFragment())return an(e);if(e.isParenthesizedExpression())return wt(e.get("expression"));if(e.isLogicalExpression())return wt(e.get("right"));if(e.isConditionalExpression())return[...wt(e.get("consequent")),...wt(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:wt(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&Ul(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?oy(n):[]}return[]}function oy(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return Fn(t.node)?an(t):[t];if(t.isJSXFragment())return an(t);if(t.isParenthesizedExpression())return wt(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return wt(t);if(!t.isBlockStatement())return[];for(let n of t.get("body")){if(!n.isReturnStatement())continue;let r=n.get("argument");return r.node?wt(r):[]}return[]}function Ul(e){let t=e.callee;return(X.isMemberExpression(t)||X.isOptionalMemberExpression(t))&&X.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function Fn(e){let t=xs(e.openingElement.name);return t==="Fragment"||t==="React.Fragment"}function xs(e){return X.isJSXIdentifier(e)?e.name:X.isJSXMemberExpression(e)?Kl(e):X.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function Kl(e){return`${X.isJSXIdentifier(e.object)?e.object.name:Kl(e.object)}.${e.property.name}`}function $t(e,t){if(t.parentPath===e&&t.listKey==="children"&&Jl(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!Jl(n))return null;let r=n;for(;r&&r!==e;){if(!iy(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function Jl(e){return e.isJSXElement()||e.isJSXFragment()}function iy(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 _n(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=ge(t,"jsx-node");if(!a.ok)return a.result;let c=ne(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return B(t,"unsupported-syntax","insert-child target must be a JSXElement or JSXFragment","jsx-node");let l=c.match.path;if(c.match.path.isJSXElement()){let A=c.match.path.node;if(!A.closingElement||A.openingElement.selfClosing)return B(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=vo(t,r.jsx);if(!u.ok)return u.result;let d=sy(u.node,!0),p=l.node.children,m={...s,targetParentLocator:n},g=A=>s?Qe(A,a.ast,d,m):A;if(o==="append")return p.push(d),g(ae(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return p.unshift(d),g(ae(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(!i)return B(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let b=ne(a.ast,i);if(!b.ok)return{ok:!1,source:t,diagnostic:b.diagnostic};let C=$t(c.match.path,b.match.path);if(!C)return B(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");l=C;let I=l.node.children,w=I.findIndex(A=>A===b.match.path.node);return w===-1?B(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(I.splice(o==="before"?w:w+1,0,d),g(ae(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as Xl from"@babel/parser";import{cloneNode as ay}from"@babel/types";function Co(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=ge(t,"jsx-node");if(!a.ok)return a.result;let c=cy(t,r);if(!c.ok)return c.result;let l=ne(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return B(t,"unsupported-syntax","insert-jsx-expression-child target must be a JSXElement or JSXFragment","jsx-node");if(l.match.path.isJSXElement()){let I=l.match.path.node;if(!I.closingElement||I.openingElement.selfClosing)return B(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=l.match.path,d=null;if(i){let I=ne(a.ast,i);if(!I.ok)return{ok:!1,source:t,diagnostic:I.diagnostic};let w=$t(l.match.path,I.match.path);if(!w)return B(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=w,d=I.match.path.node}else if(o==="before"||o==="after")return B(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let p=ay(c.node,!0),m=u.node.children,g={...s,targetParentLocator:n},b=I=>s?Qe(I,a.ast,p,g):I;if(o==="append")return m.push(p),b(ae(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return m.unshift(p),b(ae(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let C=m.findIndex(I=>I===d);return C===-1?B(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(m.splice(o==="before"?C:C+1,0,p),b(ae(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function cy(e,t){try{let r=Xl.parse(`const __VD_EXPR__ = <>{${t}}</>;`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],o=r?.type==="VariableDeclaration"?r.declarations[0]?.init:null,i=o?.type==="JSXFragment"?o.children[0]:void 0;return i?.type!=="JSXExpressionContainer"?{ok:!1,result:B(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:B(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as ly,nullLiteral as bs}from"@babel/types";import*as On from"@babel/types";function Mn(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=ge(t,"jsx-node");if(!a.ok)return a.result;let c=ne(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let l=ne(a.ast,r);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return B(t,"unsupported-syntax","move-node target parent must be a JSXElement or JSXFragment","jsx-node");let u=l.match.path;if(l.match.path.isJSXElement()){let w=l.match.path.node;if(!w.closingElement||w.openingElement.selfClosing)return B(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let d=null;if(i){let w=ne(a.ast,i);if(!w.ok)return{ok:!1,source:t,diagnostic:w.diagnostic};let A=$t(l.match.path,w.match.path);if(!A)return B(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=A,d=w.match.path}else if(o==="before"||o==="after")return B(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let p=d&&typeof d.key=="number"?d.key:-1;if(d&&p===-1)return B(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let m=ly(c.match.path.node,!0);if(!On.isJSXElement(m)&&!On.isJSXExpressionContainer(m)&&!On.isJSXFragment(m))return B(t,"unsupported-syntax","move-node source must resolve to a JSX child","jsx-node");let g=c.match.path.parentPath?.node===u.node&&typeof c.match.path.key=="number"?c.match.path.key:-1;if(d&&c.match.path.parentPath?.node===d.parentPath?.node&&c.match.path.key===d.key)return B(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");uy(c.match.path);let b=u.node.children,C={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return b.push(m),Qe(So(a.ast,t),a.ast,m,C);if(o==="prepend")return b.unshift(m),Qe(So(a.ast,t),a.ast,m,C);let I=p-(g!==-1&&g<p?1:0);return b.splice(o==="before"?I:I+1,0,m),Qe(So(a.ast,t),a.ast,m,C)}function uy(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(bs());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(bs());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(bs());return}e.remove()}import*as zl from"@babel/parser";import{cloneNode as dy,nullLiteral as Ss}from"@babel/types";function Ro(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,c=ge(t,"jsx-node");if(!c.ok)return c.result;let l=fy(t,s);if(!l.ok)return l.result;let u=ne(c.ast,n);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};let d=ne(c.ast,r);if(!d.ok)return{ok:!1,source:t,diagnostic:d.diagnostic};if(!d.match.path.isJSXElement()&&!d.match.path.isJSXFragment())return B(t,"unsupported-syntax","move-repeat-template-child target parent must be a JSXElement or JSXFragment","jsx-node");if(d.match.path.isJSXElement()){let A=d.match.path.node;if(!A.closingElement||A.openingElement.selfClosing)return B(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let p=d.match.path,m=null;if(i){let A=ne(c.ast,i);if(!A.ok)return{ok:!1,source:t,diagnostic:A.diagnostic};let O=$t(d.match.path,A.match.path);if(!O)return B(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");p=O,m=A.match.path.node}else if(o==="before"||o==="after")return B(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!u.match.path.isJSXElement())return B(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let g=p.node,b=dy(l.node,!0);py(u.match.path);let C={...a,sourceLocator:n,targetParentLocator:r},I=g.children;if(o==="append")return I.push(b),Qe(ae(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,b,C);if(o==="prepend")return I.unshift(b),Qe(ae(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,b,C);let w=I.findIndex(A=>A===m);return w===-1?B(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(I.splice(o==="before"?w:w+1,0,b),Qe(ae(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,b,C))}function fy(e,t){try{let r=zl.parse(`const __VD_EXPR__ = <>{${t}}</>;`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],o=r?.type==="VariableDeclaration"?r.declarations[0]?.init:null,i=o?.type==="JSXFragment"?o.children[0]:void 0;return i?.type!=="JSXExpressionContainer"?{ok:!1,result:B(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:B(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function py(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Ss());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Ss());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Ss());return}e.remove()}import{SiteEditSetPropsParamsSchema as my,classifySiteEditPropertyName as gy}from"@vcp-dev/contracts";import*as Dn from"@babel/types";function wo(e){let t=my.safeParse({kind:"set-props",scope:"selection",changes:e.changes});if(!t.success)return B(e.source,"unsupported-syntax","Invalid typed JSX property changes","jsx-node",{issues:t.error.issues});let n=ge(e.source,"jsx-node");if(!n.ok)return n.result;let r=Eo(n.ast,e.locator,e.source);if(!r.ok)return r.result;for(let a of t.data.changes){let c=gy(a.name);if(c.owner!=="generic")return B(e.source,"unsupported-syntax",c.diagnostic?.message??`Property '${a.name}' is not owned by the generic JSX primitive`,"jsx-node")}let o=r.match.path.node.openingElement,i=o.attributes.filter(Dn.isJSXAttribute),s=new Map;for(let a of i){let c=hy(a);if(!c)continue;let l=s.get(c)??[];l.push(a),s.set(c,l)}for(let a of t.data.changes)if((s.get(a.name)??[]).length>1)return B(e.source,"unsupported-syntax",`JSX attribute '${a.name}' has multiple sources`,"jsx-node");for(let a of t.data.changes){let c=s.get(a.name)?.[0];if(a.operation==="remove"){c&&(o.attributes=o.attributes.filter(u=>u!==c));continue}let l=sr(a.name,a.value).value;c?c.value=l:o.attributes.push(sr(a.name,a.value))}return ae(n.ast,e.source,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}function hy(e){return Dn.isJSXIdentifier(e.name)?e.name.name:Dn.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import*as Pe from"@babel/types";import{classifySiteEditPropertyName as Wl}from"@vcp-dev/contracts";function No(e){let t=Wl(e.name),n=Wl(e.property);if(t.owner!=="generic"||n.owner!=="generic")return B(e.source,"unsupported-syntax","Property binding is only available for generic properties","jsx-node");if(!Hl(e.object))return B(e.source,"unsupported-syntax","Property binding object must be a single identifier","jsx-node");if(e.property.length===0)return B(e.source,"unsupported-syntax","Property binding requires a non-empty property name","jsx-node");let r=ge(e.source,"jsx-node");if(!r.ok)return r.result;let o=Eo(r.ast,e.locator,e.source);if(!o.ok)return o.result;let i=o.match.path.node.openingElement,s=i.attributes.filter(l=>Pe.isJSXAttribute(l)&&xy(l)===e.name);if(s.length>1)return B(e.source,"unsupported-syntax",`JSX attribute '${e.name}' has multiple sources`,"jsx-node");let a=yy(e.object,e.property),c=s[0];if(c)c.value=Pe.jsxExpressionContainer(a);else{let l=sr(e.name,"");l.value=Pe.jsxExpressionContainer(a),i.attributes.push(l)}return ae(r.ast,e.source,{kind:"set-property-binding",target:"jsx-node",inverse:"restore-property-binding"})}function yy(e,t){return Hl(t)?Pe.memberExpression(Pe.identifier(e),Pe.identifier(t)):Pe.memberExpression(Pe.identifier(e),Pe.stringLiteral(t),!0)}function Hl(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)}function xy(e){return Pe.isJSXIdentifier(e.name)?e.name.name:Pe.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{getBindingIdentifiers as Sy,identifier as cr,importDeclaration as Ey,importDefaultSpecifier as vy,importNamespaceSpecifier as Iy,importSpecifier as ky,isImportDefaultSpecifier as Gl,isImportNamespaceSpecifier as Yl,isImportSpecifier as Zl,stringLiteral as Cy}from"@babel/types";function Ln(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(C=>!Oy(C));if(o!==-1){let C=r[o],I=C&&typeof C=="object"&&"kind"in C?C.kind:void 0;return B(t,"unsupported-syntax",`Unsupported import spec kind: ${String(I)}`)}let i=Ty(r);if(!i.ok)return B(t,"unsupported-syntax",i.message);let s=ge(t);if(!s.ok)return s.result;let{ast:a}=s,c=a.program,l=c.body.filter(C=>C.type==="ImportDeclaration"&&C.source.value===n),u=new Set(l.flatMap(C=>C.specifiers.flatMap(I=>{let w=My(C,I);return w?[w]:[]}))),d=i.imports.filter(C=>!u.has(ru(C)));if(d.length===0)return ir(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let p=Fy(c.body),m=d.find(C=>p.has(Es(C)));if(m)return B(t,"unsupported-syntax",`Import local binding already exists: ${Es(m)}`);let g=Ay(d);if(g.reduce((C,I)=>C+I.length,0)!==d.length)return B(t,"unsupported-syntax","Unsupported import specifier grouping");for(let C of g){if(!tu(ql(C)))return B(t,"unsupported-syntax","Unsupported import specifier combination");let I=l.find(w=>Ry(w,C));if(I)wy(I,C);else{let w=Ey(Ql(C),Cy(n));_y(c.body,w),l.push(w)}}return ae(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function Ry(e,t){return e.importKind==="type"?!1:tu(Py(Ny(e),ql(t)))}function wy(e,t){let n=!1,r=new Set(e.specifiers.map(o=>vs(o)));for(let o of Ql(t)){let i=vs(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return nu(e.specifiers),{changed:n}}function Ql(e){let t=e.map(n=>{switch(n.kind){case"named":return ky(n.local?cr(n.local):cr(n.imported),cr(n.imported));case"default":return vy(cr(n.local));case"namespace":return Iy(cr(n.local));default:return n}});return nu(t),t}function ql(e){let t=eu();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 Ny(e){let t=eu();for(let n of e.specifiers)Gl(n)?t.defaultLocals.add(n.local.name):Yl(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function eu(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function Py(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function tu(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function nu(e){let t=[...e.filter(n=>Gl(n)),...e.filter(n=>Yl(n)),...e.filter(n=>Zl(n))];e.splice(0,e.length,...t)}function Ay(e){let t=e.filter(i=>i.kind==="default"),n=e.filter(i=>i.kind==="namespace"),r=e.filter(i=>i.kind==="named"),o=[];if(n.length>0){let i=Math.max(t.length,n.length);for(let s=0;s<i;s+=1){let a=[],c=t[s],l=n[s];c&&a.push(c),l&&a.push(l),o.push(a)}return r.length>0&&o.push(r),o}if(t.length>0){o.push([t[0],...r]);for(let i of t.slice(1))o.push([i])}else r.length>0&&o.push(r);return o}function Ty(e){let t=new Map,n=new Map;for(let r of e){let o=ru(r);if(t.has(o))continue;let i=Es(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 Fy(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(Sy(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 _y(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 Oy(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 ru(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 Es(e){return e.kind==="named"?e.local??e.imported:e.local}function My(e,t){return e.importKind==="type"||Zl(t)&&t.importKind==="type"?null:vs(t)}function vs(e){if(e.type==="ImportDefaultSpecifier")return`default:${e.local.name}`;if(e.type==="ImportNamespaceSpecifier")return`namespace:${e.local.name}`;let t=e.imported.type==="Identifier"?e.imported.name:e.imported.value,n=e.local.name;return`named:${t}:${n}`}function Bn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(u=>!Ly(u));if(o!==-1){let u=r[o],d=u&&typeof u=="object"&&"kind"in u?u.kind:void 0;return B(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(d)}`)}let i=ge(t);if(!i.ok)return i.result;let{ast:s}=i,a=s.program,c=a.body.findIndex(u=>u.type==="ImportDeclaration"&&u.source.value===n);if(c===-1)return ir(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let l=a.body[c];return r.length===0?(a.body.splice(c,1),ae(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(l.specifiers=l.specifiers.filter(u=>!r.some(d=>Dy(u,d))),l.specifiers.length===0&&a.body.splice(c,1),ae(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function Dy(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 Ly(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 lr(e){let{source:t,locator:n,next:r}=e,o=Fo(t,n);return o.ok?(o.path.replaceWith(jt(r)),ae(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function Po(e){let{source:t,locator:n,index:r,value:o}=e,i=Fo(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(s=>s?.type==="SpreadElement")?B(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>i.path.node.elements.length?B(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,0,jt(o)),ae(i.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):B(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function Ao(e){let{source:t,locator:n,index:r}=e,o=Fo(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(i=>i?.type==="SpreadElement")?B(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=o.path.node.elements.length?B(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(o.path.node.elements.splice(r,1),ae(o.ast,t,{kind:"remove-array-element",target:"value",inverse:"insert-array-element"})):B(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function To(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=Fo(t,n);if(!i.ok)return i.result;if(!i.path.isArrayExpression())return B(t,"unsupported-syntax","Array operations require array expression target","value");if(i.path.node.elements.some(c=>c?.type==="SpreadElement"))return B(t,"unsupported-syntax","Spread array elements are not supported","value");if(r<0||r>=i.path.node.elements.length||o<0||o>i.path.node.elements.length)return B(t,"array-index-out-of-range","Array move indices are out of range","value");let[s]=i.path.node.elements.splice(r,1),a=Math.min(o,i.path.node.elements.length);return i.path.node.elements.splice(a,0,s),ae(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function Fo(e,t){let n=ge(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=ne(n.ast,t);return r.ok?{ok:!0,ast:n.ast,path:r.match.path}:{ok:!1,result:{ok:!1,source:e,diagnostic:r.diagnostic}}}import*as Te from"@babel/types";function _o(e){let t=ge(e.source,"value");if(!t.ok)return t.result;let n=ne(t.ast,e.objectLocator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};if(!n.match.path.isObjectExpression())return B(e.source,"unsupported-syntax","Object property upsert requires an ObjectExpression parent","value");let r=n.match.path.node;if(r.properties.some(a=>Te.isSpreadElement(a)||Te.isObjectProperty(a)&&a.computed))return B(e.source,"unsupported-syntax","Object property upsert does not support spreads or computed keys","value");let o=r.properties.filter(a=>Te.isObjectProperty(a)&&By(a.key)===e.name);if(o.length>1)return B(e.source,"unsupported-syntax",`Object property '${e.name}' has multiple sources`,"value");let i=e.value.kind==="undefined"?Te.unaryExpression("void",Te.numericLiteral(0)):jt(e.value.value),s=o[0];if(s)s.value=i,s.shorthand=!1;else{let a=Te.objectProperty(ms(e.name),i);e.name==="__proto__"&&(a.computed=!0),r.properties.push(a)}return ae(t.ast,e.source,{kind:"upsert-object-property",target:"value",inverse:"restore-object-property"})}function By(e){return Te.isIdentifier(e)?e.name:Te.isStringLiteral(e)?e.value:Te.isNumericLiteral(e)?String(e.value):null}var $y=typeof Is=="function"?Is:Is.default;function Rs(e){let t=lu(e);if(t)return{ok:!1,error:t};let n=e.projection,r=Ns(n,e.placementKey,e.expectedDocumentVersion);if(!r.ok)return{ok:!1,error:{code:r.diagnostic.code==="DOCUMENT_VERSION_STALE"?"VERSION_STALE":"RUNTIME_ANCHOR_UNRESOLVED",message:r.diagnostic.message,diagnostics:[r.diagnostic]}};let o=r.placement.containerSourceRange??n.container.sourceRange,i=r.placement;if((n.container.kind==="virtual-route-root"||n.container.kind==="starter-placeholder")&&(n.container.sourceRange===null||n.container.sourceKind==="jsx-element"||n.container.sourceKind==="atomic-expression"||n.container.kind==="starter-placeholder"))return n.container.sourceKind==="atomic-expression"?{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"An indirect page expression does not expose a safe return boundary.",diagnostics:[]}}:{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:i.placementUnitKey,importStep:iu(e),returnStep:{kind:"insert-return",node:{jsx:`<${e.component.localName} />`},placement:i.relation,replaceOriginal:n.container.kind==="starter-placeholder"}}};if(!o)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition does not expose a safe placement boundary.",diagnostics:[]}};let a={kind:"jsx-node",strategy:"source-range",sourceRange:o},c=Rt(e.source,a);if(!c.ok||!c.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:c.ok===!1?c.diagnostic.message:"Route page composition anchor could not be resolved.",diagnostics:c.ok?[]:[Oo(c.diagnostic)]}};let l=Mo(e.source,c.match.node.start??null,c.match.node.end??null);if(Xy(o,n.container.sourceRange)&&n.container.sourceHash&&l!==n.container.sourceHash)return{ok:!1,error:{code:"VERSION_STALE",message:"Route page composition container hash no longer matches the current source.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Route page composition container hash no longer matches the current source."}]}};let u=iu(e);return{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:r.placement.placementUnitKey,parentLocator:a,importStep:u,insertStep:{kind:"insert-child",parentLocator:a,node:{jsx:`<${e.component.localName} />`},placement:r.placement.relation,...r.placement.anchorSourceRange?{anchorLocator:{kind:"jsx-node",strategy:"source-range",sourceRange:r.placement.anchorSourceRange}}:{}}}}}function iu(e){let t=Jy(e.entryFile,e.component.source);return e.component.exportName==="default"?{kind:"add-import",moduleSpecifier:t,imports:[{kind:"default",local:e.component.localName}]}:{kind:"add-import",moduleSpecifier:t,imports:[{kind:"named",imported:e.component.exportName,local:e.component.localName===e.component.exportName?void 0:e.component.localName}]}}function cu(e){let t;try{t=Do.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]})}catch(i){return{ok:!1,source:e.source,diagnostic:{message:i instanceof Error?i.message:String(i)}}}let n=Do.parseExpression(e.jsx,{plugins:["jsx","typescript"]}),r=!1;return(typeof ks=="function"?ks:ks.default)(t,{ExportDefaultDeclaration(i){let s=i.get("declaration"),a=Vy(i,s);if(a){if(a.isArrowFunctionExpression()&&!a.get("body").isBlockStatement()){let c=a.get("body");c.replaceWith(su(c.node,n,e.placement,e.replaceOriginal===!0)),r=!0,i.stop();return}a.traverse({Function(c){c.node!==a.node&&c.skip()},ReturnStatement(c){if(r)return;let l=c.get("argument");l.node&&(l.replaceWith(su(l.node,n,e.placement,e.replaceOriginal===!0)),r=!0,c.stop())}}),r&&i.stop()}}}),r?{ok:!0,source:$y(t,{}).code}:{ok:!1,source:e.source,diagnostic:{message:"Route default return boundary could not be resolved."}}}function Vy(e,t){if(t.isFunctionDeclaration()||t.isFunctionExpression()||t.isArrowFunctionExpression())return t;if(!t.isIdentifier())return null;let n=e.scope.getBinding(t.node.name);if(!n)return null;let r=n.path;if(r.isFunctionDeclaration()||r.isFunctionExpression())return r;if(r.isVariableDeclarator()){let o=r.get("init");if(o.isArrowFunctionExpression()||o.isFunctionExpression())return o}return null}function su(e,t,n,r){if(Vt.isNullLiteral(e)||r)return t;let s=n==="before"||n==="prepend"?[t,e]:[e,t];return Vt.jsxFragment(Vt.jsxOpeningFragment(),Vt.jsxClosingFragment(),s)}function ws(e){let t=lu(e);if(t)return{ok:!1,error:t};let n=e.projection;if(n.container.sourceRange===null)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition does not expose a safe placement boundary.",diagnostics:[]}};let r=uu(n,e.placementUnitKey,e.expectedDocumentVersion);if(!r.ok)return{ok:!1,error:{code:r.diagnostic.code==="DOCUMENT_VERSION_STALE"?"VERSION_STALE":"NO_SAFE_PAGE_PLACEMENT",message:r.diagnostic.message,diagnostics:[r.diagnostic]}};let o=r.placement;if(!o.sourceRange||!o.sourceHash)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition source placement does not expose a safe boundary.",diagnostics:[]}};let i=Cs(o.sourceRange),s=Rt(e.source,i);if(!s.ok||!s.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:s.ok===!1?s.diagnostic.message:"Route page composition source anchor could not be resolved.",diagnostics:s.ok?[]:[Oo(s.diagnostic)]}};if(Mo(e.source,s.match.node.start??null,s.match.node.end??null)!==o.sourceHash)return{ok:!1,error:{code:"VERSION_STALE",message:"Route page composition source placement hash no longer matches the current source.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Route page composition source placement hash no longer matches the current source."}]}};if(e.operation==="remove-node")return{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"remove-node",locator:i}}};if(!e.targetPlacement)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Page-unit move requires a target placement.",diagnostics:[]}};if(e.targetPlacement.composition.routeId!==e.routeId||!Ky(e.targetPlacement.composition,e.composition))return{ok:!1,error:{code:"CROSS_PAGE_MOVE_UNSUPPORTED",message:"Page-unit move across routes or composition templates is not supported.",diagnostics:[]}};if(e.targetPlacement.documentVersion!==e.expectedDocumentVersion)return{ok:!1,error:{code:"VERSION_STALE",message:"Page-unit target placement belongs to a different document version.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Page-unit target placement belongs to a different document version."}]}};let c=Ns(n,e.targetPlacement.placementKey,e.expectedDocumentVersion);if(!c.ok)return{ok:!1,error:{code:c.diagnostic.code==="DOCUMENT_VERSION_STALE"?"VERSION_STALE":"NO_SAFE_PAGE_PLACEMENT",message:c.diagnostic.message,diagnostics:[c.diagnostic]}};let l=c.placement;if(l.placementUnitKey!==e.targetPlacement.placementUnitKey||l.relation!==e.targetPlacement.relation)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Page-unit target placement metadata does not match the cached projection.",diagnostics:[]}};let u=l.containerSourceRange;if(!u||!l.containerSourceHash)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable container boundary.",diagnostics:[]}};let d=Cs(u),p=Rt(e.source,d);if(!p.ok||!p.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:p.ok===!1?p.diagnostic.message:"Route page composition target container could not be resolved.",diagnostics:p.ok?[]:[Oo(p.diagnostic)]}};if(Mo(e.source,p.match.node.start??null,p.match.node.end??null)!==l.containerSourceHash)return au("Route page composition target container hash no longer matches the current source.");if(l.relation==="before"||l.relation==="after"){let g=l.anchorSourceRange,b=l.anchorSourceHash;if(!g||!b)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable anchor boundary.",diagnostics:[]}};let C=Cs(g),I=Rt(e.source,C);return!I.ok||!I.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:I.ok===!1?I.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:I.ok?[]:[Oo(I.diagnostic)]}}:Mo(e.source,I.match.node.start??null,I.match.node.end??null)!==b?au("Route page composition target anchor hash no longer matches the current source."):{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"move-node",locator:i,targetParentLocator:d,anchorLocator:C,placement:l.relation}}}}return{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"move-node",locator:i,targetParentLocator:d,placement:l.relation}}}}function au(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Oo(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function lu(e){let{projection:t}=e;return t.route!==e.routeId||t.entryFile!==e.entryFile?{code:"VERSION_STALE",message:"Cached page composition projection belongs to a different route.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Cached page composition projection belongs to a different route.",details:{expectedRouteId:e.routeId,projectedRouteId:t.route,expectedEntryFile:e.entryFile,projectedEntryFile:t.entryFile}}]}:e.composition&&!Uy(t.composition,e.composition)?{code:"VERSION_STALE",message:"Cached page composition projection belongs to a different composition.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Cached page composition projection belongs to a different composition.",details:{expectedComposition:e.composition,projectedComposition:t.composition}}]}:e.currentDocumentVersion!==e.expectedDocumentVersion||t.documentVersion!==e.currentDocumentVersion?{code:"VERSION_STALE",message:"Route page composition version is stale.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Route page composition version is stale.",details:{expectedDocumentVersion:e.expectedDocumentVersion,currentDocumentVersion:e.currentDocumentVersion,projectedDocumentVersion:t.documentVersion}}]}:null}function Uy(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function Ky(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function Jy(e,t){let n=ou.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=ou.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Cs(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function Mo(e,t,n){return t==null||n==null?null:`sha256:${jy("sha256").update(e.slice(t,n)).digest("hex")}`}function Xy(e,t){return e===null||t===null?e===t:e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}var zy=typeof Ps=="function"?Ps:Ps.default;function fu(e){if(!e.ast)return bt(e,[je("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=ex(e.ast);if(!t)return bt(e,[je("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=nx(t);if(n.length===0)return bt(e,[je("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")]);if(n.length>1)return bt(e,[je("MULTIPLE_PAGE_RETURNS","Route default export contains multiple page-level return statements",{returnCount:n.length})]);let r=rx(n[0].argument);if(!r)return bt(e,[je("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})]);if(r.isNullLiteral())return du(e,t,"virtual-route-root");if(ox(r,t))return bt(e,[je("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(ix(r,t)||sx(r)&&!e.source.includes("DESIGN_PLAN_REPLACE_ME"))return bt(e,[je("UNSUPPORTED_PAGE_SHAPE","Route default export shape does not provide a single safe placement boundary",{reason:"ambiguous-placement"})]);if(r.isJSXFragment()){let i=Kt(r);if(i.unsupported)return bt(e,[je("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);let s=As({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-fragment",source:e.source,containerPath:r,members:i.members});return Lo(e,t,s,{kind:"virtual-route-root",sourceKind:"jsx-fragment"})}if(r.isJSXElement()&&!jn(r)){let i=_s(r),s=As({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[i]});return Lo(e,t,s,{kind:"virtual-route-root",sourceKind:"jsx-element"})}if(r.isJSXElement()){let i=Kt(r);if(i.unsupported)return bt(e,[je("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);let s=i.members;if(cx(e.source,r,s))return du(e,t,"starter-placeholder");let a=As({input:e,containerKind:"jsx-container",sourceKind:"jsx-element",source:e.source,containerPath:r,members:s});return Lo(e,t,a,{kind:"jsx-container",sourceKind:"jsx-element"})}if(ax(r))return bt(e,[je("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);let o=ux({input:e,source:e.source,expression:r});return Lo(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"})}function Ns(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:je("DOCUMENT_VERSION_STALE","Placement lookup is stale for the requested document version",{expectedDocumentVersion:e.documentVersion,requestedDocumentVersion:n})};let r=e.placementByKey.get(t)??null;return r?{ok:!0,placement:r}:{ok:!1,diagnostic:je("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function uu(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:je("DOCUMENT_VERSION_STALE","Placement lookup is stale for the requested document version",{expectedDocumentVersion:e.documentVersion,requestedDocumentVersion:n})};let r=e.placementUnitByKey.get(t)??null;return r?{ok:!0,placement:r}:{ok:!1,diagnostic:je("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function pu(e){return e.ok?Wy(e.projection):Hy(e.projection)}function Wy(e){let t=new Map,n=[];for(let l of e.placements)l.members.length===0&&e.placements.length>1||l.members.length>0&&!l.anchorSourceRange||t.has(l.placementUnitKey)||t.set(l.placementUnitKey,l);let r=new Map,o=new Map;for(let[l,u]of t){let d=u.members.flatMap((b,C)=>mu(e,u,b,C,e.container.placementKey)),p=d.filter(({member:b})=>b.isBusinessMember).map(({sourceMember:b})=>Yy(l,b,u.independent)),m=d.length>0?d:[{sourceMember:{key:`source:${l}:empty`,kind:e.container.kind==="starter-placeholder"?"starter-placeholder":"null-return",containerKey:e.container.placementKey,label:"empty-page",sourceFile:e.entryFile,isAtomic:!0},member:null}];r.set(l,m.map(({sourceMember:b})=>b)),o.set(l,p);let g=m[0]?.sourceMember.key??l;n.push({key:l,containerKey:g,businessMemberKeys:p.map(b=>b.key),isMultiMember:u.memberCount>1})}let i=[...r.values()].flat(),s=[...o.values()].flat(),a=i[0]?.key??null,c=e.placements.map(l=>({kind:"page-composition",placementKey:l.placementKey,documentVersion:e.documentVersion,composition:e.composition,placementUnitKey:l.placementUnitKey,relation:l.relation}));return{status:"supported",version:e.version,composition:e.composition,container:Gy(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function Hy(e){let t=e.diagnostics.map(Zy);return{status:"unsupported",version:e.version,composition:e.composition,reason:Qy(e.diagnostics),diagnostics:t}}function Gy(e,t){switch(e.container.kind){case"jsx-container":return{kind:"jsx-container",key:e.container.placementKey,sourceMemberKey:t??e.container.placementKey,sourceFile:e.entryFile,componentName:e.defaultExportName??void 0};case"starter-placeholder":return{kind:"starter-placeholder",key:e.container.placementKey,sourceFile:e.entryFile};case"virtual-route-root":return{kind:"virtual-route-root",key:e.container.placementKey}}}function mu(e,t,n,r,o){let i=`source:${t.placementUnitKey}:${r}:${n.memberKey}`;return[{sourceMember:{key:i,kind:n.kind==="jsx-element"?"jsx-element":"jsx-expression",containerKey:o,label:n.label,sourceFile:e.entryFile,isAtomic:n.kind!=="jsx-element"},member:n},...n.children.flatMap((a,c)=>mu(e,t,a,c,i))]}function Yy(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function Zy(e){return{code:qy(e),message:e.message}}function Qy(e){let t=e[0];if(!t)return"UNSUPPORTED_ROUTE_STRUCTURE";switch(t.code){case"ROUTE_RETURN_NOT_FOUND":return"ROUTE_RETURN_NOT_FOUND";case"MULTIPLE_PAGE_RETURNS":return"MULTIPLE_PAGE_RETURNS";case"INDIRECT_RETURN_ONLY":return"INDIRECT_RETURN_ONLY";case"PLACEMENT_KEY_NOT_FOUND":return"RUNTIME_ANCHOR_UNRESOLVED";case"DOCUMENT_VERSION_STALE":return"VERSION_STALE";case"UNSUPPORTED_PAGE_SHAPE":return t.details?.reason==="ambiguous-placement"?"PAGE_CONTAINER_AMBIGUOUS":"UNSUPPORTED_ROUTE_STRUCTURE";default:return"UNSUPPORTED_ROUTE_STRUCTURE"}}function qy(e){switch(e.code){case"PLACEMENT_KEY_NOT_FOUND":return"RUNTIME_ANCHOR_UNRESOLVED";case"DOCUMENT_VERSION_STALE":return"VERSION_STALE";case"UNSUPPORTED_PAGE_SHAPE":return e.details?.reason==="ambiguous-placement"?"PAGE_CONTAINER_AMBIGUOUS":"UNSUPPORTED_ROUTE_STRUCTURE";default:return e.code}}function ex(e){let t=null;return zy(e,{ExportDefaultDeclaration(n){let r=n.get("declaration");if(r.isArrowFunctionExpression()||r.isFunctionDeclaration()||r.isFunctionExpression()){t=r,n.stop();return}if(!r.isIdentifier())return;let o=n.scope.getBinding(r.node.name);if(!o)return;let i=tx(o.path);i&&(t=i,n.stop())}}),t}function tx(e){if(e.isArrowFunctionExpression()||e.isFunctionDeclaration()||e.isFunctionExpression())return e;if(e.isVariableDeclarator()){let t=e.get("init");if(t.isArrowFunctionExpression()||t.isFunctionExpression())return t}return null}function nx(e){if(e.isArrowFunctionExpression()){let r=e.get("body");if(!r.isBlockStatement())return[{argument:r}]}let t=e.get("body");if(!t.isBlockStatement())return[];let n=[];return t.traverse({Function(r){r.node!==e.node&&r.skip()},ReturnStatement(r){n.push({argument:r.get("argument")})}}),n}function rx(e){if(!e.node)return null;let t=e;for(;;){if(t.isParenthesizedExpression()){t=t.get("expression");continue}if(t.isTSAsExpression()||t.isTSTypeAssertion()){t=t.get("expression");continue}if(t.isTSNonNullExpression()||t.isTypeCastExpression()){t=t.get("expression");continue}break}return t.isExpression()?t:null}function ox(e,t){if(e.isIdentifier())return Bo(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return Bo(n.node.name,t)}return!1}function ix(e,t){return e.isConditionalExpression()?Ut(e.get("consequent"),t)||Ut(e.get("alternate"),t):e.isLogicalExpression()?Ut(e.get("left"),t)||Ut(e.get("right"),t):!1}function sx(e){if(!e.isJSXElement()||!jn(e))return!1;let t=Kt(e).members;if(t.length!==1)return!1;let n=t[0];return n.kind==="jsx-element"&&!n.isBusinessMember&&n.businessMemberCount>0}function Ut(e,t){if(e.isIdentifier())return Bo(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return Bo(n.node.name,t)}return e.isConditionalExpression()?Ut(e.get("consequent"),t)||Ut(e.get("alternate"),t):e.isLogicalExpression()?Ut(e.get("left"),t)||Ut(e.get("right"),t):!1}function Bo(e,t){let n=t.scope.getBinding(e);if(!n)return!1;let r=n.path;if(r.isFunctionDeclaration()||r.isFunctionExpression()||r.isArrowFunctionExpression())return!0;if(r.isVariableDeclarator()){let o=r.get("init");return o.isFunctionExpression()||o.isArrowFunctionExpression()}return!1}function ax(e){return e.isJSXSpreadChild()}function cx(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&Fs(t)}function Fs(e){for(let t of e.get("children")){if(t.isJSXText()){if(t.node.value.trim())return!1;continue}if(t.isJSXExpressionContainer()){let n=t.get("expression");if(n.isJSXEmptyExpression()||n.isNullLiteral())continue;return!1}if(t.isJSXFragment()){if(!Fs(t))return!1;continue}if(t.isJSXElement()&&!Fs(t))return!1}return!0}function Kt(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:Os(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:st(r.node.loc),businessMemberCount:0,parentSourceRange:st(e.node.loc),children:[],isBusinessMember:!1,label:"text"});continue}if(r.isJSXExpressionContainer()){let o=r.get("expression");if(o.isJSXEmptyExpression()||o.isNullLiteral())continue;if(o.isJSXFragment()){let i=Kt(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=jn(o)?Kt(o):null;n||=i?.unsupported??!1,t.push({..._s(o,i?.members),sourceRange:st(r.node.loc),parentSourceRange:st(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:Os(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:st(r.node.loc),businessMemberCount:1,parentSourceRange:st(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&gu(r)){let o=Kt(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=jn(r)?Kt(r):null;n||=o?.unsupported??!1,t.push({..._s(r,o?.members),parentSourceRange:st(e.node.loc)})}}return{members:t,unsupported:n}}function _s(e,t){let n=e.isJSXElement()&&jn(e)?t??Kt(e).members:[],r=e.isJSXElement()&&!jn(e)&&!gu(e);return{memberKey:Os(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:st(e.node.loc),businessMemberCount:r?1:hu(n),parentSourceRange:st(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:lx(e)}}function gu(e){if(e.isJSXFragment())return!0;let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name==="Fragment"||t.type==="JSXMemberExpression"&&t.object.type==="JSXIdentifier"&&t.object.name==="React"&&t.property.name==="Fragment"}function jn(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name!=="Fragment"&&t.name[0]===t.name[0]?.toLowerCase()}function lx(e){if(e.isJSXFragment())return"Fragment";let t=e.node.openingElement.name;if(t.type==="JSXIdentifier")return t.name;if(t.type==="JSXMemberExpression"){let n=t.object;return`${n.type==="JSXIdentifier"?n.name:"member"}.${t.property.name}`}return t.name.name}function hu(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function jo(e){return e.length===0?0:Math.max(1,hu(e))}function As(e){let t=st(e.containerPath.node.loc),n=xu(e.source,e.containerPath.node.start,e.containerPath.node.end),r=qe(e.input,e.containerKind,e.sourceKind,t),o=qe(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:jo(e.members)<=1,memberCount:jo(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function ux(e){let t=st(e.expression.node.loc),n=xu(e.source,e.expression.node.start,e.expression.node.end),r=qe(e.input,"virtual-route-root","atomic-expression",t),o=qe(e.input,"virtual-route-root","placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:!0,memberCount:1,sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:[{memberKey:qe(e.input,"virtual-route-root","atomic-member",t),kind:"atomic-expression",nodeType:e.expression.node.type,sourceRange:t,businessMemberCount:1,parentSourceRange:null,children:[],isBusinessMember:!0,label:e.expression.node.type}]}}function Lo(e,t,n,r){let o=n.containerSourceRange??n.sourceRange,i=dx(e,n,o),s=as(i),a={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:bu(t),container:{kind:r.kind,placementKey:n.placementKey,placementUnitKey:n.placementUnitKey,version:e.version,isEmptyPage:n.memberCount===0,sourceKind:r.sourceKind,sourceRange:o,sourceHash:n.sourceHash},placements:i,diagnostics:[],placementByKey:new Map,unitByKey:new Map,placementsByUnitKey:new Map,placementUnitByKey:new Map};return Object.defineProperties(a,{placementByKey:{value:s.placementByKey,enumerable:!1},unitByKey:{value:s.unitByKey,enumerable:!1},placementsByUnitKey:{value:s.placementsByUnitKey,enumerable:!1},placementUnitByKey:{value:s.sourcePlacementByUnitKey,enumerable:!1}}),{ok:!0,projection:a}}function dx(e,t,n){if(t.members.length===0)return[t];let r=[],o=(l,u,d,p,m,g,b=n)=>({...t,placementKey:u,placementUnitKey:d,containerKey:t.placementKey,independent:jo(g)<=1,memberCount:jo(g),sourceRange:p,sourceHash:p?Ts(e.source,p):null,relation:l,containerSourceRange:b,containerSourceHash:b?Ts(e.source,b):null,anchorSourceRange:m,anchorSourceHash:m?Ts(e.source,m):null,members:g}),i=t.placementKey,s=t.members.map(l=>qe(e,i,"placement-unit",l.sourceRange)),a=s[0]??t.placementUnitKey,c=s.at(-1)??t.placementUnitKey;r.push(o("prepend",qe(e,i,"prepend",n),a,n,null,[]));for(let l of t.members){let u=l.parentSourceRange??n,d=qe(e,i,"placement-unit",l.sourceRange);r.push(o("before",qe(e,d,"before",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u)),r.push(o("after",qe(e,d,"after",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u))}return r.push(o("append",i,c,n,null,[])),r}function du(e,t,n){let r=qe(e,n,"empty-container",void 0),o=qe(e,n,"empty-unit",void 0),i={placementKey:r,placementUnitKey:o,version:e.version,containerKey:r,independent:!0,memberCount:0,sourceRange:null,sourceHash:null,relation:"append",containerSourceRange:null,containerSourceHash:null,anchorSourceRange:null,anchorSourceHash:null,members:[]},s=as([i]),a={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:bu(t),container:{kind:n,placementKey:r,placementUnitKey:o,version:e.version,isEmptyPage:!0,sourceKind:n==="starter-placeholder"?"starter-placeholder":"jsx-fragment",sourceRange:null,sourceHash:null},placements:[i],diagnostics:[],placementByKey:new Map,unitByKey:new Map,placementsByUnitKey:new Map,placementUnitByKey:new Map};return Object.defineProperties(a,{placementByKey:{value:s.placementByKey,enumerable:!1},unitByKey:{value:s.unitByKey,enumerable:!1},placementsByUnitKey:{value:s.placementsByUnitKey,enumerable:!1},placementUnitByKey:{value:s.sourcePlacementByUnitKey,enumerable:!1}}),{ok:!0,projection:a}}function bt(e,t){return{ok:!1,projection:{status:"unsupported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,diagnostics:t}}}function je(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function qe(e,t,n,r){return yu([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function Os(e,t,n){return yu(["member",e,String(t??-1),String(n??-1)])}function yu(e){return`pc_${Ms("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function xu(e,t,n){return t==null||n==null?null:`sha256:${Ms("sha256").update(e.slice(t,n)).digest("hex")}`}function Ts(e,t){let n=[0];for(let i=0;i<e.length;i+=1)e.charCodeAt(i)===10&&n.push(i+1);let r=n[t.startLine-1],o=n[t.endLine-1];return r===void 0||o===void 0?null:`sha256:${Ms("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function st(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function bu(e){if(e.isFunctionDeclaration())return e.node.id?.name??null;let t=e.parentPath;return t?.isVariableDeclarator()&&t.node.id.type==="Identifier"?t.node.id.name:null}function px(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var mx=160;function Su(e,t,n,r={}){let o=Pn(e),i=[];for(let[s,a]of e.elements){let c=n.get(s),l={canUpdateText:r.canUpdateTextByKey?.get(s)??c?.canUpdateText??!1,canInsertChild:c?.canInsertChild??!1,canMove:c?.canMove??!1,canRemove:c?.canRemove??!1};i.push({key:s,tag:a.tag,label:a.tag===a.componentName?a.tag:`${a.tag} (${a.componentName})`,parentKey:a.parentKey,childKeys:[...a.childKeys],operationSummary:l,...r.dynamicDataSummaryByKey?.get(s)?{dynamicDataSummary:r.dynamicDataSummaryByKey.get(s)}:{}})}return{composition:o,routeId:e.routeId,version:e.version,rootKeys:[...e.rootKeys],entries:i}}function Eu(e,t,n,r,o,i,s,a,c,l,u,d,p){let m=Pn(t),g=t.elements.get(e),b=n.nodes.get(e),C=r.get(e);if(!g||!b||!C)throw new Error(`Node not found: ${e}`);let I=Ru(g.textSegments,s),w=wu(e,t,g,C,I),A=I?yx(I):void 0,O=xx(i,I),ie=g.textSegments.map(M=>({index:M.index,value:M.value,editable:Nu(M,C,s?.get(M.index)??null),source:o.get(M.index)??null})),oe=ku(g,t),N=g.childKeys.map(M=>{let j=t.elements.get(M);return j?{key:M,tag:j.tag,label:j.tag}:null}).filter(M=>M!==null),W=[];if(g.parentKey){let M=t.elements.get(g.parentKey);if(M)for(let j of M.childKeys){if(j===e)continue;let Q=t.elements.get(j);Q&&W.push({key:j,tag:Q.tag,label:Q.tag})}}return{composition:m,key:e,tag:g.tag,componentName:g.componentName,sourceFile:g.sourceFile,sourceLocator:Iu(g),label:g.tag,capabilities:w,writeTarget:i,effectiveWriteTarget:O,provenanceChain:A,componentSemantic:c,contentModel:l,mediaModel:u,styleSource:d,conditional:a,...p?{dynamicData:p}:{},textSegments:ie,boundaryKind:g.boundaryKind,isOpaque:g.isOpaque,ancestors:oe,children:N,siblings:W}}function vu(e,t,n,r,o,i,s,a){let c=Pn(t),l=t.elements.get(e),u=n.nodes.get(e),d=r.get(e);if(!l||!u||!d)throw new Error(`Node not found: ${e}`);let p=Ru(l.textSegments,i);return{composition:c,key:e,tag:l.tag,componentName:l.componentName,sourceFile:l.sourceFile,sourceLocator:Iu(l),label:l.tag,capabilities:wu(e,t,l,d,p),provenanceChain:p?{editMode:p.editMode,diagnostics:p.diagnostics.map(m=>({code:m.code,message:m.message}))}:void 0,...s?{dynamicData:s}:{},...a?{properties:a}:{},textSegments:l.textSegments.map(m=>{let g=o.get(m.index);return{index:m.index,editable:Nu(m,d,i?.get(m.index)??null),source:g?{kind:g.kind}:null}}),boundaryKind:l.boundaryKind,isOpaque:l.isOpaque,ancestors:ku(l,t)}}function Iu(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:gx(e.sourceRange),structuralPath:e.identity.structuralPath,...hx(e.textSegments)}}function ku(e,t){let n=[],r=e.parentKey;for(;r;){let o=t.elements.get(r);if(!o)break;n.push({key:r,tag:o.tag,label:o.tag}),r=o.parentKey}return n.reverse(),n}function gx(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function hx(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,mx)}:{}}function Cu(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 Ru(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function wu(e,t,n,r,o){let i=n.identity.structuralPath.includes("#repeat:"),s=t.regions.some(u=>u.kind==="repeat-region"&&u.childKeys.includes(e)),a=o?.diagnostics.find(u=>u.code==="missing-adapter"||u.code==="external-source-readonly")?.code,c=r.canUpdateText?{mode:o?.editMode??"direct",reasonCode:a??(o?.editMode==="upstream"?"component-prop":o?.finalSource?.kind==="repeat-template"?"repeat-item-data":void 0)}:{mode:"unsupported",reasonCode:"capability-denied"},l=r.canUpdateText&&Pu(c.mode);return{...r,canUpdateText:l,editModes:{updateText:c,insertChild:r.canInsertChild?{mode:"direct",reasonCode:i||s?"repeat-template":void 0}:{mode:"unsupported",reasonCode:"capability-denied"},move:r.canMove?{mode:s?"proxy":"direct",reasonCode:s?"repeat-collection":void 0}:{mode:"unsupported",reasonCode:"capability-denied"},remove:r.canRemove?{mode:s?"proxy":"direct",reasonCode:s?"repeat-collection":void 0}:{mode:"unsupported",reasonCode:"capability-denied"}}}}function Nu(e,t,n){return!e.editable||!t.canUpdateText?!1:n?Pu(n.editMode):!0}function Pu(e){return e==="direct"||e==="proxy"||e==="upstream"}function yx(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 xx(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}:px(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 Au(e){let{key:t,element:n,graph:r,provenances:o}=e,i=Sx(t,n,r),s=i?.tag??(cn(n.tag)?n.tag:n.componentName),a=i?.identity.key??Tu(n,r)??t,c=Ix(i),l=kx(t,n,r,o,i),u=bx(t,n,r,o,a);return{componentName:s,instanceKey:a,templateOwner:vx(i??n,s),...c.length>0?{variantKeys:c}:{},...l.length>0?{slotKeys:l}:{},editableStrategy:u,impactScope:Cx(u),alternativeStrategies:Rx(u)}}function bx(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return Ds(e,n)?"instance":!cn(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function Tu(e,t){if(cn(e.tag))return e.identity.key;let n=[...t.elements.values()].filter(r=>r.importedFrom===e.sourceFile&&Ex(r,e.componentName));return n.length!==1?null:n[0].identity.key}function Sx(e,t,n){if(cn(t.tag))return t;let r=Ds(e,n);if(r)return r;let o=Tu(t,n);return o?n.elements.get(o)??null:null}function Ex(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function vx(e,t){return cn(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function Ix(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 kx(e,t,n,r,o){let i=new Set,s=Ds(e,n);s&&o?.identity.key===s.identity.key&&i.add("children");for(let a of r.values()){let c=a?.chain.find(u=>u.kind==="component-prop");if(!c)continue;let l=c.displayName.split(".").pop();l&&i.add(l)}return i.size===0&&cn(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function Ds(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(cn(r.tag))return r;n=r.parentKey}return null}function cn(e){return/^[A-Z]/.test(e)}function Cx(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function Rx(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}var wx=new Set(["markdown","body","content","value","document"]),Fu=[];function Ou(e){if(!(!Ax(e.tag)||!e.attributes))for(let t of e.attributes){if(!wx.has(t.name))continue;if(Px(t))return{kind:"markdown",field:t.name,schema:"markdown",valuePath:t.source?.expression,operationBoundary:Fu};let n=Nx(t.resolvedValue);if(n==="prosemirror-doc"||n==="node-array")return{kind:"rich-text-json",field:t.name,valuePath:t.source?.expression,schema:n,operationBoundary:Fu};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 Nx(e){if(e){if(Array.isArray(e)&&e.every(t=>_u(t)))return"node-array";if(_u(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 _u(e){return!Array.isArray(e)&&typeof e=="object"&&e!==null}function Px(e){return e.name==="markdown"}function Ax(e){return/^[A-Z]/.test(e)}var Tx=["src","alt","poster","caption","width","height"];function Mu(e){let t=e.attributes?.filter(s=>Tx.includes(s.name))??[];if(t.length===0)return;let n=t.map(s=>s.name),r=t.filter(s=>s.resolution&&s.resolution.status!=="resolved"),o=Object.fromEntries(t.filter(s=>s.source?.expression).map(s=>[s.name,s.source.expression])),i=_x(t.filter(s=>!s.resolution||s.resolution.status==="resolved").map(s=>s.value));return{kind:Fx(e.tag,n),sourceType:i,fields:n,editableFields:[],operationBoundary:[],...Object.keys(o).length>0?{valuePaths:o}:{},...r.length>0?{diagnostics:r.map(s=>({code:"unsupported-field",field:s.name,message:`Media attribute '${s.name}' has an unresolved source value`}))}:{}}}function Fx(e,t){return e==="img"?"image":e==="video"||t.includes("poster")?"video":"media"}function _x(e){return e.some(t=>t.startsWith("cms:"))?"cms-media-field":e.some(t=>/^(\.?\/|\/)/.test(t))?"local-file-reference":"asset-id"}var Ls=["set-class-name-source","apply-style-draft"];function Du(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:Ls,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element"}]};if(t.resolution&&t.resolution.status!=="resolved")return{kind:"class-name-source",className:"",sourceKind:"dynamic-expression",editable:!1,operationBoundary:[],sourcePath:t.source?.expression,diagnostics:[{code:"dynamic-binding",message:"Style binding is unresolved and cannot be edited"}]};if(t.source?.expression){let n=t.source.expression,r=typeof t.resolvedValue=="string"?t.resolvedValue:t.value!==n?t.value:void 0;return typeof r!="string"?{kind:"class-name-source",className:"",sourceKind:"dynamic-expression",editable:!1,operationBoundary:[],sourcePath:n,diagnostics:[{code:t.resolvedValue===void 0?"dynamic-binding":"non-string-binding",message:t.resolvedValue===void 0?"Style binding is dynamic and cannot be edited":"Style binding must resolve to a static string before it can be edited"}]}:{kind:"class-name-source",className:r,sourceKind:"static-expression",editable:!0,operationBoundary:Ls,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:Ls}}import{createHash as Ox}from"node:crypto";var ur=class{constructor(t){this.original=new Map,this.files=new Map,this.versions=new Map;for(let n of t)this.original.set(n.path,n.content),this.files.set(n.path,n.content),this.versions.set(n.path,n.version??1)}async readFile(t){let n=this.files.get(t);if(n===void 0)throw new Error(`Snapshot file not found: ${t}`);return n}async readFileBytes(t){return Buffer.from(await this.readFile(t),"utf8")}async getFileInfo(t){let n=this.files.get(t);return n===void 0?null:{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async writeFile(t,n){this.files.set(t,n)}async createExclusive(t,n){if(this.files.has(t))throw Object.assign(new Error(`Snapshot file already exists: ${t}`),{code:"EEXIST"});this.files.set(t,n)}async deleteFile(t){this.files.delete(t)}async exists(t){return this.files.has(t)}async listFiles(t={}){let n=t.roots??[],r=[...this.files.keys()].filter(a=>n.length===0?!0:n.some(c=>a===c||a.startsWith(`${c}/`))),o=[],i=new Set,s=0;for(let a of r.sort()){let c=Buffer.byteLength(this.files.get(a)??"","utf8"),l=a.split("/").length;if(t.maxDepth!==void 0&&l>t.maxDepth){i.add("max-depth");continue}if(t.maxFiles!==void 0&&o.length>=t.maxFiles){i.add("max-files");break}if(t.maxTotalBytes!==void 0&&s+c>t.maxTotalBytes){i.add("max-total-bytes");break}o.push({path:a,sizeBytes:c}),s+=c}return i.size>0?{files:o,truncated:{reasons:[...i]}}:{files:o}}getVersion(t){return this.versions.get(t)??0}bumpVersion(t){let n=this.getVersion(t)+1;return this.versions.set(t,n),n}getChangedFiles(){let t=new Set([...this.original.keys(),...this.files.keys()]),n=[];for(let r of[...t].sort()){let o=this.original.get(r),i=this.files.get(r);o!==i&&n.push({path:r,before:o,after:i})}return n}};function fe(e){return`sha256:${Ox("sha256").update(e).digest("hex")}`}function Bs(e){let t=e.route.graph.elements.get(e.key);if(!t)return{key:e.key,composition:e.route.composition,filePath:"",componentName:"",sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,openingElementRange:{start:0,end:0},version:{documentVersion:e.route.graph.version,contentHash:fe(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=Mx(e.route.source,t);if(!n)return{key:e.key,composition:e.route.composition,filePath:t.sourceFile,componentName:t.componentName,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,openingElementRange:{start:0,end:0},version:{documentVersion:e.route.graph.version,contentHash:fe(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Unable to locate JSX element for key ${t.identity.key}`}]};let r=n.openingElement,o=r.attributes.find(c=>c.type==="JSXAttribute"&&c.name.type==="JSXIdentifier"&&c.name.name==="className"),i={key:e.key,composition:e.route.composition,filePath:t.sourceFile,componentName:t.componentName,openingElementRange:Bu(r),version:{documentVersion:e.route.graph.version,contentHash:fe(e.route.source)}};if(!o)return{...i,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element."}]};let s=o.value,a=s?.type==="StringLiteral"?"stringLiteral":"expression";return{...i,sourceKind:a,attrRaw:Lu(e.route.source,o),valueRaw:s?Lu(e.route.source,s):null,attrRange:Bu(o),diagnostics:[]}}function ju(e){let{source:t,oldAttrRange:n,openingElementRange:r,newAttrRaw:o}=e;if(n){let a=n.start>0&&/\s/.test(t[n.start-1]??"")?n.start-1:n.start,c=o?`${a<n.start?" ":""}${o}`:"";return t.slice(0,a)+c+t.slice(n.end)}if(!o)return t;let i=r.end,s=t.slice(Math.max(0,i-2),i)==="/>"?i-2:i-1;return t.slice(0,s)+` ${o}`+t.slice(s)}function Mx(e,t){let n=yt({source:e,profile:rn({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=ne(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:Dx(t.sourceRange)});return!r.ok||r.match.node.type!=="JSXElement"?null:r.match.node}function $u(e){let t=yt({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 Lu(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function Bu(e){if(e.start==null||e.end==null)throw new Error("AST node does not include offsets.");return{start:e.start,end:e.end}}function Dx(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}import*as ra from"@babel/parser";import Xs from"@babel/traverse";import*as S from"@babel/types";import*as At from"node:path";import*as Xu from"@babel/parser";import Vs from"@babel/traverse";import*as $n from"@babel/types";import*as Y from"@babel/types";function Uo(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?$o(n,t):null}if(e.isMemberExpression()){let n=Ux(e.node),r=Lx(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?$o(o,[...r,...t]):null}return e.isAwaitExpression()||$s(e.node)?Jt(Jx(e.node),t,"awaited or fetched expression"):null}function Lx(e){let t=[],n=e;for(;Y.isMemberExpression(n);){if(n.computed)if(Y.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(Y.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(Y.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return Y.isIdentifier(n)?t:null}function $o(e,t=[]){let n=Bx(e,t);if(n)return n;let r=jx(e,t);if(r)return r;let o=$x(e,t);return o||null}function fr(e){return e?.kind==="api-source"}function Bx(e,t){if(e.path.isVariableDeclarator()&&Y.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&js(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return Jt(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&Y.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(c=>Y.isObjectProperty(c)&&Ku(c)==="data"&&dr(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&js(a.node))return Jt(e.identifier.name,t,"query hook data binding")}let n=Vx(e);if(!n||Ku(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()||!js(i.node)?null:Jt(e.identifier.name,t,"query hook data binding")}function jx(e,t){if(e.path.isVariableDeclarator()&&Y.isArrayPattern(e.path.node.id)){let a=e.path.get("init");if(!a?.isCallExpression()||!Uu(a.node))return null;let[c,l]=e.path.node.id.elements;return!Y.isIdentifier(c)||c.name!==e.identifier.name||!Y.isIdentifier(l)?null:Vu(e,l.name)?Jt(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()||!Uu(o.node)||n.node.elements.findIndex(a=>a===e.path.node)!==0)return null;let s=n.node.elements[1];return Y.isIdentifier(s)&&Vu(e,s.name)?Jt(e.identifier.name,t,"state setter is updated by API data"):null}function $x(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()?Jt(e.identifier.name,t,"awaited binding result"):$s(r.node)?Jt(e.identifier.name,t,"fetch-backed binding result"):null:null}function Vx(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 dr(e,t){return Y.isIdentifier(e)?e.name===t:Y.isAssignmentPattern(e)?dr(e.left,t):Y.isObjectPattern(e)?e.properties.some(n=>Y.isObjectProperty(n)?dr(n.value,t):dr(n.argument,t)):Y.isArrayPattern(e)?e.elements.some(n=>!!n&&dr(Y.isRestElement(n)?n.argument:n,t)):!1}function Vu(e,t){let n=!1,r=!1;return e.scope.path.traverse({CallExpression(i){$s(i.node)&&(n=!0),(Kx(i.node.callee,t)||i.node.arguments.some(s=>Y.isIdentifier(s)&&s.name===t))&&(r=!0)}}),n&&r}function js(e){let t=Ko(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function Uu(e){return Ko(e.callee)==="useState"}function $s(e){return Vo(e,t=>Y.isCallExpression(t)&&Ko(t.callee)==="fetch")}function Ux(e){let t=e;for(;Y.isMemberExpression(t);)t=t.object;return Y.isIdentifier(t)?t.name:null}function Ku(e){return e.computed?null:Y.isIdentifier(e.key)?e.key.name:Y.isStringLiteral(e.key)?e.key.value:null}function Ko(e){return Y.isIdentifier(e)?e.name:Y.isMemberExpression(e)&&Y.isIdentifier(e.property)?e.property.name:null}function Kx(e,t){return Vo(e,n=>Y.isIdentifier(n)&&n.name===t)}function Vo(e,t){if(t(e))return!0;let n=Y.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(Y.isNode(i)&&Vo(i,t))return!0;continue}if(Y.isNode(o)&&Vo(o,t))return!0}return!1}function Jx(e){return Y.isIdentifier(e)?e.name:Y.isCallExpression(e)?Ko(e.callee)??"api":Y.isAwaitExpression(e)?"awaited-api":"api"}function Jt(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:Xx(e,t),reason:n}}function Xx(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var zu=typeof Vs=="function"?Vs:Vs.default;function Wu(e,t){let n=Gu(e);if(!n)return{allowed:!0};let r=!1;return zu(n,{CallExpression(o){if(!Yu(o.node,t.sourceRange)||!zx(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||fr(Uo(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function Hu(e,t){let n=Gu(e);if(!n)return{allowed:!0};let r=!1;return zu(n,{JSXExpressionContainer(o){Yu(o.node,t.sourceRange)&&($n.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 Gu(e){try{return Xu.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function zx(e){let t=e.callee;return $n.isMemberExpression(t)&&$n.isIdentifier(t.property)&&t.property.name==="map"}function Yu(e,t){let n=e.loc;return n?Ju({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&Ju({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function Ju(e,t){return e.line!==t.line?e.line<t.line?-1:1:e.column!==t.column?e.column<t.column?-1:1:0}import*as le from"@babel/types";function Zu(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 St(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return ln(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(le.isObjectPattern(n)||le.isArrayPattern(n))return ln(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(Hx(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function ln(e,t,n=!1){return le.isIdentifier(e)?e.name===t&&n:le.isObjectPattern(e)?e.properties.some(r=>le.isObjectProperty(r)?ln(r.value,t,n):ln(r.argument,t,n)):le.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=le.isRestElement(r)?r.argument:r;return ln(o,t,n)}):le.isAssignmentPattern(e)?ln(e.left,t,!0):le.isRestElement(e)?ln(e.argument,t,n):!1}function Vn(e,t){if(e.path.isObjectPattern()){if(t){let r=at(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:St(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:St(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=Qu(r),i=!1,s=o?o.initBinding&&Us(o.initBinding)?(i=St(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=Vn(o.initBinding,{kind:"identifier",expression:o.initBinding.identifier.name,base:o.initBinding.identifier.name,path:[]});return i=c?.hasDefault??!1,c?[{kind:"property",name:c.propName},...c.remainingPath,...o.initPathPrefix]:null})():null:null,a=at(e.path.node.id,e.identifier.name);if(s&&a){let c=[...s,...a],[l,...u]=c;return!l||l.kind!=="property"?null:{propName:l.name,remainingPath:[...u,...t?.path??[]],hasDefault:i||St(e)}}}}let n=Zx(e);if(n){let r=Wx(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||St(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=Gx(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:St(e)}}let i=pr(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:St(e)}:null}if(Us(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:St(e)}}return null}function Wx(e,t){let n=e.findParent(u=>u.isVariableDeclarator());if(!n?.isVariableDeclarator())return null;let r=n.get("init");if(!r?.isExpression())return null;let o=Qu(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=Us(i)?(a=St(i),[...s]):(()=>{let u=Vn(i,{kind:"identifier",expression:i.identifier.name,base:i.identifier.name,path:[]});return a=u?.hasDefault??!1,u?[{kind:"property",name:u.propName},...u.remainingPath,...s]:null})();if(!c)return null;let l=at(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||St(t)}:null}function Qu(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=Qx(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function Us(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function Hx(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Gx(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=at(i.node,t);if(a)return a}return null}function qu(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=Jo(a,e.identifier.name);if(c&&(!n||c.propName===n))return{propName:c.propName,componentName:t,expressionPath:c.expressionPath,displayPath:`${t}.${c.propName}.default`}}}if(e.path.isObjectPattern())for(let a of e.path.get("properties")){if(!a.isObjectProperty())continue;let c=pr(a.node);if(!c||n&&c!==n)continue;let l=a.get("value");if(!l.isAssignmentPattern())continue;let u=l.get("right");if(u.isExpression())return{propName:c,componentName:t,expressionPath:u,displayPath:`${t}.${c}.default`}}let r=Yx(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=pr(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 Jo(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=pr(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&at(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=Jo(o,t);if(i)return i}}else if(n.isRestElement()){let r=n.get("argument");if(!Array.isArray(r)&&(r.isObjectPattern()||r.isArrayPattern())){let o=Jo(r,t);if(o)return o}}}if(e.isArrayPattern())for(let n of e.get("elements")){if(!n)continue;let r=n.isRestElement()&&!Array.isArray(n.get("argument"))?n.get("argument"):n;if(!Array.isArray(r)&&(r.isObjectPattern()||r.isArrayPattern())){let o=Jo(r,t);if(o)return o}}return null}function at(e,t,n=[]){if(le.isIdentifier(e))return e.name===t?n:null;if(le.isObjectPattern(e)){for(let r of e.properties)if(le.isObjectProperty(r)){let o=pr(r);if(!o)continue;let i=at(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(le.isRestElement(r)){let o=at(r.argument,t,n);if(o)return o}}if(le.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=le.isRestElement(o)?o.argument:o,s=at(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return le.isAssignmentPattern(e)?at(e.left,t,n):null}function Yx(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function Zx(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 pr(e){return e.computed?null:le.isIdentifier(e.key)?e.key.name:le.isStringLiteral(e.key)?e.key.value:null}function Qx(e){let t=[],n=e;for(;le.isMemberExpression(n);){if(n.computed)if(le.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(le.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(le.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return le.isIdentifier(n)?{base:n.name,path:t}:null}import{SiteEditSetPropsParamsSchema as rb}from"@vcp-dev/contracts";import*as Et from"@babel/types";import{SiteEditSetPropsParamsSchema as qx}from"@vcp-dev/contracts";function ed(e){let t=e.changes??(e.change?[e.change]:[]);if(!qx.safeParse({kind:"set-props",scope:"selection",changes:t}).success)return mr("invalid-change","Repeat property changes are invalid");if(t.length!==1||t[0].name!==e.target.propertyName)return mr("target-mismatch","A repeat property plan must contain exactly one change for its target property");let r=t[0];if(r.operation==="remove"&&e.target.propertyState==="missing")return{ok:!0,steps:[]};let o=ge(e.source,"value");if(!o.ok)return mr("invalid-target","Repeat property source could not be parsed");let i=[{type:"set-property-binding",order:0,file:e.target.templateFile,locator:e.target.targetElementLocator,name:r.name,object:e.target.callbackItemName,property:r.name}];for(let[s,a]of e.target.parentObjectLocators.entries()){let c=ne(o.ast,a);if(!c.ok||!c.match.path.isObjectExpression())return mr("unsupported-object",`Repeat item ${s} is not a writable object expression`);let l=s===e.target.sourceItemIndex?eb(r):tb(c.match.path.node,r.name);if(!l)return mr("unsupported-property-value",`Repeat item ${s} has an unsupported value for '${r.name}'`);i.push({type:"upsert-object-property",order:i.length,file:e.target.sourceFile,locator:a,name:r.name,value:l})}return{ok:!0,steps:i}}function eb(e){return e.operation==="set"?{kind:"value",value:e.value}:{kind:"undefined"}}function tb(e,t){let n=e.properties.filter(i=>Et.isObjectProperty(i)&&nb(i.key)===t);if(n.length>1)return null;let r=n[0];if(!r)return{kind:"undefined"};if(!Et.isExpression(r.value))return null;let o=ht(r.value);return o.status==="undefined"?{kind:"undefined"}:o.status!=="resolved"?null:{kind:"value",value:o.value}}function nb(e){return Et.isIdentifier(e)?e.name:Et.isStringLiteral(e)?e.value:Et.isNumericLiteral(e)?String(e.value):null}function mr(e,t){return{ok:!1,errorCode:e,reason:t}}function td(e){if(e.change.name!=="className"&&e.change.name!=="class")return gr("unsupported-owner",`No specialized property owner is available for '${e.change.name}'`);let t=e.classNameSource;if(!t||t.filePath!==e.node.file)return gr("owner-source-unavailable","className source details are unavailable for the selected node");if(e.change.name==="class"&&t.sourceKind==="missing")return gr("owner-source-unavailable","The class alias requires an existing className source");if(t.sourceKind==="expression")return gr("owner-source-dynamic","Dynamic className expressions are not writable by the generic property owner");if(e.change.operation==="set"&&typeof e.change.value!="string")return gr("owner-value-invalid","The className owner accepts only string values");if(e.change.operation==="remove"&&t.sourceKind==="missing")return{ok:!0,steps:[]};let n=t.sourceKind==="missing",r=e.change.operation==="set"?`className=${JSON.stringify(e.change.value)}`:null,o=e.change.operation==="remove"?"remove-attribute":n?"create-attribute":"replace-static-classname";return{ok:!0,steps:[{type:"set-class-name-source",order:0,file:e.node.file,request:{kind:"set-class-name-source",key:e.node.key,filePath:e.node.file,expectedVersion:t.version,oldAttrRaw:t.attrRaw,oldAttrRange:t.attrRange,openingElementRange:t.openingElementRange,newAttrRaw:r,intent:{source:"style-panel",operation:o}}}]}}function gr(e,t){return{ok:!1,errorCode:e,reason:t}}async function od(e){let t=rb.safeParse({kind:"set-props",scope:e.scope,changes:e.changes});if(!t.success)return Nt("invalid-change","Typed property changes are invalid");let n=[];for(let r of t.data.changes){let o=await ob(e,r);if(o){if(!o.ok)return Nt("owner-plan-failed",o.reason);nd(n,o.steps);continue}let i=await e.getPropertyState(e.node.key,r.name,e.selectionRef);if(!i)return Nt("missing-property-state",`No authoritative property state is available for '${r.name}'`);if(i.status==="blocked")return Nt("readonly-property",i.diagnostic?.message??`Property '${r.name}' is not writable`);if(!cb(i,r)&&!(r.operation==="remove"&&i.status==="missing")){if(i.status==="binding"){let s=i.target;if(s?.kind!=="value-binding"||!s.target.locator||e.scope!=="selection"||r.operation!=="set")return Nt("unsupported-binding",`Property '${r.name}' does not have a safe typed binding write target`);let a=s.target.locator;if(s.target.sourceKind==="repeat-template"&&e.selectionRef?.instanceIndex!==void 0){let c=ab(s.target,e.selectionRef.instanceIndex);if(!c)return Nt("unsupported-binding",`Property '${r.name}' could not resolve the selected repeat item`);a=c}Ks(n,{type:"update-value",order:n.length,file:s.target.file,locator:a,value:r.value});continue}if(e.selectionRef?.instanceIndex!==void 0&&e.getRepeatPropertyTarget){let s=await e.getRepeatPropertyTarget(e.node.key,r.name,e.selectionRef);if(s.ok){let a=ed({source:e.getFileContent(s.sourceFile),target:s,changes:[r]});if(!a.ok)return Nt("repeat-target-failed",a.reason);nd(n,a.steps);continue}if(i.status==="missing"||i.status==="direct")return Nt("repeat-target-failed",s.reason)}Ks(n,{type:"set-property-changes",order:n.length,file:e.node.file,locator:ib(e.node),scope:e.scope,changes:[r]})}}return n.forEach((r,o)=>{r.order=o}),sb(n)?Nt("step-conflict","Property changes resolve to conflicting write steps"):{ok:!0,steps:n}}async function ob(e,t){return t.name!=="className"&&t.name!=="class"?null:td({node:e.node,change:t,classNameSource:e.classNameSource})}function ib(e){return e.structuralPath.includes("#repeat:")||e.key.includes("::repeat-item#")?{kind:"jsx-node",strategy:"source-range",sourceRange:e.sourceRange}:{kind:"jsx-node",strategy:"structural-path",file:e.file,component:e.component,structuralPath:e.structuralPath,expectedRange:e.sourceRange}}function sb(e){let t=new Set;for(let n of e){let{order:r,...o}=n,i=`${n.file}:${n.type}:${JSON.stringify(o)}`;if(t.has(i))return!0;t.add(i)}return!1}function nd(e,t){for(let n of t)Ks(e,{...n,order:e.length})}function Ks(e,t){if(t.type==="set-property-changes"){let n=e.find(r=>r.type==="set-property-changes"&&r.file===t.file&&JSON.stringify(r.locator)===JSON.stringify(t.locator)&&r.scope===t.scope);if(n){n.changes.push(...t.changes);return}}e.push(t)}function ab(e,t){if(!e.locator)return null;let n=e.collectionPathMap?.length??e.collectionIndexMap?.length;if(n!==void 0&&t>=n)return null;let r=e.collectionPathMap?.[t];if(r)return rd(e.locator,r);let o=e.locator.path??[],i=o.findLastIndex(a=>a.kind==="index");if(i<0)return null;let s=o.map((a,c)=>c===i&&a.kind==="index"?{kind:"index",index:e.collectionIndexMap?.[t]??t}:a);return rd(e.locator,s)}function cb(e,t){if(t.operation!=="set"||e.status!=="direct")return!1;let n=e.attribute?.resolution;return n?.status==="resolved"?Js(n.value,t.value):e.attribute?.source===null&&e.attribute.value===t.value}function Js(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((n,r)=>Js(n,t[r]));if(e&&t&&typeof e=="object"&&typeof t=="object"){let n=e,r=t,o=Object.keys(n);return o.length===Object.keys(r).length&&o.every(i=>Js(n[i],r[i]))}return!1}function rd(e,t){return{kind:"value",root:e.root,path:t,expectedRange:e.expectedRange}}function Nt(e,t){return{ok:!1,errorCode:e,reason:t}}var Gt=typeof Xs=="function"?Xs:Xs.default;function he(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 Un(e){return{file:e.file,component:e.component}}function lb(e){return e.target.kind==="node"?e.target.key:null}function ub(e){return"kind"in e}function Xo(e){return!ub(e)}function Zs(e,t){let n=At.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=At.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function zs(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=Rt(n,he(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function oa(e){if(!e.component)return"Component";if(e.component.exportName!=="default")return e.component.exportName;let t=e.component.source.replace(/\\/g,"/").replace(/\/$/,""),n=t.split("/").pop()||"Component",i=(n==="index"?t.split("/").slice(-2,-1)[0]||"Component":n).replace(/\.[^.]+$/,"").split(/[^A-Za-z0-9]+/).filter(Boolean);return i.length===0?"Component":i.map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join("")}function et(e){try{return ra.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function db(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function fb(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 pe(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function fn(e,t){let n=pe(e);return!!(n&&ct(t,n))}function ct(e,t){return t.start>=e.start&&t.end<=e.end}function Sd(e){if(S.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(S.isJSXMemberExpression(e)){let t=e;for(;S.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function pb(e,t){let n=pe(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);if(!a||fn(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=Sd(i.node.name);s&&o(s,i)}}),[...r].sort()}function id(e,t,n){let r=et(e);if(!r)return{ok:!0};let o=ne(r,he(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=ne(r,he(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};if(Md(o.match.path,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let s=pb(o.match.path,i.match.path);return s.length>0?{ok:!1,bindingNames:s}:{ok:!0}}function sd(e,t,n){let r=Xt(t,n);return r?Pt(e,r):null}function Xt(e,t){let n=ne(e,he(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:na(e,t)}function Pt(e,t){let n=t.findParent(b=>b.isArrowFunctionExpression()||b.isFunctionExpression());if(!n||!n.isArrowFunctionExpression()&&!n.isFunctionExpression())return null;let r=n,o=r.parentPath;if(!o||!o.isCallExpression()&&!o.isOptionalCallExpression())return null;let i=o;if(i.node.arguments.findIndex(b=>b===r.node)!==0)return null;let a=i.get("callee");if(!a.isMemberExpression()&&!a.isOptionalMemberExpression())return null;let c=a.node,l=c.property;if(!S.isIdentifier(l)||l.name!=="map"||c.computed)return null;let u=a.get("object"),d=Go(e,u.node),p=r.node.params.map(b=>Go(e,b)),m=pe(i.node),g=pe(r.node);return!d||p.some(b=>b.length===0)||!m||!g?null:{callStart:m.start,callEnd:m.end,callbackStart:g.start,callbackEnd:g.end,collectionExpression:d,callbackParams:p,mapOperator:S.isOptionalMemberExpression(c)&&c.optional?"?.map":".map",collectionNeedsParens:ca(u.node),callbackPath:r,collectionPath:u}}function Go(e,t){let n=pe(t);return n?e.slice(n.start,n.end):""}function zo(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function mb(e,t){let n=pe(e.node);return n?gb(t).some(r=>{let o=pe(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function gb(e){let t=e.callbackPath.node.body;return S.isBlockStatement(t)?zt(t.body):Ht(t)}function zt(e){let t=[];for(let n of e){if(S.isReturnStatement(n)){n.argument&&t.push(...Ht(n.argument));continue}if(S.isBlockStatement(n)){t.push(...zt(n.body));continue}if(S.isIfStatement(n)){let r=S.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...zt(r)),n.alternate){let o=S.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...zt(o))}continue}if(S.isSwitchStatement(n)){for(let r of n.cases)t.push(...zt(r.consequent));continue}S.isTryStatement(n)&&(t.push(...zt(n.block.body)),n.handler&&t.push(...zt(n.handler.body.body)),n.finalizer&&t.push(...zt(n.finalizer.body)))}return t}function Ht(e){return S.isJSXElement(e)?hb(e)?ad(e.children):[e]:S.isJSXFragment(e)?ad(e.children):S.isParenthesizedExpression(e)||S.isTSAsExpression(e)||S.isTSSatisfiesExpression(e)||S.isTSNonNullExpression(e)||S.isTSTypeAssertion(e)?Ht(e.expression):S.isConditionalExpression(e)?[...Ht(e.consequent),...Ht(e.alternate)]:S.isLogicalExpression(e)&&Ld(e.operator)?Ht(e.right):[]}function ad(e){return e.flatMap(t=>S.isJSXElement(t)||S.isJSXFragment(t)?Ht(t):S.isJSXExpressionContainer(t)&&(S.isJSXElement(t.expression)||S.isJSXFragment(t.expression)||S.isConditionalExpression(t.expression)||S.isLogicalExpression(t.expression))?Ht(t.expression):[])}function hb(e){let t=e.openingElement.name;return S.isJSXIdentifier(t)?t.name==="Fragment":S.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function yb(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function Ws(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function cd(e,t,n,r={}){if(!r.preserveConditionalBoundary&&Md(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=pe(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(c=>aa(c)).map(c=>n.callbackPath.scope.getBinding(c)?.path.node).filter(Boolean)),s=new Set,a=(c,l)=>{let u=l.scope.getBinding(c);if(!u||fn(u.path.node,o)||i.has(u.path.node))return;t.scope.getBinding(c)!==u&&s.add(c)};return e.traverse({ReferencedIdentifier(c){a(c.node.name,c)},JSXOpeningElement(c){let l=Sd(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function ld(e,t,n){let r=pe(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>aa(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return ia(e,s=>{let a=s.scope.getBinding(s.node.name);if(!a||fn(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 xb(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>aa(a)).map(a=>e.callbackPath.scope.getBinding(a)?.path.node).filter(Boolean)),r=new Set,o=(a,c)=>{let l=c.scope.getBinding(a);if(!l||n.has(l.path.node))return;t.scope.getBinding(a)!==l&&r.add(a)},i=e.callbackPath.get("params"),s=Array.isArray(i)?i:[i];for(let a of s)a.traverse({ReferencedIdentifier(c){o(c.node.name,c)},TSTypeReference(c){let l=c.node.typeName;if(S.isIdentifier(l))o(l.name,c);else{let u=bb(l);u&&o(u,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function bb(e){let t=e;for(;S.isTSQualifiedName(t);)t=t.left;return S.isIdentifier(t)?t.name:null}function Ed(e,t){let n=pe(e.node),r=new Set;return ia(e,o=>{let i=o.scope.getBinding(o.node.name);if(!i||n&&fn(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 ia(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function Sb(e){let t=Eb(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=Bd(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=Ob({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=Od(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?ca(o):!0}}}function Eb(e,t,n){let r=kd(e,t);if(Cd(e,r),Rd(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 Gt(e,{JSXElement(s){Fd(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:sa(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 vb(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=>yr(a.file)));if(!t.has(yr(e.sourceFile))||!t.has(yr(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(yr(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=Rb(e.sourceAst,e.sourceComponent);if(!n)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without an exported source component identity"};let r=[];for(let a of e.knownSourceFiles){let c=et(a.content);if(!c)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component because a loaded source file cannot be parsed"};r.push({file:a.file,ast:c})}let o=Ib(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=vd({ast:a.ast,file:a.file,sourceFile:e.sourceFile,sourceComponent:e.sourceComponent,componentIdentities:o});if(c.hasUnsafeReference)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component because the component has unsupported value usages"};i.push(...c.callSites)}if(i.length!==1)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without a single project-wide component call site"};let[s]=i;return!lt(s.file,e.targetFile)||sa(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 Ib(e,t){let n=new Map,r=i=>{let s=Kn(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 kb(i,n))o=r(s)||o}return[...n.values()]}function kb(e,t){let n=[],r=Cb(e,t);for(let o of e.ast.program.body){if(S.isExportDefaultDeclaration(o)&&S.isIdentifier(o.declaration)&&(r.get(o.declaration.name)?.length??0)>0){let i=r.get(o.declaration.name)??[];for(let s of i){if(s.namespace){let a=br(s.namespace,o.declaration.name,"default");a&&n.push({file:e.file,namespace:a,exportName:s.exportName});continue}n.push({file:e.file,exportName:"default"})}continue}if(S.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=Sr(e.file,o.source.value);for(let s of o.specifiers){if(S.isExportNamespaceSpecifier(s)){let l=Wt(s.exported);for(let u of t.values())lt(u.file,i)&&n.push({file:e.file,namespace:Qs(l,u.namespace),exportName:u.exportName});continue}if(!S.isExportSpecifier(s))continue;let a=Wt(s.local),c=[...t.values()].filter(l=>lt(l.file,i)&&un(l.namespace,a));if(c.length>0){let l=Wt(s.exported);for(let u of c){let d=br(u.namespace,a,l);d&&n.push({file:e.file,namespace:d,exportName:u.exportName})}continue}t.has(Kn({file:i,exportName:a}))&&n.push({file:e.file,exportName:Wt(s.exported)})}continue}if(S.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!S.isExportSpecifier(i))continue;let s=Wt(i.local),a=r.get(s)??[];if(a.length>0){let c=Wt(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let u=br(l.namespace,s,c);u&&n.push({file:e.file,namespace:u,exportName:l.exportName})}}}continue}if(S.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=Sr(e.file,o.source.value),s=o.exported;if(s){let a=Wt(s);for(let c of t.values())lt(c.file,i)&&n.push({file:e.file,namespace:Qs(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())lt(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function Qs(e,t){return t?`${e}.${t}`:e}function un(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function br(e,t,n){return!un(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function Cb(e,t){let n=new Map,r=(i,s)=>{let a=n.get(i)??[];a.push(s),n.set(i,a)};for(let i of e.ast.program.body){if(!S.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=Sr(e.file,i.source.value);for(let a of i.specifiers){if(S.isImportDefaultSpecifier(a)){let c=t.get(Kn({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(u=>lt(u.file,s)&&un(u.namespace,"default"));for(let u of l){let d=br(u.namespace,"default",a.local.name);d&&r(a.local.name,{...u,namespace:d})}continue}if(S.isImportSpecifier(a)){let c=Wt(a.imported),l=[...t.values()].filter(d=>lt(d.file,s)&&un(d.namespace,c));for(let d of l)r(a.local.name,d);let u=t.get(Kn({file:s,exportName:c}));u&&r(a.local.name,u);continue}if(S.isImportNamespaceSpecifier(a))for(let c of t.values())lt(c.file,s)&&r(a.local.name,{...c,namespace:Qs(a.local.name,c.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(S.isVariableDeclaration(i))for(let s of i.declarations){if(!S.isIdentifier(s.id)||!s.init)continue;let a=Jn(s.init);if(!a||!S.isIdentifier(a))continue;let c=n.get(a.name)??[];if(c.length===0)continue;let l=n.get(s.id.name)??[],u=new Set(l.map(Kn));for(let d of c){let p=br(d.namespace,a.name,s.id.name),m=p?{...d,namespace:p}:d,g=Kn(m);u.has(g)||(r(s.id.name,m),u.add(g),o=!0)}}}return n}function Kn(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${ea(e.file)}#${t}`}function Wt(e){return S.isIdentifier(e)?e.name:e.value}function Rb(e,t){for(let n of e.program.body){if(S.isExportDefaultDeclaration(n)){let o=n.declaration;if((S.isFunctionDeclaration(o)||S.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(S.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!S.isExportNamedDeclaration(n))continue;let r=n.declaration;if((S.isFunctionDeclaration(r)||S.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(S.isVariableDeclaration(r)){for(let o of r.declarations)if(S.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!S.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:S.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function vd(e){let t=wb(e),n=[],r=Rd(e.ast,t);return Gt(e.ast,{JSXElement(o){lt(e.file,e.sourceFile)&&sa(o)===e.sourceComponent||Fd(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function Id(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function kd(e,t){let n=Id();return Gt(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function wb(e){let t=Id();return lt(e.file,e.sourceFile)&&Nb(t,kd(e.ast,e.sourceComponent)),Gt(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=Sr(e.file,o),s=e.componentIdentities.filter(a=>lt(a.file,i));if(s.length!==0)for(let a of r.specifiers){let c=n.scope.getBinding(a.local.name);if(c){if(S.isImportDefaultSpecifier(a)&&s.some(l=>l.exportName==="default")&&t.localBindings.add(c),S.isImportDefaultSpecifier(a)){let l=s.filter(u=>un(u.namespace,"default"));if(l.length>0){let u=t.namespaceMembers.get(c)??new Set;for(let d of l){let p=dd(d,"default");p&&u.add(p)}t.namespaceMembers.set(c,u)}continue}if(S.isImportSpecifier(a)){let l=S.isIdentifier(a.imported)?a.imported.name:a.imported.value,u=s.filter(d=>un(d.namespace,l));if(u.length>0){let d=t.namespaceMembers.get(c)??new Set;for(let p of u){let m=dd(p,l);m&&d.add(m)}t.namespaceMembers.set(c,d);continue}s.some(d=>!d.namespace&&d.exportName===l)&&t.localBindings.add(c);continue}if(S.isImportNamespaceSpecifier(a))for(let l of s){let u=l.namespace?`${l.namespace}.${l.exportName}`:l.exportName,d=t.namespaceMembers.get(c)??new Set;d.add(u),t.namespaceMembers.set(c,d)}}}}}),Cd(e.ast,t),t}function Nb(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 Cd(e,t){Gt(e,{VariableDeclarator(n){if(!n.node.init)return;let r=Jn(n.node.init);if(r){if(S.isIdentifier(n.node.id)){let o=dn(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&qs(t,i,o);return}if(S.isObjectPattern(n.node.id)){let o=dn(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&Pd(n.node.id,o.namespaceMembers,t,n)}}}})}function Rd(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return Gt(e,{ReferencedIdentifier(r){if(n){r.stop();return}Pb(r)||!r.isIdentifier()||!wd(r,t)||Ab(r,t)||Tb(r)||(n=!0,r.stop())}}),n}function Pb(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 wd(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)&&dn(r.node,t,r)?r:null}function Ab(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!ud(e,r))return!1;let o=wd(e,t);if(!o)return!1;if(Jn(r.node)===o.node)return!!dn(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&ud(e,a)&&!!dn(a.node,t,a)}function Tb(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function ud(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function dn(e,t,n){let r=Jn(e);if(!r)return null;if(S.isIdentifier(r)){let a=n.scope.getBinding(r.name);if(!a)return null;let c=t.namespaceMembers.get(a);return t.localBindings.has(a)?{local:!0,namespaceMembers:new Set,unsupported:!1}:c?{local:!1,namespaceMembers:new Set(c),unsupported:!1}:null}if(S.isObjectExpression(r))return Fb(r,t,n);let o=Td(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?Nd(s,o.slice(1).join(".")):null}function Fb(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!S.isObjectProperty(i))continue;let s=Ad(i);if(!s||!S.isExpression(i.value)){S.isExpression(i.value)&&(o||=dn(i.value,t,n)!==null);continue}let a=dn(i.value,t,n);if(a){o||=a.unsupported,a.local&&r.add(s);for(let c of a.namespaceMembers)r.add(`${s}.${c}`)}}return r.size>0||o?{local:!1,namespaceMembers:r,unsupported:o}:null}function Nd(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 qs(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 Pd(e,t,n,r){for(let o of e.properties){if(S.isRestElement(o)){if(S.isIdentifier(o.argument)){let c=r.scope.getBinding(o.argument.name);c&&qs(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!S.isObjectProperty(o))continue;let i=Ad(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=Nd(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=S.isAssignmentPattern(o.value)?o.value.left:o.value;if(S.isIdentifier(a)){let c=r.scope.getBinding(a.name);c&&qs(n,c,s);continue}if(S.isObjectPattern(a)&&s.namespaceMembers.size>0){Pd(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function Ad(e){return e.computed?S.isStringLiteral(e.key)||S.isNumericLiteral(e.key)?String(e.key.value):null:_b(e.key)}function _b(e){return S.isIdentifier(e)?e.name:S.isStringLiteral(e)||S.isNumericLiteral(e)?String(e.value):null}function Jn(e){return S.isParenthesizedExpression(e)||S.isTSAsExpression(e)||S.isTSSatisfiesExpression(e)||S.isTSNonNullExpression(e)||S.isTSTypeAssertion(e)?Jn(e.expression):S.isExpression(e)?e:null}function Td(e){if(S.isIdentifier(e))return[e.name];if((S.isMemberExpression(e)||S.isOptionalMemberExpression(e))&&!e.computed&&S.isIdentifier(e.property)){let t=Jn(e.object),n=t?Td(t):null;return n?[...n,e.property.name]:null}return null}function dd(e,t){if(!un(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 Fd(e,t){let n=e.node.openingElement.name;if(S.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=_d(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 _d(e){if(S.isJSXIdentifier(e))return[e.name];if(S.isJSXMemberExpression(e)){let t=_d(e.object);return t?[...t,e.property.name]:null}return null}function sa(e){let t=e.getFunctionParent();if(!t)return null;if(t.isFunctionDeclaration())return t.node.id?.name??null;if(t.isArrowFunctionExpression()||t.isFunctionExpression()){let n=t.parentPath;if(n?.isVariableDeclarator()&&S.isIdentifier(n.node.id))return n.node.id.name}return null}function Ob(e){let t=pe(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||fn(a.path.node,t))return;let c=Lb(s,a,t);if(c){if(c.hasDefault){o="Cannot move prop-backed repeat child because the collection prop has a default value that cannot be preserved safely";return}let u=jb(e.callSitePath,c.propName,e.source);if(!u.ok){o=u.reason;return}let d=Mb(u.expression,c.remainingPath);if(!d){o="Cannot move prop-backed repeat child because the mapped prop path is not a portable expression";return}let p=Ed(u.expressionPath,e.targetParentPath);if(!p.ok){o=p.reason??`Cannot move prop-backed repeat child because the mapped prop source is not visible at the target: ${p.bindingNames.join(", ")}`;return}n.set(`${c.range.start}:${c.range.end}`,{...c.range,text:d});return}e.targetParentPath.scope.getBinding(s.node.name)!==a&&r.add(s.node.name)};return e.sourceContext.collectionPath.isIdentifier()&&e.sourceContext.collectionPath.isReferencedIdentifier()&&i(e.sourceContext.collectionPath),e.sourceContext.collectionPath.traverse({ReferencedIdentifier(s){s.isIdentifier()&&i(s)}}),o?{ok:!1,reason:o}:r.size>0?{ok:!1,reason:`Cannot move prop-backed repeat child because the collection depends on bindings outside the target scope: ${[...r].sort().join(", ")}`}:n.size===0?{ok:!1,reason:"Cannot move repeat-backed child out of its component without an explicit prop mapping"}:{ok:!0,collectionExpression:$b(e.source,t,[...n.values()])}}function Mb(e,t){if(t.length===0)return e;let n=Od(e);if(!n)return null;let r=ca(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=Db(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function Db(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function Lb(e,t,n){let r=Bb(e,n),o=r?{kind:"member-expression",expression:e.node.name,base:e.node.name,path:[{kind:"property",name:r.propertyName}]}:{kind:"identifier",expression:e.node.name,base:e.node.name,path:[]},i=Vn(t,o);if(!i)return null;let s=r?.range??pe(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function Bb(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!fn(n.node,t)||n.node.computed||!S.isIdentifier(n.node.property))return null;let r=pe(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function jb(e,t,n){let r=e.get("openingElement").get("attributes");if(r.some(c=>c.isJSXSpreadAttribute()))return{ok:!1,reason:"Cannot move prop-backed repeat child through spread props; use an explicit prop mapping"};let o=r.find(c=>c.isJSXAttribute()&&S.isJSXIdentifier(c.node.name)&&c.node.name.name===t);if(!o?.isJSXAttribute())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not passed explicitly`};let i=o.get("value");if(!i.isJSXExpressionContainer())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not an expression`};let s=i.get("expression");if(!s.isExpression())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not a usable expression`};let a=Go(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 $b(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 Od(e){try{let n=ra.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=S.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&S.isExpression(r)?r:null}catch{return null}}function Vb(e){let t=pe(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||fn(s.path.node,t))return;let a=fd(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let u=fd(c,e.targetFile,e.targetFile);(!u||u.moduleFile!==a.moduleFile||!Ub(u.importSpec,a.importSpec))&&r.add(a.localName);return}let l=n.get(a.moduleSpecifier)??[];l.some(u=>JSON.stringify(u)===JSON.stringify(a.importSpec))||l.push(a.importSpec),n.set(a.moduleSpecifier,l);return}r.add(i.node.name)};return ia(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 Ub(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 fd(e,t,n){let r=Kb(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=Sr(t,i),a=i.startsWith(".")?Zs(n,s):i;if(r.isImportDefaultSpecifier()){let c=r.node.local.name;return{localName:c,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"default",local:c}}}if(r.isImportNamespaceSpecifier()){let c=r.node.local.name;return{localName:c,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"namespace",local:c}}}if(r.isImportSpecifier()){let c=S.isIdentifier(r.node.imported)?r.node.imported.name:r.node.imported.value,l=r.node.local.name;return{localName:l,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"named",imported:c,local:l===c?void 0:l}}}return null}function Kb(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function Sr(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?At.normalize(At.join(At.dirname(e),t)).replace(/\\/g,"/"):t}function lt(e,t){return ea(e)===ea(t)}function ea(e){let t=yr(e);return t.endsWith("/index")?t.slice(0,-6):t}function yr(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function aa(e){let t=[],n=r=>{if(r){if(S.isIdentifier(r)){t.push(r.name);return}if(S.isObjectPattern(r)){for(let o of r.properties){if(S.isRestElement(o)){n(o.argument);continue}S.isObjectProperty(o)&&n(o.value)}return}if(S.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(S.isAssignmentPattern(r)){n(r.left);return}if(S.isRestElement(r)){n(r.argument);return}S.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function Jb(e){let t=[];for(let n of e.callbackPath.node.params){if(S.isIdentifier(n)){t.push(n.name);continue}if(S.isRestElement(n)&&S.isIdentifier(n.argument)){t.push(`...${n.argument.name}`);continue}return{ok:!1,reason:"Cannot move cross-file repeat child because the callback parameters are not portable to the target file"}}return{ok:!0,callbackParams:t}}function Xb(e,t){return{...e,callbackParams:t}}function pd(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function ca(e){return!(S.isIdentifier(e)||S.isThisExpression(e)||S.isMemberExpression(e)||S.isOptionalMemberExpression(e)||S.isCallExpression(e)||S.isOptionalCallExpression(e))}function Md(e,t){return Dd(e,t).length>0}function Hs(e,t){let n=pe(e.node),r=pe(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()&&!zb(o,n,r)))return!0;o=o.parentPath}return!1}function zb(e,t,n){let r=pe(e.node.consequent);if(r&&ct(r,t)&&!ct(r,n))return!1;let o=e.node.alternate?pe(e.node.alternate):null;return!(o&&ct(o,t)&&!ct(o,n))}function Dd(e,t){let n=pe(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=pe(o.node.consequent),a=pe(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()&&Ld(o.node.operator)){let s=pe(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 md(e,t,n,r){let o=Dd(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=Go(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=Wb(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${Gb(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function Wb(e,t){return Hb(e.node)?t:`(${t})`}function Hb(e){return S.isIdentifier(e)||S.isThisExpression(e)||S.isSuper(e)||S.isMemberExpression(e)||S.isOptionalMemberExpression(e)||S.isCallExpression(e)||S.isOptionalCallExpression(e)||S.isBooleanLiteral(e)||S.isNumericLiteral(e)||S.isStringLiteral(e)||S.isNullLiteral(e)||S.isUnaryExpression(e)}function Ld(e){return e==="&&"||e==="||"||e==="??"}function Gb(e){return e.trim().startsWith("<")?e:`(${e})`}function Bd(e,t){let n=pe(e.node),r=pe(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=gd(e),i=gd(t);if(!o||!i||!Yb(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=Zb(s.node,n);if(a&&!ct(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=pe(s.node.right);if(a&&ct(a,n)&&!ct(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())&&Qb(s)){let a=pe(s.node.body)??pe(s.node);if(a&&!ct(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 gd(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?pe(t.node.argument):null;if(t.isArrowFunctionExpression()&&(S.isJSXElement(t.node.body)||S.isJSXFragment(t.node.body)||S.isConditionalExpression(t.node.body)||S.isLogicalExpression(t.node.body)))return pe(t.node.body);t=t.parentPath}return null}function Yb(e,t){return e.start===t.start&&e.end===t.end}function Zb(e,t){let n=pe(e.consequent);if(n&&ct(n,t))return n;let r=pe(e.alternate);return r&&ct(r,t)?r:null}function Qb(e){let t=e.parentPath;if(!t||!t.isCallExpression()&&!t.isOptionalCallExpression()||t.node.arguments[0]!==e.node)return!1;let n=t.node.callee;return(S.isMemberExpression(n)||S.isOptionalMemberExpression(n))&&S.isIdentifier(n.property)&&n.property.name==="map"&&!n.computed}var qb={table:new Set(["caption","colgroup","thead","tbody","tfoot","tr"]),thead:new Set(["tr"]),tbody:new Set(["tr"]),tfoot:new Set(["tr"]),tr:new Set(["th","td"]),ul:new Set(["li"]),ol:new Set(["li"]),select:new Set(["option","optgroup"]),optgroup:new Set(["option"])};function Wo(e,t){if(t.kind!=="native-tag")return null;let n=e.tag?.toLowerCase();if(!n||n!==e.tag||n.startsWith("component:"))return null;let r=qb[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 eS(e,t){for(let n of e.program.body){if(!S.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>S.isImportDefaultSpecifier(o));if(r&&S.isImportDefaultSpecifier(r))return r.local.name}return null}function tS(e,t,n){for(let r of e.program.body){if(!S.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>S.isImportSpecifier(i)&&(S.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&S.isImportSpecifier(o))return o.local.name}return null}function hd(e){let t=new Set;return Gt(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function yd(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function nS(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=oa(e),o=et(t);if(n.exportName!=="default"){let a=o?tS(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?yd(r,hd(o)):r;return{localName:c,importStep:Gs(e,c)}}if(!o)return{localName:r,importStep:Gs(e,r)};let i=eS(o,n.source);if(i)return{localName:i};let s=yd(r,hd(o));return{localName:s,importStep:Gs(e,s)}}function rS(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??oa(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 oS(e){if(e.kind==="native-tag")return e.text===void 0?{kind:e.kind,tag:e.tag}:{kind:e.kind,tag:e.tag,text:e.text};if(!e.component)return{kind:e.kind};let t=e.props?iS(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function iS(e){return Object.fromEntries(Object.entries(e).filter(t=>ta(t[1])))}function ta(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(ta):typeof e=="object"?Object.values(e).every(ta):!1}function sS(e,t){let n=et(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=vd({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 Gs(e,t=oa(e)){if(!e.component)throw new Error("Materialized component calls do not have a component import");return{moduleSpecifier:e.component.source,imports:e.component.exportName==="default"?[{kind:"default",local:t}]:[{kind:"named",imported:e.component.exportName,...t!==e.component.exportName?{local:t}:{}}]}}function xd(e,t){if("kind"in e)return{parentNode:null,anchorNode:null,placement:e.relation};if("parentKey"in e)return{parentNode:t.getNode(e.parentKey),anchorNode:null,placement:e.relation};let n=t.getNode(e.anchorKey);return{parentNode:n?.parentKey?t.getNode(n.parentKey)??n:n,anchorNode:n,placement:e.relation}}function aS(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function hr(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function la(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function xr(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:la(e,t.slice(0,n)),index:r.index}}return null}function Ys(e,t){return e.locator?e.collectionPathMap?.[t]?la(e.locator,e.collectionPathMap[t]):xr(e.locator)?lS(e.locator,uS(t,e.collectionIndexMap)):null:null}function cS(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:jd(o,t)}function jd(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=jd(r,t);return o===void 0?void 0:{[n.name]:o}}function Ho(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 lS(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},la(e,i)}return null}function uS(e,t){return t?.[e]??e}function bd(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 dS(e,t){return fS(e.root,t.root)&&mS(e.path??[],t.path??[])}function fS(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&&pS(e.sourceRange,t.sourceRange)}}function pS(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function na(e,t){let n=null;return Gt(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 mS(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 Yo=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:hr(t.kind,t.params.kind)};let r=t,o=this.resolveNodeRequest(t);if(!o.ok)return o.result;let i=o.node,s=this.graph.getFileVersion(i.file);return t.documentVersion!==s?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${s})`}:this.planUpdateText(n,r,i,this.graph.getCapability(i.key),await this.graph.getTextWriteTarget(i.key,r.params.segmentIndex))}case"update-array-item":{if(t.params.kind!=="update-array-item")return{ok:!1,errorCode:"unknown",reason:hr(t.kind,t.params.kind)};let r=t,o=this.resolveNodeRequest(t);if(!o.ok)return o.result;let i=o.node,s=this.graph.getFileVersion(i.file);return t.documentVersion!==s?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${s})`}:this.planUpdateArrayItem(n,r,this.graph.getCapability(i.key),await this.graph.getTextWriteTarget(i.key,r.params.segmentIndex))}case"remove-node":{if(t.params.kind!=="remove-node")return{ok:!1,errorCode:"unknown",reason:hr(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:hr(t.kind,t.params.kind)};let r=t;if(!Xo(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=xd(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:hr(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=lb(t);if(!n)return{ok:!1,result:{ok:!1,errorCode:"invalid-target",reason:`Operation '${t.kind}' requires a node target`}};let r=this.graph.getNode(n);return r?{ok:!0,node:r}:{ok:!1,result:{ok:!1,errorCode:"locator-miss",reason:`Target key '${n}' not found in graph`}}}planNodeAttributeOperation(t,n,r){let o=r.file,i=this.graph.getCapability(r.key);return n.params.filePath!==o?{ok:!1,errorCode:"stale-version",reason:"The className source file changed before save."}:this.buildPlan(t,n,[{order:0,file:o,type:"set-class-name-source",request:{...n.params,key:r.key}}],i)}async planSetProps(t,n,r){let o=this.graph.getCapability(r.key),i=await this.buildTypedPropertySteps({node:r,scope:n.params.scope,changes:n.params.changes,selectionRef:n.selectionRef});return i.ok?this.buildPlan(t,n,i.steps,o):gS(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.buildStyleDraftPropertySteps({initialOrder:s.length,node:r,props:n.params.props,selectionRef:n.selectionRef});if(!a.ok)return a;s.push(...a.steps)}return this.buildPlan(t,n,s,i)}async buildTypedPropertySteps(t){let n=this.graph.getPropertyState;return n?od({node:t.node,scope:t.scope,changes:t.changes,selectionRef:t.selectionRef,getPropertyState:n,getRepeatPropertyTarget:this.graph.getRepeatPropertyTarget,getFileContent:r=>this.graph.getFileContent(r),getFileVersion:r=>this.graph.getFileVersion(r),classNameSource:this.graph.getClassNameSource?.(t.node.key)??void 0}):{ok:!1,errorCode:"missing-property-state",reason:"Typed property planning requires authoritative property provenance"}}async buildStyleDraftPropertySteps(t){let{initialOrder:n,node:r,props:o,selectionRef:i}=t,s=[],a=[];for(let[c,l]of Object.entries(o)){if(l===void 0)continue;let u=await this.graph.getElementPropertyWriteTarget?.(r.key,c),d=r.attributes?.find(p=>p.name===c);if(!(typeof d?.resolvedValue=="string"&&d.resolvedValue===l||d?.source===null&&d.value===l)){if(u?.kind==="external-entry")return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite readonly external property '${c}'`};if(u?.kind==="value-binding"&&u.locator){let p=u.locator;if(u.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let m=Ys(u,i.instanceIndex);if(!m)return{ok:!1,errorCode:"invalid-params",reason:"apply-style-draft could not resolve the selected repeat item"};p=m}s.push({order:n+s.length,file:u.file,type:"update-value",locator:p,value:l});continue}a.push({operation:"set",name:c,value:l})}}return a.length>0&&s.push({order:n+s.length,file:r.file,type:"set-property-changes",locator:he(r),scope:"selection",changes:a}),{ok:!0,steps:s}}buildTextRewriteSteps(t,n,r,o,i){if(o?.kind==="value-binding"&&o.locator){if(o.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let a=Ys(o,i.instanceIndex);if(!a)return{ok:!1,errorCode:"invalid-params",reason:"update-text could not resolve the selected repeat item"};let c=this.coerceTextValueForValueTarget(o.file,a,r);return c.ok?{ok:!0,steps:[{order:0,file:o.file,type:"update-array-item",locator:a,value:c.value}]}:c}let s=this.coerceTextValueForValueTarget(o.file,o.locator,r);return s.ok?{ok:!0,steps:[{order:0,file:o.file,type:"update-value",locator:o.locator,value:s.value}]}:s}return{ok:!0,steps:o?.kind==="external-entry"?[{order:0,file:`external:${o.sourceId}`,type:"invoke-external-adapter",sourceType:o.sourceType,sourceId:o.sourceId,adapterId:o.adapterId,capability:"write-text",value:r}]:[{order:0,file:t.file,type:"update-text",locator:he(t),segmentIndex:n,newText:r}]}}coerceTextValueForValueTarget(t,n,r,o="update-text"){let i=this.graph.getFileContent(t),s=et(i);if(!s)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not inspect the value source`};let a=ne(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!db(a.match.path))return{ok:!0,value:r};let c=fb(r);return c===null?{ok:!1,errorCode:"invalid-params",reason:`${o} value must be a valid number for numeric source`}:{ok:!0,value:c}}planUpdateArrayItem(t,n,r,o){if(!r.canUpdateText)return{ok:!1,errorCode:"capability-denied",reason:"Cannot update repeated text on this node"};if(o?.kind!=="value-binding"||o.sourceKind!=="repeat-template"||!o.locator)return{ok:!1,errorCode:"invalid-params",reason:"update-array-item requires a writable repeat-template source"};let{index:i,value:s}=n.params,a=o.collectionPathMap?.length??o.collectionIndexMap?.length;if(a!==void 0&&i>=a)return{ok:!1,errorCode:"invalid-params",reason:`update-array-item index ${i} is outside the repeated source`};let c=Ys(o,i);if(!c)return{ok:!1,errorCode:"invalid-params",reason:"update-array-item could not resolve the selected repeat item"};let l=this.coerceTextValueForValueTarget(o.file,c,s,"update-array-item");return l.ok?this.isValueTargetUnchanged(o.file,c,l.value)?{ok:!1,errorCode:"invalid-params",reason:"update-array-item value is unchanged"}:this.buildPlan(t,n,[{order:0,file:o.file,type:"update-array-item",locator:c,value:l.value}],r):l}isValueTargetUnchanged(t,n,r){let o=et(this.graph.getFileContent(t));if(!o)return!1;let i=ne(o,n);if(!i.ok)return!1;let s=i.match.path;if(s.isStringLiteral())return typeof r=="string"&&s.node.value===r;if(s.isNumericLiteral())return typeof r=="number"&&Object.is(s.node.value,r);if(s.isBooleanLiteral())return typeof r=="boolean"&&s.node.value===r;if(s.isNullLiteral())return r===null;if(s.isUnaryExpression({operator:"-"})){let a=s.get("argument");return typeof r=="number"&&!Array.isArray(a)&&a.isNumericLiteral()&&Object.is(-a.node.value,r)}return!1}planUpdateText(t,n,r,o,i){if(!o.canUpdateText)return{ok:!1,errorCode:"capability-denied",reason:"Cannot update text on this node"};let s=this.buildTextRewriteSteps(r,n.params.segmentIndex,n.params.value,i,n.selectionRef);return s.ok?this.buildPlan(t,n,s.steps,o):s}async planRemoveNode(t,n,r,o){if(!o.canRemove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot remove this node"};let i=await this.graph.getTextWriteTarget(r.key,0);if(i?.kind==="external-entry")return this.buildPlan(t,n,[{order:0,file:`external:${i.sourceId}`,type:"invoke-external-adapter",sourceType:i.sourceType,sourceId:i.sourceId,adapterId:i.adapterId,capability:"remove-node",value:{operation:"remove-node"}}],o);if(r.isRepeatItemRoot){let d=i;if(d?.kind==="value-binding"&&d.locator){let p=xr(d.locator);if(p)return this.buildPlan(t,n,[{order:0,file:d.file,type:"remove-bound-array-item",locator:p.locator,index:p.index}],o)}return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed node removal requires a writable array target"}}let s=Ho(r,i,this.graph.getTextProvenance?.(r.key,0)??null);if(s)return{ok:!1,errorCode:"unsupported-operation",reason:s};let a=this.getRepeatBackedTemplateStructureReason(r);if(a)return{ok:!1,errorCode:"unsupported-operation",reason:a};let c=await this.getUpstreamBackedDescendantReason(r);if(c)return{ok:!1,errorCode:"unsupported-operation",reason:c};let l=[{order:0,file:r.file,type:"remove-node",locator:he(r),removeWhitespace:!0}],u=this.buildRemoveComponentImportStep(r);return u&&l.push({...u,order:l.length}),this.buildPlan(t,n,l,o)}buildRemoveComponentImportStep(t,n=this.graph.getFileContent(t.file)){if(!t.importedFrom||!t.exportName||!t.tag||sS(n,t)>1)return null;let r=Zs(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(!Xo(n.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};if(n.params.node.kind==="component-call"&&!n.params.node.component)return{ok:!1,errorCode:"unsupported-operation",reason:"Materialized component insertion requires the materialization transaction planner"};if(!o.canInsertChild)return{ok:!1,errorCode:"capability-denied",reason:"Cannot insert child into this node"};let s=this.graph.getEditableTextSegmentIndex(r.key),a=s!==null?await this.graph.getTextWriteTarget(r.key,s):null,c=Ho(r,a,s!==null?this.graph.getTextProvenance?.(r.key,s)??null:null);if(c)return{ok:!1,errorCode:"unsupported-operation",reason:c};let l=await this.getUpstreamBackedDescendantReason(r);if(l)return{ok:!1,errorCode:"unsupported-operation",reason:l};let u=await this.planExternalBackedInsertChild(t,n,r,o,i,a);if(u)return u;let d=await this.planRepeatBackedInsertChild(t,n,r,o);if(d)return d;let p=this.getRepeatBackedTemplateStructureReason(r);if(p)return{ok:!1,errorCode:"unsupported-operation",reason:p};let m=Wu(this.graph.getFileContent(r.file),r);if(!m.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:m.reason??"Cannot insert child into this node"};let g=Wo(r,n.params.node);if(g)return{ok:!1,errorCode:"unsupported-operation",reason:g};let b=[],C=0,I=n.params.node.kind==="component-call"?nS(n.params.node,this.graph.getFileContent(r.file)):void 0,w=I?.importStep;return w&&b.push({order:C++,file:r.file,type:"add-import",moduleSpecifier:w.moduleSpecifier,imports:w.imports}),b.push({order:C++,file:r.file,type:"insert-child",parentLocator:he(r),node:{jsx:rS(n.params.node,I?.localName)},placement:n.params.position.relation,anchorLocator:i?he(i):void 0}),this.buildPlan(t,n,b,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!Xo(n.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let a=s?.kind==="external-entry"?s:await this.findExternalInsertContext(r,i);if(!a)return null;let c=i?await this.graph.getTextWriteTarget(i.key,0):null;return this.buildPlan(t,n,[{order:0,file:`external:${a.sourceId}`,type:"invoke-external-adapter",sourceType:a.sourceType,sourceId:a.sourceId,adapterId:a.adapterId,capability:"insert-child",value:{operation:"insert-child",relation:n.params.position.relation,parentKey:r.key,anchorSourceId:c?.kind==="external-entry"?c.sourceId:null,node:oS(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(!Xo(n.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};if(n.params.position.relation!=="append"&&n.params.position.relation!=="prepend")return null;let i=n.params.node;if(i.kind!=="native-tag"||i.text===void 0||!this.graph.getChildNodes)return null;let s=this.graph.getChildNodes(r.key).find(d=>d.isRepeatItemRoot&&d.tag?.toLowerCase()===i.tag.toLowerCase());if(!s)return null;let a=await this.graph.getTextWriteTarget(s.key,0);if(!a||a.kind!=="value-binding"||!a.locator)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires a writable value target"};let c=xr(a.locator);if(!c)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let l=cS(a.locator,i.text);if(l===void 0)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child could not infer an item shape from the template"};let u=n.params.position.relation==="prepend"?bd(0,a.collectionIndexMap):bd(a.collectionIndexMap?.length??c.index+1,a.collectionIndexMap);return this.buildPlan(t,n,[{order:0,file:a.file,type:"insert-bound-array-item",locator:c.locator,index:u,value:l}],o)}async getUpstreamBackedDescendantReason(t){if(!this.graph.getChildNodes)return null;let n=[...this.graph.getChildNodes(t.key)];for(;n.length>0;){let r=n.shift();if(!r)continue;let o=this.graph.getEditableTextSegmentIndex(r.key),i=o!==null?await this.graph.getTextWriteTarget(r.key,o):null,s=Ho(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=et(this.graph.getFileContent(t.file));if(!n)return t.isRepeatItemRoot===!0;let r=ne(n,he(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:na(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=Pt(this.graph.getFileContent(t.file),o);return i?mb(o,i):t.isRepeatItemRoot===!0}isInsideMapCallback(t){let n=et(this.graph.getFileContent(t.file));if(!n)return!1;let r=ne(n,he(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:na(n,t);return o?!!o.findParent(i=>{if(!i.isCallExpression()&&!i.isOptionalCallExpression())return!1;let s=i.node.callee;return(S.isMemberExpression(s)||S.isOptionalMemberExpression(s))&&S.isIdentifier(s.property)&&s.property.name==="map"}):!1}planRepeatTemplateInternalMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&this.isRepeatTemplateRootNode(r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=et(c);if(!l)return null;let u=Xt(l,r),d=Xt(l,o);if(!u||!d)return null;let p=Pt(c,u),m=Pt(c,d);if(!zo(p,m))return null;if(a&&(s==="before"||s==="after")){let b=Xt(l,a),C=b?Pt(c,b):null;if(!zo(p,C))return null}if(Hs(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let g=id(c,r,o);return g.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:he(r),targetParentLocator:he(o),placement:s,anchorLocator:a?he(a):void 0,selectionContext:Un(o)}],i):{ok:!1,errorCode:"unsupported-operation",reason:g.reason??`Cannot move node because it depends on bindings outside the target scope: ${g.bindingNames.join(", ")}`}}planRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&this.isRepeatTemplateRootNode(r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=et(c);if(!l)return null;let u=Xt(l,r),d=Xt(l,o);if(!u||!d)return null;let p=Pt(c,u);if(!p)return null;let m=Pt(c,d);if(zo(p,m))return null;if(m&&!yb(m,p))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")){let A=sd(c,l,a);if(m&&!zo(m,A)||!m&&A)return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child relative to a repeat-template anchor outside the target scope"}}if(r.tag&&r.tag.toLowerCase()===r.tag){let A=Wo(o,{kind:"native-tag",tag:r.tag});if(A)return{ok:!1,errorCode:"unsupported-operation",reason:A}}let g=zs(this.graph,r);if(!g)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Hs(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let b=md(c,u,d,g);for(let A of b.conditionPaths){let O=ld(A,d,p);if(!O.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${O.bindingNames.join(", ")}`}}let C=cd(u,d,p,{preserveConditionalBoundary:b.conditionPaths.length>0});if(!C.ok)return{ok:!1,errorCode:"unsupported-operation",reason:C.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${C.bindingNames.join(", ")}`};let I=xb(p,d);if(!I.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its callback parameters depend on bindings outside the target scope: ${I.bindingNames.join(", ")}`};let w=p;if(r.component!==o.component){let A=Sb({source:c,ast:l,sourceContext:p,sourceNode:r,targetParent:o,targetParentPath:d});if(!A.ok)return{ok:!1,errorCode:"unsupported-operation",reason:A.reason};w=A.context}else{let A=Ed(p.collectionPath,d);if(!A.ok)return{ok:!1,errorCode:"unsupported-operation",reason:A.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${A.bindingNames.join(", ")}`}}return this.buildPlan(t,n,[{order:0,file:r.file,type:"move-repeat-template-child",locator:he(r),targetParentLocator:he(o),placement:s,anchorLocator:a?he(a):void 0,repeatExpression:pd(w,b.sourceJsx),selectionContext:Un(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&this.isRepeatTemplateRootNode(r)||r.file===o.file)return null;let c=this.graph.getFileContent(r.file),l=this.graph.getFileContent(o.file),u=et(c),d=et(l);if(!u||!d)return null;let p=vb({knownSourceFiles:this.graph.getKnownSourceFiles?.(),routeEntryFiles:this.graph.getRouteEntryFiles?.(),sourceAst:u,sourceFile:r.file,targetFile:o.file,sourceComponent:r.component,targetComponent:o.component});if(!p.ok)return{ok:!1,errorCode:"unsupported-operation",reason:p.reason};let m=Xt(u,r),g=Xt(d,o);if(!m||!g)return null;let b=Bd(p.callSitePath,g);if(!b.ok)return{ok:!1,errorCode:"unsupported-operation",reason:b.reason};let C=Pt(c,m);if(!C)return null;if(Pt(l,g))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")&&sd(l,d,a))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child relative to a repeat-template anchor outside the target scope"};if(r.tag&&r.tag.toLowerCase()===r.tag){let M=Wo(o,{kind:"native-tag",tag:r.tag});if(M)return{ok:!1,errorCode:"unsupported-operation",reason:M}}let w=zs(this.graph,r);if(!w)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Hs(m,g))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let A=md(c,m,g,w);for(let M of A.conditionPaths){let j=ld(M,g,C);if(!j.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${j.bindingNames.join(", ")}`}}let O=cd(m,g,C,{preserveConditionalBoundary:A.conditionPaths.length>0});if(!O.ok)return{ok:!1,errorCode:"unsupported-operation",reason:O.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${O.bindingNames.join(", ")}`};let ie=Vb({sourceFile:r.file,targetFile:o.file,sourceContext:C,targetParentPath:g});if(!ie.ok)return{ok:!1,errorCode:"unsupported-operation",reason:ie.reason};let oe=Jb(C);if(!oe.ok)return{ok:!1,errorCode:"unsupported-operation",reason:oe.reason};let N=Xb(C,oe.callbackParams),W=[{order:0,file:r.file,type:"remove-node",locator:he(r),removeWhitespace:!0}];for(let M of ie.imports)W.push({order:W.length,file:o.file,type:"add-import",moduleSpecifier:M.moduleSpecifier,imports:M.imports});return W.push({order:W.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:he(o),expression:pd(N,A.sourceJsx),placement:s,anchorLocator:a?he(a):void 0,selectionContext:Un(o)}),this.buildPlan(t,n,W,i)}async planMoveNode(t,n,r,o){if(!o.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};let i=xd(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(aS(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 I=n.params.target.relation,w=i.anchorNode&&(I==="before"||I==="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:I,anchorSourceId:w?.kind==="external-entry"?w.sourceId:null,parentKey:"parentKey"in n.params.target?n.params.target.parentKey:null}}],o)}let c=r.file!==s.file,l=n.params.target.relation,u=i.anchorNode,d=Ho(r,a,this.graph.getTextProvenance?.(r.key,0)??null);if(d&&!Ws(d))return{ok:!1,errorCode:"unsupported-operation",reason:d};if(r.isRepeatItemRoot&&u?.isRepeatItemRoot&&r.repeatOwnerKey&&r.repeatOwnerKey===u.repeatOwnerKey&&(l==="before"||l==="after")){let I=a,w=await this.graph.getTextWriteTarget(u.key,0);if(I?.kind==="value-binding"&&w?.kind==="value-binding"&&I.locator&&w.locator){let A=xr(I.locator),O=xr(w.locator);if(A&&O&&I.file===w.file&&dS(A.locator,O.locator)){let ie=A.index,oe=O.index,N=l==="before"?oe-(ie<oe?1:0):oe+(ie<oe?0:1);return this.buildPlan(t,n,[{order:0,file:I.file,type:"move-array-item",locator:A.locator,fromIndex:ie,toIndex:N}],o)}}}if(r.isRepeatItemRoot&&this.isRepeatTemplateRootNode(r))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed item outside its collection"};let p=this.getRepeatBackedTemplateStructureReason(r),m=Ws(d)?d:p;if(m&&Ws(m)){let I=this.planRepeatTemplateInternalMove(t,n,r,s,o,l,u);if(I)return I;let w=this.planRepeatTemplateHoistMove(t,n,r,s,o,l,u);if(w)return w;let A=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,l,u);return A||{ok:!1,errorCode:"unsupported-operation",reason:m}}if(p)return{ok:!1,errorCode:"unsupported-operation",reason:p};let g=await this.getUpstreamBackedDescendantReason(r);if(g)return{ok:!1,errorCode:"unsupported-operation",reason:g};if(r.tag&&r.tag.toLowerCase()===r.tag){let I=Wo(s,{kind:"native-tag",tag:r.tag});if(I)return{ok:!1,errorCode:"unsupported-operation",reason:I}}if(c)return this.planCrossFileMove(t,n,r,s,o,l,u);let b=id(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 C=[{order:0,file:r.file,type:"move-node",locator:he(r),targetParentLocator:he(s),placement:l,anchorLocator:u?he(u):void 0,selectionContext:Un(s)}];return this.buildPlan(t,n,C,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,u=this.graph.getFileContent(r.file),d=zs(this.graph,r)??`<${r.component} />`,p=Hu(u,r);if(!p.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:p.reason??"Cannot move subtree across files"};if(c.push({order:l++,file:r.file,type:"remove-node",locator:he(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let g=r.tag??r.component,C={moduleSpecifier:Zs(o.file,r.importedFrom),imports:r.exportName==="default"?[{kind:"default",local:g}]:[{kind:"named",imported:r.exportName,local:g===r.exportName?void 0:g}]};c.push({order:l++,file:o.file,type:"add-import",moduleSpecifier:C.moduleSpecifier,imports:C.imports}),c.push({order:l++,file:o.file,type:"insert-child",parentLocator:he(o),node:{jsx:d},placement:s,anchorLocator:a?he(a):void 0,selectionContext:Un(o)})}else c.push({order:l++,file:o.file,type:"insert-child",parentLocator:he(o),node:{jsx:d},placement:s,anchorLocator:a?he(a):void 0,selectionContext:Un(o)});let m=this.buildRemoveComponentImportStep(r,u);return m&&c.push({...m,order:l++}),this.buildPlan(t,n,c,i)}buildPlan(t,n,r,o){let s=[...new Set(r.map(a=>a.file))].map(a=>({file:a,content:this.graph.getFileContent(a),version:this.graph.getFileVersion(a),exists:!0,sha256:fe(this.graph.getFileContent(a))}));return{ok:!0,plan:{operationId:t,kind:n.kind,target:n.target,documentVersion:n.documentVersion,steps:r,preSnapshots:s,validatedCapability:o}}}};function gS(e){return{ok:!1,errorCode:e.errorCode==="readonly-property"?"capability-denied":e.errorCode==="missing-property-state"||e.errorCode==="repeat-target-failed"||e.errorCode==="unsupported-binding"?"unsupported-operation":"invalid-params",reason:e.reason}}import Er from"node:path";import*as Yd from"@babel/parser";import ua from"@babel/traverse";import*as v from"@babel/types";var Zd=typeof ua=="function"?ua:ua.default;function Qd(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}var $d=new WeakMap;function Vd(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 qd(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=va(s,t,n);if(!a)return null;let c=Ia(a,r.sourceRange);if(!c)return null;let l=r.source??await ft({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!l){let m=await Aa({currentFile:t,expressionPath:c,readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:new Set});if(!m)return null;if(m.kind==="external")return{kind:"external-entry",file:m.file,sourceType:m.sourceType,sourceId:m.sourceId,adapterId:m.adapterId,displayExpression:m.displayPath};let g={kind:"value",root:m.root,path:m.path.length>0?m.path:[]};return{kind:"value-binding",file:m.file,locator:g,root:m.root,path:m.path,displayExpression:m.displayExpression??kr(c.node,n),sourceKind:m.sourceKind,...m.collectionIndexMap?{collectionIndexMap:m.collectionIndexMap}:{},...m.collectionPathMap?{collectionPathMap:m.collectionPathMap}:{}}}let u=new Set,d=await KS({currentFile:t,expressionPath:c,segment:{...r,source:l},readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:u});if(!d)return null;if(d.kind==="external")return{kind:"external-entry",file:d.file,sourceType:d.sourceType,sourceId:d.sourceId,adapterId:d.adapterId,displayExpression:d.displayPath};let p={kind:"value",root:d.root,path:d.path.length>0?d.path:[]};return{kind:"value-binding",file:d.file,locator:p,root:d.root,path:d.path,displayExpression:d.displayExpression??l.expression,sourceKind:d.sourceKind,...d.collectionIndexMap?{collectionIndexMap:d.collectionIndexMap}:{},...d.collectionPathMap?{collectionPathMap:d.collectionPathMap}:{}}}async function Xn(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=va(i,t,n);if(!s)return null;let a=e.expression!==void 0?(e.sourceRange?rf(s,n,e.expression,e.sourceRange):null)??Ra(s,n,e.expression):e.sourceRange?Ia(s,e.sourceRange):null;if(!a)return null;let c=bS(a),l=new Set,u=e.sourceInfo??await ft({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:l}),d=u?await Xe({currentFile:t,expressionPath:c,sourceInfo:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:l}):await rE({currentFile:t,expressionPath:c,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:l});return xS(d,e.expression??kr(c.node,n))}async function Ea(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=va(i,t,n);if(!s)return Je("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?SS({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}):ES({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}function ef(e){try{return Yd.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function va(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=ef(n);return e.set(t,{source:n,ast:o}),o}function Ia(e,t){let n=null,r=-1;for(let o of Ir(e).expressions){let i=o.node.loc;if(!i||!ka(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s>=r&&(n=o,r=s)}return n}function hS(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of Ir(e).expressions){if(!yS(o.node.loc,t))continue;let i=(o.node.end??0)-(o.node.start??0);i<=r&&(n=o,r=i)}return n}function tf(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of Ir(e).jsxElements){let i=o.node.loc;if(!i||!ka(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s<=r&&(n=o,r=s)}return n}function Ir(e){let t=$d.get(e);if(t)return t;let n={expressions:[],jsxElements:[]};return Zd(e,{Expression(r){n.expressions.push(r)},JSXElement(r){n.jsxElements.push(r)}}),$d.set(e,n),n}function yS(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 ka(e,t){let n=Ud({line:e.start.line,column:e.start.column},{line:t.startLine,column:t.startColumn}),r=Ud({line:e.end.line,column:e.end.column},{line:t.endLine,column:t.endColumn});return n>=0&&r<=0}function nf(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 Ud(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 ft(e){if(v.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!v.isMemberExpression(e.expression))return null;let t=await gf(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:kr(e.expression,e.source),base:t.base,path:t.path}:null}function xS(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 bS(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 kr(e,t){if(t)return Ca(e,t);let n=fE(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function Ca(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Ra(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of Ir(e).expressions){if(Ca(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function rf(e,t,n,r){let o=null,i=Number.POSITIVE_INFINITY;for(let s of Ir(e).expressions){if(Ca(s.node,t)!==n)continue;let a=s.node.loc;if(!a||!ka(a,r))continue;let c=(s.node.end??0)-(s.node.start??0);c<=i&&(o=s,i=c)}return o}async function SS(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=Ia(r,o.sourceRange),u=o.source??(l?await ft({expression:l.node,scope:l.scope,source:n,currentFile:t,readFile:i,exists:s,fileCache:a,visited:c}):null);if(!u){if(!l)return vS(t,o.value);let p=await Aa({currentFile:t,expressionPath:l,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});return p?p.kind==="external"?Wd(t,p):ha(t,kr(l.node,n),p):IS({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return Je("unsupported-expression","Unable to locate text expression for provenance resolution");let d=await Xe({currentFile:t,expressionPath:l,sourceInfo:u,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});if(!d){let p=ga(l.node);if(p)return Je(p.code,p.message);let m=l.scope.getBinding(u.base);if(m?.path.isVariableDeclarator()){let g=ga(m.path.node.init);if(g)return Je(g.code,g.message)}return m?.path.isVariableDeclarator()&&v.isCallExpression(m.path.node.init)?kS("unsupported-expression",lf(m.path.node.init,e.functionCallContracts)):Je("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return d.kind==="external"?Wd(t,d):ha(t,u.expression,d)}async function ES(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return Je("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=Ra(r,n,o.conditionExpression);if(!l)return Je("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await Xe({currentFile:t,expressionPath:l,sourceInfo:o.conditionSource,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});if(!u)return Je("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(u.kind==="external")return Je("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let d=ha(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 vS(e,t){return{finalSource:{kind:"jsx-literal",file:e,locator:null,displayPath:t},chain:[{kind:"jsx-literal",file:e,displayName:t,canEditHere:!0}],confidence:"exact",editMode:"direct",diagnostics:[]}}async function IS(e){let t=await sf(e);if(t.length===0)return Je("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(CS(e.expression))return of(t);if(cf(e.expression))return Je("unsupported-expression","i18n helpers require a static message id string");if(v.isMemberExpression(e.expression)&&e.expression.computed&&!v.isNumericLiteral(e.expression.property)&&!v.isStringLiteral(e.expression.property))return Je("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return Je(n.code,n.message)}function Je(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function kS(e,t){return of([{code:e,message:t}])}function of(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function CS(e){return v.isCallExpression(e)||v.isConditionalExpression(e)||v.isLogicalExpression(e)||v.isBinaryExpression(e)}function vr(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 sf(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=ga(t);if(l)return[l];if(v.isCallExpression(t))return[{code:"unsupported-expression",message:lf(t,c)}];if(v.isMemberExpression(t)&&t.computed){let u=t.property;if(!v.isNumericLiteral(u)&&!v.isStringLiteral(u)){if(!v.isExpression(u))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let p=await pt(u,n,r,o,i,s,a);if(typeof p!="string"&&!Number.isInteger(p))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}]}}return v.isBinaryExpression(t)?vr([...await da(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):v.isLogicalExpression(t)?vr([...await da(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"}]):v.isConditionalExpression(t)?vr([...await da(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 ga(e){return cf(e)?Kd("i18n helpers require a static message id string"):AS(e)?Kd("CMS helpers require static entry id and field path string arguments"):null}async function da(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await sf({...t,expression:o}));return r}function RS(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:[wS(e.sourceType)]}}async function wa(e){for(let n of OS){if(!Jd(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return zd(Xd(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(!Jd(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return zd(Xd(r),e.externalAdapters)}return null}function wS(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function NS(e){return{code:"external-source-readonly",message:e}}function Kd(e){return{code:"unsupported-expression",message:e}}function Na(e){return!e||!v.isCallExpression(e)?null:v.isIdentifier(e.callee)?e.callee.name:v.isMemberExpression(e.callee)&&!e.callee.computed&&v.isIdentifier(e.callee.object)&&v.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function Jd(e,t){if(!t||t.length===0)return!0;let n=Na(e.node);return n?t.includes(n):!1}function Xd(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:vr(e.diagnostics??[])}:{match:e,diagnostics:[]}}function zd(e,t){let n=RS(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:vr([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function PS(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!v.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!v.isStringLiteral(n)||!v.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 AS(e){return!!e&&v.isCallExpression(e)&&v.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!v.isStringLiteral(e.arguments[0])||!v.isStringLiteral(e.arguments[1]))}function af(e){if(!(!e||!v.isCallExpression(e))){if(v.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&v.isStringLiteral(t)?t.value:null}if(v.isMemberExpression(e.callee)&&!e.callee.computed&&v.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&v.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!v.isObjectExpression(t))return null;for(let n of t.properties)if(v.isObjectProperty(n)&&!n.computed&&(v.isIdentifier(n.key)&&n.key.name==="id"||v.isStringLiteral(n.key)&&n.key.value==="id")&&v.isStringLiteral(n.value))return n.value.value;return null}}}function cf(e){return af(e)===null}async function TS(e,t,n){let r=new Set,o=Er.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=Er.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"]:[Er.posix.join(i,"locales"),Er.posix.join(i,"messages")];for(let a of s){let c=Er.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function FS(e){let t=af(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await TS(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function _S(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!v.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!v.isExpression(n))return null;let o=await pt(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:[NS("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var OS=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>PS(e)},{helperNames:["apiField"],resolve:e=>_S(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>FS({currentFile:e,expressionPath:t,exists:n})}];function Wd(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 ha(e,t,n){let r={kind:"value",root:n.root,path:n.path.length>0?n.path:[]},o=n.path.some(l=>l.kind==="index"),i=US(n),s;n.semanticKind?s=n.semanticKind:i?s="config-entry":n.sourceKind==="repeat-template"?s="repeat-template":n.path.length===0?s=n.sourceKind==="imported-binding"?"imported-binding":"binding":s=o?"array-item":"object-field";let a=n.displayExpression??t,c=[...n.chainPrefix??[]];return n.sourceKind==="binding"?c.push({kind:"binding",file:n.file,displayName:n.root.kind==="binding"?n.root.name:a,canEditHere:!0}):n.sourceKind==="imported-binding"?c.push({kind:"imported-binding",file:n.file,displayName:n.root.kind==="named-export"?n.root.name:"default",canEditHere:!0}):n.sourceKind==="repeat-template"&&c.push({kind:"repeat-template",file:n.file,displayName:t,canEditHere:!0}),n.path.length>0&&n.sourceKind!=="repeat-template"&&c.push({kind:o?"array-item":"object-field",file:n.file,displayName:a,canEditHere:!0}),i&&c.push({kind:"config-entry",file:n.file,displayName:i.displayPath,canEditHere:!0}),{finalSource:{kind:s,file:n.file,locator:r,root:n.root,path:n.path,displayPath:a,externalSource:i?{sourceType:"config-entry",sourceId:i.sourceId}:void 0},chain:c,confidence:n.sourceKind==="repeat-template"?"safe-derived":"exact",editMode:n.editMode??(n.file===e?"direct":"proxy"),diagnostics:n.diagnostics??[]}}var MS=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function Pa(e,t){let n=[...MS,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function lf(e,t){let n=e.callee;return v.isIdentifier(n)&&Pa(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 Aa(e){let t=await wa(e);if(t)return t;let n=await uf({...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 ft({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 Xe({...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 $S(e)}async function uf(e){let t=await ut({...e,allowComposed:!1});return t?.kind==="source"?t.provenance:null}async function ut(e){let t=DS(e.expressionPath),n=jS(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 ft({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 Xe({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 ft({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 Xe({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 ut({...e,expressionPath:r,allowComposed:!0}),a=await ut({...e,expressionPath:o,allowComposed:!1}),c=await ut({...e,expressionPath:i,allowComposed:!1});return fa(s,a,c)}if(t.isCallExpression())return LS({...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 ut({...e,expressionPath:r,allowComposed:!0}),s=await ut({...e,expressionPath:o,allowComposed:!0});return fa(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 ut({...e,expressionPath:r,allowComposed:!0}),s=await ut({...e,expressionPath:o,allowComposed:!0});return fa(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:ut({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function DS(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 LS(e){let t=Na(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:ut({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(v.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:ut({...e,expressionPath:o,allowComposed:!1})}}return null}function fa(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!BS(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function BS(e,t){return e.file===t.file&&e.sourceKind===t.sourceKind&&JSON.stringify(e.root)===JSON.stringify(t.root)&&JSON.stringify(e.path)===JSON.stringify(t.path)&&JSON.stringify(e.collectionIndexMap??null)===JSON.stringify(t.collectionIndexMap??null)&&JSON.stringify(e.collectionPathMap??null)===JSON.stringify(t.collectionPathMap??null)}function jS(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function $S(e){if(!e.expressionPath.isCallExpression())return null;let t=Na(e.expressionPath.node);if(!t)return null;let n=Pa(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 df({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 df(e){let t=await wa({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 ft({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 Xe({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 Aa({currentFile:e.currentFile,expressionPath:e.argumentPath,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited})}async function VS(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!v.isCallExpression(t))return null;let n=t.callee;if(!v.isIdentifier(n))return null;let r=Pa(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 df({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 US(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=Qo(t,e.path);return{sourceId:o,displayPath:o}}async function KS(e){let t=e.segment.source;return t?Xe({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 Xe(e){let t=e.sourceInfo,n=ff(e.expressionPath,t.base);if(n){let l=await pf({currentFile:e.currentFile,callPath:n.callPath,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,fileCache:e.fileCache,visited:e.visited});if(!l){let b=XS(n.callPath,[...n.basePath,...t.path]);return fr(b)?Vd(e.currentFile,b.sourceId,b.displayPath):null}let u=pE(l,[...n.basePath,...t.path]),d=l.collectionIndexMap?.[0]??0,p=[...l.pathPrefix??[],{kind:"index",index:d},...n.basePath,...t.path],m=[{kind:"index",index:0},...n.basePath,...t.path];return dt(l.value,m)===void 0?null:{kind:"value",file:l.file,root:l.root,path:u?.[0]??p,sourceKind:"repeat-template",collectionIndexMap:l.collectionIndexMap,...u?{collectionPathMap:u}:{}}}let r=e.expressionPath.scope.getBinding(t.base);if(!r)return null;if(r.path.isImportNamespaceSpecifier()){let l=t.path[0],u=r.path.parentPath;if(!l||l.kind!=="property"||!u?.isImportDeclaration())return null;let d=await Rn(e.currentFile,u.node.source.value,e.exists);if(!d)return null;let p=await Zo({file:d,exportName:l.name,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(!p||p.kind==="external")return null;let m=t.path.slice(1);return dt(p.value,m)===void 0?null:{kind:"value",file:p.file,root:p.root,path:m,sourceKind:"imported-binding",collectionIndexMap:p.collectionIndexMap}}let o=Zu(r);if(o){let l=o.expressionPath,u=await ft({expression:l.node,scope:l.scope,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(u){let d=await Xe({...e,expressionPath:l,sourceInfo:{...u,expression:Qo(u.expression,t.path),path:[...u.path,...t.path]}});if(d)return d}if(t.path.length===0){let d=await uf({currentFile:e.currentFile,expressionPath:l,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(d)return d}}if(r.kind==="param")return cE({currentFile:e.currentFile,binding:r,sourceInfo:t,graph:e.graph,readFile:e.readFile,exists:e.exists,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});let i=await VS({currentFile:e.currentFile,binding:r,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(i)return i;let s=$o(r,t.path);if(fr(s))return Vd(e.currentFile,s.sourceId,s.displayPath);let a=await mn({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:dt(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 ff(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=at(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!JS(s,r)?null:{callPath:s,basePath:i}}function JS(e,t){let n=e.node.callee;return!v.isMemberExpression(n)||!v.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}async function pf(e){let{currentFile:t,callPath:n,readFile:r,exists:o,fileCache:i,visited:s}=e,a=n.node.callee;if(!v.isMemberExpression(a)||!v.isIdentifier(a.property)||a.property.name!=="map")return null;let c=n.get("callee");if(!c.isMemberExpression())return null;let l=c.get("object");if(Array.isArray(l)||!l.isExpression())return null;let u=await Cr({currentFile:t,expressionPath:l,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});return!u||!Array.isArray(u.value)||u.value.length===0?null:u}function XS(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:Uo(r,t)}async function Cr(e){let{currentFile:t,expressionPath:n,readFile:r,exists:o,fileCache:i,visited:s}=e;if(n.isIdentifier()){let a=n.scope.getBinding(n.node.name);if(!a)return null;let c=await mn({currentFile:t,binding:a,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});return c?.kind==="static"?c:null}if(n.isCallExpression())return mf({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 Cr({...e,expressionPath:a})}if(n.isArrayExpression()){let a=nf(n.node);if(!a)return null;let c=await pt(n.node,n.scope,t,r,o,i,s);return Array.isArray(c)?{kind:"static",file:t,root:{kind:"expression",sourceRange:a},value:c,sourceKind:"binding"}:null}if(n.isMemberExpression()){let a=await ft({expression:n.node,scope:n.scope,currentFile:t,readFile:r,exists:o,fileCache:i,visited:s});if(!a)return null;let c=await Xe({currentFile:t,expressionPath:n,sourceInfo:a,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(!c||c.kind==="external")return null;let l=await zS({currentFile:t,expressionPath:n,provenance:c,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(!l||l.kind!=="static")return null;if(c.collectionPathMap?.length){let d=mE(l.value,c.collectionPathMap);if(d)return{kind:"static",file:c.file,root:c.root,value:d.value,sourceKind:c.sourceKind,collectionPathMap:d.collectionPathMap}}let u=dt(l.value,c.path);return Array.isArray(u)?{kind:"static",file:c.file,root:c.root,value:u,sourceKind:c.sourceKind,pathPrefix:c.path,collectionIndexMap:c.collectionIndexMap,collectionPathMap:c.collectionPathMap}:null}return null}async function zS(e){let{provenance:t}=e;if(t.root.kind==="binding"){let i=e.expressionPath.scope.getBinding(t.root.name);if(!i&&t.file!==e.currentFile){let s=await Yt(t.file,e.readFile,e.fileCache);i=s.ast?ba(s.ast).getBinding(t.root.name):void 0}return i?await mn({currentFile:t.file,binding:i,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited}):null}if(t.root.kind!=="expression")return null;let n=await Yt(t.file,e.readFile,e.fileCache);if(!n.ast)return null;let r=hS(n.ast,t.root.sourceRange);if(!r)return null;let o=await pt(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 mf(e){return await WS(e)??await HS(e)??await GS(e)}async function WS(e){let{callPath:t}=e,n=t.node.callee;if(!v.isMemberExpression(n)||!v.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 Cr({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(!v.isArrowFunctionExpression(s)&&!v.isFunctionExpression(s))return null;let a=s.params[0];if(!v.isIdentifier(a))return null;let c=YS(s);if(!c)return null;let l=[],u=[],d=[];for(let[p,m]of i.value.entries()){let g=ZS(c,a.name,m);if(typeof g!="boolean")return null;if(g){l.push(m),u.push(i.collectionIndexMap?.[p]??p);let b=i.collectionPathMap?.[p];b&&d.push(b)}}return{...i,value:l,pathPrefix:i.pathPrefix,collectionIndexMap:u,...d.length>0?{collectionPathMap:d}:{}}}async function HS(e){let{callPath:t}=e,n=t.node.callee;if(!v.isMemberExpression(n)||!v.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 Cr({currentFile:e.currentFile,expressionPath:o,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(!i||!Array.isArray(i.value))return null;let[s,a]=t.node.arguments,c=Hd(s,0),l=Hd(a,i.value.length);if(c===null||l===null)return null;let u=Math.max(0,c<0?i.value.length+c:c),d=Math.max(0,l<0?i.value.length+l:l),p=i.value.map((g,b)=>i.collectionIndexMap?.[b]??b).slice(u,d),m=i.collectionPathMap?.slice(u,d);return{...i,value:i.value.slice(u,d),pathPrefix:i.pathPrefix,collectionIndexMap:p,...m?{collectionPathMap:m}:{}}}function Hd(e,t){return e?v.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}async function GS(e){let{callPath:t}=e,n=t.node.callee;if(!v.isMemberExpression(n)||!v.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 Cr({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(!v.isArrowFunctionExpression(s)&&!v.isFunctionExpression(s))return null;let[a,c]=s.params;if(!v.isIdentifier(a)||!v.isIdentifier(c))return null;let l=i.value.map((d,p)=>({value:d,sourceIndex:i.collectionIndexMap?.[p]??p,originalIndex:p})),u=[...l];for(let d of l)for(let p of l)if(Gd(s,a.name,c.name,d.value,p.value)===void 0)return null;return u.sort((d,p)=>{let m=Gd(s,a.name,c.name,d.value,p.value)??0;return m===0?d.originalIndex-p.originalIndex:m}),{...i,value:u.map(d=>d.value),pathPrefix:i.pathPrefix,collectionIndexMap:u.map(d=>d.sourceIndex),...i.collectionPathMap?{collectionPathMap:u.map(d=>i.collectionPathMap?.[d.originalIndex]).filter(d=>!!d)}:{}}}function Gd(e,t,n,r,o){let i=v.isExpression(e.body)?e.body:e.body.body.find(a=>v.isReturnStatement(a))?.argument;if(!i||!v.isExpression(i))return;let s=ya(i,t,n,r,o);return typeof s=="number"?s:void 0}function ya(e,t,n,r,o){if(v.isNumericLiteral(e)||v.isStringLiteral(e)||v.isBooleanLiteral(e))return e.value;if(v.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(v.isMemberExpression(e)){let i=xa(e,t);if(i)return dt(r,i);let s=xa(e,n);return s?dt(o,s):void 0}if(v.isBinaryExpression(e)&&e.operator==="-"){let i=v.isExpression(e.left)?ya(e.left,t,n,r,o):void 0,s=v.isExpression(e.right)?ya(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function YS(e){if(v.isExpression(e.body))return e.body;for(let t of e.body.body)if(v.isReturnStatement(t)&&t.argument&&v.isExpression(t.argument))return t.argument;return null}function ZS(e,t,n){let r=pn(e,t,n);return typeof r=="boolean"?r:void 0}function pn(e,t,n){if(v.isStringLiteral(e)||v.isNumericLiteral(e)||v.isBooleanLiteral(e))return e.value;if(v.isNullLiteral(e))return null;if(v.isIdentifier(e))return e.name===t?n:void 0;if(v.isMemberExpression(e)){let r=xa(e,t);return r?dt(n,r):void 0}if(v.isUnaryExpression(e)&&e.operator==="!"){let r=pn(e.argument,t,n);return r===void 0?void 0:!r}if(v.isLogicalExpression(e)){let r=pn(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&pn(e.right,t,n);if(e.operator==="||")return r||pn(e.right,t,n)}if(v.isBinaryExpression(e)){let r=v.isExpression(e.left)?pn(e.left,t,n):void 0,o=v.isExpression(e.right)?pn(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 xa(e,t){let n=[],r=e;for(;v.isMemberExpression(r);){if(r.computed)if(v.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(v.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!v.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!v.isIdentifier(r)||r.name!==t?null:n}async function mn(e){let{currentFile:t,binding:n,readFile:r,exists:o,fileCache:i,visited:s}=e,a=`${t}::${n.kind}::${n.identifier.name}`;if(s.has(a))return null;s.add(a);try{let c=await QS({currentFile:t,binding:n,readFile:r,exists:o,fileCache:i,visited:s});if(c)return c;if(n.path.isImportSpecifier()||n.path.isImportDefaultSpecifier())return await dE({currentFile:t,binding:n,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,fileCache:i,visited:s});if(n.kind==="param")return null;if(n.path.isVariableDeclarator()){let l=n.path.node.init;if(!l||!v.isExpression(l))return null;let u=n.path.get("init");if(u&&!Array.isArray(u)&&u.isExpression()){let p=await wa({currentFile:t,expressionPath:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(p)return p;if(u.isCallExpression()){let m=await mf({currentFile:t,callPath:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});if(m)return m}}let d=await pt(l,n.path.scope,t,r,o,i,s);return d===void 0?null:{kind:"static",file:t,root:{kind:"binding",name:n.identifier.name},value:d,sourceKind:"binding"}}if(n.path.isIdentifier()&&n.path.parentPath?.isExportDefaultDeclaration()){let l=n.path.parentPath.node.declaration;if(!v.isExpression(l))return null;let u=await pt(l,n.path.scope,t,r,o,i,s);return u===void 0?null:{kind:"static",file:t,root:{kind:"binding",name:n.identifier.name},value:u,sourceKind:"binding"}}return null}finally{s.delete(a)}}async function QS(e){let{currentFile:t,binding:n,readFile:r,exists:o,fileCache:i,visited:s}=e;if(!n.path.isVariableDeclarator()||!n.path.get("id").isArrayPattern())return null;let a=n.path,c=a.node.init;if(!c||!v.isCallExpression(c))return null;let l=qS(c);if(!l||!v.isArrayPattern(a.node.id)||a.node.id.elements.findIndex(g=>v.isIdentifier(g)&&g.name===n.identifier.name)!==0)return null;let d=l==="useReducer"?1:0,p=c.arguments[d];if(!p||!v.isExpression(p))return null;let m=await pt(p,a.scope,t,r,o,i,s);return m===void 0?null:{kind:"static",file:t,root:{kind:"hook-state",name:n.identifier.name,hook:l},value:m,sourceKind:"binding"}}function qS(e){return v.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:v.isMemberExpression(e.callee)&&v.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function eE(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()||!v.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 tE(e,t){let n=eE(e.path);if(!n)return null;let r=Vn(e,t);return r?{...n,...r}:null}function Qo(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function nE(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}async function rE(e){let t=iE(e.expressionPath.node);if(!t||!sE(t.segments))return null;let n=await Xe({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 oE({...e,rootPath:n.path,segments:t.segments});return r?{...n,path:r.collectionPathMap[0]??n.path,sourceKind:"repeat-template",displayExpression:kr(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:r.collectionPathMap}:null}async function oE(e){let t=null,n,r=[];for(let i of e.segments){if(i.kind!=="dynamic")continue;let s=await ft({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=ff(e.expressionPath,s.base);if(!a)return null;let c=await pf({currentFile:e.currentFile,callPath:a.callPath,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(!c||!Array.isArray(c.value))return null;let l=c.value.map((u,d)=>{let p=dt(c.value,[{kind:"index",index:d},...a.basePath,...s.path]);return aE(p)});if(l.some(u=>u===null)||t!==null&&t!==l.length)return null;t=l.length,n??=c.collectionIndexMap,r.push(l)}if(t===null||t===0)return null;let o=[];for(let i=0;i<t;i+=1){let s=[...e.rootPath],a=0;for(let c of e.segments){if(c.kind==="dynamic"){let l=r[a]?.[i];if(!l)return null;s.push(l),a+=1;continue}s.push({...c})}o.push(s)}return{...n?{collectionIndexMap:n}:{},collectionPathMap:o}}function iE(e){let t=[],n=e;for(;v.isMemberExpression(n)||v.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(v.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(v.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(v.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(v.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return v.isIdentifier(n)?{base:n.name,segments:t}:null}function sE(e){return e.some(t=>t.kind==="dynamic")}function aE(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}async function cE(e){let t=tE(e.binding,e.sourceInfo);if(!t||!e.graph)return null;let n=[...e.graph.elements.values()].filter(l=>nE(l,e.currentFile,t.componentName,t.exportName));if(n.length!==1)return null;let r=n[0],o=r.attributes?.find(l=>l.name===t.propName);if(o&&!o.source){let l=await lE({caller:r,propName:t.propName,remainingPath:t.remainingPath,readFile:e.readFile,fileCache:e.fileCache});if(l)return pa(l,{componentName:t.componentName,propName:t.propName,file:r.sourceFile})}if(!o?.source){let l=await uE({caller:r,propName:t.propName,remainingPath:t.remainingPath,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(l)return pa(l,{componentName:t.componentName,propName:t.propName,file:r.sourceFile});let u=qu(e.binding,t.componentName,t.propName);if(!u||u.propName!==t.propName)return null;let d=await pt(u.expressionPath.node,u.expressionPath.scope,e.currentFile,e.readFile,e.exists,e.fileCache,e.visited);if(d===void 0)return null;let p=t.remainingPath;return p.length>0&&dt(d,p)===void 0?null:{kind:"value",file:e.currentFile,root:{kind:"binding",name:t.propName},path:p,sourceKind:"binding",semanticKind:"component-prop",displayExpression:u.displayPath,chainPrefix:[{kind:"component-prop",file:e.currentFile,displayName:u.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let i=await Yt(r.sourceFile,e.readFile,e.fileCache);if(!i.ast)return null;let s=rf(i.ast,i.source,o.source.expression,o.sourceRange)??Ra(i.ast,i.source,o.source.expression);if(!s)return null;let a={...o.source,expression:Qo(o.source.expression,t.remainingPath),path:[...o.source.path,...t.remainingPath]},c=await Xe({currentFile:r.sourceFile,expressionPath:s,sourceInfo:a,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return c?pa(c.kind==="external"?c:{...c,displayExpression:a.expression},{componentName:t.componentName,propName:t.propName,file:r.sourceFile}):null}async function lE(e){let t=await Yt(e.caller.sourceFile,e.readFile,e.fileCache);if(!t.ast)return null;let n=tf(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=nf(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 uE(e){let t=await Yt(e.caller.sourceFile,e.readFile,e.fileCache);if(!t.ast)return null;let n=tf(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 ft({expression:i.node,scope:i.scope,source:t.source,currentFile:e.caller.sourceFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(!s)continue;let a=[{kind:"property",name:e.propName},...e.remainingPath],c={...s,expression:Qo(s.expression,a),path:[...s.path,...a]},l=await Xe({currentFile:e.caller.sourceFile,expressionPath:i,sourceInfo:c,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(l)return l.kind==="external"?l:{...l,displayExpression:c.expression}}return null}function pa(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 dE(e){let{currentFile:t,binding:n,readFile:r,exists:o,fileCache:i,visited:s}=e,a=n.path.parentPath;if(!a||!a.isImportDeclaration())return null;let c=a.node.source.value;if(typeof c!="string")return null;let l=await Rn(t,c,o);if(!l)return null;if(n.path.isImportDefaultSpecifier()){let b=await Yt(l,r,i),C=b.ast?Sa(b.ast,"default"):null,I=await Zo({file:l,exportName:"default",readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});return!I||I.kind!=="static"?null:{kind:"static",file:C?.kind==="default-expression"?I.file:l,root:C?.kind==="default-expression"?I.root:{kind:"default-export"},value:I.value,sourceKind:"imported-binding"}}if(!n.path.isImportSpecifier())return null;let u=n.path.node.imported,d=v.isIdentifier(u)?u.name:u.value,p=await Yt(l,r,i),m=p.ast?Sa(p.ast,d):null,g=await Zo({file:l,exportName:d,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s});return g?g.kind==="external"?g:{kind:"static",file:m?.kind==="re-export"?g.file:l,root:m?.kind==="re-export"?g.root:{kind:"named-export",name:d},value:g.value,sourceKind:"imported-binding"}:null}async function Zo(e){let{file:t,exportName:n,readFile:r,exists:o,fileCache:i,visited:s}=e,a=`export::${t}::${n}`;if(!s.has(a)){s.add(a);try{let c=await Yt(t,r,i);if(!c.ast)return;let l=Sa(c.ast,n);if(!l)return;if(l.kind==="default-expression"){let m=l.expression;if(!m||!v.isIdentifier(m))return;let g=ba(c.ast).getBinding(m.name);return g?await mn({currentFile:t,binding:g,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s})??void 0:void 0}if(l.kind==="re-export"){if(!l.source||!l.name)return;let m=await Rn(t,l.source,o);return m?Zo({...e,file:m,exportName:l.name}):void 0}let u=l.name;if(!u)return;let d=ba(c.ast).getBinding(u);return d?await mn({currentFile:t,binding:d,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:s})??void 0:void 0}finally{s.delete(a)}}}function ba(e){let t=null;if(Zd(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}function Sa(e,t){for(let n of e.program.body){if(t==="default"&&v.isExportDefaultDeclaration(n))return v.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:(v.isFunctionDeclaration(n.declaration)||v.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if(v.isExportNamedDeclaration(n)){if(n.declaration){if(v.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if(v.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if((v.isFunctionDeclaration(n.declaration)||v.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if((v.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&v.isExportSpecifier(r))return n.source?{kind:"re-export",name:r.local.name,source:n.source.value}:{kind:"local-binding",name:r.local.name}}}return null}async function pt(e,t,n,r,o,i,s){if(v.isStringLiteral(e)||v.isNumericLiteral(e)||v.isBooleanLiteral(e))return e.value;if(v.isNullLiteral(e))return null;if(v.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(v.isTSAsExpression(e)||v.isTSSatisfiesExpression(e)||v.isTSNonNullExpression(e))return await pt(e.expression,t,n,r,o,i,s);if(v.isIdentifier(e)){let a=t.getBinding(e.name);if(!a)return;let c=await mn({currentFile:n,binding:a,readFile:r,exists:o,fileCache:i,visited:s});return c?.kind==="static"?c.value:void 0}if(v.isArrayExpression(e)){let a=[];for(let c of e.elements){if(!c||v.isSpreadElement(c))return;let l=await ma(c,t,n,r,o,i,s);if(l===void 0)return;a.push(l)}return a}if(v.isObjectExpression(e)){let a={};for(let c of e.properties){if(!v.isObjectProperty(c)||c.computed)return;let l=null;if(v.isIdentifier(c.key)?l=c.key.name:v.isStringLiteral(c.key)&&(l=c.key.value),!l)return;if(c.shorthand){if(!v.isIdentifier(c.value))return;let d=await ma(c.value,t,n,r,o,i,s);if(d===void 0)return;a[l]=d;continue}if(!v.isExpression(c.value))return;let u=await ma(c.value,t,n,r,o,i,s);u!==void 0&&(a[l]=u)}return a}if(v.isMemberExpression(e)){let a=await gf(e,t,n,r,o,i,s);if(!a)return;let c=t.getBinding(a.base);if(!c)return;let l=await mn({currentFile:n,binding:c,readFile:r,exists:o,fileCache:i,visited:s});return!l||l.kind!=="static"?void 0:dt(l.value,a.path)}}async function ma(e,t,n,r,o,i,s){if(!v.isSpreadElement(e))return await pt(e,t,n,r,o,i,s)}async function gf(e,t,n,r,o,i,s){if(v.isIdentifier(e))return{base:e.name,path:[]};if(!v.isMemberExpression(e))return null;let a=[],c=e;for(;v.isMemberExpression(c);){if(c.computed){let l=c.property;if(v.isNumericLiteral(l))a.unshift({kind:"index",index:l.value});else if(v.isStringLiteral(l))a.unshift({kind:"property",name:l.value});else{let u=v.isExpression(l)?await pt(l,t,n,r,o,i,s):void 0;if(typeof u=="string")a.unshift({kind:"property",name:u});else if(Number.isInteger(u))a.unshift({kind:"index",index:u});else return null}}else{if(!v.isIdentifier(c.property))return null;a.unshift({kind:"property",name:c.property.name})}c=c.object}return v.isIdentifier(c)?{base:c.name,path:a}:null}function fE(e){if(v.isIdentifier(e))return{base:e.name,path:[]};if(!v.isMemberExpression(e))return null;let t=[],n=e;for(;v.isMemberExpression(n);){if(n.computed)if(v.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(v.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!v.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return v.isIdentifier(n)?{base:n.name,path:t}:null}function dt(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 pE(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 mE(e,t){let n=[],r=[];for(let o of t){let i=dt(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 Yt(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=ef(o),s={source:o,ast:i};return n.set(e,s),s}import Ma from"@babel/generator";import{parse as PE}from"@babel/parser";import Da from"@babel/traverse";import*as k from"@babel/types";import*as It from"@babel/types";import Ta from"@babel/generator";import*as ue from"@babel/types";var gE=typeof Ta=="function"?Ta:Ta.default,hE=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,yE=/^((?:https?:)?\/\/)[^/@\s]+@/i,xE=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function yf(e,t){let n=vt(e.callee);if(!n)return null;if(n==="fetch")return Fa(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(hf(r))return Fa(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(hf(r))return Fa(e.arguments[0],r,t,["ky client contract"])}return null}function Fa(e,t,n,r){if(!e||ue.isSpreadElement(e)||ue.isJSXNamespacedName(e))return vE(t,n,r,"missing url argument");let o=Rr(e);return{sourceKind:EE(o),...o?{endpointPattern:o}:{},method:t,confidence:o?"exact":"partial",evidence:[{file:n.file,reason:[...r,o?"endpoint pattern resolved":"endpoint pattern unresolved"].join("; ")}]}}function Rr(e){if(ue.isStringLiteral(e))return qo(e.value);if(ue.isTemplateLiteral(e))return qo(bE(e));if(ue.isBinaryExpression(e)&&e.operator==="+"){let t=Rr(e.left),n=Rr(e.right);return!t&&!n?void 0:qo(`${t??_a(e.left)}${n??_a(e.right)}`)}if(ue.isMemberExpression(e)){let t=xf(e);if(t)return`env:${t}`}if(!(ue.isCallExpression(e)&&vt(e.callee)==="new URL")){if(ue.isNewExpression(e)&&ue.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!ue.isSpreadElement(t)?Rr(t):void 0,o=n&&!ue.isSpreadElement(n)?Rr(n):void 0;return o&&r?qo(`${o} + ${r}`):r??o}if(ue.isIdentifier(e))return`:${e.name}`}}function bE(e){let t="";for(let n=0;n<e.quasis.length;n+=1){t+=e.quasis[n]?.value.cooked??e.quasis[n]?.value.raw??"";let r=e.expressions[n];r&&(t+=_a(r))}return t}function _a(e){if(ue.isIdentifier(e))return`:${e.name}`;if(ue.isMemberExpression(e)){let t=xf(e);if(t)return`env:${t}`}return`:${SE(e)}`}function SE(e){return gE(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function qo(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(yE,"$1<redacted>@").replace(xE,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?hE.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function EE(e){return e?e.startsWith("/api/")?"site-api-route":/^(?:https?:)?\/\//.test(e)||e.startsWith("env:")?"external-api":e.startsWith("/")?"site-api-route":"unknown-api":"unknown-api"}function vE(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function hf(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function xf(e){return!ue.isMemberExpression(e.object)||!ue.isIdentifier(e.object.object,{name:"process"})||!IE(e.object.property,"env")?null:ue.isIdentifier(e.property)?e.property.name:ue.isStringLiteral(e.property)?e.property.value:null}function IE(e,t){return ue.isIdentifier(e)&&e.name===t}function vt(e){if(ue.isIdentifier(e))return e.name;if(ue.isMemberExpression(e)){let t=vt(e.object),n=ue.isIdentifier(e.property)?e.property.name:ue.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var kE=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),CE=new Set(["getConfig","submit"]);function bf(e,t){let n=RE(vt(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!kE.has(i))return null;let s=Oa(e,0),a=i==="getByUrl"||i==="getByUrlStrict",c=a?void 0:s,l=a?s??"/:record-url":c?`/collections/${c}`:"/collections/:collection";return{sourceKind:"vcp-cms-collection",sourceType:"cms-field",operation:i,...c?{collection:c}:{},endpointPattern:l,confidence:s?"exact":"partial",evidence:[{file:t.file,symbol:n,reason:"VCP CMS collection facade"}]}}let o="cms.forms.";if(n.startsWith(o)){let i=n.slice(o.length);if(!CE.has(i))return null;let s=Oa(e,0);return{sourceKind:"vcp-cms-form",sourceType:"cms-field",operation:i,...s?{collection:s}:{},endpointPattern:s?`/forms/${s}`:"/forms/:form",confidence:s?"exact":"partial",evidence:[{file:t.file,symbol:n,reason:"VCP CMS form facade"}]}}if(n==="cmsFetch"||n==="cmsFetchResult"||n==="cmsFetchEnvelope"){let i=Oa(e,0)??wE(e,0,"path")??"/cms/:path",s=NE(i);return{sourceKind:"vcp-cms-collection",sourceType:"cms-field",operation:n,...s?{collection:s}:{},endpointPattern:i,confidence:i==="/cms/:path"?"partial":"safe-derived",evidence:[{file:t.file,symbol:n,reason:"VCP CMS fetch helper"}]}}return null}function RE(e,t){let n=e?.indexOf(".")??-1;if(!e||n<1)return e;let r=t.imports?.get(e.slice(0,n));return r?.importedName==="collections"&&/(?:^|\/)lib\/cms\/collections(?:\.js)?$/.test(r.source)?`cms.collections${e.slice(n)}`:e}function Sf(e,t){let n=vt(e);return n==="cms.settings"?{sourceKind:"vcp-cms-settings",sourceType:"cms-field",operation:"settings",endpointPattern:"/settings",confidence:"exact",evidence:[{file:t.file,symbol:n,reason:"VCP CMS settings facade"}]}:n==="cms.navigation"?{sourceKind:"vcp-cms-navigation",sourceType:"cms-field",operation:"navigation",endpointPattern:"/navigation",confidence:"exact",evidence:[{file:t.file,symbol:n,reason:"VCP CMS navigation facade"}]}:null}function Ef(e){let t=vt(e.callee);return typeof t=="string"&&t.startsWith("cms.field.")}function Oa(e,t){let n=e.arguments[t];return It.isStringLiteral(n)?n.value:null}function wE(e,t,n){let r=e.arguments[t];if(!It.isObjectExpression(r))return null;for(let o of r.properties)if(It.isObjectProperty(o)&&!o.computed&&(It.isIdentifier(o.key)&&o.key.name===n||It.isStringLiteral(o.key)&&o.key.value===n)&&It.isStringLiteral(o.value))return o.value.value;return null}function NE(e){return/^\/collections\/([^/]+)(?:\/|$)/.exec(e)?.[1]??null}var Ba=typeof Da=="function"?Da:Da.default,WA=typeof Ma=="function"?Ma:Ma.default,AE={maxFunctionDepth:8,maxImportDepth:6},TE=new Set(["src","href","alt","poster","content","title","aria-label"]);async function wf(e){let t=e.fileCache??new Map,n=Va(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...AE,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:Vf(n,e.element.componentName)};await Nf(e.element.componentName,e.graph,r);let o=[];o.push(...await DE(e.element,e.graph,r),...await LE(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await BE(s,e.element,e.graph,r);a&&o.push(ni(a,"text","children"))}for(let s of e.element.attributes??[]){let a=ME(s,e.element);if(!a)continue;let c=await Tf(s.source,e.element,e.graph,r);c&&o.push(ni(c,a,s.name))}let i=qE(o).sort(jf);return{hasDynamicData:i.length>0,bindings:i}}async function Nf(e,t,n){if(n.importDepth>=n.options.maxImportDepth)return;let r=n.analysis.functions.get(e)??n.analysis.functions.get("default"),o=r?.params[0];if(!r||!o)return;let i=n.analysis.functions.get("default")===r?"default":e,s=[];for(let l of t.elements.values()){if(l.sourceFile===n.file&&l.tag===e){s.push(l);continue}!l.importedFrom||!l.exportName||l.importedFrom===n.file&&l.exportName!==i||(l.importedFrom===n.file||await Pf(l.importedFrom,l.exportName,n.file,n))&&s.push(l)}if(s.length===0)return;let a=new Map;for(let l of s){let u=`${n.file}#${e}<-${l.identity.key}`;if(!n.resolvingComponentProps.has(u)){n.resolvingComponentProps.add(u);try{let d=await Af(l.sourceFile,n);if(!d)continue;let p=oi(d,n,{importDepth:n.importDepth+1});p.paramSources.clear(),p.scopeVariables=Vf(d,l.componentName),await Nf(l.componentName,t,p);let m=await FE(l,p);for(let[g,b]of m){if(!b)continue;let C=a.get(g)??[];C.push(b),a.set(g,C)}}finally{n.resolvingComponentProps.delete(u)}}}let c=new Map;for(let[l,u]of a){let d=Lf(u);d.length===1&&c.set(l,d[0])}OE(o,c,n)}async function Pf(e,t,n,r,o=new Set){if(e===n)return!0;if(o.size>=r.options.maxImportDepth||o.has(`${e}#${t}`))return!1;o.add(`${e}#${t}`);let s=(await Af(e,r))?.imports.get(t);if(!s||!xt(s.source))return!1;let a=await Jf(e,s.source,r.exists);return a?a===n?!0:Pf(a,s.importedName,n,r,o):!1}async function FE(e,t){let n=new Map;Ba(t.analysis.ast,{JSXElement(o){if(_E(o.node,e.sourceRange)){for(let i of o.node.openingElement.attributes)!k.isJSXAttribute(i)||!k.isJSXIdentifier(i.name)||!k.isJSXExpressionContainer(i.value)||!k.isExpression(i.value.expression)||n.set(i.name.name,i.value.expression);o.stop()}}});let r=new Map;for(let[o,i]of n){let s=await we(i,t);s&&r.set(o,s)}return r}function _E(e,t){return e.loc?.start.line===t.startLine&&e.loc.start.column===t.startColumn&&e.loc.end.line===t.endLine&&e.loc.end.column===t.endColumn}async function Af(e,t){let n=t.fileCache.get(e);if(n)return n;if(!await t.exists(e))return null;let r=await t.readFile(e);return Va(e,r,t.fileCache)}function OE(e,t,n){if(k.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,$a(Object.fromEntries(t),n.file));return}if(k.isObjectPattern(e))for(let r of e.properties){if(!k.isObjectProperty(r)||r.computed||!k.isIdentifier(r.key))continue;let o=t.get(r.key.name);if(!o)continue;let i=k.isAssignmentPattern(r.value)?r.value.left:r.value;k.isIdentifier(i)&&n.paramSources.set(i.name,Fe(o))}}function ME(e,t){return e.name==="dangerouslySetInnerHTML"?"richtext":TE.has(e.name)?"attribute":t.importedFrom||/^[A-Z]/.test(t.tag)?"component-prop":null}async function DE(e,t,n){let r=[];for(let o of t.regions){if(o.kind!=="repeat-region"||o.ownerKey!==e.identity.key)continue;let i=o.sourceCandidates?.find(a=>a.kind==="repeat-template");if(!i)continue;let s=await ri(i.collectionSource,n);s&&r.push(ni(gn(s),"repeat-region",i.collectionExpression))}return r}async function LE(e,t,n){let r=[];for(let o of t.regions){if(o.kind!=="conditional-region"||o.ownerKey!==e.identity.key)continue;let i=o.sourceCandidates?.find(a=>a.kind==="conditional-branch");if(!i)continue;let s=await ri(i.conditionSource,n);s&&r.push(ni(gn(s),"conditional-region",i.conditionExpression))}return r}async function BE(e,t,n,r){return Tf(e.source,t,n,r)}async function Tf(e,t,n,r){let o=await jE(e,t,n,r);return o||ri(e,r)}async function jE(e,t,n,r){if(!e)return null;let o=$E(e.base,t,n);if(!o)return null;let i=await ri(o.collectionSource,r);return i?Ar(i,e.path,!0):null}function $E(e,t,n){let r=t.identity.key;for(;r;){for(let o of n.regions){if(o.kind!=="repeat-region"||!o.childKeys.includes(r))continue;let i=o.sourceCandidates?.find(s=>s.kind==="repeat-template"&&s.itemParamName===e);if(i)return i}r=n.elements.get(r)?.parentKey??null}return null}async function ri(e,t){if(!e)return null;let n=await Ff(e.base,t);return n?Ar(n,e.path,!1):null}async function Ff(e,t){let n=t.paramSources.get(e);if(n)return Fe(n);if(t.variableCache.has(e))return ev(t.variableCache.get(e)??null);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let r=await VE(e,t);if(r)return t.variableCache.set(e,Fe(r)),t.resolvingVariables.delete(e),r;let o=t.scopeVariables?.get(e)??t.analysis.variables.get(e);if(o){let s=await we(o,t);return t.variableCache.set(e,s?Fe(s):null),t.resolvingVariables.delete(e),s}let i=t.analysis.imports.get(e);if(i&&t.importDepth<t.options.maxImportDepth){let s=await Uf(i,t);if(s){let a=oi(s,t,{importDepth:t.importDepth+1}),c=Kf(i,s);if(c){let d=(await hn(c,[],a)).returnSource;return t.variableCache.set(e,d?Fe(d):null),t.resolvingVariables.delete(e),d}let l=s.variables.get(i.importedName);if(l){let u=await we(l,a);return t.variableCache.set(e,u?Fe(u):null),t.resolvingVariables.delete(e),u}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}async function VE(e,t){let n=t.analysis.stateSetters.get(e);if(!n)return null;let r=[];Ba(t.analysis.ast,{CallExpression(o){if(k.isIdentifier(o.node.callee,{name:n})){let i=o.node.arguments[0];k.isExpression(i)&&r.push(i);return}o.node.arguments.some(i=>k.isIdentifier(i)&&i.name===n)&&r.push(o.node)}});for(let o of r){let i=await we(o,t);if(i)return i}return null}async function we(e,t){if(k.isIdentifier(e))return Ff(e.name,t);if(k.isMemberExpression(e)||k.isOptionalMemberExpression(e)){let n=k.isMemberExpression(e)?Sf(e,{file:t.file}):null;if(n)return Df(n);let r=await UE(e,t);if(!r)return null;let o=ZE(e);return Ar(r,o,!1)}if(k.isAwaitExpression(e))return k.isExpression(e.argument)?we(e.argument,t):null;if(k.isCallExpression(e))return _f(e,t);if(k.isObjectExpression(e)){let n=await Of(e,t);return Object.keys(n).length>0?$a(n,t.file):null}if(k.isConditionalExpression(e)){let n=await we(e.consequent,t),r=await we(e.alternate,t);return Pr(If(n,r))}if(k.isLogicalExpression(e)){let n=await we(e.left,t),r=await we(e.right,t);return Pr(If(n,r))}return k.isTSAsExpression(e)||k.isTSSatisfiesExpression(e)||k.isTSNonNullExpression(e)||k.isTypeCastExpression(e)||k.isParenthesizedExpression(e)?we(e.expression,t):null}async function UE(e,t){let n=e;for(;k.isMemberExpression(n)||k.isOptionalMemberExpression(n);)n=n.object;return k.isExpression(n)?we(n,t):null}async function _f(e,t){let n=bf(e,{file:t.file,imports:t.analysis.imports});if(n)return Df(n);if(Ef(e)){let d=e.arguments[0];if(d&&k.isExpression(d))return Pr(await we(d,t))}let r=await KE(e,t);if(r)return r;let o=yf(e,{file:t.file});if(o)return{sourceKind:o.sourceKind,sourceType:"api-field",endpointPattern:o.endpointPattern,valuePath:o.valuePath,confidence:o.confidence,readonly:!0,evidence:o.evidence};let i=await zE(e,t);if(i)return i;let s=await WE(e,t);if(s)return s;let a=await HE(e,t);if(a)return a;let c=await GE(e,t);if(c)return c;let l=[];for(let d of e.arguments)if(k.isExpression(d)){let p=await we(d,t);p&&l.push(p)}let u=Lf(l);return u.length===1?Pr(u[0]):null}async function KE(e,t){let n=vt(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=XE(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(k.isIdentifier(s)){let a=await Nr(s.name,t);if(a)return(await hn(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!k.isObjectExpression(r))return ei(t.file,`${n} without static options`);let o=JE(r,"queryFn");if(!o)return ei(t.file,`${n} without queryFn`);if(k.isIdentifier(o)){let i=await Nr(o.name,t);return i?(await hn(i.node,[],i.context)).returnSource:ei(t.file,`${n} queryFn unresolved`)}return k.isArrowFunctionExpression(o)||k.isFunctionExpression(o)?(await hn(o,[],t)).returnSource:k.isCallExpression(o)?_f(o,t):null}function JE(e,t){for(let n of e.properties){if(!k.isObjectProperty(n)||!k.isExpression(n.value))continue;if(Mf(n)===t)return n.value}return null}function XE(e,t,n){return k.isStringLiteral(e)?{sourceKind:e.value.startsWith("/api/")?"site-api-route":"external-api",sourceType:"api-field",endpointPattern:e.value,confidence:"exact",readonly:!0,evidence:[{file:t,reason:n}]}:null}async function zE(e,t){if(!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property))return null;let n=e.callee.property.name;if(!["map","filter","slice","sort","toSorted"].includes(n))return null;let r=k.isExpression(e.callee.object)?await we(e.callee.object,t):null;if(!r)return null;if(n!=="map")return gn(r);let o=e.arguments[0];if(k.isIdentifier(o)){let i=await Nr(o.name,t);if(!i)return gn(r);let s=await hn(i.node,[r],i.context);return{...gn(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(k.isArrowFunctionExpression(o)||k.isFunctionExpression(o)){let i=await hn(o,[r],t);return{...gn(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return gn(r)}async function WE(e,t){return!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property,{name:"json"})||!k.isExpression(e.callee.object)?null:we(e.callee.object,t)}async function HE(e,t){return!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property,{name:"then"})||!k.isExpression(e.callee.object)?null:Pr(await we(e.callee.object,t))}async function GE(e,t){if(!k.isIdentifier(e.callee))return null;let n=await Nr(e.callee.name,t);if(!n)return null;let r=[];for(let i of e.arguments){if(!k.isExpression(i)){r.push(ei(t.file,`unsupported argument for ${e.callee.name}`));continue}let s=await we(i,t);r.push(s)}return(await hn(n.node,r,n.context)).returnSource}async function Nr(e,t){let n=t.analysis.functions.get(e);if(n)return{node:n,context:t};let r=t.analysis.imports.get(e);if(!r||t.importDepth>=t.options.maxImportDepth)return null;let o=await Uf(r,t);if(!o)return null;let i=oi(o,t,{importDepth:t.importDepth+1}),s=Kf(r,o);return s?{node:s,context:i}:Nr(r.importedName,i)}async function hn(e,t,n){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let r=oi(n.analysis,n,{functionDepth:n.functionDepth+1});r.scopeVariables=n.analysis.functionVariables.get(e),e.params.forEach((c,l)=>{let u=t[l];u&&La(c,QE(u),r)});let o=YE(e),i=null,s,a=!1;for(let c of o){if(k.isObjectExpression(c)){s={...s??{},...await Of(c,r)},i=i??$a(s,n.file);continue}let l=await we(c,r);if(l){if(!i){i=l;continue}let u=ja(i,l);if(!u){a=!0,i=null;continue}i=u}}return{returnSource:a?null:i,...s?{objectReturnMap:s}:{}}}function La(e,t,n){if(k.isIdentifier(e)){n.paramSources.set(e.name,Fe(t));return}if(k.isAssignmentPattern(e)){La(e.left,t,n);return}if(k.isObjectPattern(e))for(let r of e.properties){if(!k.isObjectProperty(r)||r.computed||!k.isIdentifier(r.key))continue;let o=Ar(t,[{kind:"property",name:r.key.name}],!0),i=k.isAssignmentPattern(r.value)?r.value.left:r.value;La(i,o,n)}}function YE(e){if(k.isArrowFunctionExpression(e)&&k.isExpression(e.body))return[e.body];let t=[],n=e.body;if(!k.isBlockStatement(n))return t;let r=o=>{if(k.isFunction(o)&&o!==e)return;if(k.isReturnStatement(o)){o.argument&&k.isExpression(o.argument)&&t.push(o.argument);return}let i=k.VISITOR_KEYS[o.type];for(let s of i??[]){let a=o[s];if(Array.isArray(a))for(let c of a)k.isNode(c)&&r(c);else k.isNode(a)&&r(a)}};return r(n),t}async function Of(e,t){let n={};for(let r of e.properties){if(!k.isObjectProperty(r))continue;let o=Mf(r);if(!o||!k.isExpression(r.value))continue;let i=await we(r.value,t);i&&(n[o]=i)}return n}function Mf(e){return k.isIdentifier(e.key)&&!e.computed?e.key.name:k.isStringLiteral(e.key)?e.key.value:null}function ZE(e){let t=[],n=e;for(;k.isMemberExpression(n)||k.isOptionalMemberExpression(n);){let r=n.property;n.computed?k.isStringLiteral(r)?t.unshift({kind:"property",name:r.value}):k.isNumericLiteral(r)&&t.unshift({kind:"index",index:r.value}):k.isIdentifier(r)&&t.unshift({kind:"property",name:r.name}),n=n.object}return k.isIdentifier(n),t}function Ar(e,t,n){if(t.length===0)return Fe(e);let r=t[0];if(r?.kind==="property"&&e.fieldMap?.[r.name])return Ar(e.fieldMap[r.name],t.slice(1),n);let o=Fe(e);if(o.sourceType==="cms-field"){let i=t.filter(s=>s.kind==="property").map(s=>s.name);return i[0]==="data"&&i[1]==="items"?(o.valuePath=wr(o.valuePath,"data.items[]"),o.cmsFieldRoot=!1,o):i[0]==="fields"?(o.fieldPath=wr(o.fieldPath,i.slice(1).join(".")),o.cmsFieldRoot=!0,o):o.cmsFieldRoot||n||o.fieldMap?(o.fieldPath=wr(o.fieldPath,i.join(".")),o):(o.valuePath=wr(o.valuePath,vf(t)),o)}return o.valuePath=wr(o.valuePath,vf(t)),o}function vf(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function wr(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function Df(e){return{sourceKind:e.sourceKind,sourceType:e.sourceType,operation:e.operation,collection:e.collection,endpointPattern:e.endpointPattern,valuePath:e.valuePath,confidence:e.confidence,readonly:!0,evidence:e.evidence}}function gn(e){let t=Fe(e);return t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function QE(e){let t=Fe(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&(t.cmsFieldRoot=!1),t}function Pr(e){return e?{...Fe(e),confidence:e.confidence==="unknown"?"unknown":"safe-derived",evidence:[...e.evidence,{file:e.evidence[0]?.file??"unknown",reason:"safe derived expression"}]}:null}function If(e,t){return e?t?ja(e,t):Fe(e):t?Fe(t):null}function ja(e,t){if(ti(e)!==ti(t))return null;let n=$f(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function Lf(e){let t=new Map;for(let n of e){let r=ti(n),o=t.get(r);t.set(r,o?ja(o,n):Fe(n))}return[...t.values()]}function ti(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,ti(r)])):void 0;return JSON.stringify({sourceKind:e.sourceKind,sourceType:e.sourceType,endpointPattern:e.endpointPattern,operation:e.operation,collection:e.collection,fieldPath:e.fieldPath,valuePath:e.valuePath,cmsFieldRoot:e.cmsFieldRoot,fieldMap:t})}function $a(e,t){let n=Object.values(e)[0];return{sourceKind:n?.sourceKind??"unknown-api",sourceType:n?.sourceType??"api-field",endpointPattern:n?.endpointPattern,operation:n?.operation,collection:n?.collection,confidence:n?.confidence??"partial",readonly:!0,evidence:n?.evidence??[{file:t,reason:"object return map"}],fieldMap:e}}function ei(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function ni(e,t,n){return{sourceKind:e.sourceKind,sourceType:e.sourceType,...e.endpointPattern?{endpointPattern:e.endpointPattern}:{},...e.operation?{operation:e.operation}:{},...e.collection?{collection:e.collection}:{},...e.fieldPath?{fieldPath:e.fieldPath}:{},...e.valuePath?{valuePath:e.valuePath}:{},targetKind:t,targetName:n,confidence:e.confidence,readonly:!0,evidence:e.evidence.map(r=>({...r}))}}function Bf(e){let t=[...e].sort(jf),n=t[0];return{hasDynamicData:t.length>0,sourceKinds:[...new Set(t.map(r=>r.sourceKind))],...n?.endpointPattern?{primaryEndpoint:n.endpointPattern}:{},...n?.collection?{primaryCollection:n.collection}:{},...n?.fieldPath?{primaryFieldPath:n.fieldPath}:{}}}function qE(e){let t=new Set,n=[];for(let r of e){let o=JSON.stringify({sourceKind:r.sourceKind,endpointPattern:r.endpointPattern,collection:r.collection,fieldPath:r.fieldPath,valuePath:r.valuePath,targetKind:r.targetKind,targetName:r.targetName});t.has(o)||(t.add(o),n.push(r))}return n}function jf(e,t){return kf(e.targetKind)-kf(t.targetKind)||$f(e.confidence,t.confidence)||Cf(e.sourceKind)-Cf(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function kf(e){return{"repeat-region":0,"conditional-region":1,text:2,richtext:3,attribute:4,"component-prop":5}[e]}function Cf(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function $f(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function Va(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=PE(t,{sourceType:"module",plugins:["jsx","typescript"]}),i={file:e,source:t,ast:o,variables:new Map,functions:new Map,imports:new Map,stateSetters:new Map,functionVariables:new WeakMap};return Ba(o,{ImportDeclaration(s){let a=s.node.source.value;for(let c of s.node.specifiers)k.isImportSpecifier(c)&&k.isIdentifier(c.local)?i.imports.set(c.local.name,{source:a,importedName:k.isIdentifier(c.imported)?c.imported.name:c.imported.value,localName:c.local.name,isDefault:!1}):k.isImportDefaultSpecifier(c)&&i.imports.set(c.local.name,{source:a,importedName:"default",localName:c.local.name,isDefault:!0})},FunctionDeclaration(s){s.node.id?.name&&i.functions.set(s.node.id.name,s.node)},VariableDeclarator(s){let a=s.getFunctionParent(),c=a&&(k.isFunctionDeclaration(a.node)||k.isFunctionExpression(a.node)||k.isArrowFunctionExpression(a.node))?a.node:null,l=c?i.functionVariables.get(c)??new Map:i.variables;c&&!i.functionVariables.has(c)&&i.functionVariables.set(c,l);for(let u of zn(s.node.id))l.set(u,k.isExpression(s.node.init)?s.node.init:null);if(k.isArrayPattern(s.node.id)&&k.isCallExpression(s.node.init)&&vt(s.node.init.callee)==="useState"){let[u,d]=s.node.id.elements;k.isIdentifier(u)&&k.isIdentifier(d)&&i.stateSetters.set(u.name,d.name)}k.isIdentifier(s.node.id)&&Rf(s.node.init)&&i.functions.set(s.node.id.name,s.node.init)},ExportNamedDeclaration(s){let a=s.node.declaration,c=s.node.source?.value;if(c)for(let l of s.node.specifiers){if(!k.isExportSpecifier(l))continue;let u=k.isIdentifier(l.exported)?l.exported.name:l.exported.value,d=l.local.name;i.imports.set(u,{source:c,importedName:d,localName:u,isDefault:d==="default"})}if(k.isFunctionDeclaration(a)&&a.id?.name&&i.functions.set(a.id.name,a),k.isVariableDeclaration(a))for(let l of a.declarations)k.isIdentifier(l.id)&&Rf(l.init)&&i.functions.set(l.id.name,l.init)},ExportDefaultDeclaration(s){let a=s.node.declaration;if((k.isFunctionDeclaration(a)||k.isFunctionExpression(a)||k.isArrowFunctionExpression(a))&&i.functions.set("default",a),k.isIdentifier(a)){let c=i.functions.get(a.name);c&&i.functions.set("default",c)}}}),n.set(e,i),i}function zn(e){return!e||k.isVoidPattern(e)?[]:k.isIdentifier(e)?[e.name]:k.isObjectPattern(e)?e.properties.flatMap(t=>k.isObjectProperty(t)?zn(t.value):zn(t.argument)):k.isArrayPattern(e)?e.elements.flatMap(t=>t?zn(k.isRestElement(t)?t.argument:t):[]):k.isAssignmentPattern(e)?zn(e.left):k.isRestElement(e)?zn(e.argument):[]}function Rf(e){return k.isFunctionExpression(e)||k.isArrowFunctionExpression(e)}function Vf(e,t){let n=e.functions.get(t)??e.functions.get("default");return n?e.functionVariables.get(n):void 0}async function Uf(e,t){let n=await Jf(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return Va(n,r,t.fileCache)}function Kf(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function Jf(e,t,n){return xt(t)?Rn(e,t,n):null}function oi(e,t,n={}){return{file:e.file,analysis:e,readFile:t.readFile,exists:t.exists,fileCache:t.fileCache,options:t.options,variableCache:new Map,functionDepth:n.functionDepth??t.functionDepth,importDepth:n.importDepth??t.importDepth,paramSources:new Map(t.paramSources),resolvingVariables:new Set,resolvingComponentProps:t.resolvingComponentProps,scopeVariables:e===t.analysis?t.scopeVariables:void 0}}function ev(e){return e?Fe(e):null}function Fe(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,Fe(n)]))}:{}}}var tv=50,nv=8*1024*1024;function Hf(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??tv),s=Math.max(0,t.maxUndoBytes??nv);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:u,redo:d};async function a(N){let W=[...N.steps].sort((G,ee)=>G.order-ee.order),M=W.filter(G=>G.type!=="invoke-external-adapter");if(M.length!==W.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let j=new Set(M.map(G=>G.file)),Q=await w(j),re=new Map(Q.map(G=>[G.file,G.exists===!1?"":G.content])),be;for(let G of M){let ee=Wf(G,re.get(G.file)??"");if(!ee.ok)return{ok:!1,errorCode:ee.errorCode,reason:ee.reason};re.set(G.file,ee.source),be=ee.selectionRef??be}return{ok:!0,filePlan:{operationId:N.operationId,kind:"source-edit",target:N.target,documentVersion:N.documentVersion,conflictPolicy:"compare-and-swap",edits:[...re].map(([G,ee])=>({operation:"upsert",file:G,content:ee,baseContentHash:Q.find(Ie=>Ie.file===G)?.sha256??null}))},...be?{selectionRef:be}:{}}}async function c(N){let W=[...N.steps].sort((Ie,Ft)=>Ie.order-Ft.order),M=W.filter(Ie=>Ie.type!=="invoke-external-adapter"),j=W.filter(Ie=>Ie.type==="invoke-external-adapter"),Q=new Set(M.map(Ie=>Ie.file));if(M.length>0&&j.length>0)return{ok:!1,operationId:N.operationId,errorCode:"unsupported-operation",reason:"Mixed local file rewrites and external adapter writes require an explicit compensation contract.",rolledBack:!1};if(M.length===0)return C(N,j);let re=await w(Q),be=new Map;for(let Ie of re)be.set(Ie.file,Ie.exists===!1?"":Ie.content);let G;for(let Ie of M){let Ft=be.get(Ie.file)??"",_t=Wf(Ie,Ft);if(!_t.ok)return{ok:!1,operationId:N.operationId,errorCode:_t.errorCode,reason:_t.reason,rolledBack:!1};be.set(Ie.file,_t.source),_t.selectionRef&&(G=_t.selectionRef)}let ee=await O([...be].map(([Ie,Ft])=>({file:Ie,content:Ft,exists:!0,version:0,sha256:fe(Ft)})),re);return ee.ok===!1?{ok:!1,operationId:N.operationId,errorCode:ee.rolledBack?"writeback-failed":"rollback-failed",reason:ee.reason,rolledBack:ee.rolledBack}:(n.push({operationId:N.operationId,preSnapshots:re,postSnapshots:ee.snapshots,plan:N}),p(),r.length=0,{ok:!0,operationId:N.operationId,kind:N.kind,target:N.target,resultVersion:Math.max(...ee.snapshots.map(Ie=>Ie.version)),affectedFiles:[...Q],...G?{selectionRef:G}:{}})}async function l(N){let W=new Set(N.edits.map(ee=>ee.file)),M=await w(W),j=I(N,M);if(j)return{ok:!1,operationId:N.operationId,errorCode:"stale-version",reason:j.reason,affectedFiles:[j.file],rolledBack:!1};let Q=new Map(M.map(ee=>[ee.file,ee])),re=N.edits.find(ee=>ee.operation==="create-only"&&Q.get(ee.file)?.exists!==!1);if(re)return{ok:!1,operationId:N.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${re.file}`,affectedFiles:[re.file],rolledBack:!1};let be=N.edits.map(ee=>ee.operation==="delete"?{file:ee.file,content:"",exists:!1,version:0}:{file:ee.file,content:ee.content,exists:!0,version:0,sha256:fe(ee.content)}),G=await O(be,M,new Set(N.edits.filter(ee=>ee.operation==="create-only").map(ee=>ee.file)));return G.ok===!1?{ok:!1,operationId:N.operationId,errorCode:G.rolledBack?"writeback-failed":"rollback-failed",reason:G.reason,rolledBack:G.rolledBack}:(n.push({operationId:N.operationId,preSnapshots:M,postSnapshots:G.snapshots,plan:{operationId:N.operationId,kind:N.kind,target:N.target,documentVersion:N.documentVersion,steps:[],preSnapshots:M}}),p(),r.length=0,{ok:!0,operationId:N.operationId,kind:N.kind,target:N.target,resultVersion:Math.max(...G.snapshots.map(ee=>ee.version)),affectedFiles:[...W]})}async function u(){let N=n.at(-1);if(!N)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let W=await O(N.preSnapshots,N.postSnapshots);return W.ok===!1?{ok:!1,operationId:N.operationId,errorCode:W.rolledBack?"writeback-failed":"rollback-failed",reason:W.reason,rolledBack:W.rolledBack}:(n.pop(),r.push(N),{ok:!0,operationId:N.operationId,kind:N.plan.kind,target:N.plan.target,resultVersion:Math.max(...W.snapshots.map(M=>M.version)),affectedFiles:N.preSnapshots.map(M=>M.file)})}async function d(){let N=r.at(-1);if(!N)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let W=await O(N.postSnapshots,N.preSnapshots);return W.ok===!1?{ok:!1,operationId:N.operationId,errorCode:W.rolledBack?"writeback-failed":"rollback-failed",reason:W.reason,rolledBack:W.rolledBack}:(r.pop(),n.push(N),p(),{ok:!0,operationId:N.operationId,kind:N.plan.kind,target:N.plan.target,resultVersion:Math.max(...W.snapshots.map(M=>M.version)),affectedFiles:N.postSnapshots.map(M=>M.file)})}function p(){for(;n.length>i;)n.shift();for(;n.length>0&&m()>s;)n.shift()}function m(){return n.reduce((N,W)=>N+g(W),0)}function g(N){return b(N.preSnapshots)+b(N.postSnapshots)}function b(N){return N.reduce((W,M)=>W+M.file.length+M.content.length,0)}async function C(N,W){let M=[];for(let j of W){let Q=j.capability??"write-text",re=o.find(G=>G.sourceType===j.sourceType&&(j.adapterId===void 0||G.adapterId===j.adapterId)&&(G.capabilities===void 0||G.capabilities.includes(Q)));if(!re)return{ok:!1,operationId:N.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${j.sourceType}`,rolledBack:!1};let be=await re.execute(j);if(!be.ok)return{ok:!1,operationId:N.operationId,errorCode:"writeback-failed",reason:be.reason??`External adapter failed for ${j.sourceType}`,rolledBack:!1};M.push(j.file)}return{ok:!0,operationId:N.operationId,kind:N.kind,target:N.target,resultVersion:0,affectedFiles:M}}function I(N,W){if(N.conflictPolicy!=="compare-and-swap")return null;let M=new Map(W.map(j=>[j.file,j]));for(let j of N.edits){if(j.operation==="create-only")continue;if(j.baseContentHash===void 0)return{file:j.file,reason:`Source file ${j.file} is missing baseContentHash. Reopen the file before saving.`};let Q=M.get(j.file),re=j.baseContentHash;if(re===null){if(Q?.exists!==!1)return{file:j.file,reason:`Source file ${j.file} was created or changed before save.`};continue}if(!re)return{file:j.file,reason:`Source file ${j.file} is missing baseContentHash. Reopen the file before saving.`};if(Q?.exists===!1||Q?.sha256!==re)return{file:j.file,reason:`Source file ${j.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function w(N){let W=[];for(let M of N)W.push(await A(M));return W}async function A(N){if(!await e.exists(N))return{file:N,content:"",version:0,exists:!1};let M=Math.max(1,e.getVersion(N)),j=await e.readFile(N);return{file:N,content:j,version:M,exists:!0,sha256:fe(j)}}async function O(N,W,M=new Set){let j=[];try{for(let Q of N){if(M.has(Q.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive(Q.file,Q.content)}else await ie(Q);let re=e.bumpVersion(Q.file);j.push(Q.file),Q.version=re}}catch(Q){let re=await oe(W.filter(G=>j.includes(G.file)));if(re.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${re.failedFiles.join(", ")}: ${zf(Q)}`,rolledBack:!1,instanceConflict:Xf(Q)};let be=Xf(Q);return{ok:!1,reason:`${be?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${zf(Q)}`,rolledBack:!0,instanceConflict:be}}return{ok:!0,snapshots:N.map(rv)}}async function ie(N){if(N.exists===!1){await e.deleteFile(N.file);return}await e.writeFile(N.file,N.content)}async function oe(N){let W=[];for(let M of N)try{await ie(M),e.bumpVersion(M.file)}catch{W.push(M.file)}return W.length===0?{ok:!0}:{ok:!1,failedFiles:W}}}function Xf(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function rv(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:fe(e.content)}:{}}}function zf(e){return e instanceof Error?e.message:String(e)}function Wf(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 Oe(Ln({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return Oe(Bn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return Oe(Tn({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return Oe(_n({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return Oe(Io({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return Oe(lr({source:t,locator:e.locator,next:e.value}));case"update-array-item":return Oe(lr({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return Oe(Po({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return Oe(Co({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return Oe(Ao({source:t,locator:e.locator,index:e.index}));case"move-array-item":return Oe(To({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return Oe(Mn({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return Oe(Ro({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 ov(e,t);case"set-property-changes":return Oe(wo({source:t,locator:e.locator,changes:e.changes}));case"set-property-binding":return Oe(No({source:t,locator:e.locator,name:e.name,object:e.object,property:e.property}));case"upsert-object-property":return Oe(_o({source:t,objectLocator:e.locator,name:e.name,value:e.value}));default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function ov(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!$u(n.newAttrRaw))return{ok:!1,reason:"newAttrRaw must be a valid JSX className attribute.",errorCode:"invalid-params"};let r=n.oldAttrRange!==null&&n.oldAttrRaw!==null,o=n.openingElementRange.start,i=n.openingElementRange.end,s=t.slice(o,i);if(!(Number.isInteger(o)&&Number.isInteger(i)&&o>=0&&i>o&&i<=t.length&&s.startsWith("<")&&s.endsWith(">")&&!s.startsWith("</")&&(n.oldAttrRange===null||n.oldAttrRange.start>=o&&n.oldAttrRange.end<=i)))return{ok:!1,reason:"The opening element range changed before className save.",errorCode:"stale-version"};if(!r&&n.expectedVersion.contentHash!==fe(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:ju({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function Oe(e){if(e.ok)return{ok:!0,source:e.source,...e.selectionRef?{selectionRef:e.selectionRef}:{}};switch(e.diagnostic.code){case"locator-miss":return{ok:!1,reason:e.diagnostic.message,errorCode:"locator-miss"};case"unsupported-syntax":case"binding-not-found":case"export-not-found":case"property-not-found":case"array-index-out-of-range":case"directive-conflict":case"metadata-shape-unsupported":return{ok:!1,reason:e.diagnostic.message,errorCode:"unsupported-operation"};case"invalid-parent-child-relation":case"self-closing-element":return{ok:!1,reason:e.diagnostic.message,errorCode:"invalid-target"};case"parse-failed":case"printer-failed":return{ok:!1,reason:e.diagnostic.message,errorCode:"ast-error"};default:return{ok:!1,reason:e.diagnostic.message,errorCode:"writeback-failed"}}}function Gf(){let e=new Set;return{emit(t){for(let n of Array.from(e))try{n(t)}catch{}},subscribe(t){return e.add(t),()=>{e.delete(t)}}}}import{classifySiteEditPropertyName as iv}from"@vcp-dev/contracts";async function Yf(e){let t=iv(e.propertyName);if(t.owner==="blocked")return Zt(t.owner,t.diagnostic);if(t.owner==="class-name-source"||t.owner==="style")return Zt(t.owner,{code:"owner-delegated",message:`Property '${e.propertyName}' is owned by ${t.owner}`});let n=e.element.attributes?.filter(l=>l.name===e.propertyName)??[];if(n.length>1)return Zt("generic",{code:"duplicate-property-source",message:`Property '${e.propertyName}' has multiple explicit sources`});let r=n[0],o=[];r&&o.push({kind:"attribute",order:r.order??e.element.attributes.indexOf(r),attribute:r});let i=e.element.attributeSpreads??[];for(let l of i)o.push({kind:"spread",order:l.order,spread:l,target:await av(e,l)});o.sort((l,u)=>l.order-u.order);let s=o.at(-1);if(!s)return{status:"missing",owner:"generic"};if(o.filter(l=>l.kind==="spread"&&l.order>s.order).some(l=>!l.target))return Zt("generic",{code:"ambiguous-property-source",message:`A spread may provide or override property '${e.propertyName}'`});if(s.kind==="spread")return s.target?{status:"binding",owner:"generic",target:s.target}:Zt("generic",{code:"ambiguous-property-source",message:`The final spread source for '${e.propertyName}' is not provably writable`});let c=o.filter(l=>l.kind==="spread"&&l.order<s.order);return e.operation==="remove"&&c.length>0?Zt("generic",{code:"remove-exposes-spread",message:`Removing '${e.propertyName}' would expose an earlier spread source`}):sv(e,s.attribute)}async function sv(e,t){if(t.resolution&&t.resolution.status!=="resolved"&&!t.source){let r=await Xn({file:e.file,source:e.source,sourceRange:t.sourceRange,expression:t.value,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache});return r&&r.kind!=="external-entry"?{status:"binding",owner:"generic",attribute:t,target:{kind:"value-binding",target:r}}:Zt("generic",{code:"unsupported-property-source",message:`Property '${e.propertyName}' has an unresolved value source`})}if(!t.source?.expression)return{status:"direct",owner:"generic",attribute:t,target:{kind:"jsx-attribute",file:e.file,sourceRange:t.sourceRange}};let n=await Xn({file:e.file,source:e.source,sourceRange:t.sourceRange,expression:t.source.expression,sourceInfo:t.source,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache});return!n||n.kind==="external-entry"?Zt("generic",{code:"unsupported-property-source",message:`Property '${e.propertyName}' does not have a local writable source`}):{status:"binding",owner:"generic",attribute:t,target:{kind:"value-binding",target:n}}}async function av(e,t){let n=t.source?.expression;if(!n)return;let r=await Xn({file:e.file,source:e.source,sourceRange:t.sourceRange,expression:n,sourceInfo:t.source,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache});if(!(!r||r.kind==="external-entry"))return{kind:"value-binding",target:cv(r,e.propertyName)}}function cv(e,t){let n=[...e.path??[],{kind:"property",name:t}];return{...e,path:n,locator:e.locator?{...e.locator,path:n}:{kind:"value",root:e.root??{kind:"binding",name:t},path:n}}}function Zt(e,t){return{status:"blocked",owner:e,...t?{diagnostic:t}:{}}}import*as Ka from"@babel/parser";import Ua from"@babel/traverse";import*as K from"@babel/types";import{classifySiteEditPropertyName as lv}from"@vcp-dev/contracts";var Ja=typeof Ua=="function"?Ua:Ua.default;function Xa(e){let t=lv(e.propertyName);if(t.owner!=="generic")return ze("invalid-property",t.diagnostic?.message??`Property '${e.propertyName}' is not a generic property`);let n=e.selectionRef;if(!n)return ze("missing-selection-ref","A repeat property target requires a complete selection reference");if(n.key!==e.element.identity.key)return ze("selection-mismatch","Selection reference does not identify the requested element");if(n.instanceIndex===void 0)return ze("missing-instance-index","A repeat property target requires an instance index");let r;try{r=Ka.parse(e.source,{sourceType:"module",plugins:["typescript","jsx"]})}catch(C){return ze("repeat-not-found",`Unable to parse repeat source: ${C instanceof Error?C.message:String(C)}`)}let o=uv(r,e.element.sourceRange);if(!o)return ze("repeat-not-found","The selected element is not inside a supported map repeat");if(!K.isIdentifier(o.callback.params[0]))return ze("unsupported-callback","Repeat property materialization requires an identifier callback item");let i=dv(r,o.collection,e.file,e.sources);if(!i)return ze("collection-not-found","The repeat collection is not a visible local static array");let{array:s,locator:a,sourceFile:c}=i,l=[],u=[];for(let[C,I]of s.elements.entries()){if(!I||!K.isObjectExpression(I)||!np(I))return ze("unsafe-collection","Repeat materialization requires an array of local static objects without spreads");let w=[{kind:"index",index:C}];l.push(w),u.push({kind:"value",root:a.root,path:w})}let d=u.length;if(n.instanceCount!==void 0&&n.instanceCount!==d)return ze("count-mismatch",`Selection reports ${n.instanceCount} instances but the source collection has ${d}`);let p=n.instanceIndex;if(p>=d)return ze("index-out-of-range",`Selected repeat instance ${p} is outside the source collection`);let m=s.elements[p];if(!m||!K.isObjectExpression(m))return ze("unsafe-collection","Selected repeat item is not an object");let g=yv(e.element,e.propertyName),b=gv(m,e.propertyName);return b?{ok:!0,sourceFile:c,templateFile:e.file,collectionLocator:a,parentObjectLocators:u,selectedParentObjectLocator:u[p],sourceItemIndex:p,sourceItemPath:l[p],collectionIndexMap:Array.from({length:d},(C,I)=>I),callbackItemName:o.callback.params[0].name,targetElementLocator:{kind:"jsx-node",strategy:"structural-path",file:e.element.identity.file,component:e.element.identity.component,structuralPath:e.element.identity.structuralPath,expectedRange:e.element.sourceRange},propertyName:e.propertyName,propertyState:b,selectedResolution:hv(m,e.propertyName),...g?{property:g}:{},selectionRef:n}:ze("unsafe-property-source",`Property '${e.propertyName}' has a dynamic or unsupported source in the repeat item`)}function uv(e,t){let n=[];return Ja(e,{CallExpression(r){let o=Zf(r.node);o&&qf(o.callback,t)&&n.push({...o,span:Qf(r.node)})},OptionalCallExpression(r){let o=Zf(r.node);o&&qf(o.callback,t)&&n.push({...o,span:Qf(r.node)})}}),n.sort((r,o)=>r.span-o.span),n[0]??null}function Zf(e){let t=e.callee;if(!K.isMemberExpression(t)&&!K.isOptionalMemberExpression(t)||t.computed||!K.isIdentifier(t.property)||t.property.name!=="map"||!K.isExpression(t.object))return null;let n=e.arguments[0];return!n||!K.isExpression(n)||!K.isArrowFunctionExpression(n)&&!K.isFunctionExpression(n)?null:{collection:t.object,callback:n}}function dv(e,t,n,r){let o=Tr(t);if(o&&K.isArrayExpression(o))return{array:o,locator:{kind:"value",root:{kind:"expression",sourceRange:op(o)}},sourceFile:n};if(!K.isIdentifier(t))return null;let i=[];if(Ja(e,{VariableDeclarator(s){K.isIdentifier(s.node.id)&&s.node.id.name===t.name&&s.node.init&&i.push(s.node)}}),i.length===1){let s=Tr(i[0].init);return!s||!K.isArrayExpression(s)?null:{array:s,locator:{kind:"value",root:{kind:"binding",name:t.name}},sourceFile:n}}return fv(e,t.name,n,r)}function fv(e,t,n,r){if(!r)return null;for(let o of e.program.body){if(!K.isImportDeclaration(o))continue;let i=o.specifiers.find(p=>p.local.name===t);if(!i||!K.isStringLiteral(o.source)||!K.isImportSpecifier(i))continue;let s=mv(n,o.source.value,r);if(!s)return null;let a=K.isIdentifier(i.imported)?i.imported.name:i.imported.value,c=r.get(s);if(c===void 0)return null;let l;try{l=Ka.parse(c,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}let u=pv(l,a),d=u?Tr(u):null;return!d||!K.isArrayExpression(d)?null:{array:d,locator:{kind:"value",root:{kind:"binding",name:a}},sourceFile:s}}return null}function pv(e,t){let n=null;return Ja(e,{VariableDeclarator(r){n||!K.isIdentifier(r.node.id)||r.node.id.name!==t||!r.node.init||!K.isExpression(r.node.init)||(n=r.node.init)}}),n}function mv(e,t,n){let r=Qn(e,t);return[r,r+".tsx",r+".ts",r+".jsx",r+".js",r+"/index.tsx",r+"/index.ts",r+"/index.jsx",r+"/index.js"].find(i=>n.has(i))??null}function Tr(e){return K.isParenthesizedExpression(e)?Tr(e.expression):K.isTSAsExpression(e)?tp(e.typeAnnotation)?Tr(e.expression):null:K.isTSSatisfiesExpression(e)?null:e}function tp(e){return K.isTSTypeReference(e)&&K.isIdentifier(e.typeName)&&e.typeName.name==="const"}function np(e){return e.properties.every(t=>!K.isObjectProperty(t)||t.computed||!K.isExpression(t.value)?!1:ii(t.value))}function ii(e){if(K.isTSAsExpression(e)&&tp(e.typeAnnotation))return ii(e.expression);if(K.isTSSatisfiesExpression(e))return!1;if(K.isArrayExpression(e))return e.elements.every(n=>!n||K.isSpreadElement(n)||!K.isExpression(n)?!1:ii(n));if(K.isObjectExpression(e))return np(e);let t=ht(e);return t.status==="resolved"||t.status==="undefined"}function gv(e,t){let n=e.properties.filter(o=>K.isObjectProperty(o)&&rp(o.key)===t);if(n.length>1)return null;let r=n[0];return r?K.isExpression(r.value)?ii(r.value)?"static":K.isIdentifier(r.value)||K.isMemberExpression(r.value)?"binding":null:null:"missing"}function hv(e,t){let n=e.properties.filter(o=>K.isObjectProperty(o)&&rp(o.key)===t);if(n.length>1)return{status:"unresolved"};let r=n[0];return!r||!K.isExpression(r.value)?{status:"undefined"}:ht(r.value)}function yv(e,t){let n=e.attributes?.filter(r=>r.name===t)??[];return n.length===1?n[0]:void 0}function rp(e){return K.isIdentifier(e)?e.name:K.isStringLiteral(e)?e.value:K.isNumericLiteral(e)?String(e.value):null}function op(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 Qf(e){return e.start==null||e.end==null?Number.MAX_SAFE_INTEGER:e.end-e.start}function qf(e,t){let n=op(e);return ep(n.startLine,n.startColumn,t.startLine,t.startColumn)<=0&&ep(n.endLine,n.endColumn,t.endLine,t.endColumn)>=0}function ep(e,t,n,r){return e===n?t-r:e-n}function ze(e,t){return{ok:!1,errorCode:e,reason:t}}function ap(e){let t=e.isRepeat??(e.graph?Rv(e.element,e.graph):!1),n=e.propertyProvenance??new Map,r=e.repeatTargets??new Map,o=Cv(e.element.attributes??[]),i=[...r.values()].some(u=>u.ok),s=o.map(u=>xv({attribute:u,element:e.element,isRepeat:t,selectionRef:e.selectionRef,provenance:n.get(u.name),repeatTarget:r.get(u.name)})),a=(e.element.attributeSpreads?.length??0)>0,c=(e.element.attributeSpreads??[]).slice().sort((u,d)=>u.order-d.order).map(u=>({raw:u.raw,sourceRange:Nv(u.sourceRange,e.source),order:u.order,diagnostics:u.source?[]:[{code:"unsupported-spread-source",message:"The spread source cannot be resolved safely, so property ownership is conservative."}]})),l=t&&e.selectionRef?.instanceIndex!==void 0&&i;return{documentVersion:e.documentVersion,...e.selectionRef?{selectionRef:e.selectionRef}:{},items:s,spreads:c,creation:t?{selection:l?"materialize":"unsupported",template:"unsupported"}:{selection:a?"unsupported":"direct",template:a?"unsupported":"direct"}}}function xv(e){let{attribute:t,provenance:n,repeatTarget:r}=e,o=e.selectionRef?.instanceIndex!==void 0&&r?.ok===!0?r:null,i=bv(t,n,e.isRepeat),s=Sv(t,n,o,e.isRepeat),a=vv(n,o,e.element),c=o?"repeat-item":e.isRepeat?"repeat-template":"node",l=kv(t,n,r);return{name:t.name,source:i,resolution:s,editMode:a,sourceScope:c,allowedWriteScopes:Iv(a,c,n),...sp(n,o,e.element)?{effectiveWriteTarget:sp(n,o,e.element)}:{},diagnostics:l}}function bv(e,t,n){let r;if(n&&t?.status==="binding"){let o=t.target;r=o?.kind==="value-binding"&&o.target.sourceKind==="repeat-template"?"repeat-template":"binding"}else e.syntaxKind==="boolean-shorthand"?r="boolean-shorthand":e.syntaxKind==="literal"||!e.source?r="literal":r="expression";return{kind:r,...e.raw!==void 0?{raw:e.raw}:{}}}function Sv(e,t,n,r){return n?ip(n.selectedResolution):t?.status==="blocked"?{status:"unresolved"}:r&&t?.status==="binding"?{status:"unresolved"}:ip(Ev(e))}function Ev(e){return e.resolution?e.resolution:e.syntaxKind==="boolean-shorthand"?{status:"resolved",value:!0}:e.resolvedValue!==void 0?{status:"resolved",value:e.resolvedValue}:e.source?{status:"unresolved"}:{status:"resolved",value:e.value}}function ip(e){return!e||e.status==="unresolved"?{status:"unresolved"}:e.status==="undefined"?{status:"undefined"}:{status:"resolved",value:e.value}}function vv(e,t,n){if(t)return"direct";if(!e||e.status==="blocked")return"unsupported";if(e.status==="missing"||e.status==="direct")return"direct";let r=e.target;return r?.kind!=="value-binding"?"unsupported":r.target.file===n.sourceFile?"direct":"proxy"}function Iv(e,t,n){return e==="readonly"||e==="unsupported"?[]:n?.status==="binding"?t==="repeat-template"?["template"]:["selection"]:t==="repeat-template"?["template"]:["selection","template"]}function sp(e,t,n){if(t)return{kind:"value-path",file:t.sourceFile,isProxy:t.sourceFile!==n.sourceFile,displayPath:`${wv(t.selectedParentObjectLocator)}.${t.propertyName}`};if(e?.target?.kind==="jsx-attribute")return{kind:"jsx-node",file:e.target.file,isProxy:e.target.file!==n.sourceFile,displayPath:`${n.componentName} > ${e.attribute?.name??"attribute"}`};if(e?.target?.kind==="value-binding")return{kind:"value-path",file:e.target.target.file,isProxy:e.target.target.file!==n.sourceFile,displayPath:e.target.target.displayExpression}}function kv(e,t,n){let r=[];return t?.diagnostic&&r.push({code:t.diagnostic.code,message:t.diagnostic.message}),n&&!n.ok&&t?.status!=="missing"&&r.push({code:`repeat-${n.errorCode}`,message:n.reason}),e.resolution?.status==="unresolved"&&r.length===0&&r.push({code:"unsupported-property-source",message:`Property '${e.name}' has an unresolved value source`}),r}function Cv(e){let t=new Set;return e.filter(n=>t.has(n.name)?!1:(t.add(n.name),!0))}function Rv(e,t){let n=t.regions.filter(r=>r.kind==="repeat-region");for(let r of n){let o=e;for(;o;){if(r.childKeys.includes(o.identity.key))return!0;o=o.parentKey?t.elements.get(o.parentKey):void 0}}return!1}function wv(e){return`${e.root.kind==="binding"?e.root.name:e.root.kind==="expression"?e.root.sourceRange?"expression":"value":e.root.kind}${(e.path??[]).map(n=>n.kind==="index"?`[${n.index}]`:`.${n.name}`).join("")}`}function Nv(e,t){if(!t)return{start:e.startColumn,end:e.endColumn};let n=t.split(`
5
+ `),r=(o,i)=>n.slice(0,Math.max(0,o-1)).reduce((s,a)=>s+a.length+1,0)+i;return{start:r(e.startLine,e.startColumn),end:r(e.endLine,e.endColumn)}}import{randomUUID as Pv}from"node:crypto";import si from"node:fs/promises";import za from"node:path";import{setTimeout as Av}from"node:timers/promises";var Tv={async mkdir(e,t){await si.mkdir(e,t)},async writeFile(e,t,n){await si.writeFile(e,t,n)},async rename(e,t){await si.rename(e,t)},async rm(e,t){await si.rm(e,t)}},Fv=new Set(["EACCES","EBUSY","EPERM"]),_v=[10,20,40,80,160];async function Ov(e,t,n){for(let r of _v)try{await e.rename(t,n);return}catch(o){if(!Mv(o))throw o;await Av(r)}await e.rename(t,n)}function Mv(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&Fv.has(e.code)}async function ai(e,t,n=Tv){let r=za.dirname(e),o=za.basename(e),i=za.join(r,`.${o}.${process.pid}.${Pv()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await Ov(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import{randomBytes as Yv}from"node:crypto";import Tt from"node:path";import{parse as Zv}from"@babel/parser";import Qv from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as li,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as dp,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as qv,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as eI,SiteEditMaterializationSchema as tI,parseComponentI18nResourcesJson as nI}from"@vcp-dev/contracts";var lp=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,up=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,Dv=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,Lv=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,Bv=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,jv=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,$v=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,Vv=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,Uv=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,Kv=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,Jv=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,Xv=/\b(?:bg|text|border|ring|outline|fill|stroke)-(?:black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)(?:-\d{2,3})?(?:\b|\/)/g,zv=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,Wv=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function Fr(e,t){let n=ci([...tt(e,Dv),...tt(e,Lv),...tt(e,Bv),...tt(e,t.includeRgbBackgroundImage?jv:$v),...t.includeExtendedColorFunctions?[...tt(e,Vv),...tt(e,Uv)]:[]]),r=ci([...tt(e,Kv),...tt(e,Jv)]).filter(o=>t.colorMixPolicy==="always"||lp.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...tt(e,Xv).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...tt(e,Wv).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:ci(tt(e,up)),hardCodedSurfaceOccurrences:Gv(e),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?ci(tt(e,zv)):[]}}function tt(e,t){return e.match(new RegExp(t.source,t.flags))??[]}var cp=160,Hv=/((?:[a-z][a-z0-9-]*(?:\[[^\]]*\])?:)+)$/;function Gv(e){let t=new RegExp(up.source,"g"),n=[0];for(let s=0;s<e.length;s+=1)e[s]===`
6
+ `&&n.push(s+1);let r=s=>{let a=0,c=n.length-1;for(;a<c;){let l=Math.ceil((a+c)/2);(n[l]??0)<=s?a=l:c=l-1}return a},o=[],i;for(;(i=t.exec(e))!==null;){let s=i[0],a=s.endsWith("/")?s.slice(0,-1):s,c=/^\/(\d+)/.exec(e.slice(i.index+a.length)),l=e.slice(Math.max(0,i.index-64),i.index),u=Hv.exec(l),d=r(i.index),p=e.indexOf(`
7
+ `,i.index),m=e.slice(n[d]??0,p===-1?void 0:p).trim();o.push({token:a,variant:u?.[1]??"",alpha:c?Number(c[1]):null,line:d+1,snippet:m.length>cp?`${m.slice(0,cp-1)}\u2026`:m})}return o}function ci(e){return[...new Set(e)]}var Ga="components/site/generated",fp="{{$INSTANCE}}",ui=5,rI=/^[a-z][a-z0-9-]{0,48}$/,oI=/^[a-f0-9]{8}$/,pp=/\.tsx?$/,iI=/\.json$/,sI=/\.(?:tsx?|json)$/,aI=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,cI=["react","react/","next","next/","lucide-react","react-i18next","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],Wa=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Ha=Qv,lI=typeof Ha=="function"?Ha:Ha.default;function uI(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>dp)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=EI(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=tI.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=xI(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${Ga}.`,path:e.generatedRoot}};if(!bp(r.data.instanceBaseName))return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_INVALID",message:"Static prefab instanceBaseName must contain at least one safe word.",path:r.data.instanceBaseName}};let i=hp(r.data.files),s=hp(e.controlledFiles);if(!vI(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>dp)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let a=0;for(let[c,l]of r.data.files.entries()){let u=Buffer.byteLength(l.content,"utf8");if(u>qv)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file exceeds the per-file content limit.",file:l.pathTemplate,path:`files[${c}]`}};a+=u}return a>eI?{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab exceeds the reusable total content limit."}}:{ok:!0,data:{kind:"static-prefab-materialization",instanceName:"",generatedRoot:o,instanceRoot:"",entry:{path:"",export:r.data.entry.export},files:[]}}}async function dI(e){let t=uI(e);if(!t.ok)return t;let n=t.data.generatedRoot,r=bp(e.manifest.instanceBaseName),o=Math.max(1,Math.min(ui,e.maxAttempts??ui));for(let i=0;i<o;i+=1){let s=bI(e.instanceNameGenerator?.()??Yv(4).toString("hex"));if(!s)return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_INVALID",message:"Static prefab instance suffix must be 8 lowercase hex chars."}};let a=`${r}-${s}`,c=Ep(n,a),l=fI({manifest:e.manifest,generatedRoot:n,instanceName:a,instanceRoot:c,allowedExternalImports:e.allowedExternalImports??cI});if(!l.ok)return l;if(!await pI(e.exists,c,l.data.files))return{ok:!0,data:l.data}}return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:"Unable to allocate a create-only static prefab instance after repeated conflicts."}}}async function xp(e){let t=Math.max(1,Math.min(ui,e.maxAttempts??ui));for(let n=0;n<t;n+=1){let r=await dI({...e,maxAttempts:1});if(!r.ok){if(r.error.code==="MATERIALIZATION_INSTANCE_CONFLICT")continue;return r}let o=await e.commit(r.data);if(o.ok)return{ok:!0,plan:r.data,data:o.data};if(o.error.code!=="MATERIALIZATION_INSTANCE_CONFLICT")return o}return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:"Unable to commit a complete static prefab instance after repeated conflicts."}}}function fI(e){let t=[],n=new Set;for(let i of e.manifest.files){let s=mp({pathTemplate:i.pathTemplate,generatedRoot:e.generatedRoot,instanceName:e.instanceName,instanceRoot:e.instanceRoot});if(!s.ok)return s;if(n.has(s.data))return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${s.data}`,path:s.data}};n.add(s.data),t.push({kind:"create-only",path:s.data,content:i.content,...i.role?{role:i.role}:{},sourcePathTemplate:i.pathTemplate})}t.sort((i,s)=>i.path.localeCompare(s.path));let r=mp({pathTemplate:e.manifest.entry.pathTemplate,generatedRoot:e.generatedRoot,instanceName:e.instanceName,instanceRoot:e.instanceRoot});if(!r.ok)return r;if(!t.some(i=>i.path===r.data))return{ok:!1,error:{code:"MATERIALIZATION_ENTRY_INVALID",message:"Entry path must match one of the static prefab files.",path:r.data}};let o=mI(t,e.instanceRoot,r.data,e.manifest.entry.export,e.allowedExternalImports);return o.ok?{ok:!0,data:{kind:"static-prefab-materialization",instanceName:e.instanceName,generatedRoot:e.generatedRoot,instanceRoot:e.instanceRoot,entry:{path:r.data,export:e.manifest.entry.export},files:t}}:o}async function pI(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function mp(e){if(e.pathTemplate.split(fp).length!==2)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab path templates must include the instance placeholder exactly once.",path:e.pathTemplate}};let t=e.pathTemplate.replaceAll(fp,e.instanceName),n=SI(t);return n?Ep(e.generatedRoot,e.instanceName)!==e.instanceRoot?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab instance root normalization failed.",path:e.pathTemplate}}:n!==e.instanceRoot&&!n.startsWith(`${e.instanceRoot}/`)?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab path must stay under components/site/generated/<instance>.",path:n}}:n!==t?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab path template cannot rely on path normalization semantics.",path:e.pathTemplate}}:n===e.instanceRoot||!sI.test(n)||aI.test(n)?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab files must be .ts/.tsx/.json files and cannot be config, layout, provider, or global source files.",path:n}}:{ok:!0,data:n}:{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab path template resolves to an unsafe path.",path:e.pathTemplate}}}function mI(e,t,n,r,o){let i=new Set(e.map(d=>d.path)),s=new Map,a=new Map(e.map(d=>[d.path,new Set])),c=new Map;for(let d of e){if(iI.test(d.path)){if(d.path.endsWith(li)){let g=nI(d.content);if(!g.success)return yn("MATERIALIZATION_DATA_UNSUPPORTED",g.error.message,d.path);c.set(d.path,new Set)}else try{JSON.parse(d.content)}catch{return yn("MATERIALIZATION_DATA_UNSUPPORTED","Static prefab JSON file must contain valid JSON.",d.path)}continue}let p;try{p=Zv(d.content,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files must parse as plain module source.",file:d.path}}}let m=Fr(d.content,{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0});if(m.hardCodedSurfaceHits.length>0||m.rawColorHits.length>0||m.privateTokenHits.length>0)return{ok:!1,error:{code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source must use public semantic design tokens instead of raw colors or private tokens.",file:d.path}};s.set(d.path,p)}for(let d of e){if(!pp.test(d.path))continue;let p=s.get(d.path),m=null;if(lI(p,{ImportDeclaration(g){let b=gp({importer:d.path,source:g.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});if(!b.allowed)m??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab imports must resolve within the controlled instance or match the starter allowlist.",file:d.path},g.stop();else if(b.internalPath&&(a.get(d.path).add(b.internalPath),b.internalPath.endsWith(li))){let C=gI({importer:d.path,imported:b.internalPath,source:g.node.source.value,ast:p});C.ok?c.get(b.internalPath).add(d.path):(m??=C.error,g.stop())}},ExportAllDeclaration(g){m??={code:"MATERIALIZATION_ENTRY_INVALID",message:"Static prefab files cannot use export-star declarations.",file:d.path},g.stop()},ExportNamedDeclaration(g){if(g.node.source){let b=gp({importer:d.path,source:g.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});!b.allowed||!b.internalPath?(m??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab re-exports must resolve within the controlled instance.",file:d.path},g.stop()):a.get(d.path).add(b.internalPath)}},CallExpression(g){if(g.node.callee.type==="Import"){m??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use dynamic import().",file:d.path},g.stop();return}g.node.callee.type==="Identifier"&&g.node.callee.name==="require"&&(m??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use require().",file:d.path},g.stop())},NewExpression(g){g.node.callee.type==="Identifier"&&g.node.callee.name==="Function"&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot construct functions dynamically.",file:d.path},g.stop())},MetaProperty(g){g.node.meta.type==="Identifier"&&g.node.meta.name==="import"&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot use import.meta.",file:d.path},g.stop())},MemberExpression(g){let b=yp(g.node);b&&Wa.has(b)&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${b}.`,file:d.path},g.stop())},OptionalMemberExpression(g){let b=yp(g.node);b&&Wa.has(b)&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${b}.`,file:d.path},g.stop())},Identifier(g){g.isReferencedIdentifier()&&Wa.has(g.node.name)&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${g.node.name}.`,file:d.path},g.stop())},JSXAttribute(g){g.node.name.type==="JSXIdentifier"&&g.node.name.name==="style"&&(m??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot use inline style attributes.",file:d.path},g.stop())},JSXOpeningElement(g){g.node.name.type==="JSXIdentifier"&&g.node.name.name.toLowerCase()==="style"&&(m??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot declare style elements.",file:d.path},g.stop())}}),m)return{ok:!1,error:m}}if(!pp.test(n))return yn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must be a .ts/.tsx source module.",n);let l=s.get(n);if(!l)return yn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",n);if(!hI(l,r))return yn("MATERIALIZATION_EXPORT_MISSING","Static prefab entry does not declare the manifest export.",n);for(let[d,p]of c)if(p.size!==1)return yn("MATERIALIZATION_IMPORT_FORBIDDEN","Each component .i18n.json file must have exactly one same-name Client Component static importer.",d);return yI(n,a).size!==e.length?yn("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",n):{ok:!0,data:{kind:"static-prefab-materialization",instanceName:"",generatedRoot:Ga,instanceRoot:"",entry:{path:"",export:{kind:"default"}},files:[]}}}function gp(e){if(!e.source.startsWith("./")&&!e.source.startsWith("../"))return e.source.startsWith("@/components/site/generated/")?{allowed:!1}:{allowed:e.allowedExternalImports.some(o=>o.endsWith("/")?e.source.startsWith(o):e.source===o)};if(e.source.includes("\\")||e.source.includes("\0"))return{allowed:!1};let t=Tt.posix.normalize(Tt.posix.join(Tt.posix.dirname(e.importer),e.source));if(t===e.instanceRoot||!t.startsWith(`${e.instanceRoot}/`))return{allowed:!1};let r=[t,`${t}.ts`,`${t}.tsx`,`${t}.json`,...["ts","tsx","json"].map(o=>`${t}/index.${o}`)].find(o=>e.filePaths.has(o));return r?{allowed:!0,internalPath:r}:{allowed:!1}}function gI(e){let t=Tt.posix.dirname(e.importer),n=Tt.posix.dirname(e.imported),r=Tt.posix.basename(e.importer).replace(/\.tsx?$/,""),o=Tt.posix.basename(e.imported).slice(0,-li.length),i=`./${r}${li}`;return!e.importer.endsWith(".tsx")||t!==n||r!==o||e.source!==i?{ok:!1,error:{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Component i18n resources must use an explicit same-directory, same-name import from a .tsx file.",file:e.importer}}:e.ast.program.directives.some(a=>a.value.value==="use client")?{ok:!0}:{ok:!1,error:{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:'A component that imports .i18n.json must declare the top-level "use client" directive.',file:e.importer}}}function hI(e,t){for(let n of e.program.body){if(t.kind==="default"&&n.type==="ExportDefaultDeclaration")return!0;if(t.kind!=="named"||n.type!=="ExportNamedDeclaration")continue;if(n.specifiers.some(o=>o.exported.type==="Identifier"&&o.exported.name===t.name))return!0;let r=n.declaration;if((r?.type==="FunctionDeclaration"||r?.type==="ClassDeclaration")&&r.id?.name===t.name||r?.type==="VariableDeclaration"&&r.declarations.some(o=>o.id.type==="Identifier"&&o.id.name===t.name))return!0}return!1}function yI(e,t){let n=new Set,r=[e];for(;r.length>0;){let o=r.pop();n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function yn(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function xI(e){let t=Sp(e);return t===Ga?t:null}function bI(e){let t=e.trim().toLowerCase();return oI.test(t)?t:null}function bp(e){let t=e.trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,49).replace(/-+$/g,"");return rI.test(t)?t:null}function Sp(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=Tt.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function SI(e){let t=Sp(e);return!t||t!==e?null:t}function Ep(...e){return Tt.posix.join(...e)}function hp(e){return new Set(e.map(t=>t.pathTemplate))}function EI(e){let t=new Set;for(let n of e){if(t.has(n.pathTemplate))return n.pathTemplate;t.add(n.pathTemplate)}return null}function vI(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function yp(e){let t=e;for(;;){if(!t||typeof t!="object"||!("type"in t))return null;if(t.type==="Identifier"&&"name"in t&&typeof t.name=="string")return t.name;if(t.type==="MemberExpression"||t.type==="OptionalMemberExpression"){t=t.object;continue}return null}}import{randomBytes as II}from"node:crypto";import di from"node:path";import{parse as ec}from"@babel/parser";import kI from"@babel/traverse";import*as wp from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as Za,PageResourceArtifactSchema as CI,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as RI,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as wI,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as NI,parseComponentI18nResourcesJson as PI}from"@vcp-dev/contracts";var Qa="{{$INSTANCE}}",AI=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,TI=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,qa="components/site/generated",FI=/\.(?:tsx?|json)$/,_I=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,OI=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],MI=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Ya=kI,DI=typeof Ya=="function"?Ya:Ya.default;async function tc(e){let t=CI.safeParse(e.artifact);if(!t.success)return ce("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>II(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=WI(r());if(!i)return ce("Random instance suffix must be 8 lowercase hex chars.");let s=`${HI(n.resource_id)}-${i}`,a=new Map,c=new Map,l=[];for(let A of n.pages){let O=A.final_route.slice(1);a.set(A.template_page_id,A.final_route),c.set(A.template_page_id,A.title),l.push({template_page_id:A.template_page_id,title:A.title,final_route:A.final_route,route_file_path:`app/${O}/page.tsx`})}let u=[],d=new Set,p=new Set,m=new Map,g=new Map,b=[],C=new Set(n.pages.flatMap(A=>A.components.map(O=>O.component_id)));for(let A of n.components){if(!C.has(A.component_id))continue;let O=vp({materialization:A.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c});if(!O.ok)return O;for(let ie of O.files){let oe=kp(ie,d,u);if(oe)return oe}p.add(O.entry),g.set(O.entry,O.entryExport),m.set(A.component_id,O.entry)}for(let[A,O]of n.pages.entries()){let ie=l[A],oe=vp({materialization:O.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c,pageEntryTarget:ie.route_file_path,pageTitle:ie.title});if(!oe.ok)return oe;for(let M of oe.files){let j=kp(M,d,u);if(j)return j}p.add(oe.entry),g.set(oe.entry,oe.entryExport),b.push({entry:oe.entry,declaredComponentIds:new Set(O.components.map(M=>M.component_id))});let N=u.find(M=>M.file===ie.route_file_path);if(!N)return ce("Page materialization entry did not resolve to its final route file.",ie.route_file_path);if(VI(N.content,ie.route_file_path)!==ie.final_route)return ce(`Page ${O.template_page_id} requires a static PAGE_SEO.path equal to ${ie.final_route}.`,ie.route_file_path)}let I=BI(u,p,s,m,b,g);if(!I.ok)return I;for(let A of u)if(await e.exists(A.file))return!A.file.startsWith("app/")&&o>1?tc({...e,randomHex:r,maxAttempts:o-1}):{ok:!1,code:"MATERIALIZATION_CONFLICT",message:`Page resource create-only target already exists: ${A.file}`,path:A.file};let w=jI(u);return w||(u.sort((A,O)=>A.file.localeCompare(O.file)),{ok:!0,packageInstanceId:s,pages:l,files:u})}function vp(e){let t=e.materialization.entry.pathTemplate,n=[];for(let o of e.materialization.files){let i=o.pathTemplate===t,s=i&&e.pageEntryTarget?e.pageEntryTarget:Ip(o.pathTemplate,e.packageInstanceId);if(!s)return ce("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=LI(o.content,e.packageInstanceId,e.routeByPage,e.titleByPage);if(!a.ok)return a;let c=i&&e.pageTitle!==void 0?UI(a.data,e.pageTitle,s):a;if(!c.ok)return c;n.push({operation:"create-only",file:s,content:c.data})}let r=e.pageEntryTarget??Ip(t,e.packageInstanceId);return!r||!n.some(o=>o.file===r)?ce("Materialization entry must match one controlled source file.",t):{ok:!0,files:n,entry:r,entryExport:e.materialization.entry.export}}function LI(e,t,n,r){let o,i=e.replace(AI,(c,l)=>{let u=n.get(l);return u||(o=l,c)});if(o)return ce(`Page route placeholder references unknown template page: ${o}`);let s=i.replace(TI,(c,l)=>{let u=r.get(l);return u?JSON.stringify(u):(o=l,c)});if(o)return ce(`Page title placeholder references unknown template page: ${o}`);let a=s.replaceAll(Qa,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?ce("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function Ip(e,t){let n=`${qa}/${t}`;if(e.split(Qa).length>2)return null;let o=e.replace(Qa,t),i=`${qa}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=di.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!FI.test(a)||_I.test(a)?null:a}function kp(e,t,n){return t.has(e.file)?ce(`Page resource materializations resolve duplicate target: ${e.file}`,e.file):(t.add(e.file),n.push(e),null)}function BI(e,t,n,r,o,i){let s=new Set(e.map(m=>m.file)),a=`${qa}/${n}`,c=new Map(e.map(m=>[m.file,new Set])),l=new Map;for(let m of e){if(m.file.endsWith(".json")){try{JSON.parse(m.content)}catch{return ce("Materialization JSON file must contain valid JSON.",m.file)}if(m.file.endsWith(Za)&&!PI(m.content).success)return ce("Materialization component i18n resources are invalid.",m.file);continue}try{let b=ec(m.content,{sourceType:"module",plugins:["jsx","typescript"]});l.set(m.file,b);for(let I of b.program.body)if((I.type==="ImportDeclaration"||I.type==="ExportAllDeclaration"||I.type==="ExportNamedDeclaration"&&I.source)&&I.source){let w=I.source.value,A=XI(m.file,w,s,a);if(!A.allowed)return ce(`Materialization import is outside the controlled package: ${w}`,m.file);A.internalPath&&c.get(m.file).add(A.internalPath)}let C;if(DI(b,{Identifier(I){I.isReferencedIdentifier()&&MI.has(I.node.name)&&(C??=I.node.name,I.stop())},JSXAttribute(I){I.node.name.type==="JSXIdentifier"&&I.node.name.name==="style"&&(C??="inline style",I.stop())},JSXOpeningElement(I){I.node.name.type==="JSXIdentifier"&&I.node.name.name.toLowerCase()==="style"&&(C??="style element",I.stop())}}),C)return ce(`Materialization source uses forbidden capability: ${C}`,m.file)}catch{return ce("Materialization source must parse as TS/TSX.",m.file)}let g=Fr(m.content,{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0});if(g.hardCodedSurfaceHits.length>0||g.rawColorHits.length>0||g.privateTokenHits.length>0)return ce("Materialization source violates the public theme token policy.",m.file)}if([...t].some(m=>!s.has(m)))return ce("Materialization entry is outside the controlled package.");for(let m of t)if(m.endsWith(".json"))return ce("Materialization JSON files cannot be package entries.");for(let[m,g]of i){let b=l.get(m);if(!b||!$I(b,g))return ce("Materialization entry does not declare its contracted export.",m)}let u=new Map([...r].map(([m,g])=>[g,m]));for(let m of o){let g=Rp(m.entry,c);for(let b of m.declaredComponentIds){let C=r.get(b);if(!C||!g.has(C))return ce(`Page entry does not reach declared component: ${b}`,m.entry)}for(let b of g){let C=u.get(b);if(C&&!m.declaredComponentIds.has(C))return ce(`Page entry imports undeclared component: ${C}`,m.entry)}}let d=new Set;for(let m of t)for(let g of Rp(m,c))d.add(g);if(d.size!==e.length)return ce("Every materialization file must be reachable from a package entry.");let p=zI(e,l,c);return p||{ok:!0}}function jI(e){if(e.length>RI)return ce("Page resource exceeds the aggregate source file limit.");let t=0;for(let n of e){let r=Buffer.byteLength(n.content,"utf8");if(r>wI)return ce("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>NI?ce("Page resource exceeds the aggregate content byte limit."):null}function $I(e,t){for(let n of e.program.body){if(t.kind==="default"){if(n.type==="ExportDefaultDeclaration")return!0;continue}if(n.type==="ExportNamedDeclaration"&&(n.declaration?.type==="VariableDeclaration"&&n.declaration.declarations.some(r=>r.id.type==="Identifier"&&r.id.name===t.name)||(n.declaration?.type==="FunctionDeclaration"||n.declaration?.type==="ClassDeclaration")&&n.declaration.id?.name===t.name||n.specifiers.some(r=>r.exported.type==="Identifier"&&r.exported.name===t.name)))return!0}return!1}function VI(e,t){let n;try{n=ec(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return null}for(let r of n.program.body){let o=r.type==="VariableDeclaration"?r:r.type==="ExportNamedDeclaration"&&r.declaration?.type==="VariableDeclaration"?r.declaration:null;if(o)for(let i of o.declarations){if(i.id.type!=="Identifier"||i.id.name!=="PAGE_SEO")continue;let s=fi(i.init);if(s?.type!=="ObjectExpression")return null;for(let a of s.properties){if(a.type!=="ObjectProperty"||a.computed||!KI(a.key))continue;let c=fi(a.value);return c?.type==="StringLiteral"?c.value:c?.type==="TemplateLiteral"&&c.expressions.length===0?c.quasis[0]?.value.cooked??null:null}return null}}return null}function UI(e,t,n){let r;try{r=ec(e,{sourceType:"module",sourceFilename:n,plugins:["jsx","typescript"]})}catch{return ce("Page materialization PAGE_SEO must parse as TS/TSX.",n)}for(let o of r.program.body){let i=o.type==="VariableDeclaration"?o:o.type==="ExportNamedDeclaration"&&o.declaration?.type==="VariableDeclaration"?o.declaration:null;if(i)for(let s of i.declarations){if(s.id.type!=="Identifier"||s.id.name!=="PAGE_SEO")continue;let a=fi(s.init);if(a?.type!=="ObjectExpression")return ce("Page materialization PAGE_SEO must be a static object.",n);let c=a.properties.find(u=>u.type==="ObjectProperty"&&!u.computed&&JI(u.key));if(!c||c.type!=="ObjectProperty")return ce("Page materialization PAGE_SEO must declare a static title.",n);let l=fi(c.value);return!l||l.type!=="StringLiteral"&&l.type!=="TemplateLiteral"||l.type==="TemplateLiteral"&&l.expressions.length>0||typeof l.start!="number"||typeof l.end!="number"?ce("Page materialization PAGE_SEO.title must be a static string.",n):{ok:!0,data:e.slice(0,l.start)+JSON.stringify(t)+e.slice(l.end)}}}return ce("Page materialization must declare a top-level PAGE_SEO object.",n)}function fi(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&wp.isExpression(t)?t:null}function KI(e){return e.type==="Identifier"&&e.name==="path"||e.type==="StringLiteral"&&e.value==="path"}function JI(e){return e.type==="Identifier"&&e.name==="title"||e.type==="StringLiteral"&&e.value==="title"}function XI(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=Cp(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:OI.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=di.posix.normalize(di.posix.join(di.posix.dirname(e),t)),i=Cp(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function Cp(e,t){return[e,`${e}.ts`,`${e}.tsx`,`${e}.json`,`${e}/index.ts`,`${e}/index.tsx`,`${e}/index.json`].find(n=>t.has(n))}function zI(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(Za))continue;let i=o.file.slice(0,-Za.length),s=[`${i}.tsx`,`${i}.ts`].find(u=>r.has(u));if(!s)return ce("Component i18n resources require a same-name TS/TSX companion.",o.file);let c=t.get(s)?.program.directives.some(u=>u.value.value==="use client"),l=[...n].filter(([,u])=>u.has(o.file));if(!c||l.length!==1||l[0]?.[0]!==s)return ce("Component i18n resources must have exactly one same-name Client Component static importer.",s)}return null}function Rp(e,t){let n=new Set,r=[e];for(;r.length>0;){let o=r.pop();if(!n.has(o)){n.add(o);for(let i of t.get(o)??[])r.push(i)}}return n}function WI(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function HI(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"page-resource"}function ce(e,t){return{ok:!1,code:"MATERIALIZATION_REJECTED",message:e,...t?{path:t}:{}}}import{COMPONENT_I18N_FILE_SUFFIX as GI,parseComponentI18nResourcesJson as YI,resolveSiteTextDirection as ZI,SiteLocaleSchema as QI}from"@vcp-dev/contracts";var qI=["i18next","react-i18next"],ek="components/ui/site-locale-provider.tsx",tk="components/ui/component-i18n-provider.tsx",Np="app/layout.tsx";async function rc(e){let t=e.files.filter(p=>p.path.endsWith(GI));if(t.length===0)return{ok:!0};for(let p of["package.json",Np,ek,tk])if(!await e.exists(p))return xn(`Target snapshot is missing required i18n host file: ${p}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return xn("Target snapshot package.json is invalid.")}let r=Pp(n)&&Pp(n.dependencies)?n.dependencies:{},o=qI.filter(p=>typeof r[p]!="string"||r[p].trim().length===0);if(o.length>0)return xn(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile(Np),s=nc(i,"html","lang"),a=nc(i,"html","dir"),c=nc(i,"SiteLocaleProvider","locale"),l=QI.safeParse(s);if(!l.success||!a||!c||s!==c||a!==ZI(l.data))return xn("Target snapshot app/layout.tsx must keep html lang/dir and SiteLocaleProvider locale consistent.");if(!i.includes('from "@/components/ui/site-locale-provider"')||!/<SiteLocaleProvider\b/.test(i)||!/<\/SiteLocaleProvider>/.test(i))return xn("Target snapshot root layout is not wired to SiteLocaleProvider.");let u=l.data,d=u.split("-")[0];for(let p of t){let m=YI(p.content);if(!m.success)return xn(`Component i18n resource is invalid: ${p.path}.`);if(!Object.hasOwn(m.data,u)&&!Object.hasOwn(m.data,d))return xn(`Component i18n resource ${p.path} has no locale for ${u} or ${d}.`)}return{ok:!0}}function nc(e,t,n){let r=e.match(new RegExp(`<${t}\\b[^>]*>`))?.[0];if(!r)return null;let o=[...r.matchAll(new RegExp(`\\b${n}=(?:"([^"]+)"|\\{"([^"]+)"\\})`,"g"))];return o.length!==1?null:o[0]?.[1]??o[0]?.[2]??null}function Pp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xn(e){return{ok:!1,message:e}}import{PageTemplateIdSchema as hk}from"@vcp-dev/contracts";import FT from"node:fs";import OT from"node:path";var nk=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/,rk=/^\[[^\]]+\]$/,ok=/^\[\.\.\.[^\]]+\]$/,ik=/^\[\[\.\.\.[^\]]+\]\]$/;function _r(e){let t=e.map(r=>gk(r.path)),n=ak(t);return n?t.filter(r=>lk(n,r)).map(r=>({routeId:uk(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function sk(e){return e.split("/").filter(Boolean).some(t=>rk.test(t)||ok.test(t)||ik.test(t))}function Ap(e){return sk(pi(e))}function pi(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=mk(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function ak(e){return e.some(r=>r.startsWith("app/")&&!ck(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function ck(e){return/^(?:src\/)?app\/(?:_vcp|\.vcp)/.test(e)}function lk(e,t){if(!t.startsWith(`${e}/`))return!1;let n=t.slice(t.lastIndexOf("/")+1);return nk.test(n)?t.slice(e.length+1,-n.length-1).split("/").filter(Boolean).every(r=>!r.startsWith("_")&&!r.startsWith(".")):!1}function uk(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(fk).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function dk(e){return e.startsWith("(")&&e.endsWith(")")}function fk(e){return!e||e.startsWith("@")||e.startsWith("_")||dk(e)?null:pk(e)}function pk(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function mk(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function gk(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var Or=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function $e(e,t={}){throw new Or("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Invalid page-template source (${e}): ${t.path??t.routeId??t.templateId??""}`,{reason:e,...t})}function oc(e){return hk.safeParse(e).success||$e("invalid-template-id",{templateId:e}),Buffer.from(e,"utf8").toString("base64url")}function Tp(e){/^[A-Za-z0-9_-]{1,255}$/.test(e)||$e("invalid-template-key",{path:e});let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.from(e,"base64url"))}catch{return $e("invalid-template-key",{path:e})}return oc(t)!==e&&$e("noncanonical-template-key",{path:e}),t}function yk(e){let t=pi(e),n=t.slice(1).split("/");return(!e.startsWith("/")||/[?#\\%\u0000-\u001f]/.test(e)||t.startsWith("/.vcp")||Ap(t)||t!=="/"&&n.some(r=>!r||r==="."||r===".."||r.startsWith("@")||r.startsWith("_")||r.startsWith("(")))&&$e("invalid-public-route",{routeId:e}),t}function Fp(e,t,n="app"){n!=="app"&&n!=="src/app"&&$e("invalid-app-root");let r=yk(e),o=oc(t),i=`${n}/.vcp/page-templates${r==="/"?"":r}`,s=`${i}/${o}/page.tsx`;return(Buffer.byteLength(s,"utf8")>4095||s.split("/").some(a=>Buffer.byteLength(a,"utf8")>255))&&$e("path-too-long",{path:s}),{appRoot:n,routeRoot:i,templateKey:o,templateEntryFile:s}}function _p(e){return/^(?:src\/)?app\/\.vcp\/page-templates\//.test(e)}function Op(e){let t=Array.isArray(e)?e.map(r=>[r.path,r.content]):[...e],n=new Map;for(let[r,o]of t){let i=r.replace(/\\/g,"/").replace(/^\.\//,"");i.split("/").some(s=>s===".."||s===".")&&$e("invalid-file-path",{path:i}),n.has(i)&&$e("duplicate-file-path",{path:i}),n.set(i,o)}return n}function gi(e){let t=Op(e.files),n=_r([...t.keys()].map(i=>({path:i}))),r=new Map;for(let i of n){if(r.has(i.routeId))throw new Or("PAGE_TEMPLATE_ROUTE_AMBIGUOUS",`Multiple canonical entries for ${i.routeId}`,{reason:"duplicate-route-id",routeId:i.routeId,candidates:n.filter(s=>s.routeId===i.routeId).map(s=>s.entryFile)});r.set(i.routeId,i.entryFile)}let o=[];for(let i of t.keys()){if(!_p(i))continue;let s=/^(app|src\/app)\/\.vcp\/page-templates\/(.+)\/page\.tsx$/.exec(i);s||$e("candidate-must-be-single-page",{path:i});let a=s[1],c=s[2].split("/"),l=Tp(c.pop()),u=c.length?`/${c.join("/")}`:"/";Fp(u,l,a).templateEntryFile!==i&&$e("candidate-path-mismatch",{path:i,routeId:u});let p=r.get(u);(!p||!p.startsWith(`${a}/`))&&$e("canonical-entry-missing",{path:i,routeId:u}),o.push({routeId:u,templateId:l,entryFile:i,canonicalEntryFile:p,appRoot:a})}return o.sort((i,s)=>mi(i.routeId,s.routeId)||mi(i.templateId,s.templateId))}function Mp(e){let t=Op(e.files),n=gi({files:t}),r=_r([...t.keys()].map(o=>({path:o}))).map(o=>({context:{routeId:o.routeId},entryFile:o.entryFile}));return r.push(...n.map(o=>({context:{routeId:o.routeId,effectiveTemplateId:o.templateId},entryFile:o.entryFile}))),r.sort((o,i)=>mi(o.context.routeId,i.context.routeId)||(o.context.effectiveTemplateId===void 0?-1:i.context.effectiveTemplateId===void 0?1:mi(o.context.effectiveTemplateId,i.context.effectiveTemplateId)))}function xk(e){let t=pi(e.selector.routeId),n=Mp({files:e.files}),r=n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===void 0);(!r||r.entryFile!==e.canonicalEntryFile)&&$e("canonical-entry-mismatch",{routeId:t,path:e.canonicalEntryFile});let o=e.selector.templateId===void 0?r:n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===e.selector.templateId);return o||$e("template-selection-not-found",{routeId:t,templateId:e.selector.templateId}),{...o,mode:e.selector.templateId===void 0?"direct":"candidate",effectiveEntryFile:o.entryFile}}function mi(e,t){return e<t?-1:e>t?1:0}import{HOME_PAGE_URL_PATH as Tk}from"@vcp-dev/contracts";import{parse as vF}from"@babel/parser";import{parse as KT}from"@babel/parser";import{FormBlockIdSchema as XT,FormSpecV1Schema as zT}from"@vcp-dev/contracts";var Mr="components/site/generated/forms",WT=`${Mr}/vcp-form-runtime.tsx`,hi="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",HT=new RegExp(`^${Mr}/form-(${hi})\\.spec\\.ts$`),GT=new RegExp(`^${Mr}/form-(${hi})\\.tsx$`),YT=new RegExp(`^@/${Mr}/form-(${hi})$`),ZT=new RegExp(`(?:^|/)${Mr}/form-(${hi})(?:\\.tsx?)?$`);var QT=Symbol("invalid-literal");import{createHash as tF}from"node:crypto";import{posix as rF}from"node:path";import{parse as iF}from"@babel/parser";import{FormSpecV1Schema as aF}from"@vcp-dev/contracts";var cF=Symbol("dynamic");import{parse as bk}from"@babel/parser";function yi(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.type=="string"):[]}var Sk=/^(?:src\/)?app\/(.*)page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function Ek(e){let t=Sk.exec(e);if(!t)return null;let r=(t[1]??"").split("/").filter(o=>o.length>0&&!/^\(.+\)$/.test(o));return r.length===0?"/":`/${r.join("/")}`}function vk(e){let t=e;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Dp(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Ik(e){let t=e;for(;t&&(t.type==="TSAsExpression"||t.type==="TSSatisfiesExpression"||t.type==="ParenthesizedExpression");)t=t.expression??null;return t}function ic(e){let t=e;if(t?.type==="StringLiteral"||t?.type==="NumericLiteral"||t?.type==="BooleanLiteral")return t.value;if(t?.type==="NullLiteral")return null;if(t?.type==="ArrayExpression")return(t.elements??[]).map(ic);if(t?.type==="ObjectExpression"){let n={};for(let r of yi(t.properties)){if(r.type!=="ObjectProperty"||r.computed)throw new Error("dynamic object property");let o=Dp(r.key);if(!o)throw new Error("unsupported object key");n[o]=ic(r.value)}return n}throw new Error(`unsupported static value: ${t?.type??"unknown"}`)}function sc(e,t){let n=[],r=Ek(t);if(r===null)return{found:!1,seo:null,diagnostics:n};let o;try{o=bk(e,{sourceType:"module",plugins:["typescript","jsx"]})}catch(l){return n.push({code:"page-seo.parse-failed",message:l instanceof Error?l.message:String(l)}),{found:!1,seo:null,diagnostics:n}}let i;for(let l of yi(o.program.body)){let u=l.type==="ExportNamedDeclaration"?l.declaration:l;if(u?.type==="VariableDeclaration")for(let d of yi(u.declarations)){let p=d.id;p?.type==="Identifier"&&p.name==="PAGE_SEO"&&(i=d.init)}}if(i==null)return{found:!1,seo:null,diagnostics:n};let s=Ik(i);if(!s)return{found:!1,seo:null,diagnostics:n};if(s.type!=="ObjectExpression")return n.push({code:"page-seo.dynamic-declaration",message:"PAGE_SEO is not a static object literal"}),{found:!1,seo:null,diagnostics:n};let a={};for(let l of yi(s.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=Dp(l.key);if(!(u!=="path"&&u!=="title"&&u!=="description"&&u!=="keywords"&&u!=="meta_tags_json"&&u!=="schema_json"&&u!=="breadcrumbs_json")){if(u==="path"||u==="title"||u==="description"||u==="keywords"){let d=vk(l.value);if(d===void 0){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} is not a static string; skipped`});continue}a[u]=d;continue}try{let d=ic(l.value);u==="meta_tags_json"&&d!==null&&typeof d=="object"&&!Array.isArray(d)?a.meta_tags_json=d:u==="schema_json"&&d!==null&&typeof d=="object"?a.schema_json=d:u==="breadcrumbs_json"&&Array.isArray(d)?a.breadcrumbs_json=d:n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} has unsupported static shape; skipped`})}catch(d){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} is not a static JSON-like value; skipped: ${d instanceof Error?d.message:String(d)}`})}}}let c=r;return a.path!==void 0&&(a.path!==r&&n.push({code:"page-seo.path-mismatch",message:`PAGE_SEO.path "${a.path}" != derived "${r}"; using PAGE_SEO.path`}),c=a.path),{found:!0,seo:{path:c,...a.title!==void 0?{title:a.title}:{},...a.description!==void 0?{description:a.description}:{},...a.keywords!==void 0?{keywords:a.keywords}:{},...a.meta_tags_json!==void 0?{meta_tags_json:a.meta_tags_json}:{},...a.schema_json!==void 0?{schema_json:a.schema_json}:{},...a.breadcrumbs_json!==void 0?{breadcrumbs_json:a.breadcrumbs_json}:{}},diagnostics:n}}import{parse as kk}from"@babel/parser";var Lp=["page","anchor","external","email","phone","group","file"],Ck=["link","cta"],jp=["description","badge","iconKey"],ac=["label","targetType","href","role","openInNewTab","nofollow","children",...jp],Rk=new Set(ac);function Lr(e){return Array.isArray(e)?e:[]}function Dr(e){let t=e;return t?.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function wk(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Bp(e){let t=e;return t?.type==="BooleanLiteral"&&typeof t.value=="boolean"?t.value:void 0}function cc(e){let t=[],n;try{n=kk(e,{sourceType:"module",plugins:["typescript","jsx"]})}catch(i){return{items:[],diagnostics:[{severity:"fatal",path:"NAV_ITEMS",message:`parse failed: ${String(i)}`}]}}let r;for(let i of Lr(n.program.body)){let s=i.type==="ExportNamedDeclaration"?i.declaration:i;if(s?.type==="VariableDeclaration")for(let a of Lr(s.declarations)){let c=a.id;c?.type==="Identifier"&&c.name==="NAV_ITEMS"&&(r=a.init)}}for(;r&&(r.type==="TSAsExpression"||r.type==="TSSatisfiesExpression"||r.type==="TSInstantiationExpression");)r=r.expression;if(!r||r.type!=="ArrayExpression")return{items:[],diagnostics:[{severity:"fatal",path:"NAV_ITEMS",message:"missing top-level NAV_ITEMS array literal"}]};let o=[];return Lr(r.elements).forEach((i,s)=>{let a=$p(i,`NAV_ITEMS[${s}]`,t);a&&o.push(a)}),{items:o,diagnostics:t}}function $p(e,t,n){if(e?.type!=="ObjectExpression")return n.push({severity:"fatal",path:t,message:"nav item must be an object literal"}),null;let r={};for(let l of Lr(e.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=wk(l.key);u&&(r[u]=l.value)}let o=Dr(r.label),i=Dr(r.targetType);if(!o)return n.push({severity:"fatal",path:`${t}.label`,message:"label must be a static string"}),null;if(!i||!Lp.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${Lp.join("/")}`}),null;r.group!==void 0&&n.push({severity:"warning",code:"leaf-group-field",path:`${t}.group`,message:'unsupported leaf group field ignored; use a canonical targetType: "group" node with children'});let s={label:o,targetType:i};for(let l of jp){if(r[l]===void 0)continue;let u=Dr(r[l]);u!==void 0?s[l]=u:n.push({severity:"warning",path:`${t}.${l}`,message:`${l} ignored: not a static string`})}r.icon!==void 0&&n.push({severity:"warning",path:`${t}.icon`,message:"icon component ref ignored; use static iconKey"});for(let l of Object.keys(r))Rk.has(l)||l==="group"||l==="icon"||n.push({severity:"warning",code:"unknown-field",path:`${t}.${l}`,message:`unsupported field \`${l}\` ignored; NAV_ITEMS only carries ${ac.join("/")}`});if(r.children!==void 0){if(r.children.type!=="ArrayExpression")return n.push({severity:"fatal",path:`${t}.children`,message:"children must be a static array"}),null;let l=[];Lr(r.children.elements).forEach((u,d)=>{let p=$p(u,`${t}.children[${d}]`,n);p&&l.push(p)}),s.children=l}if(i==="group")return s.children?s:(n.push({severity:"fatal",path:`${t}.children`,message:"group item requires children"}),null);let a=Dr(r.href);if(!a)return n.push({severity:"fatal",path:`${t}.href`,message:"href must be a static string for non-group item"}),null;s.href=a;let c=Dr(r.role);if(c!==void 0&&(Ck.includes(c)?s.role=c:n.push({severity:"warning",path:`${t}.role`,message:"role ignored: not link/cta"})),r.openInNewTab!==void 0){let l=Bp(r.openInNewTab);l!==void 0?s.openInNewTab=l:n.push({severity:"warning",path:`${t}.openInNewTab`,message:"openInNewTab ignored: not a static boolean"})}if(r.nofollow!==void 0){let l=Bp(r.nofollow);l!==void 0?s.nofollow=l:n.push({severity:"warning",path:`${t}.nofollow`,message:"nofollow ignored: not a static boolean"})}return s}import{parse as Nk}from"@babel/parser";function Br(e){return Array.isArray(e)?e:[]}function Vp(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function lc(e,t){let n=Up(t);if(!n)return{status:"unsupported",source:e};let r;try{r=Nk(e,{sourceType:"module",plugins:["typescript","jsx"],tokens:!0})}catch{return{status:"unsupported",source:e}}let o=[];for(let u of Br(r.program.body)){let d=u.type==="ExportNamedDeclaration"?u.declaration:u;if(d?.type==="VariableDeclaration")for(let p of Br(d.declarations)){let m=p.id;m?.type==="Identifier"&&m.name==="NAV_ITEMS"&&o.push(p)}}if(o.length===0)return{status:"navigation_not_found",source:e};if(o.length!==1)return{status:"unsupported",source:e};let i=Vp(o[0]?.init);if(!i)return{status:"unsupported",source:e};if(cc(e).diagnostics.some(({severity:u})=>u==="fatal"))return{status:"unsupported",source:e};let a=[],c=u=>{let d=Br(u.elements);for(let[p,m]of d.entries()){if(Ak(m,n)){let b=d[p+1],C=d[p-1],I=m.start,w=m.end;if(typeof I!="number"||typeof w!="number")continue;b&&typeof b.start=="number"?a.push({start:I,end:b.start}):C&&typeof C.end=="number"?a.push({start:C.end,end:w}):a.push({start:I,end:w});continue}let g=Pk(m);g&&c(g)}};if(c(i),a.length===0)return{status:"not_found",source:e};let l=e;for(let u of a.sort((d,p)=>p.start-d.start))l=l.slice(0,u.start)+l.slice(u.end);return{status:"removed",source:l,removedCount:a.length}}function Pk(e){if(e.type==="ObjectExpression")for(let t of Br(e.properties)){if(t.type!=="ObjectProperty")continue;let n=t.key;if((n?.name??n?.value)==="children")return Vp(t.value)}}function Up(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function Ak(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of Br(e.properties)){if(o.type!=="ObjectProperty")continue;let i=o.key,s=o.value,a=i?.name??i?.value;s?.type==="StringLiteral"&&(a==="href"&&(n=String(s.value)),a==="targetType"&&(r=String(s.value)))}return r==="page"&&Up(n??"")===t}var Fk="components/site/generated/",jr=[".tsx",".ts",".jsx",".js"];function Kp(e){if(e.expectedUrlPath===Tk)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set(_r(Object.keys(e.files).map(p=>({path:p}))).map(p=>p.entryFile)),n=Object.entries(e.files).filter(([p,m])=>{let g=p.replace(/\\/g,"/");if(!t.has(g))return!1;let b=sc(m,g);return b.found&&b.seo?.path===e.expectedUrlPath});if(n.length===0)return{ok:!1,code:"ROUTE_NOT_FOUND",message:"No route uniquely matches the requested page identity."};if(n.length>1)return{ok:!1,code:"ROUTE_AMBIGUOUS",message:"Multiple routes match the requested page identity."};let[r]=n[0];try{if(gi({files:new Map(Object.entries(e.files))}).some(m=>m.canonicalEntryFile===r))return{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:"Clean up page template candidates before deleting their canonical page."}}catch(p){return{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:p instanceof Error?p.message:"Invalid page template source."}}let o=_k(e.files);if(!o.ok)return o.error;let i=o.graph,s=Lk(r,i),a=Bk(r,s,i),c=[...s].filter(p=>!a.has(p)).sort((p,m)=>p.localeCompare(m)),l=[{operation:"delete",file:r},...[...a].sort((p,m)=>p.localeCompare(m)).map(p=>({operation:"delete",file:p}))],u=[],d=[];for(let[p,m]of Object.entries(e.files))if(p!==r){if(m.includes("NAV_ITEMS")){let g=lc(m,e.expectedUrlPath);g.status==="removed"?(l.push({operation:"upsert",file:p,content:g.source}),u.push(p)):g.status==="unsupported"&&d.push(`unsupported_navigation:${p}`)}m.includes(e.expectedUrlPath)&&!m.includes("NAV_ITEMS")&&d.push(`preserved_link:${p}`)}return{ok:!0,edits:l,deletedFiles:[r,...[...a].sort((p,m)=>p.localeCompare(m))],updatedFiles:u,preservedSharedFiles:c,warnings:d}}function _k(e){let t=new Set(Object.keys(e)),n=new Map;for(let[r,o]of Object.entries(e)){let i=r.replace(/\\/g,"/");if(i==="next-env.d.ts"||i.endsWith("/next-env.d.ts")||!Ok(r))continue;let s=qn(r,o);if(!s.ok)return{ok:!1,error:{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:`Page source dependencies could not be proven safe: ${r} (parse-failed).`}};let a=new Set;for(let{specifier:c}of s.module.imports){if(Mk(c))continue;let l=Qn(r,c),u=Dk(l,t);if(!u)return{ok:!1,error:{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:`Page source dependencies could not be proven safe: ${r} -> ${c} (import-not-found).`}};a.add(u)}n.set(r,a)}return{ok:!0,graph:n}}function Ok(e){let t=e.toLowerCase();return jr.some(n=>t.endsWith(n))}function Mk(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!jr.some(n=>e.endsWith(n)))}function Dk(e,t){let n=e.replace(/\\/g,"/");return(jr.some(o=>n.endsWith(o))?[n]:[...jr.map(o=>`${n}${o}`),...jr.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function Lk(e,t){let n=new Set,r=[...t.get(e)??[]];for(;r.length>0;){let o=r.pop();!o.startsWith(Fk)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function Bk(e,t,n){let r=new Set(t),o=!0;for(;o;){o=!1;for(let i of[...r])[...n].some(([a,c])=>a!==e&&!r.has(a)&&c.has(i))&&(r.delete(i),o=!0)}return r}import{SiteEditHistoryProvenanceSchema as jk}from"@vcp-dev/contracts";var $k={affectedCompositions:[]};function Gp(e){let t=null,n=new WeakMap;async function r(){return t??=Vk(e),t}return{async prepareAppend(o){let i=await e.readIndex(),s=await e.stageAppend(Wp(o),{durableManifest:!1}),a;try{a=await e.previewStagedAppend(s.entryId,i.digest)}catch(l){throw await e.discardStage(s.stageId),l}let c={kind:"append",entry:o,historyTransition:a};return n.set(c,{expectedDigest:i.digest,stageId:s.stageId,entryId:s.entryId}),c},async prepareUndo(){let i=(await r()).undo.at(-1);if(!i?.historyId)return null;let s=await e.readIndex(),a=s.entryIds.indexOf(i.historyId);if(a<0)throw new Error("undo entry is missing from index");let c=a-1,l=await e.previewCursor(c,s.digest),u={kind:"undo",entry:i,historyTransition:l};return n.set(u,{expectedDigest:s.digest,cursor:c}),u},async prepareRedo(){let i=(await r()).redo.at(-1);if(!i?.historyId)return null;let s=await e.readIndex(),a=s.entryIds.indexOf(i.historyId);if(a<0)throw new Error("redo entry is missing from index");let c=a,l=await e.previewCursor(c,s.digest),u={kind:"redo",entry:i,historyTransition:l};return n.set(u,{expectedDigest:s.digest,cursor:c}),u},async publishPrepared(o){let i=n.get(o);if(!i)throw new Error("history mutation was not prepared");let s=await r();if(o.kind==="append"){if(!i.entryId)throw new Error("staged entry id is missing");let a=await e.publishStagedAppend(i.entryId,i.expectedDigest,i.stageId);Jp(a,o.historyTransition),o.entry.historyId=i.entryId,s.entryIds=[...a.entryIds],s.cursor=a.cursor,s.undo.push(o.entry),s.redo.length=0}else{if(i.cursor===void 0)throw new Error("prepared cursor is missing");let a=await e.setCursor(i.cursor,i.expectedDigest);if(Jp(a,o.historyTransition),o.kind==="undo"){if(s.undo.at(-1)!==o.entry)throw new Error("undo state changed before publish");s.undo.pop(),s.redo.push(o.entry)}else{if(s.redo.at(-1)!==o.entry)throw new Error("redo state changed before publish");s.redo.pop(),s.undo.push(o.entry)}s.cursor=i.cursor}n.delete(o)},async discardPrepared(o){let i=n.get(o);if(!i)return;let s=o.historyTransition;if(s){let a=await e.readIndex();if(a.digest===s.publishedIndexDigest&&a.cursor===s.publishedCursor&&a.currentId===s.publishedCurrentId)throw new Error("cannot discard a history mutation whose index was published")}i.stageId&&await e.discardStage(i.stageId),n.delete(o)},async peekUndo(){return(await r()).undo.at(-1)??null},async pushUndo(o){let i=await r(),s=o;if(s.historyId){let l=i.entryIds.indexOf(s.historyId);if(l>=0)try{await e.setCursor(l),i.undo.push(o),i.cursor=l;return}catch(u){throw i.redo.push(o),u}}let a=await e.append(Wp(o)),c=a.currentId;if(!c)throw new Error("history store did not publish an entry");o.historyId=c,i.entryIds=[...a.entryIds],i.cursor=a.cursor,i.undo.push(o),i.redo.length=0},async popUndo(){return(await r()).undo.pop()??null},async peekRedo(){return(await r()).redo.at(-1)??null},async pushRedo(o){let i=await r(),s=o;if(!s.historyId)throw i.undo.push(o),new Error("cannot move an unpersisted history entry to redo");let a=i.entryIds.indexOf(s.historyId);if(a<0)throw i.undo.push(o),new Error("history entry is missing from the durable index");try{await e.setCursor(a-1),i.cursor=a-1,i.redo.push(o)}catch(c){throw i.undo.push(o),c}},async popRedo(){return(await r()).redo.pop()??null},async clearRedo(){(await r()).redo.length=0},async getStatus(){let o=await e.readStatus();return{canUndo:o.canUndo,canRedo:o.canRedo,undoDepth:o.undoDepth,redoDepth:o.redoDepth,recoveryRequired:o.recoveryRequired}},async markRecoveryRequired(o){await e.markRecoveryRequired(o)}}}function Jp(e,t){if(!t)throw new Error("durable history transition is missing");if(e.digest!==t.publishedIndexDigest||e.cursor!==t.publishedCursor||e.currentId!==t.publishedCurrentId)throw new Error("durable history published an unexpected index state")}async function Vk(e){let t=await e.readIndex(),n=await Promise.all(t.undoIds.map(async o=>Xp(e,o))),r=await Promise.all(t.redoIds.map(async o=>Xp(e,o)));return{undo:n.reverse(),redo:r.reverse(),entryIds:[...t.entryIds],cursor:t.cursor}}async function Xp(e,t){let n=await e.readEntry(t),r=Uk(n),o=r.provenance??$k;return{historyId:t,...o.initiatingComposition?{composition:o.initiatingComposition}:{},operationId:r.operationId,kind:r.kind,target:r.target,provenance:o,...r.selectionRef?{selectionRef:r.selectionRef}:{},...r.output?{output:r.output}:{},preSnapshots:await zp(e,n,r.preSnapshots),postSnapshots:await zp(e,n,r.postSnapshots)}}async function zp(e,t,n){let r=new Map(t.blobs.map(o=>[o.name,o.digest]));return Promise.all(n.map(async o=>{let i=o.exists&&o.blobName?Buffer.from(await e.readBlob(Xk(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function Wp(e){let t=[],n=(i,s)=>i.map((a,c)=>{let l={file:a.file,exists:a.exists!==!1,version:a.version,...a.sha256?{sha256:a.sha256}:{}};if(l.exists){let u=`${s}-${c}`;l.blobName=u,t.push({name:u,data:a.content})}return l}),r=Kk(e),o={operationId:e.operationId,kind:e.kind,target:e.target,...r?{provenance:r}:{},...e.selectionRef?{selectionRef:e.selectionRef}:{},...e.output?{output:e.output}:{},preSnapshots:n(e.preSnapshots,"pre"),postSnapshots:n(e.postSnapshots,"post")};return{kind:"site-edit-operation",manifest:JSON.parse(JSON.stringify(o)),blobs:t}}function Uk(e){if(!Zp(e.manifest))throw new Error("durable history manifest is not an object");let t=e.manifest,n=new Set(["operationId","kind","target","selectionRef","output","provenance","preSnapshots","postSnapshots"]);if(Object.keys(t).some(r=>!n.has(r)))throw new Error("durable history manifest contains unknown fields");if(typeof t.operationId!="string"||t.operationId.length===0||typeof t.kind!="string"||t.kind.length===0||!Array.isArray(t.preSnapshots)||!Array.isArray(t.postSnapshots))throw new Error("durable history manifest has an invalid shape");return{operationId:t.operationId,kind:t.kind,target:t.target,...t.selectionRef!==void 0?{selectionRef:t.selectionRef}:{},...t.output!==void 0?{output:t.output}:{},...t.provenance!==void 0?{provenance:Yp(t.provenance)}:{},preSnapshots:Hp(t.preSnapshots,"preSnapshots"),postSnapshots:Hp(t.postSnapshots,"postSnapshots")}}function Kk(e){if(e.provenance!==void 0)return Yp(e.provenance);if(e.composition)return{initiatingComposition:e.composition,affectedCompositions:[]}}function Yp(e){let t=jk.safeParse(e);if(!t.success)throw new Error("durable history provenance is invalid");return{...t.data.initiatingComposition?{initiatingComposition:t.data.initiatingComposition}:{},affectedCompositions:t.data.affectedCompositions.map(n=>({routeId:n.routeId,...n.effectiveTemplateId?{effectiveTemplateId:n.effectiveTemplateId}:{}}))}}function Hp(e,t){return e.map((n,r)=>{if(!Zp(n))throw new Error(`durable history ${t}[${r}] is invalid`);if(typeof n.file!="string"||n.file.length===0||!Number.isInteger(n.version)||n.exists!==void 0&&typeof n.exists!="boolean"||n.sha256!==void 0&&!Jk(n.sha256)||n.blobName!==void 0&&typeof n.blobName!="string")throw new Error(`durable history ${t}[${r}] is invalid`);return{file:n.file,exists:n.exists!==!1,version:n.version,...n.sha256?{sha256:n.sha256}:{},...n.blobName?{blobName:n.blobName}:{}}})}function Jk(e){return/^sha256:[0-9a-f]{64}$/.test(e)}function Xk(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function Zp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import Qp from"node:path";function dc(){let e=Promise.resolve();return{async runExclusive(t){let n,r=new Promise(i=>{n=i}),o=e;e=o.then(()=>r,()=>r),await o;try{return await t()}finally{n()}}}}async function em(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=Gk(i.path);if(!s.ok)return s;let a=s.path;if(o.has(a))return{ok:!1,code:"duplicate-target",path:a,reason:`Duplicate file target: ${a}`};if(o.add(a),i.kind==="create-only"){let c=t.has(a),l=n?await n(a):!1;if(c||l)return{ok:!1,code:"create-only-exists",path:a,reason:`Create-only file already exists: ${a}`}}r.push({...i,path:a})}return{ok:!0,plan:{operationId:e.operationId,intents:r}}}async function xi(e){let t=()=>zk(e);return e.mutex?e.mutex.runExclusive(t):t()}async function zk(e){let t=await em(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=Wk(e.overlay,t.plan),r;try{r=await e.buildCandidate({overlay:n,plan:t.plan})}catch(l){return{ok:!1,stage:"build",reason:"Candidate build failed.",error:l,recoveryRequired:!1}}let o,i;try{o=await e.prepareHistory?.({candidate:r,plan:t.plan}),await e.reverify?.({candidate:r,plan:t.plan,history:o}),i=await e.writeCandidate({candidate:r,plan:t.plan}),await e.markCandidateWritten?.({candidate:r,plan:t.plan,history:o,receipt:i})}catch(l){return uc({candidate:r,plan:t.plan,failedStage:"commit",error:l,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let s=r;try{let l=await e.validateCandidate({candidate:r,plan:t.plan,receipt:i});l!==void 0&&(s=l)}catch(l){return uc({candidate:r,plan:t.plan,failedStage:"validate",error:l,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let a;try{a=await e.publishCandidate({candidate:s,plan:t.plan,history:o,receipt:i})}catch(l){return uc({candidate:s,plan:t.plan,failedStage:"publish",error:l,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let c={candidate:s,plan:t.plan,history:o,receipt:i,published:a};try{await e.swapCandidate?.(c)}catch(l){return qp("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return qp("finalize",l,"Transaction finalization failed after live state swap.")}try{e.emitCommitted?.({candidate:s,plan:t.plan,published:a})}catch{}return{ok:!0,stage:"publish",published:a,plan:t.plan}}function Wk(e,t){let n=new Map(e);for(let r of t.intents)r.kind==="delete"?n.delete(r.path):n.set(r.path,r.content);return n}function uc(e){return e.rollbackCandidate({candidate:e.candidate,plan:e.plan,failedStage:e.failedStage,error:e.error,...e.history===void 0?{}:{history:e.history},...e.receipt===void 0?{}:{receipt:e.receipt}}).then(()=>({ok:!1,stage:e.failedStage,reason:Hk(e.failedStage),error:e.error,recoveryRequired:!1})).catch(t=>({ok:!1,stage:"rollback",reason:"Rollback failed after candidate commit/validation/publish failure.",error:t,recoveryRequired:!0,cause:e.error}))}function qp(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function Hk(e){switch(e){case"commit":return"Candidate write or commit verification failed.";case"validate":return"Candidate validation failed.";case"publish":return"Candidate publish failed."}}function Gk(e){if(e.length===0)return{ok:!1,code:"unsafe-path",path:e,reason:"File path must not be empty."};if(e.includes("\0")||e.includes("\\"))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};if(/^[a-zA-Z]:/.test(e)||Qp.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=Qp.posix.normalize(e);return t==="."||t===".."||t.startsWith("../")||t.includes("/../")?{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`}:t.startsWith("./")||t.includes("/./")?{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`}:{ok:!0,path:t}}function fc(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function Wn(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function tm(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function pc(e,t,n,r){if(!e.has(t)&&e.size>=r){let o=e.keys().next().value;o&&e.delete(o)}e.set(t,n)}function nm(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function Yk(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var $r=class extends Error{constructor(t){let n=t.map(nm);super(Yk(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function rm(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof $r?{routeId:e,message:n,diagnostics:t.diagnostics.map(nm)}:{routeId:e,message:n}}function mc(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function om(e){let{journal:t,index:n,observedFileDigests:r}=e;if(r.length!==t.files.length)return"ambiguous";let o=t.files.every((l,u)=>l.preDigest===r[u]),i=t.files.every((l,u)=>l.postDigest===r[u]),s=t.historyTransition,a=n.digest===s.expectedIndexDigest,c=n.digest===s.publishedIndexDigest&&n.cursor===s.publishedCursor&&n.currentId===s.publishedCurrentId;return o&&a?"safely-uncommitted":i&&c?"durably-committed":"ambiguous"}import{computeSiteEditCompositionKey as bi,SiteEditCompositionContextSchema as Zk,SiteEditCompositionSelectorSchema as Qk}from"@vcp-dev/contracts";var Me=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="SiteEditCompositionError"}};function im(e,t){throw new Me("INVALID_COMPOSITION",e,{value:t})}function Si(e){let t=Zk.safeParse(e);return t.success?t.data:im("Invalid SiteEditCompositionContext.",e)}function sm(e){let t=[],n=new Map,r=new Map;for(let l of e.compositions){let u=Si(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new Me("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=bi(u);if(n.has(d))throw new Me("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u});let p=r.get(l.entryFile);if(p)throw new Me("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:p});let m={context:u,entryFile:l.entryFile,key:d};t.push(m),n.set(d,m),r.set(l.entryFile,d)}if(t.length===0)throw new Me("INVALID_COMPOSITION","At least one composition must be registered.");let o=new Map;for(let l of e.initialDocumentVersions??[]){let u=Si(l?.composition);if(!Number.isInteger(l?.version)||(l?.version??-1)<0)throw new Me("INVALID_INITIAL_DOCUMENT_VERSION","Initial document version must be a non-negative integer.",{context:u,version:l?.version});let d=bi(u);if(!n.has(d))throw new Me("UNKNOWN_COMPOSITION","Initial document version references an unregistered composition.",{context:u,key:d});if(o.has(d))throw new Me("DUPLICATE_COMPOSITION","Initial document versions must contain each composition at most once.",{context:u,key:d});o.set(d,l.version)}function i(l){let u=Qk.safeParse(l);if(!u.success)return im("Invalid SiteEditCompositionSelector.",l);let d=t.filter(({context:p})=>p.routeId===u.data.routeId&&(u.data.templateId===void 0?p.effectiveTemplateId===void 0:p.effectiveTemplateId===u.data.templateId));if(d.length===1)return d[0];throw d.length>1?new Me("AMBIGUOUS_COMPOSITION","The composition selector matches multiple registered contexts.",{selector:u.data}):new Me("UNKNOWN_COMPOSITION","The composition selector is not registered.",{selector:u.data})}function s(l){let u=Si(l),d=bi(u),p=n.get(d);if(!p)throw new Me("UNKNOWN_COMPOSITION","The composition context is not registered.",{context:u,key:d});return p}function a(l){let u=Si(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new Me("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=bi(u),p=n.get(d);if(p){if(p.entryFile===l.entryFile)return p;throw new Me("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u})}let m=[...n.values()].find(b=>b.entryFile===l.entryFile);if(m)throw new Me("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:m.context});let g={context:u,entryFile:l.entryFile,key:d};return t.push(g),n.set(d,g),g}function c(l){let u=n.get(l);if(!u)return;n.delete(l);let d=t.findIndex(p=>p.key===l);return d>=0&&t.splice(d,1),o.delete(l),u}return{entries:t,byKey:n,initialVersions:o,register:a,unregister:c,resolveSelector:i,resolveContext:s,getByKey:l=>n.get(l),routeIds:()=>[...new Set(t.map(({context:l})=>l.routeId))]}}var sC=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,aC=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],am=32,cm=256;function cC(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var lm={maxEntries:50,maxBytes:8*1024*1024};function lC(){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 ai(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 uC(){let e=[],t=[];return{prepareAppend(r){return{kind:"append",entry:r}},prepareUndo(){let r=e.at(-1);return r?{kind:"undo",entry:r}:null},prepareRedo(){let r=t.at(-1);return r?{kind:"redo",entry:r}:null},publishPrepared(r){if(r.kind==="append"){e.push(r.entry),n(),t.length=0;return}if(r.kind==="undo"){if(e.at(-1)!==r.entry)throw new Error("undo history changed before publish");e.pop(),t.push(r.entry);return}if(t.at(-1)!==r.entry)throw new Error("redo history changed before publish");t.pop(),e.push(r.entry),n()},peekUndo(){return e.at(-1)??null},pushUndo(r){e.push(r),n(),t.length=0},popUndo(){return e.pop()??null},peekRedo(){return t.at(-1)??null},pushRedo(r){t.push(r)},popRedo(){return t.pop()??null},clearRedo(){t.length=0},getStatus(){return{canUndo:e.length>0,canRedo:t.length>0,undoDepth:e.length,redoDepth:t.length,recoveryRequired:!1}}};function n(){for(;e.length>lm.maxEntries||dC(e)>lm.maxBytes;)e.shift()}}function dC(e){return e.reduce((t,n)=>t+fC(n),0)}function fC(e){return um(e.preSnapshots)+um(e.postSnapshots)+pC(e.provenance)}function pC(e){return e?new TextEncoder().encode(JSON.stringify(e)).byteLength:0}function um(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function dm(e,t){return{key:qk(e),composition:e,routeId:e.routeId,entryFile:t,graph:null,topology:null,capabilities:null,document:null,pageComposition:null,pageCompositionProjection:null,documentIndex:null,pagePlacementByKey:null,pagePlacementUnitByKey:null,pageUnitByKey:null,pagePlacementsByUnitKey:null,dependencyFiles:new Set([t]),detailProjections:null,fileVersions:new Map,styleContext:null}}function mC(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=Ve(o.key)??o.key;if(i===o.key)continue;let s=n.get(i)??0;r.set(o.key,s),n.set(i,s+1)}return{entriesByKey:t,repeatOccurrenceIndexByKey:r}}var Ii=class extends Error{constructor(t){super(t.reason),this.result=t}},bn=class extends Error{constructor(t){super(mc(t)),this.failedRoutes=t}};function fm(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=Ve(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(Ve(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}function gC(e,t,n){if(!n)return;let r=Ve(n.key)??n.key;if(n.key!==e&&n.key!==t&&r!==t)throw new Error(`Selection reference '${n.key}' does not match selected key '${e}'`);if(n.instanceIndex!==void 0&&(!Number.isInteger(n.instanceIndex)||n.instanceIndex<0))throw new Error("Selection reference instanceIndex must be non-negative");if(n.instanceCount!==void 0&&(!Number.isInteger(n.instanceCount)||n.instanceCount<=0))throw new Error("Selection reference instanceCount must be positive");if(n.instanceIndex!==void 0&&n.instanceCount!==void 0&&n.instanceIndex>=n.instanceCount)throw new Error("Selection reference instanceIndex must be smaller than instanceCount");return{...n,key:t}}var hC=/\.(?:[cm]?[jt]sx?)$/i,yC=/\.json$/i,xC=/\.(?:css|scss|sass)$/i,bC=/\.mdx$/i,SC=/\.ya?ml$/i;function EC(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 vC(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function IC(e,t){let n=new Map;for(let r of t)n.set(r.path,r.operation==="delete"?{exists:!1}:{exists:!0,content:r.content});return{async readFile(r){let o=n.get(r);if(o){if(!o.exists)throw new Error(`Source file not found: ${r}`);return o.content}return e.readFile(r)},async writeFile(){throw new Error("Source edit preflight overlay is read-only.")},async deleteFile(){throw new Error("Source edit preflight overlay is read-only.")},async exists(r){let o=n.get(r);return o?o.exists:e.exists(r)},async getFileInfo(r){let o=n.get(r);return o?o.exists?{path:r,sizeBytes:Buffer.byteLength(o.content,"utf8")}:null:e.getFileInfo?.(r)??null},async listFiles(r={}){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let o=xm(await e.listFiles(r)),i=new Map(o.files.map(a=>[a.path,a]));for(let[a,c]of n)if(kC(a,r.roots??[])){if(!c.exists){i.delete(a);continue}i.set(a,{path:a,sizeBytes:Buffer.byteLength(c.content,"utf8")})}let s=[...i.values()].sort((a,c)=>a.path.localeCompare(c.path));return o.truncated?{files:s,truncated:o.truncated}:s},getVersion(r){return e.getVersion(r)},bumpVersion(r){return e.getVersion(r)}}}function kC(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function xm(e){return Array.isArray(e)?{files:e}:e}function CC(e){if(!nC(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!==oC||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=tC(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(hC.test(e.path)){let t=yt({source:e.content,profile:rn({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(yC.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${Le(t)}`,details:{path:e.path}}}if(xC.test(e.path)){let t=pm({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(bC.test(e.path)){let t=pm({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(SC.test(e.path))try{iC(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${Le(t)}`,details:{path:e.path}}}return{ok:!0}}function pm({content:e,path:t,profile:n}){let r=[],o=null,i=!1,s=!1,a=!1,c=!1,l=!0;for(let d=0;d<e.length;d+=1){let p=e[d]??"",m=e[d+1]??"";if(n==="mdx"&&l&&e.startsWith("```",d)){c=!c;let g=e.indexOf(`
8
8
  `,d);if(g===-1){l=!0;break}d=g,l=!0;continue}if(c){l=p===`
9
9
  `||p==="\r";continue}if(s){p==="*"&&m==="/"&&(s=!1,d+=1),l=p===`
10
10
  `||p==="\r";continue}if(a){p===`
11
11
  `||p==="\r"?(a=!1,l=!0):l=!1;continue}if(o){if(i)i=!1;else if(p==="\\")i=!0;else if(p===o)o=null;else if(n==="css"&&(p===`
12
- `||p==="\r"))return Yn(t,`Unterminated string literal in ${t}.`);l=p===`
13
- `||p==="\r";continue}if(p==="/"&&m==="*"){s=!0,d+=1,l=!1;continue}if(n==="mdx"&&p==="/"&&m==="/"){a=!0,d+=1,l=!1;continue}if(p==="'"||p==='"'||n==="mdx"&&p==="`"){o=p,l=!1;continue}if(p==="{"||p==="("||p==="["){r.push({char:p,offset:d}),l=!1;continue}if(p==="}"||p===")"||p==="]"){let g=p==="}"?"{":p===")"?"(":"[",b=r.pop();if(!b||b.char!==g)return Yn(t,`Unexpected closing token "${p}" in ${t}.`);l=!1;continue}l=p===`
14
- `||p==="\r"}if(s)return Yn(t,`Unterminated block comment in ${t}.`);if(o)return Yn(t,`Unterminated string literal in ${t}.`);if(c)return Yn(t,`Unterminated MDX code fence in ${t}.`);let u=r.at(-1);return u?Yn(t,`Unclosed token "${u.char}" in ${t}.`):{ok:!0}}function Yn(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function Jr(e){let t="idle",n=e.fileSystem??iC(),r=Qf(),o=rm({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?zp(e.historyStore):sC()),u=Zf(n,{externalAdapters:e.externalAdapters}),d=new Map,p=new Set,m=0,g=e.historyStore?.recoveryRequired??!1,b=pc(),C=O();function I(f){return(vi.isAbsolute(f)?vi.relative(e.projectRoot,f):f).replace(/\\/g,"/").replace(/^\.\//,"")}function w(f,h){let y=vi.posix.dirname(f),E=h.replace(/\.(?:tsx?|jsx?)$/i,""),R=vi.posix.relative(y,E);return R.startsWith(".")?R:`./${R}`}function A(f,h){return f.startLine===h.startLine&&f.startColumn===h.startColumn&&f.endLine===h.endLine&&f.endColumn===h.endColumn}async function O(){let f=e.historyStore;if(f)try{let h=await f.readTransactionJournal();if(!h)return;let y=await f.readIndex(),E=await Promise.all(h.files.map(async P=>await n.exists(P.path)?fe(await n.readFile(P.path)):null));if(tm({journal:h,index:y,observedFileDigests:E})!=="ambiguous"){await f.clearTransactionJournal(h.transactionId);let P=await f.readStatus();P.recoveryRequired||(await f.cleanupTmp(),P=await f.readStatus()),g=P.recoveryRequired;return}await f.markRecoveryRequired(`Ambiguous transaction journal ${h.transactionId} at phase ${h.phase}`),g=!0}catch(h){g=!0,await f.markRecoveryRequired(`Transaction journal recovery failed: ${Be(h)}`).catch(()=>{})}}function ie(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let f of o.entries){let h=cm(f.context,f.entryFile);i.set(f.key,h),oe(h,h.dependencyFiles)}function oe(f,h){let y=new Set(h);N(f),f.dependencyFiles=y;for(let E of f.dependencyFiles){let R=s.get(E);R||(R=new Set,s.set(E,R)),R.add(f.key)}}function N(f){for(let h of f.dependencyFiles){let y=s.get(h);y&&(y.delete(f.key),y.size===0&&s.delete(h))}f.dependencyFiles.clear()}function W(f){let h=new Set;for(let y of f)for(let E of s.get(y)??[])h.add(E);return h}function M(f){for(let h of f)if(!s.has(h))return!1;return!0}async function j(f,h,y,E,R){let P=new Map,F=tf(R.values()),L=new Map,_=typeof n.exists=="function"?$=>n.exists($):async()=>!1;for(let[$,J]of f.elements){let de=h.nodes.get($);if(!de)continue;let te=y.get(J.sourceFile)??E.get(J.sourceFile),ye=new Map,Se=new Map,Ee=new Map,xe=[];for(let me of J.textSegments){if(!te){ye.set(me.index,null);continue}let qn=await nf({file:J.sourceFile,source:te,segment:me,readFile:Ke=>n.readFile(Ke),exists:_,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Ke,adapterId:tn,capabilities:Gi})=>({sourceType:Ke,adapterId:tn,capabilities:Gi})),functionCallContracts:e.functionCallContracts,fileCache:F}),Le=await ka({file:J.sourceFile,source:te,target:{kind:"text-segment",segment:me},readFile:Ke=>n.readFile(Ke),exists:_,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Ke,adapterId:tn,capabilities:Gi})=>({sourceType:Ke,adapterId:tn,capabilities:Gi})),functionCallContracts:e.functionCallContracts,fileCache:F}),Ye=yC(qn);ye.set(me.index,Ye),Se.set(me.index,qn),Ee.set(me.index,Le),xe.push({editable:me.editable,source:Ye})}let T=new Map,V=new Map;if(te)for(let me of J.attributes??[]){let qn=await Wn({file:J.sourceFile,source:te,sourceRange:me.sourceRange,expression:me.source?.expression??me.value,sourceInfo:me.source,readFile:Ye=>n.readFile(Ye),exists:_,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Ye,adapterId:Ke,capabilities:tn})=>({sourceType:Ye,adapterId:Ke,capabilities:tn})),functionCallContracts:e.functionCallContracts,fileCache:F}),Le=await qf({element:J,file:J.sourceFile,source:te,propertyName:me.name,readFile:Ye=>n.readFile(Ye),exists:_,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Ye,adapterId:Ke,capabilities:tn})=>({sourceType:Ye,adapterId:Ke,capabilities:tn})),functionCallContracts:e.functionCallContracts,fileCache:F});V.set(me.name,Le),T.set(me.name,qn)}let U=Nu(xC(de.writeTarget),xe),se=Fu({key:$,element:J,graph:f,provenances:Ee}),rt=Lu(J),ot=Bu(J),Rn=ju(J),ro=te?await Af({element:J,graph:f,file:J.sourceFile,source:te,readFile:me=>n.readFile(me),exists:_,fileCache:L}):void 0,Ae=f.regions.find(me=>me.kind==="conditional-region"&&me.childKeys.includes($)),oo,Hi=Ae?.sourceCandidates?.[0];if(te&&Ae&&Hi?.kind==="conditional-branch"){let me=await ka({file:J.sourceFile,source:te,target:{kind:"conditional-branch",candidate:Hi},readFile:Le=>n.readFile(Le),exists:_,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Le,adapterId:Ye,capabilities:Ke})=>({sourceType:Le,adapterId:Ye,capabilities:Ke})),functionCallContracts:e.functionCallContracts,fileCache:F});oo={currentBranch:Ae.childKeys.indexOf($)<=0?"then":"else",availableBranches:Ae.childKeys.length>1?["then","else"]:["then"],conditionExpression:Hi.conditionExpression,provenance:{finalSource:me.finalSource?{kind:me.finalSource.kind,file:me.finalSource.file,displayPath:me.finalSource.displayPath}:null,chain:me.chain.map(Le=>({kind:Le.kind,file:Le.file,displayName:Le.displayName,canEditHere:Le.canEditHere})),confidence:me.confidence,editMode:me.editMode,diagnostics:me.diagnostics.map(Le=>({code:Le.code,message:Le.message}))}}}P.set($,{textSources:ye,textTargets:Se,elementPropertyTargets:T,propertyProvenances:V,isRepeat:FC($,f),provenances:Ee,writeTarget:U,componentSemantic:se,contentModel:rt,mediaModel:ot,styleSource:Rn,conditional:oo,dynamicData:ro})}return P}function Q(f){return typeof n.getVersion=="function"?n.getVersion(f):0}function re(f,h){let y=o.initialVersions.get(f.key)??0;for(let E of h.values())y=Math.max(y,E);return Math.max(y,f.graph?.version??0)}function be(f){return i.get(f)?.graph?.version??o.initialVersions.get(f)??0}function G(f){try{return be(o.resolveSelector(f.composition).key)}catch{return 0}}async function ee(f,h,y={}){let E=i.get(f);if(!E)return null;let R=y.sourceCache??mc(d,[]),P=await Ie(E.entryFile),{graph:F,allSources:L,diagnostics:_,parsedModules:$,entryModule:J}=await wl(E.entryFile,h,Ae=>n.readFile(Ae),typeof n.exists=="function"?Ae=>n.exists(Ae):async()=>!1,{additionalEntries:P,version:E.graph?.version??1});if(_.length>0)throw new Ur(_);let de=new Map;for(let Ae of L.keys())de.set(Ae,Q(Ae));let te=Math.max(re(E,de),y.minimumVersion??0);y.changed&&te<=(E.graph?.version??0)&&(te=(E.graph?.version??0)+1),F.version=te;for(let[Ae,oo]of L)gc(R,Ae,oo,im);let ye=await Ft(E.composition,E.entryFile,L,R);F.routeId=E.routeId,F.composition=E.composition;let Se=Nl(F),Ee=Al(Se,F),xe=await j(F,Se,L,R,$),T=tg(F,Ee,xe),V=eg(xe),U=OC(Iu(F,Se,Ee,{canUpdateTextByKey:T,dynamicDataSummaryByKey:V}),F,xe),se=gu({route:E.routeId,composition:E.composition,entryFile:E.entryFile,version:te,source:h,ast:J?.ast}),rt=hu(se);se.ok&&IC(U,F,se.projection);let ot={...U,composition:E.composition,...ye?{styleContext:ye}:{},pageComposition:rt},Rn=new Set([E.entryFile,...L.keys()]);if(ye){Rn.add(ye.entryCss.path);for(let Ae of ye.stylesheets)Rn.add(Ae.path)}let ro={...E,dependencyFiles:Rn,graph:F,topology:Se,capabilities:Ee,document:ot,pageComposition:rt,pageCompositionProjection:se.projection,pagePlacementByKey:se.ok?se.projection.placementByKey:null,pagePlacementUnitByKey:se.ok?se.projection.placementUnitByKey:null,pageUnitByKey:se.ok?se.projection.unitByKey:null,pagePlacementsByUnitKey:se.ok?se.projection.placementsByUnitKey:null,documentIndex:uC(ot),detailProjections:xe,fileVersions:de,styleContext:ye};if(y.publish===!1)return ro;Gn(d,R);for(let Ae of R.keys())p.delete(Ae);return oe(E,Rn),Object.assign(E,ro),E}async function Ie(f){let h=[];for(let y of wC(f))typeof n.exists=="function"&&await n.exists(y)&&h.push({file:y,source:await n.readFile(y)});return h}async function Ft(f,h,y,E){let R=[];for(let[$,J]of y){if(xc($)){R.push($);continue}for(let de of PC(J)){let te=pm($,de);te&&R.push(te)}}if(!R.length){for(let $ of NC(h))if(await Yc($)){R.push($);break}}let P=new Map,F=xm(R).slice(0,om);for(;F.length>0&&P.size<om;){let $=F.shift();if(P.has($)||!xc($))continue;let J=await Ot($,E);if(J!==null){P.set($,{path:$,content:J});for(let de of AC(J)){let te=pm($,de);te&&!P.has(te)&&!F.includes(te)&&F.push(te)}}}let L=[...P.values()].map($=>({...$,hash:fe($.content)})),_=L[0];return _?{composition:f,revision:fe(JSON.stringify(L.map(({path:$,hash:J})=>({path:$,hash:J})))),entryCss:_,stylesheets:L.slice(1)}:null}async function Ot(f,h){let y=h.get(f);if(y!==void 0)return y;if(!await Yc(f))return null;let E=await n.readFile(f);return gc(h,f,E,im),E}async function Yc(f){return typeof n.exists=="function"?n.exists(f):!1}function eg(f){let h=new Map;for(let[y,E]of f)E.dynamicData?.bindings.length&&h.set(y,Vf(E.dynamicData.bindings));return h}function tg(f,h,y){let E=new Map;for(let[R,P]of f.elements){if(!h.get(R)?.canUpdateText){E.set(R,!1);continue}let L=y.get(R),_=P.textSegments.some($=>{if(!$.editable)return!1;let J=L?.provenances.get($.index)??null;return!J||ng(J)});E.set(R,_)}return E}function ng(f){return f.editMode==="direct"||f.editMode==="proxy"||f.editMode==="upstream"}async function eo(f,h={}){let y=[...new Set(f)],E=h.affectedCompositionKeys!==void 0,R=E?new Set(h.affectedCompositionKeys):W(y);if(!E&&(R.size===0||!M(y)))for(let _ of i.values())Zc(_,y)&&R.add(_.key);let P=!E&&R.size===0&&y.some(fm),F=h.publish===!1?mc(d,y):void 0,L={rebuiltRoutes:[],failedRoutes:[],...h.publish===!1?{candidateRouteStates:[],candidateSourceCache:F}:{}};for(let _ of i.values())if(!(h.excludedCompositionKeys?.has(_.key)||!(R.has(_.key)||P)))try{let J=!!_.graph,de=await n.readFile(_.entryFile),te=await ee(_.key,de,{...h,...F?{sourceCache:F}:{}});te?.graph&&(L.rebuiltRoutes.push({documentChanged:J,composition:_.composition,routeId:_.routeId,version:te.graph.version}),L.candidateRouteStates?.push({composition:_.composition,key:_.key,routeId:_.routeId,state:te}))}catch(J){L.failedRoutes.push({...em(_.routeId,J),composition:_.composition})}return L}function In(f){let h=[...new Set(f)],y=W(h);if(y.size>0&&M(h))return[...y];for(let E of i.values())Zc(E,h)&&y.add(E.key);return[...y]}function rg(f){let h=new Set(In(f));return o.entries.filter(y=>h.has(y.key)).map(y=>y.context)}function og(f){return[...new Set(In(f))].sort((y,E)=>y<E?-1:y>E?1:0).map(y=>o.getByKey(y)?.context).filter(y=>y!==void 0)}function ig(f,h){let y=new Set(In(h)),E=f.provenance?.affectedCompositions??[];if(E.length===0)return y;if([...new Set(E.map(P=>o.resolveContext(P).key))].some(P=>!y.has(P)))throw new Error("History provenance does not match the affected composition index.");return y}function sg(f,h){let y=f.composition??f.provenance?.initiatingComposition;if(y){let P=o.resolveContext(y);return{context:P.context,key:P.key}}let E=[...new Set(In(h))];if(E.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${E.length}).`);let R=o.getByKey(E[0]);if(!R)throw new Error("Legacy history entry references an unknown affected composition.");return{context:R.context,key:R.key}}function Ui(f,h){r.emit({type:"operation-completed",composition:f.composition,result:f});for(let{composition:y,version:E}of h.rebuiltRoutes)r.emit({type:"document-changed",composition:y,version:E});for(let{composition:y,message:E}of h.failedRoutes)r.emit({type:"graph-error",composition:y,message:E})}function Zc(f,h){return h.some(y=>f.dependencyFiles.has(y)||f.entryFile===y||f.graph?.fileIndex.has(y))}function Qc(f){for(let h of f)a.add(h);c||ie()||(c=(async()=>{t="building";let h=!1;try{for(;a.size>0;){if(ie())return;await ag();let y=[...a];a.clear();let E=await qc(y);if(E.length===0)continue;let R=In(E);for(let L of R){let _=i.get(L)?.composition;_&&r.emit({type:"graph-invalidated",composition:_})}let{rebuiltRoutes:P,failedRoutes:F}=await eo(E,{changed:!0});for(let{documentChanged:L,composition:_,version:$}of P)r.emit({type:"graph-ready",composition:_,version:$}),L&&r.emit({type:"document-changed",composition:_,version:$});for(let{composition:L,message:_}of F)h=!0,r.emit({type:"graph-error",composition:L,message:_})}}finally{c=null,t!=="disposed"&&(t=!h&&[...i.values()].some(y=>y.graph)?"ready":"idle"),a.size>0&&Qc([])}})())}async function ag(){for(;m>0;)await new Promise(f=>setTimeout(f,0))}async function qc(f){let h=[];for(let y of new Set(f)){let E=d.get(y);if(E===void 0){if(p.has(y)&&!await n.exists(y))continue;p.delete(y),h.push(y);continue}try{await n.readFile(y)!==E&&(p.delete(y),h.push(y))}catch(R){if(!vC(R))try{if(await n.exists(y))continue}catch{continue}p.add(y),h.push(y)}}return h}function el(f){Qp(d,f);for(let h of f)h.exists===!1?p.add(h.file):p.delete(h.file)}function tl(f){p.clear();for(let h of f)p.add(h)}async function nl(f){let h=await qc(f);if(h.length===0)return;let y=In(h);for(let P of y){let F=i.get(P)?.composition;F&&r.emit({type:"graph-invalidated",composition:F})}let{rebuiltRoutes:E,failedRoutes:R}=await eo(h,{changed:!0});for(let{documentChanged:P,composition:F,version:L}of E)r.emit({type:"graph-ready",composition:F,version:L}),P&&r.emit({type:"document-changed",composition:F,version:L});for(let{composition:P,message:F}of R)r.emit({type:"graph-error",composition:P,message:F})}async function cg(f,h){let y=Qn(f,h);if(!y?.graph)return;let E=Ve(f)??f,R=y.graph.elements.get(E);R&&await nl([R.sourceFile])}async function rl(f){let h=new Set;if(f.target.kind==="node"){let y=Qn(f.target.key,f.composition),E=Ve(f.target.key)??f.target.key,R=y?.graph?.elements.get(E);R&&h.add(R.sourceFile)}else if(f.target.kind==="route"){let y=i.get(o.resolveSelector(f.target.composition).key);y&&h.add(y.entryFile)}else if(f.target.kind==="page-unit"){let y=i.get(o.resolveSelector(f.target.composition).key);y&&h.add(y.entryFile)}else if(f.target.kind==="source-file")h.add(f.target.path);else if(f.target.kind==="source-batch")for(let y of f.target.paths)h.add(y);await nl(h)}async function lg(f){if(f.params.kind!=="source-edit")return Ki(f,"invalid-params","source-edit requires source-edit params");for(let h of f.params.edits){let y=EC(h);if(!y.ok)return Ki(f,y.errorCode,y.message,y.details)}m+=1;try{let h=await mg(f.params.edits);if(!h.ok)return Ki(f,h.errorCode,h.message,h.details);await rl(f);let y={operationId:f.id,kind:"source-edit",target:f.target,documentVersion:f.documentVersion,conflictPolicy:f.params.conflictPolicy,edits:f.params.edits.map(E=>E.operation==="delete"?{operation:"delete",file:E.path,baseContentHash:E.baseContentHash??null}:{operation:"upsert",file:E.path,baseContentHash:E.baseContentHash??null,content:E.content})};return await Cn({request:f,filePlan:y})}catch(h){return{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:G(f),error:{code:D.INTERNAL_ERROR,message:Be(h)}}}finally{m-=1}}async function ug(f){if(f.target.kind!=="project"||f.params.kind!=="insert-page-resource")return Z(f,D.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");m+=1;try{let h=await sc({files:[...f.params.artifact.components.flatMap(E=>E.materialization.files.map(R=>({path:R.pathTemplate,content:R.content}))),...f.params.artifact.pages.flatMap(E=>E.materialization.files.map(R=>({path:R.pathTemplate,content:R.content})))],exists:E=>n.exists(E),readFile:E=>n.readFile(E)});if(!h.ok)return Z(f,D.MATERIALIZATION_REJECTED,h.message);let y=await oc({artifact:f.params.artifact,exists:E=>n.exists(E)});return y.ok?await Cn({request:f,filePlan:{operationId:f.id,kind:"source-edit",target:f.target,documentVersion:f.documentVersion,conflictPolicy:"overwrite",edits:y.files},output:{kind:"insert-page-resource",package_instance_id:y.packageInstanceId,pages:y.pages},historyPolicy:"none"}):Z(f,y.code==="MATERIALIZATION_CONFLICT"?D.MATERIALIZATION_CONFLICT:D.MATERIALIZATION_REJECTED,y.message,y.path?{path:y.path}:void 0)}catch(h){return Z(f,D.INTERNAL_ERROR,Be(h))}finally{m-=1}}async function dg(f){if(f.target.kind!=="project"||f.params.kind!=="delete-page-source")return Z(f,D.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return Z(f,D.PLAN_FAILED,"Complete project file listing is required for page deletion.");m+=1;try{let h=gm(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(h.truncated)return Z(f,D.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:h.truncated.reasons});let y=h.files.filter(({path:F})=>/\.(?:tsx?|jsx?)$/.test(F)),E=Object.fromEntries(await Promise.all(y.map(async({path:F})=>[F,await n.readFile(F)]))),R=$p({expectedUrlPath:f.params.expectedUrlPath,files:E});if(!R.ok)return Z(f,R.code==="HOME_PAGE_LOCKED"?D.HOME_PAGE_LOCKED:R.code==="ROUTE_NOT_FOUND"?D.ROUTE_NOT_FOUND:D.PLAN_FAILED,R.message);let P=await Promise.all(R.edits.map(async F=>({...F,baseContentHash:fe(await n.readFile(F.file))})));return Cn({request:f,filePlan:{operationId:f.id,kind:"source-edit",target:f.target,documentVersion:f.documentVersion,conflictPolicy:"compare-and-swap",edits:P},output:{kind:"delete-page-source",deleted_files:R.deletedFiles,updated_files:R.updatedFiles,preserved_shared_files:R.preservedSharedFiles,warnings:R.warnings},historyPolicy:"none"})}catch(h){return Z(f,D.INTERNAL_ERROR,Be(h))}finally{m-=1}}async function fg(f,h){if(f.kind!=="insert-child"&&f.kind!=="replace-node")return Z(f,D.UNSUPPORTED_OPERATION,"Only page-unit insert-child and replace-node materialization are supported by this transaction.");if(f.params.kind!=="insert-child"&&f.params.kind!=="replace-node"||f.kind!==f.params.kind)return Z(f,D.INVALID_PARAMS,"Page-unit materialization operation kind must match its params.");if(f.params.kind==="insert-child"){if(!("kind"in f.params.position)||f.params.position.kind!=="page-composition")return Z(f,D.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(f.params.position.documentVersion!==f.documentVersion)return Z(f,D.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.")}let y=h.document,E=h.pageCompositionProjection;if(!y||y.pageComposition?.status!=="supported"||!E||E.status!=="supported")return Z(f,D.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(f.documentVersion!==y.version||E.documentVersion!==y.version)return Z(f,D.VERSION_STALE,`Document version ${f.documentVersion} is stale (current: ${y.version}).`);let R=f.params.node.kind==="component-call"?f.params.node.materialization:void 0;if(!R)return Z(f,D.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let P=f.params.kind==="insert-child"?f.params.position:null,F=await sc({files:R.files.map(_=>({path:_.pathTemplate,content:_.content})),exists:_=>n.exists(_),readFile:_=>n.readFile(_)});if(!F.ok)return Z(f,D.MATERIALIZATION_REJECTED,F.message);let L=await Ep({manifest:R,generatedRoot:"components/site/generated",controlledFiles:R.files.map(_=>({pathTemplate:_.pathTemplate})),exists:_=>n.exists(_),commit:async _=>{let $=await n.readFile(h.entryFile),J=h.document,de=h.pageCompositionProjection;if(!J||J.pageComposition?.status!=="supported"||J.version!==f.documentVersion||!de||de.status!=="supported"||de.documentVersion!==J.version)return{ok:!0,data:Z(f,D.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let te=_.entry.path,ye=Eg(_.instanceName),Se,Ee=[];if(f.params.kind==="insert-child"){if(!P||!("kind"in P)||P.kind!=="page-composition")return{ok:!0,data:Z(f,D.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.")};let U=Ps({routeId:h.routeId,entryFile:h.entryFile,currentDocumentVersion:J.version,expectedDocumentVersion:f.documentVersion,source:$,projection:de,placementKey:P.placementKey,component:{source:te,exportName:_.entry.export.kind==="default"?"default":_.entry.export.name,localName:ye}});if(!U.ok)return{ok:!0,data:Z(f,Wi(U.error.code),U.error.message,{diagnostics:U.error.diagnostics})};let se=U.plan.returnStep?du({source:$,jsx:U.plan.returnStep.node.jsx,placement:U.plan.returnStep.placement,...U.plan.returnStep.replaceOriginal?{replaceOriginal:!0}:{}}):U.plan.insertStep?.parentLocator?Mn({source:$,locator:U.plan.insertStep.parentLocator,node:U.plan.insertStep.node,placement:U.plan.insertStep.placement,...U.plan.insertStep.anchorLocator?{anchorLocator:U.plan.insertStep.anchorLocator}:{}}):{ok:!1,source:$,diagnostic:{code:"unsupported-syntax",message:"Route composition rewrite has no insertion step."}};if(!se.ok)return{ok:!0,data:Z(f,D.AST_PARSE_ERROR,se.diagnostic.message)};Se=se.source}else{let U=As({routeId:h.routeId,composition:h.composition,entryFile:h.entryFile,currentDocumentVersion:J.version,expectedDocumentVersion:f.documentVersion,source:$,projection:de,placementUnitKey:f.target.placementUnitKey,operation:"remove-node"});if(!U.ok)return{ok:!0,data:Z(f,Wi(U.error.code),U.error.message,{diagnostics:U.error.diagnostics})};if(U.plan.rewriteStep.kind!=="remove-node")return{ok:!0,data:Z(f,D.PLAN_FAILED,"Page-unit replacement did not resolve a replaceable source node.")};let se=wo({source:$,locator:U.plan.rewriteStep.locator,node:{jsx:`<${ye} />`}});if(!se.ok)return{ok:!0,data:Z(f,D.AST_PARSE_ERROR,se.diagnostic.message)};let rt=await ol({routeState:h,placementUnitKey:f.target.placementUnitKey,source:$,mutatedSource:se.source});Se=rt.source,Ee=await Promise.all(rt.files.map(async ot=>({operation:"delete",file:ot,baseContentHash:fe(await n.readFile(ot))})))}let xe=jn({source:Se,moduleSpecifier:w(h.entryFile,te),imports:_.entry.export.kind==="default"?[{kind:"default",local:ye}]:[{kind:"named",imported:_.entry.export.name,local:ye}]});if(!xe.ok)return{ok:!0,data:Z(f,D.AST_PARSE_ERROR,xe.diagnostic.message)};let T=_.files.map(U=>({operation:"create-only",file:U.path,content:U.content})),V=[{operation:"upsert",file:h.entryFile,content:xe.source,baseContentHash:fe($)},...T,...Ee];m+=1;try{let U=await Cn({request:f,filePlan:{operationId:f.id,kind:"source-edit",target:{kind:"source-file",path:h.entryFile},documentVersion:f.documentVersion,conflictPolicy:"compare-and-swap",edits:V}});return!U.ok&&U.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:U.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:U}}finally{m-=1}}});return L.ok?L.data:Z(f,D.VERSION_STALE,L.error.message,{materializationCode:L.error.code})}async function pg(f,h){if(f.kind!=="move-node"&&f.kind!=="remove-node")return Z(f,D.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let y=h.document,E=h.pageCompositionProjection;if(!y||y.pageComposition?.status!=="supported"||!E||E.status!=="supported")return Z(f,D.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(f.documentVersion!==y.version||E.documentVersion!==y.version)return Z(f,D.VERSION_STALE,`Document version ${f.documentVersion} is stale (current: ${y.version}).`);let R=await n.readFile(h.entryFile),P=As({routeId:h.routeId,composition:h.composition,entryFile:h.entryFile,currentDocumentVersion:y.version,expectedDocumentVersion:f.documentVersion,source:R,projection:E,placementUnitKey:f.target.placementUnitKey,operation:f.kind,targetPlacement:f.kind==="move-node"&&f.params.kind==="move-node"&&"kind"in f.params.target&&f.params.target.kind==="page-composition"?f.params.target:void 0});if(!P.ok)return Z(f,Wi(P.error.code),P.error.message,{diagnostics:P.error.diagnostics});let F=P.plan.rewriteStep.kind==="move-node"?Ln({source:R,locator:P.plan.rewriteStep.locator,targetParentLocator:P.plan.rewriteStep.targetParentLocator,placement:P.plan.rewriteStep.placement,...P.plan.rewriteStep.anchorLocator?{anchorLocator:P.plan.rewriteStep.anchorLocator}:{}}):Fn({source:R,locator:P.plan.rewriteStep.locator});if(!F.ok)return Z(f,D.AST_PARSE_ERROR,F.diagnostic.message);let L=F.source,_=[];if(f.kind==="remove-node"){let J=await ol({routeState:h,placementUnitKey:f.target.placementUnitKey,source:R,mutatedSource:L});L=J.source,_=await Promise.all(J.files.map(async de=>({operation:"delete",file:de,baseContentHash:fe(await n.readFile(de))})))}let $=[{operation:"upsert",file:h.entryFile,content:L,baseContentHash:fe(R)},..._];m+=1;try{return await Cn({request:f,filePlan:{operationId:f.id,kind:"source-edit",target:{kind:"source-file",path:h.entryFile},documentVersion:f.documentVersion,conflictPolicy:"compare-and-swap",edits:$}})}finally{m-=1}}async function ol(f){let h={source:f.mutatedSource,files:[]},y=f.routeState.graph,E=f.routeState.pageCompositionProjection;if(!y||!E||E.status!=="supported"||!n.listFiles)return h;let P=E.placementUnitByKey.get(f.placementUnitKey)?.sourceRange;if(!P)return h;let F=[...y.elements.values()].find(T=>T.sourceFile===f.routeState.entryFile&&T.importedFrom&&A(T.sourceRange,P));if(!F?.importedFrom||!F.exportName)return h;let L=I(F.importedFrom),_="components/site/generated/";if(!L.startsWith(_))return h;let $=L.slice(_.length).split("/")[0];if(!$||!/-[0-9a-f]{8}$/i.test($))return h;let J=`${_}${$}`;if([...y.elements.values()].filter(T=>T.sourceFile===f.routeState.entryFile&&I(T.importedFrom??"")===L).length!==1)return h;let te=await n.listFiles({maxFiles:5e3,maxDepth:32}),ye=Array.isArray(te)?te:te.files;if(!Array.isArray(te)&&te.truncated)return h;let Se=ye.map(({path:T})=>T).filter(T=>T===J||T.startsWith(`${J}/`));if(Se.length===0||!Se.includes(L))return h;for(let{path:T}of ye)if(!(T===f.routeState.entryFile||T===J||T.startsWith(`${J}/`)))try{if((await n.readFile(T)).includes($))return h}catch{return h}let Ee=w(f.routeState.entryFile,L),xe=$n({source:f.mutatedSource,moduleSpecifier:Ee,imports:F.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:F.exportName}]});return xe.ok?{source:xe.source,files:Se.sort((T,V)=>T.localeCompare(V))}:h}async function mg(f){if(n.getFileInfo){for(let R of f)if(await n.exists(R.path)&&await n.getFileInfo(R.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${R.path}`,details:{path:R.path}}}let h=gg(f);if(h.length===0)return{ok:!0};let y=bC(n,f),E=Jr({projectRoot:e.projectRoot,fileSystem:y,compositions:[...i.values()].map(R=>({context:R.composition,entryFile:R.entryFile})),externalAdapters:e.externalAdapters,externalSourceResolvers:e.externalSourceResolvers,functionCallContracts:e.functionCallContracts,dev:e.dev});try{for(let R of h){let P=i.get(R)?.composition;if(!P)continue;let F={routeId:P.routeId,...P.effectiveTemplateId!==void 0?{templateId:P.effectiveTemplateId}:{}};await E.initializeComposition(F),E.getDocument(F)}}catch(R){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${Be(R)}`,details:{compositionKeys:h}}}finally{E.dispose()}return{ok:!0}}function gg(f){return f.map(y=>y.path).some(fm)?[...i.keys()]:[]}function Ki(f,h,y,E){let R=Kr(h);return{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:G(f),error:{code:R,message:y,...E?{details:E}:{}}}}async function Ji(f){let h=[];for(let y of new Set(f))h.push(await hg(y));return h}async function hg(f){if(!(typeof n.exists=="function"?await n.exists(f):!0))return{file:f,content:"",version:Math.max(0,Q(f)),exists:!1};let y=await n.readFile(f);return{file:f,content:y,version:Math.max(1,Q(f)),exists:!0,sha256:fe(y)}}async function il(f,h,y,E){if(!e.historyStore)return null;let R=new Map(h.map(L=>[L.file,L])),P=new Map(y.map(L=>[L.file,L])),F=[...new Set([...R.keys(),...P.keys()])].sort().map(L=>{let _=R.get(L),$=P.get(L);return{path:L,preDigest:_?.exists===!1||!_?null:fe(_.content),postDigest:$?.exists===!1||!$?null:fe($.content)}});return{schemaVersion:2,transactionId:`${f}:${E.expectedIndexDigest}`,operationId:f,phase:"prepared",historyTransition:E,files:F}}async function sl(f){return!f||!e.historyStore||await e.historyStore.writeTransactionJournal(f),f}async function kn(f){f&&e.historyStore&&await e.historyStore.clearTransactionJournal(f.transactionId)}async function Xi(f,h){let y=[];try{for(let E of f)await al(E),typeof n.bumpVersion=="function"&&n.bumpVersion(E.file),y.push(E.file)}catch(E){let R=await yg(h.filter(P=>y.includes(P.file)));return R.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${Be(E)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${R.failedFiles.join(", ")}: ${Be(E)}`,rolledBack:!1}}return{ok:!0,snapshots:f.map(xg)}}async function al(f){if(f.exists===!1){await n.deleteFile(f.file);return}await n.writeFile(f.file,f.content)}async function yg(f){let h=[];for(let y of f)try{await al(y),typeof n.bumpVersion=="function"&&n.bumpVersion(y.file)}catch{h.push(y.file)}return h.length===0?{ok:!0}:{ok:!1,failedFiles:h}}function xg(f){let h=f.exists!==!1;return{file:f.file,content:h?f.content:"",version:f.version,exists:h,...h?{sha256:fe(f.content)}:{}}}async function Cn(f){return b.runExclusive(()=>bg(f))}async function bg(f){let h=f.filePlan.edits.map(T=>T.file),y=o.resolveSelector(f.request.composition),E=y.context,R=f.historyPolicy==="none"?void 0:{initiatingComposition:E,affectedCompositions:og(h)},P=await Ji(h),F=new Map(P.filter(T=>T.exists!==!1).map(T=>[T.file,T.content])),L=ll(),_=new Map(d),$=new Set(p),J=new Set([...i.values()].filter(T=>f.filePlan.edits.some(V=>V.operation==="delete"&&V.file===T.entryFile)).map(T=>T.key)),de=f.filePlan.edits.map(T=>T.operation==="delete"?{file:T.file,content:"",version:0,exists:!1}:{file:T.file,content:T.content,version:0,exists:!0,sha256:fe(T.content)}),te={operationId:f.filePlan.operationId,intents:f.filePlan.edits.map(T=>T.operation==="delete"?{kind:"delete",path:T.file}:{kind:T.operation==="create-only"?"create-only":"upsert",path:T.file,content:T.content})},ye=null,Se=!1,Ee=await bi({overlay:F,exists:T=>n.exists(T),plan:te,buildCandidate:async({plan:T})=>({plan:T}),prepareHistory:async()=>{let T=f.historyPolicy==="none"?null:await l.prepareAppend({composition:o.resolveSelector(f.request.composition).context,operationId:f.request.id,kind:f.request.kind,target:f.request.target,preSnapshots:P,postSnapshots:de,...f.selectionRef?{selectionRef:f.selectionRef}:{},...f.output?{output:f.output}:{},...R?{provenance:R}:{}}),V=T?.historyTransition?T.historyTransition:e.historyStore?oC(await e.historyStore.readIndex()):null;if(e.historyStore&&!V)throw new Error("Durable history did not provide an exact index transition.");return ye=await il(f.request.id,P,de,V),ye=await sl(ye),{history:T,historyTransition:V}},reverify:async()=>{},writeCandidate:async()=>{let T=await u.executeFilePlan(f.filePlan);if(!T.ok)throw new ki(T);return{postSnapshots:await Ji(T.affectedFiles),affectedFiles:T.affectedFiles,internalResultVersion:T.resultVersion}},validateCandidate:async({candidate:T,receipt:V})=>{let U=await eo(V.affectedFiles,{changed:!0,minimumVersion:V.internalResultVersion,publish:!1,excludedCompositionKeys:J});if(U.failedRoutes.length>0)throw new Sn(U.failedRoutes);let se=dl(L,U.candidateRouteStates??[]),rt=ul(se,y.key);return{...T,rebuild:U,routeSnapshots:se,resultVersion:rt,...lm(f.selectionRef,se.map(ot=>ot.state.document))?{selectionRef:lm(f.selectionRef,se.map(ot=>ot.state.document))}:{}}},publishCandidate:async({candidate:T,history:V,receipt:U})=>{V?.history&&(await l.publishPrepared(V.history),Se=!0);let se=T.resultVersion??U.internalResultVersion;return{composition:E,requestId:f.request.id,kind:f.request.kind,target:f.request.target,ok:!0,resultVersion:se,affectedFiles:U.affectedFiles,...f.output?{output:f.output}:{},...T.selectionRef?{selectionRef:T.selectionRef}:{}}},swapCandidate:({candidate:T,receipt:V})=>{T.routeSnapshots&&to(T.routeSnapshots),T.rebuild?.candidateSourceCache&&Gn(d,T.rebuild.candidateSourceCache),el(V.postSnapshots)},finalizeCandidate:async()=>{await kn(ye);for(let T of J)i.delete(T)},emitCommitted:({candidate:T,published:V})=>{Ui(V,T.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:T,receipt:V})=>{if(Se)throw new Error("history was published before transaction finalization failed");if(V){let U=await Xi(P,V.postSnapshots);if(!U.ok)throw new Error(U.reason)}to(L),Gn(d,_),tl($),T?.history&&await l.discardPrepared?.(T.history),await kn(ye)}});if(Ee.ok)return Ee.published;if(Ee.stage==="precheck"||Ee.stage==="build")try{await kn(ye)}catch(T){let V=await no(Be(T));return Z(f.request,V,"Unable to clear an uncommitted transaction journal.")}if(Ee.recoveryRequired){let T=await no(Ee.reason);return Z(f.request,T===D.RECOVERY_PERSIST_FAILED?T:D.ROLLBACK_FAILED,Ee.reason)}let xe=Ee.error;return xe instanceof ki?{...Z(f.request,Kr(xe.result.errorCode),xe.result.reason),...xe.result.affectedFiles?{affectedFiles:xe.result.affectedFiles}:{}}:xe instanceof Sn?Z(f.request,D.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${hc(xe.failedRoutes)}`,{failedRoutes:xe.failedRoutes}):Z(f.request,pl(Ee.stage),Be(xe))}async function cl(f){return b.runExclusive(async()=>{let h=f==="undo"?await l.prepareUndo():await l.prepareRedo();return h?Sg(f,h):{composition:o.entries[0].context,requestId:f,kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:o.initialVersions.get(o.entries[0].key)??0,error:{code:D.INTERNAL_ERROR,message:f==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function Sg(f,h){let y=h.entry,E=f==="undo"?y.preSnapshots:y.postSnapshots,R=f==="undo"?y.postSnapshots:y.preSnapshots,P=E.map(V=>V.file),{context:F,key:L}=sg(y,P),_=await Ji(P),$=new Map(_.filter(V=>V.exists!==!1).map(V=>[V.file,V.content])),J=be(L),de=ll(),te=new Map(d),ye=new Set(p),Se=null,Ee=!1,xe,T=await bi({overlay:$,plan:{operationId:`${f}:${y.operationId}`,intents:E.map(V=>V.exists===!1?{kind:"delete",path:V.file}:{kind:"upsert",path:V.file,content:V.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(Se=await il(`${f}:${y.operationId}`,_,E,h.historyTransition),Se=await sl(Se),h),reverify:async()=>{},writeCandidate:async()=>{let V=await Xi(E,R);if(!V.ok)throw new Error(V.reason);return{snapshots:V.snapshots}},validateCandidate:async({candidate:V})=>{xe=ig(y,P);let U=await eo(P,{changed:!0,minimumVersion:J+1,publish:!1,affectedCompositionKeys:xe});if(U.failedRoutes.length>0)throw new Sn(U.failedRoutes);let se=dl(de,U.candidateRouteStates??[]),rt=ul(se,L);return{...V,rebuild:U,routeSnapshots:se,resultVersion:rt}},publishCandidate:async({candidate:V,history:U})=>{if(!U)throw new Error("history cursor intent is missing");await l.publishPrepared(U),Ee=!0;let se=V.resultVersion??J+1;return{composition:F,requestId:f,kind:y.kind,target:y.target,ok:!0,resultVersion:se,affectedFiles:P,...y.output?{output:y.output}:{}}},swapCandidate:({candidate:V,receipt:U})=>{V.routeSnapshots&&to(V.routeSnapshots),V.rebuild?.candidateSourceCache&&Gn(d,V.rebuild.candidateSourceCache),el(U.snapshots)},finalizeCandidate:async()=>{await kn(Se)},emitCommitted:({candidate:V,published:U})=>Ui(U,V.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:V,receipt:U})=>{if(Ee)throw new Error("history cursor was published before transaction finalization failed");if(U){let se=await Xi(R,U.snapshots);if(!se.ok)throw new Error(se.reason)}to(de),Gn(d,te),tl(ye),V&&await l.discardPrepared?.(V),await kn(Se)}});if(T.ok)return T.published;if(T.stage==="precheck"||T.stage==="build")try{await kn(Se)}catch(V){let U=await no(Be(V));return{composition:F,requestId:f,kind:y.kind,target:y.target,ok:!1,resultVersion:J,error:{code:U,message:"Unable to clear an uncommitted transaction journal."}}}if(T.recoveryRequired){let V=await no(T.reason);return{composition:F,requestId:f,kind:y.kind,target:y.target,ok:!1,resultVersion:J,affectedFiles:P,error:{code:V===D.RECOVERY_PERSIST_FAILED?V:D.ROLLBACK_FAILED,message:T.reason}}}return{composition:F,requestId:f,kind:y.kind,target:y.target,ok:!1,resultVersion:J,affectedFiles:P,error:{code:T.error instanceof Sn?D.ROUTE_REBUILD_FAILED:pl(T.stage),message:Be(T.error),...T.error instanceof Sn?{details:{failedRoutes:T.error.failedRoutes}}:{}}}}function ll(){return[...i.values()].map(f=>({composition:f.composition,key:f.key,routeId:f.routeId,state:{...f,dependencyFiles:new Set(f.dependencyFiles),fileVersions:new Map(f.fileVersions)}}))}function ul(f,h){return f.find(E=>E.key===h)?.state.graph?.version??o.initialVersions.get(h)??0}function dl(f,h){let y=new Map(f.map(E=>[E.key,E]));for(let E of h)y.set(E.key,E);return[...y.values()]}function to(f){for(let h of i.values())N(h);for(let h of f){let y={...h.state,dependencyFiles:new Set(h.state.dependencyFiles),fileVersions:new Map(h.state.fileVersions)};i.set(h.key,y),oe(y,y.dependencyFiles)}}async function zi(f){let h=i.get(f);if(!h)throw new Error(`Composition not found: ${f}`);if(h.graph)return;let y=await n.readFile(h.entryFile);await ee(f,y)}function Qn(f,h){let y=i.get(o.resolveSelector(h).key)??null;return!y||!fl(y,f)?null:y}function fl(f,h){if(f.documentIndex?.entriesByKey.has(h)||f.graph?.elements.has(h))return!0;let y=Ve(h);return y&&y!==h?f.graph?.elements.has(y)===!0:!1}function Z(f,h,y,E){return{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:G(f),error:{code:h,message:y,...E?{details:E}:{}}}}function pl(f){return f==="validate"?D.ROUTE_REBUILD_FAILED:f==="publish"?D.HISTORY_COMMIT_FAILED:D.WRITE_IO_ERROR}async function no(f){if(g=!0,!l.markRecoveryRequired)return D.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(f),D.RECOVERY_REQUIRED}catch{return D.RECOVERY_PERSIST_FAILED}}function Eg(f){let y=f.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(E=>E.charAt(0).toUpperCase()+E.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return y?`Prefab${y}`:"GeneratedPrefab"}function Wi(f){return f==="VERSION_STALE"?D.VERSION_STALE:f==="CROSS_PAGE_MOVE_UNSUPPORTED"?D.CROSS_PAGE_MOVE_UNSUPPORTED:D.UNSUPPORTED_OPERATION}async function ml(f){if(f.target.kind==="route"){let y=i.get(o.resolveSelector(f.target.composition).key)??null;return y?(y.graph||await zi(y.key),y):Z(f,D.ROUTE_NOT_FOUND,"Composition not found for route target.")}if(f.target.kind==="page-unit"){let y=i.get(o.resolveSelector(f.target.composition).key)??null;return y?(y.graph||await zi(y.key),y):Z(f,D.ROUTE_NOT_FOUND,"Composition not found for page-unit target.")}if(f.target.kind!=="node")return Z(f,D.UNSUPPORTED_OPERATION,`${f.kind} source target execution is not implemented yet.`);let h=i.get(o.resolveSelector(f.composition).key)??null;return h?(h.graph||await zi(h.key),fl(h,f.target.key)?h:Z(f,D.NODE_NOT_FOUND,`Target key not found: ${f.target.key}`)):Z(f,D.ROUTE_NOT_FOUND,"Composition not found for node target.")}return{get status(){return t},dispose(){t="disposed",a.clear(),i.clear(),s.clear(),d.clear(),p.clear()},registerComposition(f,h){let y=o.register({context:f,entryFile:h}),E=i.get(y.key);if(E?.entryFile===h)return;E&&N(E);let R=cm(y.context,h);i.set(y.key,R),oe(R,R.dependencyFiles),r.emit({type:"graph-invalidated",composition:y.context})},unregisterComposition(f){let h=o.resolveSelector(f),y=i.get(h.key);y&&(N(y),i.delete(h.key),o.unregister(h.key),i.size===0&&(t="idle"),r.emit({type:"graph-invalidated",composition:h.context}))},getCompositionEntryFiles(){return[...i.values()].map(f=>f.entryFile)},getCompositionContext(f){return o.resolveSelector(f).context},async initializeComposition(f){let h=o.resolveSelector(f),y=i.get(h.key);if(!y)throw new Error(`Composition not registered: ${h.key}`);if(y.graph)t="ready";else{t="building";try{let E=await n.readFile(y.entryFile);await ee(h.key,E),t="ready",r.emit({type:"graph-ready",composition:h.context,version:i.get(h.key)?.graph?.version??0})}catch(E){throw t="idle",r.emit({type:"graph-error",composition:h.context,message:Be(E)}),E}}},getDocument(f){let h=o.resolveSelector(f),y=i.get(h.key);if(!y)throw new Error(`Composition not registered: ${h.key}`);if(!y.document)throw new Error(`Composition not built: ${h.key}`);return y.document},async getHistoryStatus(){await C;let f=await l.getStatus?.();return f?{...f,recoveryRequired:g}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:g}},getObjectEditContext(f,h,y){let E=Qn(f,h),R=Ve(f)??f;if(E?.graph&&E.topology&&E.capabilities&&E.detailProjections){let P=E.detailProjections.get(R);if(P){let F=E.graph.elements.get(R);if(!F)throw new Error(`Key not found: ${f}`);let L=dC(f,R,y),_=new Map;if(P.isRepeat&&L?.instanceIndex!==void 0)for(let de of F.attributes??[])_.set(de.name,Ha({file:F.sourceFile,source:d.get(F.sourceFile)??"",element:F,propertyName:de.name,selectionRef:L,graph:E.graph,sources:d}));let $=up({element:F,graph:E.graph,source:d.get(F.sourceFile),documentVersion:E.graph.version,selectionRef:y,isRepeat:P.isRepeat,propertyProvenance:P.propertyProvenances,repeatTargets:_}),J=Cu(R,E.graph,E.topology,E.capabilities,P.textSources,P.provenances,P.dynamicData,$);return f===R?J:$C(J,f,E.document??null,E.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${f}`)},getRenderDetail(f,h){let y=Qn(f,h),E=Ve(f)??f;if(y?.graph&&y.topology&&y.capabilities&&y.detailProjections){let R=y.detailProjections.get(E);if(R){let P=ku(E,y.graph,y.topology,y.capabilities,R.textSources,R.writeTarget,R.provenances,R.conditional,R.componentSemantic,R.contentModel,R.mediaModel,R.styleSource,R.dynamicData);return f===E?P:jC(P,f,y.document??null,y.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${f}`)},getClassNameSource(f,h){let y=Qn(f,h),E=Ve(f)??f;if(!y?.graph)throw new Error(`Key not found: ${f}`);let R=y.graph.elements.get(E);if(!R)throw new Error(`Key not found: ${f}`);let P=d.get(R.sourceFile);if(P===void 0)throw new Error(`Source not loaded: ${R.sourceFile}`);return Vs({key:E,route:{composition:y.composition,routeId:y.routeId,graph:y.graph,source:P}})},refreshSourceForKey:cg,async execute(f){if(await C,g)return Z(f,D.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(f.kind==="source-edit")return lg(f);if(f.kind==="insert-page-resource")return ug(f);if(f.kind==="delete-page-source")return dg(f);let h=await ml(f);if("ok"in h)return h;await rl(f);let y=await ml(f);if("ok"in y)return y;let E=y;if(f.target.kind==="page-unit"){let L=f;return f.kind==="insert-child"||f.kind==="replace-node"?fg(L,E):f.kind==="move-node"||f.kind==="remove-node"?pg(L,E):Z(f,D.UNSUPPORTED_OPERATION,"Only page-unit insert-child, replace-node, move-node, and remove-node are currently supported by the page composition transaction.")}if(!E.graph||!E.topology||!E.capabilities)return{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:G(f),error:{code:f.target.kind==="route"?D.ROUTE_NOT_FOUND:D.NODE_NOT_FOUND,message:f.target.kind==="route"?"Composition not ready for route target.":f.target.kind==="node"?`Target key not found: ${f.target.key}`:`${f.kind} source target execution is not implemented yet.`}};let R=CC(E,E.graph,E.capabilities,d,i),P=await new qo(R).plan(f);if(!P.ok)return{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:G(f),error:{code:Kr(P.errorCode),message:P.reason}};let F=P.plan;if(F.steps.length===0)return f.kind==="set-props"?{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!0,resultVersion:G(f),affectedFiles:[]}:{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:G(f),error:{code:D.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};m+=1;try{if(F.steps.some(_=>_.type==="invoke-external-adapter")){let _=await u.execute(F);if(!_.ok)return Z(f,Kr(_.errorCode),_.reason);let $={composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!0,resultVersion:Math.max(G(f),_.resultVersion),affectedFiles:_.affectedFiles,..._.selectionRef?{selectionRef:_.selectionRef}:{}};return Ui($,{rebuiltRoutes:[],failedRoutes:[]}),$}let L=await u.prepareRewritePlan(F);return L.ok?await Cn({request:f,filePlan:L.filePlan,...L.selectionRef?{selectionRef:L.selectionRef}:{}}):Z(f,Kr(L.errorCode),L.reason)}catch(L){return{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:G(f),error:{code:D.INTERNAL_ERROR,message:Be(L)}}}finally{m-=1}},async undo(f){if(await C,g)return{composition:o.entries[0].context,requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:be(o.entries[0].key),error:{code:D.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};m+=1;try{return await cl("undo")}finally{m-=1}},async redo(f){if(await C,g)return{composition:o.entries[0].context,requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:be(o.entries[0].key),error:{code:D.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};m+=1;try{return await cl("redo")}finally{m-=1}},notifyFileChanged(f){Qc([f])},getAffectedCompositions(f){return rg(f)},subscribe(f){return r.subscribe(f)}}}function vC(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function IC(e,t,n){let r=new Map,o=new Map,i=(u,d,p)=>{let m=u.get(d)??new Set,g=m.size;return m.add(p),u.set(d,m),m.size!==g},s=(u,d)=>{if(!u.importedFrom)return!1;if(u.exportName==="default")return i(o,u.importedFrom,d);let p=i(r,`${u.importedFrom}#${u.tag}`,d);return u.exportName&&u.exportName!==u.tag&&(p=i(r,`${u.importedFrom}#${u.exportName}`,d)||p),p},a=u=>r.get(`${u.sourceFile}#${u.componentName}`)??o.get(u.sourceFile);for(let u of t.elements.values()){if(u.sourceFile!==n.entryFile||!u.importedFrom||!/^[A-Z]/.test(u.tag))continue;let d=n.placements.find(m=>m.members.some(g=>g.sourceRange!==null&&yc(u.sourceRange,g.sourceRange)));if(!d)continue;let p=d.placementUnitKey;s(u,p)}let c=!0;for(;c;){c=!1;for(let u of t.elements.values()){if(u.sourceFile===n.entryFile||!u.importedFrom||!/^[A-Z]/.test(u.tag))continue;let d=a(u);if(d)for(let p of d)c=s(u,p)||c}}let l=n.placements.find(u=>u.placementKey===n.container.placementKey&&u.relation==="append");for(let u of e.entries){let d=Ve(u.key)??u.key,p=t.elements.get(u.key)??t.elements.get(d);if(!p)continue;if(p.sourceFile===n.entryFile){if(n.container.sourceRange&&yc(p.sourceRange,n.container.sourceRange)&&l){u.pageCompositionUnitKey=l.placementUnitKey;continue}let b=n.placements.find(C=>C.members.some(I=>I.sourceRange!==null&&(yc(p.sourceRange,I.sourceRange)||kC(I.sourceRange,p.sourceRange))));if(b){u.pageCompositionUnitKey=b.placementUnitKey;continue}}let m=r.get(`${p.sourceFile}#${p.componentName}`);if(m){m.size===1&&(u.pageCompositionUnitKey=m.values().next().value);continue}let g=o.get(p.sourceFile);g?.size===1&&(u.pageCompositionUnitKey=g.values().next().value)}}function yc(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function kC(e,t){return dm(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&dm(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function dm(e,t,n,r){return e!==n?e-n:t-r}function CC(e,t,n,r,o){let i=new Map,s=new Map,a=(u,d)=>{if(s.has(u))return;s.set(u,d);let p=t.elements.get(u);for(let m of p?.childKeys??[])a(m,d)};for(let u of t.regions)if(u.kind==="repeat-region")for(let d of u.childKeys)i.set(d,u.ownerKey),a(d,u.ownerKey);return{getNode(u){let d=c(u),p=t.elements.get(d.baseKey);return p?l(u,p):null},getChildNodes(u){let d=c(u),m=e.documentIndex?.entriesByKey.get(u)?.childKeys;if(m)return m.map(b=>{let C=Ve(b)??b,I=t.elements.get(C);return I?l(b,I):null}).filter(b=>b!==null);let g=t.elements.get(d.baseKey);return g?g.childKeys.map(b=>{let C=t.elements.get(b);return C?l(b,C):null}).filter(b=>b!==null):[]},getKnownSourceFiles(){return[...r.entries()].map(([u,d])=>({file:u,content:d}))},getRouteEntryFiles(){return[...o.values()].map(u=>u.entryFile)},getCapability(u){let d=c(u),p=n.get(d.baseKey);return p?{...p,key:u,constraints:p.constraints.map(m=>({...m})),...p.editModes?{editModes:{...p.editModes}}:{}}:{composition:e.composition,key:u,canUpdateText:!1,canRemove:!1,canInsertChild:!1,canMove:!1,constraints:[]}},getFileContent(u){return r.get(u)??""},getFileVersion(u){return Math.max(e.fileVersions.get(u)??0,t.version)},getRouteEntryFile(u){return e.routeId===u?e.entryFile:null},getComponentSemantic(u){let d=c(u);return e.detailProjections?.get(d.baseKey)?.componentSemantic??null},getClassNameSource(u){let d=c(u),p=t.elements.get(d.baseKey),m=p?r.get(p.sourceFile):void 0;return!p||m===void 0?null:Vs({key:d.baseKey,route:{composition:e.composition,routeId:e.routeId,graph:t,source:m}})},getEditableTextSegmentIndex(u){let d=c(u),m=e.detailProjections?.get(d.baseKey)?.textTargets.keys()?.next();return m&&!m.done?m.value:null},async getTextWriteTarget(u,d){let p=c(u);return mm(e.detailProjections?.get(p.baseKey)?.textTargets.get(d)??null,p.repeatIndex)},async getElementPropertyWriteTarget(u,d){let p=c(u);return mm(e.detailProjections?.get(p.baseKey)?.elementPropertyTargets.get(d)??null,p.repeatIndex)},getPropertyState(u,d,p){let m=c(u),g=t.elements.get(m.baseKey);if(!g)return null;let C=e.detailProjections?.get(m.baseKey)?.propertyProvenances.get(d);if(C)return C;let I=g.attributes?.find(w=>w.name===d);return I?I.source?{status:"blocked",owner:"generic",diagnostic:{code:"unsupported-property-source",message:`Property '${d}' has an unresolved value source`}}:{status:"direct",owner:"generic",attribute:I,target:{kind:"jsx-attribute",file:g.sourceFile,sourceRange:I.sourceRange}}:(g.attributeSpreads?.length??0)>0?{status:"blocked",owner:"generic",diagnostic:{code:"ambiguous-property-source",message:`A spread may provide or override property '${d}'`}}:{status:"missing",owner:"generic"}},getRepeatPropertyTarget(u,d,p){let m=c(u),g=t.elements.get(m.baseKey);if(!g)return{ok:!1,errorCode:"repeat-not-found",reason:`Node not found: ${u}`};let b=p?{...p,key:m.baseKey}:m.repeatIndex!==null?{key:m.baseKey,instanceIndex:m.repeatIndex}:void 0;return Ha({file:g.sourceFile,source:r.get(g.sourceFile)??"",element:g,propertyName:d,selectionRef:b,graph:t,sources:r})},getTextProvenance(u,d){let p=c(u);return e.detailProjections?.get(p.baseKey)?.provenances.get(d)??null}};function c(u){let d=qk(u);return d?{baseKey:d.baseKey,repeatIndex:DC(e.document??null,u,d.baseKey,e.documentIndex)??MC(d)}:{baseKey:u,repeatIndex:null}}function l(u,d){let p=Ve(u)??u,m=e.documentIndex?.entriesByKey.get(u),g=e.detailProjections?.get(p);return{key:u,file:d.sourceFile,component:d.componentName,tag:d.tag,structuralPath:d.identity.structuralPath,sourceRange:d.sourceRange,parentKey:m?.parentKey??d.parentKey??void 0,isRepeatRegion:d.boundaryKind==="repeat-region"||s.has(p),isBoundary:!1,importedFrom:d.importedFrom,exportName:d.exportName,isRepeatItemRoot:i.has(p),repeatOwnerKey:i.get(p)??s.get(p),contentModel:g?.contentModel,attributes:d.attributes?.map(b=>({name:b.name,value:b.value,source:b.source?{expression:b.source.expression,base:b.source.base,path:b.source.path.map(C=>({...C}))}:null,resolvedValue:b.resolvedValue}))}}}var RC={"stale-version":D.VERSION_STALE,"capability-denied":D.CAPABILITY_REJECTED,"invalid-params":D.INVALID_PARAMS,"locator-miss":D.LOCATOR_FAILED,"route-not-found":D.ROUTE_NOT_FOUND,"unsupported-operation":D.UNSUPPORTED_OPERATION,"invalid-target":D.INVALID_TARGET,"ast-error":D.AST_PARSE_ERROR,"writeback-failed":D.WRITE_IO_ERROR,"rollback-failed":D.RECOVERY_REQUIRED,unknown:D.INTERNAL_ERROR};function Kr(e){return RC[e]}function Be(e){return e instanceof Error&&e.message?e.message:String(e)}function fm(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function wC(e){let t=En(e);if(!nC.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=>rC.map(a=>`${s}/${a}`))}function NC(e){let n=En(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function PC(e){return hm(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function AC(e){return hm(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function hm(e,t){let n=[];for(let r of e.matchAll(t)){let o=ym(r[1]??"");o&&n.push(o)}return n}function pm(e,t){let n=ym(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?En(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?En(`${TC(e)}/${n}`):n.startsWith("/")?En(n.slice(1)):xc(n)?En(n):null}function ym(e){return e.split(/[?#]/,1)[0]?.trim()??""}function xc(e){return/\.css$/i.test(e)}function TC(e){let t=En(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function xm(e){return Array.from(new Set(e))}function En(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 _C(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 FC(e,t){let n=t.elements.get(e);if(!n)return!1;for(let r of t.regions){if(r.kind!=="repeat-region")continue;let o=n;for(;o;){if(r.childKeys.includes(o.identity.key))return!0;o=o.parentKey?t.elements.get(o.parentKey):void 0}}return!1}function Ii(e){return e?.map(t=>({...t}))}function mm(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=Ii(e.collectionPathMap?.[t])??Ii(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:Ii(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>Ii(o)??[])}}function OC(e,t,n){let r=new Set;for(let m of t.regions)if(m.kind==="repeat-region")for(let g of m.childKeys)r.add(g);if(r.size===0)return e;let o=new Map(e.entries.map(m=>[m.key,m])),i=[],s=new Map,a=(m,g)=>Yk(m,g),c=(m,g,b)=>{let C=o.get(m);if(!C)return a(m,b);let I=a(m,b),w={...C,key:I,parentKey:g,childKeys:[]};return i.push(w),w.childKeys=C.childKeys.flatMap(A=>l(A,b,I)),I},l=(m,g,b)=>{if(!r.has(m))return[c(m,b,g)];let C=d(m,g),I=[];for(let w=0;w<C;w+=1)I.push(c(m,b,[...g,w]));return I},u=xm([...e.rootKeys,...e.entries.filter(m=>m.parentKey===null).map(m=>m.key)]);for(let m of u){if(!r.has(m)){c(m,null,[]);continue}let g=d(m,[]);for(let b=0;b<g;b+=1)c(m,null,[b])}return{...e,rootKeys:[...e.rootKeys],entries:i};function d(m,g){let b=new Set;for(let C of p(m)){let I=n.get(C);if(I){for(let w of[...I.textTargets.values(),...I.elementPropertyTargets.values()])if(!(w?.kind!=="value-binding"||w.sourceKind!=="repeat-template"))for(let A of LC(w))A.length<=g.length||BC(A,g)&&b.add(A[g.length])}}return b.size>0?b.size:_C(n.get(m))}function p(m){let g=s.get(m);if(g)return g;let b=[m],C=o.get(m);for(let I of C?.childKeys??[])b.push(...p(I));return s.set(m,b),b}}function MC(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function DC(e,t,n,r){let o=r?.repeatOccurrenceIndexByKey.get(t);if(o!==void 0)return o;if(!e)return null;let i=0;for(let s of e.entries)if((Ve(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function LC(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 BC(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 jC(e,t,n,r){if(!n)return{...e,key:t};let o=r??new Map(n.entries.map(u=>[u.key,u])),i=o.get(t);if(!i)return{...e,key:t};let s=[],a=i.parentKey;for(;a;){let u=o.get(a);if(!u)break;s.push({key:u.key,tag:u.tag,label:u.label}),a=u.parentKey}s.reverse();let c=i.childKeys.map(u=>o.get(u)).filter(u=>u!==void 0).map(u=>({key:u.key,tag:u.tag,label:u.label})),l=i.parentKey===null?[]:(o.get(i.parentKey)?.childKeys??[]).filter(u=>u!==i.key).map(u=>o.get(u)).filter(u=>u!==void 0).map(u=>({key:u.key,tag:u.tag,label:u.label}));return{...e,key:i.key,ancestors:s,children:c,siblings:l}}function $C(e,t,n,r){if(!n)return{...e,key:t};let o=r??new Map(n.entries.map(c=>[c.key,c])),i=o.get(t);if(!i)return{...e,key:t};let s=[],a=i.parentKey;for(;a;){let c=o.get(a);if(!c)break;s.push({key:c.key,tag:c.tag,label:c.label}),a=c.parentKey}return s.reverse(),{...e,key:i.key,ancestors:s}}import Ic from"node:path";import{TextDecoder as VC}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as Sm,SITE_EDIT_SOURCE_ALLOWED_DIRS as Em,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as vm,SiteEditCompositionContextSchema as UC,SiteEditSourceFileResponseSchema as bc,SiteEditSourceLocationSchema as KC,SiteEditSourcePathSchema as Ci,SiteEditSourceTreeResponseSchema as JC,isSiteEditTextSourcePath as XC}from"@vcp-dev/contracts";var zC=[...vm,...Sm,...Em];function kc(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return UC.parse(e.composition)}var Sc=2e3,Ec=12,vc=24*1024*1024,bm=512*1024,WC=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),HC={".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"},GC={".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"},YC=new VC("utf-8",{fatal:!0});async function Ri(e,t={}){let n=kc(t),{files:r,truncated:o}=await oR(e,t),i=aR(r.map(s=>s.metadata));return JC.parse({composition:n,nodes:i,defaultPath:cR(r.map(s=>s.metadata)),totalFiles:r.length,...o?{truncated:o}:{}})}async function wi(e,t,n={}){let r=kc(n),o=Ci.parse(t.path),i=await qC(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(Cc(o)){let a=Cm(o),c=await tR(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return bc.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...c})}let s=await ZC(e,o);return s.ok?bc.parse({composition:r,path:o,kind:"text",language:Rm(o),sizeBytes:s.sizeBytes,contentHash:fe(s.content),readonly:!1,content:s.content}):bc.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function ZC(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=QC(o);return i===null?{ok:!1,sizeBytes:o.byteLength}:{ok:!0,content:i,sizeBytes:o.byteLength}}let n=await e.readFile(t),r=Buffer.byteLength(n,"utf8");return n.includes("\0")?{ok:!1,sizeBytes:r}:{ok:!0,content:n,sizeBytes:r}}function QC(e){if(e.includes(0))return null;try{return YC.decode(e)}catch{return null}}async function qC(e,t,n){if(!nR(t,n))return null;let r=await eR(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function eR(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=Im(await e.listFiles({roots:[t],maxFiles:1,maxDepth:t.split("/").length})).files.find(i=>i.path===t);if(o)return o}if(!await e.exists(t))return null;if(e.readFileBytes){let r=await e.readFileBytes(t);return{path:t,sizeBytes:r.byteLength}}if(Cc(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function tR(e,t){if(!WC.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>bm)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>bm?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function nR(e,t){return vm.some(n=>n===e)||Sm.some(n=>n===e)||Em.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=Ci.safeParse(n);return r.success&&r.data===e})}function Ni(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return KC.parse({key:e.key,composition:t.composition,sourceFile:t.sourceLocator.sourceFile,componentName:t.sourceLocator.componentName,openingElementRange:{startLine:t.sourceLocator.openingElementRange.startLine,startColumn:t.sourceLocator.openingElementRange.startColumn,endLine:t.sourceLocator.openingElementRange.endLine,endColumn:t.sourceLocator.openingElementRange.endColumn},structuralPath:t.sourceLocator.structuralPath,textPreview:t.sourceLocator.textPreview})}function Im(e){return Array.isArray(e)?{files:e}:e}function rR(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function oR(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=Im(await e.listFiles({roots:iR(t),maxFiles:Sc+1,maxDepth:Ec,maxTotalBytes:vc+1})),r=new Map,o=new Set(n.truncated?.reasons),i=0;for(let a of[...n.files].sort((c,l)=>c.path.localeCompare(l.path))){let c=Ci.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>Ec){o.add("max-depth");continue}if(r.size>=Sc){o.add("max-files");break}if(i+a.sizeBytes>vc){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:sR(l,a.sizeBytes,kc(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:rR([...o]),maxFiles:Sc,maxDepth:Ec,maxTotalBytes:vc}}:{}}}function iR(e){let t=new Set(zC);for(let n of e.routeEntryFiles??[]){let r=Ci.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function sR(e,t,n){return Cc(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:Cm(e),readonly:!0}:{composition:n,path:e,kind:"text",language:Rm(e),sizeBytes:t,readonly:!1}}function aR(e){let t=[];for(let n of e){let r=n.path.split("/"),o=t,i="";for(let[s,a]of r.entries()){i=i?`${i}/${a}`:a;let c=s===r.length-1,l=o.find(u=>u.name===a);if(l||(l=c?{kind:"file",name:a,path:i,file:n}:{kind:"directory",name:a,path:i,children:[]},o.push(l)),c){if(l.kind!=="file")throw new Error(`Source tree path collision: ${n.path}`);l.file=n}else{if(l.kind!=="directory")throw new Error(`Source tree path collision: ${n.path}`);o=l.children}}}return km(t)}function km(e){return e.map(t=>t.kind==="directory"?{...t,children:km(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function cR(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 Cc(e){return!XC(e)}function Cm(e){let t=Ic.posix.extname(e).toLowerCase();return!t&&Ic.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":HC[t]??"application/octet-stream"}function Rm(e){let t=Ic.posix.extname(e).toLowerCase();return GC[t]??"plaintext"}var Pi=class{constructor(t){this.options=t,this.fileSystem=new pr(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}getDocument(t){return so(this.engine.getDocument(t),{siteId:this.options.siteId,snapshotId:this.options.snapshotId})}getInternalDocument(t){return this.engine.getDocument(t)}getStyleContext(t){return this.engine.getDocument(t).styleContext??null}getObjectEditContext(t,n,r){return ao(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return Ri(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}getSourceFile(t){return wi(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}resolveSourceLocation(t){return Ni(t,this.engine.getRenderDetail(t.key,t.composition))}async planOperation(t){let n=uR.safeParse(t);if(!n.success)return{result:io(t,n.error.issues.map(i=>i.message))};let r=new pr(this.options.files),o=this.createEngine(r,{emitEvents:!1});try{let i=await o.execute(n.data);if(!i.ok)return{result:{ok:!1,composition:i.composition,error:{code:i.error?.code??"INTERNAL_ERROR",message:i.error?.message??"Operation failed"},data:{requestId:i.requestId,kind:i.kind,target:i.target,resultVersion:i.resultVersion}}};let s={ok:!0,composition:i.composition,data:nn(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let c=dR.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(l=>fR(l,t.kind==="source-edit")),changedCompositions:o.getAffectedCompositions(a.map(l=>l.path)),diagnostics:[]});return this.options.onEvent?.({type:"site-edit.operation.planned",siteId:t.siteId,operationId:t.id,baseSnapshotId:t.baseSnapshotId,changedFiles:c.patches.map(l=>l.path),composition:i.composition,at:new Date().toISOString()}),{result:s,patchPlan:c}}finally{o.dispose()}}dispose(){this.engine.dispose()}createEngine(t,n={}){let r=n.emitEvents??!0;return Jr({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=co(o,{siteId:this.options.siteId,snapshotId:this.options.snapshotId});i&&this.options.onEvent?.(i)}:void 0,dev:this.options.dev,...this.options.historyStore?{historyStore:this.options.historyStore}:{},...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,...this.options.initialDocumentVersions?{initialDocumentVersions:this.options.initialDocumentVersions}:{}})}};function fR(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:fe(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:fe(e.before)},fullContent:e.after}}function pR(e){return new Pi(e)}import{SiteEditOperationRequestSchema as hR}from"@vcp-dev/contracts";import mt from"node:fs/promises";import je from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as mR,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as gR}from"@vcp-dev/contracts";var Ai=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=Jr({...t,fileSystem:this.fileSystem})}get status(){return this.engine.status}registerComposition(t,n){this.engine.registerComposition(t,n)}unregisterComposition(t){this.engine.unregisterComposition(t)}getDocument(t){return this.engine.getDocument(t)}getAffectedCompositions(t){return this.engine.getAffectedCompositions(t)}getCompositionContext(t){return this.engine.getCompositionContext(t)}initializeComposition(t){return this.engine.initializeComposition(t)}getHistoryStatus(){return this.engine.getHistoryStatus()}getObjectEditContext(t,n,r){return r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n)}getRenderDetail(t,n){return this.engine.getRenderDetail(t,n)}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return Ri(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.engine.getCompositionEntryFiles()})}getSourceFile(t){return wi(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.engine.getCompositionEntryFiles()})}resolveSourceLocation(t){return Ni(t,this.engine.getRenderDetail(t.key,t.composition))}refreshSourceForKey(t,n){return this.engine.refreshSourceForKey(t,n)}execute(t){return this.engine.execute(t)}undo(t){return this.engine.undo(t)}redo(t){return this.engine.redo(t)}notifyFileChanged(t){this.engine.notifyFileChanged(t)}subscribe(t){return this.engine.subscribe(t)}dispose(){this.engine.dispose()}createFileSystem(){if(this.options.fileSystem)return this.options.fileSystem;let t=new Map,{projectRoot:n}=this.options;return{async readFile(r){return mt.readFile(je.join(n,r),"utf8")},async readFileBytes(r){return mt.readFile(je.join(n,r))},async getFileInfo(r){let o=je.join(n,...r.split("/"));try{let i=await mt.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await ui(je.join(n,r),o)},async createExclusive(r,o){let i=je.join(n,r);await mt.mkdir(je.dirname(i),{recursive:!0});let s=await mt.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await mt.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await mt.rm(je.join(n,r),{force:!0});let o=r.replace(/\\/g,"/"),i=["components/site/generated","src/components/site/generated"].find(c=>o.startsWith(`${c}/`));if(!i)return;let s=je.join(n,i),a=je.dirname(je.join(n,o));for(;a!==s&&a.startsWith(`${s}${je.sep}`);){try{await mt.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=je.dirname(a);continue}break}a=je.dirname(a)}},async exists(r){try{return await mt.access(je.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...gR,...mR],i=[],s=new Set,a=new Set,c=0;for(let d of o)await u(d,i,1);let l=i.sort((d,p)=>d.path.localeCompare(p.path));return a.size>0?{files:l,truncated:{reasons:[...a]}}:{files:l};async function u(d,p,m){if(r.maxDepth!==void 0&&m>r.maxDepth){a.add("max-depth");return}let g=je.join(n,...d.split("/")),b;try{b=await mt.lstat(g)}catch{return}if(b.isSymbolicLink())return;if(b.isFile()){let I=b.ino>0?`${String(b.dev)}:${String(b.ino)}`:null;if(I&&s.has(I))return;if(r.maxFiles!==void 0&&p.length>=r.maxFiles){a.add("max-files");return}if(r.maxTotalBytes!==void 0&&c+b.size>r.maxTotalBytes){a.add("max-total-bytes");return}I&&s.add(I),p.push({path:d,sizeBytes:b.size}),c+=b.size;return}if(!b.isDirectory())return;if(r.maxFiles!==void 0&&p.length>=r.maxFiles){a.add("max-files");return}let C=await mt.readdir(g,{withFileTypes:!0});for(let I of C)I.isSymbolicLink()||await u(`${d}/${I.name}`,p,m+1)}},getVersion(r){return t.get(r)??1},bumpVersion(r){let o=(t.get(r)??1)+1;return t.set(r,o),o}}}};function Rc(e){return new Ai(e)}var Ti=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=Rc({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=co(n,{siteId:t.siteId,snapshotId:t.snapshotId});if(r){t.onEvent?.(r);for(let o of this.listeners)o(r)}},dev:t.dev,...t.historyStore?{historyStore:t.historyStore}:{},...t.tenantId?{tenantId:t.tenantId}:{},...t.initialDocumentVersions!==void 0?{initialDocumentVersions:t.initialDocumentVersions}:{},siteId:t.siteId,snapshotId:t.snapshotId})}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}registerComposition(t,n){this.engine.registerComposition(t,n)}unregisterComposition(t){this.engine.unregisterComposition(t)}getDocument(t){return{ok:!0,composition:this.engine.getCompositionContext(t),data:so(this.engine.getDocument(t),{siteId:this.options.siteId,snapshotId:this.options.snapshotId})}}getInternalDocument(t){return this.engine.getDocument(t)}getStyleContext(t){return{ok:!0,composition:this.engine.getCompositionContext(t),data:this.engine.getDocument(t).styleContext??null}}async getHistoryStatus(){return{ok:!0,composition:this.options.compositions[0].context,data:await this.engine.getHistoryStatus()}}getObjectEditContext(t,n,r){return{ok:!0,composition:this.engine.getCompositionContext(n),data:ao(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}}getClassNameSource(t,n){return{ok:!0,composition:this.engine.getCompositionContext(n),data:this.engine.getClassNameSource(t,n)}}async getSourceTree(t){return{ok:!0,composition:this.engine.getCompositionContext(t),data:await this.engine.getSourceTree(t)}}async getSourceFile(t){return{ok:!0,composition:this.engine.getCompositionContext(t.composition),data:await this.engine.getSourceFile(t)}}resolveSourceLocation(t){return{ok:!0,composition:this.engine.getCompositionContext(t.composition),data:this.engine.resolveSourceLocation(t)}}refreshSourceForKey(t,n){return this.engine.refreshSourceForKey(t,n)}async executeOperation(t,n){let r=n===void 0||t.mutationContext!==void 0?t:{...t,mutationContext:n},o=hR.safeParse(r);if(!o.success)return io(t,o.error.issues.map(s=>s.message));let i=await this.engine.execute(o.data);if(!i.ok){let s=i.error;if(!s)throw new Error("executeOperation failed without an error payload");return{ok:!1,composition:i.composition,error:{code:s.code,message:s.message},data:{requestId:i.requestId,kind:i.kind,composition:i.composition,target:i.target,resultVersion:i.resultVersion,...i.affectedFiles?.length?{affectedFiles:i.affectedFiles}:{}}}}return{ok:!0,composition:i.composition,data:nn(i)}}async undo(t){let n=await this.engine.undo();if(!n.ok){let r=n.error;if(!r)throw new Error("undo failed without an error payload");return{ok:!1,composition:n.composition,error:{code:r.code,message:r.message},data:{requestId:n.requestId,kind:n.kind,composition:n.composition,target:n.target,resultVersion:n.resultVersion}}}return{ok:!0,composition:n.composition,data:nn(n)}}async redo(t){let n=await this.engine.redo();if(!n.ok){let r=n.error;if(!r)throw new Error("redo failed without an error payload");return{ok:!1,composition:n.composition,error:{code:r.code,message:r.message},data:{requestId:n.requestId,kind:n.kind,composition:n.composition,target:n.target,resultVersion:n.resultVersion}}}return{ok:!0,composition:n.composition,data:nn(n)}}notifyFileChanged(t){this.engine.notifyFileChanged(t)}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}dispose(){this.listeners.clear(),this.engine.dispose()}};function yR(e){return new Ti(e)}import{createHash as xR,randomUUID as Bc}from"node:crypto";import ve from"node:fs/promises";import ke from"node:path";var nt=1,Nc=1,bR=2,SR="index.json",ER="recovery.json",vR="transaction-journal.json",IR="document-version.json",Fi={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},z={INVALID_ROOT:"INVALID_ROOT",INVALID_PATH:"INVALID_PATH",INVALID_SCHEMA:"INVALID_SCHEMA",INVALID_JSON:"INVALID_JSON",INDEX_CORRUPT:"INDEX_CORRUPT",ENTRY_CORRUPT:"ENTRY_CORRUPT",BLOB_CORRUPT:"BLOB_CORRUPT",RECOVERY_PENDING:"RECOVERY_PENDING",CAPACITY_EXCEEDED:"CAPACITY_EXCEEDED",NOT_FOUND:"NOT_FOUND"},H=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};async function Dm(e,t={}){let n=LR(e),r=$R(t.limits),o=wc(n),i=BR(n),s=await Ue(i),a=await Ue(o)||s;a||(await PR(n),await AR(n)),a||await VR(n);let c=await We(n),l=new Set(a?(await Bi(n)).map(d=>d.stageId):[]);a||await Xr(n,c.entryIds);let u=async()=>{if(await Ue(o)||s)throw new H(z.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")};return{rootDir:n,recoveryRequired:a,async readDocumentVersion(){return Om(n)},async writeDocumentVersion(d){if(await u(),!Number.isInteger(d)||d<0)throw new H(z.INVALID_SCHEMA,"document version must be a non-negative integer");let p=await Om(n);await zr(Km(n),{schemaVersion:1,version:Math.max(p,d)})},async stageAppend(d,p={}){await u();let m=await Nm(d,r),g={schemaVersion:Nc,stageId:Bc(),entryId:m.entryId,blobIds:m.blobs.map(b=>b.digest)};try{await Pm(n,m),await RR(n,g,p.durableManifest!==!1)}catch(b){try{await Tm(n,g)}catch(C){throw new H(z.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:C})}throw b}return{stageId:g.stageId,entryId:g.entryId,blobIds:g.blobIds}},async discardStage(d){await u(),_c(d);let p=await Ac(n,d);p&&await Tm(n,p)},async previewStagedAppend(d,p){return await u(),(await wm(n,r,d,p)).transition},async previewCursor(d,p){await u();let m=await We(n);return Fc(m,p),Pc(d,m.entryIds.length),Lm(m,m.entryIds,d)},async publishStagedAppend(d,p,m){if(await u(),Oi(d,"entryId"),m){_c(m);let b=await Ac(n,m);if(!b||b.entryId!==d)throw new H(z.INVALID_SCHEMA,"history stage does not match the published entry")}let g=await wm(n,r,d,p);return Fm({rootDir:n,previousDigest:g.current.digest,entryIds:g.entryIds,cursor:g.cursor,afterWrite:async()=>{m?await Mi(n,m):await NR(n,d),await Xr(n,g.entryIds)}})},async append(d){await u();let p=await We(n),m=await Nm(d,r),g=[...p.entryIds];p.cursor<g.length-1&&g.splice(p.cursor+1),g.push(m.entryId);try{await Pm(n,m);let b=await Bm(n,g,r);return await $c(n,b.entryIds,b.cursor),await Xr(n,b.entryIds),We(n)}catch(b){throw await Xr(n,p.entryIds),b}},async readEntry(d){return Oi(d,"entryId"),Hr(n,d)},async readBlob(d){Oi(d,"blobId");let p=await Hc(n,d),m=await qt(p,z.NOT_FOUND,"blob");return Vc(m,d,p),m},async readIndex(){return We(n)},async readStatus(){let d=await We(n);return{canUndo:d.undoIds.length>0,canRedo:d.redoIds.length>0,undoDepth:d.undoIds.length,redoDepth:d.redoIds.length,cursor:d.cursor,recoveryRequired:await Ue(o)||await Ue(i)}},async readUndoRedoIds(){let d=await We(n);return{undoIds:d.undoIds,redoIds:d.redoIds,currentId:d.currentId}},async setCursor(d,p){await u();let m=await We(n);return Fc(m,p),Pc(d,m.entryIds.length),Fm({rootDir:n,previousDigest:m.digest,entryIds:m.entryIds,cursor:d})},async markRecoveryRequired(d){await Ue(o)||await zr(wc(n),{schemaVersion:nt,reason:jR(d),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await ve.rm(wc(n),{force:!0})},async readTransactionJournal(){return await Ue(i)?_i(i):null},async writeTransactionJournal(d){await u(),Jm(d);try{await zr(i,d)}catch(m){let g=await _i(i).catch(()=>null);if(g&&Buffer.from(He(g)).equals(Buffer.from(He(d))))return;throw g?new H(z.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:m}):m}let p=await _i(i);if(!Buffer.from(He(p)).equals(Buffer.from(He(d))))throw new H(z.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(d){let p=await Ue(i)?await _i(i):null;if(p&&p.transactionId!==d)throw new H(z.INVALID_SCHEMA,"transaction journal changed concurrently");try{await ve.rm(i,{force:!0})}catch(m){if(!await Ue(i))return;throw m}if(await Ue(i))throw new H(z.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await u();for(let p of l)await Mi(n,p),l.delete(p);await TR(n);let d=await We(n);await Xr(n,d.entryIds)}}}async function wm(e,t,n,r){Oi(n,"entryId");let o=await We(e);Fc(o,r);let i=await Hr(e,n),s=[...o.entryIds];o.cursor<s.length-1&&s.splice(o.cursor+1),s.push(i.id);let a=await Bm(e,s,t);return{current:o,entryIds:a.entryIds,cursor:a.cursor,transition:Lm(o,a.entryIds,a.cursor)}}function Lm(e,t,n){return Pc(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:kR(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function kR(e,t){return en(He({schemaVersion:nt,entryIds:e,cursor:t}))}function Pc(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new H(z.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function CR(e){if(!gt(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!Ge(e.expectedIndexDigest)||!Ge(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!Ge(n)?!1:t===-1?n===null:Ge(n)}async function Nm(e,t){if(!e.kind.trim())throw new H(z.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new H(z.INVALID_JSON,"history blob name must not be empty");let l=DR(c.data),u=en(l);n.push({name:c.name,bytes:l,digest:u,sizeBytes:l.byteLength}),r.push({name:c.name,digest:u,sizeBytes:l.byteLength})}let o={schemaVersion:nt,kind:e.kind,manifest:e.manifest,blobs:r},i=He({...o}),s=en(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new H(z.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function Pm(e,t){let n=Jc(e,t.entryId),r={id:t.entryId,...t.entryBody},o=[...t.blobs.map(a=>Am(Xc(e,a.digest),a.bytes,{kind:"blob",digest:a.digest},Wc(e,a.digest))),Am(n,He(r),{kind:"entry",digest:t.entryId},zc(e,t.entryId))],s=(await Promise.allSettled(o)).find(a=>a.status==="rejected");if(s)throw s.reason}async function Am(e,t,n,r){let o=await Dc(e)??(r?await Dc(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new H(n.kind==="blob"?z.BLOB_CORRUPT:z.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await Vm(e,t)}async function Bm(e,t,n){let r=[...t],o=r.length-1;for(;;){if((await $m(e,r)).totalBytes<=n.maxSessionBytes&&r.length<=n.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new H(z.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");r.shift(),o-=1}}async function RR(e,t,n){jc(t);let r=Kc(e,t.stageId);if(n){await zr(r,t);return}await MR(r,t)}async function Ac(e,t){let n=await Dc(Kc(e,t));if(n===null)return null;let r=Gr(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=jc(r);if(o.stageId!==t)throw new H(z.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function Bi(e){let t=[];for(let n of await Li(Uc(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);_c(r);let o=await Ac(e,r);o&&t.push(o)}return t}async function Tm(e,t){jc(t);let n=await We(e),r=(await Bi(e)).filter(s=>s.stageId!==t.stageId),o=new Set(n.entryIds),i=new Set;for(let s of n.entryIds){let a=await Hr(e,s);for(let c of a.blobs)i.add(c.digest)}for(let s of r){o.add(s.entryId);for(let a of s.blobIds)i.add(a)}o.has(t.entryId)||await _m(Jc(e,t.entryId),zc(e,t.entryId));for(let s of t.blobIds)i.has(s)||await _m(Xc(e,s),Wc(e,s));await Mi(e,t.stageId),await Lc(Yr(e)),await Lc(Zr(e))}async function Mi(e,t){await Tc(Kc(e,t)),await wR(e)}async function wR(e){try{await ve.rmdir(Uc(e))}catch(t){if(Qr(t)||gt(t)&&t.code==="ENOTEMPTY")return;throw t}}async function NR(e,t){for(let n of await Bi(e))n.entryId===t&&await Mi(e,n.stageId)}async function Tc(e){if(await ve.rm(e,{force:!0}),await Ue(e))throw new H(z.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function _m(e,t){await Tc(e),await Tc(t)}function jc(e){if(!gt(e)||e.schemaVersion!==Nc||typeof e.stageId!="string"||!jm(e.stageId)||!Ge(e.entryId))throw new H(z.INVALID_SCHEMA,"history stage schema is invalid");let t=Um(e.blobIds,"history stage blobIds");return{schemaVersion:Nc,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function _c(e){if(!jm(e))throw new H(z.INVALID_PATH,"history stageId must be a UUID")}function jm(e){return typeof e=="string"&&/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu.test(e)}async function Xr(e,t){let n=new Set(t),r=new Set;for(let c of t){let l=await Hr(e,c);for(let u of l.blobs)r.add(u.digest)}for(let c of await Bi(e)){n.add(c.entryId);for(let l of c.blobIds)r.add(l)}let o=Yr(e),i=await Li(o);for(let c of i){if(!c.endsWith(".json"))continue;let l=Mm(c.slice(0,-5));l&&!n.has(l)&&await Di(ke.join(o,c))}let s=Zr(e),a=await Li(s);for(let c of a){let l=Mm(c);l&&!r.has(l)&&await Di(ke.join(s,c))}}async function We(e){let t=ji(e),n=await qt(t,z.NOT_FOUND,"index"),r=Gr(Buffer.from(n).toString("utf8"),"index"),o=_R(r),i=[...o.entryIds],{totalBytes:s}=await $m(e,i),a=i.slice(0,o.cursor+1).reverse(),c=i.slice(o.cursor+1);return{schemaVersion:nt,digest:o.digest,entryIds:i,cursor:o.cursor,currentId:i[o.cursor]??null,undoIds:a,redoIds:c,totalBytes:s}}async function $m(e,t){let n=0,r=new Set,o=ji(e),i=await qt(o,z.NOT_FOUND,"index");n+=i.byteLength;for(let s of t){let a=await Hr(e,s),c=await Xm(e,s),l=await qt(c,z.NOT_FOUND,"entry");n+=l.byteLength;for(let u of a.blobs){if(r.has(u.digest))continue;r.add(u.digest);let d=await Hc(e,u.digest),p=await qt(d,z.NOT_FOUND,"blob");Vc(p,u.digest,d),n+=p.byteLength}}return{totalBytes:n}}async function Hr(e,t){let n=await Xm(e,t),r=await qt(n,z.NOT_FOUND,"entry"),o=Gr(Buffer.from(r).toString("utf8"),`entry ${t}`),i=FR(o);if(i.id!==t)throw new H(z.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(en(He({schemaVersion:i.schemaVersion,kind:i.kind,manifest:i.manifest,blobs:i.blobs}))!==t)throw new H(z.ENTRY_CORRUPT,`entry hash mismatch for ${t}`);for(let a of i.blobs){let c=await Hc(e,a.digest),l=await qt(c,z.NOT_FOUND,"blob");Vc(l,a.digest,c)}return i}async function $c(e,t,n){let r={schemaVersion:nt,digest:en(He({schemaVersion:nt,entryIds:t,cursor:n})),entryIds:t,cursor:n};await zr(ji(e),r)}function Fc(e,t){if(t!==void 0&&e.digest!==t)throw new H(z.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function Fm(e){let t=en(He({schemaVersion:nt,entryIds:e.entryIds,cursor:e.cursor}));try{return await $c(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.(),await We(e.rootDir)}catch(n){let r=await We(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new H(z.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function PR(e){await ve.mkdir(e,{recursive:!0}),await ve.mkdir(Yr(e),{recursive:!0}),await ve.mkdir(Zr(e),{recursive:!0}),await ve.mkdir(Wr(e),{recursive:!0})}async function AR(e){await ve.rm(Wr(e),{recursive:!0,force:!0}),await ve.mkdir(Wr(e),{recursive:!0})}async function TR(e){let t=Wr(e);await ve.mkdir(t,{recursive:!0});for(let n of await Li(t))n!=="stages"&&await ve.rm(ke.join(t,n),{recursive:!0,force:!0})}function _R(e){if(!gt(e))throw new H(z.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==nt)throw new H(z.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=Um(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new H(z.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!Ge(o))throw new H(z.INDEX_CORRUPT,"index digest is invalid");let i=en(He({schemaVersion:nt,entryIds:t,cursor:r}));if(o!==i)throw new H(z.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:nt,digest:o,entryIds:t,cursor:r}}function FR(e){if(!gt(e))throw new H(z.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==nt)throw new H(z.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!Ge(t))throw new H(z.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new H(z.ENTRY_CORRUPT,"entry kind is invalid");let r=Mc(e.manifest,"entry.manifest"),o=OR(e.blobs);return{id:t,schemaVersion:nt,kind:n,manifest:r,blobs:o}}function OR(e){if(!Array.isArray(e))throw new H(z.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!gt(t))throw new H(z.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new H(z.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!Ge(o))throw new H(z.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new H(z.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function zr(e,t){await Vm(e,He(t))}async function MR(e,t){let n=ke.dirname(e),r=ke.basename(e),o=ke.join(n,`.${r}.${process.pid}.${Bc()}.tmp`);await ve.mkdir(n,{recursive:!0});try{await ve.writeFile(o,He(t),{flag:"wx"}),await ve.rename(o,e)}finally{await Di(o)}}async function Vm(e,t){let n=ke.dirname(e),r=ke.basename(e),o=ke.join(n,`.${r}.${process.pid}.${Bc()}.tmp`);await ve.mkdir(n,{recursive:!0});try{let i=await ve.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await ve.rename(o,e),await Lc(n)}finally{await Di(o)}}function He(e){return Buffer.from(JSON.stringify(Oc(e)),"utf8")}function Oc(e){if(Array.isArray(e))return e.map(t=>Oc(t));if(gt(e)){let t={};for(let n of Object.keys(e).sort())t[n]=Oc(e[n]);return t}return e}function Gr(e,t){try{return JSON.parse(e)}catch(n){throw new H(z.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function Mc(e,t){if(e===null)return null;switch(typeof e){case"boolean":case"number":case"string":return e;case"object":if(Array.isArray(e))return e.map(n=>Mc(n,t));if(gt(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=Mc(o,t);return n}break}throw new H(z.INVALID_JSON,`${t} must be JSON-serializable`)}function Um(e,t){if(!Array.isArray(e))throw new H(z.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!Ge(n))throw new H(z.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function Oi(e,t){if(!Ge(e))throw new H(z.INVALID_PATH,`${t} must be a sha256 digest`)}function Ge(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function en(e){return`sha256:${xR("sha256").update(e).digest("hex")}`}function DR(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function qt(e,t,n){try{return await ve.readFile(e)}catch(r){throw new H(t,`${n} not found: ${e}`,{cause:r})}}async function Dc(e){try{return await ve.readFile(e)}catch(t){if(Qr(t))return null;throw t}}function Vc(e,t,n){if(en(e)!==t)throw new H(z.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function Ue(e){try{return await ve.access(e),!0}catch(t){if(Qr(t))return!1;throw t}}async function Di(e){try{await ve.rm(e,{force:!0,recursive:!0})}catch{}}async function Lc(e){try{let t=await ve.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function Li(e){try{return await ve.readdir(e)}catch(t){if(Qr(t))return[];throw t}}function LR(e){if(typeof e!="string"||e.trim().length===0)throw new H(z.INVALID_ROOT,"history store rootDir must be a non-empty string");return ke.resolve(e)}function ji(e){return ke.join(e,SR)}function wc(e){return ke.join(e,ER)}function BR(e){return ke.join(e,vR)}function Km(e){return ke.join(e,IR)}async function Om(e){try{let t=await ve.readFile(Km(e),"utf8"),n=Gr(t,"document version");if(!gt(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new H(z.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(Qr(t))return 0;throw t}}async function _i(e){let t=await qt(e,z.RECOVERY_PENDING,"transaction journal"),n=Gr(Buffer.from(t).toString("utf8"),"transaction journal");return Jm(n),n}function Jm(e){if(!gt(e)||e.schemaVersion!==bR||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!CR(e.historyTransition)||!Array.isArray(e.files))throw new H(z.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!gt(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!Ge(t.preDigest)||t.postDigest!==null&&!Ge(t.postDigest))throw new H(z.INVALID_SCHEMA,"transaction journal file digest is invalid")}function jR(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function Yr(e){return ke.join(e,"entries")}function Zr(e){return ke.join(e,"blobs")}function Wr(e){return ke.join(e,"tmp")}function Uc(e){return ke.join(Wr(e),"stages")}function Kc(e,t){return ke.join(Uc(e),`${t}.json`)}function Jc(e,t){return ke.join(Yr(e),`${Wm(t)}.json`)}function Xc(e,t){return ke.join(Zr(e),Wm(t))}function zc(e,t){return ke.join(Yr(e),`${t}.json`)}function Wc(e,t){return ke.join(Zr(e),t)}async function Xm(e,t){return zm(Jc(e,t),zc(e,t))}async function Hc(e,t){return zm(Xc(e,t),Wc(e,t))}async function zm(e,t){return await Ue(e)?e:await Ue(t)?t:e}function Wm(e){return e.slice(7)}function Mm(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return Ge(t)?t:null}function gt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Qr(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function $R(e){return{maxEntries:e?.maxEntries??Fi.maxEntries,maxSessionBytes:e?.maxSessionBytes??Fi.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??Fi.maxEntryBytes}}async function VR(e){let t=ji(e);await Ue(t)||await $c(e,[],-1)}import{createHash as UR}from"node:crypto";import{computeSiteEditCompositionKey as Gm,ManagedPageTemplateRouteManifestV1Schema as KR}from"@vcp-dev/contracts";var JR="app/_vcp/page-templates/runtime.tsx",Ym=".vcp/page-templates/routes/",XR="app/_vcp/page-templates/routes/";function Zm(e){return e.startsWith(Ym)&&e.endsWith(".json")}var De=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function Zn(e){let t=xi(e);return UR("sha256").update(t,"utf8").digest("hex").slice(0,16)}function Vi(e){return e.replace(/[^A-Za-z0-9_-]/g,"_")}function qr(e,t){let n=Zn(e),r=`${XR}${n}`,o=Vi(t);return{routeRoot:r,manifestFile:`${Ym}${n}.json`,runtimeFile:JR,registryFile:`${r}/registry.ts`,templateEntryFile:`${r}/templates/${o}/page.tsx`}}function Qm(e){let t=ZR(e),n=new Map;for(let r of t){let o=Vi(r),i=n.get(o);if(i!==void 0&&i!==r)throw new De("PAGE_TEMPLATE_ID_COLLISION",`Page-template IDs ${JSON.stringify(i)} and ${JSON.stringify(r)} map to the same safe name ${JSON.stringify(o)}.`,{reason:"safe-name-collision",templateId:r,safeName:o});n.set(o,r)}}function Gc(e){let t=xi(e.routeId),n=qm(e.files),r=qr(t,""),o=n.get(r.manifestFile);if(o===void 0)return null;let i=GR(t,r.manifestFile,o);return YR({routeId:t,manifest:i,files:n}),i}function zR(e){let t=xi(e.selector.routeId),n=vn(e.canonicalEntryFile),r=Gc({routeId:t,files:e.files});if(r===null){if(e.selector.templateId!==void 0)throw new De("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Page-template selection ${JSON.stringify(e.selector.templateId)} cannot be resolved without a managed manifest for ${JSON.stringify(t)}.`,{reason:"template-selection-without-manifest",routeId:t,templateId:e.selector.templateId});return{mode:"direct",context:{routeId:t},entryFile:n,effectiveEntryFile:n}}if(vn(r.canonical_entry_file)!==n)throw new De("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Managed page-template manifest for ${JSON.stringify(t)} does not match the supplied canonical entry.`,{reason:"canonical-entry-mismatch",routeId:t,path:r.canonical_entry_file});let o=e.selector.templateId??null,i=(o?r.templates.find(c=>c.template_id===o):void 0)??r.templates.find(c=>c.template_id===r.default_template_id);if(!i)throw new De("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Managed page-template manifest for ${JSON.stringify(t)} has no resolvable default template.`,{reason:"default-entry-missing",routeId:t});let a={context:{routeId:t,effectiveTemplateId:i.template_id},entryFile:vn(i.entry_file)};return{...a,mode:"delegated",effectiveEntryFile:a.entryFile}}function WR(e){let t=qm(e.files),n=[...t.keys()].map(l=>({path:l})),r=$r(n),o=new Set,i=new Map;for(let l of r){if(o.has(l.routeId))throw new De("PAGE_TEMPLATE_ROUTE_AMBIGUOUS",`Multiple canonical page entries resolve to route ${JSON.stringify(l.routeId)}.`,{reason:"duplicate-route-id",routeId:l.routeId,candidates:r.filter(p=>p.routeId===l.routeId).map(p=>p.entryFile)});o.add(l.routeId);let u=Zn(l.routeId),d=i.get(u);if(d!==void 0&&d!==l.routeId)throw new De("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Page-template route-key collision between ${JSON.stringify(d)} and ${JSON.stringify(l.routeId)}.`,{reason:"route-key-collision",routeId:l.routeId});i.set(u,l.routeId)}let s=new Set(r.map(l=>qr(l.routeId,"").manifestFile));for(let l of t.keys())if(Zm(l)&&!s.has(l))throw new De("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Managed page-template manifest ${JSON.stringify(l)} does not belong to a scanned canonical route.`,{reason:"unknown-manifest",path:l});let a=[];for(let l of r){let u=Gc({routeId:l.routeId,files:t});if(u===null){let d={routeId:l.routeId};a.push(HR(d,l.entryFile));continue}for(let d of[...u.templates].sort(QR)){let p={routeId:l.routeId,effectiveTemplateId:d.template_id},m={context:p,entryFile:vn(d.entry_file)};a.push({key:Gm(p),composition:m})}}let c=new Set;for(let{key:l,composition:u}of a){if(c.has(l))throw new De("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Duplicate site-edit composition key for ${JSON.stringify(l)}.`,{reason:"duplicate-composition-key",routeId:u.context.routeId});c.add(l)}return a.sort((l,u)=>qR(l.composition,u.composition)||$i(l.key,u.key)).map(({composition:l})=>l)}function HR(e,t){return{key:Gm(e),composition:{context:e,entryFile:t}}}function qm(e){let t=new Map;if(tw(e)){for(let n of e)Hm(t,n.path,n.content);return t}for(let[n,r]of e)Hm(t,n,r);return t}function Hm(e,t,n){let r=vn(t);if(e.has(r))throw new De("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Snapshot contains duplicate file path ${JSON.stringify(r)}.`,{reason:"duplicate-file-path",path:r});e.set(r,n)}function GR(e,t,n){let r;try{r=JSON.parse(n)}catch{throw new De("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Managed page-template manifest ${JSON.stringify(t)} is not valid JSON.`,{reason:"invalid-json",routeId:e,path:t})}let o=KR.safeParse(r);if(!o.success)throw new De("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Managed page-template manifest ${JSON.stringify(t)} does not match the known manifest contract.`,{reason:"schema-invalid",routeId:e,path:t,issues:o.error.issues.map(i=>`${i.path.join(".")||"manifest"}: ${i.message}`)});return o.data}function YR(e){let{routeId:t,manifest:n,files:r}=e,o=qr(t,""),i=$r([...r.keys()].map(l=>({path:l}))).filter(l=>l.routeId===t);if(n.route_id!==t&&kt(t,"route-id-mismatch",o.manifestFile),n.route_key!==Zn(t)&&kt(t,"route-key-mismatch",o.manifestFile),i.length!==1)throw new De("PAGE_TEMPLATE_ROUTE_AMBIGUOUS",`Managed page-template route ${JSON.stringify(t)} has ${i.length} canonical entries.`,{reason:i.length===0?"canonical-entry-missing":"duplicate-route-id",routeId:t,candidates:i.map(l=>l.entryFile)});let s=vn(n.canonical_entry_file);(s!==i[0].entryFile||!r.has(s))&&kt(t,"canonical-entry-mismatch",s),n.default_template_id!==`vcp-default:${Zn(t)}`&&kt(t,"default-template-id-mismatch",o.manifestFile),Qm(n.templates);let a=new Set,c=new Set;for(let l of n.templates){let u=qr(t,l.template_id),d=vn(l.entry_file),p=Vi(l.template_id);l.safe_name!==p&&kt(t,"safe-name-mismatch",o.manifestFile,{templateId:l.template_id}),a.has(l.safe_name)&&kt(t,"duplicate-safe-name",o.manifestFile,{templateId:l.template_id}),a.add(l.safe_name),c.has(d)&&kt(t,"duplicate-entry-file",o.manifestFile,{templateId:l.template_id}),c.add(d),ew(d,u.routeRoot)||kt(t,"entry-outside-route-root",d,{templateId:l.template_id}),d!==u.templateEntryFile&&kt(t,"entry-path-mismatch",d,{templateId:l.template_id}),r.has(d)||kt(t,"template-entry-missing",d,{templateId:l.template_id})}}function kt(e,t,n,r={}){throw new De("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Managed page-template source for ${JSON.stringify(e)} failed validation (${t}).`,{reason:t,routeId:e,path:n,...r})}function ZR(e){return Array.isArray(e)?e.length===0||typeof e[0]=="string"?e:e.map(t=>t.template_id):"rawTemplateIds"in e?e.rawTemplateIds:"templateIds"in e?e.templateIds:[]}function QR(e,t){return+(t.kind==="default")-+(e.kind==="default")||$i(e.template_id,t.template_id)}function qR(e,t){let n=$i(e.context.routeId,t.context.routeId);if(n!==0)return n;let r=e.context.effectiveTemplateId,o=t.context.effectiveTemplateId;if(r===void 0)return-1;if(o===void 0)return 1;let s=`vcp-default:${Zn(e.context.routeId)}`,a=r===s;return Number(o===s)-Number(a)||$i(r,o)}function $i(e,t){return e<t?-1:e>t?1:0}function ew(e,t){return e.startsWith(`${t}/`)}function vn(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function tw(e){return Array.isArray(e)}export{H as FileHistoryStoreError,De as PageTemplateManagedSourceError,Ti as PreviewFileSystemSiteEditEngineRuntime,fp as SITE_EDIT_RAW_COLOR_LITERAL_RE,Pi as SnapshotSiteEditEngineRuntime,Qm as assertNoPageTemplateSafeNameCollision,qr as computeManagedPageTemplatePaths,Zn as computePageTemplateRouteKey,Vi as computePageTemplateSafeName,yR as createPreviewSiteEditEngineRuntime,pR as createSiteEditEngineRuntime,Zm as isManagedPageTemplateManifestPath,Dm as openFileHistoryStore,Gc as parseManagedPageTemplateManifest,zR as resolveManagedPageTemplateComposition,WR as scanSiteEditCompositionsFromFiles,Mr as scanSiteEditThemeStyleViolations};
12
+ `||p==="\r"))return Hn(t,`Unterminated string literal in ${t}.`);l=p===`
13
+ `||p==="\r";continue}if(p==="/"&&m==="*"){s=!0,d+=1,l=!1;continue}if(n==="mdx"&&p==="/"&&m==="/"){a=!0,d+=1,l=!1;continue}if(p==="'"||p==='"'||n==="mdx"&&p==="`"){o=p,l=!1;continue}if(p==="{"||p==="("||p==="["){r.push({char:p,offset:d}),l=!1;continue}if(p==="}"||p===")"||p==="]"){let g=p==="}"?"{":p===")"?"(":"[",b=r.pop();if(!b||b.char!==g)return Hn(t,`Unexpected closing token "${p}" in ${t}.`);l=!1;continue}l=p===`
14
+ `||p==="\r"}if(s)return Hn(t,`Unterminated block comment in ${t}.`);if(o)return Hn(t,`Unterminated string literal in ${t}.`);if(c)return Hn(t,`Unterminated MDX code fence in ${t}.`);let u=r.at(-1);return u?Hn(t,`Unclosed token "${u.char}" in ${t}.`):{ok:!0}}function Hn(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function Ur(e){let t="idle",n=e.fileSystem??lC(),r=Gf(),o=sm({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?Gp(e.historyStore):uC()),u=Hf(n,{externalAdapters:e.externalAdapters}),d=new Map,p=new Set,m=0,g=e.historyStore?.recoveryRequired??!1,b=dc(),C=O();function I(f){return(Ei.isAbsolute(f)?Ei.relative(e.projectRoot,f):f).replace(/\\/g,"/").replace(/^\.\//,"")}function w(f,h){let y=Ei.posix.dirname(f),E=h.replace(/\.(?:tsx?|jsx?)$/i,""),R=Ei.posix.relative(y,E);return R.startsWith(".")?R:`./${R}`}function A(f,h){return f.startLine===h.startLine&&f.startColumn===h.startColumn&&f.endLine===h.endLine&&f.endColumn===h.endColumn}async function O(){let f=e.historyStore;if(f)try{let h=await f.readTransactionJournal();if(!h)return;let y=await f.readIndex(),E=await Promise.all(h.files.map(async P=>await n.exists(P.path)?fe(await n.readFile(P.path)):null));if(om({journal:h,index:y,observedFileDigests:E})!=="ambiguous"){await f.clearTransactionJournal(h.transactionId);let P=await f.readStatus();P.recoveryRequired||(await f.cleanupTmp(),P=await f.readStatus()),g=P.recoveryRequired;return}await f.markRecoveryRequired(`Ambiguous transaction journal ${h.transactionId} at phase ${h.phase}`),g=!0}catch(h){g=!0,await f.markRecoveryRequired(`Transaction journal recovery failed: ${Le(h)}`).catch(()=>{})}}function ie(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let f of o.entries){let h=dm(f.context,f.entryFile);i.set(f.key,h),oe(h,h.dependencyFiles)}function oe(f,h){let y=new Set(h);N(f),f.dependencyFiles=y;for(let E of f.dependencyFiles){let R=s.get(E);R||(R=new Set,s.set(E,R)),R.add(f.key)}}function N(f){for(let h of f.dependencyFiles){let y=s.get(h);y&&(y.delete(f.key),y.size===0&&s.delete(h))}f.dependencyFiles.clear()}function W(f){let h=new Set;for(let y of f)for(let E of s.get(y)??[])h.add(E);return h}function M(f){for(let h of f)if(!s.has(h))return!1;return!0}async function j(f,h,y,E,R){let P=new Map,_=Qd(R.values()),L=new Map,F=typeof n.exists=="function"?$=>n.exists($):async()=>!1;for(let[$,J]of f.elements){let de=h.nodes.get($);if(!de)continue;let te=y.get(J.sourceFile)??E.get(J.sourceFile),ye=new Map,Se=new Map,Ee=new Map,xe=[];for(let me of J.textSegments){if(!te){ye.set(me.index,null);continue}let Yn=await qd({file:J.sourceFile,source:te,segment:me,readFile:Ke=>n.readFile(Ke),exists:F,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Ke,adapterId:en,capabilities:zi})=>({sourceType:Ke,adapterId:en,capabilities:zi})),functionCallContracts:e.functionCallContracts,fileCache:_}),De=await Ea({file:J.sourceFile,source:te,target:{kind:"text-segment",segment:me},readFile:Ke=>n.readFile(Ke),exists:F,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Ke,adapterId:en,capabilities:zi})=>({sourceType:Ke,adapterId:en,capabilities:zi})),functionCallContracts:e.functionCallContracts,fileCache:_}),Ye=EC(Yn);ye.set(me.index,Ye),Se.set(me.index,Yn),Ee.set(me.index,De),xe.push({editable:me.editable,source:Ye})}let T=new Map,V=new Map;if(te)for(let me of J.attributes??[]){let Yn=await Xn({file:J.sourceFile,source:te,sourceRange:me.sourceRange,expression:me.source?.expression??me.value,sourceInfo:me.source,readFile:Ye=>n.readFile(Ye),exists:F,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Ye,adapterId:Ke,capabilities:en})=>({sourceType:Ye,adapterId:Ke,capabilities:en})),functionCallContracts:e.functionCallContracts,fileCache:_}),De=await Yf({element:J,file:J.sourceFile,source:te,propertyName:me.name,readFile:Ye=>n.readFile(Ye),exists:F,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Ye,adapterId:Ke,capabilities:en})=>({sourceType:Ye,adapterId:Ke,capabilities:en})),functionCallContracts:e.functionCallContracts,fileCache:_});V.set(me.name,De),T.set(me.name,Yn)}let U=Cu(vC(de.writeTarget),xe),se=Au({key:$,element:J,graph:f,provenances:Ee}),rt=Ou(J),ot=Mu(J),kn=Du(J),eo=te?await wf({element:J,graph:f,file:J.sourceFile,source:te,readFile:me=>n.readFile(me),exists:F,fileCache:L}):void 0,Ae=f.regions.find(me=>me.kind==="conditional-region"&&me.childKeys.includes($)),to,Xi=Ae?.sourceCandidates?.[0];if(te&&Ae&&Xi?.kind==="conditional-branch"){let me=await Ea({file:J.sourceFile,source:te,target:{kind:"conditional-branch",candidate:Xi},readFile:De=>n.readFile(De),exists:F,graph:f,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:De,adapterId:Ye,capabilities:Ke})=>({sourceType:De,adapterId:Ye,capabilities:Ke})),functionCallContracts:e.functionCallContracts,fileCache:_});to={currentBranch:Ae.childKeys.indexOf($)<=0?"then":"else",availableBranches:Ae.childKeys.length>1?["then","else"]:["then"],conditionExpression:Xi.conditionExpression,provenance:{finalSource:me.finalSource?{kind:me.finalSource.kind,file:me.finalSource.file,displayPath:me.finalSource.displayPath}:null,chain:me.chain.map(De=>({kind:De.kind,file:De.file,displayName:De.displayName,canEditHere:De.canEditHere})),confidence:me.confidence,editMode:me.editMode,diagnostics:me.diagnostics.map(De=>({code:De.code,message:De.message}))}}}P.set($,{textSources:ye,textTargets:Se,elementPropertyTargets:T,propertyProvenances:V,isRepeat:LC($,f),provenances:Ee,writeTarget:U,componentSemantic:se,contentModel:rt,mediaModel:ot,styleSource:kn,conditional:to,dynamicData:eo})}return P}function Q(f){return typeof n.getVersion=="function"?n.getVersion(f):0}function re(f,h){let y=o.initialVersions.get(f.key)??0;for(let E of h.values())y=Math.max(y,E);return Math.max(y,f.graph?.version??0)}function be(f){return i.get(f)?.graph?.version??o.initialVersions.get(f)??0}function G(f){try{return be(o.resolveSelector(f.composition).key)}catch{return 0}}async function ee(f,h,y={}){let E=i.get(f);if(!E)return null;let R=y.sourceCache??fc(d,[]),P=await Ie(E.entryFile),{graph:_,allSources:L,diagnostics:F,parsedModules:$,entryModule:J}=await kl(E.entryFile,h,Ae=>n.readFile(Ae),typeof n.exists=="function"?Ae=>n.exists(Ae):async()=>!1,{additionalEntries:P,version:E.graph?.version??1});if(F.length>0)throw new $r(F);let de=new Map;for(let Ae of L.keys())de.set(Ae,Q(Ae));let te=Math.max(re(E,de),y.minimumVersion??0);y.changed&&te<=(E.graph?.version??0)&&(te=(E.graph?.version??0)+1),_.version=te;for(let[Ae,to]of L)pc(R,Ae,to,cm);let ye=await Ft(E.composition,E.entryFile,L,R);_.routeId=E.routeId,_.composition=E.composition;let Se=Cl(_),Ee=wl(Se,_),xe=await j(_,Se,L,R,$),T=Qm(_,Ee,xe),V=Zm(xe),U=BC(Su(_,Se,Ee,{canUpdateTextByKey:T,dynamicDataSummaryByKey:V}),_,xe),se=fu({route:E.routeId,composition:E.composition,entryFile:E.entryFile,version:te,source:h,ast:J?.ast}),rt=pu(se);se.ok&&wC(U,_,se.projection);let ot={...U,composition:E.composition,...ye?{styleContext:ye}:{},pageComposition:rt},kn=new Set([E.entryFile,...L.keys()]);if(ye){kn.add(ye.entryCss.path);for(let Ae of ye.stylesheets)kn.add(Ae.path)}let eo={...E,dependencyFiles:kn,graph:_,topology:Se,capabilities:Ee,document:ot,pageComposition:rt,pageCompositionProjection:se.projection,pagePlacementByKey:se.ok?se.projection.placementByKey:null,pagePlacementUnitByKey:se.ok?se.projection.placementUnitByKey:null,pageUnitByKey:se.ok?se.projection.unitByKey:null,pagePlacementsByUnitKey:se.ok?se.projection.placementsByUnitKey:null,documentIndex:mC(ot),detailProjections:xe,fileVersions:de,styleContext:ye};if(y.publish===!1)return eo;Wn(d,R);for(let Ae of R.keys())p.delete(Ae);return oe(E,kn),Object.assign(E,eo),E}async function Ie(f){let h=[];for(let y of TC(f))typeof n.exists=="function"&&await n.exists(y)&&h.push({file:y,source:await n.readFile(y)});return h}async function Ft(f,h,y,E){let R=[];for(let[$,J]of y){if(hc($)){R.push($);continue}for(let de of _C(J)){let te=hm($,de);te&&R.push(te)}}if(!R.length){for(let $ of FC(h))if(await Wc($)){R.push($);break}}let P=new Map,_=Em(R).slice(0,am);for(;_.length>0&&P.size<am;){let $=_.shift();if(P.has($)||!hc($))continue;let J=await _t($,E);if(J!==null){P.set($,{path:$,content:J});for(let de of OC(J)){let te=hm($,de);te&&!P.has(te)&&!_.includes(te)&&_.push(te)}}}let L=[...P.values()].map($=>({...$,hash:fe($.content)})),F=L[0];return F?{composition:f,revision:fe(JSON.stringify(L.map(({path:$,hash:J})=>({path:$,hash:J})))),entryCss:F,stylesheets:L.slice(1)}:null}async function _t(f,h){let y=h.get(f);if(y!==void 0)return y;if(!await Wc(f))return null;let E=await n.readFile(f);return pc(h,f,E,cm),E}async function Wc(f){return typeof n.exists=="function"?n.exists(f):!1}function Zm(f){let h=new Map;for(let[y,E]of f)E.dynamicData?.bindings.length&&h.set(y,Bf(E.dynamicData.bindings));return h}function Qm(f,h,y){let E=new Map;for(let[R,P]of f.elements){if(!h.get(R)?.canUpdateText){E.set(R,!1);continue}let L=y.get(R),F=P.textSegments.some($=>{if(!$.editable)return!1;let J=L?.provenances.get($.index)??null;return!J||qm(J)});E.set(R,F)}return E}function qm(f){return f.editMode==="direct"||f.editMode==="proxy"||f.editMode==="upstream"}async function Zr(f,h={}){let y=[...new Set(f)],E=h.affectedCompositionKeys!==void 0,R=E?new Set(h.affectedCompositionKeys):W(y);if(!E&&(R.size===0||!M(y)))for(let F of i.values())Hc(F,y)&&R.add(F.key);let P=!E&&R.size===0&&y.some(gm),_=h.publish===!1?fc(d,y):void 0,L={rebuiltRoutes:[],failedRoutes:[],...h.publish===!1?{candidateRouteStates:[],candidateSourceCache:_}:{}};for(let F of i.values())if(!(h.excludedCompositionKeys?.has(F.key)||!(R.has(F.key)||P)))try{let J=!!F.graph,de=await n.readFile(F.entryFile),te=await ee(F.key,de,{...h,..._?{sourceCache:_}:{}});te?.graph&&(L.rebuiltRoutes.push({documentChanged:J,composition:F.composition,routeId:F.routeId,version:te.graph.version}),L.candidateRouteStates?.push({composition:F.composition,key:F.key,routeId:F.routeId,state:te}))}catch(J){L.failedRoutes.push({...rm(F.routeId,J),composition:F.composition})}return L}function En(f){let h=[...new Set(f)],y=W(h);if(y.size>0&&M(h))return[...y];for(let E of i.values())Hc(E,h)&&y.add(E.key);return[...y]}function eg(f){let h=new Set(En(f));return o.entries.filter(y=>h.has(y.key)).map(y=>y.context)}function tg(f){return[...new Set(En(f))].sort((y,E)=>y<E?-1:y>E?1:0).map(y=>o.getByKey(y)?.context).filter(y=>y!==void 0)}function ng(f,h){let y=new Set(En(h)),E=f.provenance?.affectedCompositions??[];if(E.length===0)return y;if([...new Set(E.map(P=>o.resolveContext(P).key))].some(P=>!y.has(P)))throw new Error("History provenance does not match the affected composition index.");return y}function rg(f,h){let y=f.composition??f.provenance?.initiatingComposition;if(y){let P=o.resolveContext(y);return{context:P.context,key:P.key}}let E=[...new Set(En(h))];if(E.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${E.length}).`);let R=o.getByKey(E[0]);if(!R)throw new Error("Legacy history entry references an unknown affected composition.");return{context:R.context,key:R.key}}function ji(f,h){r.emit({type:"operation-completed",composition:f.composition,result:f});for(let{composition:y,version:E}of h.rebuiltRoutes)r.emit({type:"document-changed",composition:y,version:E});for(let{composition:y,message:E}of h.failedRoutes)r.emit({type:"graph-error",composition:y,message:E})}function Hc(f,h){return h.some(y=>f.dependencyFiles.has(y)||f.entryFile===y||f.graph?.fileIndex.has(y))}function Gc(f){for(let h of f)a.add(h);c||ie()||(c=(async()=>{t="building";let h=!1;try{for(;a.size>0;){if(ie())return;await og();let y=[...a];a.clear();let E=await Yc(y);if(E.length===0)continue;let R=En(E);for(let L of R){let F=i.get(L)?.composition;F&&r.emit({type:"graph-invalidated",composition:F})}let{rebuiltRoutes:P,failedRoutes:_}=await Zr(E,{changed:!0});for(let{documentChanged:L,composition:F,version:$}of P)r.emit({type:"graph-ready",composition:F,version:$}),L&&r.emit({type:"document-changed",composition:F,version:$});for(let{composition:L,message:F}of _)h=!0,r.emit({type:"graph-error",composition:L,message:F})}}finally{c=null,t!=="disposed"&&(t=!h&&[...i.values()].some(y=>y.graph)?"ready":"idle"),a.size>0&&Gc([])}})())}async function og(){for(;m>0;)await new Promise(f=>setTimeout(f,0))}async function Yc(f){let h=[];for(let y of new Set(f)){let E=d.get(y);if(E===void 0){if(p.has(y)&&!await n.exists(y))continue;p.delete(y),h.push(y);continue}try{await n.readFile(y)!==E&&(p.delete(y),h.push(y))}catch(R){if(!RC(R))try{if(await n.exists(y))continue}catch{continue}p.add(y),h.push(y)}}return h}function Zc(f){tm(d,f);for(let h of f)h.exists===!1?p.add(h.file):p.delete(h.file)}function Qc(f){p.clear();for(let h of f)p.add(h)}async function qc(f){let h=await Yc(f);if(h.length===0)return;let y=En(h);for(let P of y){let _=i.get(P)?.composition;_&&r.emit({type:"graph-invalidated",composition:_})}let{rebuiltRoutes:E,failedRoutes:R}=await Zr(h,{changed:!0});for(let{documentChanged:P,composition:_,version:L}of E)r.emit({type:"graph-ready",composition:_,version:L}),P&&r.emit({type:"document-changed",composition:_,version:L});for(let{composition:P,message:_}of R)r.emit({type:"graph-error",composition:P,message:_})}async function ig(f,h){let y=Gn(f,h);if(!y?.graph)return;let E=Ve(f)??f,R=y.graph.elements.get(E);R&&await qc([R.sourceFile])}async function el(f){let h=new Set;if(f.target.kind==="node"){let y=Gn(f.target.key,f.composition),E=Ve(f.target.key)??f.target.key,R=y?.graph?.elements.get(E);R&&h.add(R.sourceFile)}else if(f.target.kind==="route"){let y=i.get(o.resolveSelector(f.target.composition).key);y&&h.add(y.entryFile)}else if(f.target.kind==="page-unit"){let y=i.get(o.resolveSelector(f.target.composition).key);y&&h.add(y.entryFile)}else if(f.target.kind==="source-file")h.add(f.target.path);else if(f.target.kind==="source-batch")for(let y of f.target.paths)h.add(y);await qc(h)}async function sg(f){if(f.params.kind!=="source-edit")return $i(f,"invalid-params","source-edit requires source-edit params");for(let h of f.params.edits){let y=CC(h);if(!y.ok)return $i(f,y.errorCode,y.message,y.details)}m+=1;try{let h=await dg(f.params.edits);if(!h.ok)return $i(f,h.errorCode,h.message,h.details);await el(f);let y={operationId:f.id,kind:"source-edit",target:f.target,documentVersion:f.documentVersion,conflictPolicy:f.params.conflictPolicy,edits:f.params.edits.map(E=>E.operation==="delete"?{operation:"delete",file:E.path,baseContentHash:E.baseContentHash??null}:{operation:"upsert",file:E.path,baseContentHash:E.baseContentHash??null,content:E.content})};return await In({request:f,filePlan:y})}catch(h){return{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:G(f),error:{code:D.INTERNAL_ERROR,message:Le(h)}}}finally{m-=1}}async function ag(f){if(f.target.kind!=="project"||f.params.kind!=="insert-page-resource")return Z(f,D.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");m+=1;try{let h=await rc({files:[...f.params.artifact.components.flatMap(E=>E.materialization.files.map(R=>({path:R.pathTemplate,content:R.content}))),...f.params.artifact.pages.flatMap(E=>E.materialization.files.map(R=>({path:R.pathTemplate,content:R.content})))],exists:E=>n.exists(E),readFile:E=>n.readFile(E)});if(!h.ok)return Z(f,D.MATERIALIZATION_REJECTED,h.message);let y=await tc({artifact:f.params.artifact,exists:E=>n.exists(E)});return y.ok?await In({request:f,filePlan:{operationId:f.id,kind:"source-edit",target:f.target,documentVersion:f.documentVersion,conflictPolicy:"overwrite",edits:y.files},output:{kind:"insert-page-resource",package_instance_id:y.packageInstanceId,pages:y.pages},historyPolicy:"none"}):Z(f,y.code==="MATERIALIZATION_CONFLICT"?D.MATERIALIZATION_CONFLICT:D.MATERIALIZATION_REJECTED,y.message,y.path?{path:y.path}:void 0)}catch(h){return Z(f,D.INTERNAL_ERROR,Le(h))}finally{m-=1}}async function cg(f){if(f.target.kind!=="project"||f.params.kind!=="delete-page-source")return Z(f,D.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return Z(f,D.PLAN_FAILED,"Complete project file listing is required for page deletion.");m+=1;try{let h=xm(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(h.truncated)return Z(f,D.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:h.truncated.reasons});let y=h.files.filter(({path:_})=>/\.(?:tsx?|jsx?)$/.test(_)),E=Object.fromEntries(await Promise.all(y.map(async({path:_})=>[_,await n.readFile(_)]))),R=Kp({expectedUrlPath:f.params.expectedUrlPath,files:E});if(!R.ok)return Z(f,R.code==="HOME_PAGE_LOCKED"?D.HOME_PAGE_LOCKED:R.code==="ROUTE_NOT_FOUND"?D.ROUTE_NOT_FOUND:D.PLAN_FAILED,R.message);let P=await Promise.all(R.edits.map(async _=>({..._,baseContentHash:fe(await n.readFile(_.file))})));return In({request:f,filePlan:{operationId:f.id,kind:"source-edit",target:f.target,documentVersion:f.documentVersion,conflictPolicy:"compare-and-swap",edits:P},output:{kind:"delete-page-source",deleted_files:R.deletedFiles,updated_files:R.updatedFiles,preserved_shared_files:R.preservedSharedFiles,warnings:R.warnings},historyPolicy:"none"})}catch(h){return Z(f,D.INTERNAL_ERROR,Le(h))}finally{m-=1}}async function lg(f,h){if(f.kind!=="insert-child"&&f.kind!=="replace-node")return Z(f,D.UNSUPPORTED_OPERATION,"Only page-unit insert-child and replace-node materialization are supported by this transaction.");if(f.params.kind!=="insert-child"&&f.params.kind!=="replace-node"||f.kind!==f.params.kind)return Z(f,D.INVALID_PARAMS,"Page-unit materialization operation kind must match its params.");if(f.params.kind==="insert-child"){if(!("kind"in f.params.position)||f.params.position.kind!=="page-composition")return Z(f,D.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(f.params.position.documentVersion!==f.documentVersion)return Z(f,D.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.")}let y=h.document,E=h.pageCompositionProjection;if(!y||y.pageComposition?.status!=="supported"||!E||E.status!=="supported")return Z(f,D.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(f.documentVersion!==y.version||E.documentVersion!==y.version)return Z(f,D.VERSION_STALE,`Document version ${f.documentVersion} is stale (current: ${y.version}).`);let R=f.params.node.kind==="component-call"?f.params.node.materialization:void 0;if(!R)return Z(f,D.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let P=f.params.kind==="insert-child"?f.params.position:null,_=await rc({files:R.files.map(F=>({path:F.pathTemplate,content:F.content})),exists:F=>n.exists(F),readFile:F=>n.readFile(F)});if(!_.ok)return Z(f,D.MATERIALIZATION_REJECTED,_.message);let L=await xp({manifest:R,generatedRoot:"components/site/generated",controlledFiles:R.files.map(F=>({pathTemplate:F.pathTemplate})),exists:F=>n.exists(F),commit:async F=>{let $=await n.readFile(h.entryFile),J=h.document,de=h.pageCompositionProjection;if(!J||J.pageComposition?.status!=="supported"||J.version!==f.documentVersion||!de||de.status!=="supported"||de.documentVersion!==J.version)return{ok:!0,data:Z(f,D.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let te=F.entry.path,ye=xg(F.instanceName),Se,Ee=[];if(f.params.kind==="insert-child"){if(!P||!("kind"in P)||P.kind!=="page-composition")return{ok:!0,data:Z(f,D.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.")};let U=Rs({routeId:h.routeId,entryFile:h.entryFile,currentDocumentVersion:J.version,expectedDocumentVersion:f.documentVersion,source:$,projection:de,placementKey:P.placementKey,component:{source:te,exportName:F.entry.export.kind==="default"?"default":F.entry.export.name,localName:ye}});if(!U.ok)return{ok:!0,data:Z(f,Ji(U.error.code),U.error.message,{diagnostics:U.error.diagnostics})};let se=U.plan.returnStep?cu({source:$,jsx:U.plan.returnStep.node.jsx,placement:U.plan.returnStep.placement,...U.plan.returnStep.replaceOriginal?{replaceOriginal:!0}:{}}):U.plan.insertStep?.parentLocator?_n({source:$,locator:U.plan.insertStep.parentLocator,node:U.plan.insertStep.node,placement:U.plan.insertStep.placement,...U.plan.insertStep.anchorLocator?{anchorLocator:U.plan.insertStep.anchorLocator}:{}}):{ok:!1,source:$,diagnostic:{code:"unsupported-syntax",message:"Route composition rewrite has no insertion step."}};if(!se.ok)return{ok:!0,data:Z(f,D.AST_PARSE_ERROR,se.diagnostic.message)};Se=se.source}else{let U=ws({routeId:h.routeId,composition:h.composition,entryFile:h.entryFile,currentDocumentVersion:J.version,expectedDocumentVersion:f.documentVersion,source:$,projection:de,placementUnitKey:f.target.placementUnitKey,operation:"remove-node"});if(!U.ok)return{ok:!0,data:Z(f,Ji(U.error.code),U.error.message,{diagnostics:U.error.diagnostics})};if(U.plan.rewriteStep.kind!=="remove-node")return{ok:!0,data:Z(f,D.PLAN_FAILED,"Page-unit replacement did not resolve a replaceable source node.")};let se=ko({source:$,locator:U.plan.rewriteStep.locator,node:{jsx:`<${ye} />`}});if(!se.ok)return{ok:!0,data:Z(f,D.AST_PARSE_ERROR,se.diagnostic.message)};let rt=await tl({routeState:h,placementUnitKey:f.target.placementUnitKey,source:$,mutatedSource:se.source});Se=rt.source,Ee=await Promise.all(rt.files.map(async ot=>({operation:"delete",file:ot,baseContentHash:fe(await n.readFile(ot))})))}let xe=Ln({source:Se,moduleSpecifier:w(h.entryFile,te),imports:F.entry.export.kind==="default"?[{kind:"default",local:ye}]:[{kind:"named",imported:F.entry.export.name,local:ye}]});if(!xe.ok)return{ok:!0,data:Z(f,D.AST_PARSE_ERROR,xe.diagnostic.message)};let T=F.files.map(U=>({operation:"create-only",file:U.path,content:U.content})),V=[{operation:"upsert",file:h.entryFile,content:xe.source,baseContentHash:fe($)},...T,...Ee];m+=1;try{let U=await In({request:f,filePlan:{operationId:f.id,kind:"source-edit",target:{kind:"source-file",path:h.entryFile},documentVersion:f.documentVersion,conflictPolicy:"compare-and-swap",edits:V}});return!U.ok&&U.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:U.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:U}}finally{m-=1}}});return L.ok?L.data:Z(f,D.VERSION_STALE,L.error.message,{materializationCode:L.error.code})}async function ug(f,h){if(f.kind!=="move-node"&&f.kind!=="remove-node")return Z(f,D.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let y=h.document,E=h.pageCompositionProjection;if(!y||y.pageComposition?.status!=="supported"||!E||E.status!=="supported")return Z(f,D.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(f.documentVersion!==y.version||E.documentVersion!==y.version)return Z(f,D.VERSION_STALE,`Document version ${f.documentVersion} is stale (current: ${y.version}).`);let R=await n.readFile(h.entryFile),P=ws({routeId:h.routeId,composition:h.composition,entryFile:h.entryFile,currentDocumentVersion:y.version,expectedDocumentVersion:f.documentVersion,source:R,projection:E,placementUnitKey:f.target.placementUnitKey,operation:f.kind,targetPlacement:f.kind==="move-node"&&f.params.kind==="move-node"&&"kind"in f.params.target&&f.params.target.kind==="page-composition"?f.params.target:void 0});if(!P.ok)return Z(f,Ji(P.error.code),P.error.message,{diagnostics:P.error.diagnostics});let _=P.plan.rewriteStep.kind==="move-node"?Mn({source:R,locator:P.plan.rewriteStep.locator,targetParentLocator:P.plan.rewriteStep.targetParentLocator,placement:P.plan.rewriteStep.placement,...P.plan.rewriteStep.anchorLocator?{anchorLocator:P.plan.rewriteStep.anchorLocator}:{}}):Tn({source:R,locator:P.plan.rewriteStep.locator});if(!_.ok)return Z(f,D.AST_PARSE_ERROR,_.diagnostic.message);let L=_.source,F=[];if(f.kind==="remove-node"){let J=await tl({routeState:h,placementUnitKey:f.target.placementUnitKey,source:R,mutatedSource:L});L=J.source,F=await Promise.all(J.files.map(async de=>({operation:"delete",file:de,baseContentHash:fe(await n.readFile(de))})))}let $=[{operation:"upsert",file:h.entryFile,content:L,baseContentHash:fe(R)},...F];m+=1;try{return await In({request:f,filePlan:{operationId:f.id,kind:"source-edit",target:{kind:"source-file",path:h.entryFile},documentVersion:f.documentVersion,conflictPolicy:"compare-and-swap",edits:$}})}finally{m-=1}}async function tl(f){let h={source:f.mutatedSource,files:[]},y=f.routeState.graph,E=f.routeState.pageCompositionProjection;if(!y||!E||E.status!=="supported"||!n.listFiles)return h;let P=E.placementUnitByKey.get(f.placementUnitKey)?.sourceRange;if(!P)return h;let _=[...y.elements.values()].find(T=>T.sourceFile===f.routeState.entryFile&&T.importedFrom&&A(T.sourceRange,P));if(!_?.importedFrom||!_.exportName)return h;let L=I(_.importedFrom),F="components/site/generated/";if(!L.startsWith(F))return h;let $=L.slice(F.length).split("/")[0];if(!$||!/-[0-9a-f]{8}$/i.test($))return h;let J=`${F}${$}`;if([...y.elements.values()].filter(T=>T.sourceFile===f.routeState.entryFile&&I(T.importedFrom??"")===L).length!==1)return h;let te=await n.listFiles({maxFiles:5e3,maxDepth:32}),ye=Array.isArray(te)?te:te.files;if(!Array.isArray(te)&&te.truncated)return h;let Se=ye.map(({path:T})=>T).filter(T=>T===J||T.startsWith(`${J}/`));if(Se.length===0||!Se.includes(L))return h;for(let{path:T}of ye)if(!(T===f.routeState.entryFile||T===J||T.startsWith(`${J}/`)))try{if((await n.readFile(T)).includes($))return h}catch{return h}let Ee=w(f.routeState.entryFile,L),xe=Bn({source:f.mutatedSource,moduleSpecifier:Ee,imports:_.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:_.exportName}]});return xe.ok?{source:xe.source,files:Se.sort((T,V)=>T.localeCompare(V))}:h}async function dg(f){if(n.getFileInfo){for(let R of f)if(await n.exists(R.path)&&await n.getFileInfo(R.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${R.path}`,details:{path:R.path}}}let h=fg(f);if(h.length===0)return{ok:!0};let y=IC(n,f),E=Ur({projectRoot:e.projectRoot,fileSystem:y,compositions:[...i.values()].map(R=>({context:R.composition,entryFile:R.entryFile})),externalAdapters:e.externalAdapters,externalSourceResolvers:e.externalSourceResolvers,functionCallContracts:e.functionCallContracts,dev:e.dev});try{for(let R of h){let P=i.get(R)?.composition;if(!P)continue;let _={routeId:P.routeId,...P.effectiveTemplateId!==void 0?{templateId:P.effectiveTemplateId}:{}};await E.initializeComposition(_),E.getDocument(_)}}catch(R){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${Le(R)}`,details:{compositionKeys:h}}}finally{E.dispose()}return{ok:!0}}function fg(f){return f.map(y=>y.path).some(gm)?[...i.keys()]:[]}function $i(f,h,y,E){let R=Vr(h);return{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:G(f),error:{code:R,message:y,...E?{details:E}:{}}}}async function Vi(f){let h=[];for(let y of new Set(f))h.push(await pg(y));return h}async function pg(f){if(!(typeof n.exists=="function"?await n.exists(f):!0))return{file:f,content:"",version:Math.max(0,Q(f)),exists:!1};let y=await n.readFile(f);return{file:f,content:y,version:Math.max(1,Q(f)),exists:!0,sha256:fe(y)}}async function nl(f,h,y,E){if(!e.historyStore)return null;let R=new Map(h.map(L=>[L.file,L])),P=new Map(y.map(L=>[L.file,L])),_=[...new Set([...R.keys(),...P.keys()])].sort().map(L=>{let F=R.get(L),$=P.get(L);return{path:L,preDigest:F?.exists===!1||!F?null:fe(F.content),postDigest:$?.exists===!1||!$?null:fe($.content)}});return{schemaVersion:2,transactionId:`${f}:${E.expectedIndexDigest}`,operationId:f,phase:"prepared",historyTransition:E,files:_}}async function rl(f){return!f||!e.historyStore||await e.historyStore.writeTransactionJournal(f),f}async function vn(f){f&&e.historyStore&&await e.historyStore.clearTransactionJournal(f.transactionId)}async function Ui(f,h){let y=[];try{for(let E of f)await ol(E),typeof n.bumpVersion=="function"&&n.bumpVersion(E.file),y.push(E.file)}catch(E){let R=await mg(h.filter(P=>y.includes(P.file)));return R.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${Le(E)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${R.failedFiles.join(", ")}: ${Le(E)}`,rolledBack:!1}}return{ok:!0,snapshots:f.map(gg)}}async function ol(f){if(f.exists===!1){await n.deleteFile(f.file);return}await n.writeFile(f.file,f.content)}async function mg(f){let h=[];for(let y of f)try{await ol(y),typeof n.bumpVersion=="function"&&n.bumpVersion(y.file)}catch{h.push(y.file)}return h.length===0?{ok:!0}:{ok:!1,failedFiles:h}}function gg(f){let h=f.exists!==!1;return{file:f.file,content:h?f.content:"",version:f.version,exists:h,...h?{sha256:fe(f.content)}:{}}}async function In(f){return b.runExclusive(()=>hg(f))}async function hg(f){let h=f.filePlan.edits.map(T=>T.file),y=o.resolveSelector(f.request.composition),E=y.context,R=f.historyPolicy==="none"?void 0:{initiatingComposition:E,affectedCompositions:tg(h)},P=await Vi(h),_=new Map(P.filter(T=>T.exists!==!1).map(T=>[T.file,T.content])),L=sl(),F=new Map(d),$=new Set(p),J=new Set([...i.values()].filter(T=>f.filePlan.edits.some(V=>V.operation==="delete"&&V.file===T.entryFile)).map(T=>T.key)),de=f.filePlan.edits.map(T=>T.operation==="delete"?{file:T.file,content:"",version:0,exists:!1}:{file:T.file,content:T.content,version:0,exists:!0,sha256:fe(T.content)}),te={operationId:f.filePlan.operationId,intents:f.filePlan.edits.map(T=>T.operation==="delete"?{kind:"delete",path:T.file}:{kind:T.operation==="create-only"?"create-only":"upsert",path:T.file,content:T.content})},ye=null,Se=!1,Ee=await xi({overlay:_,exists:T=>n.exists(T),plan:te,buildCandidate:async({plan:T})=>({plan:T}),prepareHistory:async()=>{let T=f.historyPolicy==="none"?null:await l.prepareAppend({composition:o.resolveSelector(f.request.composition).context,operationId:f.request.id,kind:f.request.kind,target:f.request.target,preSnapshots:P,postSnapshots:de,...f.selectionRef?{selectionRef:f.selectionRef}:{},...f.output?{output:f.output}:{},...R?{provenance:R}:{}}),V=T?.historyTransition?T.historyTransition:e.historyStore?cC(await e.historyStore.readIndex()):null;if(e.historyStore&&!V)throw new Error("Durable history did not provide an exact index transition.");return ye=await nl(f.request.id,P,de,V),ye=await rl(ye),{history:T,historyTransition:V}},reverify:async()=>{},writeCandidate:async()=>{let T=await u.executeFilePlan(f.filePlan);if(!T.ok)throw new Ii(T);return{postSnapshots:await Vi(T.affectedFiles),affectedFiles:T.affectedFiles,internalResultVersion:T.resultVersion}},validateCandidate:async({candidate:T,receipt:V})=>{let U=await Zr(V.affectedFiles,{changed:!0,minimumVersion:V.internalResultVersion,publish:!1,excludedCompositionKeys:J});if(U.failedRoutes.length>0)throw new bn(U.failedRoutes);let se=cl(L,U.candidateRouteStates??[]),rt=al(se,y.key);return{...T,rebuild:U,routeSnapshots:se,resultVersion:rt,...fm(f.selectionRef,se.map(ot=>ot.state.document))?{selectionRef:fm(f.selectionRef,se.map(ot=>ot.state.document))}:{}}},publishCandidate:async({candidate:T,history:V,receipt:U})=>{V?.history&&(await l.publishPrepared(V.history),Se=!0);let se=T.resultVersion??U.internalResultVersion;return{composition:E,requestId:f.request.id,kind:f.request.kind,target:f.request.target,ok:!0,resultVersion:se,affectedFiles:U.affectedFiles,...f.output?{output:f.output}:{},...T.selectionRef?{selectionRef:T.selectionRef}:{}}},swapCandidate:({candidate:T,receipt:V})=>{T.routeSnapshots&&Qr(T.routeSnapshots),T.rebuild?.candidateSourceCache&&Wn(d,T.rebuild.candidateSourceCache),Zc(V.postSnapshots)},finalizeCandidate:async()=>{await vn(ye);for(let T of J)i.delete(T)},emitCommitted:({candidate:T,published:V})=>{ji(V,T.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:T,receipt:V})=>{if(Se)throw new Error("history was published before transaction finalization failed");if(V){let U=await Ui(P,V.postSnapshots);if(!U.ok)throw new Error(U.reason)}Qr(L),Wn(d,F),Qc($),T?.history&&await l.discardPrepared?.(T.history),await vn(ye)}});if(Ee.ok)return Ee.published;if(Ee.stage==="precheck"||Ee.stage==="build")try{await vn(ye)}catch(T){let V=await qr(Le(T));return Z(f.request,V,"Unable to clear an uncommitted transaction journal.")}if(Ee.recoveryRequired){let T=await qr(Ee.reason);return Z(f.request,T===D.RECOVERY_PERSIST_FAILED?T:D.ROLLBACK_FAILED,Ee.reason)}let xe=Ee.error;return xe instanceof Ii?{...Z(f.request,Vr(xe.result.errorCode),xe.result.reason),...xe.result.affectedFiles?{affectedFiles:xe.result.affectedFiles}:{}}:xe instanceof bn?Z(f.request,D.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${mc(xe.failedRoutes)}`,{failedRoutes:xe.failedRoutes}):Z(f.request,ul(Ee.stage),Le(xe))}async function il(f){return b.runExclusive(async()=>{let h=f==="undo"?await l.prepareUndo():await l.prepareRedo();return h?yg(f,h):{composition:o.entries[0].context,requestId:f,kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:o.initialVersions.get(o.entries[0].key)??0,error:{code:D.INTERNAL_ERROR,message:f==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function yg(f,h){let y=h.entry,E=f==="undo"?y.preSnapshots:y.postSnapshots,R=f==="undo"?y.postSnapshots:y.preSnapshots,P=E.map(V=>V.file),{context:_,key:L}=rg(y,P),F=await Vi(P),$=new Map(F.filter(V=>V.exists!==!1).map(V=>[V.file,V.content])),J=be(L),de=sl(),te=new Map(d),ye=new Set(p),Se=null,Ee=!1,xe,T=await xi({overlay:$,plan:{operationId:`${f}:${y.operationId}`,intents:E.map(V=>V.exists===!1?{kind:"delete",path:V.file}:{kind:"upsert",path:V.file,content:V.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(Se=await nl(`${f}:${y.operationId}`,F,E,h.historyTransition),Se=await rl(Se),h),reverify:async()=>{},writeCandidate:async()=>{let V=await Ui(E,R);if(!V.ok)throw new Error(V.reason);return{snapshots:V.snapshots}},validateCandidate:async({candidate:V})=>{xe=ng(y,P);let U=await Zr(P,{changed:!0,minimumVersion:J+1,publish:!1,affectedCompositionKeys:xe});if(U.failedRoutes.length>0)throw new bn(U.failedRoutes);let se=cl(de,U.candidateRouteStates??[]),rt=al(se,L);return{...V,rebuild:U,routeSnapshots:se,resultVersion:rt}},publishCandidate:async({candidate:V,history:U})=>{if(!U)throw new Error("history cursor intent is missing");await l.publishPrepared(U),Ee=!0;let se=V.resultVersion??J+1;return{composition:_,requestId:f,kind:y.kind,target:y.target,ok:!0,resultVersion:se,affectedFiles:P,...y.output?{output:y.output}:{}}},swapCandidate:({candidate:V,receipt:U})=>{V.routeSnapshots&&Qr(V.routeSnapshots),V.rebuild?.candidateSourceCache&&Wn(d,V.rebuild.candidateSourceCache),Zc(U.snapshots)},finalizeCandidate:async()=>{await vn(Se)},emitCommitted:({candidate:V,published:U})=>ji(U,V.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:V,receipt:U})=>{if(Ee)throw new Error("history cursor was published before transaction finalization failed");if(U){let se=await Ui(R,U.snapshots);if(!se.ok)throw new Error(se.reason)}Qr(de),Wn(d,te),Qc(ye),V&&await l.discardPrepared?.(V),await vn(Se)}});if(T.ok)return T.published;if(T.stage==="precheck"||T.stage==="build")try{await vn(Se)}catch(V){let U=await qr(Le(V));return{composition:_,requestId:f,kind:y.kind,target:y.target,ok:!1,resultVersion:J,error:{code:U,message:"Unable to clear an uncommitted transaction journal."}}}if(T.recoveryRequired){let V=await qr(T.reason);return{composition:_,requestId:f,kind:y.kind,target:y.target,ok:!1,resultVersion:J,affectedFiles:P,error:{code:V===D.RECOVERY_PERSIST_FAILED?V:D.ROLLBACK_FAILED,message:T.reason}}}return{composition:_,requestId:f,kind:y.kind,target:y.target,ok:!1,resultVersion:J,affectedFiles:P,error:{code:T.error instanceof bn?D.ROUTE_REBUILD_FAILED:ul(T.stage),message:Le(T.error),...T.error instanceof bn?{details:{failedRoutes:T.error.failedRoutes}}:{}}}}function sl(){return[...i.values()].map(f=>({composition:f.composition,key:f.key,routeId:f.routeId,state:{...f,dependencyFiles:new Set(f.dependencyFiles),fileVersions:new Map(f.fileVersions)}}))}function al(f,h){return f.find(E=>E.key===h)?.state.graph?.version??o.initialVersions.get(h)??0}function cl(f,h){let y=new Map(f.map(E=>[E.key,E]));for(let E of h)y.set(E.key,E);return[...y.values()]}function Qr(f){for(let h of i.values())N(h);for(let h of f){let y={...h.state,dependencyFiles:new Set(h.state.dependencyFiles),fileVersions:new Map(h.state.fileVersions)};i.set(h.key,y),oe(y,y.dependencyFiles)}}async function Ki(f){let h=i.get(f);if(!h)throw new Error(`Composition not found: ${f}`);if(h.graph)return;let y=await n.readFile(h.entryFile);await ee(f,y)}function Gn(f,h){let y=i.get(o.resolveSelector(h).key)??null;return!y||!ll(y,f)?null:y}function ll(f,h){if(f.documentIndex?.entriesByKey.has(h)||f.graph?.elements.has(h))return!0;let y=Ve(h);return y&&y!==h?f.graph?.elements.has(y)===!0:!1}function Z(f,h,y,E){return{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:G(f),error:{code:h,message:y,...E?{details:E}:{}}}}function ul(f){return f==="validate"?D.ROUTE_REBUILD_FAILED:f==="publish"?D.HISTORY_COMMIT_FAILED:D.WRITE_IO_ERROR}async function qr(f){if(g=!0,!l.markRecoveryRequired)return D.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(f),D.RECOVERY_REQUIRED}catch{return D.RECOVERY_PERSIST_FAILED}}function xg(f){let y=f.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(E=>E.charAt(0).toUpperCase()+E.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return y?`Prefab${y}`:"GeneratedPrefab"}function Ji(f){return f==="VERSION_STALE"?D.VERSION_STALE:f==="CROSS_PAGE_MOVE_UNSUPPORTED"?D.CROSS_PAGE_MOVE_UNSUPPORTED:D.UNSUPPORTED_OPERATION}async function dl(f){if(f.target.kind==="route"){let y=i.get(o.resolveSelector(f.target.composition).key)??null;return y?(y.graph||await Ki(y.key),y):Z(f,D.ROUTE_NOT_FOUND,"Composition not found for route target.")}if(f.target.kind==="page-unit"){let y=i.get(o.resolveSelector(f.target.composition).key)??null;return y?(y.graph||await Ki(y.key),y):Z(f,D.ROUTE_NOT_FOUND,"Composition not found for page-unit target.")}if(f.target.kind!=="node")return Z(f,D.UNSUPPORTED_OPERATION,`${f.kind} source target execution is not implemented yet.`);let h=i.get(o.resolveSelector(f.composition).key)??null;return h?(h.graph||await Ki(h.key),ll(h,f.target.key)?h:Z(f,D.NODE_NOT_FOUND,`Target key not found: ${f.target.key}`)):Z(f,D.ROUTE_NOT_FOUND,"Composition not found for node target.")}return{get status(){return t},dispose(){t="disposed",a.clear(),i.clear(),s.clear(),d.clear(),p.clear()},registerComposition(f,h){let y=o.register({context:f,entryFile:h}),E=i.get(y.key);if(E?.entryFile===h)return;E&&N(E);let R=dm(y.context,h);i.set(y.key,R),oe(R,R.dependencyFiles),r.emit({type:"graph-invalidated",composition:y.context})},unregisterComposition(f){let h=o.resolveSelector(f),y=i.get(h.key);y&&(N(y),i.delete(h.key),o.unregister(h.key),i.size===0&&(t="idle"),r.emit({type:"graph-invalidated",composition:h.context}))},getCompositionEntryFiles(){return[...i.values()].map(f=>f.entryFile)},getCompositionContext(f){return o.resolveSelector(f).context},async initializeComposition(f){let h=o.resolveSelector(f),y=i.get(h.key);if(!y)throw new Error(`Composition not registered: ${h.key}`);if(y.graph)t="ready";else{t="building";try{let E=await n.readFile(y.entryFile);await ee(h.key,E),t="ready",r.emit({type:"graph-ready",composition:h.context,version:i.get(h.key)?.graph?.version??0})}catch(E){throw t="idle",r.emit({type:"graph-error",composition:h.context,message:Le(E)}),E}}},getDocument(f){let h=o.resolveSelector(f),y=i.get(h.key);if(!y)throw new Error(`Composition not registered: ${h.key}`);if(!y.document)throw new Error(`Composition not built: ${h.key}`);return y.document},async getHistoryStatus(){await C;let f=await l.getStatus?.();return f?{...f,recoveryRequired:g}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:g}},getObjectEditContext(f,h,y){let E=Gn(f,h),R=Ve(f)??f;if(E?.graph&&E.topology&&E.capabilities&&E.detailProjections){let P=E.detailProjections.get(R);if(P){let _=E.graph.elements.get(R);if(!_)throw new Error(`Key not found: ${f}`);let L=gC(f,R,y),F=new Map;if(P.isRepeat&&L?.instanceIndex!==void 0)for(let de of _.attributes??[])F.set(de.name,Xa({file:_.sourceFile,source:d.get(_.sourceFile)??"",element:_,propertyName:de.name,selectionRef:L,graph:E.graph,sources:d}));let $=ap({element:_,graph:E.graph,source:d.get(_.sourceFile),documentVersion:E.graph.version,selectionRef:y,isRepeat:P.isRepeat,propertyProvenance:P.propertyProvenances,repeatTargets:F}),J=vu(R,E.graph,E.topology,E.capabilities,P.textSources,P.provenances,P.dynamicData,$);return f===R?J:JC(J,f,E.document??null,E.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${f}`)},getRenderDetail(f,h){let y=Gn(f,h),E=Ve(f)??f;if(y?.graph&&y.topology&&y.capabilities&&y.detailProjections){let R=y.detailProjections.get(E);if(R){let P=Eu(E,y.graph,y.topology,y.capabilities,R.textSources,R.writeTarget,R.provenances,R.conditional,R.componentSemantic,R.contentModel,R.mediaModel,R.styleSource,R.dynamicData);return f===E?P:KC(P,f,y.document??null,y.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${f}`)},getClassNameSource(f,h){let y=Gn(f,h),E=Ve(f)??f;if(!y?.graph)throw new Error(`Key not found: ${f}`);let R=y.graph.elements.get(E);if(!R)throw new Error(`Key not found: ${f}`);let P=d.get(R.sourceFile);if(P===void 0)throw new Error(`Source not loaded: ${R.sourceFile}`);return Bs({key:E,route:{composition:y.composition,routeId:y.routeId,graph:y.graph,source:P}})},refreshSourceForKey:ig,async execute(f){if(await C,g)return Z(f,D.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(f.kind==="source-edit")return sg(f);if(f.kind==="insert-page-resource")return ag(f);if(f.kind==="delete-page-source")return cg(f);let h=await dl(f);if("ok"in h)return h;await el(f);let y=await dl(f);if("ok"in y)return y;let E=y;if(f.target.kind==="page-unit"){let L=f;return f.kind==="insert-child"||f.kind==="replace-node"?lg(L,E):f.kind==="move-node"||f.kind==="remove-node"?ug(L,E):Z(f,D.UNSUPPORTED_OPERATION,"Only page-unit insert-child, replace-node, move-node, and remove-node are currently supported by the page composition transaction.")}if(!E.graph||!E.topology||!E.capabilities)return{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:G(f),error:{code:f.target.kind==="route"?D.ROUTE_NOT_FOUND:D.NODE_NOT_FOUND,message:f.target.kind==="route"?"Composition not ready for route target.":f.target.kind==="node"?`Target key not found: ${f.target.key}`:`${f.kind} source target execution is not implemented yet.`}};let R=PC(E,E.graph,E.capabilities,d,i),P=await new Yo(R).plan(f);if(!P.ok)return{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:G(f),error:{code:Vr(P.errorCode),message:P.reason}};let _=P.plan;if(_.steps.length===0)return f.kind==="set-props"?{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!0,resultVersion:G(f),affectedFiles:[]}:{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:G(f),error:{code:D.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};m+=1;try{if(_.steps.some(F=>F.type==="invoke-external-adapter")){let F=await u.execute(_);if(!F.ok)return Z(f,Vr(F.errorCode),F.reason);let $={composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!0,resultVersion:Math.max(G(f),F.resultVersion),affectedFiles:F.affectedFiles,...F.selectionRef?{selectionRef:F.selectionRef}:{}};return ji($,{rebuiltRoutes:[],failedRoutes:[]}),$}let L=await u.prepareRewritePlan(_);return L.ok?await In({request:f,filePlan:L.filePlan,...L.selectionRef?{selectionRef:L.selectionRef}:{}}):Z(f,Vr(L.errorCode),L.reason)}catch(L){return{composition:o.resolveSelector(f.composition).context,requestId:f.id,kind:f.kind,target:f.target,ok:!1,resultVersion:G(f),error:{code:D.INTERNAL_ERROR,message:Le(L)}}}finally{m-=1}},async undo(f){if(await C,g)return{composition:o.entries[0].context,requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:be(o.entries[0].key),error:{code:D.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};m+=1;try{return await il("undo")}finally{m-=1}},async redo(f){if(await C,g)return{composition:o.entries[0].context,requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:be(o.entries[0].key),error:{code:D.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};m+=1;try{return await il("redo")}finally{m-=1}},notifyFileChanged(f){Gc([f])},getAffectedCompositions(f){return eg(f)},subscribe(f){return r.subscribe(f)}}}function RC(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function wC(e,t,n){let r=new Map,o=new Map,i=(u,d,p)=>{let m=u.get(d)??new Set,g=m.size;return m.add(p),u.set(d,m),m.size!==g},s=(u,d)=>{if(!u.importedFrom)return!1;if(u.exportName==="default")return i(o,u.importedFrom,d);let p=i(r,`${u.importedFrom}#${u.tag}`,d);return u.exportName&&u.exportName!==u.tag&&(p=i(r,`${u.importedFrom}#${u.exportName}`,d)||p),p},a=u=>r.get(`${u.sourceFile}#${u.componentName}`)??o.get(u.sourceFile);for(let u of t.elements.values()){if(u.sourceFile!==n.entryFile||!u.importedFrom||!/^[A-Z]/.test(u.tag))continue;let d=n.placements.find(m=>m.members.some(g=>g.sourceRange!==null&&gc(u.sourceRange,g.sourceRange)));if(!d)continue;let p=d.placementUnitKey;s(u,p)}let c=!0;for(;c;){c=!1;for(let u of t.elements.values()){if(u.sourceFile===n.entryFile||!u.importedFrom||!/^[A-Z]/.test(u.tag))continue;let d=a(u);if(d)for(let p of d)c=s(u,p)||c}}let l=n.placements.find(u=>u.placementKey===n.container.placementKey&&u.relation==="append");for(let u of e.entries){let d=Ve(u.key)??u.key,p=t.elements.get(u.key)??t.elements.get(d);if(!p)continue;if(p.sourceFile===n.entryFile){if(n.container.sourceRange&&gc(p.sourceRange,n.container.sourceRange)&&l){u.pageCompositionUnitKey=l.placementUnitKey;continue}let b=n.placements.find(C=>C.members.some(I=>I.sourceRange!==null&&(gc(p.sourceRange,I.sourceRange)||NC(I.sourceRange,p.sourceRange))));if(b){u.pageCompositionUnitKey=b.placementUnitKey;continue}}let m=r.get(`${p.sourceFile}#${p.componentName}`);if(m){m.size===1&&(u.pageCompositionUnitKey=m.values().next().value);continue}let g=o.get(p.sourceFile);g?.size===1&&(u.pageCompositionUnitKey=g.values().next().value)}}function gc(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function NC(e,t){return mm(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&mm(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function mm(e,t,n,r){return e!==n?e-n:t-r}function PC(e,t,n,r,o){let i=new Map,s=new Map,a=(u,d)=>{if(s.has(u))return;s.set(u,d);let p=t.elements.get(u);for(let m of p?.childKeys??[])a(m,d)};for(let u of t.regions)if(u.kind==="repeat-region")for(let d of u.childKeys)i.set(d,u.ownerKey),a(d,u.ownerKey);return{getNode(u){let d=c(u),p=t.elements.get(d.baseKey);return p?l(u,p):null},getChildNodes(u){let d=c(u),m=e.documentIndex?.entriesByKey.get(u)?.childKeys;if(m)return m.map(b=>{let C=Ve(b)??b,I=t.elements.get(C);return I?l(b,I):null}).filter(b=>b!==null);let g=t.elements.get(d.baseKey);return g?g.childKeys.map(b=>{let C=t.elements.get(b);return C?l(b,C):null}).filter(b=>b!==null):[]},getKnownSourceFiles(){return[...r.entries()].map(([u,d])=>({file:u,content:d}))},getRouteEntryFiles(){return[...o.values()].map(u=>u.entryFile)},getCapability(u){let d=c(u),p=n.get(d.baseKey);return p?{...p,key:u,constraints:p.constraints.map(m=>({...m})),...p.editModes?{editModes:{...p.editModes}}:{}}:{composition:e.composition,key:u,canUpdateText:!1,canRemove:!1,canInsertChild:!1,canMove:!1,constraints:[]}},getFileContent(u){return r.get(u)??""},getFileVersion(u){return Math.max(e.fileVersions.get(u)??0,t.version)},getRouteEntryFile(u){return e.routeId===u?e.entryFile:null},getComponentSemantic(u){let d=c(u);return e.detailProjections?.get(d.baseKey)?.componentSemantic??null},getClassNameSource(u){let d=c(u),p=t.elements.get(d.baseKey),m=p?r.get(p.sourceFile):void 0;return!p||m===void 0?null:Bs({key:d.baseKey,route:{composition:e.composition,routeId:e.routeId,graph:t,source:m}})},getEditableTextSegmentIndex(u){let d=c(u),m=e.detailProjections?.get(d.baseKey)?.textTargets.keys()?.next();return m&&!m.done?m.value:null},async getTextWriteTarget(u,d){let p=c(u);return ym(e.detailProjections?.get(p.baseKey)?.textTargets.get(d)??null,p.repeatIndex)},async getElementPropertyWriteTarget(u,d){let p=c(u);return ym(e.detailProjections?.get(p.baseKey)?.elementPropertyTargets.get(d)??null,p.repeatIndex)},getPropertyState(u,d,p){let m=c(u),g=t.elements.get(m.baseKey);if(!g)return null;let C=e.detailProjections?.get(m.baseKey)?.propertyProvenances.get(d);if(C)return C;let I=g.attributes?.find(w=>w.name===d);return I?I.source?{status:"blocked",owner:"generic",diagnostic:{code:"unsupported-property-source",message:`Property '${d}' has an unresolved value source`}}:{status:"direct",owner:"generic",attribute:I,target:{kind:"jsx-attribute",file:g.sourceFile,sourceRange:I.sourceRange}}:(g.attributeSpreads?.length??0)>0?{status:"blocked",owner:"generic",diagnostic:{code:"ambiguous-property-source",message:`A spread may provide or override property '${d}'`}}:{status:"missing",owner:"generic"}},getRepeatPropertyTarget(u,d,p){let m=c(u),g=t.elements.get(m.baseKey);if(!g)return{ok:!1,errorCode:"repeat-not-found",reason:`Node not found: ${u}`};let b=p?{...p,key:m.baseKey}:m.repeatIndex!==null?{key:m.baseKey,instanceIndex:m.repeatIndex}:void 0;return Xa({file:g.sourceFile,source:r.get(g.sourceFile)??"",element:g,propertyName:d,selectionRef:b,graph:t,sources:r})},getTextProvenance(u,d){let p=c(u);return e.detailProjections?.get(p.baseKey)?.provenances.get(d)??null}};function c(u){let d=rC(u);return d?{baseKey:d.baseKey,repeatIndex:$C(e.document??null,u,d.baseKey,e.documentIndex)??jC(d)}:{baseKey:u,repeatIndex:null}}function l(u,d){let p=Ve(u)??u,m=e.documentIndex?.entriesByKey.get(u),g=e.detailProjections?.get(p);return{key:u,file:d.sourceFile,component:d.componentName,tag:d.tag,structuralPath:d.identity.structuralPath,sourceRange:d.sourceRange,parentKey:m?.parentKey??d.parentKey??void 0,isRepeatRegion:d.boundaryKind==="repeat-region"||s.has(p),isBoundary:!1,importedFrom:d.importedFrom,exportName:d.exportName,isRepeatItemRoot:i.has(p),repeatOwnerKey:i.get(p)??s.get(p),contentModel:g?.contentModel,attributes:d.attributes?.map(b=>({name:b.name,value:b.value,source:b.source?{expression:b.source.expression,base:b.source.base,path:b.source.path.map(C=>({...C}))}:null,resolvedValue:b.resolvedValue}))}}}var AC={"stale-version":D.VERSION_STALE,"capability-denied":D.CAPABILITY_REJECTED,"invalid-params":D.INVALID_PARAMS,"locator-miss":D.LOCATOR_FAILED,"route-not-found":D.ROUTE_NOT_FOUND,"unsupported-operation":D.UNSUPPORTED_OPERATION,"invalid-target":D.INVALID_TARGET,"ast-error":D.AST_PARSE_ERROR,"writeback-failed":D.WRITE_IO_ERROR,"rollback-failed":D.RECOVERY_REQUIRED,unknown:D.INTERNAL_ERROR};function Vr(e){return AC[e]}function Le(e){return e instanceof Error&&e.message?e.message:String(e)}function gm(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function TC(e){let t=Sn(e);if(!sC.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=>aC.map(a=>`${s}/${a}`))}function FC(e){let n=Sn(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function _C(e){return bm(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function OC(e){return bm(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function bm(e,t){let n=[];for(let r of e.matchAll(t)){let o=Sm(r[1]??"");o&&n.push(o)}return n}function hm(e,t){let n=Sm(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?Sn(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?Sn(`${MC(e)}/${n}`):n.startsWith("/")?Sn(n.slice(1)):hc(n)?Sn(n):null}function Sm(e){return e.split(/[?#]/,1)[0]?.trim()??""}function hc(e){return/\.css$/i.test(e)}function MC(e){let t=Sn(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function Em(e){return Array.from(new Set(e))}function Sn(e){let t=e.replace(/\\/g,"/").replace(/^\.\//,""),n=[];for(let r of t.split("/"))if(!(!r||r===".")){if(r===".."){n.pop();continue}n.push(r)}return n.join("/")}function DC(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 LC(e,t){let n=t.elements.get(e);if(!n)return!1;for(let r of t.regions){if(r.kind!=="repeat-region")continue;let o=n;for(;o;){if(r.childKeys.includes(o.identity.key))return!0;o=o.parentKey?t.elements.get(o.parentKey):void 0}}return!1}function vi(e){return e?.map(t=>({...t}))}function ym(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=vi(e.collectionPathMap?.[t])??vi(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:vi(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>vi(o)??[])}}function BC(e,t,n){let r=new Set;for(let m of t.regions)if(m.kind==="repeat-region")for(let g of m.childKeys)r.add(g);if(r.size===0)return e;let o=new Map(e.entries.map(m=>[m.key,m])),i=[],s=new Map,a=(m,g)=>eC(m,g),c=(m,g,b)=>{let C=o.get(m);if(!C)return a(m,b);let I=a(m,b),w={...C,key:I,parentKey:g,childKeys:[]};return i.push(w),w.childKeys=C.childKeys.flatMap(A=>l(A,b,I)),I},l=(m,g,b)=>{if(!r.has(m))return[c(m,b,g)];let C=d(m,g),I=[];for(let w=0;w<C;w+=1)I.push(c(m,b,[...g,w]));return I},u=Em([...e.rootKeys,...e.entries.filter(m=>m.parentKey===null).map(m=>m.key)]);for(let m of u){if(!r.has(m)){c(m,null,[]);continue}let g=d(m,[]);for(let b=0;b<g;b+=1)c(m,null,[b])}return{...e,rootKeys:[...e.rootKeys],entries:i};function d(m,g){let b=new Set;for(let C of p(m)){let I=n.get(C);if(I){for(let w of[...I.textTargets.values(),...I.elementPropertyTargets.values()])if(!(w?.kind!=="value-binding"||w.sourceKind!=="repeat-template"))for(let A of VC(w))A.length<=g.length||UC(A,g)&&b.add(A[g.length])}}return b.size>0?b.size:DC(n.get(m))}function p(m){let g=s.get(m);if(g)return g;let b=[m],C=o.get(m);for(let I of C?.childKeys??[])b.push(...p(I));return s.set(m,b),b}}function jC(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function $C(e,t,n,r){let o=r?.repeatOccurrenceIndexByKey.get(t);if(o!==void 0)return o;if(!e)return null;let i=0;for(let s of e.entries)if((Ve(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function VC(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 UC(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 KC(e,t,n,r){if(!n)return{...e,key:t};let o=r??new Map(n.entries.map(u=>[u.key,u])),i=o.get(t);if(!i)return{...e,key:t};let s=[],a=i.parentKey;for(;a;){let u=o.get(a);if(!u)break;s.push({key:u.key,tag:u.tag,label:u.label}),a=u.parentKey}s.reverse();let c=i.childKeys.map(u=>o.get(u)).filter(u=>u!==void 0).map(u=>({key:u.key,tag:u.tag,label:u.label})),l=i.parentKey===null?[]:(o.get(i.parentKey)?.childKeys??[]).filter(u=>u!==i.key).map(u=>o.get(u)).filter(u=>u!==void 0).map(u=>({key:u.key,tag:u.tag,label:u.label}));return{...e,key:i.key,ancestors:s,children:c,siblings:l}}function JC(e,t,n,r){if(!n)return{...e,key:t};let o=r??new Map(n.entries.map(c=>[c.key,c])),i=o.get(t);if(!i)return{...e,key:t};let s=[],a=i.parentKey;for(;a;){let c=o.get(a);if(!c)break;s.push({key:c.key,tag:c.tag,label:c.label}),a=c.parentKey}return s.reverse(),{...e,key:i.key,ancestors:s}}import Ec from"node:path";import{TextDecoder as XC}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as Im,SITE_EDIT_SOURCE_ALLOWED_DIRS as km,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as Cm,SiteEditCompositionContextSchema as zC,SiteEditSourceFileResponseSchema as yc,SiteEditSourceLocationSchema as WC,SiteEditSourcePathSchema as ki,SiteEditSourceTreeResponseSchema as HC,isSiteEditTextSourcePath as GC}from"@vcp-dev/contracts";var YC=[...Cm,...Im,...km];function vc(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return zC.parse(e.composition)}var xc=2e3,bc=12,Sc=24*1024*1024,vm=512*1024,ZC=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),QC={".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"},qC={".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"},eR=new XC("utf-8",{fatal:!0});async function Ci(e,t={}){let n=vc(t),{files:r,truncated:o}=await cR(e,t),i=dR(r.map(s=>s.metadata));return HC.parse({composition:n,nodes:i,defaultPath:fR(r.map(s=>s.metadata)),totalFiles:r.length,...o?{truncated:o}:{}})}async function Ri(e,t,n={}){let r=vc(n),o=ki.parse(t.path),i=await rR(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(Ic(o)){let a=Nm(o),c=await iR(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return yc.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...c})}let s=await tR(e,o);return s.ok?yc.parse({composition:r,path:o,kind:"text",language:Pm(o),sizeBytes:s.sizeBytes,contentHash:fe(s.content),readonly:!1,content:s.content}):yc.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function tR(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=nR(o);return i===null?{ok:!1,sizeBytes:o.byteLength}:{ok:!0,content:i,sizeBytes:o.byteLength}}let n=await e.readFile(t),r=Buffer.byteLength(n,"utf8");return n.includes("\0")?{ok:!1,sizeBytes:r}:{ok:!0,content:n,sizeBytes:r}}function nR(e){if(e.includes(0))return null;try{return eR.decode(e)}catch{return null}}async function rR(e,t,n){if(!sR(t,n))return null;let r=await oR(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function oR(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=Rm(await e.listFiles({roots:[t],maxFiles:1,maxDepth:t.split("/").length})).files.find(i=>i.path===t);if(o)return o}if(!await e.exists(t))return null;if(e.readFileBytes){let r=await e.readFileBytes(t);return{path:t,sizeBytes:r.byteLength}}if(Ic(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function iR(e,t){if(!ZC.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>vm)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>vm?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function sR(e,t){return Cm.some(n=>n===e)||Im.some(n=>n===e)||km.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=ki.safeParse(n);return r.success&&r.data===e})}function wi(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return WC.parse({key:e.key,composition:t.composition,sourceFile:t.sourceLocator.sourceFile,componentName:t.sourceLocator.componentName,openingElementRange:{startLine:t.sourceLocator.openingElementRange.startLine,startColumn:t.sourceLocator.openingElementRange.startColumn,endLine:t.sourceLocator.openingElementRange.endLine,endColumn:t.sourceLocator.openingElementRange.endColumn},structuralPath:t.sourceLocator.structuralPath,textPreview:t.sourceLocator.textPreview})}function Rm(e){return Array.isArray(e)?{files:e}:e}function aR(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function cR(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=Rm(await e.listFiles({roots:lR(t),maxFiles:xc+1,maxDepth:bc,maxTotalBytes:Sc+1})),r=new Map,o=new Set(n.truncated?.reasons),i=0;for(let a of[...n.files].sort((c,l)=>c.path.localeCompare(l.path))){let c=ki.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>bc){o.add("max-depth");continue}if(r.size>=xc){o.add("max-files");break}if(i+a.sizeBytes>Sc){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:uR(l,a.sizeBytes,vc(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:aR([...o]),maxFiles:xc,maxDepth:bc,maxTotalBytes:Sc}}:{}}}function lR(e){let t=new Set(YC);for(let n of e.routeEntryFiles??[]){let r=ki.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function uR(e,t,n){return Ic(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:Nm(e),readonly:!0}:{composition:n,path:e,kind:"text",language:Pm(e),sizeBytes:t,readonly:!1}}function dR(e){let t=[];for(let n of e){let r=n.path.split("/"),o=t,i="";for(let[s,a]of r.entries()){i=i?`${i}/${a}`:a;let c=s===r.length-1,l=o.find(u=>u.name===a);if(l||(l=c?{kind:"file",name:a,path:i,file:n}:{kind:"directory",name:a,path:i,children:[]},o.push(l)),c){if(l.kind!=="file")throw new Error(`Source tree path collision: ${n.path}`);l.file=n}else{if(l.kind!=="directory")throw new Error(`Source tree path collision: ${n.path}`);o=l.children}}}return wm(t)}function wm(e){return e.map(t=>t.kind==="directory"?{...t,children:wm(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function fR(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 Ic(e){return!GC(e)}function Nm(e){let t=Ec.posix.extname(e).toLowerCase();return!t&&Ec.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":QC[t]??"application/octet-stream"}function Pm(e){let t=Ec.posix.extname(e).toLowerCase();return qC[t]??"plaintext"}var Ni=class{constructor(t){this.options=t,this.fileSystem=new ur(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}getDocument(t){return ro(this.engine.getDocument(t),{siteId:this.options.siteId,snapshotId:this.options.snapshotId})}getInternalDocument(t){return this.engine.getDocument(t)}getStyleContext(t){return this.engine.getDocument(t).styleContext??null}getObjectEditContext(t,n,r){return oo(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return Ci(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}getSourceFile(t){return Ri(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}resolveSourceLocation(t){return wi(t,this.engine.getRenderDetail(t.key,t.composition))}async planOperation(t){let n=mR.safeParse(t);if(!n.success)return{result:no(t,n.error.issues.map(i=>i.message))};let r=new ur(this.options.files),o=this.createEngine(r,{emitEvents:!1});try{let i=await o.execute(n.data);if(!i.ok)return{result:{ok:!1,composition:i.composition,error:{code:i.error?.code??"INTERNAL_ERROR",message:i.error?.message??"Operation failed"},data:{requestId:i.requestId,kind:i.kind,target:i.target,resultVersion:i.resultVersion}}};let s={ok:!0,composition:i.composition,data:tn(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let c=gR.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(l=>hR(l,t.kind==="source-edit")),changedCompositions:o.getAffectedCompositions(a.map(l=>l.path)),diagnostics:[]});return this.options.onEvent?.({type:"site-edit.operation.planned",siteId:t.siteId,operationId:t.id,baseSnapshotId:t.baseSnapshotId,changedFiles:c.patches.map(l=>l.path),composition:i.composition,at:new Date().toISOString()}),{result:s,patchPlan:c}}finally{o.dispose()}}dispose(){this.engine.dispose()}createEngine(t,n={}){let r=n.emitEvents??!0;return Ur({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=io(o,{siteId:this.options.siteId,snapshotId:this.options.snapshotId});i&&this.options.onEvent?.(i)}:void 0,dev:this.options.dev,...this.options.historyStore?{historyStore:this.options.historyStore}:{},...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,...this.options.initialDocumentVersions?{initialDocumentVersions:this.options.initialDocumentVersions}:{}})}};function hR(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:fe(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:fe(e.before)},fullContent:e.after}}function yR(e){return new Ni(e)}import{SiteEditOperationRequestSchema as SR}from"@vcp-dev/contracts";import mt from"node:fs/promises";import Be from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as xR,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as bR}from"@vcp-dev/contracts";var Pi=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=Ur({...t,fileSystem:this.fileSystem})}get status(){return this.engine.status}registerComposition(t,n){this.engine.registerComposition(t,n)}unregisterComposition(t){this.engine.unregisterComposition(t)}getDocument(t){return this.engine.getDocument(t)}getAffectedCompositions(t){return this.engine.getAffectedCompositions(t)}getCompositionContext(t){return this.engine.getCompositionContext(t)}initializeComposition(t){return this.engine.initializeComposition(t)}getHistoryStatus(){return this.engine.getHistoryStatus()}getObjectEditContext(t,n,r){return r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n)}getRenderDetail(t,n){return this.engine.getRenderDetail(t,n)}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return Ci(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.engine.getCompositionEntryFiles()})}getSourceFile(t){return Ri(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.engine.getCompositionEntryFiles()})}resolveSourceLocation(t){return wi(t,this.engine.getRenderDetail(t.key,t.composition))}refreshSourceForKey(t,n){return this.engine.refreshSourceForKey(t,n)}execute(t){return this.engine.execute(t)}undo(t){return this.engine.undo(t)}redo(t){return this.engine.redo(t)}notifyFileChanged(t){this.engine.notifyFileChanged(t)}subscribe(t){return this.engine.subscribe(t)}dispose(){this.engine.dispose()}createFileSystem(){if(this.options.fileSystem)return this.options.fileSystem;let t=new Map,{projectRoot:n}=this.options;return{async readFile(r){return mt.readFile(Be.join(n,r),"utf8")},async readFileBytes(r){return mt.readFile(Be.join(n,r))},async getFileInfo(r){let o=Be.join(n,...r.split("/"));try{let i=await mt.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await ai(Be.join(n,r),o)},async createExclusive(r,o){let i=Be.join(n,r);await mt.mkdir(Be.dirname(i),{recursive:!0});let s=await mt.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await mt.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await mt.rm(Be.join(n,r),{force:!0});let o=r.replace(/\\/g,"/"),i=["components/site/generated","src/components/site/generated"].find(c=>o.startsWith(`${c}/`));if(!i)return;let s=Be.join(n,i),a=Be.dirname(Be.join(n,o));for(;a!==s&&a.startsWith(`${s}${Be.sep}`);){try{await mt.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=Be.dirname(a);continue}break}a=Be.dirname(a)}},async exists(r){try{return await mt.access(Be.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...bR,...xR],i=[],s=new Set,a=new Set,c=0;for(let d of o)await u(d,i,1);let l=i.sort((d,p)=>d.path.localeCompare(p.path));return a.size>0?{files:l,truncated:{reasons:[...a]}}:{files:l};async function u(d,p,m){if(r.maxDepth!==void 0&&m>r.maxDepth){a.add("max-depth");return}let g=Be.join(n,...d.split("/")),b;try{b=await mt.lstat(g)}catch{return}if(b.isSymbolicLink())return;if(b.isFile()){let I=b.ino>0?`${String(b.dev)}:${String(b.ino)}`:null;if(I&&s.has(I))return;if(r.maxFiles!==void 0&&p.length>=r.maxFiles){a.add("max-files");return}if(r.maxTotalBytes!==void 0&&c+b.size>r.maxTotalBytes){a.add("max-total-bytes");return}I&&s.add(I),p.push({path:d,sizeBytes:b.size}),c+=b.size;return}if(!b.isDirectory())return;if(r.maxFiles!==void 0&&p.length>=r.maxFiles){a.add("max-files");return}let C=await mt.readdir(g,{withFileTypes:!0});for(let I of C)I.isSymbolicLink()||await u(`${d}/${I.name}`,p,m+1)}},getVersion(r){return t.get(r)??1},bumpVersion(r){let o=(t.get(r)??1)+1;return t.set(r,o),o}}}};function kc(e){return new Pi(e)}var Ai=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=kc({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=io(n,{siteId:t.siteId,snapshotId:t.snapshotId});if(r){t.onEvent?.(r);for(let o of this.listeners)o(r)}},dev:t.dev,...t.historyStore?{historyStore:t.historyStore}:{},...t.tenantId?{tenantId:t.tenantId}:{},...t.initialDocumentVersions!==void 0?{initialDocumentVersions:t.initialDocumentVersions}:{},siteId:t.siteId,snapshotId:t.snapshotId})}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}registerComposition(t,n){this.engine.registerComposition(t,n)}unregisterComposition(t){this.engine.unregisterComposition(t)}getDocument(t){return{ok:!0,composition:this.engine.getCompositionContext(t),data:ro(this.engine.getDocument(t),{siteId:this.options.siteId,snapshotId:this.options.snapshotId})}}getInternalDocument(t){return this.engine.getDocument(t)}getStyleContext(t){return{ok:!0,composition:this.engine.getCompositionContext(t),data:this.engine.getDocument(t).styleContext??null}}async getHistoryStatus(){return{ok:!0,composition:this.options.compositions[0].context,data:await this.engine.getHistoryStatus()}}getObjectEditContext(t,n,r){return{ok:!0,composition:this.engine.getCompositionContext(n),data:oo(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}}getClassNameSource(t,n){return{ok:!0,composition:this.engine.getCompositionContext(n),data:this.engine.getClassNameSource(t,n)}}async getSourceTree(t){return{ok:!0,composition:this.engine.getCompositionContext(t),data:await this.engine.getSourceTree(t)}}async getSourceFile(t){return{ok:!0,composition:this.engine.getCompositionContext(t.composition),data:await this.engine.getSourceFile(t)}}resolveSourceLocation(t){return{ok:!0,composition:this.engine.getCompositionContext(t.composition),data:this.engine.resolveSourceLocation(t)}}refreshSourceForKey(t,n){return this.engine.refreshSourceForKey(t,n)}async executeOperation(t,n){let r=n===void 0||t.mutationContext!==void 0?t:{...t,mutationContext:n},o=SR.safeParse(r);if(!o.success)return no(t,o.error.issues.map(s=>s.message));let i=await this.engine.execute(o.data);if(!i.ok){let s=i.error;if(!s)throw new Error("executeOperation failed without an error payload");return{ok:!1,composition:i.composition,error:{code:s.code,message:s.message},data:{requestId:i.requestId,kind:i.kind,composition:i.composition,target:i.target,resultVersion:i.resultVersion,...i.affectedFiles?.length?{affectedFiles:i.affectedFiles}:{}}}}return{ok:!0,composition:i.composition,data:tn(i)}}async undo(t){let n=await this.engine.undo();if(!n.ok){let r=n.error;if(!r)throw new Error("undo failed without an error payload");return{ok:!1,composition:n.composition,error:{code:r.code,message:r.message},data:{requestId:n.requestId,kind:n.kind,composition:n.composition,target:n.target,resultVersion:n.resultVersion}}}return{ok:!0,composition:n.composition,data:tn(n)}}async redo(t){let n=await this.engine.redo();if(!n.ok){let r=n.error;if(!r)throw new Error("redo failed without an error payload");return{ok:!1,composition:n.composition,error:{code:r.code,message:r.message},data:{requestId:n.requestId,kind:n.kind,composition:n.composition,target:n.target,resultVersion:n.resultVersion}}}return{ok:!0,composition:n.composition,data:tn(n)}}notifyFileChanged(t){this.engine.notifyFileChanged(t)}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}dispose(){this.listeners.clear(),this.engine.dispose()}};function ER(e){return new Ai(e)}import{createHash as vR,randomUUID as Dc}from"node:crypto";import ve from"node:fs/promises";import ke from"node:path";var nt=1,Rc=1,IR=2,kR="index.json",CR="recovery.json",RR="transaction-journal.json",wR="document-version.json",Fi={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},z={INVALID_ROOT:"INVALID_ROOT",INVALID_PATH:"INVALID_PATH",INVALID_SCHEMA:"INVALID_SCHEMA",INVALID_JSON:"INVALID_JSON",INDEX_CORRUPT:"INDEX_CORRUPT",ENTRY_CORRUPT:"ENTRY_CORRUPT",BLOB_CORRUPT:"BLOB_CORRUPT",RECOVERY_PENDING:"RECOVERY_PENDING",CAPACITY_EXCEEDED:"CAPACITY_EXCEEDED",NOT_FOUND:"NOT_FOUND"},H=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};async function jm(e,t={}){let n=VR(e),r=JR(t.limits),o=Cc(n),i=UR(n),s=await Ue(i),a=await Ue(o)||s;a||(await _R(n),await OR(n)),a||await XR(n);let c=await We(n),l=new Set(a?(await Li(n)).map(d=>d.stageId):[]);a||await Kr(n,c.entryIds);let u=async()=>{if(await Ue(o)||s)throw new H(z.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")};return{rootDir:n,recoveryRequired:a,async readDocumentVersion(){return Lm(n)},async writeDocumentVersion(d){if(await u(),!Number.isInteger(d)||d<0)throw new H(z.INVALID_SCHEMA,"document version must be a non-negative integer");let p=await Lm(n);await Jr(zm(n),{schemaVersion:1,version:Math.max(p,d)})},async stageAppend(d,p={}){await u();let m=await Tm(d,r),g={schemaVersion:Rc,stageId:Dc(),entryId:m.entryId,blobIds:m.blobs.map(b=>b.digest)};try{await Fm(n,m),await AR(n,g,p.durableManifest!==!1)}catch(b){try{await Om(n,g)}catch(C){throw new H(z.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:C})}throw b}return{stageId:g.stageId,entryId:g.entryId,blobIds:g.blobIds}},async discardStage(d){await u(),Ac(d);let p=await Nc(n,d);p&&await Om(n,p)},async previewStagedAppend(d,p){return await u(),(await Am(n,r,d,p)).transition},async previewCursor(d,p){await u();let m=await We(n);return Tc(m,p),wc(d,m.entryIds.length),$m(m,m.entryIds,d)},async publishStagedAppend(d,p,m){if(await u(),_i(d,"entryId"),m){Ac(m);let b=await Nc(n,m);if(!b||b.entryId!==d)throw new H(z.INVALID_SCHEMA,"history stage does not match the published entry")}let g=await Am(n,r,d,p);return Dm({rootDir:n,previousDigest:g.current.digest,entryIds:g.entryIds,cursor:g.cursor,afterWrite:async()=>{m?await Oi(n,m):await FR(n,d),await Kr(n,g.entryIds)}})},async append(d){await u();let p=await We(n),m=await Tm(d,r),g=[...p.entryIds];p.cursor<g.length-1&&g.splice(p.cursor+1),g.push(m.entryId);try{await Fm(n,m);let b=await Vm(n,g,r);return await Bc(n,b.entryIds,b.cursor),await Kr(n,b.entryIds),We(n)}catch(b){throw await Kr(n,p.entryIds),b}},async readEntry(d){return _i(d,"entryId"),zr(n,d)},async readBlob(d){_i(d,"blobId");let p=await zc(n,d),m=await Qt(p,z.NOT_FOUND,"blob");return jc(m,d,p),m},async readIndex(){return We(n)},async readStatus(){let d=await We(n);return{canUndo:d.undoIds.length>0,canRedo:d.redoIds.length>0,undoDepth:d.undoIds.length,redoDepth:d.redoIds.length,cursor:d.cursor,recoveryRequired:await Ue(o)||await Ue(i)}},async readUndoRedoIds(){let d=await We(n);return{undoIds:d.undoIds,redoIds:d.redoIds,currentId:d.currentId}},async setCursor(d,p){await u();let m=await We(n);return Tc(m,p),wc(d,m.entryIds.length),Dm({rootDir:n,previousDigest:m.digest,entryIds:m.entryIds,cursor:d})},async markRecoveryRequired(d){await Ue(o)||await Jr(Cc(n),{schemaVersion:nt,reason:KR(d),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await ve.rm(Cc(n),{force:!0})},async readTransactionJournal(){return await Ue(i)?Ti(i):null},async writeTransactionJournal(d){await u(),Wm(d);try{await Jr(i,d)}catch(m){let g=await Ti(i).catch(()=>null);if(g&&Buffer.from(He(g)).equals(Buffer.from(He(d))))return;throw g?new H(z.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:m}):m}let p=await Ti(i);if(!Buffer.from(He(p)).equals(Buffer.from(He(d))))throw new H(z.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(d){let p=await Ue(i)?await Ti(i):null;if(p&&p.transactionId!==d)throw new H(z.INVALID_SCHEMA,"transaction journal changed concurrently");try{await ve.rm(i,{force:!0})}catch(m){if(!await Ue(i))return;throw m}if(await Ue(i))throw new H(z.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await u();for(let p of l)await Oi(n,p),l.delete(p);await MR(n);let d=await We(n);await Kr(n,d.entryIds)}}}async function Am(e,t,n,r){_i(n,"entryId");let o=await We(e);Tc(o,r);let i=await zr(e,n),s=[...o.entryIds];o.cursor<s.length-1&&s.splice(o.cursor+1),s.push(i.id);let a=await Vm(e,s,t);return{current:o,entryIds:a.entryIds,cursor:a.cursor,transition:$m(o,a.entryIds,a.cursor)}}function $m(e,t,n){return wc(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:NR(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function NR(e,t){return qt(He({schemaVersion:nt,entryIds:e,cursor:t}))}function wc(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new H(z.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function PR(e){if(!gt(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!Ge(e.expectedIndexDigest)||!Ge(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!Ge(n)?!1:t===-1?n===null:Ge(n)}async function Tm(e,t){if(!e.kind.trim())throw new H(z.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new H(z.INVALID_JSON,"history blob name must not be empty");let l=$R(c.data),u=qt(l);n.push({name:c.name,bytes:l,digest:u,sizeBytes:l.byteLength}),r.push({name:c.name,digest:u,sizeBytes:l.byteLength})}let o={schemaVersion:nt,kind:e.kind,manifest:e.manifest,blobs:r},i=He({...o}),s=qt(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new H(z.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function Fm(e,t){let n=Uc(e,t.entryId),r={id:t.entryId,...t.entryBody},o=[...t.blobs.map(a=>_m(Kc(e,a.digest),a.bytes,{kind:"blob",digest:a.digest},Xc(e,a.digest))),_m(n,He(r),{kind:"entry",digest:t.entryId},Jc(e,t.entryId))],s=(await Promise.allSettled(o)).find(a=>a.status==="rejected");if(s)throw s.reason}async function _m(e,t,n,r){let o=await Oc(e)??(r?await Oc(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new H(n.kind==="blob"?z.BLOB_CORRUPT:z.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await Jm(e,t)}async function Vm(e,t,n){let r=[...t],o=r.length-1;for(;;){if((await Km(e,r)).totalBytes<=n.maxSessionBytes&&r.length<=n.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new H(z.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");r.shift(),o-=1}}async function AR(e,t,n){Lc(t);let r=Vc(e,t.stageId);if(n){await Jr(r,t);return}await jR(r,t)}async function Nc(e,t){let n=await Oc(Vc(e,t));if(n===null)return null;let r=Wr(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=Lc(r);if(o.stageId!==t)throw new H(z.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function Li(e){let t=[];for(let n of await Di($c(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);Ac(r);let o=await Nc(e,r);o&&t.push(o)}return t}async function Om(e,t){Lc(t);let n=await We(e),r=(await Li(e)).filter(s=>s.stageId!==t.stageId),o=new Set(n.entryIds),i=new Set;for(let s of n.entryIds){let a=await zr(e,s);for(let c of a.blobs)i.add(c.digest)}for(let s of r){o.add(s.entryId);for(let a of s.blobIds)i.add(a)}o.has(t.entryId)||await Mm(Uc(e,t.entryId),Jc(e,t.entryId));for(let s of t.blobIds)i.has(s)||await Mm(Kc(e,s),Xc(e,s));await Oi(e,t.stageId),await Mc(Hr(e)),await Mc(Gr(e))}async function Oi(e,t){await Pc(Vc(e,t)),await TR(e)}async function TR(e){try{await ve.rmdir($c(e))}catch(t){if(Yr(t)||gt(t)&&t.code==="ENOTEMPTY")return;throw t}}async function FR(e,t){for(let n of await Li(e))n.entryId===t&&await Oi(e,n.stageId)}async function Pc(e){if(await ve.rm(e,{force:!0}),await Ue(e))throw new H(z.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function Mm(e,t){await Pc(e),await Pc(t)}function Lc(e){if(!gt(e)||e.schemaVersion!==Rc||typeof e.stageId!="string"||!Um(e.stageId)||!Ge(e.entryId))throw new H(z.INVALID_SCHEMA,"history stage schema is invalid");let t=Xm(e.blobIds,"history stage blobIds");return{schemaVersion:Rc,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function Ac(e){if(!Um(e))throw new H(z.INVALID_PATH,"history stageId must be a UUID")}function Um(e){return typeof e=="string"&&/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu.test(e)}async function Kr(e,t){let n=new Set(t),r=new Set;for(let c of t){let l=await zr(e,c);for(let u of l.blobs)r.add(u.digest)}for(let c of await Li(e)){n.add(c.entryId);for(let l of c.blobIds)r.add(l)}let o=Hr(e),i=await Di(o);for(let c of i){if(!c.endsWith(".json"))continue;let l=Bm(c.slice(0,-5));l&&!n.has(l)&&await Mi(ke.join(o,c))}let s=Gr(e),a=await Di(s);for(let c of a){let l=Bm(c);l&&!r.has(l)&&await Mi(ke.join(s,c))}}async function We(e){let t=Bi(e),n=await Qt(t,z.NOT_FOUND,"index"),r=Wr(Buffer.from(n).toString("utf8"),"index"),o=DR(r),i=[...o.entryIds],{totalBytes:s}=await Km(e,i),a=i.slice(0,o.cursor+1).reverse(),c=i.slice(o.cursor+1);return{schemaVersion:nt,digest:o.digest,entryIds:i,cursor:o.cursor,currentId:i[o.cursor]??null,undoIds:a,redoIds:c,totalBytes:s}}async function Km(e,t){let n=0,r=new Set,o=Bi(e),i=await Qt(o,z.NOT_FOUND,"index");n+=i.byteLength;for(let s of t){let a=await zr(e,s),c=await Hm(e,s),l=await Qt(c,z.NOT_FOUND,"entry");n+=l.byteLength;for(let u of a.blobs){if(r.has(u.digest))continue;r.add(u.digest);let d=await zc(e,u.digest),p=await Qt(d,z.NOT_FOUND,"blob");jc(p,u.digest,d),n+=p.byteLength}}return{totalBytes:n}}async function zr(e,t){let n=await Hm(e,t),r=await Qt(n,z.NOT_FOUND,"entry"),o=Wr(Buffer.from(r).toString("utf8"),`entry ${t}`),i=LR(o);if(i.id!==t)throw new H(z.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(qt(He({schemaVersion:i.schemaVersion,kind:i.kind,manifest:i.manifest,blobs:i.blobs}))!==t)throw new H(z.ENTRY_CORRUPT,`entry hash mismatch for ${t}`);for(let a of i.blobs){let c=await zc(e,a.digest),l=await Qt(c,z.NOT_FOUND,"blob");jc(l,a.digest,c)}return i}async function Bc(e,t,n){let r={schemaVersion:nt,digest:qt(He({schemaVersion:nt,entryIds:t,cursor:n})),entryIds:t,cursor:n};await Jr(Bi(e),r)}function Tc(e,t){if(t!==void 0&&e.digest!==t)throw new H(z.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function Dm(e){let t=qt(He({schemaVersion:nt,entryIds:e.entryIds,cursor:e.cursor}));try{return await Bc(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.(),await We(e.rootDir)}catch(n){let r=await We(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new H(z.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function _R(e){await ve.mkdir(e,{recursive:!0}),await ve.mkdir(Hr(e),{recursive:!0}),await ve.mkdir(Gr(e),{recursive:!0}),await ve.mkdir(Xr(e),{recursive:!0})}async function OR(e){await ve.rm(Xr(e),{recursive:!0,force:!0}),await ve.mkdir(Xr(e),{recursive:!0})}async function MR(e){let t=Xr(e);await ve.mkdir(t,{recursive:!0});for(let n of await Di(t))n!=="stages"&&await ve.rm(ke.join(t,n),{recursive:!0,force:!0})}function DR(e){if(!gt(e))throw new H(z.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==nt)throw new H(z.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=Xm(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new H(z.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!Ge(o))throw new H(z.INDEX_CORRUPT,"index digest is invalid");let i=qt(He({schemaVersion:nt,entryIds:t,cursor:r}));if(o!==i)throw new H(z.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:nt,digest:o,entryIds:t,cursor:r}}function LR(e){if(!gt(e))throw new H(z.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==nt)throw new H(z.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!Ge(t))throw new H(z.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new H(z.ENTRY_CORRUPT,"entry kind is invalid");let r=_c(e.manifest,"entry.manifest"),o=BR(e.blobs);return{id:t,schemaVersion:nt,kind:n,manifest:r,blobs:o}}function BR(e){if(!Array.isArray(e))throw new H(z.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!gt(t))throw new H(z.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new H(z.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!Ge(o))throw new H(z.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new H(z.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function Jr(e,t){await Jm(e,He(t))}async function jR(e,t){let n=ke.dirname(e),r=ke.basename(e),o=ke.join(n,`.${r}.${process.pid}.${Dc()}.tmp`);await ve.mkdir(n,{recursive:!0});try{await ve.writeFile(o,He(t),{flag:"wx"}),await ve.rename(o,e)}finally{await Mi(o)}}async function Jm(e,t){let n=ke.dirname(e),r=ke.basename(e),o=ke.join(n,`.${r}.${process.pid}.${Dc()}.tmp`);await ve.mkdir(n,{recursive:!0});try{let i=await ve.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await ve.rename(o,e),await Mc(n)}finally{await Mi(o)}}function He(e){return Buffer.from(JSON.stringify(Fc(e)),"utf8")}function Fc(e){if(Array.isArray(e))return e.map(t=>Fc(t));if(gt(e)){let t={};for(let n of Object.keys(e).sort())t[n]=Fc(e[n]);return t}return e}function Wr(e,t){try{return JSON.parse(e)}catch(n){throw new H(z.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function _c(e,t){if(e===null)return null;switch(typeof e){case"boolean":case"number":case"string":return e;case"object":if(Array.isArray(e))return e.map(n=>_c(n,t));if(gt(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=_c(o,t);return n}break}throw new H(z.INVALID_JSON,`${t} must be JSON-serializable`)}function Xm(e,t){if(!Array.isArray(e))throw new H(z.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!Ge(n))throw new H(z.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function _i(e,t){if(!Ge(e))throw new H(z.INVALID_PATH,`${t} must be a sha256 digest`)}function Ge(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function qt(e){return`sha256:${vR("sha256").update(e).digest("hex")}`}function $R(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function Qt(e,t,n){try{return await ve.readFile(e)}catch(r){throw new H(t,`${n} not found: ${e}`,{cause:r})}}async function Oc(e){try{return await ve.readFile(e)}catch(t){if(Yr(t))return null;throw t}}function jc(e,t,n){if(qt(e)!==t)throw new H(z.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function Ue(e){try{return await ve.access(e),!0}catch(t){if(Yr(t))return!1;throw t}}async function Mi(e){try{await ve.rm(e,{force:!0,recursive:!0})}catch{}}async function Mc(e){try{let t=await ve.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function Di(e){try{return await ve.readdir(e)}catch(t){if(Yr(t))return[];throw t}}function VR(e){if(typeof e!="string"||e.trim().length===0)throw new H(z.INVALID_ROOT,"history store rootDir must be a non-empty string");return ke.resolve(e)}function Bi(e){return ke.join(e,kR)}function Cc(e){return ke.join(e,CR)}function UR(e){return ke.join(e,RR)}function zm(e){return ke.join(e,wR)}async function Lm(e){try{let t=await ve.readFile(zm(e),"utf8"),n=Wr(t,"document version");if(!gt(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new H(z.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(Yr(t))return 0;throw t}}async function Ti(e){let t=await Qt(e,z.RECOVERY_PENDING,"transaction journal"),n=Wr(Buffer.from(t).toString("utf8"),"transaction journal");return Wm(n),n}function Wm(e){if(!gt(e)||e.schemaVersion!==IR||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!PR(e.historyTransition)||!Array.isArray(e.files))throw new H(z.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!gt(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!Ge(t.preDigest)||t.postDigest!==null&&!Ge(t.postDigest))throw new H(z.INVALID_SCHEMA,"transaction journal file digest is invalid")}function KR(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function Hr(e){return ke.join(e,"entries")}function Gr(e){return ke.join(e,"blobs")}function Xr(e){return ke.join(e,"tmp")}function $c(e){return ke.join(Xr(e),"stages")}function Vc(e,t){return ke.join($c(e),`${t}.json`)}function Uc(e,t){return ke.join(Hr(e),`${Ym(t)}.json`)}function Kc(e,t){return ke.join(Gr(e),Ym(t))}function Jc(e,t){return ke.join(Hr(e),`${t}.json`)}function Xc(e,t){return ke.join(Gr(e),t)}async function Hm(e,t){return Gm(Uc(e,t),Jc(e,t))}async function zc(e,t){return Gm(Kc(e,t),Xc(e,t))}async function Gm(e,t){return await Ue(e)?e:await Ue(t)?t:e}function Ym(e){return e.slice(7)}function Bm(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return Ge(t)?t:null}function gt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Yr(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function JR(e){return{maxEntries:e?.maxEntries??Fi.maxEntries,maxSessionBytes:e?.maxSessionBytes??Fi.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??Fi.maxEntryBytes}}async function XR(e){let t=Bi(e);await Ue(t)||await Bc(e,[],-1)}export{H as FileHistoryStoreError,Or as PageTemplateManagedSourceError,Ai as PreviewFileSystemSiteEditEngineRuntime,lp as SITE_EDIT_RAW_COLOR_LITERAL_RE,Ni as SnapshotSiteEditEngineRuntime,Fp as computeManagedPageTemplatePaths,ER as createPreviewSiteEditEngineRuntime,yR as createSiteEditEngineRuntime,Tp as decodePageTemplateKey,oc as encodePageTemplateId,_p as isManagedPageTemplateSourcePath,jm as openFileHistoryStore,xk as resolveManagedPageTemplateComposition,gi as scanManagedPageTemplateCandidates,Mp as scanSiteEditCompositionsFromFiles,Fr as scanSiteEditThemeStyleViolations};