@vcp-dev/site-edit-engine 0.11.45 → 0.11.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1 -1
  2. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@ import*as bC from"@babel/parser";import*as qt from"@babel/types";import*as Wr fr
3
3
  `).map(r=>ZR(r,t)).join(`
4
4
  `)}function dc(e){let{ast:t,source:n}=e;try{let r=YR(n),i=GR(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=qR(i,r)),{ok:!0,source:i}}catch(r){return de(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}function qh(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 hs(e,t,n){return{ok:!0,source:t,operation:{type:n.kind,nodeId:n.target,kind:n.kind,target:n.target,beforeSourceHash:qh(e),afterSourceHash:qh(t),inverse:n.inverse}}}function et(e,t,n){let r=dc({ast:e,source:t});return r.ok?hs(t,r.source,n):r}function ft(e,t){let n=ds(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function fc(e,t){return dc({ast:e,source:t})}function lP(e,t,n){let r=Be(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function ui(e,t,n){let r=lP(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:de(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function Zr(e){return typeof e=="string"?Sd(e):typeof e=="number"?sP(e):typeof e=="boolean"?eP(e):e===null?iP():Array.isArray(e)?QR(e.map(t=>Zr(t))):aP(Object.entries(e).map(([t,n])=>{let r=cP(Ed(t),Zr(n));return t==="__proto__"&&(r.computed=!0),r}))}function uP(e){return typeof e=="string"?Sd(e):rP(Zr(e))}function ys(e,t){return nP(oP(e),uP(t))}function pc(e,t){try{let r=Qh.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:de(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:de(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function Ed(e){return/^[$A-Z_][0-9A-Z_$]*$/i.test(e)?tP(e):Sd(e)}function mc(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=ft(t,"jsx-node");if(!i.ok)return i.result;let s=Be(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let l=dP(s.match.path)[r];if(!l)return de(t,"locator-miss",`Text segment ${r} not found`,"jsx-node");switch(l.kind){case"jsx-text":{let c=l.path.node.value;if(o.trim().length===0){let d=c.match(/^\s*/)?.[0]??"",f=c.match(/\s*$/)?.[0]??"";l.path.replaceWithMultiple([...d?[Do.jsxText(d)]:[],Do.jsxExpressionContainer(Do.stringLiteral("")),...f?[Do.jsxText(f)]:[]]);break}let u=fP(c,o);l.path.node.value=u,l.path.node.extra={rawValue:u,raw:u.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/{/g,"&#123;").replace(/}/g,"&#125;")};break}case"string-literal":l.path.node.value=o;break;case"template-literal":{let c=l.quasiIndex;l.path.node.quasis[c].value.raw=o.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${").replace(/\r/g,"\\r"),l.path.node.quasis[c].value.cooked=o;break}}return et(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function dP(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=pP(r.get("expression"));o.length>0&&t.push(...o)}}return t}function fP(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function pP(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||n.length===1&&e.node.expressions.length===0)&&t.push({kind:"template-literal",path:e,quasiIndex:r});if(t.length>0)return t}return e.isCallExpression()?[]:[]}import{nullLiteral as Id}from"@babel/types";function Mo(e){let{source:t,locator:n}=e,r=ft(t,"jsx-node");if(!r.ok)return r.result;let o=Be(r.ast,n);return o.ok?(mP(o.match.path),et(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function mP(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Id());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Id());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Id());return}e.remove()}import{cloneNode as gP}from"@babel/types";function di(e){let t=ft(e.source,"jsx-node");if(!t.ok)return t.result;let n=Be(t.ast,e.locator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};let r=pc(e.source,e.node.jsx);return r.ok?(n.match.path.replaceWith(gP(r.node,!0)),et(t.ast,e.source,{kind:"replace-node",target:"jsx-node",inverse:"replace-node"})):r.result}import{cloneNode as CP}from"@babel/types";import vd from"@babel/traverse";import*as Re from"@babel/types";function xs(e,t,n){return`${e}::${t}::${n}`}var Z={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"};var hP=typeof vd=="function"?vd:vd.default;function Un(e,t,n,r){if(!e.ok)return e;let o=$n(n,t);if(!o)return e;let i=yP(t,o,r);return i?{...e,selectionRef:i}:e}function yP(e,t,n){let r=xP(e,t);if(!r)return;let o=n.sourceLocator?ey(n.sourceLocator):void 0,i=n.targetParentLocator?ey(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??SP(r)??i?.component??o?.component;if(!(!s||!a))return{key:xs(s,a,EP(r))}}function ey(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function xP(e,t){let n=sy(e,t);return!n||n.node.type!=="JSXElement"?null:n}function sy(e,t){let n=null;return hP(e,{JSXElement(r){r.node===t&&(n=r,r.stop())},JSXFragment(r){r.node===t&&(n=r,r.stop())}}),n}function $n(e,t){if(!e)return null;if(Re.isJSXElement(e))return _P(t,e)?ty(e.children,t):e;if(Re.isJSXFragment(e))return ty(e.children,t);if(Re.isJSXExpressionContainer(e)||Re.isParenthesizedExpression(e)||Re.isTSAsExpression(e)||Re.isTSSatisfiesExpression(e)||Re.isTSTypeAssertion(e)||Re.isTSNonNullExpression(e))return $n(e.expression,t);if(Re.isLogicalExpression(e))return $n(e.right,t);if(Re.isConditionalExpression(e))return $n(e.consequent,t)??$n(e.alternate,t);if(Re.isCallExpression(e)||Re.isOptionalCallExpression(e))return ay(e)?bP(e.arguments[0],t):null;if(Re.isArrayExpression(e))for(let n of e.elements){if(!n)continue;let r=$n(n,t);if(r)return r}return null}function ty(e,t){for(let n of e){let r=$n(n,t);if(r)return r}return null}function bP(e,t){return!e||!Re.isArrowFunctionExpression(e)&&!Re.isFunctionExpression(e)?null:Re.isBlockStatement(e.body)?bs(e.body.body,t):$n(e.body,t)}function bs(e,t){for(let n of e){if(Re.isReturnStatement(n)){let r=$n(n.argument,t);if(r)return r;continue}if(Re.isBlockStatement(n)){let r=bs(n.body,t);if(r)return r;continue}if(Re.isIfStatement(n)){let r=ny(n.consequent,t);if(r)return r;let o=n.alternate?ny(n.alternate,t):null;if(o)return o;continue}if(Re.isSwitchStatement(n))for(let r of n.cases){let o=bs(r.consequent,t);if(o)return o}}return null}function ny(e,t){return Re.isBlockStatement(e)?bs(e.body,t):bs([e],t)}function SP(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(Re.isFunctionDeclaration(n))return n.id?.name??"default"}if(t.isVariableDeclarator()&&Re.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 ry=new WeakMap,oy=new WeakMap,kd=new WeakMap;function EP(e){let t=ry.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=IP(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return ry.set(e.node,o),o}function IP(e){let t=cy(e.node.openingElement.name);return!t||ht(e)?null:/^[A-Z]/.test(t)?`component:${t}#${iy(e,t)}`:`${t}#${iy(e,t)}`}function iy(e,t){let n=vP(e);if(!n)return 0;let r=kd.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=kd.get(n.node);o||(o=new Map,kd.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of Bo(n))if(cy(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 vP(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(ht(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Bo(e){let t=oy.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(ht(o)){n.push(...Bo(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Bo(o));continue}o.isJSXExpressionContainer()&&n.push(...dr(o.get("expression")))}return oy.set(e.node,n),n}function dr(e){if(e.isJSXElement())return ht(e)?Bo(e):[e];if(e.isJSXFragment())return Bo(e);if(e.isParenthesizedExpression())return dr(e.get("expression"));if(e.isLogicalExpression())return dr(e.get("right"));if(e.isConditionalExpression())return[...dr(e.get("consequent")),...dr(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:dr(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&ay(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?kP(n):[]}return[]}function kP(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return ht(t)?Bo(t):[t];if(t.isJSXFragment())return Bo(t);if(t.isParenthesizedExpression())return dr(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return dr(t);if(!t.isBlockStatement())return[];let n=[];for(let r of t.get("body")){if(r.isVariableDeclaration())for(let i of r.get("declarations")){let s=i.get("init");(s.isJSXElement()||s.isJSXFragment())&&n.push(...dr(s))}if(!r.isReturnStatement())continue;let o=r.get("argument");return o.node&&n.push(...dr(o)),n}return n}function ay(e){let t=e.callee;return(Re.isMemberExpression(t)||Re.isOptionalMemberExpression(t))&&Re.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function _P(e,t){let n=sy(e,t);return n?ht(n):!1}function cy(e){return Re.isJSXIdentifier(e)?e.name:Re.isJSXMemberExpression(e)?ly(e):Re.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function ly(e){return`${Re.isJSXIdentifier(e.object)?e.object.name:ly(e.object)}.${e.property.name}`}function qr(e,t){if(t.parentPath===e&&t.listKey==="children"&&_d(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!_d(n))return null;let r=n;for(;r&&r!==e;){if(!_d(r)||!ht(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function _d(e){return e.isJSXElement()||e.isJSXFragment()}function Vn(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=ft(t,"jsx-node");if(!a.ok)return a.result;let l=Be(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return de(t,"unsupported-syntax","insert-child target must be a JSXElement or JSXFragment","jsx-node");let c=l.match.path;if(l.match.path.isJSXElement()){let S=l.match.path.node;if(!S.closingElement||S.openingElement.selfClosing)return de(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=pc(t,r.jsx);if(!u.ok)return u.result;let d=CP(u.node,!0),f=c.node.children,m={...s,targetParentLocator:n},g=S=>s?Un(S,a.ast,d,m):S;if(o==="append")return f.push(d),g(et(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return f.unshift(d),g(et(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(!i)return de(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let p=Be(a.ast,i);if(!p.ok)return{ok:!1,source:t,diagnostic:p.diagnostic};let h=qr(l.match.path,p.match.path);if(!h)return de(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");c=h;let x=c.node.children,b=x.findIndex(S=>S===p.match.path.node);return b===-1?de(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(x.splice(o==="before"?b:b+1,0,d),g(et(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as uy from"@babel/parser";import{cloneNode as RP}from"@babel/types";function gc(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=ft(t,"jsx-node");if(!a.ok)return a.result;let l=PP(t,r);if(!l.ok)return l.result;let c=Be(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return de(t,"unsupported-syntax","insert-jsx-expression-child target must be a JSXElement or JSXFragment","jsx-node");if(c.match.path.isJSXElement()){let x=c.match.path.node;if(!x.closingElement||x.openingElement.selfClosing)return de(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=c.match.path,d=null;if(i){let x=Be(a.ast,i);if(!x.ok)return{ok:!1,source:t,diagnostic:x.diagnostic};let b=qr(c.match.path,x.match.path);if(!b)return de(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=b,d=x.match.path.node}else if(o==="before"||o==="after")return de(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let f=RP(l.node,!0),m=u.node.children,g={...s,targetParentLocator:n},p=x=>s?Un(x,a.ast,f,g):x;if(o==="append")return m.push(f),p(et(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return m.unshift(f),p(et(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let h=m.findIndex(x=>x===d);return h===-1?de(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(m.splice(o==="before"?h:h+1,0,f),p(et(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function PP(e,t){try{let r=uy.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:de(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:de(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as NP,nullLiteral as Cd}from"@babel/types";import*as Qr from"@babel/types";import*as dy from"@babel/types";function Ss(e,t){let n=e.parentPath;if(!n?.isConditionalExpression()||e.key!=="consequent"||!dy.isNullLiteral(n.node.alternate))return e;let r=n.parentPath;return!r?.isJSXExpressionContainer()||r.parentPath?.node!==t.node||r.listKey!=="children"?e:r}function jo(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=ft(t,"jsx-node");if(!a.ok)return a.result;let l=Be(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};let c=Be(a.ast,r);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return de(t,"unsupported-syntax","move-node target parent must be a JSXElement or JSXFragment","jsx-node");let u=c.match.path;if(c.match.path.isJSXElement()){let S=c.match.path.node;if(!S.closingElement||S.openingElement.selfClosing)return de(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let d=null;if(i){let S=Be(a.ast,i);if(!S.ok)return{ok:!1,source:t,diagnostic:S.diagnostic};let E=S.match.path.isJSXElement()?Ss(S.match.path,c.match.path):S.match.path,v=qr(c.match.path,E);if(!v)return de(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=v,d=E}else if(o==="before"||o==="after")return de(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let f=d&&typeof d.key=="number"?d.key:-1;if(d&&f===-1)return de(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let m=l.match.path.isJSXElement()?Ss(l.match.path,c.match.path):l.match.path,g=NP(m.node,!0);if(!Qr.isJSXElement(g)&&!Qr.isJSXExpressionContainer(g)&&!Qr.isJSXFragment(g)&&!Qr.isJSXText(g))return de(t,"unsupported-syntax","move-node source must resolve to a JSX child","jsx-node");let p=m.parentPath?.node===u.node&&typeof m.key=="number"?m.key:-1;if(d&&m.parentPath?.node===d.parentPath?.node&&m.key===d.key)return de(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");AP(m);let h=u.node.children,x={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return h.push(g),Un(fc(a.ast,t),a.ast,g,x);if(o==="prepend")return h.unshift(g),Un(fc(a.ast,t),a.ast,g,x);let b=f-(p!==-1&&p<f?1:0);return h.splice(o==="before"?b:b+1,0,g),Un(fc(a.ast,t),a.ast,g,x)}function AP(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Cd());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Cd());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Cd());return}e.remove()}import*as fy from"@babel/parser";import{cloneNode as wP,nullLiteral as Rd}from"@babel/types";function hc(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,l=ft(t,"jsx-node");if(!l.ok)return l.result;let c=TP(t,s);if(!c.ok)return c.result;let u=Be(l.ast,n);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};let d=Be(l.ast,r);if(!d.ok)return{ok:!1,source:t,diagnostic:d.diagnostic};if(!d.match.path.isJSXElement()&&!d.match.path.isJSXFragment())return de(t,"unsupported-syntax","move-repeat-template-child target parent must be a JSXElement or JSXFragment","jsx-node");if(d.match.path.isJSXElement()){let S=d.match.path.node;if(!S.closingElement||S.openingElement.selfClosing)return de(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let f=d.match.path,m=null;if(i){let S=Be(l.ast,i);if(!S.ok)return{ok:!1,source:t,diagnostic:S.diagnostic};let E=qr(d.match.path,S.match.path);if(!E)return de(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");f=E,m=S.match.path.node}else if(o==="before"||o==="after")return de(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!u.match.path.isJSXElement())return de(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let g=f.node,p=wP(c.node,!0);OP(u.match.path);let h={...a,sourceLocator:n,targetParentLocator:r},x=g.children;if(o==="append")return x.push(p),Un(et(l.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),l.ast,p,h);if(o==="prepend")return x.unshift(p),Un(et(l.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),l.ast,p,h);let b=x.findIndex(S=>S===m);return b===-1?de(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(x.splice(o==="before"?b:b+1,0,p),Un(et(l.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),l.ast,p,h))}function TP(e,t){try{let r=fy.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:de(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:de(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function OP(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Rd());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Rd());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Rd());return}e.remove()}import{SiteEditSetPropsParamsSchema as LP,classifySiteEditPropertyName as FP}from"@vcp-dev/platform-shared/contracts";import*as fi from"@babel/types";function yc(e){let t=LP.safeParse({kind:"set-props",scope:"selection",changes:e.changes});if(!t.success)return de(e.source,"unsupported-syntax","Invalid typed JSX property changes","jsx-node",{issues:t.error.issues});let n=ft(e.source,"jsx-node");if(!n.ok)return n.result;let r=ui(n.ast,e.locator,e.source);if(!r.ok)return r.result;for(let a of t.data.changes){let l=FP(a.name);if(l.owner!=="generic")return de(e.source,"unsupported-syntax",l.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(fi.isJSXAttribute),s=new Map;for(let a of i){let l=DP(a);if(!l)continue;let c=s.get(l)??[];c.push(a),s.set(l,c)}for(let a of t.data.changes)if((s.get(a.name)??[]).length>1)return de(e.source,"unsupported-syntax",`JSX attribute '${a.name}' has multiple sources`,"jsx-node");for(let a of t.data.changes){let l=s.get(a.name)?.[0];if(a.operation==="remove"){l&&(o.attributes=o.attributes.filter(u=>u!==l));continue}let c=ys(a.name,a.value).value;l?l.value=c:o.attributes.push(ys(a.name,a.value))}return et(n.ast,e.source,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}function DP(e){return fi.isJSXIdentifier(e.name)?e.name.name:fi.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{SiteEditOperationParamsSchema as MP}from"@vcp-dev/platform-shared/contracts";import*as ye from"@babel/types";var py=["prefetch","replace","scroll","locale","onNavigate"],BP=/^on(?:Click|DoubleClick|AuxClick|MouseDown|MouseUp|PointerDown|PointerUp|TouchStart|TouchEnd|KeyDown|KeyUp|ContextMenu)(?:Capture)?$/;function jP(e){let t=e;for(;t;){if(t.isJSXElement()&&t.node.openingElement.attributes.some(n=>ye.isJSXAttribute(n)&&ye.isJSXIdentifier(n.name)&&BP.test(n.name.name)))return!0;t=t.parentPath}return!1}function xc(e){let t=ft(e.source,"jsx-node");if(!t.ok)return t.result;let n=ui(t.ast,e.locator,e.source);if(!n.ok)return n.result;let r=MP.safeParse({kind:"set-link-target",scope:"selection",link:e.link,changes:e.changes});if(!r.success||r.data.kind!=="set-link-target")return Tr(e.source,"Invalid typed link-target changes");let o=n.match.path,i=o.node,s=i.openingElement,a=zP(s.name);if(!a)return Tr(e.source,"Unsupported JSX link tag");if(s.attributes.some(ye.isJSXSpreadAttribute))return Tr(e.source,"Link elements with spread props cannot be transformed safely");let l=new Map;for(let g of s.attributes){if(!ye.isJSXAttribute(g))continue;let p=Nd(g);if(!p)return Tr(e.source,"Unsupported JSX attribute name");let h=l.get(p)??[];h.push(g),l.set(p,h)}if([...l.values()].some(g=>g.length>1))return Tr(e.source,"Duplicate JSX attributes cannot be transformed safely");let c=l.get("href")?.[0];if(c&&!XP(c))return Tr(e.source,"Dynamic link href cannot be transformed safely");let u=a==="a",d=u?null:VP(o,s.name);if(!u&&!d)return Tr(e.source,"Only native anchors and imported next/link components are supported");if(e.link.kind==="none"&&jP(o))return Tr(e.source,"A link with an active event handler in its JSX ancestry cannot become an inert anchor");let f=null;if(e.link.kind==="internal-route")if(d)f=a;else{let g=KP(t.ast,o);if(!g.ok)return Tr(e.source,g.reason);f=g.localName}if(d&&e.link.kind!=="internal-route"){let g=ye.jsxIdentifier("a");s.name=g,i.closingElement&&(i.closingElement.name=ye.jsxIdentifier("a")),JP(t.ast,d,o)}else f&&u&&(s.name=ye.jsxIdentifier(f),i.closingElement&&(i.closingElement.name=ye.jsxIdentifier(f)));let m=new Set;return e.link.kind==="none"?(m.add("href"),m.add("target"),m.add("rel"),py.forEach(g=>m.add(g))):(m.add("href"),e.link.kind==="native-link"&&py.forEach(g=>m.add(g))),s.attributes=s.attributes.filter(g=>{if(!ye.isJSXAttribute(g))return!0;let p=Nd(g);return!p||!m.has(p)}),e.link.kind!=="none"&&s.attributes.push(ye.jsxAttribute(ye.jsxIdentifier("href"),ye.stringLiteral(e.link.href))),$P(s,e.changes),et(t.ast,e.source,{kind:"set-link-target",target:"jsx-node",inverse:"set-link-target"})}function $P(e,t){for(let n of t){let r=e.attributes.find(s=>ye.isJSXAttribute(s)&&Nd(s)===n.name);if(n.operation==="remove"){e.attributes=e.attributes.filter(s=>s!==r);continue}let o=typeof n.value=="string"?ye.stringLiteral(n.value):ye.jsxExpressionContainer(Pd(n.value)),i=ye.jsxAttribute(ye.jsxIdentifier(n.name),o);r&&ye.isJSXAttribute(r)?r.value=i.value:e.attributes.push(i)}}function Pd(e){return e===null?ye.nullLiteral():typeof e=="string"?ye.stringLiteral(e):typeof e=="number"?ye.numericLiteral(e):typeof e=="boolean"?ye.booleanLiteral(e):Array.isArray(e)?ye.arrayExpression(e.map(t=>Pd(t))):typeof e=="object"?ye.objectExpression(Object.entries(e).map(([t,n])=>ye.objectProperty(ye.isValidIdentifier(t)?ye.identifier(t):ye.stringLiteral(t),Pd(n)))):ye.nullLiteral()}function UP(e){return ye.isImportDefaultSpecifier(e)||ye.isImportSpecifier(e)&&e.importKind!=="type"&&(ye.isIdentifier(e.imported,{name:"default"})||ye.isStringLiteral(e.imported,{value:"default"}))}function my(e){return!e.parentPath?.isImportDeclaration()||e.parentPath.node.importKind==="type"?!1:e.isImportDefaultSpecifier()||e.isImportSpecifier()&&e.node.importKind!=="type"&&(ye.isIdentifier(e.node.imported,{name:"default"})||ye.isStringLiteral(e.node.imported,{value:"default"}))}function VP(e,t){if(!ye.isJSXIdentifier(t))return null;let n=e.scope.getBinding(t.name);if(!n||!my(n.path))return null;let r=n.path.parentPath;return!r?.isImportDeclaration()||r.node.source.value!=="next/link"?null:t.name}function KP(e,t){let n=e.program.body.filter(l=>ye.isImportDeclaration(l)&&l.source.value==="next/link"&&l.importKind!=="type"),r=n[0],o=n.flatMap(l=>l.specifiers).find(UP);if(o)return t.scope.getBinding(o.local.name)?.path.node!==o?{ok:!1,reason:"The next/link import is shadowed at the selected element"}:{ok:!0,localName:o.local.name};let i=t.scope.getProgramParent(),s=["Link","NextLink",...Array.from({length:20},(l,c)=>`NextLink${c+2}`)].find(l=>!i.hasBinding(l)&&!t.scope.hasBinding(l));if(!s)return{ok:!1,reason:"Cannot create an unshadowed runtime next/link import"};let a=ye.importDefaultSpecifier(ye.identifier(s));if(r)r.specifiers.unshift(a);else{let l=ye.importDeclaration([a],ye.stringLiteral("next/link")),c=0;for(;c<e.program.body.length&&ye.isImportDeclaration(e.program.body[c]);)c+=1;e.program.body.splice(c,0,l)}return{ok:!0,localName:s}}function JP(e,t,n){let r=n.scope.getProgramParent();r.crawl();let o=r.getBinding(t);if(!o||!my(o.path)||o.referenced)return;let i=o.path.parentPath;if(!(!i?.isImportDeclaration()||i.node.source.value!=="next/link")&&(i.node.specifiers=i.node.specifiers.filter(s=>s!==o.path.node),i.node.specifiers.length===0)){let s=e.program.body.indexOf(i.node);s>=0&&e.program.body.splice(s,1)}}function XP(e){return!e.value||ye.isStringLiteral(e.value)}function zP(e){return ye.isJSXIdentifier(e)?e.name:null}function Nd(e){return ye.isJSXIdentifier(e.name)?e.name.name:null}function Tr(e,t){return de(e,"unsupported-syntax",t,"jsx-node")}import*as Xt from"@babel/types";import{classifySiteEditPropertyName as gy}from"@vcp-dev/platform-shared/contracts";function bc(e){let t=gy(e.name),n=gy(e.property);if(t.owner!=="generic"||n.owner!=="generic")return de(e.source,"unsupported-syntax","Property binding is only available for generic properties","jsx-node");if(!hy(e.object))return de(e.source,"unsupported-syntax","Property binding object must be a single identifier","jsx-node");if(e.property.length===0)return de(e.source,"unsupported-syntax","Property binding requires a non-empty property name","jsx-node");let r=ft(e.source,"jsx-node");if(!r.ok)return r.result;let o=ui(r.ast,e.locator,e.source);if(!o.ok)return o.result;let i=o.match.path.node.openingElement,s=i.attributes.filter(c=>Xt.isJSXAttribute(c)&&HP(c)===e.name);if(s.length>1)return de(e.source,"unsupported-syntax",`JSX attribute '${e.name}' has multiple sources`,"jsx-node");let a=WP(e.object,e.property),l=s[0];if(l)l.value=Xt.jsxExpressionContainer(a);else{let c=ys(e.name,"");c.value=Xt.jsxExpressionContainer(a),i.attributes.push(c)}return et(r.ast,e.source,{kind:"set-property-binding",target:"jsx-node",inverse:"restore-property-binding"})}function WP(e,t){return hy(t)?Xt.memberExpression(Xt.identifier(e),Xt.identifier(t)):Xt.memberExpression(Xt.identifier(e),Xt.stringLiteral(t),!0)}function hy(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)}function HP(e){return Xt.isJSXIdentifier(e.name)?e.name.name:Xt.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{getBindingIdentifiers as YP,identifier as Es,importDeclaration as ZP,importDefaultSpecifier as qP,importNamespaceSpecifier as QP,importSpecifier as eN,isImportDefaultSpecifier as yy,isImportNamespaceSpecifier as xy,isImportSpecifier as by,stringLiteral as tN}from"@babel/types";function Kn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(h=>!uN(h));if(o!==-1){let h=r[o],x=h&&typeof h=="object"&&"kind"in h?h.kind:void 0;return de(t,"unsupported-syntax",`Unsupported import spec kind: ${String(x)}`)}let i=aN(r);if(!i.ok)return de(t,"unsupported-syntax",i.message);let s=ft(t);if(!s.ok)return s.result;let{ast:a}=s,l=a.program,c=l.body.filter(h=>h.type==="ImportDeclaration"&&h.source.value===n),u=new Set(c.flatMap(h=>h.specifiers.flatMap(x=>{let b=dN(h,x);return b?[b]:[]}))),d=i.imports.filter(h=>!u.has(_y(h)));if(d.length===0)return hs(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let f=cN(l.body),m=d.find(h=>f.has(Ad(h)));if(m)return de(t,"unsupported-syntax",`Import local binding already exists: ${Ad(m)}`);let g=sN(d);if(g.reduce((h,x)=>h+x.length,0)!==d.length)return de(t,"unsupported-syntax","Unsupported import specifier grouping");for(let h of g){if(!vy(Ey(h)))return de(t,"unsupported-syntax","Unsupported import specifier combination");let x=c.find(b=>nN(b,h));if(x)rN(x,h);else{let b=ZP(Sy(h),tN(n));lN(l.body,b),c.push(b)}}return et(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function nN(e,t){return e.importKind==="type"?!1:vy(iN(oN(e),Ey(t)))}function rN(e,t){let n=!1,r=new Set(e.specifiers.map(o=>wd(o)));for(let o of Sy(t)){let i=wd(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return ky(e.specifiers),{changed:n}}function Sy(e){let t=e.map(n=>{switch(n.kind){case"named":return eN(n.local?Es(n.local):Es(n.imported),Es(n.imported));case"default":return qP(Es(n.local));case"namespace":return QP(Es(n.local));default:return n}});return ky(t),t}function Ey(e){let t=Iy();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 oN(e){let t=Iy();for(let n of e.specifiers)yy(n)?t.defaultLocals.add(n.local.name):xy(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function Iy(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function iN(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function vy(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function ky(e){let t=[...e.filter(n=>yy(n)),...e.filter(n=>xy(n)),...e.filter(n=>by(n))];e.splice(0,e.length,...t)}function sN(e){let t=e.filter(i=>i.kind==="default"),n=e.filter(i=>i.kind==="namespace"),r=e.filter(i=>i.kind==="named"),o=[];if(n.length>0){let i=Math.max(t.length,n.length);for(let s=0;s<i;s+=1){let a=[],l=t[s],c=n[s];l&&a.push(l),c&&a.push(c),o.push(a)}return r.length>0&&o.push(r),o}if(t.length>0){o.push([t[0],...r]);for(let i of t.slice(1))o.push([i])}else r.length>0&&o.push(r);return o}function aN(e){let t=new Map,n=new Map;for(let r of e){let o=_y(r);if(t.has(o))continue;let i=Ad(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 cN(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(YP(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 lN(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 uN(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 _y(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 Ad(e){return e.kind==="named"?e.local??e.imported:e.local}function dN(e,t){return e.importKind==="type"||by(t)&&t.importKind==="type"?null:wd(t)}function wd(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 pi(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(u=>!pN(u));if(o!==-1){let u=r[o],d=u&&typeof u=="object"&&"kind"in u?u.kind:void 0;return de(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(d)}`)}let i=ft(t);if(!i.ok)return i.result;let{ast:s}=i,a=s.program,l=a.body.findIndex(u=>u.type==="ImportDeclaration"&&u.source.value===n);if(l===-1)return hs(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let c=a.body[l];return r.length===0?(a.body.splice(l,1),et(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(c.specifiers=c.specifiers.filter(u=>!r.some(d=>fN(u,d))),c.specifiers.length===0&&a.body.splice(l,1),et(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function fN(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 pN(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 Is(e){let{source:t,locator:n,next:r}=e,o=vc(t,n);return o.ok?(o.path.replaceWith(Zr(r)),et(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function Sc(e){let{source:t,locator:n,index:r,value:o}=e,i=vc(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(s=>s?.type==="SpreadElement")?de(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>i.path.node.elements.length?de(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,0,Zr(o)),et(i.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):de(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function Ec(e){let{source:t,locator:n,index:r}=e,o=vc(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(i=>i?.type==="SpreadElement")?de(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=o.path.node.elements.length?de(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(o.path.node.elements.splice(r,1),et(o.ast,t,{kind:"remove-array-element",target:"value",inverse:"insert-array-element"})):de(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function Ic(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=vc(t,n);if(!i.ok)return i.result;if(!i.path.isArrayExpression())return de(t,"unsupported-syntax","Array operations require array expression target","value");if(i.path.node.elements.some(l=>l?.type==="SpreadElement"))return de(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 de(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),et(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function vc(e,t){let n=ft(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=Be(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 Gt from"@babel/types";function kc(e){let t=ft(e.source,"value");if(!t.ok)return t.result;let n=Be(t.ast,e.objectLocator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};if(!n.match.path.isObjectExpression())return de(e.source,"unsupported-syntax","Object property upsert requires an ObjectExpression parent","value");let r=n.match.path.node;if(r.properties.some(a=>Gt.isSpreadElement(a)||Gt.isObjectProperty(a)&&a.computed))return de(e.source,"unsupported-syntax","Object property upsert does not support spreads or computed keys","value");let o=r.properties.filter(a=>Gt.isObjectProperty(a)&&mN(a.key)===e.name);if(o.length>1)return de(e.source,"unsupported-syntax",`Object property '${e.name}' has multiple sources`,"value");let i=e.value.kind==="undefined"?Gt.unaryExpression("void",Gt.numericLiteral(0)):Zr(e.value.value),s=o[0];if(s)s.value=i,s.shorthand=!1;else{let a=Gt.objectProperty(Ed(e.name),i);e.name==="__proto__"&&(a.computed=!0),r.properties.push(a)}return et(t.ast,e.source,{kind:"upsert-object-property",target:"value",inverse:"restore-object-property"})}function mN(e){return Gt.isIdentifier(e)?e.name:Gt.isStringLiteral(e)?e.value:Gt.isNumericLiteral(e)?String(e.value):null}import{isSiteEditRuntimeContainerTag as gN,isSiteEditRuntimeVoidElementTag as hN}from"@vcp-dev/platform-shared/contracts/site-edit-runtime-capability";function mi(e){if(!e.composition)throw new Error("Composition unavailable for render source graph.");return e.composition}function yN(e,t,n){let r=mi(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(E=>({kind:E.kind,message:E.reason})),a=i.isOpaque,c=o.parentKey===null&&i.componentName==="Page",u=i.tag.toLowerCase(),d=i.tag!==u,f=!d&&hN(u),m=d||gN(u),g=d&&i.childKeys.length>0&&!i.isPublicUiComponent,p=i.textSegments.length>0&&i.textSegments.some(E=>E.editable);f&&!s.some(E=>E.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' is void: children cannot be inserted`}),!f&&!m&&!s.some(E=>E.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' cannot contain structured children`});let h=p&&(!a||i.importedFrom==="next/link"),x=!i.isPublicUiComponent&&!f&&m&&(!a||g);return{composition:r,key:e,canUpdateText:h,canInsertChild:x,canMove:!c,canRemove:!c,constraints:s}}function _c(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,yN(r,e,t));return n}function Td(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:$e(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=xN(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:$e(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Unable to locate JSX element for key ${t.identity.key}`}]};let r=n.node.openingElement,o=r.attributes.find(d=>d.type==="JSXAttribute"&&d.name.type==="JSXIdentifier"&&d.name.name==="className"),i={key:e.key,composition:e.route.composition,filePath:t.sourceFile,componentName:t.componentName,openingElementRange:Ry(r),version:{documentVersion:e.route.graph.version,contentHash:$e(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",l=n.get("openingElement").get("attributes").find(d=>d.node===o),c=l?.isJSXAttribute()?l.get("value"):null,u=c?.isJSXExpressionContainer()?bN(c.get("expression")):void 0;return{...i,sourceKind:a,attrRaw:Cy(e.route.source,o),valueRaw:s?Cy(e.route.source,s):null,...u===void 0?{}:{resolvedClassName:u},attrRange:Ry(o),diagnostics:[]}}function Py(e){let{source:t,oldAttrRange:n,openingElementRange:r,newAttrRaw:o}=e;if(n){let a=n.start>0&&/\s/.test(t[n.start-1]??"")?n.start-1:n.start,l=o?`${a<n.start?" ":""}${o}`:"";return t.slice(0,a)+l+t.slice(n.end)}if(!o)return t;let i=r.end,s=t.slice(Math.max(0,i-2),i)==="/>"?i-2:i-1;return t.slice(0,s)+` ${o}`+t.slice(s)}function xN(e,t){let n=cr({source:e,profile:wo({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=Be(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:SN(t.sourceRange)});return!r.ok||!r.match.path.isJSXElement()?null:r.match.path}function bN(e){let t=new Set,n=e;if(n.isIdentifier()){for(;n.isIdentifier();){let r=n.scope.getBinding(n.node.name);if(!r?.constant||!r.path.isVariableDeclarator()||!r.path.get("id").isIdentifier({name:n.node.name})||!r.path.parentPath.isVariableDeclaration({kind:"const"})||t.has(r.path.node))return;t.add(r.path.node);let o=r.path.get("init");if(!o.isExpression())return;n=o}if(n.isStringLiteral())return n.node.value;if(n.isTemplateLiteral()&&n.node.expressions.length===0)return n.node.quasis.map(r=>r.value.cooked??r.value.raw).join("")}}function Ny(e){let t=cr({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 Cy(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function Ry(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 SN(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function Ay(){let e=new Set;return{emit(t){for(let n of Array.from(e))try{n(t)}catch{}},subscribe(t){return e.add(t),()=>{e.delete(t)}}}}import{randomUUID as EN}from"node:crypto";import Cc from"node:fs/promises";import Od from"node:path";import{setTimeout as IN}from"node:timers/promises";var vN={async mkdir(e,t){await Cc.mkdir(e,t)},async writeFile(e,t,n){await Cc.writeFile(e,t,n)},async rename(e,t){await Cc.rename(e,t)},async rm(e,t){await Cc.rm(e,t)}},kN=new Set(["EACCES","EBUSY","EPERM"]),_N=[10,20,40,80,160];async function CN(e,t,n){for(let r of _N)try{await e.rename(t,n);return}catch(o){if(!RN(o))throw o;await IN(r)}await e.rename(t,n)}function RN(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&kN.has(e.code)}async function Rc(e,t,n=vN){let r=Od.dirname(e),o=Od.basename(e),i=Od.join(r,`.${o}.${process.pid}.${EN()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await CN(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import Ld from"@babel/traverse";import*as w from"@babel/types";import*as Ge from"@babel/types";function fr(e,t={}){if(Ge.isTSAsExpression(e)||Ge.isTSSatisfiesExpression(e)||Ge.isTSNonNullExpression(e)||Ge.isTypeCastExpression(e)||Ge.isParenthesizedExpression(e))return fr(e.expression,t);if(Ge.isStringLiteral(e))return{status:"resolved",value:e.value};if(Ge.isNumericLiteral(e))return Number.isFinite(e.value)?{status:"resolved",value:e.value}:{status:"unresolved"};if(Ge.isBooleanLiteral(e))return{status:"resolved",value:e.value};if(Ge.isNullLiteral(e))return{status:"resolved",value:null};if(Ge.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(Ge.isIdentifier(e))return e.name==="undefined"&&!t.resolveIdentifier?{status:"undefined"}:t.resolveIdentifier?.(e.name)??{status:"unresolved"};if(Ge.isUnaryExpression(e)&&e.operator==="void"&&Ge.isNumericLiteral(e.argument)&&e.argument.value===0)return{status:"undefined"};if(Ge.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||Ge.isSpreadElement(r))return{status:"unresolved"};let o=fr(r,t);if(o.status!=="resolved")return{status:"unresolved"};n.push(o.value)}return{status:"resolved",value:n}}if(Ge.isObjectExpression(e)){let n=Object.create(null);for(let r of e.properties){if(!Ge.isObjectProperty(r)||r.computed||!Ge.isExpression(r.value))return{status:"unresolved"};let o=PN(r.key);if(o===null)return{status:"unresolved"};let i=fr(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 Ge.isMemberExpression(e)||Ge.isOptionalMemberExpression(e)?t.resolveMember?.(e)??{status:"unresolved"}:{status:"unresolved"}}function PN(e){return Ge.isIdentifier(e)?e.name:Ge.isStringLiteral(e)?e.value:Ge.isNumericLiteral(e)?String(e.value):null}var NN=typeof Ld=="function"?Ld:Ld.default;function Qt(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 AN(e){return/^[A-Z]/.test(e)}function jd(e){let t=e.openingElement;return w.isJSXIdentifier(t.name)?t.name.name==="Fragment":w.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function hi(e){return w.isJSXFragment(e)}function Ty(e){return w.isJSXIdentifier(e.name)?e.name.name:w.isJSXMemberExpression(e.name)?Oy(e.name):w.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function Oy(e){return w.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:w.isJSXMemberExpression(e.object)?`${Oy(e.object)}.${e.property.name}`:e.property.name}function wN(e){return e.split(".")[0]??e}function TN(e){let t=e;for(;t;){let n=t.node;if(w.isFunctionDeclaration(n)&&n.id||w.isVariableDeclarator(n)&&w.isIdentifier(n.id))return n.id.name;if(w.isExportDefaultDeclaration(n)){let r=n.declaration;if(w.isFunctionDeclaration(r)&&r.id)return r.id.name;if(w.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function ON(){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 LN(e){let t=new Map;for(let n of e.program.body){if(!w.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(w.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(w.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(w.isImportSpecifier(o)){let i=w.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function Or(e,t=[]){if(w.isIdentifier(e))return t.push(e.name),t;if(w.isObjectPattern(e)){for(let n of e.properties)w.isObjectProperty(n)?Or(n.value,t):w.isRestElement(n)&&Or(n.argument,t);return t}if(w.isArrayPattern(e)){for(let n of e.elements)n&&(w.isRestElement(n)?Or(n.argument,t):Or(n,t));return t}return w.isAssignmentPattern(e)?(Or(e.left,t),t):(w.isRestElement(e)&&Or(e.argument,t),t)}function Zn(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function vs(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 FN(e,t,n){e.set(t,{resolved:!0,value:n})}function $d(e,t){e.set(t,{resolved:!1})}function Ly(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 Ut(e,t,n){if(w.isTSAsExpression(e)||w.isTSSatisfiesExpression(e)||w.isTSNonNullExpression(e)||w.isTypeCastExpression(e)||w.isParenthesizedExpression(e))return Ut(e.expression,t,n);if(w.isLogicalExpression(e))return Pc([Ut(e.left,t,n),Ut(e.right,t,n)]);if(w.isBinaryExpression(e))return Pc([w.isExpression(e.left)?Ut(e.left,t,n):null,w.isExpression(e.right)?Ut(e.right,t,n):null]);if(w.isConditionalExpression(e))return Pc([Ut(e.consequent,t,n),Ut(e.alternate,t,n)]);if(w.isTemplateLiteral(e))return Pc(e.expressions.filter(w.isExpression).map(i=>Ut(i,t,n)));if(w.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!w.isMemberExpression(e)&&!w.isOptionalMemberExpression(e))return null;let r=[],o=e;for(;w.isMemberExpression(o)||w.isOptionalMemberExpression(o);){if(o.computed)if(w.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(w.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&w.isExpression(o.property)){let i=eo(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(!w.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return w.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:Zn(e,t),base:o.name,path:r}:null}function Pc(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 Ud(e,t,n){if(w.isArrayExpression(e)){let r=e.elements[0];return e.elements.length===1&&w.isExpression(r)?Ut(r,t,n):null}return w.isCallExpression(e)&&w.isMemberExpression(e.callee)&&!e.callee.computed&&w.isIdentifier(e.callee.property)&&["filter","slice","sort","toSorted","reverse","toReversed"].includes(e.callee.property.name)&&w.isExpression(e.callee.object)?Ud(e.callee.object,t,n):Ut(e,t,n)}function eo(e,t){if(w.isStringLiteral(e)||w.isNumericLiteral(e)||w.isBooleanLiteral(e))return e.value;if(w.isNullLiteral(e))return null;if(w.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(w.isIdentifier(e)){let n=vs(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(w.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||w.isSpreadElement(r))return;let o=eo(r,t);if(o===void 0)return;n.push(o)}return n}if(w.isObjectExpression(e)){let n={};for(let r of e.properties){if(!w.isObjectProperty(r)||r.computed||!w.isExpression(r.value))return;let o=null;if(w.isIdentifier(r.key)?o=r.key.name:w.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!w.isIdentifier(r.value))return;let s=vs(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=eo(r.value,t);if(i===void 0)return;n[o]=i}return n}if(w.isMemberExpression(e)){let n=Ut(e,"",t);if(!n)return;let r=vs(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=Ly(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(w.isCallExpression(e))return Dy(e,t)??void 0}function Fy(e,t,n){let r=Ut(e,n,t);if(!r)return w.isMemberExpression(e)||w.isBinaryExpression(e)||w.isLogicalExpression(e)||w.isConditionalExpression(e)||w.isCallExpression(e)?{value:Zn(e,n),source:null}:null;let o=vs(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?Ly(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 Fd(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:ON(),parentStack:[],valueScopes:i,importMap:o}}function Md(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of Or(o.id))$d(n,s);if(!w.isIdentifier(o.id)||!o.init||!w.isExpression(o.init))continue;let i=eo(o.init,t);i!==void 0&&FN(n,o.id.name,i)}}function DN(e){let t=[];for(let n of e){if(w.isVariableDeclaration(n)){t.push(n);continue}w.isExportNamedDeclaration(n)&&n.declaration&&w.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function MN(e,t,n){let r=[],o=0;for(let i of e)if(w.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:Qt(i),editable:!0,source:null})}else if(w.isJSXExpressionContainer(i)&&w.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:Qt(i),editable:!0,source:null});else if(w.isJSXExpressionContainer(i)&&w.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:Qt(i),editable:!0,source:null}):r.push({index:o++,value:Zn(s,n),sourceRange:Qt(i),editable:!0,source:Ut(s,n,t)})}else if(w.isJSXExpressionContainer(i)&&w.isExpression(i.expression)){let s=Fy(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:Qt(i),editable:!0,source:s.source})}return r}function BN(e,t,n){let r=[];for(let[o,i]of e.attributes.entries()){if(!w.isJSXAttribute(i))continue;let s=$N(i.name);if(!s)continue;let a=Zn(i,n);if(w.isStringLiteral(i.value)){r.push({name:s,value:i.value.value,sourceRange:Qt(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:Qt(i),source:null,syntaxKind:"boolean-shorthand",raw:a,order:o,resolution:{status:"resolved",value:!0},resolvedValue:!0});continue}if(w.isJSXExpressionContainer(i.value)&&w.isExpression(i.value.expression)){let l=eo(i.value.expression,t);if(s==="className"){let m=typeof l=="string"?l:l===void 0?Dy(i.value.expression,t):null;if(m){r.push({name:s,value:m,sourceRange:Qt(i),source:null,resolvedValue:m,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:m}});continue}}let c=Fy(i.value.expression,t,n);if(l!==void 0){r.push({name:s,value:WN(l),sourceRange:Qt(i),source:Ut(i.value.expression,n,t),resolvedValue:l,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:l}});continue}let u=UN(i.value.expression,t),d=Ut(i.value.expression,n,t),f=c?.value??Zn(i.value.expression,n);r.push({name:s,value:u.status==="undefined"?"undefined":f,sourceRange:Qt(i),source:c?.source??d,syntaxKind:"expression",raw:a,order:o,resolution:u})}}return r}function jN(e,t,n){return e.attributes.flatMap((r,o)=>!w.isJSXSpreadAttribute(r)||!w.isExpression(r.argument)?[]:[{raw:Zn(r.argument,n),sourceRange:Qt(r),order:o,source:Ut(r.argument,n,t)}])}function $N(e){return w.isJSXIdentifier(e)?e.name:w.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function UN(e,t){return fr(e,{resolveIdentifier(n){let r=vs(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=eo(n,t);return r===void 0?{status:"unresolved"}:{status:"resolved",value:r}}})}function Dy(e,t){let n=gi(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function gi(e,t){if(w.isStringLiteral(e))return[e.value];if(w.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(w.isNullLiteral(e))return[];if(w.isBooleanLiteral(e))return e.value?null:[];if(w.isIdentifier(e)||w.isMemberExpression(e)){if(w.isIdentifier(e)&&e.name==="undefined")return[];let n=eo(e,t);return typeof n=="string"?[n]:null}if(w.isConditionalExpression(e)){let n=gi(e.consequent,t),r=gi(e.alternate,t);return!n||!r?null:[...n,...r]}if(w.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=eo(e.left,t);return n===!1||n===null?[]:gi(e.right,t)}if(w.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||w.isSpreadElement(r))return null;let o=gi(r,t);if(!o)return null;n.push(...o)}return n}if(w.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!w.isObjectProperty(r))return null;let o=KN(r.key);if(!o)return null;n.push(o)}return n}if(w.isCallExpression(e)){let n=VN(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!w.isExpression(o))return null;let i=gi(o,t);if(!i)return null;r.push(...i)}return r}return null}function VN(e){return w.isIdentifier(e)?e.name:w.isMemberExpression(e)&&w.isIdentifier(e.property)?e.property.name:null}function KN(e){return w.isIdentifier(e)?e.name:w.isStringLiteral(e)?e.value:null}function JN(e,t){let n=e.attributes.find(r=>w.isJSXAttribute(r)&&w.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!w.isJSXAttribute(n)||!w.isJSXExpressionContainer(n.value)?null:n.value.expression}function XN(e,t){for(let n of t){let r=JN(e,n);if(r)return r}return null}function zN(e){return w.isJSXIdentifier(e.name)?e.name.name:null}function WN(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function HN(e){if(!w.isCallExpression(e)&&!w.isOptionalCallExpression(e))return null;let t=e.callee;return!w.isMemberExpression(t)&&!w.isOptionalMemberExpression(t)||!w.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!w.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function Dd(e){return w.isArrowFunctionExpression(e)||w.isFunctionExpression(e)}function GN(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function YN(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function wy(e,t,n,r){if(!e||!w.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:Zn(e,n),collectionSource:Ud(e,n,r)};if(t){let i=t.params[0],s=t.params[1];w.isIdentifier(i)&&(o.itemParamName=i.name),w.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function Lr(e,t,n){if(!e)return[];if(w.isJSXElement(e)){if(jd(e))return Oc(e.children,t,n);let r=wc(e,t,n);return r?[r]:[]}return hi(e)?Tc(e,t,n):w.isParenthesizedExpression(e)?Lr(e.expression,t,n):w.isExpression(e)?Lc(e,t,n):[]}function Nc(e,t,n){let r=new Map;for(let o of e.params)for(let i of Or(o))$d(r,i);t.valueScopes.push(r);try{if(!w.isBlockStatement(e.body))return Lr(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return My(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function My(e,t,n){let r=[];for(let o of e){if(w.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];if(i){Md([o],t,i);for(let s of o.declarations)w.isIdentifier(s.id)&&(w.isJSXElement(s.init)||w.isJSXFragment(s.init))&&r.push(...Lr(s.init,t,n))}continue}r.push(...Bd(o,t,n))}return r}function Bd(e,t,n){if(w.isReturnStatement(e))return e.argument?Lr(e.argument,t,n):[];if(w.isBlockStatement(e))return $o(e.body,t,n);if(w.isIfStatement(e)){let r=w.isBlockStatement(e.consequent)?$o(e.consequent.body,t,n):Bd(e.consequent,t,n),o=e.alternate?w.isBlockStatement(e.alternate)?$o(e.alternate.body,t,n):Bd(e.alternate,t,n):[];return[...r,...o]}if(w.isSwitchStatement(e))return $o(e.cases.flatMap(r=>r.consequent),t,n);if(w.isTryStatement(e)){let r=$o(e.block.body,t,n);return e.handler&&r.push(...$o(e.handler.body.body,t,n)),e.finalizer&&r.push(...$o(e.finalizer.body,t,n)),r}return[]}function $o(e,t,n){let r=new Map;t.valueScopes.push(r);try{return My(e,t,n)}finally{t.valueScopes.pop()}}function Ac(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:Qt(r),sourceCandidates:i&&i.length>0?i:void 0})}function ZN(e,t,n,r){let o=XN(e.openingElement,["items","dataSource","data"]),i={key:t,tag:Ty(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!w.isJSXAttribute(s))continue;let a=zN(s);if(!a||!w.isJSXExpressionContainer(s.value))continue;let l=s.value.expression;if(!w.isJSXEmptyExpression(l)){if(GN(a)&&Dd(l)){let c=Nc(l,n,r),u=wy(o,l,r,n);Ac(n,"repeat-region",t,s,c,u?[u]:void 0);continue}if(YN(a)){let c=Dd(l)?Nc(l,n,r):Lr(l,n,r);Ac(n,"conditional-region",t,s,c)}}}if(o)for(let s of e.children){if(!w.isJSXExpressionContainer(s)||!Dd(s.expression))continue;let a=Nc(s.expression,n,r),l=wy(o,s.expression,r,n);Ac(n,"repeat-region",t,s,a,l?[l]:void 0)}}finally{n.parentStack.pop()}}function wc(e,t,n){let r=Ty(e.openingElement);if(r==="Fragment"||jd(e))return Oc(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=AN(r),a;if(s){let E=t.ordinalTracker.getOrdinal(i,r);a=`component:${r}#${E}`}else{let E=t.ordinalTracker.getOrdinal(i,r);a=`${r}#${E}`}let l=o?t.elements.get(o.key)?.identity.structuralPath:void 0,c=l?`${l}/${a}`:a,u=xs(t.file,t.componentName,c),d={file:t.file,component:t.componentName,structuralPath:c,key:u},f=s?"component-boundary":null,m=MN(e.children,t,n),g=BN(e.openingElement,t,n),p=jN(e.openingElement,t,n),h,x,b=!1;if(s){let E=t.importMap.get(r)??t.importMap.get(wN(r));E&&(h=E.specifier,x=E.exportName,b=To(E.specifier,t.file))}let S={identity:d,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:Qt(e),parentKey:i,childKeys:[],textSegments:m,attributes:g.length>0?g:void 0,attributeSpreads:p.length>0?p:void 0,boundaryKind:f,isOpaque:s,...b?{isPublicUiComponent:!0}:{},importedFrom:h,exportName:x};return t.elements.set(u,S),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(u),ZN(e,u,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:u,tag:r}),qN(e.children,t,n),t.parentStack.pop()),u}function Tc(e,t,n){return Oc(e.children,t,n)}function Oc(e,t,n){let r=[];for(let o of e)if(w.isJSXElement(o))if(jd(o))r.push(...Oc(o.children,t,n));else{let i=wc(o,t,n);i&&r.push(i)}else hi(o)?r.push(...Tc(o,t,n)):w.isJSXExpressionContainer(o)&&r.push(...Lc(o.expression,t,n));return r}function qN(e,t,n){for(let r of e)w.isJSXElement(r)?wc(r,t,n):hi(r)?Tc(r,t,n):w.isJSXExpressionContainer(r)&&Lc(r.expression,t,n)}function QN(e){return e==="&&"||e==="||"||e==="??"}function Lc(e,t,n){if(w.isJSXEmptyExpression(e))return[];let r=HN(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,l={kind:"repeat-template",collectionExpression:Zn(r.collection,n),collectionSource:Ud(r.collection,n,t)};if(w.isArrowFunctionExpression(a)||w.isFunctionExpression(a)){let u=a.params[0],d=a.params[1];w.isIdentifier(u)&&(l.itemParamName=u.name),w.isIdentifier(d)&&(l.indexParamName=d.name)}s.push(l);let c={kind:"repeat-region",ownerKey:i?.key??"",childKeys:[],sourceRange:Qt(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(c),(w.isArrowFunctionExpression(a)||w.isFunctionExpression(a))&&c.childKeys.push(...Nc(a,t,n)),c.childKeys}if(w.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:Zn(e.test,n),conditionSource:Ut(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Qt(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Lr(e.consequent,t,n)),s.childKeys.push(...Lr(e.alternate,t,n)),s.childKeys}if(w.isLogicalExpression(e)&&QN(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:Zn(e.left,n),conditionSource:Ut(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Qt(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Lr(e.right,t,n)),s.childKeys}if(w.isParenthesizedExpression(e))return Lc(e.expression,t,n);if(w.isJSXElement(e)){let o=wc(e,t,n);return o?[o]:[]}return hi(e)?Tc(e,t,n):[]}function eA(e){let t=e.argument;return t&&(w.isExpression(t)||hi(t))?t:null}function ks(e,t){let n=[];for(let r of e){if(w.isReturnStatement(r)){let o=eA(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(w.isIfStatement(r)){let o=w.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...ks(o,r.test)),r.alternate){let i=w.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...ks(i,r.test))}continue}if(w.isSwitchStatement(r))for(let o of r.cases){let i=o.test?w.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...ks(o.consequent,i))}}return n}function Fc(e){return{routeId:e,rootKeys:[],elements:new Map,regions:[],fileIndex:new Map,version:1,diagnostics:[]}}function By(e){let{file:t,source:n,ast:r}=e,o=e.imports.map(f=>f.specifier);if(!w.traverseFast(r,f=>{if(w.isJSXElement(f)||w.isJSXFragment(f))return w.traverseFast.stop}))return{graph:Fc(t),localImports:o};let s=new Map,a=[],l=[],c=new Map,u=LN(r);NN(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(f){let m=TN(f);if(!m)return;let g=f.node,p=[];if(w.isArrowFunctionExpression(g))w.isExpression(g.body)||hi(g.body)?p=[{argument:g.body,statement:w.returnStatement(w.isExpression(g.body)?g.body:null)}]:w.isBlockStatement(g.body)&&(p=ks(g.body.body));else{let v=g.body;w.isBlockStatement(v)&&(p=ks(v.body))}if(p.length===0){f.skip();return}let h=new Map;Md(DN(r.program.body),Fd(t,m,s,a,u,[h]),h);let x=new Map;for(let v of g.params)for(let N of Or(v))$d(x,N);let b=w.isBlockStatement(g.body)?g.body.body:[],S=p[0]?.statement??null;for(let v of b){if(S&&v===S)break;w.isVariableDeclaration(v)&&Md([v],Fd(t,m,s,a,u,[h,x]),x)}let E=Fd(t,m,s,a,u,[h,x]);for(let v of p){let N=Lr(v.argument,E,n);for(let I of N)l.includes(I)||l.push(I);if(v.condition){let I={kind:"conditional-branch",conditionExpression:Zn(v.condition,n),conditionSource:Ut(v.condition,n,E)};Ac(E,"conditional-region","",v.statement,N,[I])}}f.skip()}});let d=[...s.keys()];return d.length>0&&c.set(t,d),{graph:{routeId:t,rootKeys:l,elements:s,regions:a,fileIndex:c,version:1,diagnostics:[]},localImports:o}}function Vd(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function Dc(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function jy(e,t){if(e.length===0)return[];if(e.length===1)return[await t(e[0])];let n=new Array(e.length),r=0,o=Array.from({length:Math.min(8,e.length)},async()=>{for(;r<e.length;){let s=r++;n[s]=await t(e[s])}}),i=await Promise.allSettled(o);for(let s of i)if(s.status==="rejected")throw s.reason;return n}async function yi(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??Oe,l=new Map,c=new Map,u=new Map,d=[],f=new Set,m=x=>{let b=`${x.path}\0${x.code}\0${x.message}\0${JSON.stringify(x.details??{})}`;f.has(b)||(f.add(b),d.push(x))},g=[{file:e,source:t,depth:0,diagnosticEntryFile:e,importStack:[]},...(o.additionalEntries??[]).map(x=>({file:x.file,source:x.source,depth:0,diagnosticEntryFile:x.file,importStack:[]}))],p=new Set;for(;g.length>0;){let x=g.shift(),{file:b,source:S,depth:E,diagnosticEntryFile:v,importStack:N}=x;if(p.has(b))continue;p.add(b),l.set(b,S);let I=o.validationOnly&&E<i?o.validatedImports?.(b,S):void 0,A,C;if(I)A=Fc(b),C=I;else{let J=a(b,S);if(!J.ok){m(Dc(J.diagnostic,v,N));continue}u.set(b,J.module);let Y=o.validationOnly&&E<i?{graph:Fc(b),localImports:J.module.imports.map($=>$.specifier)}:By(J.module);A=Y.graph,C=Y.localImports}let O=[...new Set([...A.elements.values()].map(J=>J.importedFrom).filter(J=>typeof J=="string"&&_t(J)))],L=O.length?await jy(O,J=>Ya(b,J,r)):[],X=new Map(O.map((J,Y)=>[J,L[Y]]));for(let J of A.elements.values())if(J.importedFrom&&_t(J.importedFrom)){let Y=J.importedFrom,$=X.get(Y);$.ok?(J.importedFrom=$.path,Nr($.path)&&(J.isPublicUiComponent=!0)):To(Y,b)||m(Dc($.diagnostic,v,Vd(N,b,Y,$.diagnostic.path)))}if(c.set(b,A),E>=i)continue;let j=await jy(C,async J=>{if(yh(J))return null;let Y=X.get(J)??await Ya(b,J,r);if(!Y.ok)return To(J,b)?null:{diagnostic:Dc(Y.diagnostic,v,Vd(N,b,J,Y.diagnostic.path))};let $=Y.path;if(p.has($)||Nr($))return null;let ce=Vd(N,b,J,$);try{let ue=await n($);return{entry:{file:$,source:ue,depth:E+1,diagnosticEntryFile:v,importStack:ce}}}catch(ue){return{diagnostic:Dc({path:$,code:"import-read-failed",message:`Failed to read imported file: ${$}`,details:{fromFile:b,specifier:J,reason:ue instanceof Error?ue.message:String(ue)}},v,ce)}}});for(let J of j)J&&"entry"in J?g.push(J.entry):J&&m(J.diagnostic)}let h=tA(e,c,s,(o.additionalEntries??[]).map(x=>x.file));return h.diagnostics=d,{graph:h,allSources:l,diagnostics:d,parsedModules:u,entryModule:u.get(e)??null}}function tA(e,t,n,r=[]){let o=new Map,i=[],s=new Map,a=[];for(let[l,c]of t){for(let[u,d]of c.elements)o.set(u,d);for(let u of c.regions)i.push(u);for(let[u,d]of c.fileIndex){let f=s.get(u)??[];s.set(u,[...f,...d])}if(l===e){a=c.rootKeys;continue}r.includes(l)&&(a=[...a,...c.rootKeys])}return{routeId:e,rootKeys:a,elements:o,regions:i,fileIndex:s,version:n}}function $y(e=256){if(!Number.isSafeInteger(e)||e<1)throw new RangeError("Validated syntax capacity must be positive.");let t=new Map;return{remember(n){for(let r of n)t.get(r.file)?.source!==r.source&&(t.delete(r.file),t.size>=e&&t.delete(t.keys().next().value),t.set(r.file,{source:r.source,imports:Object.freeze(r.imports.map(o=>o.specifier))}))},getImports(n,r){let o=t.get(n);return o?.source===r?o.imports:void 0},clear(){t.clear()}}}import{SiteEditHistoryProvenanceSchema as AA}from"@vcp-dev/platform-shared/contracts";import{createHash as nA,randomUUID as qd}from"node:crypto";import It from"node:fs/promises";import Rt from"node:path";var Yy=new WeakMap;function xi(e){return Yy.get(e)?.()??e.readIndex()}var Jn=1,Jd=1,rA=2,oA="index.json",iA="recovery.json",sA="transaction-journal.json",aA="document-version.json",jc={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},we={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"},Le=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};function Fr(){return{entries:new Map,blobSizes:new Map}}function Mc(e,t){let n={entries:new Map,blobs:new Map,objectBytes:0};for(let r of e)Zy(n,r,t);return n}function Zy(e,t,n){let r=e.entries.get(t);if(r){e.entries.set(t,{...r,references:r.references+1});return}let o=n.entries.get(t),i=new Map(o.entry.blobs.map(s=>[s.digest,n.blobSizes.get(s.digest)]));e.entries.set(t,{sizeBytes:o.sizeBytes,references:1,blobs:i}),e.objectBytes+=o.sizeBytes;for(let[s,a]of i){let l=e.blobs.get(s);e.blobs.set(s,{sizeBytes:a,references:(l?.references??0)+1}),l||(e.objectBytes+=a)}}function qy(e,t){let n=e.entries.get(t);if(n.references>1){e.entries.set(t,{...n,references:n.references-1});return}e.entries.delete(t),e.objectBytes-=n.sizeBytes;for(let r of n.blobs.keys()){let o=e.blobs.get(r);o.references>1?e.blobs.set(r,{...o,references:o.references-1}):(e.blobs.delete(r),e.objectBytes-=o.sizeBytes)}}async function Qy(e,t={}){let n=kA(e),r=PA(t.limits),o=Kd(n),i=_A(n),s=await hn(i),a=await hn(o)||s;a||(await hA(n),await yA(n)),a||await NA(n);let l=Fr(),c=await Uc(n,l),u=new Set(a?(await zc(n)).map(b=>b.stageId):[]);a||await Xy(n,c.entryIds,l);let d=c.digest,f=Mc(c.entryIds,l),m=async b=>{let{index:S,sizeBytes:E}=await Ns(n);if(sx(S,b),S.digest!==d){let v=Fr();await rx(n,S.entryIds,v,E),f=Mc(S.entryIds,v),d=S.digest}return{...Wc(S),totalBytes:f.objectBytes+E}},g=async b=>{Qd(b),await m(),await Ky(n,f,[b.entryId],b.blobIds,b.stageId),await $c(n,b.stageId)},p=async(b,S)=>{let E=await m(S);tx(b,E.entryIds.length);let v=Fr();for(let N of E.entryIds.slice(Math.min(E.cursor,b)+1,Math.max(E.cursor,b)+1))await Cs(n,N,v);return E},h=async()=>{if(await hn(o)||s)throw new Le(we.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")},x={rootDir:n,recoveryRequired:a,async readDocumentVersion(){return Hy(n)},async writeDocumentVersion(b){if(await h(),!Number.isInteger(b)||b<0)throw new Le(we.INVALID_SCHEMA,"document version must be a non-negative integer");let S=await Hy(n);b<=S||await _s(ux(n),{schemaVersion:1,version:Math.max(S,b)})},async stageAppend(b,S={}){await h();let E=await uA(b,r),v={schemaVersion:Jd,stageId:qd(),entryId:E.entryId,blobIds:E.blobs.map(N=>N.digest)};try{await dA(n,E),await pA(n,v,S.durableManifest!==!1)}catch(N){try{await g(v)}catch(I){throw new Le(we.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:I})}throw N}return{stageId:v.stageId,entryId:v.entryId,blobIds:v.blobIds}},async discardStage(b){await h(),Wd(b);let S=await Xd(n,b);S&&await g(S)},async previewStagedAppend(b,S){await h();let E=await m(S);return(await Uy(n,r,b,E,f)).transition},async previewCursor(b,S){await h();let E=await p(b,S);return ex(E,E.entryIds,b)},async publishStagedAppend(b,S,E){if(await h(),Kc(b,"entryId"),E){Wd(E);let C=await Xd(n,E);if(!C||C.entryId!==b)throw new Le(we.INVALID_SCHEMA,"history stage does not match the published entry")}let v=await m(S),N=f,I=await Uy(n,r,b,v,N),A=await Wy({rootDir:n,previousDigest:I.current.digest,entryIds:I.entryIds,cursor:I.cursor,readback:async()=>zy(n,I.usage),afterWrite:async()=>{E?await $c(n,E):await gA(n,b),await Ky(n,I.usage,[...N.entries.keys()].filter(C=>!I.usage.entries.has(C)),[...N.blobs.keys()].filter(C=>!I.usage.blobs.has(C)))}});return f=I.usage,d=A.digest,A},async append(b){await h();let S=await m(),E=await x.stageAppend(b);try{return await x.publishStagedAppend(E.entryId,S.digest,E.stageId)}catch(v){throw await x.discardStage(E.stageId),v}},async readEntry(b){return Kc(b,"entryId"),Cs(n,b)},async readBlob(b){Kc(b,"blobId");let S=await fx(n,b),E=await Rs(S,we.NOT_FOUND,"blob");return lx(E,b,S),E},async readIndex(){let b=Fr(),S=await Uc(n,b);return f=Mc(S.entryIds,b),d=S.digest,S},async readStatus(){let b=await Vc(n);return{canUndo:b.undoIds.length>0,canRedo:b.redoIds.length>0,undoDepth:b.undoIds.length,redoDepth:b.redoIds.length,cursor:b.cursor,recoveryRequired:await hn(o)||await hn(i)}},async readUndoRedoIds(){let b=await Vc(n);return{undoIds:b.undoIds,redoIds:b.redoIds,currentId:b.currentId}},async setCursor(b,S){await h();let E=await p(b,S),v=await Wy({rootDir:n,previousDigest:E.digest,entryIds:E.entryIds,cursor:b,readback:async()=>zy(n,f)});return d=v.digest,v},async markRecoveryRequired(b){await hn(o)||await _s(Kd(n),{schemaVersion:Jn,reason:CA(b),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await It.rm(Kd(n),{force:!0})},async readTransactionJournal(){return await hn(i)?Bc(i):null},async writeTransactionJournal(b){await h(),dx(b);try{await _s(i,b)}catch(E){let v=await Bc(i).catch(()=>null);if(v&&Buffer.from(yn(v)).equals(Buffer.from(yn(b))))return;throw v?new Le(we.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:E}):E}let S=await Bc(i);if(!Buffer.from(yn(S)).equals(Buffer.from(yn(b))))throw new Le(we.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(b){let S=await hn(i)?await Bc(i):null;if(S&&S.transactionId!==b)throw new Le(we.INVALID_SCHEMA,"transaction journal changed concurrently");try{await It.rm(i,{force:!0})}catch(E){if(!await hn(i))return;throw E}if(await hn(i))throw new Le(we.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await h();for(let E of u)await $c(n,E),u.delete(E);await xA(n);let b=Fr(),S=await Uc(n,b);await Xy(n,S.entryIds,b),f=Mc(S.entryIds,b),d=S.digest}};return Yy.set(x,()=>Vc(n)),x}async function Uy(e,t,n,r,o){Kc(n,"entryId");let i=Fr(),s=await Cs(e,n,i),a={entries:new Map(o.entries),blobs:new Map(o.blobs),objectBytes:o.objectBytes},l=r.entryIds.slice(0,r.cursor+1);for(let u of r.entryIds.slice(r.cursor+1))qy(a,u);Zy(a,s.id,i),l.push(s.id);let c=fA(l,t,a);return{current:r,entryIds:c.entryIds,cursor:c.cursor,usage:a,transition:ex(r,c.entryIds,c.cursor)}}function ex(e,t,n){return tx(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:cA(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function cA(e,t){return to(yn({schemaVersion:Jn,entryIds:e,cursor:t}))}function tx(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new Le(we.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function lA(e){if(!qn(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!Rn(e.expectedIndexDigest)||!Rn(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!Rn(n)?!1:t===-1?n===null:Rn(n)}async function uA(e,t){if(!e.kind.trim())throw new Le(we.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let l of e.blobs??[]){if(!l.name.trim())throw new Le(we.INVALID_JSON,"history blob name must not be empty");let c=vA(l.data),u=to(c);n.push({name:l.name,bytes:c,digest:u,sizeBytes:c.byteLength}),r.push({name:l.name,digest:u,sizeBytes:c.byteLength})}let o={schemaVersion:Jn,kind:e.kind,manifest:e.manifest,blobs:r},i=yn({...o}),s=to(i),a=i.byteLength+n.reduce((l,c)=>l+c.sizeBytes,0);if(a>t.maxEntryBytes)throw new Le(we.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function dA(e,t){let n=rf(e,t.entryId),r={id:t.entryId,...t.entryBody},o=new Map(t.blobs.map(l=>[l.digest,l])),i=[...Array.from(o.values(),l=>Vy(of(e,l.digest),l.bytes,{kind:"blob",digest:l.digest},af(e,l.digest))),Vy(n,yn(r),{kind:"entry",digest:t.entryId},sf(e,t.entryId))],a=(await Promise.allSettled(i)).find(l=>l.status==="rejected");if(a)throw a.reason}async function Vy(e,t,n,r){let o=await Yd(e)??(r?await Yd(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new Le(n.kind==="blob"?we.BLOB_CORRUPT:we.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await ax(e,t)}function fA(e,t,n){let r=[...e],o=r.length-1;for(;;){if(n.objectBytes+yn(ix(r,o)).byteLength<=t.maxSessionBytes&&r.length<=t.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new Le(we.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");qy(n,r.shift()),o-=1}}async function pA(e,t,n){Qd(t);let r=nf(e,t.stageId);if(n){await _s(r,t);return}await IA(r,t)}async function Xd(e,t){let n=await Yd(nf(e,t));if(n===null)return null;let r=As(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=Qd(r);if(o.stageId!==t)throw new Le(we.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function zc(e){let t=[];for(let n of await Xc(tf(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);Wd(r);let o=await Xd(e,r);o&&t.push(o)}return t}async function Ky(e,t,n,r,o){if(n.length===0&&r.length===0)return;let i=new Set(t.entries.keys()),s=new Set;for(let a of await zc(e))if(a.stageId!==o){i.add(a.entryId);for(let l of a.blobIds)s.add(l)}for(let a of new Set(n))i.has(a)||await Jy(rf(e,a),sf(e,a));for(let a of new Set(r))!t.blobs.has(a)&&!s.has(a)&&await Jy(of(e,a),af(e,a));await Zd(ws(e)),await Zd(Ts(e))}async function $c(e,t){await zd(nf(e,t)),await mA(e)}async function mA(e){try{await It.rmdir(tf(e))}catch(t){if(Os(t)||qn(t)&&t.code==="ENOTEMPTY")return;throw t}}async function gA(e,t){for(let n of await zc(e))n.entryId===t&&await $c(e,n.stageId)}async function zd(e){if(await It.rm(e,{force:!0}),await hn(e))throw new Le(we.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function Jy(e,t){await zd(e),await zd(t)}function Qd(e){if(!qn(e)||e.schemaVersion!==Jd||typeof e.stageId!="string"||!nx(e.stageId)||!Rn(e.entryId))throw new Le(we.INVALID_SCHEMA,"history stage schema is invalid");let t=cx(e.blobIds,"history stage blobIds");return{schemaVersion:Jd,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function Wd(e){if(!nx(e))throw new Le(we.INVALID_PATH,"history stageId must be a UUID")}function nx(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 Xy(e,t,n=Fr()){let r=new Set(t),o=new Set;for(let c of t){let u=await Cs(e,c,n);for(let d of u.blobs)o.add(d.digest)}for(let c of await zc(e)){r.add(c.entryId);for(let u of c.blobIds)o.add(u)}let i=ws(e),s=await Xc(i);for(let c of s){if(!c.endsWith(".json"))continue;let u=Gy(c.slice(0,-5));u&&!r.has(u)&&await Jc(Rt.join(i,c))}let a=Ts(e),l=await Xc(a);for(let c of l){let u=Gy(c);u&&!o.has(u)&&await Jc(Rt.join(a,c))}}async function Uc(e,t=Fr()){let{index:n,sizeBytes:r}=await Ns(e),{totalBytes:o}=await rx(e,n.entryIds,t,r);return{...Wc(n),totalBytes:o}}async function zy(e,t){let{index:n,sizeBytes:r}=await Ns(e);return{...Wc(n),totalBytes:t.objectBytes+r}}async function Ns(e){let t=ef(e),n=await Rs(t,we.NOT_FOUND,"index"),r=As(Buffer.from(n).toString("utf8"),"index");return{index:bA(r),sizeBytes:n.byteLength}}async function Vc(e){return Wc((await Ns(e)).index)}function Wc(e){let t=[...e.entryIds],n=t.slice(0,e.cursor+1).reverse(),r=t.slice(e.cursor+1);return{schemaVersion:Jn,digest:e.digest,entryIds:t,cursor:e.cursor,currentId:t[e.cursor]??null,undoIds:n,redoIds:r}}async function rx(e,t,n,r){let o=0,i=new Set;o+=r??(await Ns(e)).sizeBytes;for(let s of new Set(t)){let a=await Cs(e,s,n);o+=n.entries.get(s).sizeBytes;for(let l of a.blobs)i.has(l.digest)||(i.add(l.digest),o+=n.blobSizes.get(l.digest))}return{totalBytes:o}}async function Cs(e,t,n=Fr()){let r=n.entries.get(t);if(r)return r.entry;let o=await RA(e,t),i=await Rs(o,we.NOT_FOUND,"entry"),s=As(Buffer.from(i).toString("utf8"),`entry ${t}`),a=SA(s);if(a.id!==t)throw new Le(we.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(to(yn({schemaVersion:a.schemaVersion,kind:a.kind,manifest:a.manifest,blobs:a.blobs}))!==t)throw new Le(we.ENTRY_CORRUPT,`entry hash mismatch for ${t}`);let c=[...new Set(a.blobs.map(d=>d.digest))].filter(d=>!n.blobSizes.has(d)),u=async d=>{let f=await fx(e,d),m=await Rs(f,we.NOT_FOUND,"blob");return lx(m,d,f),m.byteLength};if(c.length===1)n.blobSizes.set(c[0],await u(c[0]));else if(c.length>1){let d=new Array(c.length),f=[],m=0,g=Array.from({length:Math.min(4,c.length)},async()=>{for(;m<c.length&&f.length===0;){let x=m++;try{d[x]=await u(c[x])}catch(b){f.push({index:x,error:b})}}}),p=await Promise.allSettled(g),h=f.sort((x,b)=>x.index-b.index)[0];if(h)throw h.error;for(let x of p)if(x.status==="rejected")throw x.reason;for(let x=0;x<c.length;x++)n.blobSizes.set(c[x],d[x])}return n.entries.set(t,{entry:a,sizeBytes:i.byteLength}),a}async function ox(e,t,n){await _s(ef(e),ix(t,n))}function ix(e,t){return{schemaVersion:Jn,digest:to(yn({schemaVersion:Jn,entryIds:e,cursor:t})),entryIds:e,cursor:t}}function sx(e,t){if(t!==void 0&&e.digest!==t)throw new Le(we.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function Wy(e){sx(await Vc(e.rootDir),e.previousDigest);let t=to(yn({schemaVersion:Jn,entryIds:e.entryIds,cursor:e.cursor}));try{await ox(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.();let n=await e.readback();if(n.digest!==t)throw new Le(we.INDEX_CORRUPT,"history index readback did not match the published transition");return n}catch(n){let r=await Uc(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new Le(we.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function hA(e){await It.mkdir(e,{recursive:!0}),await It.mkdir(ws(e),{recursive:!0}),await It.mkdir(Ts(e),{recursive:!0}),await It.mkdir(Ps(e),{recursive:!0})}async function yA(e){await It.rm(Ps(e),{recursive:!0,force:!0}),await It.mkdir(Ps(e),{recursive:!0})}async function xA(e){let t=Ps(e);await It.mkdir(t,{recursive:!0});for(let n of await Xc(t))n!=="stages"&&await It.rm(Rt.join(t,n),{recursive:!0,force:!0})}function bA(e){if(!qn(e))throw new Le(we.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==Jn)throw new Le(we.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=cx(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new Le(we.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!Rn(o))throw new Le(we.INDEX_CORRUPT,"index digest is invalid");let i=to(yn({schemaVersion:Jn,entryIds:t,cursor:r}));if(o!==i)throw new Le(we.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:Jn,digest:o,entryIds:t,cursor:r}}function SA(e){if(!qn(e))throw new Le(we.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==Jn)throw new Le(we.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!Rn(t))throw new Le(we.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new Le(we.ENTRY_CORRUPT,"entry kind is invalid");let r=Gd(e.manifest,"entry.manifest"),o=EA(e.blobs);return{id:t,schemaVersion:Jn,kind:n,manifest:r,blobs:o}}function EA(e){if(!Array.isArray(e))throw new Le(we.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!qn(t))throw new Le(we.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new Le(we.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!Rn(o))throw new Le(we.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new Le(we.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function _s(e,t){await ax(e,yn(t))}async function IA(e,t){let n=Rt.dirname(e),r=Rt.basename(e),o=Rt.join(n,`.${r}.${process.pid}.${qd()}.tmp`);await It.mkdir(n,{recursive:!0});try{await It.writeFile(o,yn(t),{flag:"wx"}),await It.rename(o,e)}finally{await Jc(o)}}async function ax(e,t){let n=Rt.dirname(e),r=Rt.basename(e),o=Rt.join(n,`.${r}.${process.pid}.${qd()}.tmp`);await It.mkdir(n,{recursive:!0});try{let i=await It.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await It.rename(o,e),await Zd(n)}finally{await Jc(o)}}function yn(e){return Buffer.from(JSON.stringify(Hd(e)),"utf8")}function Hd(e){if(Array.isArray(e))return e.map(t=>Hd(t));if(qn(e)){let t={};for(let n of Object.keys(e).sort())t[n]=Hd(e[n]);return t}return e}function As(e,t){try{return JSON.parse(e)}catch(n){throw new Le(we.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function Gd(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=>Gd(n,t));if(qn(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=Gd(o,t);return n}break}throw new Le(we.INVALID_JSON,`${t} must be JSON-serializable`)}function cx(e,t){if(!Array.isArray(e))throw new Le(we.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!Rn(n))throw new Le(we.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function Kc(e,t){if(!Rn(e))throw new Le(we.INVALID_PATH,`${t} must be a sha256 digest`)}function Rn(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function to(e){return`sha256:${nA("sha256").update(e).digest("hex")}`}function vA(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function Rs(e,t,n){try{return await It.readFile(e)}catch(r){throw new Le(t,`${n} not found: ${e}`,{cause:r})}}async function Yd(e){try{return await It.readFile(e)}catch(t){if(Os(t))return null;throw t}}function lx(e,t,n){if(to(e)!==t)throw new Le(we.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function hn(e){try{return await It.access(e),!0}catch(t){if(Os(t))return!1;throw t}}async function Jc(e){try{await It.rm(e,{force:!0,recursive:!0})}catch{}}async function Zd(e){try{let t=await It.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function Xc(e){try{return await It.readdir(e)}catch(t){if(Os(t))return[];throw t}}function kA(e){if(typeof e!="string"||e.trim().length===0)throw new Le(we.INVALID_ROOT,"history store rootDir must be a non-empty string");return Rt.resolve(e)}function ef(e){return Rt.join(e,oA)}function Kd(e){return Rt.join(e,iA)}function _A(e){return Rt.join(e,sA)}function ux(e){return Rt.join(e,aA)}async function Hy(e){try{let t=await It.readFile(ux(e),"utf8"),n=As(t,"document version");if(!qn(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new Le(we.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(Os(t))return 0;throw t}}async function Bc(e){let t=await Rs(e,we.RECOVERY_PENDING,"transaction journal"),n=As(Buffer.from(t).toString("utf8"),"transaction journal");return dx(n),n}function dx(e){if(!qn(e)||e.schemaVersion!==rA||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!lA(e.historyTransition)||!Array.isArray(e.files))throw new Le(we.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!qn(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!Rn(t.preDigest)||t.postDigest!==null&&!Rn(t.postDigest))throw new Le(we.INVALID_SCHEMA,"transaction journal file digest is invalid")}function CA(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function ws(e){return Rt.join(e,"entries")}function Ts(e){return Rt.join(e,"blobs")}function Ps(e){return Rt.join(e,"tmp")}function tf(e){return Rt.join(Ps(e),"stages")}function nf(e,t){return Rt.join(tf(e),`${t}.json`)}function rf(e,t){return Rt.join(ws(e),`${mx(t)}.json`)}function of(e,t){return Rt.join(Ts(e),mx(t))}function sf(e,t){return Rt.join(ws(e),`${t}.json`)}function af(e,t){return Rt.join(Ts(e),t)}async function RA(e,t){return px(rf(e,t),sf(e,t))}async function fx(e,t){return px(of(e,t),af(e,t))}async function px(e,t){return await hn(e)?e:await hn(t)?t:e}function mx(e){return e.slice(7)}function Gy(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return Rn(t)?t:null}function qn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Os(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function PA(e){return{maxEntries:e?.maxEntries??jc.maxEntries,maxSessionBytes:e?.maxSessionBytes??jc.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??jc.maxEntryBytes}}async function NA(e){let t=ef(e);await hn(t)||await ox(e,[],-1)}var wA={affectedCompositions:[]};function bx(e){let t=null,n=new WeakMap;async function r(){return t??=TA(e),t}async function o(i){if(!i)return null;let s=cf(i);return s?OA(e,s):i}return{async prepareAppend(i){let s=await xi(e),a=await e.stageAppend(yx(i),{durableManifest:!1}),l;try{l=await e.previewStagedAppend(a.entryId,s.digest)}catch(u){throw await e.discardStage(a.stageId),u}let c={kind:"append",entry:i,historyTransition:l};return n.set(c,{expectedDigest:s.digest,stageId:a.stageId,entryId:a.entryId}),c},async prepareUndo(){let i=await r(),s=await o(i.undo.at(-1));if(!s?.historyId)return null;let a=await xi(e),l=a.entryIds.indexOf(s.historyId);if(l<0)throw new Error("undo entry is missing from index");if(l!==a.cursor)throw new Error("undo state changed before prepare");let c=l-1,u=await e.previewCursor(c,a.digest),d={kind:"undo",entry:s,historyTransition:u};return n.set(d,{expectedDigest:a.digest,cursor:c}),d},async prepareRedo(){let i=await r(),s=await o(i.redo.at(-1));if(!s?.historyId)return null;let a=await xi(e),l=a.entryIds.indexOf(s.historyId);if(l<0)throw new Error("redo entry is missing from index");if(l!==a.cursor+1)throw new Error("redo state changed before prepare");let c=l,u=await e.previewCursor(c,a.digest),d={kind:"redo",entry:s,historyTransition:u};return n.set(d,{expectedDigest:a.digest,cursor:c}),d},async publishPrepared(i){let s=n.get(i);if(!s)throw new Error("history mutation was not prepared");let a=await r();if(i.kind==="append"){if(!s.entryId)throw new Error("staged entry id is missing");let l=await e.publishStagedAppend(s.entryId,s.expectedDigest,s.stageId);gx(l,i.historyTransition),i.entry.historyId=s.entryId,Object.assign(a,bi(l))}else{if(s.cursor===void 0)throw new Error("prepared cursor is missing");let l=i.kind==="undo"?a.undo:a.redo;if(cf(l.at(-1))!==cf(i.entry))throw new Error("history state changed before publish");let c=await e.setCursor(s.cursor,s.expectedDigest);gx(c,i.historyTransition),Object.assign(a,bi(c))}n.delete(i)},async discardPrepared(i){let s=n.get(i);if(!s)return;let a=i.historyTransition;if(a){let l=await xi(e);if(l.digest===a.publishedIndexDigest&&l.cursor===a.publishedCursor&&l.currentId===a.publishedCurrentId)throw new Error("cannot discard a history mutation whose index was published")}s.stageId&&await e.discardStage(s.stageId),n.delete(i)},async peekUndo(){return o((await r()).undo.at(-1))},async pushUndo(i){let s=await r(),a=i;if(a.historyId){let u=s.entryIds.indexOf(a.historyId);if(u>=0)try{let d=await e.setCursor(u);Object.assign(s,bi(d));return}catch(d){throw s.redo.push(i),d}}let l=await e.append(yx(i)),c=l.currentId;if(!c)throw new Error("history store did not publish an entry");i.historyId=c,Object.assign(s,bi(l))},async popUndo(){let i=await r(),s=await o(i.undo.at(-1));return i.undo.pop(),s},async peekRedo(){return o((await r()).redo.at(-1))},async pushRedo(i){let s=await r(),a=i;if(!a.historyId)throw s.undo.push(i),new Error("cannot move an unpersisted history entry to redo");let l=s.entryIds.indexOf(a.historyId);if(l<0)throw s.undo.push(i),new Error("history entry is missing from the durable index");try{let c=await e.setCursor(l-1);Object.assign(s,bi(c))}catch(c){throw s.undo.push(i),c}},async popRedo(){let i=await r(),s=await o(i.redo.at(-1));return i.redo.pop(),s},async clearRedo(){(await r()).redo.length=0},async getStatus(){let i=await e.readStatus();return{canUndo:i.canUndo,canRedo:i.canRedo,undoDepth:i.undoDepth,redoDepth:i.redoDepth,recoveryRequired:i.recoveryRequired}},async markRecoveryRequired(i){await e.markRecoveryRequired(i)}}}function gx(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")}function cf(e){return typeof e=="string"?e:e?.historyId}async function TA(e){let t=await xi(e);return bi(t)}function bi(e){return{undo:[...e.undoIds].reverse(),redo:[...e.redoIds].reverse(),entryIds:[...e.entryIds],cursor:e.cursor}}async function OA(e,t){let n=await e.readEntry(t),r=LA(n),o=r.provenance??wA;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 hx(e,n,r.preSnapshots),postSnapshots:await hx(e,n,r.postSnapshots)}}async function hx(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(MA(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function yx(e){let t=[],n=(i,s)=>i.map((a,l)=>{let c={file:a.file,exists:a.exists!==!1,version:a.version,...a.sha256?{sha256:a.sha256}:{}};if(c.exists){let u=`${s}-${l}`;c.blobName=u,t.push({name:u,data:a.content})}return c}),r=FA(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 LA(e){if(!Ex(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:Sx(t.provenance)}:{},preSnapshots:xx(t.preSnapshots,"preSnapshots"),postSnapshots:xx(t.postSnapshots,"postSnapshots")}}function FA(e){if(e.provenance!==void 0)return Sx(e.provenance);if(e.composition)return{initiatingComposition:e.composition,affectedCompositions:[]}}function Sx(e){let t=AA.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 xx(e,t){return e.map((n,r)=>{if(!Ex(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&&!DA(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 DA(e){return/^sha256:[0-9a-f]{64}$/.test(e)}function MA(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function Ex(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{GeneratedSiteCapabilitiesSchema as BA}from"@vcp-dev/platform-shared/contracts";var Ix={schema_version:1,policy_version:"starter-capabilities-v1",source:{starter_package_path:"templates/next-starter/package.json",components_catalog_path:"templates/next-starter/components.catalog.json",package_name:"vcp-next-starter",package_version:"0.0.0"},runtime_dependencies:[{name:"@gsap/react",version:"2.1.2"},{name:"@hookform/resolvers",version:"3.10.0"},{name:"@opennextjs/cloudflare",version:"1.19.11"},{name:"@radix-ui/react-accordion",version:"1.2.12"},{name:"@radix-ui/react-alert-dialog",version:"1.1.15"},{name:"@radix-ui/react-aspect-ratio",version:"1.1.8"},{name:"@radix-ui/react-avatar",version:"1.1.11"},{name:"@radix-ui/react-checkbox",version:"1.3.3"},{name:"@radix-ui/react-collapsible",version:"1.1.12"},{name:"@radix-ui/react-context-menu",version:"2.2.16"},{name:"@radix-ui/react-dialog",version:"1.1.15"},{name:"@radix-ui/react-dropdown-menu",version:"2.1.16"},{name:"@radix-ui/react-hover-card",version:"1.1.15"},{name:"@radix-ui/react-label",version:"2.1.8"},{name:"@radix-ui/react-menubar",version:"1.1.16"},{name:"@radix-ui/react-navigation-menu",version:"1.2.14"},{name:"@radix-ui/react-popover",version:"1.1.15"},{name:"@radix-ui/react-progress",version:"1.1.8"},{name:"@radix-ui/react-radio-group",version:"1.3.8"},{name:"@radix-ui/react-scroll-area",version:"1.2.10"},{name:"@radix-ui/react-select",version:"2.2.6"},{name:"@radix-ui/react-separator",version:"1.1.8"},{name:"@radix-ui/react-slider",version:"1.3.6"},{name:"@radix-ui/react-slot",version:"1.2.3"},{name:"@radix-ui/react-switch",version:"1.2.6"},{name:"@radix-ui/react-tabs",version:"1.1.13"},{name:"@radix-ui/react-toggle",version:"1.1.10"},{name:"@radix-ui/react-toggle-group",version:"1.1.11"},{name:"@radix-ui/react-tooltip",version:"1.2.8"},{name:"class-variance-authority",version:"0.7.1"},{name:"clsx",version:"2.1.1"},{name:"cmdk",version:"1.1.1"},{name:"date-fns",version:"4.3.0"},{name:"embla-carousel-react",version:"8.6.0"},{name:"gsap",version:"3.15.0"},{name:"i18next",version:"26.3.0"},{name:"input-otp",version:"1.4.2"},{name:"lucide-react",version:"0.525.0"},{name:"motion",version:"12.40.0"},{name:"next",version:"16.3.4"},{name:"react",version:"19.2.6"},{name:"react-day-picker",version:"9.14.0"},{name:"react-dom",version:"19.2.6"},{name:"react-hook-form",version:"7.76.1"},{name:"react-i18next",version:"17.0.8"},{name:"recharts",version:"2.15.4"},{name:"sonner",version:"2.0.7"},{name:"tailwind-merge",version:"3.6.0"},{name:"vaul",version:"1.1.2"},{name:"zod",version:"3.25.76"}],catalog_dependencies:["@hookform/resolvers","@radix-ui/react-accordion","@radix-ui/react-alert-dialog","@radix-ui/react-aspect-ratio","@radix-ui/react-avatar","@radix-ui/react-checkbox","@radix-ui/react-collapsible","@radix-ui/react-context-menu","@radix-ui/react-dialog","@radix-ui/react-dropdown-menu","@radix-ui/react-hover-card","@radix-ui/react-label","@radix-ui/react-menubar","@radix-ui/react-navigation-menu","@radix-ui/react-popover","@radix-ui/react-progress","@radix-ui/react-radio-group","@radix-ui/react-scroll-area","@radix-ui/react-select","@radix-ui/react-separator","@radix-ui/react-slider","@radix-ui/react-slot","@radix-ui/react-switch","@radix-ui/react-tabs","@radix-ui/react-toggle","@radix-ui/react-toggle-group","@radix-ui/react-tooltip","class-variance-authority","clsx","cmdk","date-fns","embla-carousel-react","input-otp","lucide-react","motion","react-day-picker","react-hook-form","recharts","sonner","tailwind-merge","vaul","zod"],public_paths:["components.json","components/site/generated/*","components/ui/*","components/ui/accordion.tsx","components/ui/alert-dialog.tsx","components/ui/alert.tsx","components/ui/aspect-ratio.tsx","components/ui/avatar.tsx","components/ui/badge.tsx","components/ui/border-beam.tsx","components/ui/breadcrumb.tsx","components/ui/button-group.tsx","components/ui/button.tsx","components/ui/calendar.tsx","components/ui/callout.tsx","components/ui/card.tsx","components/ui/carousel.tsx","components/ui/chart.tsx","components/ui/checkbox.tsx","components/ui/code-block.tsx","components/ui/collapsible.tsx","components/ui/command.tsx","components/ui/composite-carousel.tsx","components/ui/context-menu.tsx","components/ui/dialog.tsx","components/ui/drawer.tsx","components/ui/dropdown-menu.tsx","components/ui/empty.tsx","components/ui/field.tsx","components/ui/form.tsx","components/ui/hover-card.tsx","components/ui/input-group.tsx","components/ui/input-otp.tsx","components/ui/input.tsx","components/ui/item.tsx","components/ui/kbd.tsx","components/ui/label.tsx","components/ui/magic-card.tsx","components/ui/marquee.tsx","components/ui/menubar.tsx","components/ui/multi-step-form.tsx","components/ui/navigation-menu.tsx","components/ui/number-ticker.tsx","components/ui/pagination.tsx","components/ui/popover.tsx","components/ui/progress.tsx","components/ui/radio-group.tsx","components/ui/safe-image.tsx","components/ui/scroll-area.tsx","components/ui/scroll-choreographer.tsx","components/ui/select.tsx","components/ui/separator.tsx","components/ui/sheet.tsx","components/ui/site-footer-shell.tsx","components/ui/site-header.tsx","components/ui/skeleton.tsx","components/ui/slider.tsx","components/ui/sonner.tsx","components/ui/spinner.tsx","components/ui/stepper.tsx","components/ui/switch.tsx","components/ui/table.tsx","components/ui/tabs.tsx","components/ui/textarea.tsx","components/ui/toggle-group.tsx","components/ui/toggle.tsx","components/ui/tooltip.tsx","components/ui/video-frame.tsx","lib/cms","lib/utils.ts#cn"],generated_sections_path:"components/site/generated/*",ui_baseline:{kit:"shadcn-style",components_config:"components.json",class_name_helper:"lib/utils.ts#cn"},host_contract_digest:"03208e0d83ae2140368f162b6051dd45d4d6ac97f3652958b3ba24a6273d6eca"};function Hc(){let e=BA.safeParse(Ix);return e.success?e.data:null}import{randomBytes as jA}from"node:crypto";import Gc from"node:path";import{parse as Nx}from"@babel/parser";import $A from"@babel/traverse";import*as Ax from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as uf,PageResourceArtifactSchema as UA,SITE_EDIT_RESOURCE_OPERATION_MAX_FILE_COUNT as VA,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as KA,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as JA,parseComponentI18nResourcesJson as XA}from"@vcp-dev/platform-shared/contracts";var df="{{$INSTANCE}}",zA=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,WA=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,ff="components/site/generated",HA=/\.(?:tsx?|json)$/,GA=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,YA=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],ZA=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),lf=$A,qA=typeof lf=="function"?lf:lf.default;async function pf(e){let t=UA.safeParse(e.artifact);if(!t.success)return vt("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>jA(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=aw(r());if(!i)return vt("Random instance suffix must be 8 lowercase hex chars.");let s=`${cw(n.resource_id)}-${i}`,a=new Map,l=new Map,c=[];for(let S of n.pages){let E=S.final_route.slice(1);a.set(S.template_page_id,S.final_route),l.set(S.template_page_id,S.title),c.push({template_page_id:S.template_page_id,title:S.title,final_route:S.final_route,route_file_path:`app/${E}/page.tsx`})}let u=[],d=new Set,f=new Set,m=new Map,g=new Map,p=[],h=new Set(n.pages.flatMap(S=>S.components.map(E=>E.component_id)));for(let S of n.components){if(!h.has(S.component_id))continue;let E=vx({materialization:S.materialization,packageInstanceId:s,routeByPage:a,titleByPage:l});if(!E.ok)return E;for(let v of E.files){let N=_x(v,d,u);if(N)return N}f.add(E.entry),g.set(E.entry,E.entryExport),m.set(S.component_id,E.entry)}for(let[S,E]of n.pages.entries()){let v=c[S],N=vx({materialization:E.materialization,packageInstanceId:s,routeByPage:a,titleByPage:l,pageEntryTarget:v.route_file_path,pageTitle:v.title});if(!N.ok)return N;for(let I of N.files){let A=_x(I,d,u);if(A)return A}f.add(N.entry),g.set(N.entry,N.entryExport),p.push({entry:N.entry,declaredComponentIds:new Set(E.components.map(I=>I.component_id))})}let x=ew(u,f,s,m,p,g);if(!x.ok)return x;for(let S of u)if(await e.exists(S.file))return!S.file.startsWith("app/")&&o>1?pf({...e,randomHex:r,maxAttempts:o-1}):{ok:!1,code:"MATERIALIZATION_CONFLICT",message:`Page resource create-only target already exists: ${S.file}`,path:S.file};let b=tw(u);return b||(u.sort((S,E)=>S.file.localeCompare(E.file)),{ok:!0,packageInstanceId:s,pages:c,files:u})}function vx(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:kx(o.pathTemplate,e.packageInstanceId);if(!s)return vt("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=QA(o.content,e.packageInstanceId,e.routeByPage,e.titleByPage);if(!a.ok)return a;let l=i&&e.pageTitle!==void 0?rw(a.data,e.pageTitle,s):a;if(!l.ok)return l;n.push({operation:"create-only",file:s,content:l.data})}let r=e.pageEntryTarget??kx(t,e.packageInstanceId);return!r||!n.some(o=>o.file===r)?vt("Materialization entry must match one controlled source file.",t):{ok:!0,files:n,entry:r,entryExport:e.materialization.entry.export}}function QA(e,t,n,r){let o,i=e.replace(zA,(l,c)=>{let u=n.get(c);return u||(o=c,l)});if(o)return vt(`Page route placeholder references unknown template page: ${o}`);let s=i.replace(WA,(l,c)=>{let u=r.get(c);return u?JSON.stringify(u):(o=c,l)});if(o)return vt(`Page title placeholder references unknown template page: ${o}`);let a=s.replaceAll(df,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?vt("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function kx(e,t){let n=`${ff}/${t}`;if(e.split(df).length>2)return null;let o=e.replace(df,t),i=`${ff}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=Gc.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!HA.test(a)||GA.test(a)?null:a}function _x(e,t,n){return t.has(e.file)?vt(`Page resource materializations resolve duplicate target: ${e.file}`,e.file):(t.add(e.file),n.push(e),null)}function ew(e,t,n,r,o,i){let s=new Set(e.map(m=>m.file)),a=`${ff}/${n}`,l=new Map(e.map(m=>[m.file,new Set])),c=new Map;for(let m of e){if(m.file.endsWith(".json")){try{JSON.parse(m.content)}catch{return vt("Materialization JSON file must contain valid JSON.",m.file)}if(m.file.endsWith(uf)&&!XA(m.content).success)return vt("Materialization component i18n resources are invalid.",m.file);continue}try{let g=Nx(m.content,{sourceType:"module",plugins:["jsx","typescript"]});c.set(m.file,g);for(let h of g.program.body)if((h.type==="ImportDeclaration"||h.type==="ExportAllDeclaration"||h.type==="ExportNamedDeclaration"&&h.source)&&h.source){let x=h.source.value,b=iw(m.file,x,s,a);if(!b.allowed)return vt(`Materialization import is outside the controlled package: ${x}`,m.file);b.internalPath&&l.get(m.file).add(b.internalPath)}let p;if(qA(g,{Identifier(h){h.isReferencedIdentifier()&&ZA.has(h.node.name)&&(p??=h.node.name,h.stop())},JSXOpeningElement(h){h.node.name.type==="JSXIdentifier"&&h.node.name.name.toLowerCase()==="style"&&(p??="style element",h.stop())}}),p)return vt(`Materialization source uses forbidden capability: ${p}`,m.file)}catch{return vt("Materialization source must parse as TS/TSX.",m.file)}}if([...t].some(m=>!s.has(m)))return vt("Materialization entry is outside the controlled package.");for(let m of t)if(m.endsWith(".json"))return vt("Materialization JSON files cannot be package entries.");for(let[m,g]of i){let p=c.get(m);if(!p||!nw(p,g))return vt("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=Px(m.entry,l);for(let p of m.declaredComponentIds){let h=r.get(p);if(!h||!g.has(h))return vt(`Page entry does not reach declared component: ${p}`,m.entry)}for(let p of g){let h=u.get(p);if(h&&!m.declaredComponentIds.has(h))return vt(`Page entry imports undeclared component: ${h}`,m.entry)}}let d=new Set;for(let m of t)for(let g of Px(m,l))d.add(g);if(d.size!==e.length)return vt("Every materialization file must be reachable from a package entry.");let f=sw(e,c,l);return f||{ok:!0}}function tw(e){if(e.length>VA)return vt("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>KA)return vt("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>JA?vt("Page resource exceeds the aggregate content byte limit."):null}function nw(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 rw(e,t,n){let r;try{r=Nx(e,{sourceType:"module",sourceFilename:n,plugins:["jsx","typescript"]})}catch{return vt("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=Cx(s.init);if(a?.type!=="ObjectExpression")return{ok:!0,data:e};let l=a.properties.find(u=>u.type==="ObjectProperty"&&!u.computed&&ow(u.key));if(!l||l.type!=="ObjectProperty")return{ok:!0,data:e};let c=Cx(l.value);return c?c.type!=="StringLiteral"&&c.type!=="TemplateLiteral"||c.type==="TemplateLiteral"&&c.expressions.length>0||typeof c.start!="number"||typeof c.end!="number"?{ok:!0,data:e}:{ok:!0,data:e.slice(0,c.start)+JSON.stringify(t)+e.slice(c.end)}:{ok:!0,data:e}}}return{ok:!0,data:e}}function Cx(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&Ax.isExpression(t)?t:null}function ow(e){return e.type==="Identifier"&&e.name==="title"||e.type==="StringLiteral"&&e.value==="title"}function iw(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=Rx(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:YA.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=Gc.posix.normalize(Gc.posix.join(Gc.posix.dirname(e),t)),i=Rx(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function Rx(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 sw(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(uf))continue;let i=o.file.slice(0,-uf.length),s=[`${i}.tsx`,`${i}.ts`].find(u=>r.has(u));if(!s)return vt("Component i18n resources require a same-name TS/TSX companion.",o.file);let l=t.get(s)?.program.directives.some(u=>u.value.value==="use client"),c=[...n].filter(([,u])=>u.has(o.file));if(!l||c.length!==1||c[0]?.[0]!==s)return vt("Component i18n resources must have exactly one same-name Client Component static importer.",s)}return null}function Px(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 aw(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function cw(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"page-resource"}function vt(e,t){return{ok:!1,code:"MATERIALIZATION_REJECTED",message:e,...t?{path:t}:{}}}import{randomBytes as Lw}from"node:crypto";import Mr from"node:path";import{parse as Fw}from"@babel/parser";import Dw from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as Zc,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as Mx,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as Mw,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as Bw,SiteEditMaterializationSchema as jw,parseComponentI18nResourcesJson as $w}from"@vcp-dev/platform-shared/contracts";import{parse as kw}from"@babel/parser";import _w from"@babel/traverse";import{GeneratedSiteCapabilitiesSchema as Cw,FormDefinitionIdSchema as Rw}from"@vcp-dev/platform-shared/contracts";var Tx={colorMixPolicy:"always",includeExtendedColorFunctions:!0},Ox=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,Lx=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,lw=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,uw=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,dw=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,fw=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,pw=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,mw=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,gw=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,hw=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,yw=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,xw=/\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,bw=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,Sw=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function mf(e,t){let n=Yc([...Xn(e,lw),...Xn(e,uw),...Xn(e,dw),...Xn(e,t.includeRgbBackgroundImage?fw:pw),...t.includeExtendedColorFunctions?[...Xn(e,mw),...Xn(e,gw)]:[]]),r=Yc([...Xn(e,hw),...Xn(e,yw)]).filter(o=>t.colorMixPolicy==="always"||Ox.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...Xn(e,xw).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...Xn(e,Sw).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:Yc(Xn(e,Lx)),hardCodedSurfaceOccurrences:vw(e),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?Ew(e):[]}}function Ew(e){return Yc(Xn(e,bw))}function Xn(e,t){return e.match(new RegExp(t.source,t.flags))??[]}var wx=160,Iw=/((?:[a-z][a-z0-9-]*(?:\[[^\]]*\])?:)+)$/;function vw(e){let t=new RegExp(Lx.source,"g"),n=[0];for(let s=0;s<e.length;s+=1)e[s]===`
5
5
  `&&n.push(s+1);let r=s=>{let a=0,l=n.length-1;for(;a<l;){let c=Math.ceil((a+l)/2);(n[c]??0)<=s?a=c:l=c-1}return a},o=[],i;for(;(i=t.exec(e))!==null;){let s=i[0],a=s.endsWith("/")?s.slice(0,-1):s,l=/^\/(\d+)/.exec(e.slice(i.index+a.length)),c=e.slice(Math.max(0,i.index-64),i.index),u=Iw.exec(c),d=r(i.index),f=e.indexOf(`
6
- `,i.index),m=e.slice(n[d]??0,f===-1?void 0:f).trim();o.push({token:a,variant:u?.[1]??"",alpha:l?Number(l[1]):null,line:d+1,snippet:m.length>wx?`${m.slice(0,wx-1)}\u2026`:m})}return o}function Yc(e){return[...new Set(e)]}var Pw=["@/components/site/","@/lib/generated/","@/lib/cms","@/lib/cms/"],Nw=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Fx=new Set(["require","module","exports","__dirname","__filename"]),gf=_w,Aw=typeof gf=="function"?gf:gf.default;function yf(e,t={}){let n=[],r=ww(t.hostCapabilities),o=mf(e,t.style??Tx),i;try{i=kw(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return{ok:!1,violations:[{code:"parse-failed",message:"Generated source failed Babel parsing."}],styleViolations:o}}t.themeStyleMode==="reject"&&Ow(o)&&n.push({code:"style-forbidden",message:"Generated source must use public semantic design tokens instead of raw colors, hard-coded surfaces, or private tokens."});let s=u=>{n.some(f=>f.code===u.code&&f.name===u.name&&f.source===u.source)||n.push(u)};return Aw(i,{ImportDeclaration(u){a(u.node.source.value)},ExportNamedDeclaration(u){let d=u.node.source?.value;d&&a(d)},ExportAllDeclaration(u){a(u.node.source.value)},CallExpression(u){let d=u.node.callee;if(d.type==="Import"){s({code:"dynamic-import-forbidden",message:"Generated source cannot use dynamic import()."});return}d.type==="Identifier"&&(d.name==="require"?s({code:"commonjs-forbidden",message:"Generated source cannot use CommonJS require().",name:d.name}):(d.name==="eval"||d.name==="Function")&&s({code:"dynamic-code-forbidden",message:`Generated source cannot execute dynamic code through ${d.name}().`,name:d.name}))},NewExpression(u){u.node.callee.type==="Identifier"&&u.node.callee.name==="Function"&&s({code:"dynamic-code-forbidden",message:"Generated source cannot construct functions dynamically through Function().",name:"Function"})},MetaProperty(u){u.node.meta.type==="Identifier"&&u.node.meta.name==="import"&&s({code:"import-meta-forbidden",message:"Generated source cannot use import.meta."})},MemberExpression(u){c(hf(u.node))},OptionalMemberExpression(u){c(hf(u.node))},Identifier(u){u.isReferencedIdentifier()&&c(u.node.name)},JSXAttribute(u){t.rejectInlineStyles&&u.node.name.type==="JSXIdentifier"&&u.node.name.name==="style"&&s({code:"inline-style-forbidden",message:"Generated source cannot use inline style attributes."})},JSXOpeningElement(u){t.rejectStyleElements&&u.node.name.type==="JSXIdentifier"&&u.node.name.name.toLowerCase()==="style"&&s({code:"inline-style-forbidden",message:"Generated source cannot declare style elements."})}}),{ok:n.length===0,violations:n,styleViolations:o};function a(u){if(!(t.trustedManagedImports?.includes(u)&&Rw.safeParse(/^@\/components\/site\/generated\/forms\/form-([^/]+)$/u.exec(u)?.[1]).success)&&!(u.startsWith("./")||u.startsWith("../"))){if(t.allowSiteOwnedImports&&Pw.some(d=>d.endsWith("/")?u.startsWith(d):u===d)){l(u);return}r?Tw(u,r)||s({code:"import-forbidden",message:`Generated source imports a package or public path outside the trusted host capabilities: ${u}.`,source:u}):s({code:t.hostCapabilities===void 0?"host-capabilities-unavailable":"host-capabilities-invalid",message:"Generated code cannot use an external import without trusted host capabilities.",source:u}),l(u)}}function l(u){t.protectedImportPrefixes?.some(d=>u.startsWith(d))&&s({code:"protected-import-forbidden",message:`Generated source cannot import protected host output directly: ${u}.`,source:u})}function c(u){if(!(!u||!Nw.has(u))){if(u==="eval"||u==="Function"){s({code:"dynamic-code-forbidden",message:`Generated source cannot execute dynamic code through ${u}.`,name:u});return}s({code:Fx.has(u)?"commonjs-forbidden":"browser-global-forbidden",message:Fx.has(u)?`Generated source cannot depend on the CommonJS global ${u}.`:`Generated source cannot depend on the restricted global ${u}.`,name:u})}}}function ww(e){if(e==null)return null;let t=Cw.safeParse(e);return t.success?t.data:null}function Tw(e,t){if(t.runtime_dependencies.some(({name:r})=>e===r||e.startsWith(`${r}/`)))return!0;if(!e.startsWith("@/"))return!1;let n=e.slice(2);return t.public_paths.some(r=>{let[o]=r.split("#",1);return o.endsWith("/*")?n.startsWith(o.slice(0,-1)):Dx(n)===Dx(o)})}function Dx(e){return e.replace(/\.(?:jsx?|tsx?|json)$/i,"")}function Ow(e){return e.hardCodedSurfaceHits.length>0||e.rawColorHits.length>0||e.privateTokenHits.length>0}function hf(e){return e.type==="Identifier"?e.name:e.type==="MemberExpression"||e.type==="OptionalMemberExpression"?hf(e.object):null}var Kx="components/site/generated",Bx="{{$INSTANCE}}",qc=5,Uw=/^[a-z][a-z0-9-]{0,48}$/,Vw=/^[a-f0-9]{8}$/,jx=/\.tsx?$/,Kw=/\.json$/,Jw=/\.(?:tsx?|json)$/,Xw=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,xf=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),bf=Dw,zw=typeof bf=="function"?bf:bf.default;function Ww(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>Mx)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=cT(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=jw.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=iT(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${Kx}.`,path:e.generatedRoot}};if(!Jx(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=Ux(r.data.files),s=Ux(e.controlledFiles);if(!lT(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>Mx)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let a=0;for(let[l,c]of r.data.files.entries()){let u=Buffer.byteLength(c.content,"utf8");if(u>Mw)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file exceeds the per-file content limit.",file:c.pathTemplate,path:`files[${l}]`}};a+=u}return a>Bw?{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 Hw(e){let t=Ww(e);if(!t.ok)return t;let n=t.data.generatedRoot,r=Jx(e.manifest.instanceBaseName),o=Math.max(1,Math.min(qc,e.maxAttempts??qc));for(let i=0;i<o;i+=1){let s=sT(e.instanceNameGenerator?.()??Lw(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}`,l=zx(n,a),c=Gw({manifest:e.manifest,generatedRoot:n,instanceName:a,instanceRoot:l,hostCapabilities:e.hostCapabilities??null,availableHostDependencies:e.availableHostDependencies});if(!c.ok)return c;if(!await Zw(e.exists,l,c.data.files))return{ok:!0,data:c.data}}return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:"Unable to allocate a create-only static prefab instance after repeated conflicts."}}}async function Sf(e){let t=Math.max(1,Math.min(qc,e.maxAttempts??qc));for(let n=0;n<t;n+=1){let r=await Hw({...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 Gw(e){let t=Yw(e);if(t)return{ok:!1,error:t};let n=[],r=new Set;for(let s of e.manifest.files){let a=Ls({pathTemplate:s.pathTemplate,generatedRoot:e.generatedRoot,instanceName:e.instanceName,instanceRoot:e.instanceRoot});if(!a.ok)return a;if(r.has(a.data))return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${a.data}`,path:a.data}};r.add(a.data),n.push({kind:"create-only",path:a.data,content:s.content,...s.role?{role:s.role}:{},sourcePathTemplate:s.pathTemplate})}n.sort((s,a)=>s.path.localeCompare(a.path));let o=Ls({pathTemplate:e.manifest.entry.pathTemplate,generatedRoot:e.generatedRoot,instanceName:e.instanceName,instanceRoot:e.instanceRoot});if(!o.ok)return o;if(!n.some(s=>s.path===o.data))return{ok:!1,error:{code:"MATERIALIZATION_ENTRY_INVALID",message:"Entry path must match one of the static prefab files.",path:o.data}};let i=Ef({files:n,instanceRoot:e.instanceRoot,entries:[{path:o.data,export:e.manifest.entry.export}],hostCapabilities:e.hostCapabilities,declaredProjectDependencies:Object.keys(e.manifest.projectDependencies??{}),availableHostDependencies:e.availableHostDependencies});return i.ok?{ok:!0,data:{kind:"static-prefab-materialization",instanceName:e.instanceName,generatedRoot:e.generatedRoot,instanceRoot:e.instanceRoot,entry:{path:o.data,export:e.manifest.entry.export},files:n}}:i}function Yw(e){if(e.availableHostDependencies===void 0)return null;let t=new Set(Object.keys(e.manifest.projectDependencies??{})),n=new Set(e.availableHostDependencies);return n.size!==e.availableHostDependencies.length||[...n].some(r=>!t.has(r))?{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Target host dependency evidence must match declared materialization dependencies."}:[...t].some(r=>!n.has(r))?{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"The target host does not provide every declared materialization dependency."}:[...t].some(r=>!e.hostCapabilities?.runtime_dependencies.some(({name:o})=>o===r))?{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Materialization dependencies exceed the trusted host capability contract."}:null}async function Zw(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function Ls(e){if(e.pathTemplate.split(Bx).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(Bx,e.instanceName),n=aT(t);return n?zx(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||!Jw.test(n)||Xw.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 Ef(e){let{files:t,instanceRoot:n,entries:r,hostCapabilities:o}=e,i=new Set(e.declaredProjectDependencies??[]),s=e.availableHostDependencies===void 0?null:new Set(e.availableHostDependencies),a=new Set(t.map(m=>m.path)),l=new Map,c=new Map(t.map(m=>[m.path,new Set])),u=new Map;for(let m of t){if(Kw.test(m.path)){if(m.path.endsWith(Zc)){let x=$w(m.content);if(!x.success)return Dr("MATERIALIZATION_DATA_UNSUPPORTED",x.error.message,m.path);u.set(m.path,new Set)}else try{JSON.parse(m.content)}catch{return Dr("MATERIALIZATION_DATA_UNSUPPORTED","Static prefab JSON file must contain valid JSON.",m.path)}continue}let g;try{g=Fw(m.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:m.path}}}let p=yf(m.content,{hostCapabilities:o,protectedImportPrefixes:["@/components/site/generated/"],trustedManagedImports:e.trustedManagedImports,rejectInlineStyles:!1,rejectStyleElements:!0,themeStyleMode:e.preserveCapturedStyles?"report":"ignore",style:{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!1,rejectPrivateTokens:!1,rejectTailwindPalette:!1}}),h=Qw(p.violations,m.path);if(h)return{ok:!1,error:h};l.set(m.path,g)}for(let m of t){if(!jx.test(m.path))continue;let g=l.get(m.path),p=null;if(zw(g,{ImportDeclaration(h){let x=$x({importer:m.path,source:h.node.source.value,instanceRoot:n,filePaths:a});if(!x.allowed)p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab imports must resolve within the controlled instance or match the starter allowlist.",file:m.path},h.stop();else if(!x.internalPath&&!eT(h.node.source.value,i,s))p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"External prefab imports must be declared and available in the target host.",file:m.path},h.stop();else if(x.internalPath&&(c.get(m.path).add(x.internalPath),x.internalPath.endsWith(Zc))){let b=nT({importer:m.path,imported:x.internalPath,source:h.node.source.value,ast:g});b.ok?u.get(x.internalPath).add(m.path):(p??=b.error,h.stop())}},ExportAllDeclaration(h){p??={code:"MATERIALIZATION_ENTRY_INVALID",message:"Static prefab files cannot use export-star declarations.",file:m.path},h.stop()},ExportNamedDeclaration(h){if(h.node.source){let x=$x({importer:m.path,source:h.node.source.value,instanceRoot:n,filePaths:a});!x.allowed||!x.internalPath&&!e.trustedManagedImports?.includes(h.node.source.value)?(p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab re-exports must resolve within the controlled instance.",file:m.path},h.stop()):x.internalPath&&c.get(m.path).add(x.internalPath)}},CallExpression(h){if(h.node.callee.type==="Import"){p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use dynamic import().",file:m.path},h.stop();return}h.node.callee.type==="Identifier"&&h.node.callee.name==="require"&&(p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use require().",file:m.path},h.stop())},NewExpression(h){h.node.callee.type==="Identifier"&&h.node.callee.name==="Function"&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot construct functions dynamically.",file:m.path},h.stop())},MetaProperty(h){h.node.meta.type==="Identifier"&&h.node.meta.name==="import"&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot use import.meta.",file:m.path},h.stop())},MemberExpression(h){let x=Vx(h.node);x&&xf.has(x)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${x}.`,file:m.path},h.stop())},OptionalMemberExpression(h){let x=Vx(h.node);x&&xf.has(x)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${x}.`,file:m.path},h.stop())},Identifier(h){h.isReferencedIdentifier()&&xf.has(h.node.name)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h.node.name}.`,file:m.path},h.stop())},JSXAttribute(h){!e.preserveCapturedStyles||h.node.name.type!=="JSXIdentifier"||h.node.name.name!=="style"||qw(h.node.value)||(p??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot use inline style attributes.",file:m.path},h.stop())},JSXOpeningElement(h){h.node.name.type==="JSXIdentifier"&&h.node.name.name.toLowerCase()==="style"&&(p??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot declare style elements.",file:m.path},h.stop())},StringLiteral(h){e.preserveCapturedStyles&&Qc(h.node.value)&&(p??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Captured styles cannot load URLs or execute CSS expressions.",file:m.path},h.stop())},TemplateElement(h){e.preserveCapturedStyles&&Qc(h.node.value.cooked??h.node.value.raw)&&(p??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Captured styles cannot load URLs or execute CSS expressions.",file:m.path},h.stop())},JSXElement(h){let x=h.node.openingElement.name;e.preserveCapturedStyles&&x.type==="JSXIdentifier"&&["script","iframe","object","embed"].includes(x.name.toLowerCase())&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Captured components cannot embed executable external documents.",file:m.path},h.stop())}}),p)return{ok:!1,error:p}}if(r.length===0)return Dr("MATERIALIZATION_ENTRY_INVALID","Static prefab requires at least one source entry.");let d=new Set;for(let m of r){if(d.has(m.path))return Dr("MATERIALIZATION_PATH_INVALID",`Static prefab contains duplicate source entries: ${m.path}`,m.path);if(d.add(m.path),!jx.test(m.path))return Dr("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must be a .ts/.tsx source module.",m.path);let g=l.get(m.path);if(!g)return Dr("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",m.path);if(!rT(g,m.export))return Dr("MATERIALIZATION_EXPORT_MISSING","Static prefab entry does not declare the manifest export.",m.path)}for(let[m,g]of u)if(g.size!==1)return Dr("MATERIALIZATION_IMPORT_FORBIDDEN","Each component .i18n.json file must have exactly one same-name Client Component static importer.",m);let f=new Set;for(let m of r)for(let g of oT(m.path,c))f.add(g);return f.size!==t.length?Dr("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",r[0]?.path):{ok:!0}}function Qc(e){return/(?:url|expression)\s*\(|@import|javascript:|-moz-binding|\\/iu.test(e)}function qw(e){return e?.type!=="JSXExpressionContainer"||e.expression.type!=="ObjectExpression"?!1:e.expression.properties.every(t=>{if(t.type!=="ObjectProperty"||t.computed)return!1;let n=t.key.type==="Identifier"?t.key.name:t.key.type==="StringLiteral"?t.key.value:null;if(!n||n==="__proto__"||n==="constructor"||n==="prototype"||Qc(n))return!1;let r=t.value;return r.type==="StringLiteral"&&!Qc(r.value)||r.type==="NumericLiteral"||r.type==="NullLiteral"||r.type==="UnaryExpression"&&["-","+"].includes(r.operator)&&r.argument.type==="NumericLiteral"})}function Qw(e,t){let n=e[0];if(!n)return null;let r=new Set(["host-capabilities-unavailable","host-capabilities-invalid","import-forbidden","protected-import-forbidden","dynamic-import-forbidden","commonjs-forbidden"]),o=new Set(["inline-style-forbidden","style-forbidden"]);return{code:r.has(n.code)?"MATERIALIZATION_IMPORT_FORBIDDEN":o.has(n.code)?"MATERIALIZATION_STYLE_FORBIDDEN":"MATERIALIZATION_DATA_UNSUPPORTED",message:n.message,file:t}}function $x(e){if(!e.source.startsWith("./")&&!e.source.startsWith("../"))return{allowed:!0};if(e.source.includes("\\")||e.source.includes("\0"))return{allowed:!1};let t=Mr.posix.normalize(Mr.posix.join(Mr.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 eT(e,t,n){if(n===null)return!0;let r=tT(e);return r===null||t.has(r)&&n.has(r)}function tT(e){if(e.startsWith("@/")||e.startsWith("./")||e.startsWith("../")||e.startsWith("/"))return null;if(e.startsWith("@")){let[t,n]=e.split("/");return t&&n?`${t}/${n}`:e}return e.split("/")[0]||null}function nT(e){let t=Mr.posix.dirname(e.importer),n=Mr.posix.dirname(e.imported),r=Mr.posix.basename(e.importer).replace(/\.tsx?$/,""),o=Mr.posix.basename(e.imported).slice(0,-Zc.length),i=`./${r}${Zc}`;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 rT(e,t){for(let n of e.program.body){if(t.kind==="default"&&n.type==="ExportDefaultDeclaration"||t.kind==="default"&&n.type==="ExportNamedDeclaration"&&n.exportKind!=="type"&&n.specifiers.some(o=>o.type==="ExportSpecifier"&&o.exportKind!=="type"&&o.exported.type==="Identifier"&&o.exported.name==="default"))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 oT(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 Dr(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function iT(e){let t=Xx(e);return t===Kx?t:null}function sT(e){let t=e.trim().toLowerCase();return Vw.test(t)?t:null}function Jx(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 Uw.test(t)?t:null}function Xx(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=Mr.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function aT(e){let t=Xx(e);return!t||t!==e?null:t}function zx(...e){return Mr.posix.join(...e)}function Ux(e){return new Set(e.map(t=>t.pathTemplate))}function cT(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 lT(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Vx(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{createHash as Wf}from"node:crypto";import $f from"@babel/traverse";function If(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 l=Object.freeze([...a]),c=l.find(u=>u.anchorSourceRange!==null&&u.members.length>0)??l.find(u=>u.members.length>0)??l[0];c&&(o.set(s,l),i.set(s,c),r.set(s,Object.freeze({placementUnitKey:s,placementKeys:Object.freeze(l.map(u=>u.placementKey)),sourcePlacementKey:c.placementKey})))}return{placementByKey:t,unitByKey:r,placementsByUnitKey:o,sourcePlacementByUnitKey:i}}function el(e){if(e.node.alternate||!uT(e.get("test")))return!1;let t=e.get("consequent"),n=t.isBlockStatement()?t.get("body"):[t];if(n.length!==1)return!1;let r=n[0];if(r.isThrowStatement())return!0;if(!r.isExpressionStatement())return!1;let o=r.get("expression");if(!o.isCallExpression()||o.node.arguments.length!==0)return!1;let i=o.get("callee");if(!i.isIdentifier())return!1;let s=i.scope.getBinding(i.node.name);if(!s?.constant||s.constantViolations.length>0||!s.path.isImportSpecifier()||s.path.node.importKind==="type")return!1;let a=s.path.node.imported,l=a.type==="Identifier"?a.name:a.value,c=s.path.parentPath;return!!(l==="notFound"&&c?.isImportDeclaration()&&c.node.importKind!=="type"&&c.node.source.value==="next/navigation")}function uT(e){let t=Wx(e);return e.traverse({enter(n){Wx(n)||(t=!1,n.stop())}}),t}function Wx(e){if(e.isAssignmentExpression()||e.isUpdateExpression()||e.isAwaitExpression()||e.isYieldExpression()||e.isNewExpression()||e.isTaggedTemplateExpression()||e.isOptionalCallExpression()||e.isJSXElement()||e.isJSXFragment()||e.isFunction()||e.isUnaryExpression({operator:"delete"}))return!1;if(!e.isCallExpression())return!0;let t=e.get("callee"),n=e.get("arguments");if(!t.isMemberExpression()||t.node.computed||n.length!==1)return!1;let r=t.get("object"),o=t.get("property");if(!r.isIdentifier()||!o.isIdentifier())return!1;if(r.node.name==="Object"&&o.node.name==="keys"&&!r.scope.getBinding("Object"))return!n[0].isSpreadElement();let i=r.scope.getBinding(r.node.name);return!!(o.node.name==="includes"&&n[0].isStringLiteral()&&i?.constant&&i.path.isVariableDeclarator()&&i.path.parentPath?.isVariableDeclaration({kind:"const"}))}import{createHash as LT}from"node:crypto";import ob from"node:path";import*as Ii from"@babel/parser";import wf from"@babel/traverse";import Tf from"@babel/generator";import*as ve from"@babel/types";import Rf from"@babel/generator";import{parse as ET}from"@babel/parser";import Pf from"@babel/traverse";import*as Ue from"@babel/types";import{PortableInvocationBindingSchema as IT}from"@vcp-dev/platform-shared/contracts";import vf from"@babel/traverse";import*as Je from"@babel/types";var Hx=typeof vf=="function"?vf:vf.default;function Pn(e){let t=Yx(e.module,e.exportName,e.parsedModules??new Map([[e.module.file,e.module]]),new Set);return t?Gx(t,e.allowNonRenderingGuards):no("component-export-unresolved","The requested local component export is not a statically resolvable function.",e.module.file)}function pr(e){let t=dT(e.module,e.componentName,e.callSourceRange);return t.kind==="local"?Gx(t.definition):t.kind==="imported"?!e.imported?.module&&!_t(t.specifier)?no("component-external-module-opaque","External package components are opaque to the local source graph.",t.specifier):e.imported?e.imported.module?Pn({module:e.imported.module,exportName:e.imported.exportName,parsedModules:e.imported.parsedModules}):no("component-module-unavailable","The component source module is unavailable in the parsed graph.",e.imported.file):no("component-local-binding-unresolved","The JSX call does not resolve to a statically declared local component function.",e.module.file):no("component-local-binding-unresolved","The JSX call does not resolve to a statically declared local component function.",e.module.file)}function Gx(e,t=!1){let n=hT(e.module.ast,e.node);if(!n)return no("component-function-unresolved","The component function has no source AST path.",e.module.file);let r=Zx(n,t);if(!r){let s=xT(n);return s?{ok:!0,componentName:e.name,sourceFile:e.module.file,metadataOnly:!1,roots:[s[0]],returnAlternatives:s}:no("component-control-flow-unsupported","Component roots require an expression body or one direct return.",e.module.file)}let o=[],i=qx(r);return nl(r,o)?{ok:!0,componentName:e.name,sourceFile:e.module.file,metadataOnly:i,roots:o}:no("component-root-dynamic","Component return contains an unsupported dynamic or spread root.",e.module.file)}function dT(e,t,n){let r={kind:"unresolved"};return Hx(e.ast,{JSXElement(o){if(!mT(o.node.loc,n))return;let i=o.node.openingElement.name;if(!Je.isJSXIdentifier(i)||i.name!==t)return;let s=o.scope.getBinding(t);if(!s||s.constantViolations.length>0){o.stop();return}if(fT(s.path)){let l=s.path.parentPath;l?.isImportDeclaration()&&(r={kind:"imported",specifier:l.node.source.value}),o.stop();return}let a=pT(s.path);a&&(r={kind:"local",definition:{node:a,name:t,module:e}}),o.stop()}}),r}function fT(e){return e.isImportSpecifier()||e.isImportDefaultSpecifier()||e.isImportNamespaceSpecifier()}function pT(e){if(e.isFunctionDeclaration())return e.node;if(!e.isVariableDeclarator())return null;let t=e.get("init");return!Array.isArray(t)&&Cf(t.node)?t.node:null}function mT(e,t){return e!=null&&e.start.line===t.startLine&&e.start.column===t.startColumn&&e.end.line===t.endLine&&e.end.column===t.endColumn}function Yx(e,t,n,r){let o=`${e.file}#${t}`;if(r.has(o))return null;let i=new Set(r).add(o),s=(u,d)=>{let f=Hr(e.file,u,n),m=f?n.get(f):void 0;return m?Yx(m,d,n,i):null},a=u=>{let d=gT(e,u);if(d)return{...d,module:e};for(let f of e.ast.program.body)if(!(!Je.isImportDeclaration(f)||f.importKind==="type")){for(let m of f.specifiers)if(m.local.name===u){if(Je.isImportDefaultSpecifier(m))return s(f.source.value,"default");if(Je.isImportSpecifier(m)&&m.importKind!=="type")return s(f.source.value,tl(m.imported))}}return null};for(let u of e.ast.program.body){if(Je.isExportDefaultDeclaration(u)&&t==="default"){let d=u.declaration;if(Cf(d))return{node:d,name:ST(d)??"default",module:e};if(Je.isIdentifier(d))return a(d.name)}if(!(!Je.isExportNamedDeclaration(u)||u.exportKind==="type")){if(u.declaration){let d=bT(u.declaration,t);if(d)return a(d)}for(let d of u.specifiers)if(Je.isExportSpecifier(d)&&d.exportKind!=="type"&&tl(d.exported)===t)return u.source?s(u.source.value,tl(d.local)):a(tl(d.local))}}let l=e.ast.program.body.flatMap(u=>{if(!Je.isExportAllDeclaration(u)||u.exportKind==="type"||t==="default")return[];let d=s(u.source.value,t);return d?[d]:[]}),c=l.filter((u,d)=>l.findIndex(f=>f.node===u.node&&f.module.file===u.module.file)===d);return c.length===1?c[0]:null}function gT(e,t){for(let n of e.ast.program.body){let r=Je.isExportNamedDeclaration(n)?n.declaration:n;if(Je.isFunctionDeclaration(r)&&r.id?.name===t)return{node:r,name:t};if(Je.isVariableDeclaration(r)){for(let o of r.declarations)if(Je.isIdentifier(o.id)&&o.id.name===t&&Cf(o.init))return{node:o.init,name:t}}}return null}function hT(e,t){let n=null;return Hx(e,{Function(r){r.node===t&&(n=r,r.stop())}}),n}function Zx(e,t=!1){let n=e.get("body");if(!n.isBlockStatement())return n;let r=n.get("body"),o=r.at(-1);return!o?.isReturnStatement()||!o.get("argument").node||!r.slice(0,-1).every(i=>i.isVariableDeclaration()||i.isFunctionDeclaration()||yT(i)||t&&i.isIfStatement()&&el(i))?null:o.get("argument")}function yT(e){if(!e.isExpressionStatement())return!1;let t=e.get("expression");if(!t.isCallExpression())return!1;let n=t.get("callee");if(!n.isIdentifier())return!1;let r=n.scope.getBinding(n.node.name);if(!r?.constant||!r.path.isImportSpecifier())return!1;let o=r.path.node.imported,i=r.path.parentPath;if(!Je.isIdentifier(o,{name:"useEffect"})||!i?.isImportDeclaration()||i.node.source.value!=="react"||i.node.importKind==="type"||r.path.node.importKind==="type")return!1;let s=t.get("arguments")[0];return!!(s&&(s.isArrowFunctionExpression()||s.isFunctionExpression()))}function xT(e){let t=e.get("body");if(!t.isBlockStatement())return null;let n=kf(t.get("body"));if(!n||n.length<2)return null;let r=[],o=null;for(let i of n){if(!i.isJSXElement())return null;let s=i.node.openingElement.name;if(!Je.isJSXIdentifier(s)||!/^[A-Z]/.test(s.name))return null;let a=i.scope.getBinding(s.name);if(!a||a.constantViolations.length>0||o&&o!==a.path.node||(o=a.path.node,i.node.children.some(l=>!Je.isJSXText(l)||l.value.trim()!=="")||i.node.openingElement.attributes.some(l=>Je.isJSXSpreadAttribute(l)||Je.isJSXAttribute(l)&&Je.isJSXIdentifier(l.name,{name:"children"}))))return null;r.push(i)}return r}function kf(e){for(let[t,n]of e.entries()){if(n.isVariableDeclaration()||n.isFunctionDeclaration())continue;if(n.isReturnStatement()){let a=n.get("argument");return a.node&&t===e.length-1?[a]:null}if(!n.isIfStatement())return null;let r=a=>kf(a.isBlockStatement()?a.get("body"):[a]),o=r(n.get("consequent")),i=n.get("alternate"),s=i.node?t===e.length-1?r(i):null:kf(e.slice(t+1));return o&&s?[...o,...s]:null}return null}function nl(e,t){if(qx(e))return!0;if(e.isJSXFragment()||e.isJSXElement()&&ht(e)){let n=e.get("children");for(let r of Array.isArray(n)?n:[n])if(!r.isJSXText()&&(r.isJSXSpreadChild()||!nl(r,t)))return!1;return!0}if(e.isJSXElement())return t.push(e),!0;if(e.isJSXExpressionContainer()){let n=e.get("expression");return n.isJSXEmptyExpression()||n.isNullLiteral()||nl(n,t)}return e.isParenthesizedExpression()||e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isTypeCastExpression()?nl(e.get("expression"),t):e.isNullLiteral()||e.isStringLiteral()||e.isNumericLiteral()||e.isBooleanLiteral()}function _f(e){return["base","link","meta","script","style","title"].includes(e)}function qx(e){let t=!1,n=r=>{if(r.isJSXElement()){let o=r.node.openingElement.name;return Je.isJSXIdentifier(o)&&_f(o.name)?(t=!0,!0):ht(r)?r.get("children").every(i=>n(i)):!1}if(r.isJSXFragment())return r.get("children").every(o=>n(o));if(r.isJSXText())return r.node.value.trim()==="";if(r.isNullLiteral()||r.isBooleanLiteral()||r.isJSXEmptyExpression())return!0;if(r.isJSXExpressionContainer()||r.isParenthesizedExpression()||r.isTSAsExpression()||r.isTSTypeAssertion()||r.isTSNonNullExpression())return n(r.get("expression"));if(r.isConditionalExpression())return n(r.get("consequent"))&&n(r.get("alternate"));if(r.isArrayExpression())return r.get("elements").every(o=>!o.node||n(o));if(r.isCallExpression()){let o=r.get("callee"),i=r.get("arguments");if(!o.isMemberExpression()||o.node.computed||!Je.isIdentifier(o.node.property,{name:"map"})||i.length!==1)return!1;let s=i[0];if(!s.isArrowFunctionExpression()&&!s.isFunctionExpression())return!1;let a=Zx(s);return a!==null&&n(a)}return!1};return n(e)&&t}function bT(e,t){return Je.isFunctionDeclaration(e)?e.id?.name===t?t:null:Je.isVariableDeclaration(e)&&e.declarations.some(n=>Je.isIdentifier(n.id)&&n.id.name===t)?t:null}function Cf(e){return Je.isFunctionDeclaration(e)||Je.isFunctionExpression(e)||Je.isArrowFunctionExpression(e)}function ST(e){return"id"in e&&e.id&&Je.isIdentifier(e.id)?e.id.name:null}function tl(e){return Je.isIdentifier(e)?e.name:e.value}function no(e,t,n){return{ok:!1,diagnostic:{code:e,message:t,file:n}}}var Nf=typeof Rf=="function"?Rf:Rf.default,Qx=typeof Pf=="function"?Pf:Pf.default,tb=new Set(["sourceBlockId","source_block_id","originalBlockId","original_block_id"]),vT=new Set(["sourceOrder","source_order","originalOrder","original_order"]),kT=new Set(["data-site-block-id","data-site-block-order","data-vcp-block-id","data-vcp-edit-key","data-vcp-order","sourceBlockId","source_block_id","originalBlockId","original_block_id","sourceOrder","source_order","originalOrder","original_order"]),_T=/^[A-Za-z_$][A-Za-z0-9_$]*$/u,CT=/^[A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)*$/u;function oo(e){if(!rb(e)||!Array.isArray(e.bindings))return ro("INVOCATION_INPUT_INVALID","bindings must be an array in a portable invocation.","bindings");let t=AT(e);if(!t||!CT.test(t))return ro("INVOCATION_COMPONENT_INVALID","Portable invocation requires a safe JSX component local name.","component");let n=nb(e.targetBlockId);if(!n.ok)return n;let r=wT(e.targetOrder);if(!r.ok)return r;let o=e.searchParamsIdentifier??"searchParams";if(!_T.test(o))return ro("INVOCATION_VALUE_UNRESOLVED","The route searchParams binding requires a safe local identifier.","searchParamsIdentifier");let i=[],s=[],a=new Set,l=!1,c=!1,u=0;for(let[f,m]of e.bindings.entries()){let g=IT.safeParse(m);if(!g.success)return ro("INVOCATION_VALUE_UNRESOLVED","Portable invocation values must use the closed JSON/server/identity contract.",`bindings.${f}`);let p=g.data;if(a.has(p.propName))return ro("INVOCATION_DUPLICATE_PROP",`Portable invocation contains duplicate prop ${p.propName}.`,`bindings.${f}.propName`);if(a.add(p.propName),vT.has(p.propName))return ro("INVOCATION_SOURCE_METADATA","Source block order cannot be copied or rebound as a component prop.",`bindings.${f}`);if(tb.has(p.propName)&&p.value.kind!=="target-block-id")return ro("INVOCATION_SOURCE_METADATA","Source block identity/order cannot be copied as a business prop.",`bindings.${f}`);if(p.value.kind==="target-block-id"&&(u+=1,u>1))return ro("INVOCATION_DUPLICATE_PROP","A portable invocation may bind the target block identity only once.",`bindings.${f}`);p.value.kind==="route-search-params"&&(l=!0),p.value.kind==="route-params"&&(c=!0),s.push(p),i.push(Ue.jsxAttribute(Ue.jsxIdentifier(p.propName),Ue.jsxExpressionContainer(PT(p.value,n.value,o))))}let d=Ue.jsxElement(Ue.jsxOpeningElement(NT(t),i,!0),null,[],!0);return{ok:!0,plan:{kind:"portable-invocation",component:t,jsx:Nf(d,{jsescOption:{minimal:!0}}).code,bindings:s,targetBlockId:n.value,targetOrder:r.value,requiresRouteSearchParams:l,requiresRouteParams:c,searchParamsIdentifier:l?o:null}}}function RT(e){if(!rb(e)||e.jsx===void 0==(e.source===void 0))return Si("BLOCK_METADATA_INPUT_INVALID","Provide exactly one JSX expression or full source module.","input");let t=nb(e.targetBlockId);if(!t.ok)return Si("BLOCK_METADATA_TARGET_INVALID",t.error.message,"targetBlockId");if(!Number.isSafeInteger(e.targetOrder)||e.targetOrder<0)return Si("BLOCK_METADATA_TARGET_INVALID","targetOrder must be a non-negative safe integer.","targetOrder");let n=e.jsx!==void 0,r,o;try{if(!n&&e.entryExport){let m=Oe("portable-entry.tsx",e.source);if(!m.ok)throw new Error(m.diagnostic.message);o=m.module,r=o.ast}else r=ET(n?e.jsx:e.source,{sourceType:"module",plugins:["jsx","typescript"]})}catch(m){return Si("BLOCK_METADATA_PARSE_FAILED",m instanceof Error?m.message:String(m),n?"jsx":"source")}let i=[],s;if(o&&e.entryExport){let m=Pn({module:o,exportName:e.entryExport.kind==="default"?"default":e.entryExport.name});m.ok&&m.roots.length===1&&(s=m.roots[0],i.push(s.node))}else Qx(r,{JSXElement(m){eb(m)||i.push(m.node)},JSXFragment(m){eb(m)||i.push(m.node)}});if(i.length!==1)return Si("BLOCK_METADATA_ROOT_AMBIGUOUS","Portable block metadata requires exactly one JSX root.",n?"jsx":"source");let a=i[0],l=TT(a);if(!l)return Si("BLOCK_METADATA_ROOT_AMBIGUOUS","Portable block metadata requires exactly one direct JSX element root.",n?"jsx":"source");let c=0,u=0,d=m=>{let g=OT(m.node.name);!g||!kT.has(g)||(g==="data-site-block-id"||g==="data-vcp-block-id"||tb.has(g)?c+=1:u+=1,m.remove())};s?s.traverse({JSXAttribute:d}):Qx(r,{JSXAttribute:d}),l.openingElement.attributes.push(Ue.jsxAttribute(Ue.jsxIdentifier("data-site-block-id"),Ue.stringLiteral(t.value)),Ue.jsxAttribute(Ue.jsxIdentifier("data-site-block-order"),Ue.jsxExpressionContainer(Ue.numericLiteral(e.targetOrder))));let f=n?Nf(a,{jsescOption:{minimal:!0}}).code:Nf(r,{jsescOption:{minimal:!0}}).code;return{ok:!0,plan:{kind:"portable-block-metadata",source:f,jsx:f,targetBlockId:t.value,targetOrder:e.targetOrder,removedSourceBlockIdCount:c,removedSourceOrderCount:u}}}function PT(e,t,n){return e.kind==="route-params"?Ue.identifier("params"):e.kind==="route-search-params"?Ue.identifier(n):e.kind==="target-block-id"?Ue.stringLiteral(t):Af(e.value)}function Af(e){return e===null?Ue.nullLiteral():typeof e=="string"?Ue.stringLiteral(e):typeof e=="number"?Ue.numericLiteral(e):typeof e=="boolean"?Ue.booleanLiteral(e):Array.isArray(e)?Ue.arrayExpression(e.map(t=>Af(t))):Ue.objectExpression(Object.entries(e).map(([t,n])=>Ue.objectProperty(Ue.stringLiteral(t),Af(n))))}function NT(e){let t=e.split("."),n=Ue.jsxIdentifier(t[0]);for(let r of t.slice(1))n=Ue.jsxMemberExpression(n,Ue.jsxIdentifier(r));return n}function AT(e){return typeof e.componentName=="string"?e.componentName:typeof e.component=="string"?e.component:e.component&&typeof e.component=="object"?e.component.localName:null}function nb(e){return typeof e!="string"||e.length===0||e.trim()!==e||e.length>256?{ok:!1,error:{code:"INVOCATION_TARGET_BLOCK_INVALID",path:"targetBlockId",message:"targetBlockId must be a non-blank stable identity."}}:{ok:!0,value:e}}function wT(e){return e!=null?!Number.isSafeInteger(e)||e<0?{ok:!1,error:{code:"INVOCATION_TARGET_ORDER_INVALID",path:"targetOrder",message:"targetOrder must be a non-negative safe integer."}}:{ok:!0,value:e}:{ok:!0,value:null}}function TT(e){if(Ue.isJSXElement(e))return e;let t=e.children.filter(Ue.isJSXElement),n=e.children.some(r=>Ue.isJSXText(r)&&r.value.trim().length>0);return t.length===1&&!n?t[0]??null:null}function eb(e){let t=e.parentPath;for(;t;){if(t.isJSXElement()||t.isJSXFragment())return!0;t=t.parentPath}return!1}function OT(e){return Ue.isJSXIdentifier(e)?e.name:null}function rb(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ro(e,t,n){return{ok:!1,error:{code:e,path:n,message:t}}}function Si(e,t,n){return{ok:!1,error:{code:e,path:n,message:t}}}var Of=typeof Tf=="function"?Tf:Tf.default,FT=typeof wf=="function"?wf:wf.default;function Bs(e){let t=ub(e);if(t)return{ok:!1,error:t};let n=e.projection,r=jf(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,i=BT(n,o),s=HT(e);if(!s.ok)return s;let a={jsx:s.invocation?.jsx??`<${e.component.localName} />`},l=DT(e);if(i){let g=Lf(e);return g.ok?{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:o.placementUnitKey,importStep:l,...s.invocation?{invocation:s.invocation}:{},...s.serverParamsStep?{serverParamsStep:s.serverParamsStep}:{},returnStep:{kind:"insert-return",node:a,placement:o.relation,replaceOriginal:n.container.kind==="starter-placeholder"},rewriteStep:{kind:"insert-root-expression",locator:g.locator,sourceHash:g.sourceHash,node:a,placement:o.relation,replaceOriginal:n.container.kind==="starter-placeholder"}}}:g.result}let c=o.containerSourceRange??n.container.sourceRange,u=o.containerSourceHash??(ol(c,n.container.sourceRange)?n.container.sourceHash:null);if(!c||!u)return Fs("Route page composition does not expose a verifiable container boundary.");let d=Ms(c),f=sb(e.source,d,u,"Route page composition container");if(!f.ok)return f.result;let m=o.anchorSourceRange?Ms(o.anchorSourceRange):void 0;if(m){if(!o.anchorSourceHash)return Fs("Route page composition placement does not expose a verifiable anchor boundary.");let g=sb(e.source,m,o.anchorSourceHash,"Route page composition anchor");if(!g.ok)return g.result}return{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:o.placementUnitKey,importStep:l,...s.invocation?{invocation:s.invocation}:{},...s.serverParamsStep?{serverParamsStep:s.serverParamsStep}:{},insertStep:{kind:"insert-child",parentLocator:d,node:a,placement:o.relation,...m?{anchorLocator:m}:{}},rewriteStep:{kind:"insert-child",parentLocator:d,node:a,placement:o.relation,...m?{anchorLocator:m}:{}}}}}function Mf(e){let t=Oe(e.entryFile,e.source);if(!t.ok)return io("PORTABLE_ROUTE_SOURCE_INVALID",t.diagnostic.message);let n=Qn({route:e.routeId,composition:e.composition??{routeId:e.routeId},entryFile:e.entryFile,version:e.documentVersion,source:e.source,ast:t.module.ast});if(!n.ok)return io("PORTABLE_ROUTE_UNSUPPORTED","Portable route does not expose a supported page-composition boundary.",n.projection.diagnostics);let r=n.projection.placements.flatMap(c=>{if(c.relation!==e.anchor.relation)return[];if(e.anchor.sourceRange)return c.anchorSourceRange&&ol(c.anchorSourceRange,e.anchor.sourceRange)?[{placement:c,matchCount:1}]:[];let u=c.members.reduce((d,f)=>d+cb(f,e.anchor.componentName),0);return u===0?[]:[{placement:c,matchCount:u}]}),o=r.reduce((c,u)=>c+u.matchCount,0);if(o===0)return io("PORTABLE_ROUTE_ANCHOR_MISSING","Portable route anchor was not found in the canonical page composition.");if(o!==1||r.length!==1)return io("PORTABLE_ROUTE_ANCHOR_AMBIGUOUS","Portable route anchor does not identify exactly one page-composition gap.");let i=Bs({routeId:e.routeId,entryFile:e.entryFile,currentDocumentVersion:e.documentVersion,expectedDocumentVersion:e.documentVersion,source:e.source,projection:n.projection,placementKey:r[0].placement.placementKey,component:e.component,invocation:e.invocation});if(!i.ok)return i;let s=e.source,a=i.plan.rewriteStep;if(a.kind==="insert-root-expression"){let c=js({source:s,locator:a.locator,expectedSourceHash:a.sourceHash,action:{kind:"insert",jsx:a.node.jsx,placement:a.placement,replaceOriginal:a.replaceOriginal}});if(!c.ok)return io("PORTABLE_ROUTE_PATCH_FAILED",c.diagnostic.message);s=c.source}else{let c=Vn({source:s,locator:a.parentLocator,node:a.node,placement:a.placement,...a.anchorLocator?{anchorLocator:a.anchorLocator}:{}});if(!c.ok)return io("PORTABLE_ROUTE_PATCH_FAILED",c.diagnostic.message);s=c.source}if(i.plan.serverParamsStep){let c=db({source:s,step:i.plan.serverParamsStep});if(!c.ok)return io("PORTABLE_ROUTE_PATCH_FAILED",c.diagnostic.message);s=c.source}let l=Kn({source:s,moduleSpecifier:i.plan.importStep.moduleSpecifier,imports:i.plan.importStep.imports});return l.ok?{ok:!0,plan:i.plan,patch:{kind:"portable-route-composition-patch",path:e.entryFile,expectedSourceHash:t.module.sourceHash,source:l.source}}:io("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message)}function cb(e,t){return(e.label===t?1:0)+e.children.reduce((n,r)=>n+cb(r,t),0)}function io(e,t,n=[]){return{ok:!1,error:{code:e,message:t,diagnostics:n}}}function DT(e){let t=VT(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 js(e){if(e.locator.root.kind!=="expression"||e.locator.path?.length)return Uo(e.source,"Root expression rewrite requires an exact expression locator.");let t=ds(e.source,"value");if(!t.ok)return Uo(e.source,t.diagnostic.message);let n=Be(t.ast,e.locator);if(!n.ok)return Uo(e.source,n.diagnostic.message);let r=n.match.path;if(!r.isExpression())return Uo(e.source,"Resolved value locator does not point to an expression.");let o=Ei(e.source,r.node.start??null,r.node.end??null);if(!o||o!==e.expectedSourceHash)return Uo(e.source,"Root expression hash no longer matches the current source.");if(e.action.kind==="remove")return r.replaceWith(ve.nullLiteral()),{ok:!0,source:Of(t.ast,{}).code};let i;try{i=Ii.parseExpression(e.action.jsx,{plugins:["jsx","typescript"]})}catch(s){return Uo(e.source,s instanceof Error?s.message:String(s))}return!ve.isJSXElement(i)&&!ve.isJSXFragment(i)?Uo(e.source,"Root expression rewrite requires a JSX insertion expression."):(e.action.kind==="replace"?r.replaceWith(i):r.replaceWith(MT(r.node,i,e.action.placement,e.action.replaceOriginal)),{ok:!0,source:Of(t.ast,{}).code})}function MT(e,t,n,r){if(ve.isNullLiteral(e)||r)return t;let o=ve.isJSXFragment(e)?[...e.children]:[ve.isJSXElement(e)?e:ve.jsxExpressionContainer(e)],s=n==="before"||n==="prepend"?[t,...o]:[...o,t];return ve.jsxFragment(ve.jsxOpeningFragment(),ve.jsxClosingFragment(),s)}function Uo(e,t){return{ok:!1,source:e,diagnostic:{message:t}}}function Bf(e){let t=ub(e);if(t)return{ok:!1,error:t};let n=e.projection,r=yb(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:[]}};if(jT(n,o)){let p=Lf(e);return p.ok?e.operation==="remove-node"&&!ib(n,o.placementUnitKey)?Fs("The last editable page unit cannot be deleted."):e.operation==="move-node"?Fs("A singleton root expression cannot be moved without a safe parent boundary."):{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:p.sourceHash,rewriteStep:{kind:e.operation==="remove-node"?"remove-root-expression":"replace-root-expression",locator:p.locator,sourceHash:p.sourceHash}}}:p.result}let s=Ms(o.sourceRange),a=ur(e.source,s);if(!a.ok||!a.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:a.ok===!1?a.diagnostic.message:"Route page composition source anchor could not be resolved.",diagnostics:a.ok?[]:[Ds(a.diagnostic)]}};if(Ei(e.source,a.match.node.start??null,a.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"){let p=Lf(e);return p.ok?ib(n,o.placementUnitKey)?{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:s}}}:Fs("The last editable page unit cannot be deleted."):p.result}if(e.operation==="replace-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:"replace-node",locator:s}}};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||!UT(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=jf(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 u=c.placement;if(u.placementUnitKey!==e.targetPlacement.placementUnitKey||u.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 d=u.containerSourceRange;if(!d||!u.containerSourceHash)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable container boundary.",diagnostics:[]}};let f=Ms(d),m=ur(e.source,f);if(!m.ok||!m.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:m.ok===!1?m.diagnostic.message:"Route page composition target container could not be resolved.",diagnostics:m.ok?[]:[Ds(m.diagnostic)]}};if(Ei(e.source,m.match.node.start??null,m.match.node.end??null)!==u.containerSourceHash)return ab("Route page composition target container hash no longer matches the current source.");if(u.relation==="before"||u.relation==="after"){let p=u.anchorSourceRange,h=u.anchorSourceHash;if(!p||!h)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable anchor boundary.",diagnostics:[]}};let x=Ms(p),b=ur(e.source,x);return!b.ok||!b.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:b.ok===!1?b.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:b.ok?[]:[Ds(b.diagnostic)]}}:Ei(e.source,b.match.node.start??null,b.match.node.end??null)!==h?ab("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:s,targetParentLocator:f,anchorLocator:x,placement:u.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:s,targetParentLocator:f,placement:u.relation}}}}function ib(e,t){for(let n of e.placementUnitByKey.values())if(n.placementUnitKey!==t&&n.members.length>0)return!0;return!1}function BT(e,t){let n=e.placementUnitByKey.get(t.placementUnitKey);return n&&e.container.kind!=="jsx-container"&&ol(n.sourceRange,e.mutationTarget.sourceRange)&&n.sourceHash===e.mutationTarget.sourceHash?!0:e.container.sourceRange===null&&(e.container.kind==="virtual-route-root"||e.container.kind==="starter-placeholder")}function jT(e,t){return e.container.kind!=="jsx-container"&&ol(t.sourceRange,e.mutationTarget.sourceRange)&&t.sourceHash===e.mutationTarget.sourceHash}function Lf(e){let t=e.projection.mutationTarget,n={kind:"value",root:{kind:"expression",sourceRange:t.sourceRange}},r=ur(e.source,n);return!r.ok||!r.match.node?{ok:!1,result:{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:r.ok===!1?r.diagnostic.message:"Route mutation target could not be resolved.",diagnostics:r.ok?[]:[Ds(r.diagnostic)]}}}:Ei(e.source,r.match.node.start??null,r.match.node.end??null)!==t.sourceHash?{ok:!1,result:lb("Route mutation target hash no longer matches the current source.")}:{ok:!0,locator:n,sourceHash:t.sourceHash}}function sb(e,t,n,r){let o=ur(e,t);return!o.ok||!o.match.node?{ok:!1,result:{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:o.ok===!1?o.diagnostic.message:`${r} could not be resolved.`,diagnostics:o.ok?[]:[Ds(o.diagnostic)]}}}:Ei(e,o.match.node.start??null,o.match.node.end??null)!==n?{ok:!1,result:lb(`${r} hash no longer matches the current source.`)}:{ok:!0}}function lb(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Fs(e){return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:e,diagnostics:[]}}}function ab(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Ds(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function ub(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&&!$T(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 $T(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function UT(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function VT(e,t){let n=ob.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=ob.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Ms(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function Ei(e,t,n){return t==null||n==null?null:`sha256:${LT("sha256").update(e.slice(t,n)).digest("hex")}`}function ol(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}function db(e){let t;try{t=Ii.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]})}catch(r){return{ok:!1,source:e.source,diagnostic:{message:r instanceof Error?r.message:String(r)}}}let n=KT(t,e.step);return n.ok?{ok:!0,source:Of(t,{}).code}:{ok:!1,source:e.source,diagnostic:{message:n.message}}}function KT(e,t){let n=gb(e);if(!n)return{ok:!1,message:"Route default function could not be resolved for searchParams wiring."};let r=Df(n.node.params[0]);if(t.action==="reuse")return n.node.params.length!==1||!r?{ok:!1,message:"Existing route searchParams binding no longer matches the plan."}:pb(r)!==t.identifier?{ok:!1,message:"Existing route searchParams binding no longer matches the plan."}:{ok:!0};let o=fb(n.node.params,t.typescript);if(!o.ok||o.action!=="add"||o.identifier!==t.identifier)return{ok:!1,message:"Route searchParams signature changed before the patch was applied."};if(n.node.params.length===0)return n.node.params.push(t.typescript?Ff():JT()),{ok:!0};let i=n.node.params[0],s=Df(i);return s?(XT(s,t.typescript),{ok:!0}):{ok:!1,message:"Route page parameter is not a supported object pattern."}}function JT(){return ve.objectPattern([ve.objectProperty(ve.identifier("searchParams"),ve.identifier("searchParams"),!1,!0)])}function Ff(){let t=Ii.parse("function __PortablePage({ searchParams }: { searchParams?: Promise<Record<string, string | string[] | undefined>> }) {}",{sourceType:"module",plugins:["typescript"]}).program.body[0];if(!ve.isFunctionDeclaration(t))throw new Error("Failed to construct the canonical searchParams type.");let n=t.params[0];if(!ve.isObjectPattern(n))throw new Error("Failed to construct the canonical searchParams pattern.");return ve.cloneNode(n,!0)}function XT(e,t){let n=ve.objectProperty(ve.identifier("searchParams"),ve.identifier("searchParams"),!1,!0),r=e.properties.findIndex(ve.isRestElement);if(r<0?e.properties.push(n):e.properties.splice(r,0,n),!t)return;let o=mb(e);if(!o){e.typeAnnotation=Ff().typeAnnotation;return}if(!ve.isTSTypeLiteral(o.typeAnnotation))return;let i=Ff().typeAnnotation;if(!i||!ve.isTSTypeAnnotation(i)||!ve.isTSTypeLiteral(i.typeAnnotation))return;let s=i.typeAnnotation.members[0];s&&!zT(o.typeAnnotation)&&o.typeAnnotation.members.push(ve.cloneNode(s,!0))}function zT(e){return e.members.some(t=>!("key"in t)||!t.key?!1:hb(t.key)==="searchParams")}function WT(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 HT(e){if(!e.invocation)return{ok:!0};let t=oo({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder});if(!t.ok)return rl(t.error.message);if(t.plan.requiresRouteParams)return rl("A captured native detail parameter has no independently proven target route binding.","UNSUPPORTED_ROUTE_PARAMS");let n;if(t.plan.requiresRouteSearchParams){let r=GT(e.source,e.entryFile);if(!r.ok)return rl(r.message,"UNSUPPORTED_ROUTE_PARAMS");if(n=r.step,r.step.identifier!==t.plan.searchParamsIdentifier&&(t=oo({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder,searchParamsIdentifier:r.step.identifier}),!t.ok))return rl(t.error.message)}return{ok:!0,invocation:t.plan,...n?{serverParamsStep:n}:{}}}function rl(e,t="PORTABLE_INVOCATION_INVALID"){return{ok:!1,error:{code:t,message:e,diagnostics:[]}}}function GT(e,t){let n;try{n=Ii.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch(s){return{ok:!1,message:s instanceof Error?s.message:String(s)}}if(n.program.directives.some(s=>s.value.value==="use client"))return{ok:!1,message:"Portable route searchParams wiring cannot cross a use client boundary."};let r=gb(n);if(!r)return{ok:!1,message:"Portable route searchParams wiring requires a default server function."};let o=/\.(?:ts|tsx)$/iu.test(t),i=fb(r.node.params,o);return i.ok?{ok:!0,step:{kind:"ensure-search-params",action:i.action,identifier:i.identifier,typescript:o}}:i}function fb(e,t){if(e.length===0)return{ok:!0,action:"add",identifier:"searchParams"};if(e.length!==1)return{ok:!1,message:"Portable route searchParams wiring rejects a default page with multiple parameters."};let n=Df(e[0]);if(!n)return{ok:!1,message:"Portable route searchParams wiring requires an object page parameter or an empty signature."};let r=pb(n);return r==="unsupported"?{ok:!1,message:"Portable route searchParams wiring cannot prove the existing searchParams binding."}:r?{ok:!0,action:"reuse",identifier:r}:t&&!YT(n)?{ok:!1,message:"Portable route searchParams wiring cannot safely extend this typed page signature."}:{ok:!0,action:"add",identifier:"searchParams"}}function Df(e){return!e||ve.isTSParameterProperty(e)?null:ve.isObjectPattern(e)?e:ve.isAssignmentPattern(e)&&ve.isObjectPattern(e.left)?e.left:null}function pb(e){for(let t of e.properties)if(!(!ve.isObjectProperty(t)||t.computed||hb(t.key)!=="searchParams"))return ve.isIdentifier(t.value)?t.value.name:ve.isAssignmentPattern(t.value)&&ve.isIdentifier(t.value.left)?t.value.left.name:"unsupported";return null}function YT(e){let t=mb(e);return t?ve.isTSTypeLiteral(t.typeAnnotation):e.properties.length===0}function mb(e){return e.typeAnnotation&&ve.isTSTypeAnnotation(e.typeAnnotation)?e.typeAnnotation:null}function gb(e){let t=null;return FT(e,{ExportDefaultDeclaration(n){if(t)return;let r=WT(n,n.get("declaration"));r&&(t=r)}}),t}function hb(e){return ve.isIdentifier(e)?e.name:ve.isStringLiteral(e)?e.value:null}var ZT=typeof $f=="function"?$f:$f.default;function Qn(e){if(!e.ast)return er(e,[Vt("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=iO(e.ast);if(!t)return er(e,[Vt("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=aO(t);if(!n.ok)return er(e,[n.diagnostic]);let r=n.expression;if(r.isIdentifier()){let o=lO(r,t);if(o.status==="resolved")r=o.expression;else if(o.status==="invalid")return er(e,[Vt("UNSUPPORTED_PAGE_SHAPE","Route default export local binding is not a supported JSX root")])}if(dO(r,t))return er(e,[Vt("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(r.isNullLiteral())return Vf(e,t,"virtual-route-root",r);if(uO(r)){let o=gO({input:e,source:e.source,expression:r});return Uf(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"},r)}if(r.isConditionalExpression())return er(e,[Vt("UNSUPPORTED_PAGE_SHAPE","Route conditional root contains an unsupported branch shape",{reason:"ambiguous-placement"})]);if(r.isJSXElement()&&!ht(r)&&!Us(r)){let o=Xf(r),i=Sb({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[o]});return Uf(e,t,i,{kind:"virtual-route-root",sourceKind:"jsx-element"},r)}if(r.isJSXElement()||r.isJSXFragment()){let o=pO(r);if(!o.ok)return er(e,[o.diagnostic]);let i=vi(o.path);if(i.unsupported)return er(e,[Vt("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);if(fO(e.source,r,i.members))return Vf(e,t,"starter-placeholder",r);let s=r.isJSXFragment()||ht(r);if(i.members.length===0&&s)return Vf(e,t,"virtual-route-root",r);let a=o.path===r&&s?"virtual-route-root":"jsx-container",l=o.path.isJSXFragment()?"jsx-fragment":"jsx-element",c=Sb({input:e,containerKind:a,sourceKind:l,source:e.source,containerPath:o.path,members:i.members});return Uf(e,t,c,{kind:a,sourceKind:l},r)}return er(e,[Vt("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")])}function jf(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Vt("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:Vt("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function yb(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Vt("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:Vt("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function Eb(e){return e.ok?qT(e.projection):QT(e.projection)}function qT(e){let t=new Map,n=[];for(let c of e.placements)c.members.length===0&&e.placements.length>1||c.members.length>0&&!c.anchorSourceRange||t.has(c.placementUnitKey)||t.set(c.placementUnitKey,c);let r=new Map,o=new Map;for(let[c,u]of t){let d=u.members.flatMap((p,h)=>Ib(e,u,p,h,e.container.placementKey)),f=d.filter(({member:p})=>p.isBusinessMember).map(({sourceMember:p})=>tO(c,p,u.independent)),m=d.length>0?d:[{sourceMember:{key:`source:${c}: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(c,m.map(({sourceMember:p})=>p)),o.set(c,f);let g=m[0]?.sourceMember.key??c;n.push({key:c,containerKey:g,businessMemberKeys:f.map(p=>p.key),isMultiMember:u.memberCount>1})}let i=[...r.values()].flat(),s=[...o.values()].flat(),a=i[0]?.key??null,l=e.placements.map(c=>({kind:"page-composition",placementKey:c.placementKey,documentVersion:e.documentVersion,composition:e.composition,placementUnitKey:c.placementUnitKey,relation:c.relation}));return{status:"supported",version:e.version,composition:e.composition,container:eO(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:l}}function QT(e){let t=e.diagnostics.map(nO);return{status:"unsupported",version:e.version,composition:e.composition,reason:rO(e.diagnostics),diagnostics:t}}function eO(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 Ib(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,l)=>Ib(e,t,a,l,i))]}function tO(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function nO(e){return{code:oO(e),message:e.message}}function rO(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 oO(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 iO(e){let t=null;return ZT(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=sO(o.path);i&&(t=i,n.stop())}}),t}function sO(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 aO(e){let t=e.get("body");if(!t.isBlockStatement()){let s=$s(t);return s?{ok:!0,expression:s}:{ok:!1,diagnostic:Vt("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")}}let n=t.get("body"),r=n.at(-1);if(!r)return{ok:!1,diagnostic:Vt("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")};if(!r.isReturnStatement())return{ok:!1,diagnostic:Vt("UNSUPPORTED_PAGE_SHAPE","Route default export must end with a direct terminal return",{reason:"terminal-return-required"})};for(let s of n.slice(0,-1)){if(s.isIfStatement()){if(!cO(s)&&!el(s))return{ok:!1,diagnostic:Vt("UNSUPPORTED_PAGE_SHAPE","Route guard return shape is not statically safe",{reason:"guard-shape"})};continue}if(vb(s)||kb(s))return{ok:!1,diagnostic:Vt("UNSUPPORTED_PAGE_SHAPE","Route default export contains unsupported control flow before the terminal return",{reason:"control-flow-return"})}}let o=r.get("argument"),i=$s(o);return i?{ok:!0,expression:i}:{ok:!1,diagnostic:Vt("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})}}function cO(e){if(e.node.alternate)return null;let t=e.get("consequent");if(t.isReturnStatement())return t;if(!t.isBlockStatement())return null;let n=t.get("body"),r=n.at(-1);if(!r?.isReturnStatement())return null;for(let o of n.slice(0,-1))if(vb(o)||kb(o))return null;return r}function vb(e){return e.isForStatement()||e.isForInStatement()||e.isForOfStatement()||e.isWhileStatement()||e.isDoWhileStatement()||e.isSwitchStatement()||e.isTryStatement()||e.isWithStatement()}function kb(e){let t=!1;return e.traverse({Function(n){n.skip()},ReturnStatement(){t=!0}}),t}function lO(e,t){let n=t.scope.getBinding(e.node.name);if(!n||n.scope.path.node!==t.node)return{status:"not-local"};if(!n.path.isVariableDeclarator())return{status:"not-local"};let r=n.path.parentPath;if(!r?.isVariableDeclaration()||r.node.kind!=="const")return{status:"invalid"};let o=n.path.get("init");if(Array.isArray(o)||!o.node)return{status:"invalid"};let i=$s(o);return!i||!i.isJSXElement()&&!i.isJSXFragment()?{status:"invalid"}:n.referencePaths.length!==1||n.referencePaths[0]?.node!==e.node||n.constantViolations.length!==0?{status:"invalid"}:{status:"resolved",expression:i}}function uO(e){return e.isConditionalExpression()?xb($s(e.get("consequent")))&&xb($s(e.get("alternate"))):!1}function xb(e){return!!(e&&(e.isJSXElement()||e.isJSXFragment()||e.isNullLiteral()))}function $s(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 dO(e,t){if(e.isIdentifier())return bb(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return bb(n.node.name,t)}return!1}function bb(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 fO(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&Jf(t)}function Jf(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(!Jf(t))return!1;continue}if(t.isJSXElement()&&!Jf(t))return!1}return!0}function pO(e){return{ok:!0,path:e}}function vi(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:zf(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:zn(r.node.loc),businessMemberCount:0,parentSourceRange:zn(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=vi(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=Us(o)?vi(o):null;n||=i?.unsupported??!1,t.push({...Xf(o,i?.members),sourceRange:zn(r.node.loc),parentSourceRange:zn(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:zf(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:zn(r.node.loc),businessMemberCount:1,parentSourceRange:zn(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&ht(r)){let o=vi(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=Us(r)?vi(r):null;n||=o?.unsupported??!1,t.push({...Xf(r,o?.members),parentSourceRange:zn(e.node.loc)})}}return{members:t,unsupported:n}}function Xf(e,t){let n=e.isJSXElement()&&Us(e)?t??vi(e).members:[],r=e.isJSXElement()&&!Us(e)&&!ht(e);return{memberKey:zf(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:zn(e.node.loc),businessMemberCount:r?1:_b(n),parentSourceRange:zn(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:mO(e)}}function Us(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name[0]===t.name[0]?.toLowerCase()}function mO(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 _b(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function il(e){return e.length===0?0:Math.max(1,_b(e))}function Sb(e){let t=zn(e.containerPath.node.loc),n=Hf(e.source,e.containerPath.node.start,e.containerPath.node.end),r=Wn(e.input,e.containerKind,e.sourceKind,t),o=Wn(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:il(e.members)<=1,memberCount:il(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function gO(e){let t=zn(e.expression.node.loc),n=Hf(e.source,e.expression.node.start,e.expression.node.end),r=Wn(e.input,"virtual-route-root","atomic-expression",t),o=Wn(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:Wn(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 Cb(e,t){let n=zn(t.node.loc),r=Hf(e.source,t.node.start,t.node.end);return!n||!r?null:{kind:"expression",documentVersion:e.version,sourceRange:n,sourceHash:r}}function Uf(e,t,n,r,o){let i=Cb(e,o);if(!i)return er(e,[Vt("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let s=n.containerSourceRange??n.sourceRange,a=hO(e,n,s),l=If(a),c={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Pb(t),container:{kind:r.kind,placementKey:n.placementKey,placementUnitKey:n.placementUnitKey,version:e.version,isEmptyPage:n.memberCount===0,sourceKind:r.sourceKind,sourceRange:s,sourceHash:n.sourceHash},placements:a,diagnostics:[],placementByKey:new Map,unitByKey:new Map,placementsByUnitKey:new Map,placementUnitByKey:new Map,mutationTarget:i};return Object.defineProperties(c,{placementByKey:{value:l.placementByKey,enumerable:!1},unitByKey:{value:l.unitByKey,enumerable:!1},placementsByUnitKey:{value:l.placementsByUnitKey,enumerable:!1},placementUnitByKey:{value:l.sourcePlacementByUnitKey,enumerable:!1}}),{ok:!0,projection:c}}function hO(e,t,n){if(t.members.length===0)return[t];let r=[],o=(c,u,d,f,m,g,p=n)=>({...t,placementKey:u,placementUnitKey:d,containerKey:t.placementKey,independent:il(g)<=1,memberCount:il(g),sourceRange:f,sourceHash:f?Kf(e.source,f):null,relation:c,containerSourceRange:p,containerSourceHash:p?Kf(e.source,p):null,anchorSourceRange:m,anchorSourceHash:m?Kf(e.source,m):null,members:g}),i=t.placementKey,s=t.members.map(c=>Wn(e,i,"placement-unit",c.sourceRange)),a=s[0]??t.placementUnitKey,l=s.at(-1)??t.placementUnitKey;r.push(o("prepend",Wn(e,i,"prepend",n),a,n,null,[]));for(let c of t.members){let u=c.parentSourceRange??n,d=Wn(e,i,"placement-unit",c.sourceRange);r.push(o("before",Wn(e,d,"before",c.sourceRange),d,c.sourceRange,c.sourceRange,[c],u)),r.push(o("after",Wn(e,d,"after",c.sourceRange),d,c.sourceRange,c.sourceRange,[c],u))}return r.push(o("append",i,l,n,null,[])),r}function Vf(e,t,n,r){let o=Cb(e,r);if(!o)return er(e,[Vt("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let i=Wn(e,n,"empty-container",void 0),s=Wn(e,n,"empty-unit",void 0),a={placementKey:i,placementUnitKey:s,version:e.version,containerKey:i,independent:!0,memberCount:0,sourceRange:null,sourceHash:null,relation:"append",containerSourceRange:null,containerSourceHash:null,anchorSourceRange:null,anchorSourceHash:null,members:[]},l=If([a]),c={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Pb(t),container:{kind:n,placementKey:i,placementUnitKey:s,version:e.version,isEmptyPage:!0,sourceKind:n==="starter-placeholder"?"starter-placeholder":"jsx-fragment",sourceRange:null,sourceHash:null},placements:[a],diagnostics:[],placementByKey:new Map,unitByKey:new Map,placementsByUnitKey:new Map,placementUnitByKey:new Map,mutationTarget:o};return Object.defineProperties(c,{placementByKey:{value:l.placementByKey,enumerable:!1},unitByKey:{value:l.unitByKey,enumerable:!1},placementsByUnitKey:{value:l.placementsByUnitKey,enumerable:!1},placementUnitByKey:{value:l.sourcePlacementByUnitKey,enumerable:!1}}),{ok:!0,projection:c}}function er(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 Vt(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function Wn(e,t,n,r){return Rb([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function zf(e,t,n){return Rb(["member",e,String(t??-1),String(n??-1)])}function Rb(e){return`pc_${Wf("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function Hf(e,t,n){return t==null||n==null?null:`sha256:${Wf("sha256").update(e.slice(t,n)).digest("hex")}`}function Kf(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:${Wf("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function zn(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function Pb(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}import{createHash as PO}from"node:crypto";import*as tr from"@babel/types";function Nb(e){if(!e.path.isIdentifier())return{kind:"not-alias"};let t=e.path.scope.getBinding(e.path.node.name);if(!t)return{kind:"unbound"};if(t.constantViolations.length>0)return{kind:"reassigned"};let n=t.path;if(!n.isVariableDeclarator())return{kind:"not-alias"};if(e.aliases.has(n.node)||e.aliases.size>=(e.maxDepth??32))return{kind:"guard"};let r=n.get("init");return Array.isArray(r)||!r.node?{kind:"not-alias"}:{kind:"initializer",initializer:r,aliases:new Set(e.aliases).add(n.node)}}import Gf from"@babel/traverse";import*as ki from"@babel/types";var xO=typeof Gf=="function"?Gf:Gf.default,bO=32;function Vo(e,t,n,r=new Set){if(r.has(e.ast)||r.size>=bO)return null;let o=new Set(r).add(e.ast),i;if(xO(e.ast,{Program(d){i=d,d.stop()}}),!i)return null;let s=(d,f)=>{let m=Hr(e.file,d,n),g=m?n.get(m):void 0;return g?Vo(g,f,n,o):null},a=d=>{let f=i.scope.getBinding(d);if(!f||f.constantViolations.length)return null;let m=f.path.parentPath;return m?.isImportDeclaration()?m.node.importKind==="type"?null:f.path.isImportDefaultSpecifier()?s(m.node.source.value,"default"):f.path.isImportSpecifier()&&f.path.node.importKind!=="type"?s(m.node.source.value,sl(f.path.node.imported)):null:f.path.isVariableDeclarator()?f.path.get("init"):f.path},l=[],c=[];for(let d of i.get("body"))if(d.isExportDefaultDeclaration()&&t==="default"){let f=d.get("declaration");l.push(f.isIdentifier()?a(f.node.name):f)}else if(d.isExportNamedDeclaration()&&d.node.exportKind!=="type"){let f=d.get("declaration");f.node&&Object.hasOwn(ki.getBindingIdentifiers(f.node),t)&&l.push(a(t));for(let m of d.node.specifiers)ki.isExportSpecifier(m)&&m.exportKind!=="type"&&sl(m.exported)===t&&l.push(d.node.source?s(d.node.source.value,sl(m.local)):a(sl(m.local)))}else d.isExportAllDeclaration()&&d.node.exportKind!=="type"&&t!=="default"&&c.push(d.node.source.value);if(l.length)return l.length===1?l[0]:null;let u=c.map(d=>s(d,t)).filter(d=>d!==null);return u.length===1?u[0]:null}function sl(e){return ki.isIdentifier(e)?e.name:e.value}import*as Fe from"@babel/types";var SO=32;function Nn(e,t=new Map,n=new Set){if(n.has(e.node)||n.size>=SO)return null;let r=new Set(n).add(e.node),o=t.get(e.node);if(o)return Vs(o,t,r);if(e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isTSSatisfiesExpression()||e.isParenthesizedExpression())return Nn(e.get("expression"),t,r);if(e.isIdentifier()){let i=e.scope.getBinding(e.node.name);return!i||i.constantViolations.length?null:Zf(i,t,r)}if(e.isMemberExpression()||e.isOptionalMemberExpression()){let i=An(e.node.property,e.node.computed),s=e.get("object"),a=Nn(s,t,r);return i!==null&&a?ll(a,i,t,r):null}if(e.isConditionalExpression())return Vs([e.get("consequent"),e.get("alternate")],t,r);if(e.isLogicalExpression())return Vs([e.get("left"),e.get("right")],t,r);if(e.isSequenceExpression()){let i=e.get("expressions").at(-1);return i?Nn(i,t,r):null}if(e.isCallExpression()&&Fe.isIdentifier(e.node.callee)){let i=e.scope.getBinding(e.node.callee.name);if(!i||!_i(i))return null;let s=i.path.isFunctionDeclaration()?i.path:i.path.isVariableDeclarator()?i.path.get("init"):null;if(!s||!(s.isFunctionDeclaration()||s.isFunctionExpression()||s.isArrowFunctionExpression())||s.node.async||s.node.generator)return null;let a=s,l=new Map(t),c=e.get("arguments");for(let[m,g]of a.get("params").entries()){if(!g.isIdentifier())return null;let p=c[m];if(!p?.isExpression())return null;let h=Nn(p,t,r);if(!h)return null;let x=g.scope.getBinding(g.node.name);if(!x)return null;l.set(x.identifier,h)}let u=a.get("body"),d=u.isBlockStatement()?u.get("body")[0]:u;if(!d)return null;let f=d.isReturnStatement()?d.get("argument"):d;return f.node?Nn(f,l,r):null}return[e]}function Zf(e,t=new Map,n=new Set){if(e.constantViolations.length)return null;let r=t.get(e.identifier);if(r)return Vs(r,t,n);if(!e.path.isVariableDeclarator())return null;let o=e.path.get("init");if(!o.node)return null;let i=Nn(o,t,n);if(!i)return null;let s=Yf(e.path.node.id,e.identifier.name);return s?s.reduce((a,l)=>a&&ll(a,l,t,n),i):null}function al(e){if(!e.params.every(n=>Fe.isIdentifier(n)||Fe.isAssignmentPattern(n)&&Fe.isIdentifier(n.left)&&Br(n.right)))return!1;if(!Fe.isBlockStatement(e.body))return Br(e.body);if(e.body.body.length!==1)return!1;let t=e.body.body[0];return Fe.isReturnStatement(t)&&!!t.argument&&Br(t.argument)}function _i(e){if(e.constantViolations.length>0)return!1;if(e.path.isFunctionDeclaration())return al(e.path.node);let t=e.path.isVariableDeclarator()?e.path:e.path.findParent(r=>r.isVariableDeclarator()),n=t?.isVariableDeclarator()?t.node.init:null;return Fe.isArrowFunctionExpression(n)||Fe.isFunctionExpression(n)?al(n):!1}function Br(e){let t=!0;return Fe.traverseFast(e,n=>{(Fe.isCallExpression(n)&&!cl(n)||Fe.isOptionalCallExpression(n)||Fe.isNewExpression(n)||Fe.isAwaitExpression(n)||Fe.isAssignmentExpression(n)||Fe.isUpdateExpression(n)||Fe.isUnaryExpression(n,{operator:"delete"})||Fe.isYieldExpression(n)||Fe.isTaggedTemplateExpression(n))&&(t=!1)}),t}function cl(e){return Fe.isIdentifier(e.callee,{name:"useTranslations"})&&e.arguments.length===1&&Fe.isStringLiteral(e.arguments[0])}function Vs(e,t,n){let r=[];for(let o of e){let i=Nn(o,t,n);if(!i)return null;r.push(...i)}return r.length?r:null}function ll(e,t,n,r=new Set){let o=[];for(let i of e)if(i.isObjectExpression()){let s=i.get("properties");if(s.some(l=>!l.isObjectProperty()||l.node.computed))return null;let a=s.filter(l=>l.isObjectProperty()&&An(l.node.key,!1)===t);if(a.length!==1||!a[0].isObjectProperty())return null;o.push(a[0].get("value"))}else if(i.isArrayExpression()&&/^(?:0|[1-9]\d*)$/u.test(t)){if(i.node.elements.some(a=>Fe.isSpreadElement(a)))return null;let s=i.get("elements")[Number(t)];if(!s?.node||s.isSpreadElement())return null;o.push(s)}else return null;return Vs(o,n,r)}function qf(e,t){let n=Nn(e,t);return!!(n?.length&&n.every(r=>Fe.isLiteral(r.node)&&!r.isRegExpLiteral()||r.isTemplateLiteral()||r.isBinaryExpression()||r.isUnaryExpression()))}function An(e,t){return!t&&Fe.isIdentifier(e)?e.name:Fe.isStringLiteral(e)||Fe.isNumericLiteral(e)?String(e.value):null}function Yf(e,t){if(Fe.isIdentifier(e))return e.name===t?[]:null;if(Fe.isObjectPattern(e))for(let n of e.properties){if(!Fe.isObjectProperty(n)||n.computed)continue;let r=An(n.key,!1),o=Yf(n.value,t);if(r!==null&&o)return[r,...o]}if(Fe.isArrayPattern(e))for(let[n,r]of e.elements.entries()){if(!r)continue;let o=Yf(r,t);if(o)return[String(n),...o]}return null}function Ab(e,t=new Set,n){return wb(e.get("callee"),t,n)}function wb(e,t,n){if(t.has(e.node)||t.size>=32)return{kind:"guard"};if(e.isIdentifier()){let r=e.scope.getBinding(e.node.name);if(!r)return{kind:"unknown"};if(t.has(r.path.node))return{kind:"guard"};let o=new Set(t).add(r.path.node),i=r.path.parentPath;if(i?.isImportDeclaration()&&n){let c=i.node.source.value;if(!(c.startsWith(".")||c.startsWith("@/")))return{kind:"unknown"};let u=r.path.scope.getProgramParent().path.node,d=[...n.values()].find(h=>h.ast.program===u),f=d&&Hr(d.file,c,n),m=f?n.get(f):void 0,g=r.path.isImportDefaultSpecifier()?"default":r.path.isImportSpecifier()&&r.path.node.importKind!=="type"?An(r.path.node.imported,!1):null,p=m&&g&&i.node.importKind!=="type"?Vo(m,g,n):null;return p?Ci(p,o,n):{kind:"guard"}}let s=r.path.isVariableDeclarator()?r.path.get("init"):r.path;if(!s.node)return{kind:"unknown"};let a=Ci(s,o,n);if(a.kind!=="sources")return a;let l=[...a.sources];for(let c of r.constantViolations){if(!c.isAssignmentExpression({operator:"="}))return{kind:"guard"};let u=Ci(c.get("right"),o,n);if(u.kind!=="sources")return{kind:"guard"};l.push(...u.sources)}return{kind:"sources",sources:l,aliases:a.aliases}}if(e.isMemberExpression()||e.isOptionalMemberExpression()){let r=An(e.node.property,e.node.computed),o=e.get("object"),i=Nn(o);if(!i)return{kind:"unknown"};let s=[],a=new Set(t).add(e.node);for(let l of i){if(!l.isObjectExpression())return{kind:"unknown"};if(r===null||l.node.properties.some(d=>d.type!=="ObjectProperty"))return{kind:"guard"};let c=l.get("properties").filter(d=>d.isObjectProperty()&&An(d.node.key,d.node.computed)===r);if(c.length!==1||!c[0].isObjectProperty())return{kind:"guard"};let u=Ci(c[0].get("value"),a,n);if(u.kind!=="sources")return{kind:"guard"};s.push(...u.sources),a=u.aliases}return{kind:"sources",sources:s,aliases:a}}return Ci(e,new Set(t).add(e.node),n)}function Ci(e,t,n){if(e.isIdentifier())return wb(e,t,n);if(e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isParenthesizedExpression())return Ci(e.get("expression"),t,n);if(!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression()))return{kind:"unknown"};let r=e,o=[];for(let s of r.get("params"))s.isAssignmentPattern()&&o.push(s.get("right")),s.traverse({AssignmentPattern(a){o.push(a.get("right"))}});let i=r.get("body");return i.isBlockStatement()?i.traverse({Function(s){s.skip()},ReturnStatement(s){let a=s.get("argument");a.node&&o.push(a),s.skip()}}):o.push(i),{kind:"sources",sources:o,aliases:t}}function dl(e,t){return JSON.stringify([t,e])}var IO=new Set;function Db(e,t){let n=new Map,r=[],o=new Map,i=(g,p)=>JSON.stringify([g,p.loc?.start.line,p.loc?.start.column,p.loc?.end.line,p.loc?.end.column]);for(let g of e.graph.elements.values()){let p=g.sourceRange;o.set(JSON.stringify([g.sourceFile,p.startLine,p.startColumn,p.endLine,p.endColumn]),g)}let s=g=>r.push({code:"render-occurrence-unproven",message:"A block render occurrence cannot be proven statically.",file:g}),a=(g,p)=>!Fb(p)&&[...t].some(h=>e.graph.elements.get(h)?.sourceFile===g);function l(g,p,h,x,b,S=IO){if(g.isIdentifier())return x&&ul(g,x)?x.children.some(v=>l(v.path,v.file,h,v.substitution,b,S)):u({path:g,file:p,active:h,substitution:x,unknownIsRelevant:b,aliases:S});if(g.isCallExpression()||g.isOptionalCallExpression()){let v=g,N=Ab(v,S,e.parsedModules);return N.kind==="guard"||N.kind==="sources"&&N.sources.some(I=>l(I,[...e.parsedModules.values()].find(A=>A.ast.program===I.scope.getProgramParent().path.node)?.file??p,h,x,b,N.aliases))?!0:v.get("arguments").some(I=>l(I,p,h,x,b,S))||N.kind==="unknown"&&b}if(g.isJSXElement()){if(ht(g))return g.get("children").some(L=>l(L,p,h,x,b,S));let v=o.get(i(p,g.node));if(v){if(t.has(v.identity.key))return!0;if(v.boundaryKind==="component-boundary"&&!v.isPublicUiComponent){let L=e.parsedModules.get(v.sourceFile);if(!L)return!1;let X=pr({module:L,componentName:v.tag,callSourceRange:v.sourceRange,...v.importedFrom?{imported:{file:v.importedFrom,module:e.parsedModules.get(v.importedFrom),exportName:v.exportName??v.tag,parsedModules:e.parsedModules}}:{}});return X.ok?X.metadataOnly?!1:c(X,g,v.sourceFile,h,x,S):X.diagnostic.code==="component-external-module-opaque"?Ks(g).some(j=>l(j,p,h,x,!1,S)):a(L.file,X.diagnostic.code)}return g.get("children").some(L=>l(L,p,h,x,b,S))}let N=g.node.openingElement.name;if(!tr.isJSXIdentifier(N))return!1;if(/^[a-z]/.test(N.name))return g.get("children").some(L=>l(L,p,h,x,b,S));let I=e.parsedModules.get(p),A=g.node.loc;if(!I||!A)return!1;let C=RO({path:g,file:p,componentName:N.name,parsedModules:e.parsedModules}),O=pr({module:I,componentName:N.name,callSourceRange:{startLine:A.start.line,startColumn:A.start.column,endLine:A.end.line,endColumn:A.end.column},...C?{imported:C}:{}});return O.ok?O.metadataOnly?!1:c(O,g,p,h,x,S):O.diagnostic.code==="component-external-module-opaque"?Ks(g).some(L=>l(L,p,h,x,!1,S)):a(I.file,O.diagnostic.code)}if(g.isJSXFragment())return g.get("children").some(v=>l(v,p,h,x,b,S));if(g.isJSXExpressionContainer()||g.isParenthesizedExpression()||g.isTSAsExpression()||g.isTSNonNullExpression()||g.isTSTypeAssertion())return l(g.get("expression"),p,h,x,b,S);let E=!1;return g.traverse({"CallExpression|OptionalCallExpression"(v){l(v,p,h,x,b,S)&&(E=!0),v.skip(),E&&v.stop()},ReferencedIdentifier(v){l(v,p,h,x,b,S)&&(E=!0),E&&v.stop()},JSXElement(v){l(v,p,h,x,b,S)&&(E=!0),v.skip(),E&&v.stop()},JSXFragment(v){l(v,p,h,x,b,S)&&(E=!0),v.skip(),E&&v.stop()}}),E?!0:b&&!Ko(g)}function c(g,p,h,x,b,S){let E=`${g.sourceFile}#${g.componentName}`;if(x.has(E))return!1;let v=new Set(x).add(E);return g.returnAlternatives?.some(N=>Ks(N).some(I=>l(I,g.sourceFile,v,null,!1,S)))||g.roots.some(N=>l(N,g.sourceFile,v,null,!1,S))?!0:Tb(g.roots).kind==="none"?!1:Lb(p).some(N=>l(N,h,v,b,!0,S))}function u(g){if(!g.path.isIdentifier())return g.unknownIsRelevant;let p=Nb({path:g.path,aliases:g.aliases});return p.kind==="unbound"?g.unknownIsRelevant&&g.path.node.name!=="undefined":p.kind==="guard"||p.kind==="reassigned"?!0:p.kind==="not-alias"?g.unknownIsRelevant:l(p.initializer,g.file,g.active,g.substitution,g.unknownIsRelevant,p.aliases)?!0:Qf(p.initializer).isIdentifier()?!1:g.unknownIsRelevant&&!Ko(p.initializer)}let d=(g,p,h,x,b,S)=>{if(g.isIdentifier()){l(g,p,x,S,!1)&&s(p);return}if(g.isJSXElement()){if(ht(g)){for(let N of g.get("children"))d(N,p,h,x,b,S);return}let E=o.get(i(p,g.node));if(!E)return;let v=E.identity.key;if(t.has(v)){b||s(p);let N=n.get(v)??[];N.push(dl(v,h)),n.set(v,N)}if(E.boundaryKind==="component-boundary"&&!E.isPublicUiComponent){let N=e.parsedModules.get(E.sourceFile);if(!N)return;let I=pr({module:N,componentName:E.tag,callSourceRange:E.sourceRange,...E.importedFrom?{imported:{file:E.importedFrom,module:e.parsedModules.get(E.importedFrom),exportName:E.exportName??E.tag,parsedModules:e.parsedModules}}:{}});if(!I.ok){if(I.diagnostic.code==="component-external-module-opaque"){Ks(g).some(j=>l(j,p,x,S,!1))&&s(p);return}[...t].some(j=>e.graph.elements.get(j)?.sourceFile===N.file)&&!Fb(I.diagnostic.code)&&s(N.file);return}if(I.metadataOnly)return;let A=`${I.sourceFile}#${I.componentName}`;if(x.has(A)){s(N.file);return}let C=new Set(x).add(A);I.returnAlternatives?.some(j=>Ks(j).some(J=>l(J,I.sourceFile,C,S,!1)))&&s(I.sourceFile);let O=Tb(I.roots),L=CO(g);if(O.kind==="unproven"||O.kind==="supported"&&L){for(let j of Lb(g))if(l(j,p,C,S,!0)){s(p);break}}let X=O.kind==="supported"&&!L?{bindingNode:O.bindingNode,children:g.get("children").map(j=>({path:j,file:p,substitution:S}))}:null;for(let j of I.roots)d(j,I.sourceFile,[...h,v],C,b,X);return}for(let N of g.get("children"))d(N,p,h,x,b,S);return}if(g.isJSXFragment()){for(let E of g.get("children"))d(E,p,h,x,b,S);return}if(g.isJSXExpressionContainer()){let E=g.get("expression");if(S&&!E.isJSXEmptyExpression()){let v=Qf(E);if(ul(v,S)){for(let N of S.children)d(N.path,N.file,h,x,b,N.substitution);return}if(vO(E,S))for(let N of S.children)d(N.path,N.file,h,x,!1,N.substitution)}d(E,p,h,x,b,S);return}if(g.isParenthesizedExpression()||g.isTSAsExpression()||g.isTSNonNullExpression()||g.isTSTypeAssertion()){d(g.get("expression"),p,h,x,b,S);return}l(g,p,x,S,!1)&&s(p),g.traverse({JSXElement(E){d(E,p,h,x,!1,S),E.skip()}})},f=e.parsedModules.get(e.entryFile);if(!f)return{occurrences:n,diagnostics:r};let m=Pn({module:f,exportName:"default",allowNonRenderingGuards:!0});if(!m.ok)return s(e.entryFile),{occurrences:n,diagnostics:r};for(let g of m.roots)d(g,f.file,[],new Set,!0,null);return{occurrences:n,diagnostics:r}}function Qf(e){let t=e;for(;t.isParenthesizedExpression()||t.isTSAsExpression()||t.isTSNonNullExpression()||t.isTSTypeAssertion();)t=t.get("expression");return t}function Ko(e){let t=Qf(e);return t.isStringLiteral()||t.isNumericLiteral()||t.isBooleanLiteral()||t.isNullLiteral()||t.isBigIntLiteral()||t.isJSXElement()||t.isJSXFragment()?!0:t.isIdentifier()?t.node.name==="undefined"&&!t.scope.getBinding("undefined"):t.isTemplateLiteral()?t.node.expressions.length===0:t.isArrayExpression()?t.get("elements").every(n=>!n.node||Ko(n)):t.isConditionalExpression()?Ko(t.get("consequent"))&&Ko(t.get("alternate")):t.isLogicalExpression()?Ko(t.get("left"))&&Ko(t.get("right")):!1}function ul(e,t){if(!e.isIdentifier())return!1;let n=e.scope.getBinding(e.node.name);return!!(n&&(n.path.node===t.bindingNode||n.identifier===t.bindingNode))}function vO(e,t){if(ul(e,t))return!0;let n=!1;return e.traverse({Identifier(r){ul(r,t)&&(n=!0,r.stop())}}),n}function Tb(e){let t=e[0]?.getFunctionParent();if(!t)return{kind:"none"};let n=t.get("params")[0];return n?n.isAssignmentPattern()?Ob(n.get("left"),!0):Ob(n,!1):{kind:"none"}}function Ob(e,t){if(e.isObjectPattern()){let n=[],r=!1;for(let i of e.get("properties")){if(i.isObjectProperty()){if(i.node.computed){mr(i.get("value"))&&(r=!0);continue}let s=i.node.key;(tr.isIdentifier(s)?s.name:tr.isStringLiteral(s)?s.value:null)==="children"&&n.push(i);continue}i.isRestElement()&&mr(i.get("argument"))&&(r=!0)}if(n.length>1)return r||n.some(i=>mr(i.get("value")))?{kind:"unproven"}:{kind:"none"};if(n.length===0)return r?{kind:"unproven"}:{kind:"none"};if(r)return{kind:"unproven"};let o=n[0].get("value");if(o.isIdentifier()){let i=o.scope.getBinding(o.node.name);return!i||i.path.node!==o.node&&i.identifier!==o.node?{kind:"unproven"}:i.constantViolations.length>0?{kind:"unproven"}:i.referencePaths.length===0?{kind:"none"}:i.referencePaths.every(s=>kO(s))?t?{kind:"unproven"}:{kind:"supported",bindingNode:o.node}:{kind:"unproven"}}return mr(o)?{kind:"unproven"}:{kind:"none"}}if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return!n||n.referencePaths.length===0?{kind:"none"}:n.referencePaths.every(r=>_O(r))?{kind:"none"}:{kind:"unproven"}}return mr(e)?{kind:"unproven"}:{kind:"none"}}function mr(e){if(e.isIdentifier()){let t=e.scope.getBinding(e.node.name);return!!(t&&t.referencePaths.length>0)}return e.isAssignmentPattern()?mr(e.get("left")):e.isRestElement()?mr(e.get("argument")):e.isObjectPattern()?e.get("properties").some(t=>t.isObjectProperty()?mr(t.get("value")):t.isRestElement()?mr(t.get("argument")):!0):e.isArrayPattern()?e.get("elements").some(t=>t.node?mr(t):!1):!0}function kO(e){let t=e.parentPath;for(;t&&(t.isParenthesizedExpression()||t.isTSAsExpression()||t.isTSNonNullExpression()||t.isTSTypeAssertion());)t=t.parentPath;if(!t||!t.isJSXExpressionContainer())return!1;let n=t.parentPath;return!!(n&&(n.isJSXElement()||n.isJSXFragment()))}function _O(e){let t=e.parentPath;if(!t||!t.isMemberExpression()&&!t.isOptionalMemberExpression()||t.node.object!==e.node)return!1;let n=t.node.property;return t.node.computed?tr.isStringLiteral(n)&&n.value!=="children":tr.isIdentifier(n)&&n.name!=="children"}function CO(e){for(let t of e.get("openingElement").get("attributes")){if(t.isJSXAttribute()){let n=t.node.name;if(tr.isJSXIdentifier(n)&&n.name==="children")return!0;continue}if(t.isJSXSpreadAttribute()&&Mb(t.get("argument")))return!0}return!1}function Lb(e){let t=e.get("children").map(n=>n);for(let n of e.get("openingElement").get("attributes")){if(n.isJSXAttribute()){let r=n.node.name;if(!tr.isJSXIdentifier(r)||r.name!=="children")continue;let o=n.get("value");o&&!Array.isArray(o)&&t.push(o);continue}if(n.isJSXSpreadAttribute()){let r=n.get("argument");Mb(r)&&t.push(r)}}return t}function Ks(e){let t=e.get("children").map(n=>n);for(let n of e.get("openingElement").get("attributes"))if(n.isJSXSpreadAttribute())t.push(n.get("argument"));else if(n.isJSXAttribute()){let r=n.get("value");r&&!Array.isArray(r)&&t.push(r)}return t}function Mb(e){if(e.isJSXElement()||e.isJSXFragment())return!0;let t=!1;return e.traverse({JSXElement(n){t=!0,n.stop()},JSXFragment(n){t=!0,n.stop()}}),t}function RO(e){let t=e.path.scope.getBinding(e.componentName);if(!t)return;let n=t.path;if(!n.isImportDefaultSpecifier()&&!n.isImportSpecifier())return;let r=n.parentPath;if(!r?.isImportDeclaration())return;let o=Hr(e.file,r.node.source.value,e.parsedModules);if(!o)return;let i=n.isImportDefaultSpecifier()?"default":tr.isIdentifier(n.node.imported)?n.node.imported.name:n.node.imported.value;return{file:o,module:e.parsedModules.get(o),exportName:i,parsedModules:e.parsedModules}}function Fb(e){return e==="component-export-unresolved"||e==="component-local-binding-unresolved"}function $b(e){let t=[],n=[];return Ub(e.element,e,[],e.ownerNode,e.element,[],new Set,t,n),{roots:t,diagnostics:n}}function Ub(e,t,n,r,o,i,s,a,l,c=[]){if(c.length>1&&(e.boundaryKind!=="component-boundary"||e.isPublicUiComponent)){l.push({code:"conditional-component-root-unproven",message:"Conditional returns require one proven local component definition.",file:e.sourceFile});return}if(e.boundaryKind!=="component-boundary"||e.isPublicUiComponent){if(_f(e.tag))return;a.push({element:e,callChain:n,ownerNode:r,ownerMember:o,ownerCallChain:i});return}let u=t.parsedModules.get(e.sourceFile);if(!u){l.push({code:"component-module-unavailable",message:"The component source module is unavailable in the parsed graph.",file:e.sourceFile,structuralPath:e.identity.structuralPath});return}let d=pr({module:u,componentName:e.tag,callSourceRange:e.sourceRange,...e.importedFrom?{imported:{file:e.importedFrom,module:t.parsedModules.get(e.importedFrom),exportName:e.exportName??e.tag,parsedModules:t.parsedModules}}:{}});if(!d.ok){l.push({...d.diagnostic,structuralPath:e.identity.structuralPath});return}if(d.metadataOnly)return;let f=d.sourceFile,m=`${f}#${d.componentName}`;if(s.has(m)){l.push({code:"component-call-cycle",message:"A component call cycle cannot be expanded safely.",file:e.sourceFile,structuralPath:e.identity.structuralPath});return}if(d.roots.length===0){l.push({code:"component-root-empty",message:"A component call has no statically addressable JSX root.",file:f,structuralPath:e.identity.structuralPath});return}let g=[...n,{sourceFile:e.sourceFile,component:e.tag,exportName:e.exportName??e.tag,callLocator:{key:e.identity.key,structuralPath:e.identity.structuralPath,sourceRange:e.sourceRange},...c.length>1?{alternativeLocators:c.map(b=>({key:b.identity.key,structuralPath:b.identity.structuralPath,sourceRange:b.sourceRange}))}:{}}],p=d.roots.length>1?{kind:"component-definition",key:m}:r,h=new Set(s);h.add(m);let x=[];for(let b of d.returnAlternatives??[]){let S=jb(b),E=S?Bb(t.graph,f,S):[];if(E.length!==1){l.push({code:"conditional-component-root-unproven",message:"A conditional call site is absent or ambiguous in the source graph.",file:f});return}x.push(E[0])}for(let b of d.roots){let S=jb(b),E=S?Bb(t.graph,f,S):[];if(E.length!==1){l.push({code:E.length?"component-root-ambiguous":"component-root-unresolved",message:"The component root could not be matched to one source graph node.",file:f,structuralPath:e.identity.structuralPath});continue}Ub(E[0],t,g,p,d.roots.length>1?E[0]:o,d.roots.length>1?g:i,h,a,l,x)}}function Bb(e,t,n){return(e.fileIndex.get(t)??[]).map(r=>e.elements.get(r)).filter(r=>!!r&&r.sourceRange.startLine===n.startLine&&r.sourceRange.startColumn===n.startColumn&&r.sourceRange.endLine===n.endLine&&r.sourceRange.endColumn===n.endColumn)}function jb(e){let t=e.node.loc;return t?{startLine:t.start.line,startColumn:t.start.column,endLine:t.end.line,endColumn:t.end.column}:null}function fl(e){let t=[],n=[];if(e.projection.entryFile!==e.entryFile||!Kb(e.projection.composition,e.composition)||e.graph.composition&&!Kb(e.graph.composition,e.composition))return{roots:[],diagnostics:[Js("composition-mismatch",e.entryFile)]};if(!e.parsedModules.has(e.entryFile))return{roots:[],diagnostics:[Js("entry-module-unavailable",e.entryFile)]};for(let i of e.graph.diagnostics??[])t.push({code:`source-graph-${i.code}`,message:i.message,file:i.path});let r=e.projection.placements.filter(i=>i.relation==="before").flatMap(i=>i.members);for(let i of r){if(i.kind==="text")continue;if(i.kind!=="jsx-element"||!i.sourceRange){t.push(Js("route-member-not-addressable",e.entryFile));continue}let s=AO(e.graph,e.entryFile,i.sourceRange);if(s.length!==1){t.push(Js(s.length?"route-root-ambiguous":"route-root-unresolved",e.entryFile));continue}let a=s[0],l=$b({element:a,graph:e.graph,parsedModules:e.parsedModules,ownerNode:{kind:"route-member",key:a.parentKey??`${e.entryFile}#${e.projection.container.placementKey}`}});t.push(...l.diagnostics);for(let c of l.roots){let u=c.ownerMember;n.push({...c,parentStructuralPath:u.parentKey?e.graph.elements.get(u.parentKey)?.identity.structuralPath??null:null})}}let o=Db(e,new Set(n.map(i=>i.element.identity.key)));t.push(...o.diagnostics);for(let i of n){let s=i.element.identity.key,a=dl(s,i.callChain.map(l=>l.callLocator.key));o.occurrences.get(s)?.filter(l=>l===a).length!==1&&t.push(Js("render-occurrence-unproven",i.element.sourceFile))}return{roots:NO(n,e.composition,o.occurrences),diagnostics:t}}function NO(e,t,n){let r=e.map(i=>{let s=i.element,a=n.get(s.identity.key)??[],l=i.callChain.map(c=>c.callLocator.key);return{rootKey:PO("sha256").update(JSON.stringify([t,l,s.identity.key])).digest("hex"),rootRef:{key:s.identity.key,...a.length>1?{instanceIndex:a.indexOf(dl(s.identity.key,l)),instanceCount:a.length}:{}},sourceFile:s.sourceFile,structuralPath:s.identity.structuralPath,sourceRange:s.sourceRange,callChain:i.callChain,ownerNode:i.ownerNode,ownerMemberKey:i.ownerMember.identity.key,ownerCallKeys:i.ownerCallChain.map(c=>c.callLocator.key),parentStructuralPath:i.parentStructuralPath,siblingRootKeys:[],siblingIndex:0}}),o=new Map;for(let i of r){let s=Vb(i);o.set(s,[...o.get(s)??[],i])}return r.map(i=>{let s=o.get(Vb(i))??[i];return{...i,siblingIndex:s.indexOf(i),siblingRootKeys:s.filter(a=>a!==i).map(a=>a.rootKey)}})}function Vb(e){return JSON.stringify([e.ownerNode.kind,e.ownerNode.key,e.parentStructuralPath,e.ownerCallKeys])}function AO(e,t,n){return(e.fileIndex.get(t)??[]).map(r=>e.elements.get(r)).filter(r=>!!r&&r.sourceRange.startLine===n.startLine&&r.sourceRange.startColumn===n.startColumn&&r.sourceRange.endLine===n.endLine&&r.sourceRange.endColumn===n.endColumn)}function Kb(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function Js(e,t){return{code:e,message:"Page block roots could not be proven from the current source graph.",file:t}}import{SiteEditPageBlockDirectorySchema as wO,SiteEditPageBlockDescriptorSchema as TO,SiteEditSourcePathSchema as Xb}from"@vcp-dev/platform-shared/contracts";function pl(e){let t=new Map;for(let[n,r]of e.elements){let o=/^[A-Z]/.test(r.tag),i={file:r.sourceFile,componentName:r.componentName,isProxy:o},s=r.boundaryKind,a=[];r.isOpaque&&a.push({kind:"opaque-region",reason:`Component '${r.tag}' is opaque: internal structure not editable`}),o&&!r.isOpaque&&a.push({kind:"component-boundary",reason:`Component '${r.tag}' boundary: editing requires source file access`});let l={key:n,writeTarget:i,boundaryKind:s,parentKey:r.parentKey,childKeys:[...r.childKeys],constraints:a};t.set(n,l)}for(let n of e.regions){let r=n.kind==="repeat-region"?"repeat-region":n.kind==="conditional-region"?"conditional-region":n.kind==="opaque-region"?"opaque-region":"component-boundary",o=n.kind==="repeat-region"?"Node is inside a repeat region: operations affect the template, not individual instances":n.kind==="conditional-region"?"Node is inside a conditional region: visibility depends on runtime condition":`Node is inside a ${n.kind}`;for(let i of n.childKeys){let s=t.get(i);s&&s.constraints.push({kind:r,reason:o}),Jb(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function Jb(e,t,n,r,o){let i=o.elements.get(e);if(i)for(let s of i.childKeys){let a=r.get(s);a&&!a.constraints.some(l=>l.kind===t)&&(a.constraints.push({kind:t,reason:n}),Jb(s,t,n,r,o))}}function Xs(e){let t=[],n={...e.graph,composition:e.composition},r=_c(pl(n),n),o=[],i=new Map;for(let a of e.roots){let l=e.graph.elements.get(a.rootRef.key),c=e.graph.elements.get(a.ownerMemberKey),u=e.parsedModules.get(a.sourceFile),d=FO(a,e.graph),f=d?e.parsedModules.get(d):void 0;if(!l||!c||c.sourceFile!==d||!u||!Xb.safeParse(a.sourceFile).success||!d||!f||!Xb.safeParse(d).success){t.push(ep("root-source-unavailable",a.sourceFile));continue}if(i.has(a.rootKey)){t.push(ep("block-key-ambiguous",a.sourceFile));continue}let m=$e(u.source),g=TO.safeParse({blockKey:a.rootKey,rootRef:a.rootRef,definitionKey:a.rootRef.key,source:{file:a.sourceFile,structuralPath:a.structuralPath,contentHash:m},owner:a.ownerNode,siblingBlockKeys:a.siblingRootKeys,placementUnitKey:DO(a,e),capabilities:OO(l,r),...LO(l,r)});if(!g.success){t.push(ep("page-block-descriptor-invalid",a.sourceFile));continue}let p=g.data;o.push(p),i.set(a.rootKey,{blockKey:a.rootKey,composition:e.composition,documentVersion:e.documentVersion,descriptor:p,root:a,ownerFile:d,ownerSourceHash:$e(f.source),ownerSourceContent:f.source,sourceHash:m,sourceContent:u.source,ownerLocator:{kind:"jsx-element",file:c.sourceFile,sourceRange:c.sourceRange,structuralPath:c.identity.structuralPath,componentName:c.componentName},rootLocator:{kind:"jsx-element",file:l.sourceFile,sourceRange:l.sourceRange,structuralPath:l.identity.structuralPath,componentName:l.componentName}})}let s=wO.safeParse(o);return s.success?{composition:e.composition,documentVersion:e.documentVersion,descriptors:s.data,bindings:i,diagnostics:t}:{composition:e.composition,documentVersion:e.documentVersion,descriptors:[],bindings:new Map,diagnostics:[...t,{code:"page-block-directory-invalid",message:"The proven page block directory failed its strict contract."}]}}function OO(e,t){let n=t.get(e.identity.key),r=e.parentKey?t.get(e.parentKey):void 0;return{insert:r?r.canInsertChild:!0,replace:!!(n?.canRemove&&(!r||r.canInsertChild)),move:n?.canMove??!1,remove:n?.canRemove??!1,save:!0}}function LO(e,t){let n=t.get(e.identity.key),r={},o=n?.constraints[0]?.message??"The existing Engine capability check denied this operation.";return(!n||!n.canRemove)&&(r.replace={code:n?"CAPABILITY_DENIED":"CAPABILITY_UNAVAILABLE",reason:o},r.remove={code:n?"CAPABILITY_DENIED":"CAPABILITY_UNAVAILABLE",reason:o}),(!n||!n.canMove)&&(r.move={code:n?"CAPABILITY_DENIED":"CAPABILITY_UNAVAILABLE",reason:o}),Object.keys(r).length?{unavailableReasons:r}:{}}function FO(e,t){if(e.ownerNode.kind==="component-definition"){let n=e.ownerNode.key.lastIndexOf("#");return n>0?e.ownerNode.key.slice(0,n):null}return t.elements.get(e.ownerMemberKey)?.sourceFile??null}function DO(e,t){let n=e.callChain[0]?.callLocator.key??e.rootRef.key,r=t.graph.elements.get(n);if(r)return t.projection.placements.find(o=>o.members.some(i=>i.sourceRange!==null&&i.sourceRange.startLine===r.sourceRange.startLine&&i.sourceRange.startColumn===r.sourceRange.startColumn&&i.sourceRange.endLine===r.sourceRange.endLine&&i.sourceRange.endColumn===r.sourceRange.endColumn))?.placementUnitKey}function ep(e,t){return{code:e,message:"The page block source binding could not be proven.",file:t}}import tp from"@babel/traverse";import{BlockRenderRefSchema as MO,SiteEditPageBlockPositionSchema as BO,SiteEditPageBlockTargetSchema as jO}from"@vcp-dev/platform-shared/contracts";var $O=typeof tp=="function"?tp:tp.default;function Ri(e,t,n,r){if(!jO.safeParse(t).success)return xn("INVALID_PARAMS","Invalid page block target.");if(n!==e.documentVersion)return xn("VERSION_STALE","The page block index is stale.");if(t.composition.routeId!==e.composition.routeId||t.composition.templateId!==e.composition.effectiveTemplateId)return xn("INVALID_TARGET","The target belongs to another composition.");let o=e.bindings.get(t.blockKey);return o?r&&(!MO.safeParse(r).success||r.key!==o.descriptor.rootRef.key||r.instanceIndex!==o.descriptor.rootRef.instanceIndex||r.instanceCount!==o.descriptor.rootRef.instanceCount)?xn("INVALID_TARGET","The render occurrence does not match the target."):{ok:!0,binding:o}:xn("INVALID_TARGET","The page block target was not found.")}function ml(e,t){if(!BO.safeParse(t).success)return xn("INVALID_PARAMS","Invalid page block boundary.");if(t.documentVersion!==e.documentVersion)return xn("VERSION_STALE","The page block boundary is stale.");if(t.composition.routeId!==e.composition.routeId||t.composition.templateId!==e.composition.effectiveTemplateId)return xn("INVALID_TARGET","The boundary belongs to another composition.");let n=e.bindings.get(t.anchorBlockKey);if(!n)return xn("INVALID_TARGET","The boundary anchor was not found.");let r=[n,...n.descriptor.siblingBlockKeys.map(u=>e.bindings.get(u))];if(r.some(u=>!u))return xn("INVALID_TARGET","A verified sibling binding is unavailable.");let o=r.sort((u,d)=>u.root.siblingIndex-d.root.siblingIndex),i=zb(n);if(!i)return xn("INVALID_TARGET","The operation owner call site is unavailable.");let s=Wb(n,i);if(s===void 0)return xn("INVALID_TARGET","The boundary parent source range is ambiguous.");for(let u of o)if(u.ownerFile!==n.ownerFile||u.root.ownerNode.kind!==n.root.ownerNode.kind||u.root.ownerNode.key!==n.root.ownerNode.key||!UO(Wb(u,zb(u)),s))return xn("INVALID_TARGET","Siblings do not share one proven source boundary.");let a=o.findIndex(u=>u.blockKey===n.blockKey);if(a<0)return xn("INVALID_TARGET","Anchor order is ambiguous.");let l=t.placement==="before"?o[a-1]:n,c=t.placement==="before"?n:o[a+1];return{ok:!0,boundary:{ownerFile:n.ownerFile,parentLocator:s,anchorLocator:i,sourceHash:n.ownerSourceHash,placement:t.placement,beforeBlockKey:l?.blockKey??null,afterBlockKey:c?.blockKey??null}}}function zb(e){return e.ownerLocator.file===e.ownerFile?e.ownerLocator:null}function Wb(e,t){if(!t)return;let n=Oe(t.file,e.ownerSourceContent);if(!n.ok)return;let r=[];if($O(n.module.ast,{JSXElement(i){let s=np(i.node);s&&s.startLine===t.sourceRange.startLine&&s.startColumn===t.sourceRange.startColumn&&s.endLine===t.sourceRange.endLine&&s.endColumn===t.sourceRange.endColumn&&r.push(i)}}),r.length!==1)return;let o=r[0].parentPath;for(;o;){if(o.isJSXFragment()){let i=np(o.node);return i?{kind:"jsx-fragment",file:t.file,sourceRange:i}:void 0}if(o.isJSXElement()){let i=np(o.node),s=t.structuralPath?.lastIndexOf("/")??-1,a=s<0?void 0:t.structuralPath.slice(0,s);return i?{kind:"jsx-element",file:t.file,sourceRange:i,...a?{structuralPath:a}:{},...t.componentName?{componentName:t.componentName}:{}}:void 0}o=o.parentPath}return null}function UO(e,t){return e===void 0||t===void 0||e===null||t===null?e===t:e.file===t.file&&e.kind===t.kind&&e.sourceRange.startLine===t.sourceRange.startLine&&e.sourceRange.startColumn===t.sourceRange.startColumn&&e.sourceRange.endLine===t.sourceRange.endLine&&e.sourceRange.endColumn===t.sourceRange.endColumn}function np(e){let t=e.loc;return t?{startLine:t.start.line,startColumn:t.start.column,endLine:t.end.line,endColumn:t.end.column}:null}function xn(e,t){return{ok:!1,code:e,message:t}}import Yb from"node:path";import{SiteEditSourcePathSchema as qO}from"@vcp-dev/platform-shared/contracts";import gl from"node:path";import rp from"@babel/traverse";import*as so from"@babel/types";import{SiteEditSourcePathSchema as Hb,SiteEditPageBlockTargetSchema as VO}from"@vcp-dev/platform-shared/contracts";var KO=typeof rp=="function"?rp:rp.default;function Gb(e){if(!e.operationId)return wt("INVALID_PARAMS","An operationId is required.");if(!VO.safeParse(e.target).success)return wt("INVALID_PARAMS","Invalid page block target.");if(e.target.kind!=="page-block"||e.target.blockKey!==e.binding.blockKey||e.target.composition.routeId!==e.binding.composition.routeId||e.target.composition.templateId!==e.binding.composition.effectiveTemplateId)return wt("INVALID_TARGET","The request target does not match its resolved block binding.");if(e.documentVersion!==e.binding.documentVersion)return wt("VERSION_STALE","The resolved block belongs to a stale document version.");if(e.operation==="move-node"||e.operation==="remove-node")return wt("UNSUPPORTED_OPERATION","Move and remove are planned by the structural operation task.");if(!e.node)return wt("INVALID_PARAMS","An insert/replacement node is required.");let t=e.operation==="insert-child"?e.boundary?.ownerFile:e.binding.ownerFile;if(!t||!Hb.safeParse(t).success)return wt("INVALID_TARGET","The exact owner source file is unavailable.");let n=e.files.get(t);if(n===void 0)return wt("INVALID_TARGET","The exact owner source is absent from the fixed file map.");if($e(n)!==e.binding.ownerSourceHash)return wt("VERSION_STALE","The owner source hash changed after target resolution.");let r=e.files.get(e.binding.descriptor.source.file);if(r===void 0||$e(r)!==e.binding.descriptor.source.contentHash)return wt("VERSION_STALE","The block source hash changed after target resolution.");let o;if(e.operation==="insert-child"){if(o=e.boundary,!o||o.ownerFile!==e.binding.ownerFile||o.sourceHash!==e.binding.ownerSourceHash||o.anchorLocator.file!==t||o.parentLocator?.file!==t)return wt("INVALID_TARGET","The insertion boundary is not in the resolved source owner.");let c=o.placement==="before"?o.afterBlockKey:o.beforeBlockKey;if(c!==e.binding.blockKey&&!e.binding.descriptor.siblingBlockKeys.includes(c??""))return wt("INVALID_TARGET","The boundary anchor is not a verified same-owner sibling.");if(!o.parentLocator)return wt("UNSUPPORTED_OPERATION","A root without a source parent has no safe sibling insertion boundary.")}let i=XO(e.node,t,n,e.files);if(!i.ok)return i;let s=e.operation==="replace-node"?di({source:n,locator:JO(e.binding),node:{jsx:i.value.jsx}}):Vn({source:n,locator:op(o.parentLocator),anchorLocator:op(o.anchorLocator),placement:o.placement,node:{jsx:i.value.jsx}});if(!s.ok)return wt("UNSUPPORTED_OPERATION",s.diagnostic.message);let a=s.source;if(i.value.import){let c=Kn({source:a,moduleSpecifier:i.value.import.moduleSpecifier,imports:i.value.import.specifiers});if(!c.ok)return wt("UNSUPPORTED_OPERATION",c.diagnostic.message);a=c.source}return{ok:!0,plan:{operationId:e.operationId,kind:"source-edit",target:e.target,documentVersion:e.documentVersion,conflictPolicy:"compare-and-swap",edits:[{operation:"upsert",file:t,content:a,baseContentHash:e.binding.ownerSourceHash}]}}}function JO(e){return op(e.ownerLocator)}function op(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e.sourceRange,...e.structuralPath&&e.componentName?{expectedIdentity:{file:e.file,component:e.componentName,structuralPath:e.structuralPath}}:{}}}function XO(e,t,n,r){if(e.kind==="native-tag")return/^[A-Za-z][A-Za-z0-9:_-]*$/.test(e.tag)?{ok:!0,value:{jsx:e.text===void 0?`<${e.tag} />`:`<${e.tag}>{${JSON.stringify(e.text)}}</${e.tag}>`}}:wt("INVALID_PARAMS","The native JSX tag is invalid.");if(!e.component)return wt("UNSUPPORTED_OPERATION","A materialized component entry is resolved by the materialization task.");let o=zO(t,e.component.source,r);if(!o)return wt("INVALID_TARGET","The component source is not in the safe fixed file map.");let i=Oe(t,n);if(!i.ok)return wt("UNSUPPORTED_OPERATION",i.diagnostic.message);let s=WO(i.module.ast.program.body,e.component.source,e.component.exportName),a=s??GO(YO(e.component.exportName,o),HO(i.module.ast)),l=ZO(e.props??{});if(!l.ok)return l;let c=`<${a}${l.value?` ${l.value}`:""} />`;if(s)return{ok:!0,value:{jsx:c}};let u=e.component.exportName==="default"?{kind:"default",local:a}:{kind:"named",imported:e.component.exportName,...a!==e.component.exportName?{local:a}:{}};return{ok:!0,value:{jsx:c,import:{moduleSpecifier:e.component.source,specifiers:[u]}}}}function zO(e,t,n){let r=t.startsWith("@/")?t.slice(2):t.startsWith("./")||t.startsWith("../")?gl.posix.normalize(gl.posix.join(gl.posix.dirname(e),t)):null;return r?(/\.(?:tsx?|jsx?)$/i.test(r)?[r]:[".tsx",".ts",".jsx",".js"].map(i=>`${r}${i}`).concat([".tsx",".ts",".jsx",".js"].map(i=>`${r}/index${i}`))).find(i=>Hb.safeParse(i).success&&n.has(i))??null:null}function WO(e,t,n){for(let r of e)if(!(!so.isImportDeclaration(r)||r.source.value!==t)){for(let o of r.specifiers)if(n==="default"&&so.isImportDefaultSpecifier(o)||n!=="default"&&so.isImportSpecifier(o)&&(so.isIdentifier(o.imported)?o.imported.name:o.imported.value)===n)return o.local.name}return null}function HO(e){let t=new Set;return KO(e,{Program(n){n.scope.crawl(),t=new Set(Object.keys(n.scope.bindings)),n.stop()}}),t}function GO(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function YO(e,t){let r=(e==="default"?gl.posix.basename(t).replace(/\.(?:tsx?|jsx?)$/i,""):e).replace(/[^A-Za-z0-9_$]/g,""),o=r?r[0].toUpperCase()+r.slice(1):"Component";return/^[A-Za-z_$][\w$]*$/.test(o)?o:"Component"}function ZO(e){let t=[];for(let[n,r]of Object.entries(e)){if(!/^[A-Za-z_][A-Za-z0-9_:.-]*$/.test(n))return wt("INVALID_PARAMS","A component prop name is invalid.");let o;try{o=JSON.stringify(r)}catch{return wt("INVALID_PARAMS","Component props must be JSON serializable.")}if(o===void 0)return wt("INVALID_PARAMS","Component props must be JSON serializable.");t.push(`${n}={${o}}`)}return{ok:!0,value:t.join(" ")}}function wt(e,t){return{ok:!1,code:e,message:t}}function Zb(e){if(e.materialization.kind!=="static-prefab-materialization"||!e.materialization.files.some(i=>i.path===e.materialization.entry.path))return hl("MATERIALIZATION_ENTRY_INVALID","The materialization entry must identify one controlled create-only file.");if(!e.materialization.files.every(i=>i.kind==="create-only"&&qO.safeParse(i.path).success))return hl("MATERIALIZATION_PATH_INVALID","Every materialized output must remain a safe create-only Snapshot source.");if(e.materialization.files.some(i=>e.files.has(i.path)))return hl("MATERIALIZATION_INSTANCE_CONFLICT","A generated materialization path already exists in the fixed Snapshot source map.");let t=e.operation==="insert-child"?e.boundary?.ownerFile:e.binding.ownerFile;if(!t||!e.files.has(t))return hl("INVALID_TARGET","The exact page-block owner source is missing from the fixed file map.");let n=eL(t,e.materialization.entry.path),r=Gb({operationId:e.operationId,documentVersion:e.documentVersion,target:e.target,binding:e.binding,...e.boundary?{boundary:e.boundary}:{},operation:e.operation,node:{kind:"component-call",component:{source:n,exportName:e.materialization.entry.export.kind==="default"?"default":e.materialization.entry.export.name},props:{}},files:QO(e.files,e.materialization)});if(!r.ok)return r;let o=e.materialization.files.map(i=>({operation:"create-only",file:i.path,content:i.content}));return{ok:!0,plan:{...r.plan,target:e.target,edits:[...o,...r.plan.edits]}}}function QO(e,t){let n=new Map(e);for(let r of t.files)n.set(r.path,r.content);return n}function eL(e,t){let n=Yb.posix.relative(Yb.posix.dirname(e),t);return n.startsWith(".")?n:`./${n}`}function hl(e,t){return{ok:!1,code:e,message:t}}import{PageTemplateIdSchema as dL}from"@vcp-dev/platform-shared/contracts";import CW from"node:fs";import PW from"node:path";var tL=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function zs(e){let t=e.map(r=>uL(r.path)),n=nL(t);return n?t.filter(r=>oL(n,r)).map(r=>({routeId:iL(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function ip(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=lL(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function nL(e){return e.some(r=>r.startsWith("app/")&&!rL(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function rL(e){return/^(?:src\/)?app\/(?:_vcp|\.vcp)/.test(e)}function oL(e,t){if(!t.startsWith(`${e}/`))return!1;let n=t.slice(t.lastIndexOf("/")+1);return tL.test(n)?t.slice(e.length+1,-n.length-1).split("/").filter(Boolean).every(r=>!r.startsWith("_")&&!r.startsWith(".")):!1}function iL(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(aL).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function sL(e){return e.startsWith("(")&&e.endsWith(")")}function aL(e){return!e||e.startsWith("@")||e.startsWith("_")||sL(e)?null:cL(e)}function cL(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function lL(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function uL(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var Ws=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function bn(e,t={}){throw new Ws("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Invalid page-template source (${e}): ${t.path??t.routeId??t.templateId??""}`,{reason:e,...t})}function sp(e){return dL.safeParse(e).success||bn("invalid-template-id",{templateId:e}),Buffer.from(e,"utf8").toString("base64url")}function qb(e){/^[A-Za-z0-9_-]{1,255}$/.test(e)||bn("invalid-template-key",{path:e});let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.from(e,"base64url"))}catch{return bn("invalid-template-key",{path:e})}return sp(t)!==e&&bn("noncanonical-template-key",{path:e}),t}function fL(e){let t=ip(e),n=t.slice(1).split("/");return(!e.startsWith("/")||/[?#\\%\u0000-\u001f]/.test(e)||t.startsWith("/.vcp")||t!=="/"&&n.some(r=>!r||r==="."||r===".."||r.startsWith("@")||r.startsWith("_")||r.startsWith("(")||pL(r)&&!Qb(r)))&&bn("invalid-public-route",{routeId:e}),t}function pL(e){return e.includes("[")||e.includes("]")}function Qb(e){return/^\[\[\.\.\.[^\[\]]+\]\]$|^\[[^\[\]]+\]$/.test(e)}function eS(e){return e.some(Qb)}function tS(e,t,n="app"){n!=="app"&&n!=="src/app"&&bn("invalid-app-root");let r=fL(e),o=sp(t),i=eS(r.slice(1).split("/")),s=i?`${n}/.vcp/page-templates/${o}${r}`:`${n}/.vcp/page-templates${r==="/"?"":r}`,a=i?`${s}/page.tsx`:`${s}/${o}/page.tsx`;return(Buffer.byteLength(a,"utf8")>4095||a.split("/").some(l=>Buffer.byteLength(l,"utf8")>255))&&bn("path-too-long",{path:a}),{appRoot:n,routeRoot:s,templateKey:o,templateEntryFile:a}}function nS(e){return/^(?:src\/)?app\/\.vcp\/page-templates\//.test(e)}function rS(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===".")&&bn("invalid-file-path",{path:i}),n.has(i)&&bn("duplicate-file-path",{path:i}),n.set(i,o)}return n}function xl(e){let t=rS(e.files),n=zs([...t.keys()].map(i=>({path:i}))),r=new Map;for(let i of n){if(r.has(i.routeId))throw new Ws("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(!nS(i))continue;let s=/^(app|src\/app)\/\.vcp\/page-templates\/(.+)\/page\.tsx$/.exec(i);s||bn("candidate-must-be-single-page",{path:i});let a=s[1],l=s[2].split("/"),c=eS(l),u=c?l[0]:l.pop(),d=c?l.slice(1):l,f=qb(u),m=d.length?`/${d.join("/")}`:"/";tS(m,f,a).templateEntryFile!==i&&bn("candidate-path-mismatch",{path:i,routeId:m});let p=r.get(m);(!p||!p.startsWith(`${a}/`))&&bn("canonical-entry-missing",{path:i,routeId:m}),o.push({routeId:m,templateId:f,entryFile:i,canonicalEntryFile:p,appRoot:a})}return o.sort((i,s)=>yl(i.routeId,s.routeId)||yl(i.templateId,s.templateId))}function bl(e){let t=rS(e.files),n=xl({files:t}),r=zs([...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)=>yl(o.context.routeId,i.context.routeId)||(o.context.effectiveTemplateId===void 0?-1:i.context.effectiveTemplateId===void 0?1:yl(o.context.effectiveTemplateId,i.context.effectiveTemplateId)))}function mL(e){let t=ip(e.selector.routeId),n=bl({files:e.files}),r=n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===void 0);(!r||r.entryFile!==e.canonicalEntryFile)&&bn("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||bn("template-selection-not-found",{routeId:t,templateId:e.selector.templateId}),{...o,mode:e.selector.templateId===void 0?"direct":"candidate",effectiveEntryFile:o.entryFile}}function yl(e,t){return e<t?-1:e>t?1:0}import{HOME_PAGE_URL_PATH as DL}from"@vcp-dev/platform-shared/contracts";import{parse as AL}from"@babel/parser";import gL from"@babel/traverse";var ap=gL,hL=typeof ap=="function"?ap:ap.default;function cp(e,t){let n=e.referencePaths.filter(r=>!r.findParent(o=>o.isJSXClosingElement()));return n.length===1&&n[0]?.node===t}function oS(e){let t=new Map,n=new Set,r=new Set,o=new Map,i=new Set;return hL(e,{Program(s){for(let a of Object.values(s.scope.bindings))a.constant&&(a.kind==="const"||a.kind==="hoisted")&&i.add(a.path.node)},ReferencedIdentifier(s){let a=s.scope.getBinding(s.node.name);if(!a?.constant||a.kind!=="const"||!a.path.isVariableDeclarator()||!cp(a,s.node))return;let l=a.path.node.init;l&&t.set(s.node,l)},JSXOpeningElement(s){let a=s.get("name");for(;a.isJSXMemberExpression();)a=a.get("object");if(!a.isJSXIdentifier())return;let l=a.scope.getBinding(a.node.name);if(!l?.constant)return;let c=l.path.parentPath;if((l.path.isImportSpecifier()||l.path.isImportDefaultSpecifier()||l.path.isImportNamespaceSpecifier())&&c?.isImportDeclaration()&&c.node.importKind!=="type"&&(!l.path.isImportSpecifier()||l.path.node.importKind!=="type")){n.add(s.node),cp(l,a.node)&&r.add(s.node);return}if(!(!s.get("name").isJSXIdentifier()||!cp(l,a.node))){if(l.path.isFunctionDeclaration())o.set(s.node,l.path.node);else if(l.kind==="const"&&l.path.isVariableDeclarator()){let u=l.path.get("init");(u.isArrowFunctionExpression()||u.isFunctionExpression())&&o.set(s.node,u.node)}}}}),{valueAliases:t,importedOpenings:n,uniqueImportedOpenings:r,localComponentOpenings:o,stableDeclarations:i}}import{parse as qW}from"@babel/parser";import{FormBlockIdSchema as eH,FormSpecV1Schema as tH}from"@vcp-dev/platform-shared/contracts";import{posix as jW}from"node:path";import yL from"@babel/traverse";var lp=yL,UW=typeof lp=="function"?lp:lp.default,VW=Symbol("unknown-member");import{parse as XW}from"@babel/parser";import{FormBlockIdSchema as WW}from"@vcp-dev/platform-shared/contracts";var Hs="components/site/generated/forms",oH=`${Hs}/vcp-form-runtime.tsx`,Sl="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",iH=new RegExp(`^${Hs}/form-(${Sl})\\.spec\\.ts$`),sH=new RegExp(`^${Hs}/form-(${Sl})\\.tsx$`),aH=new RegExp(`^@/${Hs}/form-(${Sl})$`),cH=new RegExp(`(?:^|/)${Hs}/form-(${Sl})(?:\\.tsx?)?$`);var lH=Symbol("invalid-literal");import{createHash as fH}from"node:crypto";import{posix as mH}from"node:path";import{parse as hH}from"@babel/parser";import{FormSpecV1Schema as xH}from"@vcp-dev/platform-shared/contracts";var bH=Symbol("dynamic");import{parse as xL}from"@babel/parser";function El(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.type=="string"):[]}var bL=/^(?:src\/)?app\/(.*)page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function iS(e){let t=bL.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 SL(e){let t=e;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function sS(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function EL(e){let t=e;for(;t&&(t.type==="TSAsExpression"||t.type==="TSSatisfiesExpression"||t.type==="ParenthesizedExpression");)t=t.expression??null;return t}function up(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(up);if(t?.type==="ObjectExpression"){let n={};for(let r of El(t.properties)){if(r.type!=="ObjectProperty"||r.computed)throw new Error("dynamic object property");let o=sS(r.key);if(!o)throw new Error("unsupported object key");n[o]=up(r.value)}return n}throw new Error(`unsupported static value: ${t?.type??"unknown"}`)}function dp(e,t){let n=[],r=iS(t);if(r===null)return{found:!1,seo:null,diagnostics:n};let o;try{o=xL(e,{sourceType:"module",plugins:["typescript","jsx"]})}catch(c){return n.push({code:"page-seo.parse-failed",message:c instanceof Error?c.message:String(c)}),{found:!1,seo:null,diagnostics:n}}let i;for(let c of El(o.program.body)){let u=c.type==="ExportNamedDeclaration"?c.declaration:c;if(u?.type==="VariableDeclaration")for(let d of El(u.declarations)){let f=d.id;f?.type==="Identifier"&&f.name==="PAGE_SEO"&&(i=d.init)}}if(i==null)return{found:!1,seo:null,diagnostics:n};let s=EL(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 c of El(s.properties)){if(c.type!=="ObjectProperty"||c.computed)continue;let u=sS(c.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=SL(c.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=up(c.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 l=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`}),l=a.path),{found:!0,seo:{path:l,...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 IL}from"@babel/parser";var aS=["page","anchor","external","email","phone","group","file"],vL=["link","cta"],lS=["description","badge","iconKey"],fp=["label","targetType","href","role","openInNewTab","nofollow","children",...lS],kL=new Set(fp);function Ys(e){return Array.isArray(e)?e:[]}function Gs(e){let t=e;return t?.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function _L(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function cS(e){let t=e;return t?.type==="BooleanLiteral"&&typeof t.value=="boolean"?t.value:void 0}function pp(e){let t=[],n;try{n=IL(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 Ys(n.program.body)){let s=i.type==="ExportNamedDeclaration"?i.declaration:i;if(s?.type==="VariableDeclaration")for(let a of Ys(s.declarations)){let l=a.id;l?.type==="Identifier"&&l.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 Ys(r.elements).forEach((i,s)=>{let a=uS(i,`NAV_ITEMS[${s}]`,t);a&&o.push(a)}),{items:o,diagnostics:t}}function uS(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 c of Ys(e.properties)){if(c.type!=="ObjectProperty"||c.computed)continue;let u=_L(c.key);u&&(r[u]=c.value)}let o=Gs(r.label),i=Gs(r.targetType);if(!o)return n.push({severity:"fatal",path:`${t}.label`,message:"label must be a static string"}),null;if(!i||!aS.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${aS.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 c of lS){if(r[c]===void 0)continue;let u=Gs(r[c]);u!==void 0?s[c]=u:n.push({severity:"warning",path:`${t}.${c}`,message:`${c} 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 c of Object.keys(r))kL.has(c)||c==="group"||c==="icon"||n.push({severity:"warning",code:"unknown-field",path:`${t}.${c}`,message:`unsupported field \`${c}\` ignored; NAV_ITEMS only carries ${fp.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 c=[];Ys(r.children.elements).forEach((u,d)=>{let f=uS(u,`${t}.children[${d}]`,n);f&&c.push(f)}),s.children=c}if(i==="group")return s.children?s:(n.push({severity:"fatal",path:`${t}.children`,message:"group item requires children"}),null);let a=Gs(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 l=Gs(r.role);if(l!==void 0&&(vL.includes(l)?s.role=l:n.push({severity:"warning",path:`${t}.role`,message:"role ignored: not link/cta"})),r.openInNewTab!==void 0){let c=cS(r.openInNewTab);c!==void 0?s.openInNewTab=c:n.push({severity:"warning",path:`${t}.openInNewTab`,message:"openInNewTab ignored: not a static boolean"})}if(r.nofollow!==void 0){let c=cS(r.nofollow);c!==void 0?s.nofollow=c:n.push({severity:"warning",path:`${t}.nofollow`,message:"nofollow ignored: not a static boolean"})}return s}import{parse as CL}from"@babel/parser";function Zs(e){return Array.isArray(e)?e:[]}function dS(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function RL(e){let t;try{t=CL(e,{sourceType:"module",plugins:["typescript","jsx"],tokens:!0})}catch{return{status:"unsupported"}}let n=[];for(let o of Zs(t.program.body)){let i=o.type==="ExportNamedDeclaration"?o.declaration:o;if(i?.type==="VariableDeclaration")for(let s of Zs(i.declarations)){let a=s.id;a?.type==="Identifier"&&a.name==="NAV_ITEMS"&&n.push(s)}}if(n.length===0)return{status:"navigation_not_found"};if(n.length!==1)return{status:"unsupported"};let r=dS(n[0]?.init);return!r||typeof r.start!="number"||typeof r.end!="number"?{status:"unsupported"}:{status:"ok",array:r,start:r.start,end:r.end}}function mp(e,t){let n=fS(t);if(!n)return{status:"unsupported",source:e};let r=RL(e);if(r.status!=="ok")return{status:r.status,source:e};let o=r.array;if(pp(e).diagnostics.some(({severity:c})=>c==="fatal"))return{status:"unsupported",source:e};let s=[],a=c=>{let u=Zs(c.elements);for(let[d,f]of u.entries()){if(NL(f,n)){let g=u[d+1],p=u[d-1],h=f.start,x=f.end;if(typeof h!="number"||typeof x!="number")continue;if(g&&typeof g.start=="number")s.push({start:h,end:g.start});else if(p&&typeof p.end=="number")s.push({start:p.end,end:x});else{let b=/^\s*,/.exec(e.slice(x));s.push({start:h,end:b?x+b[0].length:x})}continue}let m=PL(f);m&&a(m)}};if(a(o),s.length===0)return{status:"not_found",source:e};let l=e;for(let c of s.sort((u,d)=>d.start-u.start))l=l.slice(0,c.start)+l.slice(c.end);return{status:"removed",source:l,removedCount:s.length}}function PL(e){if(e.type==="ObjectExpression")for(let t of Zs(e.properties)){if(t.type!=="ObjectProperty")continue;let n=t.key;if((n?.name??n?.value)==="children")return dS(t.value)}}function fS(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function NL(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of Zs(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"&&fS(n??"")===t}import{estimateNavLabelWidth as NH}from"@vcp-dev/platform-shared/contracts";import{parse as TH}from"@babel/parser";function gr(e,t){let n,r;try{n=AL(e,{sourceType:"module",sourceFilename:t.filePath,plugins:["jsx","typescript"]}),t.requireStaticMount&&(r=oS(n))}catch(j){let J=j.loc;return{form_codes:[],components:[],uncertain_components:[],rendered_component_openings:[],renders_native_form:!1,diagnostics:[{code:"rendered-module.parse-failed",message:j instanceof Error?j.message:"Rendered module failed Babel parsing.",file_path:t.filePath??"",line:J?.line??1}]}}let o=n.program,i=cn(o?.body),s=new Map,a=new Map,l=new Map,c=new Map,u=j=>{if(j?.type==="FunctionDeclaration"){let J=j.id;J?.type==="Identifier"&&typeof J.name=="string"&&(!r||r.stableDeclarations.has(j))&&a.set(J.name,j);return}if(j?.type==="VariableDeclaration")for(let J of cn(j.declarations)){if(r&&!r.stableDeclarations.has(J))continue;let Y=J.id,$=J.init;Y?.type==="Identifier"&&typeof Y.name=="string"&&$&&(ao($)?a.set(Y.name,$):$.type==="Identifier"&&typeof $.name=="string"&&l.set(Y.name,$.name))}};for(let j of i){if(j.type==="ImportDeclaration"){let J=j.source?.value;if(typeof J!="string")continue;for(let Y of cn(j.specifiers)){let $=Y.local;if(!($?.type!=="Identifier"||typeof $.name!="string")){if(Y.type==="ImportDefaultSpecifier")s.set($.name,{source:J,exportName:"default"});else if(Y.type==="ImportNamespaceSpecifier")s.set($.name,{source:J,exportName:"*"});else if(Y.type==="ImportSpecifier"){let ce=Y.imported,ue=ce?.type==="Identifier"&&typeof ce.name=="string"?ce.name:ce?.type==="StringLiteral"&&typeof ce.value=="string"?ce.value:"";ue&&s.set($.name,{source:J,exportName:ue})}}}continue}j.type==="ExportNamedDeclaration"?u(j.declaration):u(j)}for(let j of i){if(j.type==="ExportDefaultDeclaration"){let $=j.declaration;$&&ao($)?c.set("default",$):$?.type==="Identifier"&&typeof $.name=="string"&&c.set("default",$.name);continue}if(j.type!=="ExportNamedDeclaration")continue;let J=j.declaration;if(J?.type==="FunctionDeclaration"){let $=J.id;$?.type==="Identifier"&&typeof $.name=="string"&&c.set($.name,$.name)}else if(J?.type==="VariableDeclaration")for(let $ of cn(J.declarations)){let ce=$.id;ce?.type==="Identifier"&&typeof ce.name=="string"&&c.set(ce.name,ce.name)}let Y=j.source?.value;for(let $ of cn(j.specifiers)){let ce=hS($.local),ue=hS($.exported);if(!(!ce||!ue))if(typeof Y=="string"){let Ee=`#re-export:${ue}`;s.set(Ee,{source:Y,exportName:ce}),c.set(ue,Ee)}else c.set(ue,ce)}}let d=new Set,f=[],m=new Set,g=[],p=new Set,h=[],x=new Map,b=!1,S=new Set,E=new Map,v=new Map,N=!1,I=[],A=new Map,C=new Map,O=(j,J="rendered")=>{let Y=mS(j,s);if(!Y)return!1;let $=`${Y.source}\0${Y.exportName}`;if(J==="uncertain")return!m.has($)&&!p.has($)&&(p.add($),g.push({source:Y.source,export_name:Y.exportName})),!0;if(!m.has($)&&(m.add($),f.push({source:Y.source,export_name:Y.exportName}),p.delete($))){let ce=g.findIndex(ue=>ue.source===Y.source&&ue.export_name===Y.exportName);ce>=0&&g.splice(ce,1)}return!0},L=(j,J="rendered",Y=[])=>{let $=`${J}\0${hp(Y)}`,ce=A.get(j)??new Set,ue=C.get(j)??new Set;if(ce.has($)||ue.has(J))return;ce.add($),A.set(j,ce),ue.add(J),C.set(j,ue);let Ee=new Map(a),We=new Map,pt=[],fn=(U,Ce=!1)=>{if(qs(U)){if(!Ce&&ao(U)){if(U.type==="FunctionDeclaration"){let De=U.id;De?.type==="Identifier"&&typeof De.name=="string"&&Ee.set(De.name,U)}return}if(U.type==="VariableDeclarator"){let De=U.id,ie=U.init;De?.type==="Identifier"&&typeof De.name=="string"&&ie&&(ao(ie)?Ee.set(De.name,ie):We.set(De.name,ie))}else if(U.type==="ReturnStatement"){let De=U.argument;De&&pt.push(De)}if(U.type==="CallExpression"){let De=U.callee;if(De?.type==="Import"&&I.push({code:"rendered-module.dynamic-import",message:"Rendered component graph must use static imports.",file_path:t.filePath??"",line:U.loc?.start.line??1}),Qs(De)==="cms.forms.getConfig"){let ie=cn(U.arguments)[0];ie?.type==="StringLiteral"&&typeof ie.value=="string"&&ie.value.trim()?J==="rendered"?d.add(ie.value.trim()):I.push({code:"rendered-module.unresolved-export",message:"Unable to prove whether a CMS form inside a JSX prop is rendered.",file_path:t.filePath??"",line:U.loc?.start.line??1}):I.push({code:"rendered-module.dynamic-form-code",message:"Rendered cms.forms.getConfig() requires a non-empty string literal.",file_path:t.filePath??"",line:U.loc?.start.line??1})}}for(let[De,ie]of Object.entries(U))if(De!=="loc")if(Array.isArray(ie))for(let Xe of ie)fn(Xe);else fn(ie)}};fn(j,!0),t.requireStaticMount&&j.body?.type==="BlockStatement"&&pt.length>0&&(cn(j.body?.body).filter(Ce=>Ce.type==="ReturnStatement").length!==1||pt.length!==1)&&(N=!0,pt.length=0);let on=new Set,sn=new Set,W=(U,Ce=J,De=Y)=>{if(!(!qs(U)||ao(U))){if(t.requireStaticMount){if(De.length>0)return;if(U.type==="JSXText"&&Ce==="rendered"&&typeof U.start=="number"&&typeof U.end=="number"&&E.set(U.start,U.end),U.type==="LogicalExpression"||U.type==="ConditionalExpression"){let ie=U.type==="ConditionalExpression"?U.test:U.left;if(ie?.type==="BooleanLiteral"){let Xe=U.type==="ConditionalExpression"?ie.value?U.consequent:U.alternate:U.operator==="&&"?ie.value?U.right:null:U.operator==="||"?ie.value?null:U.right:null;W(Xe,Ce,De)}else Il(U)&&(N=!0);return}if(U.type==="CallExpression"){Il(U)&&(N=!0);return}}if(U.type==="Identifier"&&typeof U.name=="string"){let ie=r?r.valueAliases.get(U):We.get(U.name),Xe=`${Ce}\0${U.name}\0${hp(De)}`;ie&&!on.has(Xe)&&!sn.has(U.name)?(on.add(Xe),sn.add(U.name),W(ie,Ce,De),sn.delete(U.name)):r?N=!0:O(U.name,Ce);return}if(U.type==="CallExpression"){let ie=U.callee,Xe=cn(U.arguments),yt=Qs(ie),Nt=ie?.type==="Identifier"&&typeof ie.name=="string"?s.get(ie.name):void 0;if(Ce==="rendered"&&(yt==="createElement"||yt.endsWith(".createElement")||Nt?.source==="react"&&Nt.exportName==="createElement")&&Xe[0]?.type==="StringLiteral"&&Xe[0].value==="form"&&(b=!0),ie?.type==="Identifier"&&typeof ie.name=="string"){let Et=Ee.get(ie.name);if(Et){L(Et,Ce,De);return}}if(ie&&ao(ie)){L(ie,Ce,De);return}if(OL(ie)){for(let Et of Xe)if(ao(Et))L(Et,Ce,De);else if(Et.type==="Identifier"&&typeof Et.name=="string"){let pn=Ee.get(Et.name);pn&&L(pn,Ce,De)}return}for(let Et of Xe)Il(Et)&&I.push({code:"rendered-module.unresolved-export",message:"Unable to prove whether a JSX-producing call argument is rendered.",file_path:t.filePath??"",line:Et.loc?.start.line??1});return}if(U.type==="JSXElement"){let ie=U.openingElement,Xe=ie?pS(De,TL(ie)):De;if(t.requireStaticMount&&ie){if(Xe.length>0)return;if(wL(ie)){N=!0;return}let Et=gp(ie);Ce==="rendered"&&Et.has("data-site-block-id")&&typeof ie.end=="number"&&S.add(ie.end)}W(ie,Ce,Xe);let yt=ie?ea(ie.name):void 0,Nt=cn(U.children);if(t.requireStaticMount&&yt==="a")return;if(t.requireStaticMount&&yt&&!/^[a-z]/.test(yt)){Nt.some(Il)&&(N=!0);return}for(let Et of Nt)W(Et,Ce,Xe);return}if(U.type==="JSXOpeningElement"){let ie=ea(U.name);Ce==="rendered"&&ie==="form"&&(b=!0);let Xe=ie&&(!r||r.importedOpenings.has(U))?mS(ie,s):void 0;if(r&&Ce==="rendered"&&ie&&typeof U.start=="number"){let yt=gp(U).get("href");v.set(U.start,{start:U.start,name:ie,...typeof yt=="string"?{href:yt}:{},...Xe?{imported:Xe}:{}})}if(Ce==="rendered"&&Xe&&(!r||r.uniqueImportedOpenings.has(U))&&typeof U.start=="number"){let yt=`${Xe.source}\0${Xe.exportName}\0${U.start}`,Nt=x.get(yt);if(!Nt){let Et=gp(U).get("formBlockId");Nt={source:Xe.source,export_name:Xe.exportName,start_offset:U.start,...typeof Et=="string"?{static_form_block_id:Et}:{}},x.set(yt,Nt),h.push(Nt)}De.length>0&&(Nt.static_render_blockers=pS(Nt.static_render_blockers??[],De))}if(r)if(Xe)O(ie,Ce);else{let yt=r.localComponentOpenings.get(U);qs(yt)?L(yt,Ce,De):/^[A-Z]/.test(ie)&&!gS(ie)&&(N=!0)}else if(ie&&!O(ie,Ce)){let yt=Ee.get(ie);yt?L(yt,Ce,De):We.has(ie)?W(We.get(ie),Ce,De):gS(ie)||/^[A-Z]/.test(ie)&&I.push({code:"rendered-module.dynamic-import",message:`Unable to resolve rendered component ${ie} from a static import.`,file_path:t.filePath??"",line:U.loc?.start.line??1})}for(let yt of cn(U.attributes))W(yt,"uncertain",De);return}if(U.type==="JSXAttribute"){let ie=U.value,Xe=ie?.type==="JSXExpressionContainer"?ie.expression:ie;Xe&&ao(Xe)?L(Xe,"uncertain",De):W(Xe,"uncertain",De);return}for(let[ie,Xe]of Object.entries(U))if(!(ie==="loc"||ie==="closingElement"))if(Array.isArray(Xe))for(let yt of Xe)W(yt,Ce,De);else W(Xe,Ce,De)}},pe=j.body;pe&&pe.type!=="BlockStatement"&&pt.push(pe);for(let U of pt)W(U);ue.delete(J)},X=c.get(t.exportName);if(typeof X=="string"){let j=X,J=new Set;for(;l.has(j)&&!J.has(j);)J.add(j),j=l.get(j);if(!O(j)){let Y=a.get(j);Y?L(Y):I.push(yS(t))}}else X?L(X):I.push(yS(t));return{form_codes:[...d],components:f,uncertain_components:g,rendered_component_openings:h,renders_native_form:b,...t.requireStaticMount?{static_block_content_starts:[...S],static_jsx_openings:[...v.values()],static_jsx_text_spans:[...E].map(([j,J])=>({start:j,end:J})),has_uncertain_mounts:N||g.length>0}:{},diagnostics:I}}function wL(e){return cn(e.attributes).some(t=>{if(t.type==="JSXSpreadAttribute")return!0;let n=xp(t.name);if(!n||!["hidden","inert","aria-hidden","className","style"].includes(n))return!1;let r=t.value;if(r?.type!=="JSXExpressionContainer")return!1;let o=r.expression;return o?.type!=="ObjectExpression"&&vl(o)===void 0})}function hp(e){return e.map(t=>`${t.start_offset}:${t.reason}`).join("|")}function pS(e,t){return[...new Map([...e,...t].map(r=>[hp([r]),r])).values()]}function TL(e){let t=new Map;for(let a of cn(e.attributes)){if(a.type==="JSXSpreadAttribute"){t.clear();continue}let l=xp(a.name);if(!l)continue;let c=a.value;t.set(l,c?.type==="JSXExpressionContainer"?c.expression:c)}let n=ea(e.name)??"unknown",r=[],o=a=>{r.push({element_name:n,line:e.loc?.start.line??1,start_offset:FL(e.start),reason:a})};for(let a of["hidden","inert","aria-hidden","disabled"]){if(!t.has(a)||a==="disabled"&&n!=="fieldset")continue;let l=vl(t.get(a));(l===!0||(a==="aria-hidden"?l==="true":typeof l=="string"))&&o(a)}let i=t.get("style");if(i?.type==="ObjectExpression"){let a=new Map;for(let c of cn(i.properties)){let u=c.key,d=!c.computed&&u?.type==="Identifier"?u.name:u?.type==="StringLiteral"?u.value:void 0;c.type!=="ObjectProperty"||typeof d!="string"?a.clear():a.set(d,vl(c.value))}a.get("display")==="none"&&o("style.display=none"),a.get("visibility")==="hidden"&&o("style.visibility=hidden");let l=a.get("opacity");(l===0||typeof l=="string"&&l.trim()==="0")&&o("style.opacity=0")}let s=vl(t.get("className"));if(typeof s=="string"){let a=s.split(/\s+/).filter(Boolean),c={hidden:new Set(["block","inline","inline-block","flex","inline-flex","grid","inline-grid","table","inline-table","table-row","table-cell","flow-root","contents","list-item"]),invisible:new Set(["visible"]),"sr-only":new Set(["not-sr-only"])};for(let[u,d]of Object.entries(c))a.includes(u)&&!a.some(f=>d.has(f.split(":").at(-1)))&&o(`className=${u}`)}return r}function vl(e){if(e===null)return!0;if(e){if(e.type==="StringLiteral"||e.type==="BooleanLiteral"||e.type==="NumericLiteral")return e.value;if(e.type==="TemplateLiteral"&&cn(e.expressions).length===0)return cn(e.quasis)[0]?.value?.cooked}}function mS(e,t){let n=t.get(e);if(n)return n;let[r,...o]=e.split(".");if(!r||o.length===0)return;let i=t.get(r);if(i?.exportName==="*")return{source:i.source,exportName:o.join(".")}}function gS(e){return e.endsWith(".Provider")||e.endsWith(".Consumer")}function ao(e){return e?.type==="FunctionDeclaration"||e?.type==="FunctionExpression"||e?.type==="ArrowFunctionExpression"}function OL(e){let t=Qs(e),n=e?.type==="MemberExpression"&&e.computed!==!0?e.property:void 0;return t==="Array.from"||t==="React.Children.map"||n?.type==="Identifier"&&(n.name==="map"||n.name==="flatMap")}function Il(e){let t=!1;return yp(e,n=>{if(!t){if(n.type==="JSXOpeningElement"){t=!0;return}n.type==="CallExpression"&&Qs(n.callee)==="cms.forms.getConfig"&&(t=!0)}}),t}function hS(e){return e?.type==="Identifier"&&typeof e.name=="string"?e.name:e?.type==="StringLiteral"&&typeof e.value=="string"?e.value:""}function yS(e){return{code:"rendered-module.unresolved-export",message:`Unable to resolve rendered export ${e.exportName}.`,file_path:e.filePath??"",line:1}}function Qs(e){if(!e)return"";if(e.type==="Identifier"&&typeof e.name=="string")return e.name;if(e.type!=="MemberExpression"||e.computed===!0)return"";let t=Qs(e.object),n=e.property;return!t||n?.type!=="Identifier"||typeof n.name!="string"?"":`${t}.${n.name}`}function gp(e){let t=new Map,n=Array.isArray(e.attributes)?e.attributes:[];for(let r of n){let o=r;if(o.type!=="JSXAttribute")continue;let i=xp(o.name);i&&t.set(i,LL(o.value))}return t}function LL(e){if(e==null)return!0;let t=e;if(t.type==="StringLiteral")return t.value;if(t.type!=="JSXExpressionContainer")return;let n=t.expression;if(n&&(n.type==="StringLiteral"||n.type==="NumericLiteral"))return n.value}function xp(e){let t=e;if(t?.type==="JSXIdentifier")return typeof t.name=="string"?t.name:void 0}function FL(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function yp(e,t){if(qs(e)){t(e);for(let[n,r]of Object.entries(e))if(n!=="loc"){if(Array.isArray(r)){for(let o of r)yp(o,t);continue}yp(r,t)}}}function qs(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function ea(e){let t=e;if(!t)return"";if(t.type==="JSXIdentifier")return typeof t.name=="string"?t.name:"";if(t.type==="JSXMemberExpression"){let n=ea(t.object),r=ea(t.property);return n&&r?`${n}.${r}`:r||n}return""}function cn(e){return Array.isArray(e)?e.filter(t=>qs(t)):[]}var ML="components/site/generated/",ta=[".tsx",".ts",".jsx",".js"];function xS(e){if(e.expectedUrlPath===DL)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set(zs(Object.keys(e.files).map(p=>({path:p}))).map(p=>p.entryFile)),n=Object.entries(e.files).filter(([p,h])=>{let x=p.replace(/\\/g,"/");if(!t.has(x))return!1;let b=dp(h,x);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=new Set([r]);try{let p=xl({files:new Map(Object.entries(e.files))});for(let h of p)h.canonicalEntryFile===r&&o.add(h.entryFile)}catch(p){return{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:p instanceof Error?p.message:"Invalid page template source."}}let i=BL(e.files);if(!i.ok)return i.error;let s=i.graph,a=VL(o,s),l=KL(o,a,s),c=[...a].filter(p=>!l.has(p)).sort((p,h)=>p.localeCompare(h)),u=[...o,...[...l].sort((p,h)=>p.localeCompare(h))],d=new Set(u),f=u.map(p=>({operation:"delete",file:p})),m=[],g=[];for(let[p,h]of Object.entries(e.files))if(!d.has(p)){if(h.includes("NAV_ITEMS")){let x=mp(h,e.expectedUrlPath);x.status==="removed"?(f.push({operation:"upsert",file:p,content:x.source}),m.push(p)):x.status==="unsupported"&&g.push(`unsupported_navigation:${p}`)}h.includes(e.expectedUrlPath)&&!h.includes("NAV_ITEMS")&&g.push(`preserved_link:${p}`)}return{ok:!0,edits:f,deletedFiles:u,updatedFiles:m,preservedSharedFiles:c,warnings:g}}function BL(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")||!jL(r))continue;let s=Oe(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:l}of s.module.imports){if($L(l))continue;let c=ar(r,l),u=UL(c,t);if(!u)return{ok:!1,error:{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:`Page source dependencies could not be proven safe: ${r} -> ${l} (import-not-found).`}};a.add(u)}n.set(r,a)}return{ok:!0,graph:n}}function jL(e){let t=e.toLowerCase();return ta.some(n=>t.endsWith(n))}function $L(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!ta.some(n=>e.endsWith(n)))}function UL(e,t){let n=e.replace(/\\/g,"/");return(ta.some(o=>n.endsWith(o))?[n]:[...ta.map(o=>`${n}${o}`),...ta.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function VL(e,t){let n=new Set,r=[...e].flatMap(o=>[...t.get(o)??[]]);for(;r.length>0;){let o=r.pop();!o.startsWith(ML)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function KL(e,t,n){let r=new Set(t),o=!0;for(;o;){o=!1;for(let i of[...r])[...n].some(([a,l])=>!e.has(a)&&!r.has(a)&&l.has(i))&&(r.delete(i),o=!0)}return r}import*as xE from"@babel/parser";import*as Ye from"@babel/types";import*as Ul from"node:path";import*as nt from"@babel/types";var JL=new Set(["copyWithin","fill","pop","push","reverse","shift","sort","splice","unshift"]);function co(e,t){let n=[e],r=new Set;for(;n.length>0;){let o=n.pop();if(r.has(o))continue;r.add(o);let i=Sp(o)?.expressionPath;if(i?.isIdentifier()){let s=i.scope.getBinding(i.node.name);s&&n.push(s)}for(let s of o.referencePaths){if(s.node===t)continue;let a=s.parentPath;if(a?.isVariableDeclarator()&&s.key==="init"&&nt.isIdentifier(a.node.id)){let f=a.scope.getBinding(a.node.id.name);f&&n.push(f);continue}if(!a?.isMemberExpression()&&!a?.isOptionalMemberExpression()||s.key!=="object")continue;let l=a.parentPath;if(l?.isAssignmentExpression()&&a.key==="left")return!0;if(!l?.isCallExpression()&&!l?.isOptionalCallExpression()||a.key!=="callee")continue;let{property:c,computed:u}=a.node,d=u&&nt.isStringLiteral(c)?c.value:!u&&nt.isIdentifier(c)?c.name:null;if(d&&JL.has(d))return!0}}return!1}function Sp(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 hr(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return Jo(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(nt.isObjectPattern(n)||nt.isArrayPattern(n))return Jo(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(zL(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function Jo(e,t,n=!1){return nt.isIdentifier(e)?e.name===t&&n:nt.isObjectPattern(e)?e.properties.some(r=>nt.isObjectProperty(r)?Jo(r.value,t,n):Jo(r.argument,t,n)):nt.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=nt.isRestElement(r)?r.argument:r;return Jo(o,t,n)}):nt.isAssignmentPattern(e)?Jo(e.left,t,!0):nt.isRestElement(e)?Jo(e.argument,t,n):!1}function Pi(e,t){if(e.path.isObjectPattern()){if(t){let r=nr(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:hr(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:hr(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=bS(r),i=!1,s=o?o.initBinding&&bp(o.initBinding)?(i=hr(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let l=Pi(o.initBinding,{kind:"identifier",expression:o.initBinding.identifier.name,base:o.initBinding.identifier.name,path:[]});return i=l?.hasDefault??!1,l?[{kind:"property",name:l.propName},...l.remainingPath,...o.initPathPrefix]:null})():null:null,a=nr(e.path.node.id,e.identifier.name);if(s&&a){let l=[...s,...a],[c,...u]=l;return!c||c.kind!=="property"?null:{propName:c.name,remainingPath:[...u,...t?.path??[]],hasDefault:i||hr(e)}}}}let n=GL(e);if(n){let r=XL(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||hr(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=WL(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:hr(e)}}let i=na(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:hr(e)}:null}if(bp(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:hr(e)}}return null}function XL(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=bS(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,l=bp(i)?(a=hr(i),[...s]):(()=>{let u=Pi(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(!l)return null;let c=nr(n.node.id,t.identifier.name);return c?{path:[...l,...c],hasDefault:a||hr(t)}:null}function bS(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=YL(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function bp(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function zL(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function WL(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=nr(i.node,t);if(a)return a}return null}function SS(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let l=kl(a,e.identifier.name);if(l&&(!n||l.propName===n))return{propName:l.propName,componentName:t,expressionPath:l.expressionPath,displayPath:`${t}.${l.propName}.default`}}}if(e.path.isObjectPattern())for(let a of e.path.get("properties")){if(!a.isObjectProperty())continue;let l=na(a.node);if(!l||n&&l!==n)continue;let c=a.get("value");if(!c.isAssignmentPattern())continue;let u=c.get("right");if(u.isExpression())return{propName:l,componentName:t,expressionPath:u,displayPath:`${t}.${l}.default`}}let r=HL(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=na(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 kl(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=na(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&nr(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=kl(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=kl(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=kl(r,t);if(o)return o}}return null}function nr(e,t,n=[]){if(nt.isIdentifier(e))return e.name===t?n:null;if(nt.isObjectPattern(e)){for(let r of e.properties)if(nt.isObjectProperty(r)){let o=na(r);if(!o)continue;let i=nr(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(nt.isRestElement(r)){let o=nr(r.argument,t,n);if(o)return o}}if(nt.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=nt.isRestElement(o)?o.argument:o,s=nr(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return nt.isAssignmentPattern(e)?nr(e.left,t,n):null}function HL(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function GL(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 na(e){return e.computed?null:nt.isIdentifier(e.key)?e.key.name:nt.isStringLiteral(e.key)?e.key.value:null}function YL(e){let t=[],n=e;for(;nt.isMemberExpression(n);){if(n.computed)if(nt.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(nt.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(nt.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return nt.isIdentifier(n)?{base:n.name,path:t}:null}import*as CS from"@babel/parser";import vp from"@babel/traverse";import*as Ni from"@babel/types";import*as Ve from"@babel/types";var ES=new WeakMap;function Rl(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?_l(n,t):null}if(e.isMemberExpression()){let n=nF(e.node),r=ZL(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?_l(o,[...r,...t]):null}return e.isAwaitExpression()||Ip(e.node)?lo(oF(e.node),t,"awaited or fetched expression"):null}function ZL(e){let t=[],n=e;for(;Ve.isMemberExpression(n);){if(n.computed)if(Ve.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(Ve.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(Ve.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return Ve.isIdentifier(n)?t:null}function _l(e,t=[],n){let r=qL(e,t);if(r)return r;let o=QL(e,t,n);if(o)return o;let i=eF(e,t,n);return i||null}function oa(e){return e?.kind==="api-source"}function qL(e,t){if(e.path.isVariableDeclarator()&&Ve.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&Ep(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return lo(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&Ve.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(l=>Ve.isObjectProperty(l)&&kS(l)==="data"&&ra(l.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&Ep(a.node))return lo(e.identifier.name,t,"query hook data binding")}let n=tF(e);if(!n||kS(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()||!Ep(i.node)?null:lo(e.identifier.name,t,"query hook data binding")}function QL(e,t,n){if(e.path.isVariableDeclarator()&&Ve.isArrayPattern(e.path.node.id)){let l=e.path.get("init");if(!l?.isCallExpression()||!vS(l.node))return null;let[c,u]=e.path.node.id.elements;return!Ve.isIdentifier(c)||c.name!==e.identifier.name||!Ve.isIdentifier(u)?null:IS(e,u.name,n)?lo(e.identifier.name,t,"state setter is updated by API data"):null}if(!e.path.isIdentifier())return null;let r=e.path.parentPath;if(!r?.isArrayPattern())return null;let o=r.parentPath;if(!o?.isVariableDeclarator())return null;let i=o.get("init");if(!i?.isCallExpression()||!vS(i.node)||r.node.elements.findIndex(l=>l===e.path.node)!==0)return null;let a=r.node.elements[1];return Ve.isIdentifier(a)&&IS(e,a.name,n)?lo(e.identifier.name,t,"state setter is updated by API data"):null}function eF(e,t,n){let r=e.path.isVariableDeclarator()?e.path:e.path.findParent(i=>i.isVariableDeclarator());if(!r?.isVariableDeclarator())return null;let o=r.get("init");return o?.isExpression()?o.isAwaitExpression()?lo(e.identifier.name,t,"awaited binding result"):Ip(o.node,n)?lo(e.identifier.name,t,"fetch-backed binding result"):null:null}function tF(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 ra(e,t){return Ve.isIdentifier(e)?e.name===t:Ve.isAssignmentPattern(e)?ra(e.left,t):Ve.isObjectPattern(e)?e.properties.some(n=>Ve.isObjectProperty(n)?ra(n.value,t):ra(n.argument,t)):Ve.isArrayPattern(e)?e.elements.some(n=>!!n&&ra(Ve.isRestElement(n)?n.argument:n,t)):!1}function IS(e,t,n){let r=!1,o=!1,i=e.scope.path,s;if(n){let l=ES.get(n);l||(l=new WeakMap,ES.set(n,l)),s=l.get(i.node),s||(s=new Map,l.set(i.node,s));let c=s.get(t);if(c!==void 0)return c}i.traverse({CallExpression(l){Ip(l.node)&&(r=!0),(rF(l.node.callee,t)||l.node.arguments.some(c=>Ve.isIdentifier(c)&&c.name===t))&&(o=!0)}});let a=r&&o;return s?.set(t,a),a}function Ep(e){let t=Pl(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function vS(e){return Pl(e.callee)==="useState"}function Ip(e,t){let n=t?.get(e);if(n!==void 0)return n;let r=Cl(e,o=>Ve.isCallExpression(o)&&Pl(o.callee)==="fetch");return t?.set(e,r),r}function nF(e){let t=e;for(;Ve.isMemberExpression(t);)t=t.object;return Ve.isIdentifier(t)?t.name:null}function kS(e){return e.computed?null:Ve.isIdentifier(e.key)?e.key.name:Ve.isStringLiteral(e.key)?e.key.value:null}function Pl(e){return Ve.isIdentifier(e)?e.name:Ve.isMemberExpression(e)&&Ve.isIdentifier(e.property)?e.property.name:null}function rF(e,t){return Cl(e,n=>Ve.isIdentifier(n)&&n.name===t)}function Cl(e,t){if(t(e))return!0;let n=Ve.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(Ve.isNode(i)&&Cl(i,t))return!0;continue}if(Ve.isNode(o)&&Cl(o,t))return!0}return!1}function oF(e){return Ve.isIdentifier(e)?e.name:Ve.isCallExpression(e)?Pl(e.callee)??"api":Ve.isAwaitExpression(e)?"awaited-api":"api"}function lo(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:iF(e,t),reason:n}}function iF(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var RS=typeof vp=="function"?vp:vp.default;function PS(e,t){let n=AS(e);if(!n)return{allowed:!0};let r=!1;return RS(n,{CallExpression(o){if(!wS(o.node,t.sourceRange)||!sF(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||oa(Rl(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function NS(e,t){let n=AS(e);if(!n)return{allowed:!0};let r=!1;return RS(n,{JSXExpressionContainer(o){wS(o.node,t.sourceRange)&&(Ni.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 AS(e){try{return CS.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function sF(e){let t=e.callee;return Ni.isMemberExpression(t)&&Ni.isIdentifier(t.property)&&t.property.name==="map"}function wS(e,t){let n=e.loc;return n?_S({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&_S({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function _S(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 ge from"@babel/types";import*as TS from"@babel/parser";import kp from"@babel/traverse";import*as St from"@babel/types";import*as Ai from"node:path";var rr=typeof kp=="function"?kp:kp.default;function zt(e){try{return TS.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function _p(e){return e.computed?St.isStringLiteral(e.key)||St.isNumericLiteral(e.key)?String(e.key.value):null:aF(e.key)}function aF(e){return St.isIdentifier(e)?e.name:St.isStringLiteral(e)||St.isNumericLiteral(e)?String(e.value):null}function Xo(e){return St.isParenthesizedExpression(e)||St.isTSAsExpression(e)||St.isTSSatisfiesExpression(e)||St.isTSNonNullExpression(e)||St.isTSTypeAssertion(e)?Xo(e.expression):St.isExpression(e)?e:null}function Cp(e){if(St.isIdentifier(e))return[e.name];if((St.isMemberExpression(e)||St.isOptionalMemberExpression(e))&&!e.computed&&St.isIdentifier(e.property)){let t=Xo(e.object),n=t?Cp(t):null;return n?[...n,e.property.name]:null}return null}function zo(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?Ai.normalize(Ai.join(Ai.dirname(e),t)).replace(/\\/g,"/"):t}function wn(e,t){return Nl(e)===Nl(t)}function Nl(e){let t=wi(e);return t.endsWith("/index")?t.slice(0,-6):t}function wi(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function FS(e,t,n){let r=jS(e,t);if($S(e,r),US(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 rr(e,{JSXElement(s){XS(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:Al(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 DS(e,t){let n=new Map,r=i=>{let s=Ti(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 cF(i,n))o=r(s)||o}return[...n.values()]}function cF(e,t){let n=[],r=lF(e,t);for(let o of e.ast.program.body){if(ge.isExportDefaultDeclaration(o)&&ge.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=ia(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(ge.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=zo(e.file,o.source.value);for(let s of o.specifiers){if(ge.isExportNamespaceSpecifier(s)){let c=uo(s.exported);for(let u of t.values())wn(u.file,i)&&n.push({file:e.file,namespace:Rp(c,u.namespace),exportName:u.exportName});continue}if(!ge.isExportSpecifier(s))continue;let a=uo(s.local),l=[...t.values()].filter(c=>wn(c.file,i)&&Wo(c.namespace,a));if(l.length>0){let c=uo(s.exported);for(let u of l){let d=ia(u.namespace,a,c);d&&n.push({file:e.file,namespace:d,exportName:u.exportName})}continue}t.has(Ti({file:i,exportName:a}))&&n.push({file:e.file,exportName:uo(s.exported)})}continue}if(ge.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!ge.isExportSpecifier(i))continue;let s=uo(i.local),a=r.get(s)??[];if(a.length>0){let l=uo(i.exported);n.push({file:e.file,exportName:l});for(let c of a){let u=ia(c.namespace,s,l);u&&n.push({file:e.file,namespace:u,exportName:c.exportName})}}}continue}if(ge.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=zo(e.file,o.source.value),s=o.exported;if(s){let a=uo(s);for(let l of t.values())wn(l.file,i)&&n.push({file:e.file,namespace:Rp(a,l.namespace),exportName:l.exportName});continue}for(let a of t.values())wn(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function Rp(e,t){return t?`${e}.${t}`:e}function Wo(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function ia(e,t,n){return!Wo(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function lF(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(!ge.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=zo(e.file,i.source.value);for(let a of i.specifiers){if(ge.isImportDefaultSpecifier(a)){let l=t.get(Ti({file:s,exportName:"default"}));l&&r(a.local.name,l);let c=[...t.values()].filter(u=>wn(u.file,s)&&Wo(u.namespace,"default"));for(let u of c){let d=ia(u.namespace,"default",a.local.name);d&&r(a.local.name,{...u,namespace:d})}continue}if(ge.isImportSpecifier(a)){let l=uo(a.imported),c=[...t.values()].filter(d=>wn(d.file,s)&&Wo(d.namespace,l));for(let d of c)r(a.local.name,d);let u=t.get(Ti({file:s,exportName:l}));u&&r(a.local.name,u);continue}if(ge.isImportNamespaceSpecifier(a))for(let l of t.values())wn(l.file,s)&&r(a.local.name,{...l,namespace:Rp(a.local.name,l.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(ge.isVariableDeclaration(i))for(let s of i.declarations){if(!ge.isIdentifier(s.id)||!s.init)continue;let a=Xo(s.init);if(!a||!ge.isIdentifier(a))continue;let l=n.get(a.name)??[];if(l.length===0)continue;let c=n.get(s.id.name)??[],u=new Set(c.map(Ti));for(let d of l){let f=ia(d.namespace,a.name,s.id.name),m=f?{...d,namespace:f}:d,g=Ti(m);u.has(g)||(r(s.id.name,m),u.add(g),o=!0)}}}return n}function Ti(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${Nl(e.file)}#${t}`}function uo(e){return ge.isIdentifier(e)?e.name:e.value}function MS(e,t){for(let n of e.program.body){if(ge.isExportDefaultDeclaration(n)){let o=n.declaration;if((ge.isFunctionDeclaration(o)||ge.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(ge.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!ge.isExportNamedDeclaration(n))continue;let r=n.declaration;if((ge.isFunctionDeclaration(r)||ge.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(ge.isVariableDeclaration(r)){for(let o of r.declarations)if(ge.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!ge.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:ge.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function Np(e){let t=uF(e),n=[],r=US(e.ast,t);return rr(e.ast,{JSXElement(o){wn(e.file,e.sourceFile)&&Al(o)===e.sourceComponent||XS(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function BS(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function jS(e,t){let n=BS();return rr(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function uF(e){let t=BS();return wn(e.file,e.sourceFile)&&dF(t,jS(e.ast,e.sourceComponent)),rr(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=zo(e.file,o),s=e.componentIdentities.filter(a=>wn(a.file,i));if(s.length!==0)for(let a of r.specifiers){let l=n.scope.getBinding(a.local.name);if(l){if(ge.isImportDefaultSpecifier(a)&&s.some(c=>c.exportName==="default")&&t.localBindings.add(l),ge.isImportDefaultSpecifier(a)){let c=s.filter(u=>Wo(u.namespace,"default"));if(c.length>0){let u=t.namespaceMembers.get(l)??new Set;for(let d of c){let f=LS(d,"default");f&&u.add(f)}t.namespaceMembers.set(l,u)}continue}if(ge.isImportSpecifier(a)){let c=ge.isIdentifier(a.imported)?a.imported.name:a.imported.value,u=s.filter(d=>Wo(d.namespace,c));if(u.length>0){let d=t.namespaceMembers.get(l)??new Set;for(let f of u){let m=LS(f,c);m&&d.add(m)}t.namespaceMembers.set(l,d);continue}s.some(d=>!d.namespace&&d.exportName===c)&&t.localBindings.add(l);continue}if(ge.isImportNamespaceSpecifier(a))for(let c of s){let u=c.namespace?`${c.namespace}.${c.exportName}`:c.exportName,d=t.namespaceMembers.get(l)??new Set;d.add(u),t.namespaceMembers.set(l,d)}}}}}),$S(e.ast,t),t}function dF(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 $S(e,t){rr(e,{VariableDeclarator(n){if(!n.node.init)return;let r=Xo(n.node.init);if(r){if(ge.isIdentifier(n.node.id)){let o=Ho(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&Pp(t,i,o);return}if(ge.isObjectPattern(n.node.id)){let o=Ho(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&JS(n.node.id,o.namespaceMembers,t,n)}}}})}function US(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return rr(e,{ReferencedIdentifier(r){if(n){r.stop();return}fF(r)||!r.isIdentifier()||!VS(r,t)||pF(r,t)||mF(r)||(n=!0,r.stop())}}),n}function fF(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 VS(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)&&Ho(r.node,t,r)?r:null}function pF(e,t){let n=e.findParent(l=>l.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!OS(e,r))return!1;let o=VS(e,t);if(!o)return!1;if(Xo(r.node)===o.node)return!!Ho(r.node,t,r);let s=e.findParent(l=>l.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&OS(e,a)&&!!Ho(a.node,t,a)}function mF(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function OS(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Ho(e,t,n){let r=Xo(e);if(!r)return null;if(ge.isIdentifier(r)){let a=n.scope.getBinding(r.name);if(!a)return null;let l=t.namespaceMembers.get(a);return t.localBindings.has(a)?{local:!0,namespaceMembers:new Set,unsupported:!1}:l?{local:!1,namespaceMembers:new Set(l),unsupported:!1}:null}if(ge.isObjectExpression(r))return gF(r,t,n);let o=Cp(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?KS(s,o.slice(1).join(".")):null}function gF(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!ge.isObjectProperty(i))continue;let s=_p(i);if(!s||!ge.isExpression(i.value)){ge.isExpression(i.value)&&(o||=Ho(i.value,t,n)!==null);continue}let a=Ho(i.value,t,n);if(a){o||=a.unsupported,a.local&&r.add(s);for(let l of a.namespaceMembers)r.add(`${s}.${l}`)}}return r.size>0||o?{local:!1,namespaceMembers:r,unsupported:o}:null}function KS(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 Pp(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 JS(e,t,n,r){for(let o of e.properties){if(ge.isRestElement(o)){if(ge.isIdentifier(o.argument)){let l=r.scope.getBinding(o.argument.name);l&&Pp(n,l,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!ge.isObjectProperty(o))continue;let i=_p(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=KS(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=ge.isAssignmentPattern(o.value)?o.value.left:o.value;if(ge.isIdentifier(a)){let l=r.scope.getBinding(a.name);l&&Pp(n,l,s);continue}if(ge.isObjectPattern(a)&&s.namespaceMembers.size>0){JS(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function LS(e,t){if(!Wo(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 XS(e,t){let n=e.node.openingElement.name;if(ge.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=zS(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 zS(e){if(ge.isJSXIdentifier(e))return[e.name];if(ge.isJSXMemberExpression(e)){let t=zS(e.object);return t?[...t,e.property.name]:null}return null}function Al(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()&&ge.isIdentifier(n.node.id))return n.node.id.name}return null}function WS(e,t){let n=zt(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=Np({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 it(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 tt(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function yr(e,t){let n=tt(e);return!!(n&&Tn(t,n))}function Tn(e,t){return t.start>=e.start&&t.end<=e.end}function Hn(e,t){let n=Be(e,it(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:wl(e,t)}function Oi(e,t){let n=tt(t);return n?e.slice(n.start,n.end):""}function HS(e,t){return e.start===t.start&&e.end===t.end}function wl(e,t){let n=null;return rr(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 Tl(e,t){return Ap(e,t).length>0}function Ol(e,t){let n=tt(e.node),r=tt(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()&&!hF(o,n,r)))return!0;o=o.parentPath}return!1}function hF(e,t,n){let r=tt(e.node.consequent);if(r&&Tn(r,t)&&!Tn(r,n))return!1;let o=e.node.alternate?tt(e.node.alternate):null;return!(o&&Tn(o,t)&&!Tn(o,n))}function Ap(e,t){let n=tt(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=tt(o.node.consequent),a=tt(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()&&wp(o.node.operator)){let s=tt(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 wp(e){return e==="&&"||e==="||"||e==="??"}function GS(e,t){let n=tt(e.consequent);if(n&&Tn(n,t))return n;let r=tt(e.alternate);return r&&Tn(r,t)?r:null}function YS(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=>wi(a.file)));if(!t.has(wi(e.sourceFile))||!t.has(wi(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(wi(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=MS(e.sourceAst,e.sourceComponent);if(!n)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without an exported source component identity"};let r=[];for(let a of e.knownSourceFiles){let l=zt(a.content);if(!l)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component because a loaded source file cannot be parsed"};r.push({file:a.file,ast:l})}let o=DS(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let l=Np({ast:a.ast,file:a.file,sourceFile:e.sourceFile,sourceComponent:e.sourceComponent,componentIdentities:o});if(l.hasUnsafeReference)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component because the component has unsupported value usages"};i.push(...l.callSites)}if(i.length!==1)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without a single project-wide component call site"};let[s]=i;return!wn(s.file,e.targetFile)||Al(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}}import{SiteEditSetPropsParamsSchema as IF}from"@vcp-dev/platform-shared/contracts";function Ll(e){let{state:t,scope:n,operation:r,selectionRef:o,repeatTarget:i}=e;if(!t||t.status==="blocked")return{ok:!1,code:"readonly-property",reason:t?.diagnostic?.message??"No safe property write target is available"};if(t.status==="binding"){let s=t.target;if(s?.kind!=="value-binding"||!s.target.locator||n!=="selection"||r!=="set")return sa();let a=s.target,l=a.locator;if(a.sourceKind==="repeat-template"){let c=o?.instanceIndex;if(c===void 0)return sa();let u=yF(a,c,o?.instanceCount);if(!u)return sa();l=u}return{ok:!0,target:{kind:"value-binding",file:a.file,locator:l}}}return o?.instanceIndex!==void 0?n!=="selection"||!i?.ok?{ok:!1,code:"repeat-target-failed",reason:i&&!i.ok?i.reason:"No safe selected repeat property target is available"}:{ok:!0,target:{kind:"repeat-property",target:i}}:e.isRepeat&&n!=="template"||t.status==="direct"&&t.target?.kind!=="jsx-attribute"?sa():{ok:!0,target:{kind:"jsx-attribute"}}}function sa(){return{ok:!1,code:"unsupported-binding",reason:"Property does not have a safe typed binding write target for this scope and operation"}}function yF(e,t,n){if(!e.locator||!Number.isInteger(t)||t<0)return null;let r=e.collectionPathMap?.length??e.collectionIndexMap?.length;if(r!==void 0&&(t>=r||n!==void 0&&n!==r))return null;let o=e.collectionPathMap?.[t];if(o)return{...e.locator,path:o};let i=e.locator.path??[],s=i.findLastIndex(l=>l.kind==="index");if(s<0)return null;let a=i.map((l,c)=>c===s&&l.kind==="index"?{kind:"index",index:e.collectionIndexMap?.[t]??t}:l);return{...e.locator,path:a}}import*as xr from"@babel/types";import{SiteEditSetPropsParamsSchema as xF}from"@vcp-dev/platform-shared/contracts";function ZS(e){let t=e.changes??(e.change?[e.change]:[]);if(!xF.safeParse({kind:"set-props",scope:"selection",changes:t}).success)return aa("invalid-change","Repeat property changes are invalid");if(t.length!==1||t[0].name!==e.target.propertyName)return aa("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=ft(e.source,"value");if(!o.ok)return aa("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 l=Be(o.ast,a);if(!l.ok||!l.match.path.isObjectExpression())return aa("unsupported-object",`Repeat item ${s} is not a writable object expression`);let c=s===e.target.sourceItemIndex?bF(r):SF(l.match.path.node,r.name);if(!c)return aa("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:c})}return{ok:!0,steps:i}}function bF(e){return e.operation==="set"?{kind:"value",value:e.value}:{kind:"undefined"}}function SF(e,t){let n=e.properties.filter(i=>xr.isObjectProperty(i)&&EF(i.key)===t);if(n.length>1)return null;let r=n[0];if(!r)return{kind:"undefined"};if(!xr.isExpression(r.value))return null;let o=fr(r.value);return o.status==="undefined"?{kind:"undefined"}:o.status!=="resolved"?null:{kind:"value",value:o.value}}function EF(e){return xr.isIdentifier(e)?e.name:xr.isStringLiteral(e)?e.value:xr.isNumericLiteral(e)?String(e.value):null}function aa(e,t){return{ok:!1,errorCode:e,reason:t}}function qS(e){if(e.change.name!=="className"&&e.change.name!=="class")return ca("unsupported-owner",`No specialized property owner is available for '${e.change.name}'`);let t=e.classNameSource;if(!t||t.filePath!==e.node.file)return ca("owner-source-unavailable","className source details are unavailable for the selected node");if(e.change.name==="class"&&t.sourceKind==="missing")return ca("owner-source-unavailable","The class alias requires an existing className source");if(t.sourceKind==="expression")return ca("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 ca("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 ca(e,t){return{ok:!1,errorCode:e,reason:t}}async function eE(e){let t=IF.safeParse({kind:"set-props",scope:e.scope,changes:e.changes});if(!t.success)return fo("invalid-change","Typed property changes are invalid");if(e.node.importedFrom==="next/link"&&e.node.exportName==="default"){let r=t.data.changes.find(o=>o.name==="href");if(r&&(r.operation==="remove"||typeof r.value!="string"||r.value.trim().length===0))return fo("invalid-change","next/link requires a non-empty href; use the dedicated link-target operation to remove the link")}let n=[];for(let r of t.data.changes){let o=await vF(e,r);if(o){if(!o.ok)return fo("owner-plan-failed",o.reason);QS(n,o.steps);continue}let i=await e.getPropertyState(e.node.key,r.name,e.selectionRef);if(!i)return fo("missing-property-state",`No authoritative property state is available for '${r.name}'`);if(i.status==="blocked")return fo("readonly-property",i.diagnostic?.message??`Property '${r.name}' is not writable`);if(CF(i,r)||r.operation==="remove"&&i.status==="missing")continue;let s=e.selectionRef?.instanceIndex!==void 0&&i.status!=="binding"?await e.getRepeatPropertyTarget?.(e.node.key,r.name,e.selectionRef):void 0,a=Ll({state:i,scope:e.scope,operation:r.operation,selectionRef:e.selectionRef,repeatTarget:s});if(!a.ok)return fo(a.code,a.reason);let l=a.target;if(l.kind==="value-binding"&&r.operation==="set"){Tp(n,{type:"update-value",order:n.length,file:l.file,locator:l.locator,value:r.value});continue}if(l.kind==="repeat-property"){let c=ZS({source:e.getFileContent(l.target.sourceFile),target:l.target,changes:[r]});if(!c.ok)return fo("repeat-target-failed",c.reason);QS(n,c.steps);continue}Tp(n,{type:"set-property-changes",order:n.length,file:e.node.file,locator:kF(e.node),scope:e.scope,changes:[r]})}return n.forEach((r,o)=>{r.order=o}),_F(n)?fo("step-conflict","Property changes resolve to conflicting write steps"):{ok:!0,steps:n}}async function vF(e,t){return t.name!=="className"&&t.name!=="class"?null:qS({node:e.node,change:t,classNameSource:e.classNameSource})}function kF(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 _F(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 QS(e,t){for(let n of t)Tp(e,{...n,order:e.length})}function Tp(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 CF(e,t){if(t.operation!=="set"||e.status!=="direct")return!1;let n=e.attribute?.resolution;return n?.status==="resolved"?Op(n.value,t.value):e.attribute?.source===null&&e.attribute.value===t.value}function Op(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)=>Op(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=>Op(n[i],r[i]))}return!1}function fo(e,t){return{ok:!1,errorCode:e,reason:t}}import*as Fi from"@babel/types";import*as be from"@babel/types";function Lp(e,t,n){let r=Hn(t,n);return r?br(e,r):null}function br(e,t){let n=t.findParent(p=>p.isArrowFunctionExpression()||p.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(p=>p===r.node)!==0)return null;let a=i.get("callee");if(!a.isMemberExpression()&&!a.isOptionalMemberExpression())return null;let l=a.node,c=l.property;if(!be.isIdentifier(c)||c.name!=="map"||l.computed)return null;let u=a.get("object"),d=Oi(e,u.node),f=r.node.params.map(p=>Oi(e,p)),m=tt(i.node),g=tt(r.node);return!d||f.some(p=>p.length===0)||!m||!g?null:{callStart:m.start,callEnd:m.end,callbackStart:g.start,callbackEnd:g.end,collectionExpression:d,callbackParams:f,mapOperator:be.isOptionalMemberExpression(l)&&l.optional?"?.map":".map",collectionNeedsParens:Fl(u.node),callbackPath:r,collectionPath:u}}function la(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function RF(e,t){let n=tt(e.node);return n?PF(t).some(r=>{let o=tt(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function PF(e){let t=e.callbackPath.node.body;return be.isBlockStatement(t)?po(t.body):mo(t)}function po(e){let t=[];for(let n of e){if(be.isReturnStatement(n)){n.argument&&t.push(...mo(n.argument));continue}if(be.isBlockStatement(n)){t.push(...po(n.body));continue}if(be.isIfStatement(n)){let r=be.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...po(r)),n.alternate){let o=be.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...po(o))}continue}if(be.isSwitchStatement(n)){for(let r of n.cases)t.push(...po(r.consequent));continue}be.isTryStatement(n)&&(t.push(...po(n.block.body)),n.handler&&t.push(...po(n.handler.body.body)),n.finalizer&&t.push(...po(n.finalizer.body)))}return t}function mo(e){return be.isJSXElement(e)?NF(e)?tE(e.children):[e]:be.isJSXFragment(e)?tE(e.children):be.isParenthesizedExpression(e)||be.isTSAsExpression(e)||be.isTSSatisfiesExpression(e)||be.isTSNonNullExpression(e)||be.isTSTypeAssertion(e)?mo(e.expression):be.isConditionalExpression(e)?[...mo(e.consequent),...mo(e.alternate)]:be.isLogicalExpression(e)&&wp(e.operator)?mo(e.right):[]}function tE(e){return e.flatMap(t=>be.isJSXElement(t)||be.isJSXFragment(t)?mo(t):be.isJSXExpressionContainer(t)&&(be.isJSXElement(t.expression)||be.isJSXFragment(t.expression)||be.isConditionalExpression(t.expression)||be.isLogicalExpression(t.expression))?mo(t.expression):[])}function NF(e){let t=e.openingElement.name;return be.isJSXIdentifier(t)?t.name==="Fragment":be.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function nE(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function Fl(e){return!(be.isIdentifier(e)||be.isThisExpression(e)||be.isMemberExpression(e)||be.isOptionalMemberExpression(e)||be.isCallExpression(e)||be.isOptionalCallExpression(e))}function rE(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(be.isMemberExpression(n)||be.isOptionalMemberExpression(n))&&be.isIdentifier(n.property)&&n.property.name==="map"&&!n.computed}function Li(e,t){let n=zt(e);if(!n)return t.isRepeatItemRoot===!0;let r=Be(n,it(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:wl(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=br(e,o);return i?RF(o,i):t.isRepeatItemRoot===!0}function oE(e,t){let n=zt(e);if(!n)return!1;let r=Be(n,it(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:wl(n,t);return o?!!o.findParent(i=>{if(!i.isCallExpression()&&!i.isOptionalCallExpression())return!1;let s=i.node.callee;return(be.isMemberExpression(s)||be.isOptionalMemberExpression(s))&&be.isIdentifier(s.property)&&s.property.name==="map"}):!1}import*as ut from"@babel/types";function Fp(e){if(ut.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(ut.isJSXMemberExpression(e)){let t=e;for(;ut.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function AF(e,t){let n=tt(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);!a||yr(a.path.node,n)||go(a,i,t)||r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=Fp(i.node.name);s&&o(s,i)}}),[...r].sort()}function Dp(e,t,n){let r=zt(e);if(!r)return{ok:!0};let o=Be(r,it(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=Be(r,it(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};let s=Ss(o.match.path,i.match.path);if(Tl(s,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let a=AF(s,i.match.path);return a.length>0?{ok:!1,bindingNames:a}:{ok:!0}}function sE(e){let t=e;for(;ut.isTSQualifiedName(t);)t=t.left;return ut.isIdentifier(t)?t.name:null}function ua(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function Dl(e){let t=[],n=r=>{if(r){if(ut.isIdentifier(r)){t.push(r.name);return}if(ut.isObjectPattern(r)){for(let o of r.properties){if(ut.isRestElement(o)){n(o.argument);continue}ut.isObjectProperty(o)&&n(o.value)}return}if(ut.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(ut.isAssignmentPattern(r)){n(r.left);return}if(ut.isRestElement(r)){n(r.argument);return}ut.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function Mp(e,t){let n=tt(e.node),r=tt(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=iE(e),i=iE(t);if(!o||!i||!HS(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=GS(s.node,n);if(a&&!Tn(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=tt(s.node.right);if(a&&Tn(a,n)&&!Tn(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())&&rE(s)){let a=tt(s.node.body)??tt(s.node);if(a&&!Tn(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 iE(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?tt(t.node.argument):null;if(t.isArrowFunctionExpression()&&(ut.isJSXElement(t.node.body)||ut.isJSXFragment(t.node.body)||ut.isConditionalExpression(t.node.body)||ut.isLogicalExpression(t.node.body)))return tt(t.node.body);t=t.parentPath}return null}function go(e,t,n){return n.scope.getBinding(t)===e}function Bp(e,t,n,r={}){if(!r.preserveConditionalBoundary&&Tl(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=tt(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(l=>Dl(l)).map(l=>n.callbackPath.scope.getBinding(l)?.path.node).filter(Boolean)),s=new Set,a=(l,c)=>{let u=c.scope.getBinding(l);!u||yr(u.path.node,o)||i.has(u.path.node)||go(u,l,t)||s.add(l)};return e.traverse({ReferencedIdentifier(l){a(l.node.name,l)},JSXOpeningElement(l){let c=Fp(l.node.name);c&&a(c,l)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function jp(e,t,n){let r=tt(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>Dl(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return ua(e,s=>{let a=s.scope.getBinding(s.node.name);!a||yr(a.path.node,r)||o.has(a.path.node)||go(a,s.node.name,t)||i.add(s.node.name)}),i.size>0?{ok:!1,bindingNames:[...i].sort()}:{ok:!0}}function aE(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>Dl(a)).map(a=>e.callbackPath.scope.getBinding(a)?.path.node).filter(Boolean)),r=new Set,o=(a,l)=>{let c=l.scope.getBinding(a);!c||n.has(c.path.node)||go(c,a,t)||r.add(a)},i=e.callbackPath.get("params"),s=Array.isArray(i)?i:[i];for(let a of s)a.traverse({ReferencedIdentifier(l){o(l.node.name,l)},TSTypeReference(l){let c=l.node.typeName;if(Fi.isIdentifier(c))o(c.name,l);else{let u=sE(c);u&&o(u,l)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function $p(e,t){let n=tt(e.node),r=new Set;return ua(e,o=>{let i=o.scope.getBinding(o.node.name);i&&(n&&yr(i.path.node,n)||go(i,o.node.name,t)||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 cE(e){let t=[];for(let n of e.callbackPath.node.params){if(Fi.isIdentifier(n)){t.push(n.name);continue}if(Fi.isRestElement(n)&&Fi.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 lE(e,t){return{...e,callbackParams:t}}function Up(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function da(e,t,n,r){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"&&!r?.allowUpstreamBindingRemoval?"Cannot edit upstream-bound node structure with a generic node operation":null}function uE(e,t,n,r){return e.parentKey===t.key&&e.file===t.file&&n?.kind==="value-binding"&&n.file!==e.file&&n.sourceKind!=="repeat-template"&&r?.finalSource?.kind!=="component-prop"}function Go(e){return{file:e.file,component:e.component}}function wF(e){return e.target.kind==="node"?e.target.key:null}function TF(e){return"kind"in e&&e.kind==="page-composition"}function jl(e){return typeof e=="object"&&e!==null&&"kind"in e&&e.kind==="block-boundary"}function Ml(e){return!TF(e)&&!jl(e)}function zp(e,t){let n=Ul.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Ul.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Vp(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=ur(n,it(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function Hp(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 OF(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function LF(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 Kp(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function FF(e){let t=FS(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=Mp(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=DF({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=bE(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?Fl(o):!0}}}function DF(e){let t=tt(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||yr(a.path.node,t))return;let l=jF(s,a,t);if(l){if(l.hasDefault){o="Cannot move prop-backed repeat child because the collection prop has a default value that cannot be preserved safely";return}let c=UF(e.callSitePath,l.propName,e.source);if(!c.ok){o=c.reason;return}let u=MF(c.expression,l.remainingPath);if(!u){o="Cannot move prop-backed repeat child because the mapped prop path is not a portable expression";return}let d=$p(c.expressionPath,e.targetParentPath);if(!d.ok){o=d.reason??`Cannot move prop-backed repeat child because the mapped prop source is not visible at the target: ${d.bindingNames.join(", ")}`;return}n.set(`${l.range.start}:${l.range.end}`,{...l.range,text:u});return}go(a,s.node.name,e.targetParentPath)||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:VF(e.source,t,[...n.values()])}}function MF(e,t){if(t.length===0)return e;let n=bE(e);if(!n)return null;let r=Fl(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=BF(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function BF(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function jF(e,t,n){let r=$F(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=Pi(t,o);if(!i)return null;let s=r?.range??tt(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function $F(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!yr(n.node,t)||n.node.computed||!Ye.isIdentifier(n.node.property))return null;let r=tt(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function UF(e,t,n){let r=e.get("openingElement").get("attributes");if(r.some(l=>l.isJSXSpreadAttribute()))return{ok:!1,reason:"Cannot move prop-backed repeat child through spread props; use an explicit prop mapping"};let o=r.find(l=>l.isJSXAttribute()&&Ye.isJSXIdentifier(l.node.name)&&l.node.name.name===t);if(!o?.isJSXAttribute())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not passed explicitly`};let i=o.get("value");if(!i.isJSXExpressionContainer())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not an expression`};let s=i.get("expression");if(!s.isExpression())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not a usable expression`};let a=Oi(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 VF(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 bE(e){try{let n=xE.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=Ye.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&Ye.isExpression(r)?r:null}catch{return null}}function KF(e){let t=tt(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||yr(s.path.node,t))return;let a=dE(s,e.sourceFile,e.targetFile);if(a){let l=e.targetParentPath.scope.getBinding(a.localName);if(l){let u=dE(l,e.targetFile,e.targetFile);(!u||u.moduleFile!==a.moduleFile||!JF(u.importSpec,a.importSpec))&&r.add(a.localName);return}let c=n.get(a.moduleSpecifier)??[];c.some(u=>JSON.stringify(u)===JSON.stringify(a.importSpec))||c.push(a.importSpec),n.set(a.moduleSpecifier,c);return}r.add(i.node.name)};return ua(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 JF(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 dE(e,t,n){let r=XF(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=zo(t,i),a=i.startsWith(".")?zp(n,s):i;if(r.isImportDefaultSpecifier()){let l=r.node.local.name;return{localName:l,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"default",local:l}}}if(r.isImportNamespaceSpecifier()){let l=r.node.local.name;return{localName:l,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"namespace",local:l}}}if(r.isImportSpecifier()){let l=Ye.isIdentifier(r.node.imported)?r.node.imported.name:r.node.imported.value,c=r.node.local.name;return{localName:c,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"named",imported:l,local:c===l?void 0:c}}}return null}function XF(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function fE(e,t,n,r){let o=Ap(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let l=Oi(e,a.conditionPath.node);if(!l)return{sourceJsx:r,conditionPaths:[]};let c=zF(a.conditionPath,l);if(s.push(a.conditionPath),a.kind==="logical"){i=`${c} ${a.operator} ${HF(i)}`;continue}i=a.branch==="consequent"?`${c} ? ${i} : null`:`${c} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function zF(e,t){return WF(e.node)?t:`(${t})`}function WF(e){return Ye.isIdentifier(e)||Ye.isThisExpression(e)||Ye.isSuper(e)||Ye.isMemberExpression(e)||Ye.isOptionalMemberExpression(e)||Ye.isCallExpression(e)||Ye.isOptionalCallExpression(e)||Ye.isBooleanLiteral(e)||Ye.isNumericLiteral(e)||Ye.isStringLiteral(e)||Ye.isNullLiteral(e)||Ye.isUnaryExpression(e)}function HF(e){return e.trim().startsWith("<")?e:`(${e})`}var GF={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 Bl(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=GF[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 YF(e,t){for(let n of e.program.body){if(!Ye.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>Ye.isImportDefaultSpecifier(o));if(r&&Ye.isImportDefaultSpecifier(r))return r.local.name}return null}function ZF(e,t,n){for(let r of e.program.body){if(!Ye.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>Ye.isImportSpecifier(i)&&(Ye.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&Ye.isImportSpecifier(o))return o.local.name}return null}function pE(e){let t=new Set;return rr(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function mE(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function qF(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=Hp(e),o=zt(t);if(n.exportName!=="default"){let a=o?ZF(o,n.source,n.exportName):null;if(a)return{localName:a};let l=o?mE(r,pE(o)):r;return{localName:l,importStep:Jp(e,l)}}if(!o)return{localName:r,importStep:Jp(e,r)};let i=YF(o,n.source);if(i)return{localName:i};let s=mE(r,pE(o));return{localName:s,importStep:Jp(e,s)}}function QF(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??Hp(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 eD(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?tD(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function tD(e){return Object.fromEntries(Object.entries(e).filter(t=>Wp(t[1])))}function Wp(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(Wp):typeof e=="object"?Object.values(e).every(Wp):!1}function Jp(e,t=Hp(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 gE(e,t){if("kind"in e)return{parentNode:null,anchorNode:null,placement:e.relation};if(e.relation==="prepend"||e.relation==="append"){let o=t.getNode(e.parentKey);return{parentNode:o,anchorNode:null,placement:e.relation,...o?{}:{error:{errorCode:"locator-miss",reason:`Target parent '${e.parentKey}' not found in graph`}}}}if(!("anchorKey"in e))return{parentNode:null,anchorNode:null,placement:e.relation,error:{errorCode:"invalid-target",reason:`Sibling target '${e.relation}' requires an anchor`}};let n=t.getNode(e.anchorKey),r=t.getNode(e.parentKey);return n?r?n.parentKey!==r.key?{parentNode:r,anchorNode:n,placement:e.relation,error:{errorCode:"invalid-target",reason:`Target anchor '${n.key}' belongs to parent '${n.parentKey??"<root>"}', expected '${r.key}'`}}:{parentNode:r,anchorNode:n,placement:e.relation}:{parentNode:null,anchorNode:n,placement:e.relation,error:{errorCode:"locator-miss",reason:`Target parent '${e.parentKey}' not found in graph`}}:{parentNode:r,anchorNode:null,placement:e.relation,error:{errorCode:"locator-miss",reason:`Target anchor '${e.anchorKey}' not found in graph`}}}function nD(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function Di(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function Gp(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function fa(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:Gp(e,t.slice(0,n)),index:r.index}}return null}function Xp(e,t){return e.locator?e.collectionPathMap?.[t]?Gp(e.locator,e.collectionPathMap[t]):fa(e.locator)?oD(e.locator,iD(t,e.collectionIndexMap)):null:null}function rD(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:SE(o,t)}function SE(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=SE(r,t);return o===void 0?void 0:{[n.name]:o}}function oD(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},Gp(e,i)}return null}function iD(e,t){return t?.[e]??e}function hE(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 sD(e,t){return aD(e.root,t.root)&&lD(e.path??[],t.path??[])}function aD(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&&cD(e.sourceRange,t.sourceRange)}}function cD(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function lD(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 $l=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:Di(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:Di(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:Di(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:Di(t.kind,t.params.kind)};let r=t;if(jl(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page-block boundaries require the page-block resolver"};if(!Ml(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=gE(r.params.position,this.graph);if(o.error)return{ok:!1,errorCode:o.error.errorCode,reason:o.error.reason};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:Di(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"set-link-target":{if(t.params.kind!=="set-link-target")return{ok:!1,errorCode:"invalid-params",reason:Di(t.kind,t.params.kind)};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.planSetLinkTarget(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=wF(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):yE(i)}async planSetLinkTarget(t,n,r){if(r.tag!=="a"&&!(r.importedFrom==="next/link"&&r.exportName==="default"))return{ok:!1,errorCode:"capability-denied",reason:"Only native anchors and source-verified next/link nodes can be changed"};if(r.structuralPath.includes("#repeat:")||r.isRepeatRegion||r.isRepeatItemRoot)return{ok:!1,errorCode:"capability-denied",reason:"Link target changes are not supported inside repeat templates"};if(n.selectionRef?.instanceIndex!==void 0||(n.selectionRef?.instanceCount??1)>1)return{ok:!1,errorCode:"capability-denied",reason:"Link target changes require a single non-repeated selection"};if(n.params.changes.length>0){let o=await this.buildTypedPropertySteps({node:r,scope:"selection",changes:n.params.changes,selectionRef:n.selectionRef});if(!o.ok)return yE(o);if(o.steps.some(i=>i.type!=="set-property-changes"||i.file!==r.file))return{ok:!1,errorCode:"capability-denied",reason:"Link descriptions must have a direct, unique source in the selected file"}}return this.buildPlan(t,n,[{type:"set-link-target",order:0,file:r.file,locator:it(r),link:n.params.link,changes:n.params.changes}],this.graph.getCapability(r.key))}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?eE({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[l,c]of Object.entries(o)){if(c===void 0)continue;let u=await this.graph.getElementPropertyWriteTarget?.(r.key,l),d=r.attributes?.find(m=>m.name===l);if((await this.graph.getPropertyState?.(r.key,l,i))?.status==="blocked"||!u&&d?.source)return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite a derived or unresolved property '${l}'`};if(!(typeof d?.resolvedValue=="string"&&d.resolvedValue===c||d?.source===null&&d.value===c)){if(u?.kind==="external-entry")return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite readonly external property '${l}'`};if(u?.kind==="value-binding"&&u.locator){let m=u.locator;if(u.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let g=Xp(u,i.instanceIndex);if(!g)return{ok:!1,errorCode:"invalid-params",reason:"apply-style-draft could not resolve the selected repeat item"};m=g}s.push({order:n+s.length,file:u.file,type:"update-value",locator:m,value:c});continue}a.push({operation:"set",name:l,value:c})}}return a.length>0&&s.push({order:n+s.length,file:r.file,type:"set-property-changes",locator:it(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=Xp(o,i.instanceIndex);if(!a)return{ok:!1,errorCode:"invalid-params",reason:"update-text could not resolve the selected repeat item"};let l=this.coerceTextValueForValueTarget(o.file,a,r);return l.ok?{ok:!0,steps:[{order:0,file:o.file,type:"update-array-item",locator:a,value:l.value}]}:l}let s=this.coerceTextValueForValueTarget(o.file,o.locator,r);return s.ok?{ok:!0,steps:[{order:0,file:o.file,type:"update-value",locator:o.locator,value:s.value}]}:s}return{ok:!0,steps:o?.kind==="external-entry"?[{order:0,file:`external:${o.sourceId}`,type:"invoke-external-adapter",sourceType:o.sourceType,sourceId:o.sourceId,adapterId:o.adapterId,capability:"write-text",value:r}]:[{order:0,file:t.file,type:"update-text",locator:it(t),segmentIndex:n,newText:r}]}}coerceTextValueForValueTarget(t,n,r,o="update-text"){let i=this.graph.getFileContent(t),s=zt(i);if(!s)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not inspect the value source`};let a=Be(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!OF(a.match.path))return{ok:!0,value:r};let l=LF(r);return l===null?{ok:!1,errorCode:"invalid-params",reason:`${o} value must be a valid number for numeric source`}:{ok:!0,value:l}}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 l=Xp(o,i);if(!l)return{ok:!1,errorCode:"invalid-params",reason:"update-array-item could not resolve the selected repeat item"};let c=this.coerceTextValueForValueTarget(o.file,l,s,"update-array-item");return c.ok?this.isValueTargetUnchanged(o.file,l,c.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:l,value:c.value}],r):c}isValueTargetUnchanged(t,n,r){let o=zt(this.graph.getFileContent(t));if(!o)return!1;let i=Be(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){let s=this.graph.getTextProvenance?.(r.key,n.params.segmentIndex);if(s&&(s.editMode==="readonly"||s.editMode==="unsupported"))return{ok:!1,errorCode:"unsupported-operation",reason:"Text has no identity-preserving write target"};if(!o.canUpdateText)return{ok:!1,errorCode:"capability-denied",reason:"Cannot update text on this node"};let a=this.buildTextRewriteSteps(r,n.params.segmentIndex,n.params.value,i,n.selectionRef);return a.ok?this.buildPlan(t,n,a.steps,o):a}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 f=fa(d.locator);if(f)return this.buildPlan(t,n,[{order:0,file:d.file,type:"remove-bound-array-item",locator:f.locator,index:f.index}],o)}return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed node removal requires a writable array target"}}let s=da(r,i,this.graph.getTextProvenance?.(r.key,0)??null,{allowUpstreamBindingRemoval:!0});if(s)return{ok:!1,errorCode:"unsupported-operation",reason:s};let a=this.getRepeatBackedTemplateStructureReason(r);if(a)return{ok:!1,errorCode:"unsupported-operation",reason:a};let l=await this.getUpstreamBackedDescendantReason(r,{allowUpstreamBindingRemoval:!0});if(l)return{ok:!1,errorCode:"unsupported-operation",reason:l};let c=[{order:0,file:r.file,type:"remove-node",locator:it(r),removeWhitespace:!0}],u=this.buildRemoveComponentImportStep(r);return u&&c.push({...u,order:c.length}),this.buildPlan(t,n,c,o)}buildRemoveComponentImportStep(t,n=this.graph.getFileContent(t.file)){if(!t.importedFrom||!t.exportName||!t.tag||WS(n,t)>1)return null;let r=zp(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(!Ml(n.params.position))return jl(n.params.position)?{ok:!1,errorCode:"unsupported-operation",reason:"Page-block boundaries require the page-block resolver"}:{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,l=da(r,a,s!==null?this.graph.getTextProvenance?.(r.key,s)??null:null);if(l)return{ok:!1,errorCode:"unsupported-operation",reason:l};let c=await this.getUpstreamBackedDescendantReason(r);if(c)return{ok:!1,errorCode:"unsupported-operation",reason:c};let u=await this.planExternalBackedInsertChild(t,n,r,o,i,a);if(u)return u;let d=await this.planRepeatBackedInsertChild(t,n,r,o);if(d)return d;let f=this.getRepeatBackedTemplateStructureReason(r);if(f)return{ok:!1,errorCode:"unsupported-operation",reason:f};let m=PS(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=Bl(r,n.params.node);if(g)return{ok:!1,errorCode:"unsupported-operation",reason:g};let p=[],h=0,x=n.params.node.kind==="component-call"?qF(n.params.node,this.graph.getFileContent(r.file)):void 0,b=x?.importStep;return b&&p.push({order:h++,file:r.file,type:"add-import",moduleSpecifier:b.moduleSpecifier,imports:b.imports}),p.push({order:h++,file:r.file,type:"insert-child",parentLocator:it(r),node:{jsx:QF(n.params.node,x?.localName)},placement:n.params.position.relation,anchorLocator:i?it(i):void 0}),this.buildPlan(t,n,p,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!Ml(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 l=i?await this.graph.getTextWriteTarget(i.key,0):null;return this.buildPlan(t,n,[{order:0,file:`external:${a.sourceId}`,type:"invoke-external-adapter",sourceType:a.sourceType,sourceId:a.sourceId,adapterId:a.adapterId,capability:"insert-child",value:{operation:"insert-child",relation:n.params.position.relation,parentKey:r.key,anchorSourceId:l?.kind==="external-entry"?l.sourceId:null,node:eD(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(!Ml(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 l=fa(a.locator);if(!l)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let c=rD(a.locator,i.text);if(c===void 0)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child could not infer an item shape from the template"};let u=n.params.position.relation==="prepend"?hE(0,a.collectionIndexMap):hE(a.collectionIndexMap?.length??l.index+1,a.collectionIndexMap);return this.buildPlan(t,n,[{order:0,file:a.file,type:"insert-bound-array-item",locator:l.locator,index:u,value:c}],o)}async getUpstreamBackedDescendantReason(t,n){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=this.graph.getEditableTextSegmentIndex(o.key),s=i!==null?await this.graph.getTextWriteTarget(o.key,i):null,a=da(o,s,i!==null?this.graph.getTextProvenance?.(o.key,i)??null:null,n);if(a)return a;r.push(...this.graph.getChildNodes(o.key))}return null}getRepeatBackedTemplateStructureReason(t){if(t.isRepeatItemRoot)return Li(this.graph.getFileContent(t.file),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:")||oE(this.graph.getFileContent(t.file),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}planRepeatTemplateInternalMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&Li(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let l=this.graph.getFileContent(r.file),c=zt(l);if(!c)return null;let u=Hn(c,r),d=Hn(c,o);if(!u||!d)return null;let f=br(l,u),m=br(l,d);if(!la(f,m))return null;if(a&&(s==="before"||s==="after")){let p=Hn(c,a),h=p?br(l,p):null;if(!la(f,h))return null}if(Ol(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let g=Dp(l,r,o);return g.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:it(r),targetParentLocator:it(o),placement:s,anchorLocator:a?it(a):void 0,selectionContext:Go(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&&Li(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let l=this.graph.getFileContent(r.file),c=zt(l);if(!c)return null;let u=Hn(c,r),d=Hn(c,o);if(!u||!d)return null;let f=br(l,u);if(!f)return null;let m=br(l,d);if(la(f,m))return null;if(m&&!nE(m,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")){let S=Lp(l,c,a);if(m&&!la(m,S)||!m&&S)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 S=Bl(o,{kind:"native-tag",tag:r.tag});if(S)return{ok:!1,errorCode:"unsupported-operation",reason:S}}let g=Vp(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(Ol(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let p=fE(l,u,d,g);for(let S of p.conditionPaths){let E=jp(S,d,f);if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${E.bindingNames.join(", ")}`}}let h=Bp(u,d,f,{preserveConditionalBoundary:p.conditionPaths.length>0});if(!h.ok)return{ok:!1,errorCode:"unsupported-operation",reason:h.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${h.bindingNames.join(", ")}`};let x=aE(f,d);if(!x.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its callback parameters depend on bindings outside the target scope: ${x.bindingNames.join(", ")}`};let b=f;if(r.component!==o.component){let S=FF({source:l,ast:c,sourceContext:f,sourceNode:r,targetParent:o,targetParentPath:d});if(!S.ok)return{ok:!1,errorCode:"unsupported-operation",reason:S.reason};b=S.context}else{let S=$p(f.collectionPath,d);if(!S.ok)return{ok:!1,errorCode:"unsupported-operation",reason:S.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${S.bindingNames.join(", ")}`}}return this.buildPlan(t,n,[{order:0,file:r.file,type:"move-repeat-template-child",locator:it(r),targetParentLocator:it(o),placement:s,anchorLocator:a?it(a):void 0,repeatExpression:Up(b,p.sourceJsx),selectionContext:Go(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&Li(this.graph.getFileContent(r.file),r)||r.file===o.file)return null;let l=this.graph.getFileContent(r.file),c=this.graph.getFileContent(o.file),u=zt(l),d=zt(c);if(!u||!d)return null;let f=YS({knownSourceFiles:this.graph.getKnownSourceFiles?.(),routeEntryFiles:this.graph.getRouteEntryFiles?.(),sourceAst:u,sourceFile:r.file,targetFile:o.file,sourceComponent:r.component,targetComponent:o.component});if(!f.ok)return{ok:!1,errorCode:"unsupported-operation",reason:f.reason};let m=Hn(u,r),g=Hn(d,o);if(!m||!g)return null;let p=Mp(f.callSitePath,g);if(!p.ok)return{ok:!1,errorCode:"unsupported-operation",reason:p.reason};let h=br(l,m);if(!h)return null;if(br(c,g))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")&&Lp(c,d,a))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child relative to a repeat-template anchor outside the target scope"};if(r.tag&&r.tag.toLowerCase()===r.tag){let C=Bl(o,{kind:"native-tag",tag:r.tag});if(C)return{ok:!1,errorCode:"unsupported-operation",reason:C}}let b=Vp(this.graph,r);if(!b)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Ol(m,g))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let S=fE(l,m,g,b);for(let C of S.conditionPaths){let O=jp(C,g,h);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 E=Bp(m,g,h,{preserveConditionalBoundary:S.conditionPaths.length>0});if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:E.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${E.bindingNames.join(", ")}`};let v=KF({sourceFile:r.file,targetFile:o.file,sourceContext:h,targetParentPath:g});if(!v.ok)return{ok:!1,errorCode:"unsupported-operation",reason:v.reason};let N=cE(h);if(!N.ok)return{ok:!1,errorCode:"unsupported-operation",reason:N.reason};let I=lE(h,N.callbackParams),A=[{order:0,file:r.file,type:"remove-node",locator:it(r),removeWhitespace:!0}];for(let C of v.imports)A.push({order:A.length,file:o.file,type:"add-import",moduleSpecifier:C.moduleSpecifier,imports:C.imports});return A.push({order:A.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:it(o),expression:Up(I,S.sourceJsx),placement:s,anchorLocator:a?it(a):void 0,selectionContext:Go(o)}),this.buildPlan(t,n,A,i)}async planMoveNode(t,n,r,o){if(!o.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};if(jl(n.params.target))return{ok:!1,errorCode:"unsupported-operation",reason:"Page-block boundaries require the page-block resolver"};if("kind"in n.params.target&&n.params.target.kind==="source-sibling"){let S=n.params.target,E=this.graph.getNode(S.anchorKey);if(!E||r.file!==E.file||r.component!==E.component)return{ok:!1,errorCode:"locator-miss",reason:"Source sibling move requires a sibling in the same component file"};let v=this.graph.getFileVersion(r.file);if(n.documentVersion!==v)return{ok:!1,errorCode:"stale-version",reason:`Document version ${n.documentVersion} is stale or otherwise does not match source sibling file version (current: ${v})`};let N=this.graph.getFileContent(r.file),I=zt(N),A=I?Hn(I,r):null,C=I?Hn(I,E):null,O=A?.parentPath,L=C?.parentPath;if(!A||!C||!O||!L||O.node!==L.node||!O.isJSXFragment()&&!(O.isJSXElement()&&ht(O)))return{ok:!1,errorCode:"unsupported-operation",reason:"Source sibling move requires two direct children of the same transparent Fragment"};let X=O.node.loc;return X?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:it(r),targetParentLocator:{kind:"jsx-node",strategy:"source-range",sourceRange:{startLine:X.start.line,startColumn:X.start.column,endLine:X.end.line,endColumn:X.end.column}},placement:S.relation,anchorLocator:it(E),selectionContext:Go(r)}],o):{ok:!1,errorCode:"locator-miss",reason:"Source Fragment has no stable source range"}}let i=gE(n.params.target,this.graph);if(i.error)return{ok:!1,errorCode:i.error.errorCode,reason:i.error.reason};let s=i.parentNode;if(!s)return{ok:!1,errorCode:"locator-miss",reason:`Target parent for request '${n.id}' not found in graph`};let a=this.graph.getFileVersion(s.file);if(n.documentVersion!==a)return{ok:!1,errorCode:"stale-version",reason:`Document version ${n.documentVersion} is stale or otherwise does not match target parent version (current: ${a})`};if(nD(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 l=await this.graph.getTextWriteTarget(r.key,0);if(l?.kind==="external-entry"){let S=n.params.target.relation,E=i.anchorNode&&(S==="before"||S==="after")?await this.graph.getTextWriteTarget(i.anchorNode.key,0):null;return this.buildPlan(t,n,[{order:0,file:`external:${l.sourceId}`,type:"invoke-external-adapter",sourceType:l.sourceType,sourceId:l.sourceId,adapterId:l.adapterId,capability:"move-node",value:{operation:"move-node",relation:S,anchorSourceId:E?.kind==="external-entry"?E.sourceId:null,parentKey:"parentKey"in n.params.target?n.params.target.parentKey:null}}],o)}let c=r.file!==s.file,u=n.params.target.relation,d=i.anchorNode,f=this.graph.getTextProvenance?.(r.key,0)??null,m=da(r,l,f);if(m&&!Kp(m)&&!uE(r,s,l,f))return{ok:!1,errorCode:"unsupported-operation",reason:m};if(r.isRepeatItemRoot&&d?.isRepeatItemRoot&&r.repeatOwnerKey&&r.repeatOwnerKey===d.repeatOwnerKey&&(u==="before"||u==="after")){let S=l,E=await this.graph.getTextWriteTarget(d.key,0);if(S?.kind==="value-binding"&&E?.kind==="value-binding"&&S.locator&&E.locator){let v=fa(S.locator),N=fa(E.locator);if(v&&N&&S.file===E.file&&sD(v.locator,N.locator)){let I=v.index,A=N.index,C=u==="before"?A-(I<A?1:0):A+(I<A?0:1);return this.buildPlan(t,n,[{order:0,file:S.file,type:"move-array-item",locator:v.locator,fromIndex:I,toIndex:C}],o)}}}if(r.isRepeatItemRoot&&Li(this.graph.getFileContent(r.file),r))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed item outside its collection"};let g=this.getRepeatBackedTemplateStructureReason(r),p=Kp(m)?m:g;if(p&&Kp(p)){let S=this.planRepeatTemplateInternalMove(t,n,r,s,o,u,d);if(S)return S;let E=this.planRepeatTemplateHoistMove(t,n,r,s,o,u,d);if(E)return E;let v=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,u,d);return v||{ok:!1,errorCode:"unsupported-operation",reason:p}}if(g)return{ok:!1,errorCode:"unsupported-operation",reason:g};let h=await this.getUpstreamBackedDescendantReason(r);if(h)return{ok:!1,errorCode:"unsupported-operation",reason:h};if(r.tag&&r.tag.toLowerCase()===r.tag){let S=Bl(s,{kind:"native-tag",tag:r.tag});if(S)return{ok:!1,errorCode:"unsupported-operation",reason:S}}if(c)return this.planCrossFileMove(t,n,r,s,o,u,d);let x=Dp(this.graph.getFileContent(r.file),r,s);if(!x.ok)return{ok:!1,errorCode:"unsupported-operation",reason:x.reason??`Cannot move node because it depends on bindings outside the target scope: ${x.bindingNames.join(", ")}`};let b=[{order:0,file:r.file,type:"move-node",locator:it(r),targetParentLocator:it(s),placement:u,anchorLocator:d?it(d):void 0,selectionContext:Go(s)}];return this.buildPlan(t,n,b,o)}planCrossFileMove(t,n,r,o,i,s,a){let l=[],c=0,u=this.graph.getFileContent(r.file),d=Vp(this.graph,r)??`<${r.component} />`,f=NS(u,r);if(!f.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:f.reason??"Cannot move subtree across files"};if(l.push({order:c++,file:r.file,type:"remove-node",locator:it(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let g=r.tag??r.component,h={moduleSpecifier:zp(o.file,r.importedFrom),imports:r.exportName==="default"?[{kind:"default",local:g}]:[{kind:"named",imported:r.exportName,local:g===r.exportName?void 0:g}]};l.push({order:c++,file:o.file,type:"add-import",moduleSpecifier:h.moduleSpecifier,imports:h.imports}),l.push({order:c++,file:o.file,type:"insert-child",parentLocator:it(o),node:{jsx:d},placement:s,anchorLocator:a?it(a):void 0,selectionContext:Go(o)})}else l.push({order:c++,file:o.file,type:"insert-child",parentLocator:it(o),node:{jsx:d},placement:s,anchorLocator:a?it(a):void 0,selectionContext:Go(o)});let m=this.buildRemoveComponentImportStep(r,u);return m&&l.push({...m,order:c++}),this.buildPlan(t,n,l,i)}buildPlan(t,n,r,o){let s=[...new Set(r.map(a=>a.file))].map(a=>({file:a,content:this.graph.getFileContent(a),version:this.graph.getFileVersion(a),exists:!0,sha256:$e(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 yE(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 nm from"@babel/generator";import{parse as vD,parseExpression as kD}from"@babel/parser";import*as k from"@babel/types";import*as Sr from"@babel/types";import Yp from"@babel/generator";import*as ct from"@babel/types";var uD=typeof Yp=="function"?Yp:Yp.default,dD=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,fD=/^((?:https?:)?\/\/)[^/@\s]+@/i,pD=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function IE(e,t){let n=On(e.callee);if(!n)return null;if(n==="fetch")return Zp(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(EE(r))return Zp(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(EE(r))return Zp(e.arguments[0],r,t,["ky client contract"])}return null}function Zp(e,t,n,r){if(!e||ct.isSpreadElement(e)||ct.isJSXNamespacedName(e))return yD(t,n,r,"missing url argument");let o=pa(e);return{sourceKind:hD(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 pa(e){if(ct.isStringLiteral(e))return Yo(e.value);if(ct.isTemplateLiteral(e))return Yo(mD(e));if(ct.isBinaryExpression(e)&&e.operator==="+"){let t=pa(e.left),n=pa(e.right);return!t&&!n?void 0:Yo(`${t??qp(e.left)}${n??qp(e.right)}`)}if(ct.isMemberExpression(e)){let t=vE(e);if(t)return`env:${t}`}if(!(ct.isCallExpression(e)&&On(e.callee)==="new URL")){if(ct.isNewExpression(e)&&ct.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!ct.isSpreadElement(t)?pa(t):void 0,o=n&&!ct.isSpreadElement(n)?pa(n):void 0;return o&&r?Yo(`${o} + ${r}`):r??o}if(ct.isIdentifier(e))return`:${e.name}`}}function mD(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+=qp(r))}return t}function qp(e){if(ct.isIdentifier(e))return`:${e.name}`;if(ct.isMemberExpression(e)){let t=vE(e);if(t)return`env:${t}`}return`:${gD(e)}`}function gD(e){return uD(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function Yo(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(fD,"$1<redacted>@").replace(pD,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?dD.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function hD(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 yD(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function EE(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function vE(e){return!ct.isMemberExpression(e.object)||!ct.isIdentifier(e.object.object,{name:"process"})||!xD(e.object.property,"env")?null:ct.isIdentifier(e.property)?e.property.name:ct.isStringLiteral(e.property)?e.property.value:null}function xD(e,t){return ct.isIdentifier(e)&&e.name===t}function On(e){if(ct.isIdentifier(e))return e.name;if(ct.isMemberExpression(e)){let t=On(e.object),n=ct.isIdentifier(e.property)?e.property.name:ct.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var bD=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),SD=new Set(["getConfig","submit"]);function jr(e,t){let n=kE(On(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!bD.has(i))return null;let s=Qp(e,0),a=i==="getByUrl"||i==="getByUrlStrict",l=a?void 0:s,c=a?s??"/:record-url":l?`/collections/${l}`:"/collections/:collection";return{sourceKind:"vcp-cms-collection",sourceType:"cms-field",operation:i,...l?{collection:l}:{},endpointPattern:c,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(!SD.has(i))return null;let s=Qp(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=Qp(e,0)??ED(e,0,"path")??"/cms/:path",s=ID(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 kE(e,t){if(!e)return null;let n=e.indexOf("."),r=n<0?e:e.slice(0,n),o=n<0?"":e.slice(n),i=t.imports?.get(r);return i?i.importedName==="cms"&&/^(?:src\/)?lib\/cms(?:\/index)?\.[cm]?[jt]s$/.test(i.source)?`cms${o}`:i.importedName==="collections"&&/^(?:src\/)?lib\/cms\/collections\.[cm]?[jt]s$/.test(i.source)?`cms.collections${o}`:!o&&["cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(i.importedName)&&/^(?:src\/)?lib\/cms\/client\.[cm]?[jt]s$/.test(i.source)?i.importedName:null:null}function _E(e,t){let n=On(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 Vl(e,t){let n=On(e.callee),r=t?kE(n,t):n;return typeof r=="string"&&r.startsWith("cms.field.")}function Qp(e,t){let n=e.arguments[t];return Sr.isStringLiteral(n)?n.value:null}function ED(e,t,n){let r=e.arguments[t];if(!Sr.isObjectExpression(r))return null;for(let o of r.properties)if(Sr.isObjectProperty(o)&&!o.computed&&(Sr.isIdentifier(o.key)&&o.key.name===n||Sr.isStringLiteral(o.key)&&o.key.value===n)&&Sr.isStringLiteral(o.value))return o.value.value;return null}function ID(e){let t=/^\/collections\/([^/]+)(?:\/|$)/.exec(e)?.[1];return t&&/^[a-z0-9][a-z0-9_-]*$/i.test(t)?t:null}function Kl(e){return e.match(/^\/([a-z0-9][a-z0-9_-]*)\/[^/?#]+(?:[?#].*)?$/i)?.[1]??null}import*as jt from"@babel/types";var em=new WeakMap;function Er(e,t){let n=em.get(e)?.get(t);if(n!==void 0)return n;let r=new Set([t]),o=c=>{let u=c;for(;jt.isMemberExpression(u)||jt.isOptionalMemberExpression(u);)u=u.object;return jt.isIdentifier(u)?u.name:null},i=!0;for(;i;)i=!1,jt.traverseFast(e,c=>{if(!jt.isVariableDeclarator(c)||!c.init)return;let u=o(c.init);if(!(!u||!r.has(u)))for(let d of Object.keys(jt.getBindingIdentifiers(c.id)))r.has(d)||(r.add(d),i=!0)});let s=c=>{let u=o(c);return u?r.has(u):Object.keys(jt.getBindingIdentifiers(c)).some(d=>r.has(d))},a=!1;jt.traverseFast(e,c=>{(jt.isAssignmentExpression(c)&&s(c.left)||jt.isUpdateExpression(c)&&s(c.argument)||jt.isUnaryExpression(c,{operator:"delete"})&&s(c.argument))&&(a=!0)});let l=em.get(e)??new Map;return l.set(t,a),em.set(e,l),a}function CE(e=4096){if(!Number.isSafeInteger(e)||e<1)throw new RangeError("Re-export relation capacity must be positive.");let t=new Map,n=new Set,r=o=>{let i=t.get(o.fromFile),s=i?.get(o.exportName),a=s?.get(o.targetFile);a?.get(o.maxImportDepth)===o&&(a.delete(o.maxImportDepth),a.size===0&&s.delete(o.targetFile),s.size===0&&i.delete(o.exportName),i.size===0&&t.delete(o.fromFile),n.delete(o))};return{resolve(o,i){let{fromFile:s,exportName:a,targetFile:l,maxImportDepth:c}=o,u=t.get(s)?.get(a)?.get(l)?.get(c);if(u)return u.pending;let d=i();n.size>=e&&r(n.values().next().value);let f={fromFile:s,exportName:a,targetFile:l,maxImportDepth:c,pending:d},m=t.get(s)??new Map,g=m.get(a)??new Map,p=g.get(l)??new Map;return p.set(c,f),g.set(l,p),m.set(a,g),t.set(s,m),n.add(f),d.catch(()=>{r(f)}),d}}}import*as en from"@babel/types";import{posix as tm}from"node:path";function Mi(e,t,n=new Set){if(n.has(e))return;let r=new Set(n).add(e);if(en.isBooleanLiteral(e))return e.value;if(en.isUnaryExpression(e,{operator:"!"})){let c=Mi(e.argument,t,r);return c===void 0?void 0:!c}if(en.isLogicalExpression(e)){let c=Mi(e.left,t,r),u=Mi(e.right,t,r);if(e.operator==="&&")return c===!1||u===!1?!1:c===!0?u:void 0;if(e.operator==="||")return c===!0||u===!0?!0:c===!1?u:void 0}if(!en.isCallExpression(e)||!en.isIdentifier(e.callee))return;let o=t.imports.get(e.callee.name),i=o?.source.startsWith(".")&&t.file?tm.normalize(tm.join(tm.dirname(t.file),o.source)):o?.source;if(o?.importedName==="isProductionBuildPhase"&&/(?:^|\/)lib\/cms\/build-sample(?:\.[jt]s)?$/.test(i??""))return!1;let s=t.functions.get(e.callee.name);if(!s||n.has(s))return;let a=en.isExpression(s.body)?s.body:s.body.body.length===1&&en.isReturnStatement(s.body.body[0])?s.body.body[0].argument:null;if(!a||!en.isExpression(a))return;let l=s.params.flatMap(c=>en.isIdentifier(c)?[c.name]:[]);return Mi(a,{file:t.file,imports:new Map([...t.imports].filter(([c])=>!l.includes(c))),functions:new Map([...t.functions].filter(([c])=>!l.includes(c)))},r.add(s))}var BG=typeof nm=="function"?nm:nm.default,ME=new WeakMap;function BE(e){let t=new Map;return ME.set(t,new Map([...e].map(n=>[n.file,n]))),t}var _D={maxFunctionDepth:8,maxImportDepth:6},CD=new Set(["src","href","alt","poster","content","title","aria-label"]),RE=new WeakMap;function RD(e,t,n){let r=RE.get(t.fileCache);r||(r=new WeakMap,RE.set(t.fileCache,r));let o=r.get(e);if(!o){o={imported:[],local:new Map};let u=0;for(let d of e.elements.values()){let f={element:d,order:u++};d.importedFrom&&d.exportName&&o.imported.push(f);let m=o.local.get(d.sourceFile);m||(m=new Map,o.local.set(d.sourceFile,m));let g=m.get(d.tag)??[];g.push(f),m.set(d.tag,g)}r.set(e,o)}let i=o.local.get(t.file)?.get(n)??[],s=o.imported,a=[],l=0,c=0;for(;l<s.length||c<i.length;){let u=s[l],d=i[c];u&&(!d||u.order<d.order)?(a.push(u.element),l++):d&&(!u||d.order<u.order)?(a.push(d.element),c++):(a.push(u.element),l++,c++)}return a}async function Zl(e){if(!e.element.textSegments.some(s=>s.source||s.value.includes("("))&&!(e.element.attributes??[]).some(s=>(s.source||s.syntaxKind==="expression"&&s.resolution?.status!=="resolved")&&NE(s,e.element))&&!e.graph.regions.some(s=>s.ownerKey===e.element.identity.key&&(s.kind==="repeat-region"||s.kind==="conditional-region")))return{hasDynamicData:!1,bindings:[]};let t=e.fileCache??new Map,n=cm(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{..._D,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,paramArguments:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:nI(n,e.element.componentName),scopeFunction:lm(n,e.element.componentName)};await jE(e.element.componentName,e.graph,r);let o=[];o.push(...await wD(e.element,e.graph,r),...await TD(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await OD(s,e.element,e.graph,r);a&&o.push(...Gl(a,"text","children"))}for(let s of e.element.attributes??[]){let a=NE(s,e.element);if(!a)continue;let l=await VE(s.source,e.element,e.graph,r);if(!l&&s.syntaxKind==="expression"&&!(s.source&&Qo(s.source.base,e.element,e.graph))){let u=n.jsxElementsByRange.get(ql(e.element.sourceRange))?.openingElement.attributes.find(d=>k.isJSXAttribute(d)&&k.isJSXIdentifier(d.name,{name:s.name}));k.isJSXExpressionContainer(u?.value)&&k.isExpression(u.value.expression)&&!JE(u.value.expression,e.element,e.graph)&&(l=await xt(u.value.expression,r))}l&&o.push(...Gl(l,a,s.name))}let i=XD(o).sort(eI);return{hasDynamicData:i.length>0,bindings:i}}async function jE(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 c of RD(t,n,e)){if(c.sourceFile===n.file&&c.tag===e){s.push(c);continue}!c.importedFrom||!c.exportName||c.importedFrom===n.file&&c.exportName!==i||(c.importedFrom===n.file||await PD(c.importedFrom,c.exportName,n.file,n))&&s.push(c)}if(s.length===0)return;let a=new Map;for(let c of s){let u=`${n.file}#${e}<-${c.identity.key}`;if(!n.resolvingComponentProps.has(u)){n.resolvingComponentProps.add(u);try{let d=await UE(c.sourceFile,n);if(!d)continue;let f=xo(d,n,{importDepth:n.importDepth+1});f.paramSources.clear(),f.scopeVariables=nI(d,c.componentName),f.scopeFunction=lm(d,c.componentName),f.lexicalContext=void 0,await jE(c.componentName,t,f);let m=await ND(c,t,f);for(let[g,p]of m){if(!p)continue;let h=a.get(g)??[];h.push(p),a.set(g,h)}}finally{n.resolvingComponentProps.delete(u)}}}let l=new Map;for(let[c,u]of a){let d=tu(u),f=d.length===1?d[0]:am(d,n.file);f&&l.set(c,f)}AD(o,l,n)}var PE=new WeakMap;function PD(e,t,n,r){let o=PE.get(r.fileCache);return o||(o=CE(),PE.set(r.fileCache,o)),o.resolve({fromFile:e,exportName:t,targetFile:n,maxImportDepth:r.options.maxImportDepth},()=>$E(e,t,n,r))}async function $E(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 UE(e,r))?.imports.get(t);if(!s||!_t(s.source))return!1;let a=await dm(e,s.source,r.exists);return a?a===n?!0:$E(a,s.importedName,n,r,o):!1}async function ND(e,t,n){let r=new Map,o=n.analysis.jsxElementsByRange.get(ql(e.sourceRange));if(o)for(let s of o.openingElement.attributes)!k.isJSXAttribute(s)||!k.isJSXIdentifier(s.name)||!k.isJSXExpressionContainer(s.value)||!k.isExpression(s.value.expression)||r.set(s.name.name,s.value.expression);let i=new Map;for(let[s,a]of r){let l=e.attributes?.find(d=>d.name===s)?.source??null,u=(l?Qo(l.base,e,t):null)?await Ql(l,e,t,n):JE(a,e,t)?null:await xt(a,n);u&&i.set(s,u)}return i}function ql(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}async function UE(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 cm(e,r,t.fileCache)}function AD(e,t,n){if(k.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,Ui(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,Wt(o))}}function NE(e,t){return e.name==="dangerouslySetInnerHTML"?"richtext":CD.has(e.name)?"attribute":t.importedFrom||/^[A-Z]/.test(t.tag)?"component-prop":null}async function wD(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 eu(i.collectionSource,n);s&&r.push(...Gl(Ur(s),"repeat-region",i.collectionExpression))}return r}async function TD(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 eu(i.conditionSource,n);s&&r.push(...Gl(Ur(s),"conditional-region",i.conditionExpression))}return r}async function OD(e,t,n,r){if(!e.source){let i=r.analysis.jsxElementsByRange.get(ql(t.sourceRange))?.children.find(s=>k.isJSXExpressionContainer(s)&&s.loc?.start.line===e.sourceRange.startLine&&s.loc.start.column===e.sourceRange.startColumn&&s.loc.end.line===e.sourceRange.endLine&&s.loc.end.column===e.sourceRange.endColumn);return k.isJSXExpressionContainer(i)&&k.isCallExpression(i.expression)&&Vl(i.expression)?KE(i.expression,t,n,r):null}return VE(e.source,t,n,r)}async function VE(e,t,n,r){return e&&Qo(e.base,t,n)?Ql(e,t,n,r):eu(e,r)}async function Ql(e,t,n,r,o){if(!e)return null;let i=Qo(e.base,t,n,o);if(!i||i.candidate.itemParamName!==e.base)return null;let s=i.candidate.collectionSource,l=(s?Qo(s.base,t,n,i.region):null)?await Ql(s,t,n,r,i.region):s?await eu(s,r):await LD(i.candidate.collectionExpression,t,n,r,i.region);return l?$i(l,e.path,!0):null}async function LD(e,t,n,r,o){let i;try{i=kD(e,{plugins:["typescript","jsx"]})}catch{return null}return KE(i,t,n,r,o)}async function KE(e,t,n,r,o){let i=xo(r.analysis,r),s=new Set;k.traverseFast(e,a=>{k.isIdentifier(a)&&s.add(a.name)});for(let a of s){let l=Qo(a,t,n,o);if(!l)continue;if(l.candidate.itemParamName!==a)return null;let c=await Ql({kind:"identifier",expression:a,base:a,path:[]},t,n,r,o);if(!c)return null;i.paramSources.set(a,c)}return xt(e,i)}function Qo(e,t,n,r){let o=t.identity.key,i=null;for(;o;){for(let s of n.regions){if(s.kind!=="repeat-region"||!s.childKeys.includes(o)||r&&!AE(s.sourceRange,r.sourceRange))continue;let a=s.sourceCandidates?.find(l=>l.kind==="repeat-template"&&(l.itemParamName===e||l.indexParamName===e));a&&(!i||AE(i.region.sourceRange,s.sourceRange))&&(i={candidate:a,region:s})}o=n.elements.get(o)?.parentKey??null}return i}function AE(e,t){let n=e.startLine-t.startLine||e.startColumn-t.startColumn,r=e.endLine-t.endLine||e.endColumn-t.endColumn;return n<=0&&r>=0&&(n<0||r>0)}function JE(e,t,n){let r=!1;return k.traverseFast(e,o=>{!r&&k.isIdentifier(o)&&Qo(o.name,t,n)&&(r=!0)}),r}async function eu(e,t){if(!e)return null;let n=await im(e.base,t);return n?$i(n,e.path,!1):null}async function im(e,t){let n=t.paramSources.get(e);if(n)return Wt(n);if(t.variableCache.has(e))return zD(t.variableCache.get(e)??null);let r=yo(e,t);if(r&&r!==t)return im(e,r);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let o=await DD(e,t);if(o)return t.variableCache.set(e,Wt(o)),t.resolvingVariables.delete(e),o;let i=t.scopeVariables?.has(e),s=i?t.scopeVariables.get(e):r?null:t.analysis.variables.get(e);if(s){let l=k.isArrayExpression(s)&&s.elements.length===0?await FD(e,t):await xt(s,t);return t.variableCache.set(e,l?Wt(l):null),t.resolvingVariables.delete(e),l}if(i||r)return t.resolvingVariables.delete(e),t.variableCache.set(e,null),null;let a=t.analysis.imports.get(e);if(a&&t.importDepth<t.options.maxImportDepth){let l=await um(a,t);if(l){let c=xo(l,t,{importDepth:t.importDepth+1}),u=rI(a,l);if(u){let m=(await Zo(u,[],c)).returnSource;return t.variableCache.set(e,m?Wt(m):null),t.resolvingVariables.delete(e),m}let d=l.variables.get(a.importedName);if(d){let f=await xt(d,c);return t.variableCache.set(e,f?Wt(f):null),t.resolvingVariables.delete(e),f}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}function yo(e,t){return t.scopeVariables?.has(e)||t.scopeFunction?.params.some(n=>ho(n).includes(e))?t:t.lexicalContext?yo(e,t.lexicalContext):void 0}function Jl(e,t,n=new Set){if(k.isIdentifier(e)){let s=yo(e.name,t);if(s&&s!==t)return Jl(e,s,n)}if(n.has(e))return null;if(n.add(e),k.isStringLiteral(e))return e.value;if(!k.isIdentifier(e))return null;let r=yo(e.name,t),o=t.paramArguments.get(e.name);if(o)return Jl(o.expression,o.context,n);let i=t.scopeVariables?.has(e.name)?t.scopeVariables.get(e.name):r?null:t.analysis.variables.get(e.name);return i?Jl(i,t,n):null}function Ir(e,t,n=new Set){if(n.has(e))return null;let r=new Set(n).add(e);if(k.isStringLiteral(e))return e.value;if(k.isNumericLiteral(e))return String(e.value);if(k.isIdentifier(e)){if(/token|secret|password|authorization|cookie|credential/i.test(e.name))return":redacted";let o=yo(e.name,t),i=o??t,s=i.paramArguments.get(e.name),a=i.scopeVariables?.has(e.name)?i.scopeVariables.get(e.name):o?null:i.analysis.variables.get(e.name);return(s?Ir(s.expression,s.context,r):a?Ir(a,i,r):null)??`:${e.name}`}if(k.isBinaryExpression(e,{operator:"+"})){let o=Ir(e.left,t,r),i=Ir(e.right,t,r);return o!==null&&i!==null?o+i:null}if(k.isTemplateLiteral(e)){let o=e.quasis[0]?.value.cooked??"";for(let[i,s]of e.expressions.entries()){if(!k.isExpression(s))return null;o+=(Ir(s,t,r)??":param")+(e.quasis[i+1]?.value.cooked??"")}return o}if(k.isCallExpression(e)&&k.isIdentifier(e.callee)&&["encodeURIComponent","decodeURIComponent"].includes(e.callee.name)&&k.isExpression(e.arguments[0])){let o=Ir(e.arguments[0],t,r);if(o===null||o.startsWith(":"))return o;try{return e.callee.name==="encodeURIComponent"?encodeURIComponent(o):decodeURIComponent(o)}catch{return null}}return k.isTSAsExpression(e)||k.isTSNonNullExpression(e)||k.isParenthesizedExpression(e)?Ir(e.expression,t,r):null}async function FD(e,t){let n=t.scopeFunction;if(!n)return null;let r=[],o=!1,i=0,s=u=>{let d=!1;return k.traverseFast(u,f=>{k.isIdentifier(f,{name:e})&&(d=!0)}),d},a=u=>{let d=u;for(;k.isMemberExpression(d);)d=d.object;return k.isIdentifier(d,{name:e})},l=async(u,d)=>{if(!o){if(k.isFunction(u)){s(u)&&(o=!0);return}if(k.isVariableDeclarator(u)&&(ho(u.id).includes(e)&&i++,u.init&&s(u.init)&&(o=!0)),(k.isAssignmentExpression(u)||k.isUpdateExpression(u))&&a(k.isAssignmentExpression(u)?u.left:u.argument)){o=!0;return}if(k.isUnaryExpression(u,{operator:"delete"})&&a(u.argument)){o=!0;return}if(k.isCallExpression(u)){if(k.isMemberExpression(u.callee)&&k.isIdentifier(u.callee.object,{name:e})){if(!k.isIdentifier(u.callee.property,{name:"push"})||u.callee.computed||!u.arguments.length){o=!0;return}for(let f of u.arguments){let m=k.isSpreadElement(f)?f.argument:f,g=k.isExpression(m)?await xt(m,d):null;g?r.push(Hl(g)):o=!0}return}if(u.arguments.some(f=>s(f))){o=!0;return}}if(k.isForOfStatement(u)){let f=await xt(u.right,d),m=xo(d.analysis,d),g=k.isVariableDeclaration(u.left)?u.left.declarations[0]?.id:u.left;f&&g&&Wl(g,Hl(f),m),await l(u.body,m);return}for(let f of k.VISITOR_KEYS[u.type]??[]){let m=u[f];for(let g of Array.isArray(m)?m:[m])k.isNode(g)&&await l(g,d)}}};await l(n.body,t);let c=tu(r);return!o&&i===1&&c.length===1?Ur(c[0]):null}async function DD(e,t){let n=t.analysis.stateSetters.get(e);if(!n)return null;let r=t.analysis.stateSetterCandidates.get(n)??[];for(let o of r){let i=await xt(o,t);if(i)return i}return null}async function xt(e,t){if(k.isIdentifier(e))return im(e.name,t);if(k.isMemberExpression(e)||k.isOptionalMemberExpression(e)){let n=k.isMemberExpression(e)?_E(e,{file:t.file}):null;if(n)return qE(n);let r=await MD(e,t);if(!r)return null;let o=JD(e);return $i(r,o,!1)}if(k.isAwaitExpression(e))return k.isExpression(e.argument)?xt(e.argument,t):null;if((k.isCallExpression(e)||k.isOptionalCallExpression(e))&&(k.isMemberExpression(e.callee)||k.isOptionalMemberExpression(e.callee))&&!e.callee.computed&&k.isIdentifier(e.callee.property)&&["trim","trimStart","trimEnd"].includes(e.callee.property.name)&&e.arguments.length===0&&k.isExpression(e.callee.object))return qo(await xt(e.callee.object,t));if(k.isCallExpression(e))return zE(e,t);if(k.isObjectExpression(e)){let n=await HE(e,t);return Object.keys(n).length>0?Ui(n,t.file):null}if(k.isArrayExpression(e)){let n={};for(let[r,o]of e.elements.entries()){if(!k.isExpression(o))continue;let i=await xt(o,t);i&&(n[String(r)]=i)}return Object.keys(n).length?Ui(n,t.file):null}if(k.isConditionalExpression(e)){let n=await xt(e.consequent,t),r=await xt(e.alternate,t);return qo(om(n,r))}if(k.isLogicalExpression(e)){let n=await xt(e.left,t),r=await xt(e.right,t);return qo(om(n,r))}return k.isTSAsExpression(e)||k.isTSSatisfiesExpression(e)||k.isTSNonNullExpression(e)||k.isTypeCastExpression(e)||k.isParenthesizedExpression(e)?xt(e.expression,t):null}async function MD(e,t){let n=e;for(;k.isMemberExpression(n)||k.isOptionalMemberExpression(n);)n=n.object;return k.isExpression(n)?xt(n,t):null}async function XE(e,t,n=0){if(n>=t.options.maxFunctionDepth)return null;let r=yo(e,t);if(r){if(r.scopeFunction&&Er(r.scopeFunction,e))return null;let s=r.paramArguments.get(e);return s&&k.isIdentifier(s.expression)?XE(s.expression.name,s.context,n+1):null}let o=t.analysis.imports.get(e);if(!o||!["cms","collections","cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(o.importedName)||Er(t.analysis.ast,e))return null;let i=await dm(t.file,o.source,t.exists);return i?{...o,source:i}:null}async function zE(e,t){let n=e.arguments[0],r=k.isExpression(n)?Jl(n,t):null,i=On(e.callee)?.split(".")[0],s=i?await XE(i,t):null,a=r!==null&&!k.isStringLiteral(n)?{...e,arguments:[k.stringLiteral(r),...e.arguments.slice(1)]}:e;if(s&&["cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(s.importedName)&&k.isObjectExpression(n)){let x=WE(n,"path"),b=x&&Ir(x,t);b?.startsWith("/")&&(a={...e,arguments:[{...n,properties:n.properties.map(S=>k.isObjectProperty(S)&&ei(S)==="path"?{...S,value:k.stringLiteral(Yo(b))}:S)},...e.arguments.slice(1)]})}let l=jr(a,{file:t.file,imports:i&&s?new Map([[i,s]]):new Map});if(l){if(s&&["cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(s.importedName)&&l.endpointPattern==="/content/by-url"&&k.isObjectExpression(n)){let x=wE(n,"query"),b=k.isObjectExpression(x)?wE(x,"path"):null,S=b&&Ir(b,t),E=S&&Kl(S);E&&(l.collection=E,l.evidence.push({file:t.file,reason:"CMS collection namespace from the actual content request path"}))}if(k.isMemberExpression(e.callee)){let x=await $r(e.callee,t);if(x&&!Xl(x.node))return null;if(x&&Xl(x.node)){let b=await rm(e,t,{node:x.node,context:x.context});return b&&{...b,...b.sourceKind===l.sourceKind?{operation:l.operation}:{}}}}if((l.operation==="getByUrl"||l.operation==="getByUrlStrict")&&k.isExpression(n)){let x=Ir(n,t);x?.startsWith("/")&&(l.endpointPattern=Yo(x))}return qE(l)}if(On(e.callee)==="Promise.all"&&k.isArrayExpression(n))return xt(n,t);if(Vl(e)){if(!Vl(e,{file:t.file,imports:i&&s?new Map([[i,s]]):new Map})||!k.isExpression(e.callee))return null;let x=await $r(e.callee,t);if(x)return Xl(x.node)?rm(e,t,{node:x.node,context:x.context}):null;let b=e.arguments[0];if(b&&k.isExpression(b))return qo(await xt(b,t))}let c=await BD(e,t);if(c)return c;let u=IE(e,{file:t.file});if(u)return{sourceKind:u.sourceKind,sourceType:"api-field",endpointPattern:u.endpointPattern,valuePath:u.valuePath,confidence:u.confidence,readonly:!0,evidence:u.evidence};let d=await $D(e,t);if(d)return d;let f=await UD(e,t);if(f)return f;let m=await VD(e,t);if(m)return m;let g=await rm(e,t);if(g)return g;let p=[];for(let x of e.arguments)if(k.isExpression(x)){let b=await xt(x,t);b&&p.push(b)}let h=tu(p);return h.length===1?qo(h[0]):null}async function BD(e,t){let n=On(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=jD(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(k.isIdentifier(s)){let a=await ji(s.name,t);if(a)return(await Zo(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!k.isObjectExpression(r))return ma(t.file,`${n} without static options`);let o=WE(r,"queryFn");if(!o)return ma(t.file,`${n} without queryFn`);if(k.isIdentifier(o)){let i=await ji(o.name,t);return i?(await Zo(i.node,[],i.context)).returnSource:ma(t.file,`${n} queryFn unresolved`)}return k.isArrowFunctionExpression(o)||k.isFunctionExpression(o)?(await Zo(o,[],t)).returnSource:k.isCallExpression(o)?zE(o,t):null}function WE(e,t){for(let n of e.properties){if(!k.isObjectProperty(n)||!k.isExpression(n.value))continue;if(ei(n)===t)return n.value}return null}function wE(e,t){let n=new Set;for(let i of e.properties){if(!k.isObjectProperty(i)||i.computed)return null;let s=ei(i);if(!s||n.has(s))return null;n.add(s)}let r=e.properties.filter(i=>k.isObjectProperty(i)&&ei(i)===t);if(r.length!==1)return null;let o=r[0];return k.isObjectProperty(o)&&k.isExpression(o.value)?o.value:null}function jD(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 $D(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","reverse","toReversed"].includes(n))return null;let r=k.isExpression(e.callee.object)?await xt(e.callee.object,t):null;if(!r)return null;if(n!=="map")return Ur(r);let o=e.arguments[0];if(r.cmsCallerSources){let i=await Promise.all(r.cmsCallerSources.map(s=>TE(o,s,t)));return am(i,t.file)}return TE(o,r,t)}async function TE(e,t,n){if(k.isIdentifier(e)){let r=await ji(e.name,n);if(!r)return Ur(t);let o=await Zo(r.node,[t],r.context);return{...Ur(t),...o.objectReturnMap??o.returnSource?.fieldMap?{fieldMap:o.objectReturnMap??o.returnSource.fieldMap}:{}}}if(k.isArrowFunctionExpression(e)||k.isFunctionExpression(e)){let r=await Zo(e,[t],n);return{...Ur(t),...r.objectReturnMap??r.returnSource?.fieldMap?{fieldMap:r.objectReturnMap??r.returnSource.fieldMap}:{}}}return Ur(t)}async function UD(e,t){return!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property,{name:"json"})||!k.isExpression(e.callee.object)?null:xt(e.callee.object,t)}async function VD(e,t){return!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property,{name:"then"})||!k.isExpression(e.callee.object)?null:qo(await xt(e.callee.object,t))}async function rm(e,t,n){let r=n;if(!r&&k.isIdentifier(e.callee))r=await ji(e.callee.name,t)??void 0;else if(!r&&k.isMemberExpression(e.callee)){let s=await $r(e.callee,t);s&&Xl(s.node)&&(r={node:s.node,context:s.context})}if(!r)return null;let o=[];for(let s of e.arguments){if(!k.isExpression(s)){o.push(ma(t.file,`unsupported argument for ${On(e.callee)??"call"}`));continue}let a=await xt(s,t);o.push(a)}return(await Zo(r.node,o,r.context,{arguments:e.arguments,context:t})).returnSource}function Xl(e){return k.isFunctionDeclaration(e)||Yl(e)||k.isObjectMethod(e)&&e.kind==="method"}async function $r(e,t,n=new Set){let r={node:null,context:t};if(n.has(e)||n.size>=32)return r;let o=new Set(n).add(e);if(k.isTSAsExpression(e)||k.isTSSatisfiesExpression(e)||k.isTSNonNullExpression(e))return $r(e.expression,t,o);if(k.isIdentifier(e)){let i=yo(e.name,t),s=i??t;if(Er(i?.scopeFunction??t.analysis.ast,e.name))return r;let a=s.paramArguments.get(e.name);if(a)return $r(a.expression,a.context,o);let l=i?i.scopeVariables?.get(e.name):s.analysis.variables.get(e.name);if(l)return $r(l,s,o);if(i)return null;let c=s.analysis.functions.get(e.name);if(c)return{node:c,context:s};let u=s.analysis.imports.get(e.name);if(!u||s.importDepth>=s.options.maxImportDepth)return null;let d=await um(u,s);return d?$r(k.identifier(u.importedName),xo(d,s,{importDepth:s.importDepth+1}),o):null}if(k.isMemberExpression(e)&&k.isExpression(e.object)){let i=e.computed?k.isStringLiteral(e.property)?e.property.value:null:k.isIdentifier(e.property)?e.property.name:null;if(!i)return null;let s=await $r(e.object,t,o);if(!s)return null;if(!k.isObjectExpression(s.node))return{node:null,context:s.context};if(s.node.properties.some(c=>k.isSpreadElement(c)||c.computed))return{node:null,context:s.context};let a=s.node.properties.filter(c=>(k.isObjectMethod(c)||k.isObjectProperty(c))&&(k.isIdentifier(c.key)?c.key.name:k.isStringLiteral(c.key)?c.key.value:null)===i);if(a.length===0)return null;if(a.length!==1)return{node:null,context:s.context};let l=a[0];return k.isObjectMethod(l)?l.kind==="method"?{node:l,context:s.context}:null:k.isObjectProperty(l)&&k.isExpression(l.value)?$r(l.value,s.context,o):null}return{node:e,context:t}}async function ji(e,t,n=new Set){let r=t.paramArguments.get(e);if(r&&!n.has(r.expression)){if(n.add(r.expression),Yl(r.expression))return{node:r.expression,context:r.context};if(k.isIdentifier(r.expression))return ji(r.expression.name,r.context,n)}let o=t.analysis.functions.get(e);if(o)return{node:o,context:t};let i=t.analysis.imports.get(e);if(!i||t.importDepth>=t.options.maxImportDepth)return null;let s=await um(i,t);if(!s)return null;let a=xo(s,t,{importDepth:t.importDepth+1}),l=rI(i,s);return l?{node:l,context:a}:ji(i.importedName,a)}async function Zo(e,t,n,r){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let o=xo(n.analysis,n,{functionDepth:n.functionDepth+1}),i=n.analysis.functionParents.get(e),s=n;for(;s&&(s.analysis!==n.analysis||s.scopeFunction!==i);)s=s.lexicalContext;o.lexicalContext=s,o.paramSources=new Map,o.paramArguments=new Map,o.scopeVariables=n.analysis.functionVariables.get(e),o.scopeFunction=e,e.params.forEach((f,m)=>{for(let x of ho(f))o.paramSources.delete(x),o.paramArguments.delete(x);let g=k.isAssignmentPattern(f)?f.left:f,p=r?.arguments[m];k.isIdentifier(g)&&k.isExpression(p)&&r&&o.paramArguments.set(g.name,{expression:p,context:r.context});let h=t[m];h&&Wl(f,Hl(h),o)});let a=KD(e,o),l=a.map(YE).filter(f=>!ZE(f));if(a.length>1&&l.length>0&&l.every(f=>k.isObjectExpression(f))){let f=await GE(l,o);return{returnSource:Ui(f,n.file),objectReturnMap:f}}let c=null,u,d=!1;for(let f of a){let m=xo(n.analysis,o);if(k.isObjectExpression(f)){u={...u??{},...await HE(f,m)},c=c??Ui(u,n.file);continue}let g=await xt(f,m);if(g){if(!c){c=g;continue}let p=sm(c,g);if(!p){d=!0,c=null;continue}c=p}}return{returnSource:d?null:c,...u?{objectReturnMap:u}:{}}}function Wl(e,t,n){if(k.isIdentifier(e)){n.paramSources.set(e.name,Wt(t));return}if(k.isAssignmentPattern(e)){Wl(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=$i(t,[{kind:"property",name:r.key.name}],!0),i=k.isAssignmentPattern(r.value)?r.value.left:r.value;o&&Wl(i,o,n)}}function KD(e,t){if(k.isArrowFunctionExpression(e)&&k.isExpression(e.body))return[e.body];let n=[],r=e.body;if(!k.isBlockStatement(r))return n;let o=i=>{if(k.isFunction(i)&&i!==e)return;if(k.isReturnStatement(i)){i.argument&&k.isExpression(i.argument)&&n.push(i.argument);return}if(k.isIfStatement(i)){let a=Mi(i.test,{file:t.file,imports:new Map([...t.analysis.imports].filter(([l])=>!yo(l,t))),functions:t.analysis.functions});if(a!==void 0){a?o(i.consequent):i.alternate&&o(i.alternate);return}}let s=k.VISITOR_KEYS[i.type];for(let a of s??[]){let l=i[a];if(Array.isArray(l))for(let c of l)k.isNode(c)&&o(c);else k.isNode(l)&&o(l)}};return o(r),n}async function HE(e,t){let n={};for(let r of e.properties){if(!k.isObjectProperty(r))continue;let o=ei(r);if(!o||!k.isExpression(r.value))continue;let i=await xt(r.value,t);i&&(n[o]=i)}return n}async function GE(e,t){let n=[];for(let i of e){let s=new Map,a=!1;for(let l of i.properties){if(k.isObjectProperty(l)&&k.isExpression(l.value)){let c=ei(l);if(c!==null){s.set(c,YE(l.value));continue}}s.clear(),a=!0}n.push({properties:s,hasUnknownKeys:a})}let r=new Map,o=new Set(n.flatMap(({properties:i})=>[...i.keys()]));for(let i of o){if(n.some(({properties:l,hasUnknownKeys:c})=>c&&!l.has(i)))continue;let s=n.flatMap(({properties:l})=>{let c=l.get(i);return c&&!ZE(c)?[c]:[]});if(s.length===0)continue;if(s.every(l=>k.isObjectExpression(l))){let l=await GE(s,t);Object.keys(l).length&&r.set(i,Ui(l,t.file));continue}let a=null;for(let l of s){let c=await xt(l,t);if(a=c&&om(a,c),!a)break}a&&r.set(i,a)}return Object.fromEntries(r)}function YE(e){for(;k.isTSAsExpression(e)||k.isTSSatisfiesExpression(e)||k.isTSNonNullExpression(e)||k.isParenthesizedExpression(e);)e=e.expression;return e}function ZE(e){return k.isNullLiteral(e)||k.isArrayExpression(e)&&e.elements.length===0}function ei(e){return k.isIdentifier(e.key)&&!e.computed?e.key.name:k.isStringLiteral(e.key)?e.key.value:null}function JD(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 $i(e,t,n){if(t.length===0)return Wt(e);if(e.cmsCallerSources){let s=e.cmsCallerSources.map(a=>$i(a,t,n));return s.every(a=>a!==null)?am(s,e.evidence[0].file):null}let r=t[0],o=r?.kind==="property"?r.name:r?String(r.index):null;if(e.fieldMap&&o!==null){let s=e.fieldMap[o];return s?$i(s,t.slice(1),n):null}let i=Wt(e);if(i.sourceType==="cms-field"){let s=t.filter(l=>l.kind==="property").map(l=>l.name);if(s[0]==="data"&&s[1]==="items")return i.valuePath=Bi(i.valuePath,"data.items[]"),i.cmsFieldRoot=!1,i;let a=s[0]==="fields"?0:s[0]==="data"&&s[1]==="fields"?1:-1;return a>=0?(a===1&&(i.valuePath=Bi(i.valuePath,"data")),i.fieldPath=Bi(i.fieldPath,s.slice(a+1).join(".")),i.cmsFieldRoot=!0,i):i.cmsFieldRoot||n||i.fieldMap?(i.fieldPath=Bi(i.fieldPath,s.join(".")),i):(i.valuePath=Bi(i.valuePath,OE(t)),i)}return i.valuePath=Bi(i.valuePath,OE(t)),i}function OE(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function Bi(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function qE(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 Ur(e){let t=Wt(e);return t.cmsCallerSources=t.cmsCallerSources?.map(Ur),t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function Hl(e){let t=Wt(e);return t.cmsCallerSources=t.cmsCallerSources?.map(Hl),t.valuePath=void 0,t.sourceType==="cms-field"&&!t.fieldPath&&(t.cmsFieldRoot=!1),t}function qo(e){return e?{...Wt(e),...e.cmsCallerSources?{cmsCallerSources:e.cmsCallerSources.map(t=>qo(t))}:{},confidence:e.confidence==="unknown"?"unknown":"safe-derived",evidence:[...e.evidence,{file:e.evidence[0]?.file??"unknown",reason:"safe derived expression"}]}:null}function om(e,t){return e?t?sm(e,t):Wt(e):t?Wt(t):null}function sm(e,t){if(ga(e)!==ga(t))return null;let n=tI(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function tu(e){let t=new Map;for(let n of e){let r=ga(n),o=t.get(r);t.set(r,o?sm(o,n):Wt(n))}return[...t.values()]}function am(e,t){let n=tu(e.flatMap(r=>r.cmsCallerSources??[r]));return n.length===0||n.length>16||n.some(r=>r.sourceKind!=="vcp-cms-collection"||!r.collection||!["exact","safe-derived"].includes(r.confidence))?null:{...ma(t,"competing component callers"),cmsCallerSources:n}}function ga(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,ga(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,cmsCallerSources:e.cmsCallerSources?.map(ga).sort(),fieldMap:t})}function Ui(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 ma(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function LE(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 Gl(e,t,n){return e.cmsCallerSources?e.cmsCallerSources.map(r=>{let o=LE(r,t,n);return o.evidence.push({file:e.evidence[0].file,reason:"CMS shared component caller"}),o}):[LE(e,t,n)]}function QE(e){let t=[...e].sort(eI),n=t.filter(i=>!i.evidence.some(({reason:s})=>s==="CMS shared component caller")),r=n[0],o=[...new Set(n.flatMap(i=>i.sourceKind==="vcp-cms-collection"&&i.collection?[i.collection]:[]))];return{hasDynamicData:t.length>0,sourceKinds:[...new Set(t.map(i=>i.sourceKind))],...o.length>0?{collections:o}:{},...r?.endpointPattern?{primaryEndpoint:r.endpointPattern}:{},...r?.collection?{primaryCollection:r.collection}:{},...r?.fieldPath?{primaryFieldPath:r.fieldPath}:{}}}function XD(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 eI(e,t){return FE(e.targetKind)-FE(t.targetKind)||tI(e.confidence,t.confidence)||DE(e.sourceKind)-DE(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function FE(e){return{"repeat-region":0,"conditional-region":1,text:2,richtext:3,attribute:4,"component-prop":5}[e]}function DE(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function tI(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function cm(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=ME.get(n)?.get(e),i=o?.source===t?o.ast:vD(t,{sourceType:"module",plugins:["jsx","typescript"]}),s={file:e,source:t,ast:i,variables:new Map,functions:new Map,imports:new Map,stateSetters:new Map,stateSetterCandidates:new Map,jsxElementsByRange:new Map,functionVariables:new WeakMap,functionParents:new WeakMap},a=[],l=[];k.traverse(i,{enter(d){switch(k.isFunction(d)&&(s.functionParents.set(d,a.at(-1)??null),a.push(d)),d.type){case"CallExpression":l.push(d);break;case"JSXElement":{let f=d.loc;if(!f)return;let m=ql({startLine:f.start.line,startColumn:f.start.column,endLine:f.end.line,endColumn:f.end.column});s.jsxElementsByRange.has(m)||s.jsxElementsByRange.set(m,d);break}case"ImportDeclaration":{let f=d.source.value;for(let m of d.specifiers)k.isImportSpecifier(m)&&k.isIdentifier(m.local)?s.imports.set(m.local.name,{source:f,importedName:k.isIdentifier(m.imported)?m.imported.name:m.imported.value,localName:m.local.name,isDefault:!1}):k.isImportDefaultSpecifier(m)&&s.imports.set(m.local.name,{source:f,importedName:"default",localName:m.local.name,isDefault:!0});break}case"FunctionDeclaration":{d.id?.name&&s.functions.set(d.id.name,d);break}case"VariableDeclarator":{let f=a.at(-1),m=f&&(k.isFunctionDeclaration(f)||k.isFunctionExpression(f)||k.isArrowFunctionExpression(f)||k.isObjectMethod(f))?f:null,g=m?s.functionVariables.get(m)??new Map:s.variables;m&&!s.functionVariables.has(m)&&s.functionVariables.set(m,g);for(let[p,h]of zl(d.id,k.isExpression(d.init)?d.init:null))g.set(p,h);if(k.isArrayPattern(d.id)&&k.isCallExpression(d.init)&&On(d.init.callee)==="useState"){let[p,h]=d.id.elements;k.isIdentifier(p)&&k.isIdentifier(h)&&s.stateSetters.set(p.name,h.name)}k.isIdentifier(d.id)&&Yl(d.init)&&s.functions.set(d.id.name,d.init);break}case"ExportNamedDeclaration":{let f=d.declaration,m=d.source?.value;if(m)for(let g of d.specifiers){if(!k.isExportSpecifier(g))continue;let p=k.isIdentifier(g.exported)?g.exported.name:g.exported.value,h=g.local.name;s.imports.set(p,{source:m,importedName:h,localName:p,isDefault:h==="default"})}if(k.isFunctionDeclaration(f)&&f.id?.name&&s.functions.set(f.id.name,f),k.isVariableDeclaration(f))for(let g of f.declarations)k.isIdentifier(g.id)&&Yl(g.init)&&s.functions.set(g.id.name,g.init);break}case"ExportDefaultDeclaration":{let f=d.declaration;if((k.isFunctionDeclaration(f)||k.isFunctionExpression(f)||k.isArrowFunctionExpression(f))&&s.functions.set("default",f),k.isIdentifier(f)){let m=s.functions.get(f.name);m&&s.functions.set("default",m)}break}}},exit(d){k.isFunction(d)&&a.pop()}});let c=new Set(s.stateSetters.values()),u=(d,f)=>{let m=s.stateSetterCandidates.get(d)??[];m.push(f),s.stateSetterCandidates.set(d,m)};if(c.size>0)for(let d of l){let f=k.isIdentifier(d.callee)?d.callee.name:null;f&&c.has(f)&&k.isExpression(d.arguments[0])&&u(f,d.arguments[0]);let m=new Set;for(let g of d.arguments)k.isIdentifier(g)&&g.name!==f&&c.has(g.name)&&m.add(g.name);for(let g of m)u(g,d)}return n.set(e,s),s}function zl(e,t){return k.isIdentifier(e)?[[e.name,t]]:k.isAssignmentPattern(e)?zl(e.left,t):k.isArrayPattern(e)?e.elements.flatMap((n,r)=>n&&!k.isRestElement(n)?zl(n,t?k.memberExpression(t,k.numericLiteral(r),!0):null):[]):k.isObjectPattern(e)?e.properties.flatMap(n=>{if(!k.isObjectProperty(n)||n.computed)return[];let r=ei(n);return r?zl(n.value,t?k.memberExpression(t,k.stringLiteral(r),!0):null):[]}):[]}function ho(e){return!e||k.isVoidPattern(e)?[]:k.isIdentifier(e)?[e.name]:k.isObjectPattern(e)?e.properties.flatMap(t=>k.isObjectProperty(t)?ho(t.value):ho(t.argument)):k.isArrayPattern(e)?e.elements.flatMap(t=>t?ho(k.isRestElement(t)?t.argument:t):[]):k.isAssignmentPattern(e)?ho(e.left):k.isRestElement(e)?ho(e.argument):[]}function Yl(e){return k.isFunctionExpression(e)||k.isArrowFunctionExpression(e)}function nI(e,t){let n=lm(e,t);return n?e.functionVariables.get(n):void 0}function lm(e,t){return e.functions.get(t)??e.functions.get("default")}async function um(e,t){let n=await dm(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return cm(n,r,t.fileCache)}function rI(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function dm(e,t,n){return _t(t)?No(e,t,n):null}function xo(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),paramArguments:e===t.analysis?new Map(t.paramArguments):new Map,resolvingVariables:new Set,resolvingComponentProps:t.resolvingComponentProps,scopeVariables:e===t.analysis?t.scopeVariables:void 0,scopeFunction:e===t.analysis?t.scopeFunction:void 0,lexicalContext:e===t.analysis?t.lexicalContext:void 0}}function zD(e){return e?Wt(e):null}function Wt(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.cmsCallerSources?{cmsCallerSources:e.cmsCallerSources.map(Wt)}:{},...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,Wt(n)]))}:{}}}import*as hm from"@babel/parser";import gm from"@babel/traverse";import*as Se from"@babel/types";import{classifySiteEditPropertyName as WD}from"@vcp-dev/platform-shared/contracts";import*as lI from"@babel/parser";import fm from"@babel/traverse";import*as Te from"@babel/types";function ru(e,t){let n=[],r=e;for(;Te.isMemberExpression(r);){if(r.computed)if(Te.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(Te.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!Te.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!Te.isIdentifier(r)||r.name!==t?null:n}function oI(e){if(Te.isIdentifier(e))return{base:e.name,path:[]};if(!Te.isMemberExpression(e))return null;let t=[],n=e;for(;Te.isMemberExpression(n);){if(n.computed)if(Te.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(Te.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!Te.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return Te.isIdentifier(n)?{base:n.name,path:t}:null}function tn(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}var vr=Symbol("not-closed-literal");function nu(e){switch(e.type){case"StringLiteral":case"NumericLiteral":case"BooleanLiteral":return e.value;case"NullLiteral":return null;case"TemplateLiteral":return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:vr;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":return nu(e.expression);case"ArrayExpression":{let t=[];for(let n of e.elements){if(!n||Te.isSpreadElement(n))return vr;let r=nu(n);if(r===vr)return vr;t.push(r)}return t}case"ObjectExpression":{let t={};for(let n of e.properties){if(!Te.isObjectProperty(n)||n.computed||n.shorthand||!Te.isExpression(n.value))return vr;let r=Te.isIdentifier(n.key)?n.key.name:Te.isStringLiteral(n.key)?n.key.value:null;if(!r)return vr;let o=nu(n.value);if(o===vr)return vr;t[r]=o}return t}default:return vr}}function iI(e){let{resolveBindingTarget:t}=e;async function n(i,s,a,l,c,u,d){let f=nu(i);if(f!==vr)return f;if(!Te.isTemplateLiteral(i)){if(Te.isTSAsExpression(i)||Te.isTSSatisfiesExpression(i)||Te.isTSNonNullExpression(i))return await n(i.expression,s,a,l,c,u,d);if(Te.isIdentifier(i)){let m=s.getBinding(i.name);if(!m)return;let g=await t({currentFile:a,binding:m,readFile:l,exists:c,fileCache:u,visited:d});return g?.kind==="static"?g.value:void 0}if(Te.isArrayExpression(i)){let m=[];for(let g of i.elements){if(!g||Te.isSpreadElement(g))return;let p=await r(g,s,a,l,c,u,d);if(p===void 0)return;m.push(p)}return m}if(Te.isObjectExpression(i)){let m={};for(let g of i.properties){if(!Te.isObjectProperty(g)||g.computed)return;let p=null;if(Te.isIdentifier(g.key)?p=g.key.name:Te.isStringLiteral(g.key)&&(p=g.key.value),!p)return;if(g.shorthand){if(!Te.isIdentifier(g.value))return;let x=await r(g.value,s,a,l,c,u,d);if(x===void 0)return;m[p]=x;continue}if(!Te.isExpression(g.value))return;let h=await r(g.value,s,a,l,c,u,d);h!==void 0&&(m[p]=h)}return m}if(Te.isMemberExpression(i)){let m=await o(i,s,a,l,c,u,d);if(!m)return;let g=s.getBinding(m.base);if(!g)return;let p=await t({currentFile:a,binding:g,readFile:l,exists:c,fileCache:u,visited:d});return!p||p.kind!=="static"?void 0:tn(p.value,m.path)}}}async function r(i,s,a,l,c,u,d){if(!Te.isSpreadElement(i))return await n(i,s,a,l,c,u,d)}async function o(i,s,a,l,c,u,d){if(Te.isIdentifier(i))return{base:i.name,path:[]};if(!Te.isMemberExpression(i))return null;let f=[],m=i;for(;Te.isMemberExpression(m);){if(m.computed){let g=m.property;if(Te.isNumericLiteral(g))f.unshift({kind:"index",index:g.value});else if(Te.isStringLiteral(g))f.unshift({kind:"property",name:g.value});else{let p=Te.isExpression(g)?await n(g,s,a,l,c,u,d):void 0;if(typeof p=="string")f.unshift({kind:"property",name:p});else if(Number.isInteger(p))f.unshift({kind:"index",index:p});else return null}}else{if(!Te.isIdentifier(m.property))return null;f.unshift({kind:"property",name:m.property.name})}m=m.object}return Te.isIdentifier(m)?{base:m.name,path:f}:null}return{normalizeExpressionWithScope:o,evaluateStaticExpression:n}}var uI=typeof fm=="function"?fm:fm.default,sI=new WeakMap;function dI(e){try{return lI.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function ou(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=dI(n);return e.set(t,{source:n,ast:o}),o}function iu(e,t){return pm(ha(e).expressionRanges,t,!1)}function fI(e,t){return ha(e).exactExpressions.get(pI(t))??null}function su(e,t){return pm(ha(e).jsxRanges,t,!0)}function ha(e){let t=sI.get(e);if(t)return t;let n={expressions:[],expressionRanges:[],jsxRanges:[],exactExpressions:new Map};return uI(e,{Expression(r){let o=r;n.expressions.push(o);let i=aI(o,n.expressions.length-1);if(!i)return;n.expressionRanges.push(i);let s=pI(i.range),a=n.exactExpressions.get(s);(!a||i.span<=(a.node.end??0)-(a.node.start??0))&&n.exactExpressions.set(s,o)},JSXElement(r){let o=aI(r,n.jsxRanges.length);o&&n.jsxRanges.push(o)}}),n.expressionRanges.sort(cI),n.jsxRanges.sort(cI),sI.set(e,n),n}function aI(e,t){let n=ya(e.node);return n?{path:e,range:n,traversalIndex:t,span:(e.node.end??0)-(e.node.start??0)}:null}function pI(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}function cI(e,t){return e.range.startLine-t.range.startLine||e.range.startColumn-t.range.startColumn||e.traversalIndex-t.traversalIndex}function pm(e,t,n,r){let o=0,i=e.length;for(;o<i;){let l=o+Math.floor((i-o)/2),c=e[l].range;c.startLine<t.startLine||c.startLine===t.startLine&&c.startColumn<t.startColumn?o=l+1:i=l}let s=null,a=n?1/0:-1;for(let l=o;l<e.length;l++){let c=e[l],u=c.range;if(u.startLine>t.endLine||u.startLine===t.endLine&&u.startColumn>t.endColumn)break;if(u.endLine>t.endLine||u.endLine===t.endLine&&u.endColumn>t.endColumn||r&&!r(c.path))continue;((n?c.span<a:c.span>a)||c.span===a&&(!s||c.traversalIndex>s.traversalIndex))&&(s=c,a=c.span)}return s?.path??null}function ya(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 Vi(e,t){if(t)return mm(e,t);let n=oI(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function mm(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function xa(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of ha(e).expressions){if(mm(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function mI(e,t,n,r){return pm(ha(e).expressionRanges,r,!0,o=>mm(o.node,t)===n)}function Ki(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function Ji(e){let t=null;if(uI(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}async function or(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=dI(o),s={source:o,ast:i};return n.set(e,s),s}var ym=typeof gm=="function"?gm:gm.default;function xm(e){let t=WD(e.propertyName);if(t.owner!=="generic")return Sn("invalid-property",t.diagnostic?.message??`Property '${e.propertyName}' is not a generic property`);let n=e.selectionRef;if(!n)return Sn("missing-selection-ref","A repeat property target requires a complete selection reference");if(n.key!==e.element.identity.key)return Sn("selection-mismatch","Selection reference does not identify the requested element");if(n.instanceIndex===void 0)return Sn("missing-instance-index","A repeat property target requires an instance index");let r;try{r=hm.parse(e.source,{sourceType:"module",plugins:["typescript","jsx"]})}catch(h){return Sn("repeat-not-found",`Unable to parse repeat source: ${h instanceof Error?h.message:String(h)}`)}let o=HD(r,e.element.sourceRange);if(!o)return Sn("repeat-not-found","The selected element is not inside a supported map repeat");if(o.binding&&co(o.binding))return Sn("unsafe-collection","The repeat source is mutated outside the mapped expression");if(!Se.isIdentifier(o.callback.params[0]))return Sn("unsupported-callback","Repeat property materialization requires an identifier callback item");let i=GD(r,o.collection,e.file,e.sources);if(!i)return Sn("collection-not-found","The repeat collection is not a visible local static array");let{array:s,locator:a,sourceFile:l}=i,c=[],u=[];for(let[h,x]of s.elements.entries()){if(!x||!Se.isObjectExpression(x)||!SI(x))return Sn("unsafe-collection","Repeat materialization requires an array of local static objects without spreads");let b=[{kind:"index",index:h}];c.push(b),u.push({kind:"value",root:a.root,path:b})}let d=u.length;if(n.instanceCount!==void 0&&n.instanceCount!==d)return Sn("count-mismatch",`Selection reports ${n.instanceCount} instances but the source collection has ${d}`);let f=n.instanceIndex;if(f>=d)return Sn("index-out-of-range",`Selected repeat instance ${f} is outside the source collection`);let m=s.elements[f];if(!m||!Se.isObjectExpression(m))return Sn("unsafe-collection","Selected repeat item is not an object");let g=tM(e.element,e.propertyName),p=QD(m,e.propertyName);return p?{ok:!0,sourceFile:l,templateFile:e.file,collectionLocator:a,parentObjectLocators:u,selectedParentObjectLocator:u[f],sourceItemIndex:f,sourceItemPath:c[f],collectionIndexMap:Array.from({length:d},(h,x)=>x),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:p,selectedResolution:eM(m,e.propertyName),...g?{property:g}:{},selectionRef:n}:Sn("unsafe-property-source",`Property '${e.propertyName}' has a dynamic or unsupported source in the repeat item`)}function HD(e,t){let n=[];return ym(e,{CallExpression(r){let o=gI(r);o&&yI(o.callback,t)&&n.push({...o,span:hI(r.node)})},OptionalCallExpression(r){let o=gI(r);o&&yI(o.callback,t)&&n.push({...o,span:hI(r.node)})}}),n.sort((r,o)=>r.span-o.span),n[0]??null}function gI(e){let{node:t}=e,n=t.callee;if(!Se.isMemberExpression(n)&&!Se.isOptionalMemberExpression(n)||n.computed||!Se.isIdentifier(n.property)||n.property.name!=="map"||!Se.isExpression(n.object))return null;let r=t.arguments[0];return!r||!Se.isExpression(r)||!Se.isArrowFunctionExpression(r)&&!Se.isFunctionExpression(r)?null:{collection:n.object,callback:r,binding:Se.isIdentifier(n.object)?e.scope.getBinding(n.object.name):void 0}}function GD(e,t,n,r){let o=ba(t);if(o&&Se.isArrayExpression(o))return{array:o,locator:{kind:"value",root:{kind:"expression",sourceRange:II(o)}},sourceFile:n};if(!Se.isIdentifier(t))return null;let i=[];if(ym(e,{VariableDeclarator(s){Se.isIdentifier(s.node.id)&&s.node.id.name===t.name&&s.node.init&&i.push(s.node)}}),i.length===1){let s=ba(i[0].init);return!s||!Se.isArrayExpression(s)?null:{array:s,locator:{kind:"value",root:{kind:"binding",name:t.name}},sourceFile:n}}return YD(e,t.name,n,r)}function YD(e,t,n,r){if(!r)return null;for(let o of e.program.body){if(!Se.isImportDeclaration(o))continue;let i=o.specifiers.find(m=>m.local.name===t);if(!i||!Se.isStringLiteral(o.source)||!Se.isImportSpecifier(i))continue;let s=qD(n,o.source.value,r);if(!s)return null;let a=Se.isIdentifier(i.imported)?i.imported.name:i.imported.value,l=r.get(s);if(l===void 0)return null;let c;try{c=hm.parse(l,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}let u=Ji(c).getBinding(a);if(u&&co(u))return null;let d=ZD(c,a),f=d?ba(d):null;return!f||!Se.isArrayExpression(f)?null:{array:f,locator:{kind:"value",root:{kind:"binding",name:a}},sourceFile:s}}return null}function ZD(e,t){let n=null;return ym(e,{VariableDeclarator(r){n||!Se.isIdentifier(r.node.id)||r.node.id.name!==t||!r.node.init||!Se.isExpression(r.node.init)||(n=r.node.init)}}),n}function qD(e,t,n){let r=ar(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 ba(e){return Se.isParenthesizedExpression(e)?ba(e.expression):Se.isTSAsExpression(e)?bI(e.typeAnnotation)?ba(e.expression):null:Se.isTSSatisfiesExpression(e)?null:e}function bI(e){return Se.isTSTypeReference(e)&&Se.isIdentifier(e.typeName)&&e.typeName.name==="const"}function SI(e){return e.properties.every(t=>!Se.isObjectProperty(t)||t.computed||!Se.isExpression(t.value)?!1:au(t.value))}function au(e){if(Se.isTSAsExpression(e)&&bI(e.typeAnnotation))return au(e.expression);if(Se.isTSSatisfiesExpression(e))return!1;if(Se.isArrayExpression(e))return e.elements.every(n=>!n||Se.isSpreadElement(n)||!Se.isExpression(n)?!1:au(n));if(Se.isObjectExpression(e))return SI(e);let t=fr(e);return t.status==="resolved"||t.status==="undefined"}function QD(e,t){let n=e.properties.filter(o=>Se.isObjectProperty(o)&&EI(o.key)===t);if(n.length>1)return null;let r=n[0];return r?Se.isExpression(r.value)?au(r.value)?"static":Se.isIdentifier(r.value)||Se.isMemberExpression(r.value)?"binding":null:null:"missing"}function eM(e,t){let n=e.properties.filter(o=>Se.isObjectProperty(o)&&EI(o.key)===t);if(n.length>1)return{status:"unresolved"};let r=n[0];return!r||!Se.isExpression(r.value)?{status:"undefined"}:fr(r.value)}function tM(e,t){let n=e.attributes?.filter(r=>r.name===t)??[];return n.length===1?n[0]:void 0}function EI(e){return Se.isIdentifier(e)?e.name:Se.isStringLiteral(e)?e.value:Se.isNumericLiteral(e)?String(e.value):null}function II(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 hI(e){return e.start==null||e.end==null?Number.MAX_SAFE_INTEGER:e.end-e.start}function yI(e,t){let n=II(e);return xI(n.startLine,n.startColumn,t.startLine,t.startColumn)<=0&&xI(n.endLine,n.endColumn,t.endLine,t.endColumn)>=0}function xI(e,t,n,r){return e===n?t-r:e-n}function Sn(e,t){return{ok:!1,errorCode:e,reason:t}}import{classifySiteEditPropertyName as jM}from"@vcp-dev/platform-shared/contracts";import*as _e from"@babel/types";import Sa from"node:path";import*as ae from"@babel/types";function nM(e){return ae.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:ae.isMemberExpression(e.callee)&&ae.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function rM(e){if(!ae.isNewExpression(e)||!ae.isIdentifier(e.callee,{name:"Proxy"})||e.arguments.length!==2||!ae.isIdentifier(e.arguments[0])||!ae.isObjectExpression(e.arguments[1])||e.arguments[1].properties.length!==1)return null;let[t]=e.arguments[1].properties;if(!ae.isObjectMethod(t)||t.kind!=="method"||t.computed||t.async||t.generator||!ae.isIdentifier(t.key,{name:"get"})||t.params.length!==3||!t.params.every(ae.isIdentifier)||t.body.body.length!==2)return null;let[n,r,o]=t.params,[i,s]=t.body.body;if(ae.isIfStatement(i)&&ae.isBlockStatement(i.consequent)&&i.consequent.body.length!==1)return null;let a=ae.isIfStatement(i)?i.test:null,l=a&&ae.isLogicalExpression(a,{operator:"&&"})?a.right:null,c=ae.isIfStatement(i)?ae.isBlockStatement(i.consequent)?i.consequent.body[0]:i.consequent:null,u=ae.isReturnStatement(s)?s.argument:null;return!a||!ae.isLogicalExpression(a,{operator:"&&"})||!ae.isBinaryExpression(a.left,{operator:"==="})||!ae.isUnaryExpression(a.left.left,{operator:"typeof"})||!ae.isIdentifier(a.left.left.argument,{name:r.name})||!ae.isStringLiteral(a.left.right,{value:"string"})||!ae.isUnaryExpression(l,{operator:"!"})||!ae.isBinaryExpression(l.argument,{operator:"in"})||!ae.isIdentifier(l.argument.left,{name:r.name})||!ae.isIdentifier(l.argument.right,{name:n.name})||!ae.isReturnStatement(c)||!ae.isIfStatement(i)||i.alternate||!ae.isCallExpression(u)||!ae.isMemberExpression(u.callee)||!ae.isIdentifier(u.callee.object,{name:"Reflect"})||!ae.isIdentifier(u.callee.property,{name:"get"})||u.arguments.length!==3||!ae.isIdentifier(u.arguments[0],{name:n.name})||!ae.isIdentifier(u.arguments[1],{name:r.name})||!ae.isIdentifier(u.arguments[2],{name:o.name})?null:e.arguments[0].name}function oM(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()||!ae.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 vI(e,t){let n=oM(e.path);if(!n)return null;let r=Pi(e,t);return r?{...n,...r}:null}function kI(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}function bm(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"}}function Sm(e,t){for(let n of e.program.body){if(t==="default"&&ae.isExportDefaultDeclaration(n))return ae.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:(ae.isFunctionDeclaration(n.declaration)||ae.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if(ae.isExportNamedDeclaration(n)){if(n.declaration){if(ae.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if(ae.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if((ae.isFunctionDeclaration(n.declaration)||ae.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if((ae.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&ae.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}function _I(e){let{resolveExternalExpression:t,resolveCollectionCallTarget:n,evaluateStaticExpression:r,resolveSourceInfoProvenance:o,buildExpressionSourceInfo:i}=e;async function s(p){let{currentFile:h,binding:x,readFile:b,exists:S,fileCache:E,visited:v}=p,N=`${h}::${x.kind}::${x.identifier.name}`;if(v.has(N))return null;v.add(N);try{let I=await a({currentFile:h,binding:x,readFile:b,exists:S,fileCache:E,visited:v});if(I)return I;if(x.path.isImportSpecifier()||x.path.isImportDefaultSpecifier())return await m({currentFile:h,binding:x,readFile:b,exists:S,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,fileCache:E,visited:v});if(x.kind==="param")return null;if(x.path.isVariableDeclarator()){let A=x.path.node.init;if(!A||!ae.isExpression(A))return null;let C=rM(A);if(C&&!x.path.scope.getBinding("Proxy")&&!x.path.scope.getBinding("Reflect")){let X=x.path.scope.getBinding(C),j=X?await s({...p,binding:X}):null;if(j?.kind==="static"&&j.value!==null&&!Array.isArray(j.value)&&typeof j.value=="object")return j}let O=x.path.get("init");if(O&&!Array.isArray(O)&&O.isExpression()){let X=await t({currentFile:h,expressionPath:O,readFile:b,exists:S,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:E,visited:v});if(X)return X;if(O.isCallExpression()){let j=await n({currentFile:h,callPath:O,readFile:b,exists:S,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:E,visited:v});if(j)return j}}let L=await r(A,x.path.scope,h,b,S,E,v);return L===void 0?null:{kind:"static",file:h,root:{kind:"binding",name:x.identifier.name},value:L,sourceKind:"binding"}}if(x.path.isIdentifier()&&x.path.parentPath?.isExportDefaultDeclaration()){let A=x.path.parentPath.node.declaration;if(!ae.isExpression(A))return null;let C=await r(A,x.path.scope,h,b,S,E,v);return C===void 0?null:{kind:"static",file:h,root:{kind:"binding",name:x.identifier.name},value:C,sourceKind:"binding"}}return null}finally{v.delete(N)}}async function a(p){let{currentFile:h,binding:x,readFile:b,exists:S,fileCache:E,visited:v}=p;if(!x.path.isVariableDeclarator()||!x.path.get("id").isArrayPattern())return null;let N=x.path,I=N.node.init;if(!I||!ae.isCallExpression(I))return null;let A=nM(I);if(!A||!ae.isArrayPattern(N.node.id)||N.node.id.elements.findIndex(j=>ae.isIdentifier(j)&&j.name===x.identifier.name)!==0)return null;let O=A==="useReducer"?1:0,L=I.arguments[O];if(!L||!ae.isExpression(L))return null;let X=await r(L,N.scope,h,b,S,E,v);return X===void 0?null:{kind:"static",file:h,root:{kind:"hook-state",name:x.identifier.name,hook:A},value:X,sourceKind:"binding"}}async function l(p){let h=p.expressionPath.scope.getBinding(p.sourceInfo.base);if(!h||!h.constant||h.kind!=="param"||!p.graph)return null;let x=vI(h,p.sourceInfo);if(!x)return null;let b=[...p.graph.elements.values()].filter(E=>kI(E,p.currentFile,x.componentName,x.exportName));if(!b.length)return null;let S=[];for(let E of b){if(E.sourceFile!==b[0].sourceFile||E.componentName!==b[0].componentName||E.attributeSpreads?.length)return null;let v=await or(E.sourceFile,p.readFile,p.fileCache),N=v.ast?su(v.ast,E.sourceRange):null;if(!N)return null;let I=N.parentPath;for(;I&&!I.isFunction();){if(I.isJSXElement()){let J=I.node.openingElement.name;if(!ae.isJSXIdentifier(J)||!/^[a-z]/.test(J.name))return null}else if(!I.isJSXFragment()&&!I.isReturnStatement()&&!I.isBlockStatement())return null;I=I.parentPath}if(!I)return null;let A=N.get("openingElement").get("attributes").filter(J=>J.isJSXAttribute()&&ae.isJSXIdentifier(J.node.name,{name:x.propName}));if(A.length!==1)return null;let C=A[0];if(!C?.isJSXAttribute())return null;let O=C.get("value"),L=O.isJSXExpressionContainer()?O.get("expression"):O;if(!L.isExpression())return null;let X=await r(L.node,L.scope,E.sourceFile,p.readFile,p.exists,p.fileCache,p.visited),j=X===void 0?void 0:tn(X,x.remainingPath);if(j===void 0)return null;S.push(j)}return S}async function c(p){let h=vI(p.binding,p.sourceInfo);if(!h||!p.graph)return null;let x=["component-prop",p.currentFile,p.binding.identifier.start??p.binding.path.node.start??-1,h.componentName,h.propName].join(":");if(p.visited.has(x))return null;p.visited.add(x);try{return await u(p,h,p.graph)}finally{p.visited.delete(x)}}async function u(p,h,x){let b=[...x.elements.values()].filter(C=>kI(C,p.currentFile,h.componentName,h.exportName));if(b.length!==1)return null;let S=b[0],E=S.attributes?.find(C=>C.name===h.propName);if(E&&!E.source){let C=await d({caller:S,propName:h.propName,remainingPath:h.remainingPath,readFile:p.readFile,fileCache:p.fileCache});if(C)return bm(C,{componentName:h.componentName,propName:h.propName,file:S.sourceFile})}if(!E?.source){let C=await f({caller:S,propName:h.propName,remainingPath:h.remainingPath,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited});if(C)return bm(C,{componentName:h.componentName,propName:h.propName,file:S.sourceFile});let O=SS(p.binding,h.componentName,h.propName);if(!O||O.propName!==h.propName)return null;let L=await r(O.expressionPath.node,O.expressionPath.scope,p.currentFile,p.readFile,p.exists,p.fileCache,p.visited);if(L===void 0)return null;let X=h.remainingPath;return X.length>0&&tn(L,X)===void 0?null:{kind:"value",file:p.currentFile,root:{kind:"binding",name:h.propName},path:X,sourceKind:"binding",semanticKind:"component-prop",displayExpression:O.displayPath,chainPrefix:[{kind:"component-prop",file:p.currentFile,displayName:O.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let v=await or(S.sourceFile,p.readFile,p.fileCache);if(!v.ast)return null;let N=mI(v.ast,v.source,E.source.expression,E.sourceRange)??xa(v.ast,v.source,E.source.expression);if(!N)return null;let I={...E.source,expression:Ki(E.source.expression,h.remainingPath),path:[...E.source.path,...h.remainingPath]},A=await o({currentFile:S.sourceFile,expressionPath:N,sourceInfo:I,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited});return A?bm(A.kind==="external"?A:{...A,displayExpression:I.expression},{componentName:h.componentName,propName:h.propName,file:S.sourceFile}):null}async function d(p){let h=await or(p.caller.sourceFile,p.readFile,p.fileCache);if(!h.ast)return null;let x=su(h.ast,p.caller.sourceRange);if(!x)return null;let b=x.get("openingElement").get("attributes").find(N=>N.isJSXAttribute()&&N.node.name.type==="JSXIdentifier"&&N.node.name.name===p.propName);if(!b?.isJSXAttribute())return null;let S=b.get("value"),E=S.isStringLiteral()?S:S.isJSXExpressionContainer()?S.get("expression"):null;if(!E?.isExpression())return null;let v=ya(E.node);return v?{kind:"value",file:p.caller.sourceFile,root:{kind:"expression",sourceRange:v},path:p.remainingPath,sourceKind:"binding",semanticKind:"component-prop",displayExpression:p.propName,editMode:"upstream",diagnostics:[]}:null}async function f(p){let h=await or(p.caller.sourceFile,p.readFile,p.fileCache);if(!h.ast)return null;let x=su(h.ast,p.caller.sourceRange);if(!x)return null;let b=x.get("openingElement");for(let S of b.get("attributes")){if(!S.isJSXSpreadAttribute())continue;let E=S.get("argument");if(!E.isExpression())continue;let v=await i({expression:E.node,scope:E.scope,source:h.source,currentFile:p.caller.sourceFile,readFile:p.readFile,exists:p.exists,fileCache:p.fileCache,visited:p.visited});if(!v)continue;let N=[{kind:"property",name:p.propName},...p.remainingPath],I={...v,expression:Ki(v.expression,N),path:[...v.path,...N]},A=await o({currentFile:p.caller.sourceFile,expressionPath:E,sourceInfo:I,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited});if(A)return A.kind==="external"?A:{...A,displayExpression:I.expression}}return null}async function m(p){let{currentFile:h,binding:x,readFile:b,exists:S,fileCache:E,visited:v}=p,N=x.path.parentPath;if(!N||!N.isImportDeclaration())return null;let I=N.node.source.value;if(typeof I!="string")return null;let A=await No(h,I,S);if(!A)return null;if(x.path.isImportDefaultSpecifier()){let J=await or(A,b,E),Y=J.ast?Sm(J.ast,"default"):null,$=await g({file:A,exportName:"default",readFile:b,exists:S,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:E,visited:v});return!$||$.kind!=="static"?null:{kind:"static",file:Y?.kind==="default-expression"?$.file:A,root:Y?.kind==="default-expression"?$.root:{kind:"default-export"},value:$.value,sourceKind:"imported-binding"}}if(!x.path.isImportSpecifier())return null;let C=x.path.node.imported,O=ae.isIdentifier(C)?C.name:C.value,L=await or(A,b,E),X=L.ast?Sm(L.ast,O):null,j=await g({file:A,exportName:O,readFile:b,exists:S,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:E,visited:v});return j?j.kind==="external"?j:{kind:"static",file:X?.kind==="re-export"?j.file:A,root:X?.kind==="re-export"||j.root.kind==="binding"&&j.root.name!==X?.name?j.root:{kind:"named-export",name:O},value:j.value,sourceKind:"imported-binding"}:null}async function g(p){let{file:h,exportName:x,readFile:b,exists:S,fileCache:E,visited:v}=p,N=`export::${h}::${x}`;if(!v.has(N)){v.add(N);try{let I=await or(h,b,E);if(!I.ast)return;let A=Sm(I.ast,x);if(!A)return;if(A.kind==="re-export"){if(!A.source||!A.name)return;let X=await No(h,A.source,S);return X?g({...p,file:X,exportName:A.name}):void 0}let C=A.kind==="default-expression"?ae.isIdentifier(A.expression)?A.expression.name:void 0:A.name;if(!C)return;let O=Ji(I.ast).getBinding(C);if(!O)return;let L=await s({currentFile:h,binding:O,readFile:b,exists:S,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:E,visited:v});return L?.kind==="static"&&Array.isArray(L.value)&&co(O)?void 0:L??void 0}finally{v.delete(N)}}}return{resolveExportValue:g,resolveComponentPropBinding:c,resolveComponentPropValues:l,resolveBindingTarget:s}}import*as xe from"@babel/types";function Im(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=nr(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!iM(s,r)?null:{callPath:s,basePath:i}}function iM(e,t){let n=e.node.callee;return!xe.isMemberExpression(n)||!xe.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}function NI(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:Rl(r,t)}function CI(e,t){return e?xe.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}function RI(e,t,n,r,o){let i=xe.isExpression(e.body)?e.body:e.body.body.find(a=>xe.isReturnStatement(a))?.argument;if(!i||!xe.isExpression(i))return;let s=Em(i,t,n,r,o);return typeof s=="number"?s:void 0}function Em(e,t,n,r,o){if(xe.isNumericLiteral(e)||xe.isStringLiteral(e)||xe.isBooleanLiteral(e))return e.value;if(xe.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(xe.isMemberExpression(e)){let i=ru(e,t);if(i)return tn(r,i);let s=ru(e,n);return s?tn(o,s):void 0}if(xe.isBinaryExpression(e)&&e.operator==="-"){let i=xe.isExpression(e.left)?Em(e.left,t,n,r,o):void 0,s=xe.isExpression(e.right)?Em(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function sM(e){if(xe.isExpression(e.body))return e.body;for(let t of e.body.body)if(xe.isReturnStatement(t)&&t.argument&&xe.isExpression(t.argument))return t.argument;return null}function aM(e,t,n){let r=ti(e,t,n);return typeof r=="boolean"?r:void 0}function ti(e,t,n){if(xe.isStringLiteral(e)||xe.isNumericLiteral(e)||xe.isBooleanLiteral(e))return e.value;if(xe.isNullLiteral(e))return null;if(xe.isIdentifier(e))return e.name===t?n:void 0;if(xe.isMemberExpression(e)){let r=ru(e,t);return r?tn(n,r):void 0}if(xe.isUnaryExpression(e)&&e.operator==="!"){let r=ti(e.argument,t,n);return r===void 0?void 0:!r}if(xe.isLogicalExpression(e)){let r=ti(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&ti(e.right,t,n);if(e.operator==="||")return r||ti(e.right,t,n)}if(xe.isBinaryExpression(e)){let r=xe.isExpression(e.left)?ti(e.left,t,n):void 0,o=xe.isExpression(e.right)?ti(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 AI(e){let t=[],n=e;for(;xe.isMemberExpression(n)||xe.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(xe.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(xe.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(xe.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(xe.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return xe.isIdentifier(n)?{base:n.name,segments:t}:null}function wI(e){return e.some(t=>t.kind==="dynamic")}function PI(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}function TI(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 cM(e,t){let n=[],r=[];for(let o of t){let i=tn(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}}function OI(e){let{resolveBindingTarget:t,evaluateStaticExpression:n,buildExpressionSourceInfo:r,resolveSourceInfoProvenance:o,resolveComponentPropValues:i}=e;async function s(g){let{currentFile:p,callPath:h,readFile:x,exists:b,fileCache:S,visited:E}=g,v=h.node.callee;if(!xe.isMemberExpression(v)||!xe.isIdentifier(v.property)||v.property.name!=="map")return null;let N=h.get("callee");if(!N.isMemberExpression())return null;let I=N.get("object");if(Array.isArray(I)||!I.isExpression())return null;let A=await a({currentFile:p,expressionPath:I,readFile:x,exists:b,graph:g.graph,externalSourceResolvers:g.externalSourceResolvers,externalAdapters:g.externalAdapters,functionCallContracts:g.functionCallContracts,fileCache:S,visited:E});return!A||!Array.isArray(A.value)||A.value.length===0?null:A}async function a(g){let{currentFile:p,expressionPath:h,readFile:x,exists:b,fileCache:S,visited:E}=g;if(h.isIdentifier()){let v=h.scope.getBinding(h.node.name);if(!v||co(v,h.node))return null;let N=await t({currentFile:p,binding:v,readFile:x,exists:b,graph:g.graph,externalSourceResolvers:g.externalSourceResolvers,externalAdapters:g.externalAdapters,functionCallContracts:g.functionCallContracts,fileCache:S,visited:E});return N?.kind==="static"?N:null}if(h.isCallExpression())return c({currentFile:p,callPath:h,readFile:x,exists:b,graph:g.graph,externalSourceResolvers:g.externalSourceResolvers,externalAdapters:g.externalAdapters,functionCallContracts:g.functionCallContracts,fileCache:S,visited:E});if(h.isTSAsExpression()||h.isTSSatisfiesExpression()||h.isTSNonNullExpression()){let v=h.get("expression");if(!Array.isArray(v)&&v.isExpression())return a({...g,expressionPath:v})}if(h.isArrayExpression()){let v=ya(h.node);if(!v)return null;let N=await n(h.node,h.scope,p,x,b,S,E);return Array.isArray(N)?{kind:"static",file:p,root:{kind:"expression",sourceRange:v},value:N,sourceKind:"binding"}:null}if(h.isMemberExpression()){let v=await r({expression:h.node,scope:h.scope,currentFile:p,readFile:x,exists:b,fileCache:S,visited:E});if(!v)return null;let N=await o({currentFile:p,expressionPath:h,sourceInfo:v,readFile:x,exists:b,graph:g.graph,externalSourceResolvers:g.externalSourceResolvers,externalAdapters:g.externalAdapters,functionCallContracts:g.functionCallContracts,fileCache:S,visited:E});if(!N||N.kind==="external")return null;let I=await l({currentFile:p,expressionPath:h,provenance:N,readFile:x,exists:b,graph:g.graph,externalSourceResolvers:g.externalSourceResolvers,externalAdapters:g.externalAdapters,functionCallContracts:g.functionCallContracts,fileCache:S,visited:E});if(!I||I.kind!=="static")return null;if(N.collectionPathMap?.length){let C=cM(I.value,N.collectionPathMap);if(C)return{kind:"static",file:N.file,root:N.root,value:C.value,sourceKind:N.sourceKind,collectionPathMap:C.collectionPathMap}}let A=tn(I.value,N.path);return Array.isArray(A)?{kind:"static",file:N.file,root:N.root,value:A,sourceKind:N.sourceKind,pathPrefix:N.path,collectionIndexMap:N.collectionIndexMap,collectionPathMap:N.collectionPathMap}:null}return null}async function l(g){let{provenance:p}=g;if(p.root.kind==="binding"){let S=g.expressionPath.scope.getBinding(p.root.name);if(!S&&p.file!==g.currentFile){let E=await or(p.file,g.readFile,g.fileCache);S=E.ast?Ji(E.ast).getBinding(p.root.name):void 0}return!S||co(S,g.expressionPath.node)?null:await t({currentFile:p.file,binding:S,readFile:g.readFile,exists:g.exists,graph:g.graph,externalSourceResolvers:g.externalSourceResolvers,externalAdapters:g.externalAdapters,functionCallContracts:g.functionCallContracts,fileCache:g.fileCache,visited:g.visited})}if(p.root.kind!=="expression")return null;let h=await or(p.file,g.readFile,g.fileCache);if(!h.ast)return null;let x=fI(h.ast,p.root.sourceRange);if(!x)return null;let b=await n(x.node,x.scope,p.file,g.readFile,g.exists,g.fileCache,g.visited);return b===void 0?null:{kind:"static",file:p.file,root:p.root,value:b,sourceKind:p.sourceKind}}async function c(g){return await u(g)??await d(g)??await f(g)}async function u(g){let{callPath:p}=g,h=p.node.callee;if(!xe.isMemberExpression(h)||!xe.isIdentifier(h.property)||h.property.name!=="filter")return null;let x=p.get("callee");if(!x.isMemberExpression())return null;let b=x.get("object");if(Array.isArray(b)||!b.isExpression())return null;let S=await a({currentFile:g.currentFile,expressionPath:b,readFile:g.readFile,exists:g.exists,graph:g.graph,externalSourceResolvers:g.externalSourceResolvers,externalAdapters:g.externalAdapters,functionCallContracts:g.functionCallContracts,fileCache:g.fileCache,visited:g.visited});if(!S||!Array.isArray(S.value))return null;let[E]=p.node.arguments;if(!xe.isArrowFunctionExpression(E)&&!xe.isFunctionExpression(E))return null;let v=E.params[0];if(!xe.isIdentifier(v))return null;let N=sM(E);if(!N)return null;let I=[],A=[],C=[];for(let[O,L]of S.value.entries()){let X=aM(N,v.name,L);if(typeof X!="boolean")return null;if(X){I.push(L),A.push(S.collectionIndexMap?.[O]??O);let j=S.collectionPathMap?.[O];j&&C.push(j)}}return{...S,value:I,pathPrefix:S.pathPrefix,collectionIndexMap:A,...C.length>0?{collectionPathMap:C}:{}}}async function d(g){let{callPath:p}=g,h=p.node.callee;if(!xe.isMemberExpression(h)||!xe.isIdentifier(h.property)||h.property.name!=="slice")return null;let x=p.get("callee");if(!x.isMemberExpression())return null;let b=x.get("object");if(Array.isArray(b)||!b.isExpression())return null;let S=await a({currentFile:g.currentFile,expressionPath:b,readFile:g.readFile,exists:g.exists,graph:g.graph,externalSourceResolvers:g.externalSourceResolvers,externalAdapters:g.externalAdapters,functionCallContracts:g.functionCallContracts,fileCache:g.fileCache,visited:g.visited});if(!S||!Array.isArray(S.value))return null;let[E,v]=p.node.arguments,N=CI(E,0),I=CI(v,S.value.length);if(N===null||I===null)return null;let A=Math.max(0,N<0?S.value.length+N:N),C=Math.max(0,I<0?S.value.length+I:I),O=S.value.map((X,j)=>S.collectionIndexMap?.[j]??j).slice(A,C),L=S.collectionPathMap?.slice(A,C);return{...S,value:S.value.slice(A,C),pathPrefix:S.pathPrefix,collectionIndexMap:O,...L?{collectionPathMap:L}:{}}}async function f(g){let{callPath:p}=g,h=p.node.callee;if(!xe.isMemberExpression(h)||!xe.isIdentifier(h.property)||h.property.name!=="sort"&&h.property.name!=="toSorted")return null;let x=p.get("callee");if(!x.isMemberExpression())return null;let b=x.get("object");if(Array.isArray(b)||!b.isExpression())return null;let S=await a({currentFile:g.currentFile,expressionPath:b,readFile:g.readFile,exists:g.exists,graph:g.graph,externalSourceResolvers:g.externalSourceResolvers,externalAdapters:g.externalAdapters,functionCallContracts:g.functionCallContracts,fileCache:g.fileCache,visited:g.visited});if(!S||!Array.isArray(S.value))return null;let[E]=p.node.arguments;if(!xe.isArrowFunctionExpression(E)&&!xe.isFunctionExpression(E))return null;let[v,N]=E.params;if(!xe.isIdentifier(v)||!xe.isIdentifier(N))return null;let I=S.value.map((C,O)=>({value:C,sourceIndex:S.collectionIndexMap?.[O]??O,originalIndex:O})),A=[...I];for(let C of I)for(let O of I)if(RI(E,v.name,N.name,C.value,O.value)===void 0)return null;return A.sort((C,O)=>{let L=RI(E,v.name,N.name,C.value,O.value)??0;return L===0?C.originalIndex-O.originalIndex:L}),{...S,value:A.map(C=>C.value),pathPrefix:S.pathPrefix,collectionIndexMap:A.map(C=>C.sourceIndex),...S.collectionPathMap?{collectionPathMap:A.map(C=>S.collectionPathMap?.[C.originalIndex]).filter(C=>!!C)}:{}}}async function m(g){let p=null,h=!1,x,b=[];for(let E of g.segments){if(E.kind!=="dynamic")continue;let v=await r({expression:E.expression,scope:g.expressionPath.scope,source:g.fileCache.get(g.currentFile)?.source,currentFile:g.currentFile,readFile:g.readFile,exists:g.exists,fileCache:g.fileCache,visited:g.visited});if(!v)return null;let N=Im(g.expressionPath,v.base),I;if(N){h=!0;let A=await s({currentFile:g.currentFile,callPath:N.callPath,readFile:g.readFile,exists:g.exists,graph:g.graph,externalSourceResolvers:g.externalSourceResolvers,externalAdapters:g.externalAdapters,functionCallContracts:g.functionCallContracts,fileCache:g.fileCache,visited:g.visited});if(!A||!Array.isArray(A.value))return null;I=A.value.map((C,O)=>{let L=tn(A.value,[{kind:"index",index:O},...N.basePath,...v.path]);return PI(L)}),x??=A.collectionIndexMap}else{let A=await i({...g,sourceInfo:v});if(!A)return null;I=A.map(PI)}if(I.some(A=>A===null)||p!==null&&p!==I.length)return null;p=I.length,b.push(I)}if(p===null||p===0)return null;let S=[];for(let E=0;E<p;E+=1){let v=[...g.rootPath],N=0;for(let I of g.segments){if(I.kind==="dynamic"){let A=b[N]?.[E];if(!A)return null;v.push(A),N+=1;continue}v.push({...I})}S.push(v)}return{sourceKind:h||p>1?"repeat-template":"binding",...x?{collectionIndexMap:x}:{},collectionPathMap:S}}return{resolveRepeatCollectionTarget:s,resolveCollectionCallTarget:c,resolveDynamicMemberPathMap:m}}var{normalizeExpressionWithScope:lM,evaluateStaticExpression:cu}=iI({resolveBindingTarget:e=>lu(e)}),{resolveRepeatCollectionTarget:uM,resolveCollectionCallTarget:dM,resolveDynamicMemberPathMap:fM}=OI({resolveBindingTarget:e=>lu(e),evaluateStaticExpression:cu,buildExpressionSourceInfo:kr,resolveSourceInfoProvenance:Gn,resolveComponentPropValues:e=>gM(e)}),{resolveExportValue:pM,resolveComponentPropBinding:mM,resolveComponentPropValues:gM,resolveBindingTarget:lu}=_I({resolveExternalExpression:Nm,resolveCollectionCallTarget:dM,evaluateStaticExpression:cu,resolveSourceInfoProvenance:Gn,buildExpressionSourceInfo:kr});function VI(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}var LI=new WeakMap;function hM(e){let t=LI.get(e);return t||(t=new WeakMap,LI.set(e,t)),t}function FI(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 KI(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=ou(s,t,n);if(!a)return null;let l=iu(a,r.sourceRange);if(!l)return null;let c=await kr({expression:l.node,scope:l.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!c){let f=await Om({currentFile:t,expressionPath:l,readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:new Set});return f?_m(f,Vi(l.node,n)):null}let u=new Set,d=await BM({currentFile:t,expressionPath:l,segment:{...r,source:c},readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:u});return d?_m(d,c.expression):null}async function Xi(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=ou(i,t,n);if(!s)return null;let a=e.sourceRange?iu(s,e.sourceRange):e.expression!==void 0?xa(s,n,e.expression):null;if(!a)return null;let l=uu(a);if(!l.isIdentifier()&&!l.isMemberExpression())return null;let c=new Set,u=await kr({expression:l.node,scope:l.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:c}),d=u?await Gn({currentFile:t,expressionPath:l,sourceInfo:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:c}):await ZI({currentFile:t,expressionPath:l,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:c});return _m(d,e.expression??Vi(l.node,n))}async function Pm(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=ou(i,t,n);if(!s)return Ln("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?yM({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}):xM({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}async function kr(e){if(_e.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!_e.isMemberExpression(e.expression))return null;let t=await lM(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:Vi(e.expression,e.source),base:t.base,path:t.path}:null}function _m(e,t){if(!e||e.kind==="value"&&e.editMode==="readonly")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}:{}}}async function yM(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:l}=e,c=iu(r,o.sourceRange),u=c?await kr({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:i,exists:s,fileCache:a,visited:l}):null;if(!u){if(!c||c.isStringLiteral()||c.isTemplateLiteral()&&c.node.expressions.length===0)return DI(t,o.value);let f=await Om({currentFile:t,expressionPath:c,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:l});return f?f.kind==="external"?UI(t,f):Rm(t,Vi(c.node,n),f):bM({expression:c.node,scope:c.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:l,functionCallContracts:e.functionCallContracts})}if(!c)return Ln("unsupported-expression","Unable to locate text expression for provenance resolution");let d=await Gn({currentFile:t,expressionPath:c,sourceInfo:u,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:l});if(!d){let f=Cm(c.node);if(f)return Ln(f.code,f.message);let m=c.scope.getBinding(u.base);if(m?.path.isVariableDeclarator()){let g=Cm(m.path.node.init);if(g)return Ln(g.code,g.message)}return m?.path.isVariableDeclarator()&&_e.isCallExpression(m.path.node.init)?SM("unsupported-expression",HI(m.path.node.init,e.functionCallContracts)):Ln("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return d.kind==="external"?UI(t,d):Rm(t,u.expression,d)}async function xM(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:l}=e;if(!o.conditionSource)return Ln("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let c=xa(r,n,o.conditionExpression);if(!c)return Ln("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await Gn({currentFile:t,expressionPath:c,sourceInfo:o.conditionSource,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:l});if(!u)return Ln("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(u.kind==="external")return Ln("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let d=Rm(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 DI(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 bM(e){let t=await XI(e);if(t.length===0)return Ln("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(EM(e.expression))return JI(t);if(WI(e.expression))return Ln("unsupported-expression","i18n helpers require a static message id string");if(_e.isMemberExpression(e.expression)&&e.expression.computed&&!_e.isNumericLiteral(e.expression.property)&&!_e.isStringLiteral(e.expression.property))return Ln("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return Ln(n.code,n.message)}function Ln(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function SM(e,t){return JI([{code:e,message:t}])}function JI(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function EM(e){return _e.isCallExpression(e)||_e.isConditionalExpression(e)||_e.isLogicalExpression(e)||_e.isBinaryExpression(e)}function Ea(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 XI(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:l}=e,c=Cm(t);if(c)return[c];if(_e.isCallExpression(t))return[{code:"unsupported-expression",message:HI(t,l)}];if(_e.isMemberExpression(t)&&t.computed){let u=t.property;if(!_e.isNumericLiteral(u)&&!_e.isStringLiteral(u)){if(!_e.isExpression(u))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let f=await cu(u,n,r,o,i,s,a);if(typeof f!="string"&&!Number.isInteger(f))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}]}}return _e.isBinaryExpression(t)?Ea([...await vm(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):_e.isLogicalExpression(t)?Ea([...await vm(t.left,t.right,e),{code:"unsupported-expression",message:t.operator==="??"||t.operator==="||"?"Fallback expressions are recognized but remain readonly until a safer composition editing strategy is available":"Complex conditional expressions are recognized but remain readonly until a safer editing strategy is available"}]):_e.isConditionalExpression(t)?Ea([...await vm(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 Cm(e){return WI(e)?MI("i18n helpers require a static message id string"):CM(e)?MI("CMS helpers require static entry id and field path string arguments"):null}async function vm(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await XI({...t,expression:o}));return r}function IM(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:[vM(e.sourceType)]}}async function Nm(e){for(let n of AM){if(!BI(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return $I(jI(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(!BI(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return $I(jI(r),e.externalAdapters)}return null}function vM(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function kM(e){return{code:"external-source-readonly",message:e}}function MI(e){return{code:"unsupported-expression",message:e}}function Am(e){return!e||!_e.isCallExpression(e)?null:_e.isIdentifier(e.callee)?e.callee.name:_e.isMemberExpression(e.callee)&&!e.callee.computed&&_e.isIdentifier(e.callee.object)&&_e.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function BI(e,t){if(!t||t.length===0)return!0;let n=Am(e.node);return n?t.includes(n):!1}function jI(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:Ea(e.diagnostics??[])}:{match:e,diagnostics:[]}}function $I(e,t){let n=IM(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:Ea([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function _M(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!_e.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!_e.isStringLiteral(n)||!_e.isStringLiteral(r))return null;let o=n.value,i=r.value;return{sourceType:"cms-field",sourceId:`${o}:${i}`,file:`cms://${o}/${i.replace(/\./g,"/")}`,displayPath:`${o}.${i}`}}function CM(e){return!!e&&_e.isCallExpression(e)&&_e.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!_e.isStringLiteral(e.arguments[0])||!_e.isStringLiteral(e.arguments[1]))}function zI(e){if(!(!e||!_e.isCallExpression(e))){if(_e.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&_e.isStringLiteral(t)?t.value:null}if(_e.isMemberExpression(e.callee)&&!e.callee.computed&&_e.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&_e.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!_e.isObjectExpression(t))return null;for(let n of t.properties)if(_e.isObjectProperty(n)&&!n.computed&&(_e.isIdentifier(n.key)&&n.key.name==="id"||_e.isStringLiteral(n.key)&&n.key.value==="id")&&_e.isStringLiteral(n.value))return n.value.value;return null}}}function WI(e){return zI(e)===null}async function RM(e,t,n){let r=new Set,o=Sa.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=Sa.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"]:[Sa.posix.join(i,"locales"),Sa.posix.join(i,"messages")];for(let a of s){let l=Sa.posix.join(a,`${t}.json`);if(await n(l))return l}}return null}async function PM(e){let t=zI(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await RM(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function NM(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!_e.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!_e.isExpression(n))return null;let o=await cu(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:[kM("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var AM=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>_M(e)},{helperNames:["apiField"],resolve:e=>NM(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>PM({currentFile:e,expressionPath:t,exists:n})}];function wm(e){return{...e,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Derived display values are readonly because no identity-preserving write target exists"}]}}function UI(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 Rm(e,t,n){let r={kind:"value",root:n.root,path:n.path.length>0?n.path:[]},o=n.path.some(c=>c.kind==="index"),i=MM(n),s;n.semanticKind?s=n.semanticKind:i?s="config-entry":n.sourceKind==="repeat-template"?s="repeat-template":n.path.length===0?s=n.sourceKind==="imported-binding"?"imported-binding":"binding":s=o?"array-item":"object-field";let a=n.displayExpression??t,l=[...n.chainPrefix??[]];return n.sourceKind==="binding"?l.push({kind:"binding",file:n.file,displayName:n.root.kind==="binding"?n.root.name:a,canEditHere:n.editMode!=="readonly"}):n.sourceKind==="imported-binding"?l.push({kind:"imported-binding",file:n.file,displayName:n.root.kind==="named-export"?n.root.name:"default",canEditHere:n.editMode!=="readonly"}):n.sourceKind==="repeat-template"&&l.push({kind:"repeat-template",file:n.file,displayName:t,canEditHere:n.editMode!=="readonly"}),n.path.length>0&&n.sourceKind!=="repeat-template"&&l.push({kind:o?"array-item":"object-field",file:n.file,displayName:a,canEditHere:n.editMode!=="readonly"}),i&&l.push({kind:"config-entry",file:n.file,displayName:i.displayPath,canEditHere:n.editMode!=="readonly"}),{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:n.editMode==="readonly"?l.map(c=>({...c,canEditHere:!1})):l,confidence:n.sourceKind==="repeat-template"?"safe-derived":"exact",editMode:n.editMode??(n.file===e?"direct":"proxy"),diagnostics:n.diagnostics??[]}}var wM=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function Tm(e,t){let n=[...wM,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function HI(e,t){let n=e.callee;return _e.isIdentifier(n)&&Tm(n.name,t)?.purity==="side-effect"?`Helper "${n.name}" is registered as side-effectful and remains readonly`:"Function calls remain readonly because purity does not establish an identity-preserving write target"}async function Om(e){let t=await Nm(e);if(t)return t;let n=await GI({...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 kr({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 Gn({...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 FM(e)}async function GI(e){let t=await ir({...e,allowComposed:!1});if(t?.kind!=="source")return null;let n=uu(e.expressionPath);return n.isIdentifier()||n.isMemberExpression()?t.provenance:wm(t.provenance)}async function ir(e){let t=uu(e.expressionPath),n=LM(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 kr({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 Gn({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 kr({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 Gn({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 ir({...e,expressionPath:r,allowComposed:!0}),a=await ir({...e,expressionPath:o,allowComposed:!1}),l=await ir({...e,expressionPath:i,allowComposed:!1});return km(s,a,l)}if(t.isCallExpression())return TM({...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 ir({...e,expressionPath:r,allowComposed:!0}),s=await ir({...e,expressionPath:o,allowComposed:!0});return km(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 ir({...e,expressionPath:r,allowComposed:!0}),s=await ir({...e,expressionPath:o,allowComposed:!0});return km(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:ir({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function uu(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 TM(e){let t=Am(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:ir({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(_e.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:ir({...e,expressionPath:o,allowComposed:!1})}}return null}function km(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!OM(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function OM(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 LM(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function FM(e){if(!e.expressionPath.isCallExpression())return null;let t=Am(e.expressionPath.node);if(!t)return null;let n=Tm(t,e.functionCallContracts);if(!n||n.purity!=="pure")return null;let r=n.sourceArgIndex??0,o=e.expressionPath.get(`arguments.${r}`);if(!o||Array.isArray(o)||!o.isExpression())return null;let i=await YI({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});return i?wm(i):null}async function YI(e){let t=await Nm({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 kr({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 Gn({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 Om({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 DM(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!_e.isCallExpression(t))return null;let n=t.callee;if(!_e.isIdentifier(n))return null;let r=Tm(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}`);if(!s||Array.isArray(s)||!s.isExpression())return null;let a=await YI({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});return a?wm(a):null}function MM(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=Ki(t,e.path);return{sourceId:o,displayPath:o}}async function BM(e){let t=e.segment.source;return t?Gn({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 Gn(e){let t=e.sourceInfo,n=Im(e.expressionPath,t.base);if(n){let c=await uM({currentFile:e.currentFile,callPath:n.callPath,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,fileCache:e.fileCache,visited:e.visited});if(!c){let p=NI(n.callPath,[...n.basePath,...t.path]);return oa(p)?FI(e.currentFile,p.sourceId,p.displayPath):null}let u=TI(c,[...n.basePath,...t.path]),d=c.collectionIndexMap?.[0]??0,f=[...c.pathPrefix??[],{kind:"index",index:d},...n.basePath,...t.path],m=[{kind:"index",index:0},...n.basePath,...t.path];return tn(c.value,m)===void 0?null:{kind:"value",file:c.file,root:c.root,path:u?.[0]??f,sourceKind:"repeat-template",collectionIndexMap:c.collectionIndexMap,...u?{collectionPathMap:u}:{}}}let r=e.expressionPath.scope.getBinding(t.base);if(!r)return null;if(r.path.isImportNamespaceSpecifier()){let c=t.path[0],u=r.path.parentPath;if(!c||c.kind!=="property"||!u?.isImportDeclaration())return null;let d=await No(e.currentFile,u.node.source.value,e.exists);if(!d)return null;let f=await pM({file:d,exportName:c.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(!f||f.kind==="external")return null;let m=t.path.slice(1);return tn(f.value,m)===void 0?null:{kind:"value",file:f.file,root:f.root,path:m,sourceKind:"imported-binding",collectionIndexMap:f.collectionIndexMap}}let o=Sp(r);if(o){let c=o.expressionPath,u=await kr({expression:c.node,scope:c.scope,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(u){let d=await Gn({...e,expressionPath:c,sourceInfo:{...u,expression:Ki(u.expression,t.path),path:[...u.path,...t.path]}});if(d)return d}else if(r.constant){let d=`dynamic-alias:${e.currentFile}:${c.node.start}`;if(e.visited.has(d))return null;e.visited.add(d);try{let f=await ZI({...e,expressionPath:uu(c),memberSuffix:t.path});if(f?.kind==="value")return f}finally{e.visited.delete(d)}}if(t.path.length===0){let d=await GI({currentFile:e.currentFile,expressionPath:c,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(d)return d}}if(r.kind==="param")return mM({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 DM({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=_l(r,t.path,hM(e.fileCache));if(oa(s))return FI(e.currentFile,s.sourceId,s.displayPath);let a=await lu({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:tn(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}async function ZI(e){let t=AI(e.expressionPath.node);if(!t||!wI(t.segments))return null;let n=await Gn({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 fM({...e,rootPath:n.path,segments:t.segments});if(!r)return null;let o=r.collectionPathMap.map(i=>[...i,...e.memberSuffix??[]]);if(e.memberSuffix){let i=e.expressionPath.scope.getBinding(t.base),s=i?await lu({...e,binding:i}):null;if(s?.kind!=="static"||o.some(a=>tn(s.value,a.slice(n.path.length))===void 0))return null}return{...n,path:o[0]??n.path,sourceKind:r.sourceKind,displayExpression:Vi(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:o}}async function qI(e){let t=jM(e.propertyName);if(t.owner==="blocked")return bo(t.owner,t.diagnostic);if(t.owner==="class-name-source"||t.owner==="style")return bo(t.owner,{code:"owner-delegated",message:`Property '${e.propertyName}' is owned by ${t.owner}`});let n=e.element.attributes?.filter(c=>c.name===e.propertyName)??[];if(n.length>1)return bo("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 c of i)o.push({kind:"spread",order:c.order,spread:c,target:await UM(e,c)});o.sort((c,u)=>c.order-u.order);let s=o.at(-1);if(!s)return{status:"missing",owner:"generic"};if(o.filter(c=>c.kind==="spread"&&c.order>s.order).some(c=>!c.target))return bo("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}:bo("generic",{code:"ambiguous-property-source",message:`The final spread source for '${e.propertyName}' is not provably writable`});let l=o.filter(c=>c.kind==="spread"&&c.order<s.order);return e.operation==="remove"&&l.length>0?bo("generic",{code:"remove-exposes-spread",message:`Removing '${e.propertyName}' would expose an earlier spread source`}):$M(e,s.attribute)}async function $M(e,t){if(t.resolution&&t.resolution.status!=="resolved"&&!t.source){let r=await Xi({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}}:bo("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 Xi({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"?bo("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 UM(e,t){let n=t.source?.expression;if(!n)return;let r=await Xi({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:VM(r,e.propertyName)}}function VM(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 bo(e,t){return{status:"blocked",owner:e,...t?{diagnostic:t}:{}}}function QI(e){let t=new Map;for(let r of e.elements.values()){if(r.importedFrom===void 0)continue;let o=t.get(r.importedFrom);o||(o={candidates:[],keys:new Map},t.set(r.importedFrom,o)),o.candidates.push(r)}let n=r=>{if(ni(r.tag))return r.identity.key;let o=t.get(r.sourceFile);if(!o)return null;if(o.keys.has(r.componentName))return o.keys.get(r.componentName);let i=o.candidates.filter(a=>zM(a,r.componentName)),s=i.length===1?i[0].identity.key:null;return o.keys.set(r.componentName,s),s};return r=>KM({...r,graph:e},n)}function KM(e,t){let{key:n,element:r,graph:o,provenances:i}=e,s=XM(n,r,o,t),a=s?.tag??(ni(r.tag)?r.tag:r.componentName),l=s?.identity.key??t(r,o)??n,c=HM(s),u=GM(n,r,o,i,s),d=JM(n,r,o,i,l);return{componentName:a,instanceKey:l,templateOwner:WM(s??r,a),...c.length>0?{variantKeys:c}:{},...u.length>0?{slotKeys:u}:{},editableStrategy:d,impactScope:YM(d),alternativeStrategies:ZM(d)}}function JM(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return Lm(e,n)?"instance":!ni(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function XM(e,t,n,r){if(ni(t.tag))return t;let o=Lm(e,n);if(o)return o;let i=r(t,n);return i?n.elements.get(i)??null:null}function zM(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function WM(e,t){return ni(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function HM(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 GM(e,t,n,r,o){let i=new Set,s=Lm(e,n);s&&o?.identity.key===s.identity.key&&i.add("children");for(let a of r.values()){let l=a?.chain.find(u=>u.kind==="component-prop");if(!l)continue;let c=l.displayName.split(".").pop();c&&i.add(c)}return i.size===0&&ni(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function Lm(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(ni(r.tag))return r;n=r.parentKey}return null}function ni(e){return/^[A-Z]/.test(e)}function YM(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function ZM(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}function nv(e){let t=e.isRepeat??(e.graph?sB(e.element,e.graph):!1),n=e.propertyProvenance??new Map,r=e.repeatTargets??new Map,o=iB(e.element.attributes??[]),i=[...r.values()].some(u=>u.ok),s=o.map(u=>qM({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,l=(e.element.attributeSpreads??[]).slice().sort((u,d)=>u.order-d.order).map(u=>({raw:u.raw,sourceRange:aB(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."}]})),c=t&&e.selectionRef?.instanceIndex!==void 0&&i;return{documentVersion:e.documentVersion,...e.selectionRef?{selectionRef:e.selectionRef}:{},items:s,spreads:l,creation:t?{selection:c?"materialize":"unsupported",template:"unsupported"}:{selection:a?"unsupported":"direct",template:a?"unsupported":"direct"}}}function qM(e){let{attribute:t,provenance:n,repeatTarget:r}=e,o=e.selectionRef?.instanceIndex!==void 0&&r?.ok===!0?r:null,i=QM(t,n,e.isRepeat),s=["selection","template"].map(h=>({scope:h,result:Ll({state:n,scope:h,operation:"set",selectionRef:e.selectionRef,isRepeat:e.isRepeat,repeatTarget:r})})),a=s.find(({result:h})=>h.ok)?.result,l=a?.ok?a.target:void 0,c=l?.kind==="value-binding"&&o&&(JSON.stringify(l.locator.root)!==JSON.stringify(o.selectedParentObjectLocator.root)||JSON.stringify(l.locator.path??[])!==JSON.stringify([...o.selectedParentObjectLocator.path??[],{kind:"property",name:t.name}]))?null:o,u=eB(t,n,c,e.isRepeat),d=l?rB(l,e.element,t.name):void 0,f=s.filter(({result:h})=>h.ok).map(({scope:h})=>h),m=f.length>0?nB(n,o,e.element):"unsupported",g=o?"repeat-item":e.isRepeat?"repeat-template":"node",p=oB(t,n,r);if(f.length===0&&p.length===0){let h=s.find(({result:x})=>!x.ok)?.result;h&&!h.ok&&p.push({code:h.code,message:h.reason})}return{name:t.name,source:i,resolution:u,editMode:m,sourceScope:g,allowedWriteScopes:f,...d?{effectiveWriteTarget:d}:{},diagnostics:p}}function QM(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 eB(e,t,n,r){return n?ev(n.selectedResolution):t?.status==="blocked"?{status:"unresolved"}:r&&t?.status==="binding"?{status:"unresolved"}:ev(tB(e))}function tB(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 ev(e){return!e||e.status==="unresolved"?{status:"unresolved"}:e.status==="undefined"?{status:"undefined"}:{status:"resolved",value:e.value}}function nB(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 rB(e,t,n){return e.kind==="repeat-property"?{kind:"value-path",file:e.target.sourceFile,isProxy:e.target.sourceFile!==t.sourceFile,displayPath:tv({...e.target.selectedParentObjectLocator,path:[...e.target.selectedParentObjectLocator.path??[],{kind:"property",name:n}]})}:e.kind==="value-binding"?{kind:"value-path",file:e.file,isProxy:e.file!==t.sourceFile,displayPath:tv(e.locator)}:{kind:"jsx-node",file:t.sourceFile,isProxy:!1,displayPath:t.componentName+" > "+n}}function oB(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 iB(e){let t=new Set;return e.filter(n=>t.has(n.name)?!1:(t.add(n.name),!0))}function sB(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 tv(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 aB(e,t){if(!t)return{start:e.startColumn,end:e.endColumn};let n=t.split(`
6
+ `,i.index),m=e.slice(n[d]??0,f===-1?void 0:f).trim();o.push({token:a,variant:u?.[1]??"",alpha:l?Number(l[1]):null,line:d+1,snippet:m.length>wx?`${m.slice(0,wx-1)}\u2026`:m})}return o}function Yc(e){return[...new Set(e)]}var Pw=["@/components/site/","@/lib/generated/","@/lib/cms","@/lib/cms/"],Nw=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Fx=new Set(["require","module","exports","__dirname","__filename"]),gf=_w,Aw=typeof gf=="function"?gf:gf.default;function yf(e,t={}){let n=[],r=ww(t.hostCapabilities),o=mf(e,t.style??Tx),i;try{i=kw(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return{ok:!1,violations:[{code:"parse-failed",message:"Generated source failed Babel parsing."}],styleViolations:o}}t.themeStyleMode==="reject"&&Ow(o)&&n.push({code:"style-forbidden",message:"Generated source must use public semantic design tokens instead of raw colors, hard-coded surfaces, or private tokens."});let s=u=>{n.some(f=>f.code===u.code&&f.name===u.name&&f.source===u.source)||n.push(u)};return Aw(i,{ImportDeclaration(u){a(u.node.source.value)},ExportNamedDeclaration(u){let d=u.node.source?.value;d&&a(d)},ExportAllDeclaration(u){a(u.node.source.value)},CallExpression(u){let d=u.node.callee;if(d.type==="Import"){s({code:"dynamic-import-forbidden",message:"Generated source cannot use dynamic import()."});return}d.type==="Identifier"&&(d.name==="require"?s({code:"commonjs-forbidden",message:"Generated source cannot use CommonJS require().",name:d.name}):(d.name==="eval"||d.name==="Function")&&s({code:"dynamic-code-forbidden",message:`Generated source cannot execute dynamic code through ${d.name}().`,name:d.name}))},NewExpression(u){u.node.callee.type==="Identifier"&&u.node.callee.name==="Function"&&s({code:"dynamic-code-forbidden",message:"Generated source cannot construct functions dynamically through Function().",name:"Function"})},MetaProperty(u){u.node.meta.type==="Identifier"&&u.node.meta.name==="import"&&s({code:"import-meta-forbidden",message:"Generated source cannot use import.meta."})},MemberExpression(u){c(hf(u.node))},OptionalMemberExpression(u){c(hf(u.node))},Identifier(u){u.isReferencedIdentifier()&&c(u.node.name)},JSXAttribute(u){t.rejectInlineStyles&&u.node.name.type==="JSXIdentifier"&&u.node.name.name==="style"&&s({code:"inline-style-forbidden",message:"Generated source cannot use inline style attributes."})},JSXOpeningElement(u){t.rejectStyleElements&&u.node.name.type==="JSXIdentifier"&&u.node.name.name.toLowerCase()==="style"&&s({code:"inline-style-forbidden",message:"Generated source cannot declare style elements."})}}),{ok:n.length===0,violations:n,styleViolations:o};function a(u){if(!(t.trustedManagedImports?.includes(u)&&Rw.safeParse(/^@\/components\/site\/generated\/forms\/form-([^/]+)$/u.exec(u)?.[1]).success)&&!(u.startsWith("./")||u.startsWith("../"))){if(t.allowSiteOwnedImports&&Pw.some(d=>d.endsWith("/")?u.startsWith(d):u===d)){l(u);return}r?Tw(u,r)||s({code:"import-forbidden",message:`Generated source imports a package or public path outside the trusted host capabilities: ${u}.`,source:u}):s({code:t.hostCapabilities===void 0?"host-capabilities-unavailable":"host-capabilities-invalid",message:"Generated code cannot use an external import without trusted host capabilities.",source:u}),l(u)}}function l(u){t.protectedImportPrefixes?.some(d=>u.startsWith(d))&&s({code:"protected-import-forbidden",message:`Generated source cannot import protected host output directly: ${u}.`,source:u})}function c(u){if(!(!u||!Nw.has(u))){if(u==="eval"||u==="Function"){s({code:"dynamic-code-forbidden",message:`Generated source cannot execute dynamic code through ${u}.`,name:u});return}s({code:Fx.has(u)?"commonjs-forbidden":"browser-global-forbidden",message:Fx.has(u)?`Generated source cannot depend on the CommonJS global ${u}.`:`Generated source cannot depend on the restricted global ${u}.`,name:u})}}}function ww(e){if(e==null)return null;let t=Cw.safeParse(e);return t.success?t.data:null}function Tw(e,t){if(t.runtime_dependencies.some(({name:r})=>e===r||e.startsWith(`${r}/`)))return!0;if(!e.startsWith("@/"))return!1;let n=e.slice(2);return t.public_paths.some(r=>{let[o]=r.split("#",1);return o.endsWith("/*")?n.startsWith(o.slice(0,-1)):Dx(n)===Dx(o)})}function Dx(e){return e.replace(/\.(?:jsx?|tsx?|json)$/i,"")}function Ow(e){return e.hardCodedSurfaceHits.length>0||e.rawColorHits.length>0||e.privateTokenHits.length>0}function hf(e){return e.type==="Identifier"?e.name:e.type==="MemberExpression"||e.type==="OptionalMemberExpression"?hf(e.object):null}var Kx="components/site/generated",Bx="{{$INSTANCE}}",qc=5,Uw=/^[a-z][a-z0-9-]{0,48}$/,Vw=/^[a-f0-9]{8}$/,jx=/\.tsx?$/,Kw=/\.json$/,Jw=/\.(?:tsx?|json)$/,Xw=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,xf=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),bf=Dw,zw=typeof bf=="function"?bf:bf.default;function Ww(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>Mx)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=cT(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=jw.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=iT(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${Kx}.`,path:e.generatedRoot}};if(!Jx(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=Ux(r.data.files),s=Ux(e.controlledFiles);if(!lT(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>Mx)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let a=0;for(let[l,c]of r.data.files.entries()){let u=Buffer.byteLength(c.content,"utf8");if(u>Mw)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file exceeds the per-file content limit.",file:c.pathTemplate,path:`files[${l}]`}};a+=u}return a>Bw?{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 Hw(e){let t=Ww(e);if(!t.ok)return t;let n=t.data.generatedRoot,r=Jx(e.manifest.instanceBaseName),o=Math.max(1,Math.min(qc,e.maxAttempts??qc));for(let i=0;i<o;i+=1){let s=sT(e.instanceNameGenerator?.()??Lw(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}`,l=zx(n,a),c=Gw({manifest:e.manifest,generatedRoot:n,instanceName:a,instanceRoot:l,hostCapabilities:e.hostCapabilities??null,availableHostDependencies:e.availableHostDependencies});if(!c.ok)return c;if(!await Zw(e.exists,l,c.data.files))return{ok:!0,data:c.data}}return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:"Unable to allocate a create-only static prefab instance after repeated conflicts."}}}async function Sf(e){let t=Math.max(1,Math.min(qc,e.maxAttempts??qc));for(let n=0;n<t;n+=1){let r=await Hw({...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 Gw(e){let t=Yw(e);if(t)return{ok:!1,error:t};let n=[],r=new Set;for(let s of e.manifest.files){let a=Ls({pathTemplate:s.pathTemplate,generatedRoot:e.generatedRoot,instanceName:e.instanceName,instanceRoot:e.instanceRoot});if(!a.ok)return a;if(r.has(a.data))return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${a.data}`,path:a.data}};r.add(a.data),n.push({kind:"create-only",path:a.data,content:s.content,...s.role?{role:s.role}:{},sourcePathTemplate:s.pathTemplate})}n.sort((s,a)=>s.path.localeCompare(a.path));let o=Ls({pathTemplate:e.manifest.entry.pathTemplate,generatedRoot:e.generatedRoot,instanceName:e.instanceName,instanceRoot:e.instanceRoot});if(!o.ok)return o;if(!n.some(s=>s.path===o.data))return{ok:!1,error:{code:"MATERIALIZATION_ENTRY_INVALID",message:"Entry path must match one of the static prefab files.",path:o.data}};let i=Ef({files:n,instanceRoot:e.instanceRoot,entries:[{path:o.data,export:e.manifest.entry.export}],hostCapabilities:e.hostCapabilities,declaredProjectDependencies:Object.keys(e.manifest.projectDependencies??{}),availableHostDependencies:e.availableHostDependencies});return i.ok?{ok:!0,data:{kind:"static-prefab-materialization",instanceName:e.instanceName,generatedRoot:e.generatedRoot,instanceRoot:e.instanceRoot,entry:{path:o.data,export:e.manifest.entry.export},files:n}}:i}function Yw(e){if(e.availableHostDependencies===void 0)return null;let t=new Set(Object.keys(e.manifest.projectDependencies??{})),n=new Set(e.availableHostDependencies);return n.size!==e.availableHostDependencies.length||[...n].some(r=>!t.has(r))?{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Target host dependency evidence must match declared materialization dependencies."}:[...t].some(r=>!n.has(r))?{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"The target host does not provide every declared materialization dependency."}:[...t].some(r=>!e.hostCapabilities?.runtime_dependencies.some(({name:o})=>o===r))?{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Materialization dependencies exceed the trusted host capability contract."}:null}async function Zw(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function Ls(e){if(e.pathTemplate.split(Bx).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(Bx,e.instanceName),n=aT(t);return n?zx(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||!Jw.test(n)||Xw.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 Ef(e){let{files:t,instanceRoot:n,entries:r,hostCapabilities:o}=e,i=new Set(e.declaredProjectDependencies??[]),s=e.availableHostDependencies===void 0?null:new Set(e.availableHostDependencies),a=new Set(t.map(m=>m.path)),l=new Map,c=new Map(t.map(m=>[m.path,new Set])),u=new Map;for(let m of t){if(Kw.test(m.path)){if(m.path.endsWith(Zc)){let x=$w(m.content);if(!x.success)return Dr("MATERIALIZATION_DATA_UNSUPPORTED",x.error.message,m.path);u.set(m.path,new Set)}else try{JSON.parse(m.content)}catch{return Dr("MATERIALIZATION_DATA_UNSUPPORTED","Static prefab JSON file must contain valid JSON.",m.path)}continue}let g;try{g=Fw(m.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:m.path}}}let p=yf(m.content,{hostCapabilities:o,protectedImportPrefixes:["@/components/site/generated/"],trustedManagedImports:e.trustedManagedImports,rejectInlineStyles:!1,rejectStyleElements:!0,themeStyleMode:e.preserveCapturedStyles?"report":"ignore",style:{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!1,rejectPrivateTokens:!1,rejectTailwindPalette:!1}}),h=Qw(p.violations,m.path);if(h)return{ok:!1,error:h};l.set(m.path,g)}for(let m of t){if(!jx.test(m.path))continue;let g=l.get(m.path),p=null;if(zw(g,{ImportDeclaration(h){let x=$x({importer:m.path,source:h.node.source.value,instanceRoot:n,filePaths:a});if(!x.allowed)p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab imports must resolve within the controlled instance or match the starter allowlist.",file:m.path},h.stop();else if(!x.internalPath&&!eT(h.node.source.value,i,s))p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"External prefab imports must be declared and available in the target host.",file:m.path},h.stop();else if(x.internalPath&&(c.get(m.path).add(x.internalPath),x.internalPath.endsWith(Zc))){let b=nT({importer:m.path,imported:x.internalPath,source:h.node.source.value,ast:g});b.ok?u.get(x.internalPath).add(m.path):(p??=b.error,h.stop())}},ExportAllDeclaration(h){p??={code:"MATERIALIZATION_ENTRY_INVALID",message:"Static prefab files cannot use export-star declarations.",file:m.path},h.stop()},ExportNamedDeclaration(h){if(h.node.source){let x=$x({importer:m.path,source:h.node.source.value,instanceRoot:n,filePaths:a});!x.allowed||!x.internalPath&&!e.trustedManagedImports?.includes(h.node.source.value)?(p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab re-exports must resolve within the controlled instance.",file:m.path},h.stop()):x.internalPath&&c.get(m.path).add(x.internalPath)}},CallExpression(h){if(h.node.callee.type==="Import"){p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use dynamic import().",file:m.path},h.stop();return}h.node.callee.type==="Identifier"&&h.node.callee.name==="require"&&(p??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use require().",file:m.path},h.stop())},NewExpression(h){h.node.callee.type==="Identifier"&&h.node.callee.name==="Function"&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot construct functions dynamically.",file:m.path},h.stop())},MetaProperty(h){h.node.meta.type==="Identifier"&&h.node.meta.name==="import"&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot use import.meta.",file:m.path},h.stop())},MemberExpression(h){let x=Vx(h.node);x&&xf.has(x)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${x}.`,file:m.path},h.stop())},OptionalMemberExpression(h){let x=Vx(h.node);x&&xf.has(x)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${x}.`,file:m.path},h.stop())},Identifier(h){h.isReferencedIdentifier()&&xf.has(h.node.name)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h.node.name}.`,file:m.path},h.stop())},JSXAttribute(h){!e.preserveCapturedStyles||h.node.name.type!=="JSXIdentifier"||h.node.name.name!=="style"||qw(h.node.value)||(p??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot use inline style attributes.",file:m.path},h.stop())},JSXOpeningElement(h){h.node.name.type==="JSXIdentifier"&&h.node.name.name.toLowerCase()==="style"&&(p??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot declare style elements.",file:m.path},h.stop())},StringLiteral(h){e.preserveCapturedStyles&&Qc(h.node.value)&&(p??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Captured styles cannot load URLs or execute CSS expressions.",file:m.path},h.stop())},TemplateElement(h){e.preserveCapturedStyles&&Qc(h.node.value.cooked??h.node.value.raw)&&(p??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Captured styles cannot load URLs or execute CSS expressions.",file:m.path},h.stop())},JSXElement(h){let x=h.node.openingElement.name;e.preserveCapturedStyles&&x.type==="JSXIdentifier"&&["script","iframe","object","embed"].includes(x.name.toLowerCase())&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Captured components cannot embed executable external documents.",file:m.path},h.stop())}}),p)return{ok:!1,error:p}}if(r.length===0)return Dr("MATERIALIZATION_ENTRY_INVALID","Static prefab requires at least one source entry.");let d=new Set;for(let m of r){if(d.has(m.path))return Dr("MATERIALIZATION_PATH_INVALID",`Static prefab contains duplicate source entries: ${m.path}`,m.path);if(d.add(m.path),!jx.test(m.path))return Dr("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must be a .ts/.tsx source module.",m.path);let g=l.get(m.path);if(!g)return Dr("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",m.path);if(!rT(g,m.export))return Dr("MATERIALIZATION_EXPORT_MISSING","Static prefab entry does not declare the manifest export.",m.path)}for(let[m,g]of u)if(g.size!==1)return Dr("MATERIALIZATION_IMPORT_FORBIDDEN","Each component .i18n.json file must have exactly one same-name Client Component static importer.",m);let f=new Set;for(let m of r)for(let g of oT(m.path,c))f.add(g);return f.size!==t.length?Dr("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",r[0]?.path):{ok:!0}}function Qc(e){return/(?:url|expression)\s*\(|@import|javascript:|-moz-binding|\\/iu.test(e)}function qw(e){return e?.type!=="JSXExpressionContainer"||e.expression.type!=="ObjectExpression"?!1:e.expression.properties.every(t=>{if(t.type!=="ObjectProperty"||t.computed)return!1;let n=t.key.type==="Identifier"?t.key.name:t.key.type==="StringLiteral"?t.key.value:null;if(!n||n==="__proto__"||n==="constructor"||n==="prototype"||Qc(n))return!1;let r=t.value;return r.type==="StringLiteral"&&!Qc(r.value)||r.type==="NumericLiteral"||r.type==="NullLiteral"||r.type==="UnaryExpression"&&["-","+"].includes(r.operator)&&r.argument.type==="NumericLiteral"})}function Qw(e,t){let n=e[0];if(!n)return null;let r=new Set(["host-capabilities-unavailable","host-capabilities-invalid","import-forbidden","protected-import-forbidden","dynamic-import-forbidden","commonjs-forbidden"]),o=new Set(["inline-style-forbidden","style-forbidden"]);return{code:r.has(n.code)?"MATERIALIZATION_IMPORT_FORBIDDEN":o.has(n.code)?"MATERIALIZATION_STYLE_FORBIDDEN":"MATERIALIZATION_DATA_UNSUPPORTED",message:n.message,file:t}}function $x(e){if(!e.source.startsWith("./")&&!e.source.startsWith("../"))return{allowed:!0};if(e.source.includes("\\")||e.source.includes("\0"))return{allowed:!1};let t=Mr.posix.normalize(Mr.posix.join(Mr.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 eT(e,t,n){if(n===null)return!0;let r=tT(e);return r===null||t.has(r)&&n.has(r)}function tT(e){if(e.startsWith("@/")||e.startsWith("./")||e.startsWith("../")||e.startsWith("/"))return null;if(e.startsWith("@")){let[t,n]=e.split("/");return t&&n?`${t}/${n}`:e}return e.split("/")[0]||null}function nT(e){let t=Mr.posix.dirname(e.importer),n=Mr.posix.dirname(e.imported),r=Mr.posix.basename(e.importer).replace(/\.tsx?$/,""),o=Mr.posix.basename(e.imported).slice(0,-Zc.length),i=`./${r}${Zc}`;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 rT(e,t){for(let n of e.program.body){if(t.kind==="default"&&n.type==="ExportDefaultDeclaration"||t.kind==="default"&&n.type==="ExportNamedDeclaration"&&n.exportKind!=="type"&&n.specifiers.some(o=>o.type==="ExportSpecifier"&&o.exportKind!=="type"&&o.exported.type==="Identifier"&&o.exported.name==="default"))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 oT(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 Dr(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function iT(e){let t=Xx(e);return t===Kx?t:null}function sT(e){let t=e.trim().toLowerCase();return Vw.test(t)?t:null}function Jx(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 Uw.test(t)?t:null}function Xx(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=Mr.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function aT(e){let t=Xx(e);return!t||t!==e?null:t}function zx(...e){return Mr.posix.join(...e)}function Ux(e){return new Set(e.map(t=>t.pathTemplate))}function cT(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 lT(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Vx(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{createHash as Wf}from"node:crypto";import $f from"@babel/traverse";function If(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 l=Object.freeze([...a]),c=l.find(u=>u.anchorSourceRange!==null&&u.members.length>0)??l.find(u=>u.members.length>0)??l[0];c&&(o.set(s,l),i.set(s,c),r.set(s,Object.freeze({placementUnitKey:s,placementKeys:Object.freeze(l.map(u=>u.placementKey)),sourcePlacementKey:c.placementKey})))}return{placementByKey:t,unitByKey:r,placementsByUnitKey:o,sourcePlacementByUnitKey:i}}function el(e){if(e.node.alternate||!uT(e.get("test")))return!1;let t=e.get("consequent"),n=t.isBlockStatement()?t.get("body"):[t];if(n.length!==1)return!1;let r=n[0];if(r.isThrowStatement())return!0;if(!r.isExpressionStatement())return!1;let o=r.get("expression");if(!o.isCallExpression()||o.node.arguments.length!==0)return!1;let i=o.get("callee");if(!i.isIdentifier())return!1;let s=i.scope.getBinding(i.node.name);if(!s?.constant||s.constantViolations.length>0||!s.path.isImportSpecifier()||s.path.node.importKind==="type")return!1;let a=s.path.node.imported,l=a.type==="Identifier"?a.name:a.value,c=s.path.parentPath;return!!(l==="notFound"&&c?.isImportDeclaration()&&c.node.importKind!=="type"&&c.node.source.value==="next/navigation")}function uT(e){let t=Wx(e);return e.traverse({enter(n){Wx(n)||(t=!1,n.stop())}}),t}function Wx(e){if(e.isAssignmentExpression()||e.isUpdateExpression()||e.isAwaitExpression()||e.isYieldExpression()||e.isNewExpression()||e.isTaggedTemplateExpression()||e.isOptionalCallExpression()||e.isJSXElement()||e.isJSXFragment()||e.isFunction()||e.isUnaryExpression({operator:"delete"}))return!1;if(!e.isCallExpression())return!0;let t=e.get("callee"),n=e.get("arguments");if(!t.isMemberExpression()||t.node.computed||n.length!==1)return!1;let r=t.get("object"),o=t.get("property");if(!r.isIdentifier()||!o.isIdentifier())return!1;if(r.node.name==="Object"&&o.node.name==="keys"&&!r.scope.getBinding("Object"))return!n[0].isSpreadElement();let i=r.scope.getBinding(r.node.name);return!!(o.node.name==="includes"&&n[0].isStringLiteral()&&i?.constant&&i.path.isVariableDeclarator()&&i.path.parentPath?.isVariableDeclaration({kind:"const"}))}import{createHash as LT}from"node:crypto";import ob from"node:path";import*as Ii from"@babel/parser";import wf from"@babel/traverse";import Tf from"@babel/generator";import*as ve from"@babel/types";import Rf from"@babel/generator";import{parse as ET}from"@babel/parser";import Pf from"@babel/traverse";import*as Ue from"@babel/types";import{PortableInvocationBindingSchema as IT}from"@vcp-dev/platform-shared/contracts";import vf from"@babel/traverse";import*as Je from"@babel/types";var Hx=typeof vf=="function"?vf:vf.default;function Pn(e){let t=Yx(e.module,e.exportName,e.parsedModules??new Map([[e.module.file,e.module]]),new Set);return t?Gx(t,e.allowNonRenderingGuards):no("component-export-unresolved","The requested local component export is not a statically resolvable function.",e.module.file)}function pr(e){let t=dT(e.module,e.componentName,e.callSourceRange);return t.kind==="local"?Gx(t.definition):t.kind==="imported"?!e.imported?.module&&!_t(t.specifier)?no("component-external-module-opaque","External package components are opaque to the local source graph.",t.specifier):e.imported?e.imported.module?Pn({module:e.imported.module,exportName:e.imported.exportName,parsedModules:e.imported.parsedModules}):no("component-module-unavailable","The component source module is unavailable in the parsed graph.",e.imported.file):no("component-local-binding-unresolved","The JSX call does not resolve to a statically declared local component function.",e.module.file):no("component-local-binding-unresolved","The JSX call does not resolve to a statically declared local component function.",e.module.file)}function Gx(e,t=!1){let n=hT(e.module.ast,e.node);if(!n)return no("component-function-unresolved","The component function has no source AST path.",e.module.file);let r=Zx(n,t);if(!r){let s=xT(n);return s?{ok:!0,componentName:e.name,sourceFile:e.module.file,metadataOnly:!1,roots:[s[0]],returnAlternatives:s}:no("component-control-flow-unsupported","Component roots require an expression body or one direct return.",e.module.file)}let o=[],i=qx(r);return nl(r,o)?{ok:!0,componentName:e.name,sourceFile:e.module.file,metadataOnly:i,roots:o}:no("component-root-dynamic","Component return contains an unsupported dynamic or spread root.",e.module.file)}function dT(e,t,n){let r={kind:"unresolved"};return Hx(e.ast,{JSXElement(o){if(!mT(o.node.loc,n))return;let i=o.node.openingElement.name;if(!Je.isJSXIdentifier(i)||i.name!==t)return;let s=o.scope.getBinding(t);if(!s||s.constantViolations.length>0){o.stop();return}if(fT(s.path)){let l=s.path.parentPath;l?.isImportDeclaration()&&(r={kind:"imported",specifier:l.node.source.value}),o.stop();return}let a=pT(s.path);a&&(r={kind:"local",definition:{node:a,name:t,module:e}}),o.stop()}}),r}function fT(e){return e.isImportSpecifier()||e.isImportDefaultSpecifier()||e.isImportNamespaceSpecifier()}function pT(e){if(e.isFunctionDeclaration())return e.node;if(!e.isVariableDeclarator())return null;let t=e.get("init");return!Array.isArray(t)&&Cf(t.node)?t.node:null}function mT(e,t){return e!=null&&e.start.line===t.startLine&&e.start.column===t.startColumn&&e.end.line===t.endLine&&e.end.column===t.endColumn}function Yx(e,t,n,r){let o=`${e.file}#${t}`;if(r.has(o))return null;let i=new Set(r).add(o),s=(u,d)=>{let f=Hr(e.file,u,n),m=f?n.get(f):void 0;return m?Yx(m,d,n,i):null},a=u=>{let d=gT(e,u);if(d)return{...d,module:e};for(let f of e.ast.program.body)if(!(!Je.isImportDeclaration(f)||f.importKind==="type")){for(let m of f.specifiers)if(m.local.name===u){if(Je.isImportDefaultSpecifier(m))return s(f.source.value,"default");if(Je.isImportSpecifier(m)&&m.importKind!=="type")return s(f.source.value,tl(m.imported))}}return null};for(let u of e.ast.program.body){if(Je.isExportDefaultDeclaration(u)&&t==="default"){let d=u.declaration;if(Cf(d))return{node:d,name:ST(d)??"default",module:e};if(Je.isIdentifier(d))return a(d.name)}if(!(!Je.isExportNamedDeclaration(u)||u.exportKind==="type")){if(u.declaration){let d=bT(u.declaration,t);if(d)return a(d)}for(let d of u.specifiers)if(Je.isExportSpecifier(d)&&d.exportKind!=="type"&&tl(d.exported)===t)return u.source?s(u.source.value,tl(d.local)):a(tl(d.local))}}let l=e.ast.program.body.flatMap(u=>{if(!Je.isExportAllDeclaration(u)||u.exportKind==="type"||t==="default")return[];let d=s(u.source.value,t);return d?[d]:[]}),c=l.filter((u,d)=>l.findIndex(f=>f.node===u.node&&f.module.file===u.module.file)===d);return c.length===1?c[0]:null}function gT(e,t){for(let n of e.ast.program.body){let r=Je.isExportNamedDeclaration(n)?n.declaration:n;if(Je.isFunctionDeclaration(r)&&r.id?.name===t)return{node:r,name:t};if(Je.isVariableDeclaration(r)){for(let o of r.declarations)if(Je.isIdentifier(o.id)&&o.id.name===t&&Cf(o.init))return{node:o.init,name:t}}}return null}function hT(e,t){let n=null;return Hx(e,{Function(r){r.node===t&&(n=r,r.stop())}}),n}function Zx(e,t=!1){let n=e.get("body");if(!n.isBlockStatement())return n;let r=n.get("body"),o=r.at(-1);return!o?.isReturnStatement()||!o.get("argument").node||!r.slice(0,-1).every(i=>i.isVariableDeclaration()||i.isFunctionDeclaration()||yT(i)||t&&i.isIfStatement()&&el(i))?null:o.get("argument")}function yT(e){if(!e.isExpressionStatement())return!1;let t=e.get("expression");if(!t.isCallExpression())return!1;let n=t.get("callee");if(!n.isIdentifier())return!1;let r=n.scope.getBinding(n.node.name);if(!r?.constant||!r.path.isImportSpecifier())return!1;let o=r.path.node.imported,i=r.path.parentPath;if(!Je.isIdentifier(o,{name:"useEffect"})||!i?.isImportDeclaration()||i.node.source.value!=="react"||i.node.importKind==="type"||r.path.node.importKind==="type")return!1;let s=t.get("arguments")[0];return!!(s&&(s.isArrowFunctionExpression()||s.isFunctionExpression()))}function xT(e){let t=e.get("body");if(!t.isBlockStatement())return null;let n=kf(t.get("body"));if(!n||n.length<2)return null;let r=[],o=null;for(let i of n){if(!i.isJSXElement())return null;let s=i.node.openingElement.name;if(!Je.isJSXIdentifier(s)||!/^[A-Z]/.test(s.name))return null;let a=i.scope.getBinding(s.name);if(!a||a.constantViolations.length>0||o&&o!==a.path.node||(o=a.path.node,i.node.children.some(l=>!Je.isJSXText(l)||l.value.trim()!=="")||i.node.openingElement.attributes.some(l=>Je.isJSXSpreadAttribute(l)||Je.isJSXAttribute(l)&&Je.isJSXIdentifier(l.name,{name:"children"}))))return null;r.push(i)}return r}function kf(e){for(let[t,n]of e.entries()){if(n.isVariableDeclaration()||n.isFunctionDeclaration())continue;if(n.isReturnStatement()){let a=n.get("argument");return a.node&&t===e.length-1?[a]:null}if(!n.isIfStatement())return null;let r=a=>kf(a.isBlockStatement()?a.get("body"):[a]),o=r(n.get("consequent")),i=n.get("alternate"),s=i.node?t===e.length-1?r(i):null:kf(e.slice(t+1));return o&&s?[...o,...s]:null}return null}function nl(e,t){if(qx(e))return!0;if(e.isJSXFragment()||e.isJSXElement()&&ht(e)){let n=e.get("children");for(let r of Array.isArray(n)?n:[n])if(!r.isJSXText()&&(r.isJSXSpreadChild()||!nl(r,t)))return!1;return!0}if(e.isJSXElement())return t.push(e),!0;if(e.isJSXExpressionContainer()){let n=e.get("expression");return n.isJSXEmptyExpression()||n.isNullLiteral()||nl(n,t)}return e.isParenthesizedExpression()||e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isTypeCastExpression()?nl(e.get("expression"),t):e.isNullLiteral()||e.isStringLiteral()||e.isNumericLiteral()||e.isBooleanLiteral()}function _f(e){return["base","link","meta","script","style","title"].includes(e)}function qx(e){let t=!1,n=r=>{if(r.isJSXElement()){let o=r.node.openingElement.name;return Je.isJSXIdentifier(o)&&_f(o.name)?(t=!0,!0):ht(r)?r.get("children").every(i=>n(i)):!1}if(r.isJSXFragment())return r.get("children").every(o=>n(o));if(r.isJSXText())return r.node.value.trim()==="";if(r.isNullLiteral()||r.isBooleanLiteral()||r.isJSXEmptyExpression())return!0;if(r.isJSXExpressionContainer()||r.isParenthesizedExpression()||r.isTSAsExpression()||r.isTSTypeAssertion()||r.isTSNonNullExpression())return n(r.get("expression"));if(r.isConditionalExpression())return n(r.get("consequent"))&&n(r.get("alternate"));if(r.isArrayExpression())return r.get("elements").every(o=>!o.node||n(o));if(r.isCallExpression()){let o=r.get("callee"),i=r.get("arguments");if(!o.isMemberExpression()||o.node.computed||!Je.isIdentifier(o.node.property,{name:"map"})||i.length!==1)return!1;let s=i[0];if(!s.isArrowFunctionExpression()&&!s.isFunctionExpression())return!1;let a=Zx(s);return a!==null&&n(a)}return!1};return n(e)&&t}function bT(e,t){return Je.isFunctionDeclaration(e)?e.id?.name===t?t:null:Je.isVariableDeclaration(e)&&e.declarations.some(n=>Je.isIdentifier(n.id)&&n.id.name===t)?t:null}function Cf(e){return Je.isFunctionDeclaration(e)||Je.isFunctionExpression(e)||Je.isArrowFunctionExpression(e)}function ST(e){return"id"in e&&e.id&&Je.isIdentifier(e.id)?e.id.name:null}function tl(e){return Je.isIdentifier(e)?e.name:e.value}function no(e,t,n){return{ok:!1,diagnostic:{code:e,message:t,file:n}}}var Nf=typeof Rf=="function"?Rf:Rf.default,Qx=typeof Pf=="function"?Pf:Pf.default,tb=new Set(["sourceBlockId","source_block_id","originalBlockId","original_block_id"]),vT=new Set(["sourceOrder","source_order","originalOrder","original_order"]),kT=new Set(["data-site-block-id","data-site-block-order","data-vcp-block-id","data-vcp-edit-key","data-vcp-order","sourceBlockId","source_block_id","originalBlockId","original_block_id","sourceOrder","source_order","originalOrder","original_order"]),_T=/^[A-Za-z_$][A-Za-z0-9_$]*$/u,CT=/^[A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)*$/u;function oo(e){if(!rb(e)||!Array.isArray(e.bindings))return ro("INVOCATION_INPUT_INVALID","bindings must be an array in a portable invocation.","bindings");let t=AT(e);if(!t||!CT.test(t))return ro("INVOCATION_COMPONENT_INVALID","Portable invocation requires a safe JSX component local name.","component");let n=nb(e.targetBlockId);if(!n.ok)return n;let r=wT(e.targetOrder);if(!r.ok)return r;let o=e.searchParamsIdentifier??"searchParams";if(!_T.test(o))return ro("INVOCATION_VALUE_UNRESOLVED","The route searchParams binding requires a safe local identifier.","searchParamsIdentifier");let i=[],s=[],a=new Set,l=!1,c=!1,u=0;for(let[f,m]of e.bindings.entries()){let g=IT.safeParse(m);if(!g.success)return ro("INVOCATION_VALUE_UNRESOLVED","Portable invocation values must use the closed JSON/server/identity contract.",`bindings.${f}`);let p=g.data;if(a.has(p.propName))return ro("INVOCATION_DUPLICATE_PROP",`Portable invocation contains duplicate prop ${p.propName}.`,`bindings.${f}.propName`);if(a.add(p.propName),vT.has(p.propName))return ro("INVOCATION_SOURCE_METADATA","Source block order cannot be copied or rebound as a component prop.",`bindings.${f}`);if(tb.has(p.propName)&&p.value.kind!=="target-block-id")return ro("INVOCATION_SOURCE_METADATA","Source block identity/order cannot be copied as a business prop.",`bindings.${f}`);if(p.value.kind==="target-block-id"&&(u+=1,u>1))return ro("INVOCATION_DUPLICATE_PROP","A portable invocation may bind the target block identity only once.",`bindings.${f}`);p.value.kind==="route-search-params"&&(l=!0),p.value.kind==="route-params"&&(c=!0),s.push(p),i.push(Ue.jsxAttribute(Ue.jsxIdentifier(p.propName),Ue.jsxExpressionContainer(PT(p.value,n.value,o))))}let d=Ue.jsxElement(Ue.jsxOpeningElement(NT(t),i,!0),null,[],!0);return{ok:!0,plan:{kind:"portable-invocation",component:t,jsx:Nf(d,{jsescOption:{minimal:!0}}).code,bindings:s,targetBlockId:n.value,targetOrder:r.value,requiresRouteSearchParams:l,requiresRouteParams:c,searchParamsIdentifier:l?o:null}}}function RT(e){if(!rb(e)||e.jsx===void 0==(e.source===void 0))return Si("BLOCK_METADATA_INPUT_INVALID","Provide exactly one JSX expression or full source module.","input");let t=nb(e.targetBlockId);if(!t.ok)return Si("BLOCK_METADATA_TARGET_INVALID",t.error.message,"targetBlockId");if(!Number.isSafeInteger(e.targetOrder)||e.targetOrder<0)return Si("BLOCK_METADATA_TARGET_INVALID","targetOrder must be a non-negative safe integer.","targetOrder");let n=e.jsx!==void 0,r,o;try{if(!n&&e.entryExport){let m=Oe("portable-entry.tsx",e.source);if(!m.ok)throw new Error(m.diagnostic.message);o=m.module,r=o.ast}else r=ET(n?e.jsx:e.source,{sourceType:"module",plugins:["jsx","typescript"]})}catch(m){return Si("BLOCK_METADATA_PARSE_FAILED",m instanceof Error?m.message:String(m),n?"jsx":"source")}let i=[],s;if(o&&e.entryExport){let m=Pn({module:o,exportName:e.entryExport.kind==="default"?"default":e.entryExport.name});m.ok&&m.roots.length===1&&(s=m.roots[0],i.push(s.node))}else Qx(r,{JSXElement(m){eb(m)||i.push(m.node)},JSXFragment(m){eb(m)||i.push(m.node)}});if(i.length!==1)return Si("BLOCK_METADATA_ROOT_AMBIGUOUS","Portable block metadata requires exactly one JSX root.",n?"jsx":"source");let a=i[0],l=TT(a);if(!l)return Si("BLOCK_METADATA_ROOT_AMBIGUOUS","Portable block metadata requires exactly one direct JSX element root.",n?"jsx":"source");let c=0,u=0,d=m=>{let g=OT(m.node.name);!g||!kT.has(g)||(g==="data-site-block-id"||g==="data-vcp-block-id"||tb.has(g)?c+=1:u+=1,m.remove())};s?s.traverse({JSXAttribute:d}):Qx(r,{JSXAttribute:d}),l.openingElement.attributes.push(Ue.jsxAttribute(Ue.jsxIdentifier("data-site-block-id"),Ue.stringLiteral(t.value)),Ue.jsxAttribute(Ue.jsxIdentifier("data-site-block-order"),Ue.jsxExpressionContainer(Ue.numericLiteral(e.targetOrder))));let f=n?Nf(a,{jsescOption:{minimal:!0}}).code:Nf(r,{jsescOption:{minimal:!0}}).code;return{ok:!0,plan:{kind:"portable-block-metadata",source:f,jsx:f,targetBlockId:t.value,targetOrder:e.targetOrder,removedSourceBlockIdCount:c,removedSourceOrderCount:u}}}function PT(e,t,n){return e.kind==="route-params"?Ue.identifier("params"):e.kind==="route-search-params"?Ue.identifier(n):e.kind==="target-block-id"?Ue.stringLiteral(t):Af(e.value)}function Af(e){return e===null?Ue.nullLiteral():typeof e=="string"?Ue.stringLiteral(e):typeof e=="number"?Ue.numericLiteral(e):typeof e=="boolean"?Ue.booleanLiteral(e):Array.isArray(e)?Ue.arrayExpression(e.map(t=>Af(t))):Ue.objectExpression(Object.entries(e).map(([t,n])=>Ue.objectProperty(Ue.stringLiteral(t),Af(n))))}function NT(e){let t=e.split("."),n=Ue.jsxIdentifier(t[0]);for(let r of t.slice(1))n=Ue.jsxMemberExpression(n,Ue.jsxIdentifier(r));return n}function AT(e){return typeof e.componentName=="string"?e.componentName:typeof e.component=="string"?e.component:e.component&&typeof e.component=="object"?e.component.localName:null}function nb(e){return typeof e!="string"||e.length===0||e.trim()!==e||e.length>256?{ok:!1,error:{code:"INVOCATION_TARGET_BLOCK_INVALID",path:"targetBlockId",message:"targetBlockId must be a non-blank stable identity."}}:{ok:!0,value:e}}function wT(e){return e!=null?!Number.isSafeInteger(e)||e<0?{ok:!1,error:{code:"INVOCATION_TARGET_ORDER_INVALID",path:"targetOrder",message:"targetOrder must be a non-negative safe integer."}}:{ok:!0,value:e}:{ok:!0,value:null}}function TT(e){if(Ue.isJSXElement(e))return e;let t=e.children.filter(Ue.isJSXElement),n=e.children.some(r=>Ue.isJSXText(r)&&r.value.trim().length>0);return t.length===1&&!n?t[0]??null:null}function eb(e){let t=e.parentPath;for(;t;){if(t.isJSXElement()||t.isJSXFragment())return!0;t=t.parentPath}return!1}function OT(e){return Ue.isJSXIdentifier(e)?e.name:null}function rb(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ro(e,t,n){return{ok:!1,error:{code:e,path:n,message:t}}}function Si(e,t,n){return{ok:!1,error:{code:e,path:n,message:t}}}var Of=typeof Tf=="function"?Tf:Tf.default,FT=typeof wf=="function"?wf:wf.default;function Bs(e){let t=ub(e);if(t)return{ok:!1,error:t};let n=e.projection,r=jf(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,i=BT(n,o),s=HT(e);if(!s.ok)return s;let a={jsx:s.invocation?.jsx??`<${e.component.localName} />`},l=DT(e);if(i){let g=Lf(e);return g.ok?{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:o.placementUnitKey,importStep:l,...s.invocation?{invocation:s.invocation}:{},...s.serverParamsStep?{serverParamsStep:s.serverParamsStep}:{},returnStep:{kind:"insert-return",node:a,placement:o.relation,replaceOriginal:n.container.kind==="starter-placeholder"},rewriteStep:{kind:"insert-root-expression",locator:g.locator,sourceHash:g.sourceHash,node:a,placement:o.relation,replaceOriginal:n.container.kind==="starter-placeholder"}}}:g.result}let c=o.containerSourceRange??n.container.sourceRange,u=o.containerSourceHash??(ol(c,n.container.sourceRange)?n.container.sourceHash:null);if(!c||!u)return Fs("Route page composition does not expose a verifiable container boundary.");let d=Ms(c),f=sb(e.source,d,u,"Route page composition container");if(!f.ok)return f.result;let m=o.anchorSourceRange?Ms(o.anchorSourceRange):void 0;if(m){if(!o.anchorSourceHash)return Fs("Route page composition placement does not expose a verifiable anchor boundary.");let g=sb(e.source,m,o.anchorSourceHash,"Route page composition anchor");if(!g.ok)return g.result}return{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:o.placementUnitKey,importStep:l,...s.invocation?{invocation:s.invocation}:{},...s.serverParamsStep?{serverParamsStep:s.serverParamsStep}:{},insertStep:{kind:"insert-child",parentLocator:d,node:a,placement:o.relation,...m?{anchorLocator:m}:{}},rewriteStep:{kind:"insert-child",parentLocator:d,node:a,placement:o.relation,...m?{anchorLocator:m}:{}}}}}function Mf(e){let t=Oe(e.entryFile,e.source);if(!t.ok)return io("PORTABLE_ROUTE_SOURCE_INVALID",t.diagnostic.message);let n=Qn({route:e.routeId,composition:e.composition??{routeId:e.routeId},entryFile:e.entryFile,version:e.documentVersion,source:e.source,ast:t.module.ast});if(!n.ok)return io("PORTABLE_ROUTE_UNSUPPORTED","Portable route does not expose a supported page-composition boundary.",n.projection.diagnostics);let r=n.projection.placements.flatMap(c=>{if(c.relation!==e.anchor.relation)return[];if(e.anchor.sourceRange)return c.anchorSourceRange&&ol(c.anchorSourceRange,e.anchor.sourceRange)?[{placement:c,matchCount:1}]:[];let u=c.members.reduce((d,f)=>d+cb(f,e.anchor.componentName),0);return u===0?[]:[{placement:c,matchCount:u}]}),o=r.reduce((c,u)=>c+u.matchCount,0);if(o===0)return io("PORTABLE_ROUTE_ANCHOR_MISSING","Portable route anchor was not found in the canonical page composition.");if(o!==1||r.length!==1)return io("PORTABLE_ROUTE_ANCHOR_AMBIGUOUS","Portable route anchor does not identify exactly one page-composition gap.");let i=Bs({routeId:e.routeId,entryFile:e.entryFile,currentDocumentVersion:e.documentVersion,expectedDocumentVersion:e.documentVersion,source:e.source,projection:n.projection,placementKey:r[0].placement.placementKey,component:e.component,invocation:e.invocation});if(!i.ok)return i;let s=e.source,a=i.plan.rewriteStep;if(a.kind==="insert-root-expression"){let c=js({source:s,locator:a.locator,expectedSourceHash:a.sourceHash,action:{kind:"insert",jsx:a.node.jsx,placement:a.placement,replaceOriginal:a.replaceOriginal}});if(!c.ok)return io("PORTABLE_ROUTE_PATCH_FAILED",c.diagnostic.message);s=c.source}else{let c=Vn({source:s,locator:a.parentLocator,node:a.node,placement:a.placement,...a.anchorLocator?{anchorLocator:a.anchorLocator}:{}});if(!c.ok)return io("PORTABLE_ROUTE_PATCH_FAILED",c.diagnostic.message);s=c.source}if(i.plan.serverParamsStep){let c=db({source:s,step:i.plan.serverParamsStep});if(!c.ok)return io("PORTABLE_ROUTE_PATCH_FAILED",c.diagnostic.message);s=c.source}let l=Kn({source:s,moduleSpecifier:i.plan.importStep.moduleSpecifier,imports:i.plan.importStep.imports});return l.ok?{ok:!0,plan:i.plan,patch:{kind:"portable-route-composition-patch",path:e.entryFile,expectedSourceHash:t.module.sourceHash,source:l.source}}:io("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message)}function cb(e,t){return(e.label===t?1:0)+e.children.reduce((n,r)=>n+cb(r,t),0)}function io(e,t,n=[]){return{ok:!1,error:{code:e,message:t,diagnostics:n}}}function DT(e){let t=VT(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 js(e){if(e.locator.root.kind!=="expression"||e.locator.path?.length)return Uo(e.source,"Root expression rewrite requires an exact expression locator.");let t=ds(e.source,"value");if(!t.ok)return Uo(e.source,t.diagnostic.message);let n=Be(t.ast,e.locator);if(!n.ok)return Uo(e.source,n.diagnostic.message);let r=n.match.path;if(!r.isExpression())return Uo(e.source,"Resolved value locator does not point to an expression.");let o=Ei(e.source,r.node.start??null,r.node.end??null);if(!o||o!==e.expectedSourceHash)return Uo(e.source,"Root expression hash no longer matches the current source.");if(e.action.kind==="remove")return r.replaceWith(ve.nullLiteral()),{ok:!0,source:Of(t.ast,{}).code};let i;try{i=Ii.parseExpression(e.action.jsx,{plugins:["jsx","typescript"]})}catch(s){return Uo(e.source,s instanceof Error?s.message:String(s))}return!ve.isJSXElement(i)&&!ve.isJSXFragment(i)?Uo(e.source,"Root expression rewrite requires a JSX insertion expression."):(e.action.kind==="replace"?r.replaceWith(i):r.replaceWith(MT(r.node,i,e.action.placement,e.action.replaceOriginal)),{ok:!0,source:Of(t.ast,{}).code})}function MT(e,t,n,r){if(ve.isNullLiteral(e)||r)return t;let o=ve.isJSXFragment(e)?[...e.children]:[ve.isJSXElement(e)?e:ve.jsxExpressionContainer(e)],s=n==="before"||n==="prepend"?[t,...o]:[...o,t];return ve.jsxFragment(ve.jsxOpeningFragment(),ve.jsxClosingFragment(),s)}function Uo(e,t){return{ok:!1,source:e,diagnostic:{message:t}}}function Bf(e){let t=ub(e);if(t)return{ok:!1,error:t};let n=e.projection,r=yb(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:[]}};if(jT(n,o)){let p=Lf(e);return p.ok?e.operation==="remove-node"&&!ib(n,o.placementUnitKey)?Fs("The last editable page unit cannot be deleted."):e.operation==="move-node"?Fs("A singleton root expression cannot be moved without a safe parent boundary."):{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:p.sourceHash,rewriteStep:{kind:e.operation==="remove-node"?"remove-root-expression":"replace-root-expression",locator:p.locator,sourceHash:p.sourceHash}}}:p.result}let s=Ms(o.sourceRange),a=ur(e.source,s);if(!a.ok||!a.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:a.ok===!1?a.diagnostic.message:"Route page composition source anchor could not be resolved.",diagnostics:a.ok?[]:[Ds(a.diagnostic)]}};if(Ei(e.source,a.match.node.start??null,a.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"){let p=Lf(e);return p.ok?ib(n,o.placementUnitKey)?{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:s}}}:Fs("The last editable page unit cannot be deleted."):p.result}if(e.operation==="replace-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:"replace-node",locator:s}}};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||!UT(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=jf(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 u=c.placement;if(u.placementUnitKey!==e.targetPlacement.placementUnitKey||u.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 d=u.containerSourceRange;if(!d||!u.containerSourceHash)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable container boundary.",diagnostics:[]}};let f=Ms(d),m=ur(e.source,f);if(!m.ok||!m.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:m.ok===!1?m.diagnostic.message:"Route page composition target container could not be resolved.",diagnostics:m.ok?[]:[Ds(m.diagnostic)]}};if(Ei(e.source,m.match.node.start??null,m.match.node.end??null)!==u.containerSourceHash)return ab("Route page composition target container hash no longer matches the current source.");if(u.relation==="before"||u.relation==="after"){let p=u.anchorSourceRange,h=u.anchorSourceHash;if(!p||!h)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable anchor boundary.",diagnostics:[]}};let x=Ms(p),b=ur(e.source,x);return!b.ok||!b.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:b.ok===!1?b.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:b.ok?[]:[Ds(b.diagnostic)]}}:Ei(e.source,b.match.node.start??null,b.match.node.end??null)!==h?ab("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:s,targetParentLocator:f,anchorLocator:x,placement:u.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:s,targetParentLocator:f,placement:u.relation}}}}function ib(e,t){for(let n of e.placementUnitByKey.values())if(n.placementUnitKey!==t&&n.members.length>0)return!0;return!1}function BT(e,t){let n=e.placementUnitByKey.get(t.placementUnitKey);return n&&e.container.kind!=="jsx-container"&&ol(n.sourceRange,e.mutationTarget.sourceRange)&&n.sourceHash===e.mutationTarget.sourceHash?!0:e.container.sourceRange===null&&(e.container.kind==="virtual-route-root"||e.container.kind==="starter-placeholder")}function jT(e,t){return e.container.kind!=="jsx-container"&&ol(t.sourceRange,e.mutationTarget.sourceRange)&&t.sourceHash===e.mutationTarget.sourceHash}function Lf(e){let t=e.projection.mutationTarget,n={kind:"value",root:{kind:"expression",sourceRange:t.sourceRange}},r=ur(e.source,n);return!r.ok||!r.match.node?{ok:!1,result:{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:r.ok===!1?r.diagnostic.message:"Route mutation target could not be resolved.",diagnostics:r.ok?[]:[Ds(r.diagnostic)]}}}:Ei(e.source,r.match.node.start??null,r.match.node.end??null)!==t.sourceHash?{ok:!1,result:lb("Route mutation target hash no longer matches the current source.")}:{ok:!0,locator:n,sourceHash:t.sourceHash}}function sb(e,t,n,r){let o=ur(e,t);return!o.ok||!o.match.node?{ok:!1,result:{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:o.ok===!1?o.diagnostic.message:`${r} could not be resolved.`,diagnostics:o.ok?[]:[Ds(o.diagnostic)]}}}:Ei(e,o.match.node.start??null,o.match.node.end??null)!==n?{ok:!1,result:lb(`${r} hash no longer matches the current source.`)}:{ok:!0}}function lb(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Fs(e){return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:e,diagnostics:[]}}}function ab(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Ds(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function ub(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&&!$T(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 $T(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function UT(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function VT(e,t){let n=ob.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=ob.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Ms(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function Ei(e,t,n){return t==null||n==null?null:`sha256:${LT("sha256").update(e.slice(t,n)).digest("hex")}`}function ol(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}function db(e){let t;try{t=Ii.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]})}catch(r){return{ok:!1,source:e.source,diagnostic:{message:r instanceof Error?r.message:String(r)}}}let n=KT(t,e.step);return n.ok?{ok:!0,source:Of(t,{}).code}:{ok:!1,source:e.source,diagnostic:{message:n.message}}}function KT(e,t){let n=gb(e);if(!n)return{ok:!1,message:"Route default function could not be resolved for searchParams wiring."};let r=Df(n.node.params[0]);if(t.action==="reuse")return n.node.params.length!==1||!r?{ok:!1,message:"Existing route searchParams binding no longer matches the plan."}:pb(r)!==t.identifier?{ok:!1,message:"Existing route searchParams binding no longer matches the plan."}:{ok:!0};let o=fb(n.node.params,t.typescript);if(!o.ok||o.action!=="add"||o.identifier!==t.identifier)return{ok:!1,message:"Route searchParams signature changed before the patch was applied."};if(n.node.params.length===0)return n.node.params.push(t.typescript?Ff():JT()),{ok:!0};let i=n.node.params[0],s=Df(i);return s?(XT(s,t.typescript),{ok:!0}):{ok:!1,message:"Route page parameter is not a supported object pattern."}}function JT(){return ve.objectPattern([ve.objectProperty(ve.identifier("searchParams"),ve.identifier("searchParams"),!1,!0)])}function Ff(){let t=Ii.parse("function __PortablePage({ searchParams }: { searchParams?: Promise<Record<string, string | string[] | undefined>> }) {}",{sourceType:"module",plugins:["typescript"]}).program.body[0];if(!ve.isFunctionDeclaration(t))throw new Error("Failed to construct the canonical searchParams type.");let n=t.params[0];if(!ve.isObjectPattern(n))throw new Error("Failed to construct the canonical searchParams pattern.");return ve.cloneNode(n,!0)}function XT(e,t){let n=ve.objectProperty(ve.identifier("searchParams"),ve.identifier("searchParams"),!1,!0),r=e.properties.findIndex(ve.isRestElement);if(r<0?e.properties.push(n):e.properties.splice(r,0,n),!t)return;let o=mb(e);if(!o){e.typeAnnotation=Ff().typeAnnotation;return}if(!ve.isTSTypeLiteral(o.typeAnnotation))return;let i=Ff().typeAnnotation;if(!i||!ve.isTSTypeAnnotation(i)||!ve.isTSTypeLiteral(i.typeAnnotation))return;let s=i.typeAnnotation.members[0];s&&!zT(o.typeAnnotation)&&o.typeAnnotation.members.push(ve.cloneNode(s,!0))}function zT(e){return e.members.some(t=>!("key"in t)||!t.key?!1:hb(t.key)==="searchParams")}function WT(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 HT(e){if(!e.invocation)return{ok:!0};let t=oo({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder});if(!t.ok)return rl(t.error.message);if(t.plan.requiresRouteParams)return rl("A captured native detail parameter has no independently proven target route binding.","UNSUPPORTED_ROUTE_PARAMS");let n;if(t.plan.requiresRouteSearchParams){let r=GT(e.source,e.entryFile);if(!r.ok)return rl(r.message,"UNSUPPORTED_ROUTE_PARAMS");if(n=r.step,r.step.identifier!==t.plan.searchParamsIdentifier&&(t=oo({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder,searchParamsIdentifier:r.step.identifier}),!t.ok))return rl(t.error.message)}return{ok:!0,invocation:t.plan,...n?{serverParamsStep:n}:{}}}function rl(e,t="PORTABLE_INVOCATION_INVALID"){return{ok:!1,error:{code:t,message:e,diagnostics:[]}}}function GT(e,t){let n;try{n=Ii.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch(s){return{ok:!1,message:s instanceof Error?s.message:String(s)}}if(n.program.directives.some(s=>s.value.value==="use client"))return{ok:!1,message:"Portable route searchParams wiring cannot cross a use client boundary."};let r=gb(n);if(!r)return{ok:!1,message:"Portable route searchParams wiring requires a default server function."};let o=/\.(?:ts|tsx)$/iu.test(t),i=fb(r.node.params,o);return i.ok?{ok:!0,step:{kind:"ensure-search-params",action:i.action,identifier:i.identifier,typescript:o}}:i}function fb(e,t){if(e.length===0)return{ok:!0,action:"add",identifier:"searchParams"};if(e.length!==1)return{ok:!1,message:"Portable route searchParams wiring rejects a default page with multiple parameters."};let n=Df(e[0]);if(!n)return{ok:!1,message:"Portable route searchParams wiring requires an object page parameter or an empty signature."};let r=pb(n);return r==="unsupported"?{ok:!1,message:"Portable route searchParams wiring cannot prove the existing searchParams binding."}:r?{ok:!0,action:"reuse",identifier:r}:t&&!YT(n)?{ok:!1,message:"Portable route searchParams wiring cannot safely extend this typed page signature."}:{ok:!0,action:"add",identifier:"searchParams"}}function Df(e){return!e||ve.isTSParameterProperty(e)?null:ve.isObjectPattern(e)?e:ve.isAssignmentPattern(e)&&ve.isObjectPattern(e.left)?e.left:null}function pb(e){for(let t of e.properties)if(!(!ve.isObjectProperty(t)||t.computed||hb(t.key)!=="searchParams"))return ve.isIdentifier(t.value)?t.value.name:ve.isAssignmentPattern(t.value)&&ve.isIdentifier(t.value.left)?t.value.left.name:"unsupported";return null}function YT(e){let t=mb(e);return t?ve.isTSTypeLiteral(t.typeAnnotation):e.properties.length===0}function mb(e){return e.typeAnnotation&&ve.isTSTypeAnnotation(e.typeAnnotation)?e.typeAnnotation:null}function gb(e){let t=null;return FT(e,{ExportDefaultDeclaration(n){if(t)return;let r=WT(n,n.get("declaration"));r&&(t=r)}}),t}function hb(e){return ve.isIdentifier(e)?e.name:ve.isStringLiteral(e)?e.value:null}var ZT=typeof $f=="function"?$f:$f.default;function Qn(e){if(!e.ast)return er(e,[Vt("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=iO(e.ast);if(!t)return er(e,[Vt("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=aO(t);if(!n.ok)return er(e,[n.diagnostic]);let r=n.expression;if(r.isIdentifier()){let o=lO(r,t);if(o.status==="resolved")r=o.expression;else if(o.status==="invalid")return er(e,[Vt("UNSUPPORTED_PAGE_SHAPE","Route default export local binding is not a supported JSX root")])}if(dO(r,t))return er(e,[Vt("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(r.isNullLiteral())return Vf(e,t,"virtual-route-root",r);if(uO(r)){let o=gO({input:e,source:e.source,expression:r});return Uf(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"},r)}if(r.isConditionalExpression())return er(e,[Vt("UNSUPPORTED_PAGE_SHAPE","Route conditional root contains an unsupported branch shape",{reason:"ambiguous-placement"})]);if(r.isJSXElement()&&!ht(r)&&!Us(r)){let o=Xf(r),i=Sb({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[o]});return Uf(e,t,i,{kind:"virtual-route-root",sourceKind:"jsx-element"},r)}if(r.isJSXElement()||r.isJSXFragment()){let o=pO(r);if(!o.ok)return er(e,[o.diagnostic]);let i=vi(o.path);if(i.unsupported)return er(e,[Vt("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);if(fO(e.source,r,i.members))return Vf(e,t,"starter-placeholder",r);let s=r.isJSXFragment()||ht(r);if(i.members.length===0&&s)return Vf(e,t,"virtual-route-root",r);let a=o.path===r&&s?"virtual-route-root":"jsx-container",l=o.path.isJSXFragment()?"jsx-fragment":"jsx-element",c=Sb({input:e,containerKind:a,sourceKind:l,source:e.source,containerPath:o.path,members:i.members});return Uf(e,t,c,{kind:a,sourceKind:l},r)}return er(e,[Vt("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")])}function jf(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Vt("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:Vt("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function yb(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Vt("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:Vt("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function Eb(e){return e.ok?qT(e.projection):QT(e.projection)}function qT(e){let t=new Map,n=[];for(let c of e.placements)c.members.length===0&&e.placements.length>1||c.members.length>0&&!c.anchorSourceRange||t.has(c.placementUnitKey)||t.set(c.placementUnitKey,c);let r=new Map,o=new Map;for(let[c,u]of t){let d=u.members.flatMap((p,h)=>Ib(e,u,p,h,e.container.placementKey)),f=d.filter(({member:p})=>p.isBusinessMember).map(({sourceMember:p})=>tO(c,p,u.independent)),m=d.length>0?d:[{sourceMember:{key:`source:${c}: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(c,m.map(({sourceMember:p})=>p)),o.set(c,f);let g=m[0]?.sourceMember.key??c;n.push({key:c,containerKey:g,businessMemberKeys:f.map(p=>p.key),isMultiMember:u.memberCount>1})}let i=[...r.values()].flat(),s=[...o.values()].flat(),a=i[0]?.key??null,l=e.placements.map(c=>({kind:"page-composition",placementKey:c.placementKey,documentVersion:e.documentVersion,composition:e.composition,placementUnitKey:c.placementUnitKey,relation:c.relation}));return{status:"supported",version:e.version,composition:e.composition,container:eO(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:l}}function QT(e){let t=e.diagnostics.map(nO);return{status:"unsupported",version:e.version,composition:e.composition,reason:rO(e.diagnostics),diagnostics:t}}function eO(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 Ib(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,l)=>Ib(e,t,a,l,i))]}function tO(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function nO(e){return{code:oO(e),message:e.message}}function rO(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 oO(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 iO(e){let t=null;return ZT(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=sO(o.path);i&&(t=i,n.stop())}}),t}function sO(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 aO(e){let t=e.get("body");if(!t.isBlockStatement()){let s=$s(t);return s?{ok:!0,expression:s}:{ok:!1,diagnostic:Vt("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")}}let n=t.get("body"),r=n.at(-1);if(!r)return{ok:!1,diagnostic:Vt("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")};if(!r.isReturnStatement())return{ok:!1,diagnostic:Vt("UNSUPPORTED_PAGE_SHAPE","Route default export must end with a direct terminal return",{reason:"terminal-return-required"})};for(let s of n.slice(0,-1)){if(s.isIfStatement()){if(!cO(s)&&!el(s))return{ok:!1,diagnostic:Vt("UNSUPPORTED_PAGE_SHAPE","Route guard return shape is not statically safe",{reason:"guard-shape"})};continue}if(vb(s)||kb(s))return{ok:!1,diagnostic:Vt("UNSUPPORTED_PAGE_SHAPE","Route default export contains unsupported control flow before the terminal return",{reason:"control-flow-return"})}}let o=r.get("argument"),i=$s(o);return i?{ok:!0,expression:i}:{ok:!1,diagnostic:Vt("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})}}function cO(e){if(e.node.alternate)return null;let t=e.get("consequent");if(t.isReturnStatement())return t;if(!t.isBlockStatement())return null;let n=t.get("body"),r=n.at(-1);if(!r?.isReturnStatement())return null;for(let o of n.slice(0,-1))if(vb(o)||kb(o))return null;return r}function vb(e){return e.isForStatement()||e.isForInStatement()||e.isForOfStatement()||e.isWhileStatement()||e.isDoWhileStatement()||e.isSwitchStatement()||e.isTryStatement()||e.isWithStatement()}function kb(e){let t=!1;return e.traverse({Function(n){n.skip()},ReturnStatement(){t=!0}}),t}function lO(e,t){let n=t.scope.getBinding(e.node.name);if(!n||n.scope.path.node!==t.node)return{status:"not-local"};if(!n.path.isVariableDeclarator())return{status:"not-local"};let r=n.path.parentPath;if(!r?.isVariableDeclaration()||r.node.kind!=="const")return{status:"invalid"};let o=n.path.get("init");if(Array.isArray(o)||!o.node)return{status:"invalid"};let i=$s(o);return!i||!i.isJSXElement()&&!i.isJSXFragment()?{status:"invalid"}:n.referencePaths.length!==1||n.referencePaths[0]?.node!==e.node||n.constantViolations.length!==0?{status:"invalid"}:{status:"resolved",expression:i}}function uO(e){return e.isConditionalExpression()?xb($s(e.get("consequent")))&&xb($s(e.get("alternate"))):!1}function xb(e){return!!(e&&(e.isJSXElement()||e.isJSXFragment()||e.isNullLiteral()))}function $s(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 dO(e,t){if(e.isIdentifier())return bb(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return bb(n.node.name,t)}return!1}function bb(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 fO(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&Jf(t)}function Jf(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(!Jf(t))return!1;continue}if(t.isJSXElement()&&!Jf(t))return!1}return!0}function pO(e){return{ok:!0,path:e}}function vi(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:zf(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:zn(r.node.loc),businessMemberCount:0,parentSourceRange:zn(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=vi(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=Us(o)?vi(o):null;n||=i?.unsupported??!1,t.push({...Xf(o,i?.members),sourceRange:zn(r.node.loc),parentSourceRange:zn(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:zf(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:zn(r.node.loc),businessMemberCount:1,parentSourceRange:zn(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&ht(r)){let o=vi(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=Us(r)?vi(r):null;n||=o?.unsupported??!1,t.push({...Xf(r,o?.members),parentSourceRange:zn(e.node.loc)})}}return{members:t,unsupported:n}}function Xf(e,t){let n=e.isJSXElement()&&Us(e)?t??vi(e).members:[],r=e.isJSXElement()&&!Us(e)&&!ht(e);return{memberKey:zf(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:zn(e.node.loc),businessMemberCount:r?1:_b(n),parentSourceRange:zn(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:mO(e)}}function Us(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name[0]===t.name[0]?.toLowerCase()}function mO(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 _b(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function il(e){return e.length===0?0:Math.max(1,_b(e))}function Sb(e){let t=zn(e.containerPath.node.loc),n=Hf(e.source,e.containerPath.node.start,e.containerPath.node.end),r=Wn(e.input,e.containerKind,e.sourceKind,t),o=Wn(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:il(e.members)<=1,memberCount:il(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function gO(e){let t=zn(e.expression.node.loc),n=Hf(e.source,e.expression.node.start,e.expression.node.end),r=Wn(e.input,"virtual-route-root","atomic-expression",t),o=Wn(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:Wn(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 Cb(e,t){let n=zn(t.node.loc),r=Hf(e.source,t.node.start,t.node.end);return!n||!r?null:{kind:"expression",documentVersion:e.version,sourceRange:n,sourceHash:r}}function Uf(e,t,n,r,o){let i=Cb(e,o);if(!i)return er(e,[Vt("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let s=n.containerSourceRange??n.sourceRange,a=hO(e,n,s),l=If(a),c={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Pb(t),container:{kind:r.kind,placementKey:n.placementKey,placementUnitKey:n.placementUnitKey,version:e.version,isEmptyPage:n.memberCount===0,sourceKind:r.sourceKind,sourceRange:s,sourceHash:n.sourceHash},placements:a,diagnostics:[],placementByKey:new Map,unitByKey:new Map,placementsByUnitKey:new Map,placementUnitByKey:new Map,mutationTarget:i};return Object.defineProperties(c,{placementByKey:{value:l.placementByKey,enumerable:!1},unitByKey:{value:l.unitByKey,enumerable:!1},placementsByUnitKey:{value:l.placementsByUnitKey,enumerable:!1},placementUnitByKey:{value:l.sourcePlacementByUnitKey,enumerable:!1}}),{ok:!0,projection:c}}function hO(e,t,n){if(t.members.length===0)return[t];let r=[],o=(c,u,d,f,m,g,p=n)=>({...t,placementKey:u,placementUnitKey:d,containerKey:t.placementKey,independent:il(g)<=1,memberCount:il(g),sourceRange:f,sourceHash:f?Kf(e.source,f):null,relation:c,containerSourceRange:p,containerSourceHash:p?Kf(e.source,p):null,anchorSourceRange:m,anchorSourceHash:m?Kf(e.source,m):null,members:g}),i=t.placementKey,s=t.members.map(c=>Wn(e,i,"placement-unit",c.sourceRange)),a=s[0]??t.placementUnitKey,l=s.at(-1)??t.placementUnitKey;r.push(o("prepend",Wn(e,i,"prepend",n),a,n,null,[]));for(let c of t.members){let u=c.parentSourceRange??n,d=Wn(e,i,"placement-unit",c.sourceRange);r.push(o("before",Wn(e,d,"before",c.sourceRange),d,c.sourceRange,c.sourceRange,[c],u)),r.push(o("after",Wn(e,d,"after",c.sourceRange),d,c.sourceRange,c.sourceRange,[c],u))}return r.push(o("append",i,l,n,null,[])),r}function Vf(e,t,n,r){let o=Cb(e,r);if(!o)return er(e,[Vt("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let i=Wn(e,n,"empty-container",void 0),s=Wn(e,n,"empty-unit",void 0),a={placementKey:i,placementUnitKey:s,version:e.version,containerKey:i,independent:!0,memberCount:0,sourceRange:null,sourceHash:null,relation:"append",containerSourceRange:null,containerSourceHash:null,anchorSourceRange:null,anchorSourceHash:null,members:[]},l=If([a]),c={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Pb(t),container:{kind:n,placementKey:i,placementUnitKey:s,version:e.version,isEmptyPage:!0,sourceKind:n==="starter-placeholder"?"starter-placeholder":"jsx-fragment",sourceRange:null,sourceHash:null},placements:[a],diagnostics:[],placementByKey:new Map,unitByKey:new Map,placementsByUnitKey:new Map,placementUnitByKey:new Map,mutationTarget:o};return Object.defineProperties(c,{placementByKey:{value:l.placementByKey,enumerable:!1},unitByKey:{value:l.unitByKey,enumerable:!1},placementsByUnitKey:{value:l.placementsByUnitKey,enumerable:!1},placementUnitByKey:{value:l.sourcePlacementByUnitKey,enumerable:!1}}),{ok:!0,projection:c}}function er(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 Vt(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function Wn(e,t,n,r){return Rb([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function zf(e,t,n){return Rb(["member",e,String(t??-1),String(n??-1)])}function Rb(e){return`pc_${Wf("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function Hf(e,t,n){return t==null||n==null?null:`sha256:${Wf("sha256").update(e.slice(t,n)).digest("hex")}`}function Kf(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:${Wf("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function zn(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function Pb(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}import{createHash as PO}from"node:crypto";import*as tr from"@babel/types";function Nb(e){if(!e.path.isIdentifier())return{kind:"not-alias"};let t=e.path.scope.getBinding(e.path.node.name);if(!t)return{kind:"unbound"};if(t.constantViolations.length>0)return{kind:"reassigned"};let n=t.path;if(!n.isVariableDeclarator())return{kind:"not-alias"};if(e.aliases.has(n.node)||e.aliases.size>=(e.maxDepth??32))return{kind:"guard"};let r=n.get("init");return Array.isArray(r)||!r.node?{kind:"not-alias"}:{kind:"initializer",initializer:r,aliases:new Set(e.aliases).add(n.node)}}import Gf from"@babel/traverse";import*as ki from"@babel/types";var xO=typeof Gf=="function"?Gf:Gf.default,bO=32;function Vo(e,t,n,r=new Set){if(r.has(e.ast)||r.size>=bO)return null;let o=new Set(r).add(e.ast),i;if(xO(e.ast,{Program(d){i=d,d.stop()}}),!i)return null;let s=(d,f)=>{let m=Hr(e.file,d,n),g=m?n.get(m):void 0;return g?Vo(g,f,n,o):null},a=d=>{let f=i.scope.getBinding(d);if(!f||f.constantViolations.length)return null;let m=f.path.parentPath;return m?.isImportDeclaration()?m.node.importKind==="type"?null:f.path.isImportDefaultSpecifier()?s(m.node.source.value,"default"):f.path.isImportSpecifier()&&f.path.node.importKind!=="type"?s(m.node.source.value,sl(f.path.node.imported)):null:f.path.isVariableDeclarator()?f.path.get("init"):f.path},l=[],c=[];for(let d of i.get("body"))if(d.isExportDefaultDeclaration()&&t==="default"){let f=d.get("declaration");l.push(f.isIdentifier()?a(f.node.name):f)}else if(d.isExportNamedDeclaration()&&d.node.exportKind!=="type"){let f=d.get("declaration");f.node&&Object.hasOwn(ki.getBindingIdentifiers(f.node),t)&&l.push(a(t));for(let m of d.node.specifiers)ki.isExportSpecifier(m)&&m.exportKind!=="type"&&sl(m.exported)===t&&l.push(d.node.source?s(d.node.source.value,sl(m.local)):a(sl(m.local)))}else d.isExportAllDeclaration()&&d.node.exportKind!=="type"&&t!=="default"&&c.push(d.node.source.value);if(l.length)return l.length===1?l[0]:null;let u=c.map(d=>s(d,t)).filter(d=>d!==null);return u.length===1?u[0]:null}function sl(e){return ki.isIdentifier(e)?e.name:e.value}import*as Fe from"@babel/types";var SO=32;function Nn(e,t=new Map,n=new Set){if(n.has(e.node)||n.size>=SO)return null;let r=new Set(n).add(e.node),o=t.get(e.node);if(o)return Vs(o,t,r);if(e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isTSSatisfiesExpression()||e.isParenthesizedExpression())return Nn(e.get("expression"),t,r);if(e.isIdentifier()){let i=e.scope.getBinding(e.node.name);return!i||i.constantViolations.length?null:Zf(i,t,r)}if(e.isMemberExpression()||e.isOptionalMemberExpression()){let i=An(e.node.property,e.node.computed),s=e.get("object"),a=Nn(s,t,r);return i!==null&&a?ll(a,i,t,r):null}if(e.isConditionalExpression())return Vs([e.get("consequent"),e.get("alternate")],t,r);if(e.isLogicalExpression())return Vs([e.get("left"),e.get("right")],t,r);if(e.isSequenceExpression()){let i=e.get("expressions").at(-1);return i?Nn(i,t,r):null}if(e.isCallExpression()&&Fe.isIdentifier(e.node.callee)){let i=e.scope.getBinding(e.node.callee.name);if(!i||!_i(i))return null;let s=i.path.isFunctionDeclaration()?i.path:i.path.isVariableDeclarator()?i.path.get("init"):null;if(!s||!(s.isFunctionDeclaration()||s.isFunctionExpression()||s.isArrowFunctionExpression())||s.node.async||s.node.generator)return null;let a=s,l=new Map(t),c=e.get("arguments");for(let[m,g]of a.get("params").entries()){if(!g.isIdentifier())return null;let p=c[m];if(!p?.isExpression())return null;let h=Nn(p,t,r);if(!h)return null;let x=g.scope.getBinding(g.node.name);if(!x)return null;l.set(x.identifier,h)}let u=a.get("body"),d=u.isBlockStatement()?u.get("body")[0]:u;if(!d)return null;let f=d.isReturnStatement()?d.get("argument"):d;return f.node?Nn(f,l,r):null}return[e]}function Zf(e,t=new Map,n=new Set){if(e.constantViolations.length)return null;let r=t.get(e.identifier);if(r)return Vs(r,t,n);if(!e.path.isVariableDeclarator())return null;let o=e.path.get("init");if(!o.node)return null;let i=Nn(o,t,n);if(!i)return null;let s=Yf(e.path.node.id,e.identifier.name);return s?s.reduce((a,l)=>a&&ll(a,l,t,n),i):null}function al(e){if(!e.params.every(n=>Fe.isIdentifier(n)||Fe.isAssignmentPattern(n)&&Fe.isIdentifier(n.left)&&Br(n.right)))return!1;if(!Fe.isBlockStatement(e.body))return Br(e.body);if(e.body.body.length!==1)return!1;let t=e.body.body[0];return Fe.isReturnStatement(t)&&!!t.argument&&Br(t.argument)}function _i(e){if(e.constantViolations.length>0)return!1;if(e.path.isFunctionDeclaration())return al(e.path.node);let t=e.path.isVariableDeclarator()?e.path:e.path.findParent(r=>r.isVariableDeclarator()),n=t?.isVariableDeclarator()?t.node.init:null;return Fe.isArrowFunctionExpression(n)||Fe.isFunctionExpression(n)?al(n):!1}function Br(e){let t=!0;return Fe.traverseFast(e,n=>{(Fe.isCallExpression(n)&&!cl(n)||Fe.isOptionalCallExpression(n)||Fe.isNewExpression(n)||Fe.isAwaitExpression(n)||Fe.isAssignmentExpression(n)||Fe.isUpdateExpression(n)||Fe.isUnaryExpression(n,{operator:"delete"})||Fe.isYieldExpression(n)||Fe.isTaggedTemplateExpression(n))&&(t=!1)}),t}function cl(e){return Fe.isIdentifier(e.callee,{name:"useTranslations"})&&e.arguments.length===1&&Fe.isStringLiteral(e.arguments[0])}function Vs(e,t,n){let r=[];for(let o of e){let i=Nn(o,t,n);if(!i)return null;r.push(...i)}return r.length?r:null}function ll(e,t,n,r=new Set){let o=[];for(let i of e)if(i.isObjectExpression()){let s=i.get("properties");if(s.some(l=>!l.isObjectProperty()||l.node.computed))return null;let a=s.filter(l=>l.isObjectProperty()&&An(l.node.key,!1)===t);if(a.length!==1||!a[0].isObjectProperty())return null;o.push(a[0].get("value"))}else if(i.isArrayExpression()&&/^(?:0|[1-9]\d*)$/u.test(t)){if(i.node.elements.some(a=>Fe.isSpreadElement(a)))return null;let s=i.get("elements")[Number(t)];if(!s?.node||s.isSpreadElement())return null;o.push(s)}else return null;return Vs(o,n,r)}function qf(e,t){let n=Nn(e,t);return!!(n?.length&&n.every(r=>Fe.isLiteral(r.node)&&!r.isRegExpLiteral()||r.isTemplateLiteral()||r.isBinaryExpression()||r.isUnaryExpression()))}function An(e,t){return!t&&Fe.isIdentifier(e)?e.name:Fe.isStringLiteral(e)||Fe.isNumericLiteral(e)?String(e.value):null}function Yf(e,t){if(Fe.isIdentifier(e))return e.name===t?[]:null;if(Fe.isObjectPattern(e))for(let n of e.properties){if(!Fe.isObjectProperty(n)||n.computed)continue;let r=An(n.key,!1),o=Yf(n.value,t);if(r!==null&&o)return[r,...o]}if(Fe.isArrayPattern(e))for(let[n,r]of e.elements.entries()){if(!r)continue;let o=Yf(r,t);if(o)return[String(n),...o]}return null}function Ab(e,t=new Set,n){return wb(e.get("callee"),t,n)}function wb(e,t,n){if(t.has(e.node)||t.size>=32)return{kind:"guard"};if(e.isIdentifier()){let r=e.scope.getBinding(e.node.name);if(!r)return{kind:"unknown"};if(t.has(r.path.node))return{kind:"guard"};let o=new Set(t).add(r.path.node),i=r.path.parentPath;if(i?.isImportDeclaration()&&n){let c=i.node.source.value;if(!(c.startsWith(".")||c.startsWith("@/")))return{kind:"unknown"};let u=r.path.scope.getProgramParent().path.node,d=[...n.values()].find(h=>h.ast.program===u),f=d&&Hr(d.file,c,n),m=f?n.get(f):void 0,g=r.path.isImportDefaultSpecifier()?"default":r.path.isImportSpecifier()&&r.path.node.importKind!=="type"?An(r.path.node.imported,!1):null,p=m&&g&&i.node.importKind!=="type"?Vo(m,g,n):null;return p?Ci(p,o,n):{kind:"guard"}}let s=r.path.isVariableDeclarator()?r.path.get("init"):r.path;if(!s.node)return{kind:"unknown"};let a=Ci(s,o,n);if(a.kind!=="sources")return a;let l=[...a.sources];for(let c of r.constantViolations){if(!c.isAssignmentExpression({operator:"="}))return{kind:"guard"};let u=Ci(c.get("right"),o,n);if(u.kind!=="sources")return{kind:"guard"};l.push(...u.sources)}return{kind:"sources",sources:l,aliases:a.aliases}}if(e.isMemberExpression()||e.isOptionalMemberExpression()){let r=An(e.node.property,e.node.computed),o=e.get("object"),i=Nn(o);if(!i)return{kind:"unknown"};let s=[],a=new Set(t).add(e.node);for(let l of i){if(!l.isObjectExpression())return{kind:"unknown"};if(r===null||l.node.properties.some(d=>d.type!=="ObjectProperty"))return{kind:"guard"};let c=l.get("properties").filter(d=>d.isObjectProperty()&&An(d.node.key,d.node.computed)===r);if(c.length!==1||!c[0].isObjectProperty())return{kind:"guard"};let u=Ci(c[0].get("value"),a,n);if(u.kind!=="sources")return{kind:"guard"};s.push(...u.sources),a=u.aliases}return{kind:"sources",sources:s,aliases:a}}return Ci(e,new Set(t).add(e.node),n)}function Ci(e,t,n){if(e.isIdentifier())return wb(e,t,n);if(e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isParenthesizedExpression())return Ci(e.get("expression"),t,n);if(!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression()))return{kind:"unknown"};let r=e,o=[];for(let s of r.get("params"))s.isAssignmentPattern()&&o.push(s.get("right")),s.traverse({AssignmentPattern(a){o.push(a.get("right"))}});let i=r.get("body");return i.isBlockStatement()?i.traverse({Function(s){s.skip()},ReturnStatement(s){let a=s.get("argument");a.node&&o.push(a),s.skip()}}):o.push(i),{kind:"sources",sources:o,aliases:t}}function dl(e,t){return JSON.stringify([t,e])}var IO=new Set;function Db(e,t){let n=new Map,r=[],o=new Map,i=(g,p)=>JSON.stringify([g,p.loc?.start.line,p.loc?.start.column,p.loc?.end.line,p.loc?.end.column]);for(let g of e.graph.elements.values()){let p=g.sourceRange;o.set(JSON.stringify([g.sourceFile,p.startLine,p.startColumn,p.endLine,p.endColumn]),g)}let s=g=>r.push({code:"render-occurrence-unproven",message:"A block render occurrence cannot be proven statically.",file:g}),a=(g,p)=>!Fb(p)&&[...t].some(h=>e.graph.elements.get(h)?.sourceFile===g);function l(g,p,h,x,b,S=IO){if(g.isIdentifier())return x&&ul(g,x)?x.children.some(v=>l(v.path,v.file,h,v.substitution,b,S)):u({path:g,file:p,active:h,substitution:x,unknownIsRelevant:b,aliases:S});if(g.isCallExpression()||g.isOptionalCallExpression()){let v=g,N=Ab(v,S,e.parsedModules);return N.kind==="guard"||N.kind==="sources"&&N.sources.some(I=>l(I,[...e.parsedModules.values()].find(A=>A.ast.program===I.scope.getProgramParent().path.node)?.file??p,h,x,b,N.aliases))?!0:v.get("arguments").some(I=>l(I,p,h,x,b,S))||N.kind==="unknown"&&b}if(g.isJSXElement()){if(ht(g))return g.get("children").some(L=>l(L,p,h,x,b,S));let v=o.get(i(p,g.node));if(v){if(t.has(v.identity.key))return!0;if(v.boundaryKind==="component-boundary"&&!v.isPublicUiComponent){let L=e.parsedModules.get(v.sourceFile);if(!L)return!1;let X=pr({module:L,componentName:v.tag,callSourceRange:v.sourceRange,...v.importedFrom?{imported:{file:v.importedFrom,module:e.parsedModules.get(v.importedFrom),exportName:v.exportName??v.tag,parsedModules:e.parsedModules}}:{}});return X.ok?X.metadataOnly?!1:c(X,g,v.sourceFile,h,x,S):X.diagnostic.code==="component-external-module-opaque"?Ks(g).some(j=>l(j,p,h,x,!1,S)):a(L.file,X.diagnostic.code)}return g.get("children").some(L=>l(L,p,h,x,b,S))}let N=g.node.openingElement.name;if(!tr.isJSXIdentifier(N))return!1;if(/^[a-z]/.test(N.name))return g.get("children").some(L=>l(L,p,h,x,b,S));let I=e.parsedModules.get(p),A=g.node.loc;if(!I||!A)return!1;let C=RO({path:g,file:p,componentName:N.name,parsedModules:e.parsedModules}),O=pr({module:I,componentName:N.name,callSourceRange:{startLine:A.start.line,startColumn:A.start.column,endLine:A.end.line,endColumn:A.end.column},...C?{imported:C}:{}});return O.ok?O.metadataOnly?!1:c(O,g,p,h,x,S):O.diagnostic.code==="component-external-module-opaque"?Ks(g).some(L=>l(L,p,h,x,!1,S)):a(I.file,O.diagnostic.code)}if(g.isJSXFragment())return g.get("children").some(v=>l(v,p,h,x,b,S));if(g.isJSXExpressionContainer()||g.isParenthesizedExpression()||g.isTSAsExpression()||g.isTSNonNullExpression()||g.isTSTypeAssertion())return l(g.get("expression"),p,h,x,b,S);let E=!1;return g.traverse({"CallExpression|OptionalCallExpression"(v){l(v,p,h,x,b,S)&&(E=!0),v.skip(),E&&v.stop()},ReferencedIdentifier(v){l(v,p,h,x,b,S)&&(E=!0),E&&v.stop()},JSXElement(v){l(v,p,h,x,b,S)&&(E=!0),v.skip(),E&&v.stop()},JSXFragment(v){l(v,p,h,x,b,S)&&(E=!0),v.skip(),E&&v.stop()}}),E?!0:b&&!Ko(g)}function c(g,p,h,x,b,S){let E=`${g.sourceFile}#${g.componentName}`;if(x.has(E))return!1;let v=new Set(x).add(E);return g.returnAlternatives?.some(N=>Ks(N).some(I=>l(I,g.sourceFile,v,null,!1,S)))||g.roots.some(N=>l(N,g.sourceFile,v,null,!1,S))?!0:Tb(g.roots).kind==="none"?!1:Lb(p).some(N=>l(N,h,v,b,!0,S))}function u(g){if(!g.path.isIdentifier())return g.unknownIsRelevant;let p=Nb({path:g.path,aliases:g.aliases});return p.kind==="unbound"?g.unknownIsRelevant&&g.path.node.name!=="undefined":p.kind==="guard"||p.kind==="reassigned"?!0:p.kind==="not-alias"?g.unknownIsRelevant:l(p.initializer,g.file,g.active,g.substitution,g.unknownIsRelevant,p.aliases)?!0:Qf(p.initializer).isIdentifier()?!1:g.unknownIsRelevant&&!Ko(p.initializer)}let d=(g,p,h,x,b,S)=>{if(g.isIdentifier()){l(g,p,x,S,!1)&&s(p);return}if(g.isJSXElement()){if(ht(g)){for(let N of g.get("children"))d(N,p,h,x,b,S);return}let E=o.get(i(p,g.node));if(!E)return;let v=E.identity.key;if(t.has(v)){b||s(p);let N=n.get(v)??[];N.push(dl(v,h)),n.set(v,N)}if(E.boundaryKind==="component-boundary"&&!E.isPublicUiComponent){let N=e.parsedModules.get(E.sourceFile);if(!N)return;let I=pr({module:N,componentName:E.tag,callSourceRange:E.sourceRange,...E.importedFrom?{imported:{file:E.importedFrom,module:e.parsedModules.get(E.importedFrom),exportName:E.exportName??E.tag,parsedModules:e.parsedModules}}:{}});if(!I.ok){if(I.diagnostic.code==="component-external-module-opaque"){Ks(g).some(j=>l(j,p,x,S,!1))&&s(p);return}[...t].some(j=>e.graph.elements.get(j)?.sourceFile===N.file)&&!Fb(I.diagnostic.code)&&s(N.file);return}if(I.metadataOnly)return;let A=`${I.sourceFile}#${I.componentName}`;if(x.has(A)){s(N.file);return}let C=new Set(x).add(A);I.returnAlternatives?.some(j=>Ks(j).some(J=>l(J,I.sourceFile,C,S,!1)))&&s(I.sourceFile);let O=Tb(I.roots),L=CO(g);if(O.kind==="unproven"||O.kind==="supported"&&L){for(let j of Lb(g))if(l(j,p,C,S,!0)){s(p);break}}let X=O.kind==="supported"&&!L?{bindingNode:O.bindingNode,children:g.get("children").map(j=>({path:j,file:p,substitution:S}))}:null;for(let j of I.roots)d(j,I.sourceFile,[...h,v],C,b,X);return}for(let N of g.get("children"))d(N,p,h,x,b,S);return}if(g.isJSXFragment()){for(let E of g.get("children"))d(E,p,h,x,b,S);return}if(g.isJSXExpressionContainer()){let E=g.get("expression");if(S&&!E.isJSXEmptyExpression()){let v=Qf(E);if(ul(v,S)){for(let N of S.children)d(N.path,N.file,h,x,b,N.substitution);return}if(vO(E,S))for(let N of S.children)d(N.path,N.file,h,x,!1,N.substitution)}d(E,p,h,x,b,S);return}if(g.isParenthesizedExpression()||g.isTSAsExpression()||g.isTSNonNullExpression()||g.isTSTypeAssertion()){d(g.get("expression"),p,h,x,b,S);return}l(g,p,x,S,!1)&&s(p),g.traverse({JSXElement(E){d(E,p,h,x,!1,S),E.skip()}})},f=e.parsedModules.get(e.entryFile);if(!f)return{occurrences:n,diagnostics:r};let m=Pn({module:f,exportName:"default",allowNonRenderingGuards:!0});if(!m.ok)return s(e.entryFile),{occurrences:n,diagnostics:r};for(let g of m.roots)d(g,f.file,[],new Set,!0,null);return{occurrences:n,diagnostics:r}}function Qf(e){let t=e;for(;t.isParenthesizedExpression()||t.isTSAsExpression()||t.isTSNonNullExpression()||t.isTSTypeAssertion();)t=t.get("expression");return t}function Ko(e){let t=Qf(e);return t.isStringLiteral()||t.isNumericLiteral()||t.isBooleanLiteral()||t.isNullLiteral()||t.isBigIntLiteral()||t.isJSXElement()||t.isJSXFragment()?!0:t.isIdentifier()?t.node.name==="undefined"&&!t.scope.getBinding("undefined"):t.isTemplateLiteral()?t.node.expressions.length===0:t.isArrayExpression()?t.get("elements").every(n=>!n.node||Ko(n)):t.isConditionalExpression()?Ko(t.get("consequent"))&&Ko(t.get("alternate")):t.isLogicalExpression()?Ko(t.get("left"))&&Ko(t.get("right")):!1}function ul(e,t){if(!e.isIdentifier())return!1;let n=e.scope.getBinding(e.node.name);return!!(n&&(n.path.node===t.bindingNode||n.identifier===t.bindingNode))}function vO(e,t){if(ul(e,t))return!0;let n=!1;return e.traverse({Identifier(r){ul(r,t)&&(n=!0,r.stop())}}),n}function Tb(e){let t=e[0]?.getFunctionParent();if(!t)return{kind:"none"};let n=t.get("params")[0];return n?n.isAssignmentPattern()?Ob(n.get("left"),!0):Ob(n,!1):{kind:"none"}}function Ob(e,t){if(e.isObjectPattern()){let n=[],r=!1;for(let i of e.get("properties")){if(i.isObjectProperty()){if(i.node.computed){mr(i.get("value"))&&(r=!0);continue}let s=i.node.key;(tr.isIdentifier(s)?s.name:tr.isStringLiteral(s)?s.value:null)==="children"&&n.push(i);continue}i.isRestElement()&&mr(i.get("argument"))&&(r=!0)}if(n.length>1)return r||n.some(i=>mr(i.get("value")))?{kind:"unproven"}:{kind:"none"};if(n.length===0)return r?{kind:"unproven"}:{kind:"none"};if(r)return{kind:"unproven"};let o=n[0].get("value");if(o.isIdentifier()){let i=o.scope.getBinding(o.node.name);return!i||i.path.node!==o.node&&i.identifier!==o.node?{kind:"unproven"}:i.constantViolations.length>0?{kind:"unproven"}:i.referencePaths.length===0?{kind:"none"}:i.referencePaths.every(s=>kO(s))?t?{kind:"unproven"}:{kind:"supported",bindingNode:o.node}:{kind:"unproven"}}return mr(o)?{kind:"unproven"}:{kind:"none"}}if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return!n||n.referencePaths.length===0?{kind:"none"}:n.referencePaths.every(r=>_O(r))?{kind:"none"}:{kind:"unproven"}}return mr(e)?{kind:"unproven"}:{kind:"none"}}function mr(e){if(e.isIdentifier()){let t=e.scope.getBinding(e.node.name);return!!(t&&t.referencePaths.length>0)}return e.isAssignmentPattern()?mr(e.get("left")):e.isRestElement()?mr(e.get("argument")):e.isObjectPattern()?e.get("properties").some(t=>t.isObjectProperty()?mr(t.get("value")):t.isRestElement()?mr(t.get("argument")):!0):e.isArrayPattern()?e.get("elements").some(t=>t.node?mr(t):!1):!0}function kO(e){let t=e.parentPath;for(;t&&(t.isParenthesizedExpression()||t.isTSAsExpression()||t.isTSNonNullExpression()||t.isTSTypeAssertion());)t=t.parentPath;if(!t||!t.isJSXExpressionContainer())return!1;let n=t.parentPath;return!!(n&&(n.isJSXElement()||n.isJSXFragment()))}function _O(e){let t=e.parentPath;if(!t||!t.isMemberExpression()&&!t.isOptionalMemberExpression()||t.node.object!==e.node)return!1;let n=t.node.property;return t.node.computed?tr.isStringLiteral(n)&&n.value!=="children":tr.isIdentifier(n)&&n.name!=="children"}function CO(e){for(let t of e.get("openingElement").get("attributes")){if(t.isJSXAttribute()){let n=t.node.name;if(tr.isJSXIdentifier(n)&&n.name==="children")return!0;continue}if(t.isJSXSpreadAttribute()&&Mb(t.get("argument")))return!0}return!1}function Lb(e){let t=e.get("children").map(n=>n);for(let n of e.get("openingElement").get("attributes")){if(n.isJSXAttribute()){let r=n.node.name;if(!tr.isJSXIdentifier(r)||r.name!=="children")continue;let o=n.get("value");o&&!Array.isArray(o)&&t.push(o);continue}if(n.isJSXSpreadAttribute()){let r=n.get("argument");Mb(r)&&t.push(r)}}return t}function Ks(e){let t=e.get("children").map(n=>n);for(let n of e.get("openingElement").get("attributes"))if(n.isJSXSpreadAttribute())t.push(n.get("argument"));else if(n.isJSXAttribute()){let r=n.get("value");r&&!Array.isArray(r)&&t.push(r)}return t}function Mb(e){if(e.isJSXElement()||e.isJSXFragment())return!0;let t=!1;return e.traverse({JSXElement(n){t=!0,n.stop()},JSXFragment(n){t=!0,n.stop()}}),t}function RO(e){let t=e.path.scope.getBinding(e.componentName);if(!t)return;let n=t.path;if(!n.isImportDefaultSpecifier()&&!n.isImportSpecifier())return;let r=n.parentPath;if(!r?.isImportDeclaration())return;let o=Hr(e.file,r.node.source.value,e.parsedModules);if(!o)return;let i=n.isImportDefaultSpecifier()?"default":tr.isIdentifier(n.node.imported)?n.node.imported.name:n.node.imported.value;return{file:o,module:e.parsedModules.get(o),exportName:i,parsedModules:e.parsedModules}}function Fb(e){return e==="component-export-unresolved"||e==="component-local-binding-unresolved"}function $b(e){let t=[],n=[];return Ub(e.element,e,[],e.ownerNode,e.element,[],new Set,t,n),{roots:t,diagnostics:n}}function Ub(e,t,n,r,o,i,s,a,l,c=[]){if(c.length>1&&(e.boundaryKind!=="component-boundary"||e.isPublicUiComponent)){l.push({code:"conditional-component-root-unproven",message:"Conditional returns require one proven local component definition.",file:e.sourceFile});return}if(e.boundaryKind!=="component-boundary"||e.isPublicUiComponent){if(_f(e.tag))return;a.push({element:e,callChain:n,ownerNode:r,ownerMember:o,ownerCallChain:i});return}let u=t.parsedModules.get(e.sourceFile);if(!u){l.push({code:"component-module-unavailable",message:"The component source module is unavailable in the parsed graph.",file:e.sourceFile,structuralPath:e.identity.structuralPath});return}let d=pr({module:u,componentName:e.tag,callSourceRange:e.sourceRange,...e.importedFrom?{imported:{file:e.importedFrom,module:t.parsedModules.get(e.importedFrom),exportName:e.exportName??e.tag,parsedModules:t.parsedModules}}:{}});if(!d.ok){l.push({...d.diagnostic,structuralPath:e.identity.structuralPath});return}if(d.metadataOnly)return;let f=d.sourceFile,m=`${f}#${d.componentName}`;if(s.has(m)){l.push({code:"component-call-cycle",message:"A component call cycle cannot be expanded safely.",file:e.sourceFile,structuralPath:e.identity.structuralPath});return}if(d.roots.length===0){l.push({code:"component-root-empty",message:"A component call has no statically addressable JSX root.",file:f,structuralPath:e.identity.structuralPath});return}let g=[...n,{sourceFile:e.sourceFile,component:e.tag,exportName:e.exportName??e.tag,callLocator:{key:e.identity.key,structuralPath:e.identity.structuralPath,sourceRange:e.sourceRange},...c.length>1?{alternativeLocators:c.map(b=>({key:b.identity.key,structuralPath:b.identity.structuralPath,sourceRange:b.sourceRange}))}:{}}],p=d.roots.length>1?{kind:"component-definition",key:m}:r,h=new Set(s);h.add(m);let x=[];for(let b of d.returnAlternatives??[]){let S=jb(b),E=S?Bb(t.graph,f,S):[];if(E.length!==1){l.push({code:"conditional-component-root-unproven",message:"A conditional call site is absent or ambiguous in the source graph.",file:f});return}x.push(E[0])}for(let b of d.roots){let S=jb(b),E=S?Bb(t.graph,f,S):[];if(E.length!==1){l.push({code:E.length?"component-root-ambiguous":"component-root-unresolved",message:"The component root could not be matched to one source graph node.",file:f,structuralPath:e.identity.structuralPath});continue}Ub(E[0],t,g,p,d.roots.length>1?E[0]:o,d.roots.length>1?g:i,h,a,l,x)}}function Bb(e,t,n){return(e.fileIndex.get(t)??[]).map(r=>e.elements.get(r)).filter(r=>!!r&&r.sourceRange.startLine===n.startLine&&r.sourceRange.startColumn===n.startColumn&&r.sourceRange.endLine===n.endLine&&r.sourceRange.endColumn===n.endColumn)}function jb(e){let t=e.node.loc;return t?{startLine:t.start.line,startColumn:t.start.column,endLine:t.end.line,endColumn:t.end.column}:null}function fl(e){let t=[],n=[];if(e.projection.entryFile!==e.entryFile||!Kb(e.projection.composition,e.composition)||e.graph.composition&&!Kb(e.graph.composition,e.composition))return{roots:[],diagnostics:[Js("composition-mismatch",e.entryFile)]};if(!e.parsedModules.has(e.entryFile))return{roots:[],diagnostics:[Js("entry-module-unavailable",e.entryFile)]};for(let i of e.graph.diagnostics??[])t.push({code:`source-graph-${i.code}`,message:i.message,file:i.path});let r=e.projection.placements.filter(i=>i.relation==="before").flatMap(i=>i.members);for(let i of r){if(i.kind==="text")continue;if(i.kind!=="jsx-element"||!i.sourceRange){t.push(Js("route-member-not-addressable",e.entryFile));continue}let s=AO(e.graph,e.entryFile,i.sourceRange);if(s.length!==1){t.push(Js(s.length?"route-root-ambiguous":"route-root-unresolved",e.entryFile));continue}let a=s[0],l=$b({element:a,graph:e.graph,parsedModules:e.parsedModules,ownerNode:{kind:"route-member",key:a.parentKey??`${e.entryFile}#${e.projection.container.placementKey}`}});t.push(...l.diagnostics);for(let c of l.roots){let u=c.ownerMember;n.push({...c,parentStructuralPath:u.parentKey?e.graph.elements.get(u.parentKey)?.identity.structuralPath??null:null})}}let o=Db(e,new Set(n.map(i=>i.element.identity.key)));t.push(...o.diagnostics);for(let i of n){let s=i.element.identity.key,a=dl(s,i.callChain.map(l=>l.callLocator.key));o.occurrences.get(s)?.filter(l=>l===a).length!==1&&t.push(Js("render-occurrence-unproven",i.element.sourceFile))}return{roots:NO(n,e.composition,o.occurrences),diagnostics:t}}function NO(e,t,n){let r=e.map(i=>{let s=i.element,a=n.get(s.identity.key)??[],l=i.callChain.map(c=>c.callLocator.key);return{rootKey:PO("sha256").update(JSON.stringify([t,l,s.identity.key])).digest("hex"),rootRef:{key:s.identity.key,...a.length>1?{instanceIndex:a.indexOf(dl(s.identity.key,l)),instanceCount:a.length}:{}},sourceFile:s.sourceFile,structuralPath:s.identity.structuralPath,sourceRange:s.sourceRange,callChain:i.callChain,ownerNode:i.ownerNode,ownerMemberKey:i.ownerMember.identity.key,ownerCallKeys:i.ownerCallChain.map(c=>c.callLocator.key),parentStructuralPath:i.parentStructuralPath,siblingRootKeys:[],siblingIndex:0}}),o=new Map;for(let i of r){let s=Vb(i);o.set(s,[...o.get(s)??[],i])}return r.map(i=>{let s=o.get(Vb(i))??[i];return{...i,siblingIndex:s.indexOf(i),siblingRootKeys:s.filter(a=>a!==i).map(a=>a.rootKey)}})}function Vb(e){return JSON.stringify([e.ownerNode.kind,e.ownerNode.key,e.parentStructuralPath,e.ownerCallKeys])}function AO(e,t,n){return(e.fileIndex.get(t)??[]).map(r=>e.elements.get(r)).filter(r=>!!r&&r.sourceRange.startLine===n.startLine&&r.sourceRange.startColumn===n.startColumn&&r.sourceRange.endLine===n.endLine&&r.sourceRange.endColumn===n.endColumn)}function Kb(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function Js(e,t){return{code:e,message:"Page block roots could not be proven from the current source graph.",file:t}}import{SiteEditPageBlockDirectorySchema as wO,SiteEditPageBlockDescriptorSchema as TO,SiteEditSourcePathSchema as Xb}from"@vcp-dev/platform-shared/contracts";function pl(e){let t=new Map;for(let[n,r]of e.elements){let o=/^[A-Z]/.test(r.tag),i={file:r.sourceFile,componentName:r.componentName,isProxy:o},s=r.boundaryKind,a=[];r.isOpaque&&a.push({kind:"opaque-region",reason:`Component '${r.tag}' is opaque: internal structure not editable`}),o&&!r.isOpaque&&a.push({kind:"component-boundary",reason:`Component '${r.tag}' boundary: editing requires source file access`});let l={key:n,writeTarget:i,boundaryKind:s,parentKey:r.parentKey,childKeys:[...r.childKeys],constraints:a};t.set(n,l)}for(let n of e.regions){let r=n.kind==="repeat-region"?"repeat-region":n.kind==="conditional-region"?"conditional-region":n.kind==="opaque-region"?"opaque-region":"component-boundary",o=n.kind==="repeat-region"?"Node is inside a repeat region: operations affect the template, not individual instances":n.kind==="conditional-region"?"Node is inside a conditional region: visibility depends on runtime condition":`Node is inside a ${n.kind}`;for(let i of n.childKeys){let s=t.get(i);s&&s.constraints.push({kind:r,reason:o}),Jb(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function Jb(e,t,n,r,o){let i=o.elements.get(e);if(i)for(let s of i.childKeys){let a=r.get(s);a&&!a.constraints.some(l=>l.kind===t)&&(a.constraints.push({kind:t,reason:n}),Jb(s,t,n,r,o))}}function Xs(e){let t=[],n={...e.graph,composition:e.composition},r=_c(pl(n),n),o=[],i=new Map;for(let a of e.roots){let l=e.graph.elements.get(a.rootRef.key),c=e.graph.elements.get(a.ownerMemberKey),u=e.parsedModules.get(a.sourceFile),d=FO(a,e.graph),f=d?e.parsedModules.get(d):void 0;if(!l||!c||c.sourceFile!==d||!u||!Xb.safeParse(a.sourceFile).success||!d||!f||!Xb.safeParse(d).success){t.push(ep("root-source-unavailable",a.sourceFile));continue}if(i.has(a.rootKey)){t.push(ep("block-key-ambiguous",a.sourceFile));continue}let m=$e(u.source),g=TO.safeParse({blockKey:a.rootKey,rootRef:a.rootRef,definitionKey:a.rootRef.key,source:{file:a.sourceFile,structuralPath:a.structuralPath,contentHash:m},owner:a.ownerNode,siblingBlockKeys:a.siblingRootKeys,placementUnitKey:DO(a,e),capabilities:OO(l,r),...LO(l,r)});if(!g.success){t.push(ep("page-block-descriptor-invalid",a.sourceFile));continue}let p=g.data;o.push(p),i.set(a.rootKey,{blockKey:a.rootKey,composition:e.composition,documentVersion:e.documentVersion,descriptor:p,root:a,ownerFile:d,ownerSourceHash:$e(f.source),ownerSourceContent:f.source,sourceHash:m,sourceContent:u.source,ownerLocator:{kind:"jsx-element",file:c.sourceFile,sourceRange:c.sourceRange,structuralPath:c.identity.structuralPath,componentName:c.componentName},rootLocator:{kind:"jsx-element",file:l.sourceFile,sourceRange:l.sourceRange,structuralPath:l.identity.structuralPath,componentName:l.componentName}})}let s=wO.safeParse(o);return s.success?{composition:e.composition,documentVersion:e.documentVersion,descriptors:s.data,bindings:i,diagnostics:t}:{composition:e.composition,documentVersion:e.documentVersion,descriptors:[],bindings:new Map,diagnostics:[...t,{code:"page-block-directory-invalid",message:"The proven page block directory failed its strict contract."}]}}function OO(e,t){let n=t.get(e.identity.key),r=e.parentKey?t.get(e.parentKey):void 0;return{insert:r?r.canInsertChild:!0,replace:!!(n?.canRemove&&(!r||r.canInsertChild)),move:n?.canMove??!1,remove:n?.canRemove??!1,save:!0}}function LO(e,t){let n=t.get(e.identity.key),r={},o=n?.constraints[0]?.message??"The existing Engine capability check denied this operation.";return(!n||!n.canRemove)&&(r.replace={code:n?"CAPABILITY_DENIED":"CAPABILITY_UNAVAILABLE",reason:o},r.remove={code:n?"CAPABILITY_DENIED":"CAPABILITY_UNAVAILABLE",reason:o}),(!n||!n.canMove)&&(r.move={code:n?"CAPABILITY_DENIED":"CAPABILITY_UNAVAILABLE",reason:o}),Object.keys(r).length?{unavailableReasons:r}:{}}function FO(e,t){if(e.ownerNode.kind==="component-definition"){let n=e.ownerNode.key.lastIndexOf("#");return n>0?e.ownerNode.key.slice(0,n):null}return t.elements.get(e.ownerMemberKey)?.sourceFile??null}function DO(e,t){let n=e.callChain[0]?.callLocator.key??e.rootRef.key,r=t.graph.elements.get(n);if(r)return t.projection.placements.find(o=>o.members.some(i=>i.sourceRange!==null&&i.sourceRange.startLine===r.sourceRange.startLine&&i.sourceRange.startColumn===r.sourceRange.startColumn&&i.sourceRange.endLine===r.sourceRange.endLine&&i.sourceRange.endColumn===r.sourceRange.endColumn))?.placementUnitKey}function ep(e,t){return{code:e,message:"The page block source binding could not be proven.",file:t}}import tp from"@babel/traverse";import{BlockRenderRefSchema as MO,SiteEditPageBlockPositionSchema as BO,SiteEditPageBlockTargetSchema as jO}from"@vcp-dev/platform-shared/contracts";var $O=typeof tp=="function"?tp:tp.default;function Ri(e,t,n,r){if(!jO.safeParse(t).success)return xn("INVALID_PARAMS","Invalid page block target.");if(n!==e.documentVersion)return xn("VERSION_STALE","The page block index is stale.");if(t.composition.routeId!==e.composition.routeId||t.composition.templateId!==e.composition.effectiveTemplateId)return xn("INVALID_TARGET","The target belongs to another composition.");let o=e.bindings.get(t.blockKey);return o?r&&(!MO.safeParse(r).success||r.key!==o.descriptor.rootRef.key||r.instanceIndex!==o.descriptor.rootRef.instanceIndex||r.instanceCount!==o.descriptor.rootRef.instanceCount)?xn("INVALID_TARGET","The render occurrence does not match the target."):{ok:!0,binding:o}:xn("INVALID_TARGET","The page block target was not found.")}function ml(e,t){if(!BO.safeParse(t).success)return xn("INVALID_PARAMS","Invalid page block boundary.");if(t.documentVersion!==e.documentVersion)return xn("VERSION_STALE","The page block boundary is stale.");if(t.composition.routeId!==e.composition.routeId||t.composition.templateId!==e.composition.effectiveTemplateId)return xn("INVALID_TARGET","The boundary belongs to another composition.");let n=e.bindings.get(t.anchorBlockKey);if(!n)return xn("INVALID_TARGET","The boundary anchor was not found.");let r=[n,...n.descriptor.siblingBlockKeys.map(u=>e.bindings.get(u))];if(r.some(u=>!u))return xn("INVALID_TARGET","A verified sibling binding is unavailable.");let o=r.sort((u,d)=>u.root.siblingIndex-d.root.siblingIndex),i=zb(n);if(!i)return xn("INVALID_TARGET","The operation owner call site is unavailable.");let s=Wb(n,i);if(s===void 0)return xn("INVALID_TARGET","The boundary parent source range is ambiguous.");for(let u of o)if(u.ownerFile!==n.ownerFile||u.root.ownerNode.kind!==n.root.ownerNode.kind||u.root.ownerNode.key!==n.root.ownerNode.key||!UO(Wb(u,zb(u)),s))return xn("INVALID_TARGET","Siblings do not share one proven source boundary.");let a=o.findIndex(u=>u.blockKey===n.blockKey);if(a<0)return xn("INVALID_TARGET","Anchor order is ambiguous.");let l=t.placement==="before"?o[a-1]:n,c=t.placement==="before"?n:o[a+1];return{ok:!0,boundary:{ownerFile:n.ownerFile,parentLocator:s,anchorLocator:i,sourceHash:n.ownerSourceHash,placement:t.placement,beforeBlockKey:l?.blockKey??null,afterBlockKey:c?.blockKey??null}}}function zb(e){return e.ownerLocator.file===e.ownerFile?e.ownerLocator:null}function Wb(e,t){if(!t)return;let n=Oe(t.file,e.ownerSourceContent);if(!n.ok)return;let r=[];if($O(n.module.ast,{JSXElement(i){let s=np(i.node);s&&s.startLine===t.sourceRange.startLine&&s.startColumn===t.sourceRange.startColumn&&s.endLine===t.sourceRange.endLine&&s.endColumn===t.sourceRange.endColumn&&r.push(i)}}),r.length!==1)return;let o=r[0].parentPath;for(;o;){if(o.isJSXFragment()){let i=np(o.node);return i?{kind:"jsx-fragment",file:t.file,sourceRange:i}:void 0}if(o.isJSXElement()){let i=np(o.node),s=t.structuralPath?.lastIndexOf("/")??-1,a=s<0?void 0:t.structuralPath.slice(0,s);return i?{kind:"jsx-element",file:t.file,sourceRange:i,...a?{structuralPath:a}:{},...t.componentName?{componentName:t.componentName}:{}}:void 0}o=o.parentPath}return null}function UO(e,t){return e===void 0||t===void 0||e===null||t===null?e===t:e.file===t.file&&e.kind===t.kind&&e.sourceRange.startLine===t.sourceRange.startLine&&e.sourceRange.startColumn===t.sourceRange.startColumn&&e.sourceRange.endLine===t.sourceRange.endLine&&e.sourceRange.endColumn===t.sourceRange.endColumn}function np(e){let t=e.loc;return t?{startLine:t.start.line,startColumn:t.start.column,endLine:t.end.line,endColumn:t.end.column}:null}function xn(e,t){return{ok:!1,code:e,message:t}}import Yb from"node:path";import{SiteEditSourcePathSchema as qO}from"@vcp-dev/platform-shared/contracts";import gl from"node:path";import rp from"@babel/traverse";import*as so from"@babel/types";import{SiteEditSourcePathSchema as Hb,SiteEditPageBlockTargetSchema as VO}from"@vcp-dev/platform-shared/contracts";var KO=typeof rp=="function"?rp:rp.default;function Gb(e){if(!e.operationId)return wt("INVALID_PARAMS","An operationId is required.");if(!VO.safeParse(e.target).success)return wt("INVALID_PARAMS","Invalid page block target.");if(e.target.kind!=="page-block"||e.target.blockKey!==e.binding.blockKey||e.target.composition.routeId!==e.binding.composition.routeId||e.target.composition.templateId!==e.binding.composition.effectiveTemplateId)return wt("INVALID_TARGET","The request target does not match its resolved block binding.");if(e.documentVersion!==e.binding.documentVersion)return wt("VERSION_STALE","The resolved block belongs to a stale document version.");if(e.operation==="move-node"||e.operation==="remove-node")return wt("UNSUPPORTED_OPERATION","Move and remove are planned by the structural operation task.");if(!e.node)return wt("INVALID_PARAMS","An insert/replacement node is required.");let t=e.operation==="insert-child"?e.boundary?.ownerFile:e.binding.ownerFile;if(!t||!Hb.safeParse(t).success)return wt("INVALID_TARGET","The exact owner source file is unavailable.");let n=e.files.get(t);if(n===void 0)return wt("INVALID_TARGET","The exact owner source is absent from the fixed file map.");if($e(n)!==e.binding.ownerSourceHash)return wt("VERSION_STALE","The owner source hash changed after target resolution.");let r=e.files.get(e.binding.descriptor.source.file);if(r===void 0||$e(r)!==e.binding.descriptor.source.contentHash)return wt("VERSION_STALE","The block source hash changed after target resolution.");let o;if(e.operation==="insert-child"){if(o=e.boundary,!o||o.ownerFile!==e.binding.ownerFile||o.sourceHash!==e.binding.ownerSourceHash||o.anchorLocator.file!==t||o.parentLocator?.file!==t)return wt("INVALID_TARGET","The insertion boundary is not in the resolved source owner.");let c=o.placement==="before"?o.afterBlockKey:o.beforeBlockKey;if(c!==e.binding.blockKey&&!e.binding.descriptor.siblingBlockKeys.includes(c??""))return wt("INVALID_TARGET","The boundary anchor is not a verified same-owner sibling.");if(!o.parentLocator)return wt("UNSUPPORTED_OPERATION","A root without a source parent has no safe sibling insertion boundary.")}let i=XO(e.node,t,n,e.files);if(!i.ok)return i;let s=e.operation==="replace-node"?di({source:n,locator:JO(e.binding),node:{jsx:i.value.jsx}}):Vn({source:n,locator:op(o.parentLocator),anchorLocator:op(o.anchorLocator),placement:o.placement,node:{jsx:i.value.jsx}});if(!s.ok)return wt("UNSUPPORTED_OPERATION",s.diagnostic.message);let a=s.source;if(i.value.import){let c=Kn({source:a,moduleSpecifier:i.value.import.moduleSpecifier,imports:i.value.import.specifiers});if(!c.ok)return wt("UNSUPPORTED_OPERATION",c.diagnostic.message);a=c.source}return{ok:!0,plan:{operationId:e.operationId,kind:"source-edit",target:e.target,documentVersion:e.documentVersion,conflictPolicy:"compare-and-swap",edits:[{operation:"upsert",file:t,content:a,baseContentHash:e.binding.ownerSourceHash}]}}}function JO(e){return op(e.ownerLocator)}function op(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e.sourceRange,...e.structuralPath&&e.componentName?{expectedIdentity:{file:e.file,component:e.componentName,structuralPath:e.structuralPath}}:{}}}function XO(e,t,n,r){if(e.kind==="native-tag")return/^[A-Za-z][A-Za-z0-9:_-]*$/.test(e.tag)?{ok:!0,value:{jsx:e.text===void 0?`<${e.tag} />`:`<${e.tag}>{${JSON.stringify(e.text)}}</${e.tag}>`}}:wt("INVALID_PARAMS","The native JSX tag is invalid.");if(!e.component)return wt("UNSUPPORTED_OPERATION","A materialized component entry is resolved by the materialization task.");let o=zO(t,e.component.source,r);if(!o)return wt("INVALID_TARGET","The component source is not in the safe fixed file map.");let i=Oe(t,n);if(!i.ok)return wt("UNSUPPORTED_OPERATION",i.diagnostic.message);let s=WO(i.module.ast.program.body,e.component.source,e.component.exportName),a=s??GO(YO(e.component.exportName,o),HO(i.module.ast)),l=ZO(e.props??{});if(!l.ok)return l;let c=`<${a}${l.value?` ${l.value}`:""} />`;if(s)return{ok:!0,value:{jsx:c}};let u=e.component.exportName==="default"?{kind:"default",local:a}:{kind:"named",imported:e.component.exportName,...a!==e.component.exportName?{local:a}:{}};return{ok:!0,value:{jsx:c,import:{moduleSpecifier:e.component.source,specifiers:[u]}}}}function zO(e,t,n){let r=t.startsWith("@/")?t.slice(2):t.startsWith("./")||t.startsWith("../")?gl.posix.normalize(gl.posix.join(gl.posix.dirname(e),t)):null;return r?(/\.(?:tsx?|jsx?)$/i.test(r)?[r]:[".tsx",".ts",".jsx",".js"].map(i=>`${r}${i}`).concat([".tsx",".ts",".jsx",".js"].map(i=>`${r}/index${i}`))).find(i=>Hb.safeParse(i).success&&n.has(i))??null:null}function WO(e,t,n){for(let r of e)if(!(!so.isImportDeclaration(r)||r.source.value!==t)){for(let o of r.specifiers)if(n==="default"&&so.isImportDefaultSpecifier(o)||n!=="default"&&so.isImportSpecifier(o)&&(so.isIdentifier(o.imported)?o.imported.name:o.imported.value)===n)return o.local.name}return null}function HO(e){let t=new Set;return KO(e,{Program(n){n.scope.crawl(),t=new Set(Object.keys(n.scope.bindings)),n.stop()}}),t}function GO(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function YO(e,t){let r=(e==="default"?gl.posix.basename(t).replace(/\.(?:tsx?|jsx?)$/i,""):e).replace(/[^A-Za-z0-9_$]/g,""),o=r?r[0].toUpperCase()+r.slice(1):"Component";return/^[A-Za-z_$][\w$]*$/.test(o)?o:"Component"}function ZO(e){let t=[];for(let[n,r]of Object.entries(e)){if(!/^[A-Za-z_][A-Za-z0-9_:.-]*$/.test(n))return wt("INVALID_PARAMS","A component prop name is invalid.");let o;try{o=JSON.stringify(r)}catch{return wt("INVALID_PARAMS","Component props must be JSON serializable.")}if(o===void 0)return wt("INVALID_PARAMS","Component props must be JSON serializable.");t.push(`${n}={${o}}`)}return{ok:!0,value:t.join(" ")}}function wt(e,t){return{ok:!1,code:e,message:t}}function Zb(e){if(e.materialization.kind!=="static-prefab-materialization"||!e.materialization.files.some(i=>i.path===e.materialization.entry.path))return hl("MATERIALIZATION_ENTRY_INVALID","The materialization entry must identify one controlled create-only file.");if(!e.materialization.files.every(i=>i.kind==="create-only"&&qO.safeParse(i.path).success))return hl("MATERIALIZATION_PATH_INVALID","Every materialized output must remain a safe create-only Snapshot source.");if(e.materialization.files.some(i=>e.files.has(i.path)))return hl("MATERIALIZATION_INSTANCE_CONFLICT","A generated materialization path already exists in the fixed Snapshot source map.");let t=e.operation==="insert-child"?e.boundary?.ownerFile:e.binding.ownerFile;if(!t||!e.files.has(t))return hl("INVALID_TARGET","The exact page-block owner source is missing from the fixed file map.");let n=eL(t,e.materialization.entry.path),r=Gb({operationId:e.operationId,documentVersion:e.documentVersion,target:e.target,binding:e.binding,...e.boundary?{boundary:e.boundary}:{},operation:e.operation,node:{kind:"component-call",component:{source:n,exportName:e.materialization.entry.export.kind==="default"?"default":e.materialization.entry.export.name},props:{}},files:QO(e.files,e.materialization)});if(!r.ok)return r;let o=e.materialization.files.map(i=>({operation:"create-only",file:i.path,content:i.content}));return{ok:!0,plan:{...r.plan,target:e.target,edits:[...o,...r.plan.edits]}}}function QO(e,t){let n=new Map(e);for(let r of t.files)n.set(r.path,r.content);return n}function eL(e,t){let n=Yb.posix.relative(Yb.posix.dirname(e),t);return n.startsWith(".")?n:`./${n}`}function hl(e,t){return{ok:!1,code:e,message:t}}import{PageTemplateIdSchema as dL}from"@vcp-dev/platform-shared/contracts";import CW from"node:fs";import PW from"node:path";var tL=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function zs(e){let t=e.map(r=>uL(r.path)),n=nL(t);return n?t.filter(r=>oL(n,r)).map(r=>({routeId:iL(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function ip(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=lL(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function nL(e){return e.some(r=>r.startsWith("app/")&&!rL(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function rL(e){return/^(?:src\/)?app\/(?:_vcp|\.vcp)/.test(e)}function oL(e,t){if(!t.startsWith(`${e}/`))return!1;let n=t.slice(t.lastIndexOf("/")+1);return tL.test(n)?t.slice(e.length+1,-n.length-1).split("/").filter(Boolean).every(r=>!r.startsWith("_")&&!r.startsWith(".")):!1}function iL(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(aL).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function sL(e){return e.startsWith("(")&&e.endsWith(")")}function aL(e){return!e||e.startsWith("@")||e.startsWith("_")||sL(e)?null:cL(e)}function cL(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function lL(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function uL(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var Ws=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function bn(e,t={}){throw new Ws("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Invalid page-template source (${e}): ${t.path??t.routeId??t.templateId??""}`,{reason:e,...t})}function sp(e){return dL.safeParse(e).success||bn("invalid-template-id",{templateId:e}),Buffer.from(e,"utf8").toString("base64url")}function qb(e){/^[A-Za-z0-9_-]{1,255}$/.test(e)||bn("invalid-template-key",{path:e});let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.from(e,"base64url"))}catch{return bn("invalid-template-key",{path:e})}return sp(t)!==e&&bn("noncanonical-template-key",{path:e}),t}function fL(e){let t=ip(e),n=t.slice(1).split("/");return(!e.startsWith("/")||/[?#\\%\u0000-\u001f]/.test(e)||t.startsWith("/.vcp")||t!=="/"&&n.some(r=>!r||r==="."||r===".."||r.startsWith("@")||r.startsWith("_")||r.startsWith("(")||pL(r)&&!Qb(r)))&&bn("invalid-public-route",{routeId:e}),t}function pL(e){return e.includes("[")||e.includes("]")}function Qb(e){return/^\[\[\.\.\.[^\[\]]+\]\]$|^\[[^\[\]]+\]$/.test(e)}function eS(e){return e.some(Qb)}function tS(e,t,n="app"){n!=="app"&&n!=="src/app"&&bn("invalid-app-root");let r=fL(e),o=sp(t),i=eS(r.slice(1).split("/")),s=i?`${n}/.vcp/page-templates/${o}${r}`:`${n}/.vcp/page-templates${r==="/"?"":r}`,a=i?`${s}/page.tsx`:`${s}/${o}/page.tsx`;return(Buffer.byteLength(a,"utf8")>4095||a.split("/").some(l=>Buffer.byteLength(l,"utf8")>255))&&bn("path-too-long",{path:a}),{appRoot:n,routeRoot:s,templateKey:o,templateEntryFile:a}}function nS(e){return/^(?:src\/)?app\/\.vcp\/page-templates\//.test(e)}function rS(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===".")&&bn("invalid-file-path",{path:i}),n.has(i)&&bn("duplicate-file-path",{path:i}),n.set(i,o)}return n}function xl(e){let t=rS(e.files),n=zs([...t.keys()].map(i=>({path:i}))),r=new Map;for(let i of n){if(r.has(i.routeId))throw new Ws("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(!nS(i))continue;let s=/^(app|src\/app)\/\.vcp\/page-templates\/(.+)\/page\.tsx$/.exec(i);s||bn("candidate-must-be-single-page",{path:i});let a=s[1],l=s[2].split("/"),c=eS(l),u=c?l[0]:l.pop(),d=c?l.slice(1):l,f=qb(u),m=d.length?`/${d.join("/")}`:"/";tS(m,f,a).templateEntryFile!==i&&bn("candidate-path-mismatch",{path:i,routeId:m});let p=r.get(m);(!p||!p.startsWith(`${a}/`))&&bn("canonical-entry-missing",{path:i,routeId:m}),o.push({routeId:m,templateId:f,entryFile:i,canonicalEntryFile:p,appRoot:a})}return o.sort((i,s)=>yl(i.routeId,s.routeId)||yl(i.templateId,s.templateId))}function bl(e){let t=rS(e.files),n=xl({files:t}),r=zs([...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)=>yl(o.context.routeId,i.context.routeId)||(o.context.effectiveTemplateId===void 0?-1:i.context.effectiveTemplateId===void 0?1:yl(o.context.effectiveTemplateId,i.context.effectiveTemplateId)))}function mL(e){let t=ip(e.selector.routeId),n=bl({files:e.files}),r=n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===void 0);(!r||r.entryFile!==e.canonicalEntryFile)&&bn("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||bn("template-selection-not-found",{routeId:t,templateId:e.selector.templateId}),{...o,mode:e.selector.templateId===void 0?"direct":"candidate",effectiveEntryFile:o.entryFile}}function yl(e,t){return e<t?-1:e>t?1:0}import{HOME_PAGE_URL_PATH as DL}from"@vcp-dev/platform-shared/contracts";import{parse as AL}from"@babel/parser";import gL from"@babel/traverse";var ap=gL,hL=typeof ap=="function"?ap:ap.default;function cp(e,t){let n=e.referencePaths.filter(r=>!r.findParent(o=>o.isJSXClosingElement()));return n.length===1&&n[0]?.node===t}function oS(e){let t=new Map,n=new Set,r=new Set,o=new Map,i=new Set;return hL(e,{Program(s){for(let a of Object.values(s.scope.bindings))a.constant&&(a.kind==="const"||a.kind==="hoisted")&&i.add(a.path.node)},ReferencedIdentifier(s){let a=s.scope.getBinding(s.node.name);if(!a?.constant||a.kind!=="const"||!a.path.isVariableDeclarator()||!cp(a,s.node))return;let l=a.path.node.init;l&&t.set(s.node,l)},JSXOpeningElement(s){let a=s.get("name");for(;a.isJSXMemberExpression();)a=a.get("object");if(!a.isJSXIdentifier())return;let l=a.scope.getBinding(a.node.name);if(!l?.constant)return;let c=l.path.parentPath;if((l.path.isImportSpecifier()||l.path.isImportDefaultSpecifier()||l.path.isImportNamespaceSpecifier())&&c?.isImportDeclaration()&&c.node.importKind!=="type"&&(!l.path.isImportSpecifier()||l.path.node.importKind!=="type")){n.add(s.node),cp(l,a.node)&&r.add(s.node);return}if(!(!s.get("name").isJSXIdentifier()||!cp(l,a.node))){if(l.path.isFunctionDeclaration())o.set(s.node,l.path.node);else if(l.kind==="const"&&l.path.isVariableDeclarator()){let u=l.path.get("init");(u.isArrowFunctionExpression()||u.isFunctionExpression())&&o.set(s.node,u.node)}}}}),{valueAliases:t,importedOpenings:n,uniqueImportedOpenings:r,localComponentOpenings:o,stableDeclarations:i}}import{parse as qW}from"@babel/parser";import{FormBlockIdSchema as eH,FormSpecV1Schema as tH}from"@vcp-dev/platform-shared/contracts";import{posix as jW}from"node:path";import yL from"@babel/traverse";var lp=yL,UW=typeof lp=="function"?lp:lp.default,VW=Symbol("unknown-member");import{parse as XW}from"@babel/parser";import{FormBlockIdSchema as WW}from"@vcp-dev/platform-shared/contracts";var Hs="components/site/generated/forms",oH=`${Hs}/vcp-form-runtime.tsx`,Sl="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",iH=new RegExp(`^${Hs}/form-(${Sl})\\.spec\\.ts$`),sH=new RegExp(`^${Hs}/form-(${Sl})\\.tsx$`),aH=new RegExp(`^@/${Hs}/form-(${Sl})$`),cH=new RegExp(`(?:^|/)${Hs}/form-(${Sl})(?:\\.tsx?)?$`);var lH=Symbol("invalid-literal");import{createHash as fH}from"node:crypto";import{posix as mH}from"node:path";import{parse as hH}from"@babel/parser";import{FormSpecV1Schema as xH}from"@vcp-dev/platform-shared/contracts";var bH=Symbol("dynamic");import{parse as xL}from"@babel/parser";function El(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.type=="string"):[]}var bL=/^(?:src\/)?app\/(.*)page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function iS(e){let t=bL.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 SL(e){let t=e;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function sS(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function EL(e){let t=e;for(;t&&(t.type==="TSAsExpression"||t.type==="TSSatisfiesExpression"||t.type==="ParenthesizedExpression");)t=t.expression??null;return t}function up(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(up);if(t?.type==="ObjectExpression"){let n={};for(let r of El(t.properties)){if(r.type!=="ObjectProperty"||r.computed)throw new Error("dynamic object property");let o=sS(r.key);if(!o)throw new Error("unsupported object key");n[o]=up(r.value)}return n}throw new Error(`unsupported static value: ${t?.type??"unknown"}`)}function dp(e,t){let n=[],r=iS(t);if(r===null)return{found:!1,seo:null,diagnostics:n};let o;try{o=xL(e,{sourceType:"module",plugins:["typescript","jsx"]})}catch(c){return n.push({code:"page-seo.parse-failed",message:c instanceof Error?c.message:String(c)}),{found:!1,seo:null,diagnostics:n}}let i;for(let c of El(o.program.body)){let u=c.type==="ExportNamedDeclaration"?c.declaration:c;if(u?.type==="VariableDeclaration")for(let d of El(u.declarations)){let f=d.id;f?.type==="Identifier"&&f.name==="PAGE_SEO"&&(i=d.init)}}if(i==null)return{found:!1,seo:null,diagnostics:n};let s=EL(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 c of El(s.properties)){if(c.type!=="ObjectProperty"||c.computed)continue;let u=sS(c.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=SL(c.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=up(c.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 l=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`}),l=a.path),{found:!0,seo:{path:l,...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 IL}from"@babel/parser";var aS=["page","anchor","external","email","phone","group","file"],vL=["link","cta"],lS=["description","badge","iconKey"],fp=["label","targetType","href","role","openInNewTab","nofollow","children",...lS],kL=new Set(fp);function Ys(e){return Array.isArray(e)?e:[]}function Gs(e){let t=e;return t?.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function _L(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function cS(e){let t=e;return t?.type==="BooleanLiteral"&&typeof t.value=="boolean"?t.value:void 0}function pp(e){let t=[],n;try{n=IL(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 Ys(n.program.body)){let s=i.type==="ExportNamedDeclaration"?i.declaration:i;if(s?.type==="VariableDeclaration")for(let a of Ys(s.declarations)){let l=a.id;l?.type==="Identifier"&&l.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 Ys(r.elements).forEach((i,s)=>{let a=uS(i,`NAV_ITEMS[${s}]`,t);a&&o.push(a)}),{items:o,diagnostics:t}}function uS(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 c of Ys(e.properties)){if(c.type!=="ObjectProperty"||c.computed)continue;let u=_L(c.key);u&&(r[u]=c.value)}let o=Gs(r.label),i=Gs(r.targetType);if(!o)return n.push({severity:"fatal",path:`${t}.label`,message:"label must be a static string"}),null;if(!i||!aS.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${aS.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 c of lS){if(r[c]===void 0)continue;let u=Gs(r[c]);u!==void 0?s[c]=u:n.push({severity:"warning",path:`${t}.${c}`,message:`${c} 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 c of Object.keys(r))kL.has(c)||c==="group"||c==="icon"||n.push({severity:"warning",code:"unknown-field",path:`${t}.${c}`,message:`unsupported field \`${c}\` ignored; NAV_ITEMS only carries ${fp.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 c=[];Ys(r.children.elements).forEach((u,d)=>{let f=uS(u,`${t}.children[${d}]`,n);f&&c.push(f)}),s.children=c}if(i==="group")return s.children?s:(n.push({severity:"fatal",path:`${t}.children`,message:"group item requires children"}),null);let a=Gs(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 l=Gs(r.role);if(l!==void 0&&(vL.includes(l)?s.role=l:n.push({severity:"warning",path:`${t}.role`,message:"role ignored: not link/cta"})),r.openInNewTab!==void 0){let c=cS(r.openInNewTab);c!==void 0?s.openInNewTab=c:n.push({severity:"warning",path:`${t}.openInNewTab`,message:"openInNewTab ignored: not a static boolean"})}if(r.nofollow!==void 0){let c=cS(r.nofollow);c!==void 0?s.nofollow=c:n.push({severity:"warning",path:`${t}.nofollow`,message:"nofollow ignored: not a static boolean"})}return s}import{parse as CL}from"@babel/parser";function Zs(e){return Array.isArray(e)?e:[]}function dS(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function RL(e){let t;try{t=CL(e,{sourceType:"module",plugins:["typescript","jsx"],tokens:!0})}catch{return{status:"unsupported"}}let n=[];for(let o of Zs(t.program.body)){let i=o.type==="ExportNamedDeclaration"?o.declaration:o;if(i?.type==="VariableDeclaration")for(let s of Zs(i.declarations)){let a=s.id;a?.type==="Identifier"&&a.name==="NAV_ITEMS"&&n.push(s)}}if(n.length===0)return{status:"navigation_not_found"};if(n.length!==1)return{status:"unsupported"};let r=dS(n[0]?.init);return!r||typeof r.start!="number"||typeof r.end!="number"?{status:"unsupported"}:{status:"ok",array:r,start:r.start,end:r.end}}function mp(e,t){let n=fS(t);if(!n)return{status:"unsupported",source:e};let r=RL(e);if(r.status!=="ok")return{status:r.status,source:e};let o=r.array;if(pp(e).diagnostics.some(({severity:c})=>c==="fatal"))return{status:"unsupported",source:e};let s=[],a=c=>{let u=Zs(c.elements);for(let[d,f]of u.entries()){if(NL(f,n)){let g=u[d+1],p=u[d-1],h=f.start,x=f.end;if(typeof h!="number"||typeof x!="number")continue;if(g&&typeof g.start=="number")s.push({start:h,end:g.start});else if(p&&typeof p.end=="number")s.push({start:p.end,end:x});else{let b=/^\s*,/.exec(e.slice(x));s.push({start:h,end:b?x+b[0].length:x})}continue}let m=PL(f);m&&a(m)}};if(a(o),s.length===0)return{status:"not_found",source:e};let l=e;for(let c of s.sort((u,d)=>d.start-u.start))l=l.slice(0,c.start)+l.slice(c.end);return{status:"removed",source:l,removedCount:s.length}}function PL(e){if(e.type==="ObjectExpression")for(let t of Zs(e.properties)){if(t.type!=="ObjectProperty")continue;let n=t.key;if((n?.name??n?.value)==="children")return dS(t.value)}}function fS(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function NL(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of Zs(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"&&fS(n??"")===t}import{estimateNavLabelWidth as NH}from"@vcp-dev/platform-shared/contracts";import{parse as TH}from"@babel/parser";function gr(e,t){let n,r;try{n=AL(e,{sourceType:"module",sourceFilename:t.filePath,plugins:["jsx","typescript"]}),t.requireStaticMount&&(r=oS(n))}catch(j){let J=j.loc;return{form_codes:[],components:[],uncertain_components:[],rendered_component_openings:[],renders_native_form:!1,diagnostics:[{code:"rendered-module.parse-failed",message:j instanceof Error?j.message:"Rendered module failed Babel parsing.",file_path:t.filePath??"",line:J?.line??1}]}}let o=n.program,i=cn(o?.body),s=new Map,a=new Map,l=new Map,c=new Map,u=j=>{if(j?.type==="FunctionDeclaration"){let J=j.id;J?.type==="Identifier"&&typeof J.name=="string"&&(!r||r.stableDeclarations.has(j))&&a.set(J.name,j);return}if(j?.type==="VariableDeclaration")for(let J of cn(j.declarations)){if(r&&!r.stableDeclarations.has(J))continue;let Y=J.id,$=J.init;Y?.type==="Identifier"&&typeof Y.name=="string"&&$&&(ao($)?a.set(Y.name,$):$.type==="Identifier"&&typeof $.name=="string"&&l.set(Y.name,$.name))}};for(let j of i){if(j.type==="ImportDeclaration"){let J=j.source?.value;if(typeof J!="string")continue;for(let Y of cn(j.specifiers)){let $=Y.local;if(!($?.type!=="Identifier"||typeof $.name!="string")){if(Y.type==="ImportDefaultSpecifier")s.set($.name,{source:J,exportName:"default"});else if(Y.type==="ImportNamespaceSpecifier")s.set($.name,{source:J,exportName:"*"});else if(Y.type==="ImportSpecifier"){let ce=Y.imported,ue=ce?.type==="Identifier"&&typeof ce.name=="string"?ce.name:ce?.type==="StringLiteral"&&typeof ce.value=="string"?ce.value:"";ue&&s.set($.name,{source:J,exportName:ue})}}}continue}j.type==="ExportNamedDeclaration"?u(j.declaration):u(j)}for(let j of i){if(j.type==="ExportDefaultDeclaration"){let $=j.declaration;$&&ao($)?c.set("default",$):$?.type==="Identifier"&&typeof $.name=="string"&&c.set("default",$.name);continue}if(j.type!=="ExportNamedDeclaration")continue;let J=j.declaration;if(J?.type==="FunctionDeclaration"){let $=J.id;$?.type==="Identifier"&&typeof $.name=="string"&&c.set($.name,$.name)}else if(J?.type==="VariableDeclaration")for(let $ of cn(J.declarations)){let ce=$.id;ce?.type==="Identifier"&&typeof ce.name=="string"&&c.set(ce.name,ce.name)}let Y=j.source?.value;for(let $ of cn(j.specifiers)){let ce=hS($.local),ue=hS($.exported);if(!(!ce||!ue))if(typeof Y=="string"){let Ee=`#re-export:${ue}`;s.set(Ee,{source:Y,exportName:ce}),c.set(ue,Ee)}else c.set(ue,ce)}}let d=new Set,f=[],m=new Set,g=[],p=new Set,h=[],x=new Map,b=!1,S=new Set,E=new Map,v=new Map,N=!1,I=[],A=new Map,C=new Map,O=(j,J="rendered")=>{let Y=mS(j,s);if(!Y)return!1;let $=`${Y.source}\0${Y.exportName}`;if(J==="uncertain")return!m.has($)&&!p.has($)&&(p.add($),g.push({source:Y.source,export_name:Y.exportName})),!0;if(!m.has($)&&(m.add($),f.push({source:Y.source,export_name:Y.exportName}),p.delete($))){let ce=g.findIndex(ue=>ue.source===Y.source&&ue.export_name===Y.exportName);ce>=0&&g.splice(ce,1)}return!0},L=(j,J="rendered",Y=[])=>{let $=`${J}\0${hp(Y)}`,ce=A.get(j)??new Set,ue=C.get(j)??new Set;if(ce.has($)||ue.has(J))return;ce.add($),A.set(j,ce),ue.add(J),C.set(j,ue);let Ee=new Map(a),We=new Map,pt=[],fn=(U,Ce=!1)=>{if(qs(U)){if(!Ce&&ao(U)){if(U.type==="FunctionDeclaration"){let De=U.id;De?.type==="Identifier"&&typeof De.name=="string"&&Ee.set(De.name,U)}return}if(U.type==="VariableDeclarator"){let De=U.id,ie=U.init;De?.type==="Identifier"&&typeof De.name=="string"&&ie&&(ao(ie)?Ee.set(De.name,ie):We.set(De.name,ie))}else if(U.type==="ReturnStatement"){let De=U.argument;De&&pt.push(De)}if(U.type==="CallExpression"){let De=U.callee;if(De?.type==="Import"&&I.push({code:"rendered-module.dynamic-import",message:"Rendered component graph must use static imports.",file_path:t.filePath??"",line:U.loc?.start.line??1}),Qs(De)==="cms.forms.getConfig"){let ie=cn(U.arguments)[0];ie?.type==="StringLiteral"&&typeof ie.value=="string"&&ie.value.trim()?J==="rendered"?d.add(ie.value.trim()):I.push({code:"rendered-module.unresolved-export",message:"Unable to prove whether a CMS form inside a JSX prop is rendered.",file_path:t.filePath??"",line:U.loc?.start.line??1}):I.push({code:"rendered-module.dynamic-form-code",message:"Rendered cms.forms.getConfig() requires a non-empty string literal.",file_path:t.filePath??"",line:U.loc?.start.line??1})}}for(let[De,ie]of Object.entries(U))if(De!=="loc")if(Array.isArray(ie))for(let Xe of ie)fn(Xe);else fn(ie)}};fn(j,!0),t.requireStaticMount&&j.body?.type==="BlockStatement"&&pt.length>0&&(cn(j.body?.body).filter(Ce=>Ce.type==="ReturnStatement").length!==1||pt.length!==1)&&(N=!0,pt.length=0);let on=new Set,sn=new Set,W=(U,Ce=J,De=Y)=>{if(!(!qs(U)||ao(U))){if(t.requireStaticMount){if(De.length>0)return;if(U.type==="JSXText"&&Ce==="rendered"&&typeof U.start=="number"&&typeof U.end=="number"&&E.set(U.start,U.end),U.type==="LogicalExpression"||U.type==="ConditionalExpression"){let ie=U.type==="ConditionalExpression"?U.test:U.left;if(ie?.type==="BooleanLiteral"){let Xe=U.type==="ConditionalExpression"?ie.value?U.consequent:U.alternate:U.operator==="&&"?ie.value?U.right:null:U.operator==="||"?ie.value?null:U.right:null;W(Xe,Ce,De)}else Il(U)&&(N=!0);return}if(U.type==="CallExpression"){Il(U)&&(N=!0);return}}if(U.type==="Identifier"&&typeof U.name=="string"){let ie=r?r.valueAliases.get(U):We.get(U.name),Xe=`${Ce}\0${U.name}\0${hp(De)}`;ie&&!on.has(Xe)&&!sn.has(U.name)?(on.add(Xe),sn.add(U.name),W(ie,Ce,De),sn.delete(U.name)):r?N=!0:O(U.name,Ce);return}if(U.type==="CallExpression"){let ie=U.callee,Xe=cn(U.arguments),yt=Qs(ie),Nt=ie?.type==="Identifier"&&typeof ie.name=="string"?s.get(ie.name):void 0;if(Ce==="rendered"&&(yt==="createElement"||yt.endsWith(".createElement")||Nt?.source==="react"&&Nt.exportName==="createElement")&&Xe[0]?.type==="StringLiteral"&&Xe[0].value==="form"&&(b=!0),ie?.type==="Identifier"&&typeof ie.name=="string"){let Et=Ee.get(ie.name);if(Et){L(Et,Ce,De);return}}if(ie&&ao(ie)){L(ie,Ce,De);return}if(OL(ie)){for(let Et of Xe)if(ao(Et))L(Et,Ce,De);else if(Et.type==="Identifier"&&typeof Et.name=="string"){let pn=Ee.get(Et.name);pn&&L(pn,Ce,De)}return}for(let Et of Xe)Il(Et)&&I.push({code:"rendered-module.unresolved-export",message:"Unable to prove whether a JSX-producing call argument is rendered.",file_path:t.filePath??"",line:Et.loc?.start.line??1});return}if(U.type==="JSXElement"){let ie=U.openingElement,Xe=ie?pS(De,TL(ie)):De;if(t.requireStaticMount&&ie){if(Xe.length>0)return;if(wL(ie)){N=!0;return}let Et=gp(ie);Ce==="rendered"&&Et.has("data-site-block-id")&&typeof ie.end=="number"&&S.add(ie.end)}W(ie,Ce,Xe);let yt=ie?ea(ie.name):void 0,Nt=cn(U.children);if(t.requireStaticMount&&yt==="a")return;if(t.requireStaticMount&&yt&&!/^[a-z]/.test(yt)){Nt.some(Il)&&(N=!0);return}for(let Et of Nt)W(Et,Ce,Xe);return}if(U.type==="JSXOpeningElement"){let ie=ea(U.name);Ce==="rendered"&&ie==="form"&&(b=!0);let Xe=ie&&(!r||r.importedOpenings.has(U))?mS(ie,s):void 0;if(r&&Ce==="rendered"&&ie&&typeof U.start=="number"){let yt=gp(U).get("href");v.set(U.start,{start:U.start,name:ie,...typeof yt=="string"?{href:yt}:{},...Xe?{imported:Xe}:{}})}if(Ce==="rendered"&&Xe&&(!r||r.uniqueImportedOpenings.has(U))&&typeof U.start=="number"){let yt=`${Xe.source}\0${Xe.exportName}\0${U.start}`,Nt=x.get(yt);if(!Nt){let Et=gp(U).get("formBlockId");Nt={source:Xe.source,export_name:Xe.exportName,start_offset:U.start,...typeof Et=="string"?{static_form_block_id:Et}:{}},x.set(yt,Nt),h.push(Nt)}De.length>0&&(Nt.static_render_blockers=pS(Nt.static_render_blockers??[],De))}if(r)if(Xe)O(ie,Ce);else{let yt=r.localComponentOpenings.get(U);qs(yt)?L(yt,Ce,De):/^[A-Z]/.test(ie)&&!gS(ie)&&(N=!0)}else if(ie&&!O(ie,Ce)){let yt=Ee.get(ie);yt?L(yt,Ce,De):We.has(ie)?W(We.get(ie),Ce,De):gS(ie)||/^[A-Z]/.test(ie)&&I.push({code:"rendered-module.dynamic-import",message:`Unable to resolve rendered component ${ie} from a static import.`,file_path:t.filePath??"",line:U.loc?.start.line??1})}for(let yt of cn(U.attributes))W(yt,"uncertain",De);return}if(U.type==="JSXAttribute"){let ie=U.value,Xe=ie?.type==="JSXExpressionContainer"?ie.expression:ie;Xe&&ao(Xe)?L(Xe,"uncertain",De):W(Xe,"uncertain",De);return}for(let[ie,Xe]of Object.entries(U))if(!(ie==="loc"||ie==="closingElement"))if(Array.isArray(Xe))for(let yt of Xe)W(yt,Ce,De);else W(Xe,Ce,De)}},pe=j.body;pe&&pe.type!=="BlockStatement"&&pt.push(pe);for(let U of pt)W(U);ue.delete(J)},X=c.get(t.exportName);if(typeof X=="string"){let j=X,J=new Set;for(;l.has(j)&&!J.has(j);)J.add(j),j=l.get(j);if(!O(j)){let Y=a.get(j);Y?L(Y):I.push(yS(t))}}else X?L(X):I.push(yS(t));return{form_codes:[...d],components:f,uncertain_components:g,rendered_component_openings:h,renders_native_form:b,...t.requireStaticMount?{static_block_content_starts:[...S],static_jsx_openings:[...v.values()],static_jsx_text_spans:[...E].map(([j,J])=>({start:j,end:J})),has_uncertain_mounts:N||g.length>0}:{},diagnostics:I}}function wL(e){return cn(e.attributes).some(t=>{if(t.type==="JSXSpreadAttribute")return!0;let n=xp(t.name);if(!n||!["hidden","inert","aria-hidden","className","style"].includes(n))return!1;let r=t.value;if(r?.type!=="JSXExpressionContainer")return!1;let o=r.expression;return o?.type!=="ObjectExpression"&&vl(o)===void 0})}function hp(e){return e.map(t=>`${t.start_offset}:${t.reason}`).join("|")}function pS(e,t){return[...new Map([...e,...t].map(r=>[hp([r]),r])).values()]}function TL(e){let t=new Map;for(let a of cn(e.attributes)){if(a.type==="JSXSpreadAttribute"){t.clear();continue}let l=xp(a.name);if(!l)continue;let c=a.value;t.set(l,c?.type==="JSXExpressionContainer"?c.expression:c)}let n=ea(e.name)??"unknown",r=[],o=a=>{r.push({element_name:n,line:e.loc?.start.line??1,start_offset:FL(e.start),reason:a})};for(let a of["hidden","inert","aria-hidden","disabled"]){if(!t.has(a)||a==="disabled"&&n!=="fieldset")continue;let l=vl(t.get(a));(l===!0||(a==="aria-hidden"?l==="true":typeof l=="string"))&&o(a)}let i=t.get("style");if(i?.type==="ObjectExpression"){let a=new Map;for(let c of cn(i.properties)){let u=c.key,d=!c.computed&&u?.type==="Identifier"?u.name:u?.type==="StringLiteral"?u.value:void 0;c.type!=="ObjectProperty"||typeof d!="string"?a.clear():a.set(d,vl(c.value))}a.get("display")==="none"&&o("style.display=none"),a.get("visibility")==="hidden"&&o("style.visibility=hidden");let l=a.get("opacity");(l===0||typeof l=="string"&&l.trim()==="0")&&o("style.opacity=0")}let s=vl(t.get("className"));if(typeof s=="string"){let a=s.split(/\s+/).filter(Boolean),c={hidden:new Set(["block","inline","inline-block","flex","inline-flex","grid","inline-grid","table","inline-table","table-row","table-cell","flow-root","contents","list-item"]),invisible:new Set(["visible"]),"sr-only":new Set(["not-sr-only"])};for(let[u,d]of Object.entries(c))a.includes(u)&&!a.some(f=>d.has(f.split(":").at(-1)))&&o(`className=${u}`)}return r}function vl(e){if(e===null)return!0;if(e){if(e.type==="StringLiteral"||e.type==="BooleanLiteral"||e.type==="NumericLiteral")return e.value;if(e.type==="TemplateLiteral"&&cn(e.expressions).length===0)return cn(e.quasis)[0]?.value?.cooked}}function mS(e,t){let n=t.get(e);if(n)return n;let[r,...o]=e.split(".");if(!r||o.length===0)return;let i=t.get(r);if(i?.exportName==="*")return{source:i.source,exportName:o.join(".")}}function gS(e){return e.endsWith(".Provider")||e.endsWith(".Consumer")}function ao(e){return e?.type==="FunctionDeclaration"||e?.type==="FunctionExpression"||e?.type==="ArrowFunctionExpression"}function OL(e){let t=Qs(e),n=e?.type==="MemberExpression"&&e.computed!==!0?e.property:void 0;return t==="Array.from"||t==="React.Children.map"||n?.type==="Identifier"&&(n.name==="map"||n.name==="flatMap")}function Il(e){let t=!1;return yp(e,n=>{if(!t){if(n.type==="JSXOpeningElement"){t=!0;return}n.type==="CallExpression"&&Qs(n.callee)==="cms.forms.getConfig"&&(t=!0)}}),t}function hS(e){return e?.type==="Identifier"&&typeof e.name=="string"?e.name:e?.type==="StringLiteral"&&typeof e.value=="string"?e.value:""}function yS(e){return{code:"rendered-module.unresolved-export",message:`Unable to resolve rendered export ${e.exportName}.`,file_path:e.filePath??"",line:1}}function Qs(e){if(!e)return"";if(e.type==="Identifier"&&typeof e.name=="string")return e.name;if(e.type!=="MemberExpression"||e.computed===!0)return"";let t=Qs(e.object),n=e.property;return!t||n?.type!=="Identifier"||typeof n.name!="string"?"":`${t}.${n.name}`}function gp(e){let t=new Map,n=Array.isArray(e.attributes)?e.attributes:[];for(let r of n){let o=r;if(o.type!=="JSXAttribute")continue;let i=xp(o.name);i&&t.set(i,LL(o.value))}return t}function LL(e){if(e==null)return!0;let t=e;if(t.type==="StringLiteral")return t.value;if(t.type!=="JSXExpressionContainer")return;let n=t.expression;if(n&&(n.type==="StringLiteral"||n.type==="NumericLiteral"))return n.value}function xp(e){let t=e;if(t?.type==="JSXIdentifier")return typeof t.name=="string"?t.name:void 0}function FL(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function yp(e,t){if(qs(e)){t(e);for(let[n,r]of Object.entries(e))if(n!=="loc"){if(Array.isArray(r)){for(let o of r)yp(o,t);continue}yp(r,t)}}}function qs(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function ea(e){let t=e;if(!t)return"";if(t.type==="JSXIdentifier")return typeof t.name=="string"?t.name:"";if(t.type==="JSXMemberExpression"){let n=ea(t.object),r=ea(t.property);return n&&r?`${n}.${r}`:r||n}return""}function cn(e){return Array.isArray(e)?e.filter(t=>qs(t)):[]}var ML="components/site/generated/",ta=[".tsx",".ts",".jsx",".js"];function xS(e){if(e.expectedUrlPath===DL)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set(zs(Object.keys(e.files).map(p=>({path:p}))).map(p=>p.entryFile)),n=Object.entries(e.files).filter(([p,h])=>{let x=p.replace(/\\/g,"/");if(!t.has(x))return!1;let b=dp(h,x);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=new Set([r]);try{let p=xl({files:new Map(Object.entries(e.files))});for(let h of p)h.canonicalEntryFile===r&&o.add(h.entryFile)}catch(p){return{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:p instanceof Error?p.message:"Invalid page template source."}}let i=BL(e.files);if(!i.ok)return i.error;let s=i.graph,a=VL(o,s),l=KL(o,a,s),c=[...a].filter(p=>!l.has(p)).sort((p,h)=>p.localeCompare(h)),u=[...o,...[...l].sort((p,h)=>p.localeCompare(h))],d=new Set(u),f=u.map(p=>({operation:"delete",file:p})),m=[],g=[];for(let[p,h]of Object.entries(e.files))if(!d.has(p)){if(h.includes("NAV_ITEMS")){let x=mp(h,e.expectedUrlPath);x.status==="removed"?(f.push({operation:"upsert",file:p,content:x.source}),m.push(p)):x.status==="unsupported"&&g.push(`unsupported_navigation:${p}`)}h.includes(e.expectedUrlPath)&&!h.includes("NAV_ITEMS")&&g.push(`preserved_link:${p}`)}return{ok:!0,edits:f,deletedFiles:u,updatedFiles:m,preservedSharedFiles:c,warnings:g}}function BL(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")||!jL(r))continue;let s=Oe(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:l}of s.module.imports){if($L(l))continue;let c=ar(r,l),u=UL(c,t);if(!u)return{ok:!1,error:{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:`Page source dependencies could not be proven safe: ${r} -> ${l} (import-not-found).`}};a.add(u)}n.set(r,a)}return{ok:!0,graph:n}}function jL(e){let t=e.toLowerCase();return ta.some(n=>t.endsWith(n))}function $L(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!ta.some(n=>e.endsWith(n)))}function UL(e,t){let n=e.replace(/\\/g,"/");return(ta.some(o=>n.endsWith(o))?[n]:[...ta.map(o=>`${n}${o}`),...ta.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function VL(e,t){let n=new Set,r=[...e].flatMap(o=>[...t.get(o)??[]]);for(;r.length>0;){let o=r.pop();!o.startsWith(ML)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function KL(e,t,n){let r=new Set(t),o=!0;for(;o;){o=!1;for(let i of[...r])[...n].some(([a,l])=>!e.has(a)&&!r.has(a)&&l.has(i))&&(r.delete(i),o=!0)}return r}import*as xE from"@babel/parser";import*as Ye from"@babel/types";import*as Ul from"node:path";import*as nt from"@babel/types";var JL=new Set(["copyWithin","fill","pop","push","reverse","shift","sort","splice","unshift"]);function co(e,t){let n=[e],r=new Set;for(;n.length>0;){let o=n.pop();if(r.has(o))continue;r.add(o);let i=Sp(o)?.expressionPath;if(i?.isIdentifier()){let s=i.scope.getBinding(i.node.name);s&&n.push(s)}for(let s of o.referencePaths){if(s.node===t)continue;let a=s.parentPath;if(a?.isVariableDeclarator()&&s.key==="init"&&nt.isIdentifier(a.node.id)){let f=a.scope.getBinding(a.node.id.name);f&&n.push(f);continue}if(!a?.isMemberExpression()&&!a?.isOptionalMemberExpression()||s.key!=="object")continue;let l=a.parentPath;if(l?.isAssignmentExpression()&&a.key==="left")return!0;if(!l?.isCallExpression()&&!l?.isOptionalCallExpression()||a.key!=="callee")continue;let{property:c,computed:u}=a.node,d=u&&nt.isStringLiteral(c)?c.value:!u&&nt.isIdentifier(c)?c.name:null;if(d&&JL.has(d))return!0}}return!1}function Sp(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 hr(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return Jo(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(nt.isObjectPattern(n)||nt.isArrayPattern(n))return Jo(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(zL(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function Jo(e,t,n=!1){return nt.isIdentifier(e)?e.name===t&&n:nt.isObjectPattern(e)?e.properties.some(r=>nt.isObjectProperty(r)?Jo(r.value,t,n):Jo(r.argument,t,n)):nt.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=nt.isRestElement(r)?r.argument:r;return Jo(o,t,n)}):nt.isAssignmentPattern(e)?Jo(e.left,t,!0):nt.isRestElement(e)?Jo(e.argument,t,n):!1}function Pi(e,t){if(e.path.isObjectPattern()){if(t){let r=nr(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:hr(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:hr(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=bS(r),i=!1,s=o?o.initBinding&&bp(o.initBinding)?(i=hr(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let l=Pi(o.initBinding,{kind:"identifier",expression:o.initBinding.identifier.name,base:o.initBinding.identifier.name,path:[]});return i=l?.hasDefault??!1,l?[{kind:"property",name:l.propName},...l.remainingPath,...o.initPathPrefix]:null})():null:null,a=nr(e.path.node.id,e.identifier.name);if(s&&a){let l=[...s,...a],[c,...u]=l;return!c||c.kind!=="property"?null:{propName:c.name,remainingPath:[...u,...t?.path??[]],hasDefault:i||hr(e)}}}}let n=GL(e);if(n){let r=XL(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||hr(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=WL(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:hr(e)}}let i=na(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:hr(e)}:null}if(bp(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:hr(e)}}return null}function XL(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=bS(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,l=bp(i)?(a=hr(i),[...s]):(()=>{let u=Pi(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(!l)return null;let c=nr(n.node.id,t.identifier.name);return c?{path:[...l,...c],hasDefault:a||hr(t)}:null}function bS(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=YL(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function bp(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function zL(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function WL(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=nr(i.node,t);if(a)return a}return null}function SS(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let l=kl(a,e.identifier.name);if(l&&(!n||l.propName===n))return{propName:l.propName,componentName:t,expressionPath:l.expressionPath,displayPath:`${t}.${l.propName}.default`}}}if(e.path.isObjectPattern())for(let a of e.path.get("properties")){if(!a.isObjectProperty())continue;let l=na(a.node);if(!l||n&&l!==n)continue;let c=a.get("value");if(!c.isAssignmentPattern())continue;let u=c.get("right");if(u.isExpression())return{propName:l,componentName:t,expressionPath:u,displayPath:`${t}.${l}.default`}}let r=HL(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=na(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 kl(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=na(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&nr(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=kl(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=kl(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=kl(r,t);if(o)return o}}return null}function nr(e,t,n=[]){if(nt.isIdentifier(e))return e.name===t?n:null;if(nt.isObjectPattern(e)){for(let r of e.properties)if(nt.isObjectProperty(r)){let o=na(r);if(!o)continue;let i=nr(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(nt.isRestElement(r)){let o=nr(r.argument,t,n);if(o)return o}}if(nt.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=nt.isRestElement(o)?o.argument:o,s=nr(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return nt.isAssignmentPattern(e)?nr(e.left,t,n):null}function HL(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function GL(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 na(e){return e.computed?null:nt.isIdentifier(e.key)?e.key.name:nt.isStringLiteral(e.key)?e.key.value:null}function YL(e){let t=[],n=e;for(;nt.isMemberExpression(n);){if(n.computed)if(nt.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(nt.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(nt.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return nt.isIdentifier(n)?{base:n.name,path:t}:null}import*as CS from"@babel/parser";import vp from"@babel/traverse";import*as Ni from"@babel/types";import*as Ve from"@babel/types";var ES=new WeakMap;function Rl(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?_l(n,t):null}if(e.isMemberExpression()){let n=nF(e.node),r=ZL(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?_l(o,[...r,...t]):null}return e.isAwaitExpression()||Ip(e.node)?lo(oF(e.node),t,"awaited or fetched expression"):null}function ZL(e){let t=[],n=e;for(;Ve.isMemberExpression(n);){if(n.computed)if(Ve.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(Ve.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(Ve.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return Ve.isIdentifier(n)?t:null}function _l(e,t=[],n){let r=qL(e,t);if(r)return r;let o=QL(e,t,n);if(o)return o;let i=eF(e,t,n);return i||null}function oa(e){return e?.kind==="api-source"}function qL(e,t){if(e.path.isVariableDeclarator()&&Ve.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&Ep(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return lo(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&Ve.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(l=>Ve.isObjectProperty(l)&&kS(l)==="data"&&ra(l.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&Ep(a.node))return lo(e.identifier.name,t,"query hook data binding")}let n=tF(e);if(!n||kS(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()||!Ep(i.node)?null:lo(e.identifier.name,t,"query hook data binding")}function QL(e,t,n){if(e.path.isVariableDeclarator()&&Ve.isArrayPattern(e.path.node.id)){let l=e.path.get("init");if(!l?.isCallExpression()||!vS(l.node))return null;let[c,u]=e.path.node.id.elements;return!Ve.isIdentifier(c)||c.name!==e.identifier.name||!Ve.isIdentifier(u)?null:IS(e,u.name,n)?lo(e.identifier.name,t,"state setter is updated by API data"):null}if(!e.path.isIdentifier())return null;let r=e.path.parentPath;if(!r?.isArrayPattern())return null;let o=r.parentPath;if(!o?.isVariableDeclarator())return null;let i=o.get("init");if(!i?.isCallExpression()||!vS(i.node)||r.node.elements.findIndex(l=>l===e.path.node)!==0)return null;let a=r.node.elements[1];return Ve.isIdentifier(a)&&IS(e,a.name,n)?lo(e.identifier.name,t,"state setter is updated by API data"):null}function eF(e,t,n){let r=e.path.isVariableDeclarator()?e.path:e.path.findParent(i=>i.isVariableDeclarator());if(!r?.isVariableDeclarator())return null;let o=r.get("init");return o?.isExpression()?o.isAwaitExpression()?lo(e.identifier.name,t,"awaited binding result"):Ip(o.node,n)?lo(e.identifier.name,t,"fetch-backed binding result"):null:null}function tF(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 ra(e,t){return Ve.isIdentifier(e)?e.name===t:Ve.isAssignmentPattern(e)?ra(e.left,t):Ve.isObjectPattern(e)?e.properties.some(n=>Ve.isObjectProperty(n)?ra(n.value,t):ra(n.argument,t)):Ve.isArrayPattern(e)?e.elements.some(n=>!!n&&ra(Ve.isRestElement(n)?n.argument:n,t)):!1}function IS(e,t,n){let r=!1,o=!1,i=e.scope.path,s;if(n){let l=ES.get(n);l||(l=new WeakMap,ES.set(n,l)),s=l.get(i.node),s||(s=new Map,l.set(i.node,s));let c=s.get(t);if(c!==void 0)return c}i.traverse({CallExpression(l){Ip(l.node)&&(r=!0),(rF(l.node.callee,t)||l.node.arguments.some(c=>Ve.isIdentifier(c)&&c.name===t))&&(o=!0)}});let a=r&&o;return s?.set(t,a),a}function Ep(e){let t=Pl(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function vS(e){return Pl(e.callee)==="useState"}function Ip(e,t){let n=t?.get(e);if(n!==void 0)return n;let r=Cl(e,o=>Ve.isCallExpression(o)&&Pl(o.callee)==="fetch");return t?.set(e,r),r}function nF(e){let t=e;for(;Ve.isMemberExpression(t);)t=t.object;return Ve.isIdentifier(t)?t.name:null}function kS(e){return e.computed?null:Ve.isIdentifier(e.key)?e.key.name:Ve.isStringLiteral(e.key)?e.key.value:null}function Pl(e){return Ve.isIdentifier(e)?e.name:Ve.isMemberExpression(e)&&Ve.isIdentifier(e.property)?e.property.name:null}function rF(e,t){return Cl(e,n=>Ve.isIdentifier(n)&&n.name===t)}function Cl(e,t){if(t(e))return!0;let n=Ve.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(Ve.isNode(i)&&Cl(i,t))return!0;continue}if(Ve.isNode(o)&&Cl(o,t))return!0}return!1}function oF(e){return Ve.isIdentifier(e)?e.name:Ve.isCallExpression(e)?Pl(e.callee)??"api":Ve.isAwaitExpression(e)?"awaited-api":"api"}function lo(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:iF(e,t),reason:n}}function iF(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var RS=typeof vp=="function"?vp:vp.default;function PS(e,t){let n=AS(e);if(!n)return{allowed:!0};let r=!1;return RS(n,{CallExpression(o){if(!wS(o.node,t.sourceRange)||!sF(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||oa(Rl(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function NS(e,t){let n=AS(e);if(!n)return{allowed:!0};let r=!1;return RS(n,{JSXExpressionContainer(o){wS(o.node,t.sourceRange)&&(Ni.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 AS(e){try{return CS.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function sF(e){let t=e.callee;return Ni.isMemberExpression(t)&&Ni.isIdentifier(t.property)&&t.property.name==="map"}function wS(e,t){let n=e.loc;return n?_S({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&_S({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function _S(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 ge from"@babel/types";import*as TS from"@babel/parser";import kp from"@babel/traverse";import*as St from"@babel/types";import*as Ai from"node:path";var rr=typeof kp=="function"?kp:kp.default;function zt(e){try{return TS.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function _p(e){return e.computed?St.isStringLiteral(e.key)||St.isNumericLiteral(e.key)?String(e.key.value):null:aF(e.key)}function aF(e){return St.isIdentifier(e)?e.name:St.isStringLiteral(e)||St.isNumericLiteral(e)?String(e.value):null}function Xo(e){return St.isParenthesizedExpression(e)||St.isTSAsExpression(e)||St.isTSSatisfiesExpression(e)||St.isTSNonNullExpression(e)||St.isTSTypeAssertion(e)?Xo(e.expression):St.isExpression(e)?e:null}function Cp(e){if(St.isIdentifier(e))return[e.name];if((St.isMemberExpression(e)||St.isOptionalMemberExpression(e))&&!e.computed&&St.isIdentifier(e.property)){let t=Xo(e.object),n=t?Cp(t):null;return n?[...n,e.property.name]:null}return null}function zo(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?Ai.normalize(Ai.join(Ai.dirname(e),t)).replace(/\\/g,"/"):t}function wn(e,t){return Nl(e)===Nl(t)}function Nl(e){let t=wi(e);return t.endsWith("/index")?t.slice(0,-6):t}function wi(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function FS(e,t,n){let r=jS(e,t);if($S(e,r),US(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 rr(e,{JSXElement(s){XS(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:Al(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 DS(e,t){let n=new Map,r=i=>{let s=Ti(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 cF(i,n))o=r(s)||o}return[...n.values()]}function cF(e,t){let n=[],r=lF(e,t);for(let o of e.ast.program.body){if(ge.isExportDefaultDeclaration(o)&&ge.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=ia(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(ge.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=zo(e.file,o.source.value);for(let s of o.specifiers){if(ge.isExportNamespaceSpecifier(s)){let c=uo(s.exported);for(let u of t.values())wn(u.file,i)&&n.push({file:e.file,namespace:Rp(c,u.namespace),exportName:u.exportName});continue}if(!ge.isExportSpecifier(s))continue;let a=uo(s.local),l=[...t.values()].filter(c=>wn(c.file,i)&&Wo(c.namespace,a));if(l.length>0){let c=uo(s.exported);for(let u of l){let d=ia(u.namespace,a,c);d&&n.push({file:e.file,namespace:d,exportName:u.exportName})}continue}t.has(Ti({file:i,exportName:a}))&&n.push({file:e.file,exportName:uo(s.exported)})}continue}if(ge.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!ge.isExportSpecifier(i))continue;let s=uo(i.local),a=r.get(s)??[];if(a.length>0){let l=uo(i.exported);n.push({file:e.file,exportName:l});for(let c of a){let u=ia(c.namespace,s,l);u&&n.push({file:e.file,namespace:u,exportName:c.exportName})}}}continue}if(ge.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=zo(e.file,o.source.value),s=o.exported;if(s){let a=uo(s);for(let l of t.values())wn(l.file,i)&&n.push({file:e.file,namespace:Rp(a,l.namespace),exportName:l.exportName});continue}for(let a of t.values())wn(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function Rp(e,t){return t?`${e}.${t}`:e}function Wo(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function ia(e,t,n){return!Wo(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function lF(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(!ge.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=zo(e.file,i.source.value);for(let a of i.specifiers){if(ge.isImportDefaultSpecifier(a)){let l=t.get(Ti({file:s,exportName:"default"}));l&&r(a.local.name,l);let c=[...t.values()].filter(u=>wn(u.file,s)&&Wo(u.namespace,"default"));for(let u of c){let d=ia(u.namespace,"default",a.local.name);d&&r(a.local.name,{...u,namespace:d})}continue}if(ge.isImportSpecifier(a)){let l=uo(a.imported),c=[...t.values()].filter(d=>wn(d.file,s)&&Wo(d.namespace,l));for(let d of c)r(a.local.name,d);let u=t.get(Ti({file:s,exportName:l}));u&&r(a.local.name,u);continue}if(ge.isImportNamespaceSpecifier(a))for(let l of t.values())wn(l.file,s)&&r(a.local.name,{...l,namespace:Rp(a.local.name,l.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(ge.isVariableDeclaration(i))for(let s of i.declarations){if(!ge.isIdentifier(s.id)||!s.init)continue;let a=Xo(s.init);if(!a||!ge.isIdentifier(a))continue;let l=n.get(a.name)??[];if(l.length===0)continue;let c=n.get(s.id.name)??[],u=new Set(c.map(Ti));for(let d of l){let f=ia(d.namespace,a.name,s.id.name),m=f?{...d,namespace:f}:d,g=Ti(m);u.has(g)||(r(s.id.name,m),u.add(g),o=!0)}}}return n}function Ti(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${Nl(e.file)}#${t}`}function uo(e){return ge.isIdentifier(e)?e.name:e.value}function MS(e,t){for(let n of e.program.body){if(ge.isExportDefaultDeclaration(n)){let o=n.declaration;if((ge.isFunctionDeclaration(o)||ge.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(ge.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!ge.isExportNamedDeclaration(n))continue;let r=n.declaration;if((ge.isFunctionDeclaration(r)||ge.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(ge.isVariableDeclaration(r)){for(let o of r.declarations)if(ge.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!ge.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:ge.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function Np(e){let t=uF(e),n=[],r=US(e.ast,t);return rr(e.ast,{JSXElement(o){wn(e.file,e.sourceFile)&&Al(o)===e.sourceComponent||XS(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function BS(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function jS(e,t){let n=BS();return rr(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function uF(e){let t=BS();return wn(e.file,e.sourceFile)&&dF(t,jS(e.ast,e.sourceComponent)),rr(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=zo(e.file,o),s=e.componentIdentities.filter(a=>wn(a.file,i));if(s.length!==0)for(let a of r.specifiers){let l=n.scope.getBinding(a.local.name);if(l){if(ge.isImportDefaultSpecifier(a)&&s.some(c=>c.exportName==="default")&&t.localBindings.add(l),ge.isImportDefaultSpecifier(a)){let c=s.filter(u=>Wo(u.namespace,"default"));if(c.length>0){let u=t.namespaceMembers.get(l)??new Set;for(let d of c){let f=LS(d,"default");f&&u.add(f)}t.namespaceMembers.set(l,u)}continue}if(ge.isImportSpecifier(a)){let c=ge.isIdentifier(a.imported)?a.imported.name:a.imported.value,u=s.filter(d=>Wo(d.namespace,c));if(u.length>0){let d=t.namespaceMembers.get(l)??new Set;for(let f of u){let m=LS(f,c);m&&d.add(m)}t.namespaceMembers.set(l,d);continue}s.some(d=>!d.namespace&&d.exportName===c)&&t.localBindings.add(l);continue}if(ge.isImportNamespaceSpecifier(a))for(let c of s){let u=c.namespace?`${c.namespace}.${c.exportName}`:c.exportName,d=t.namespaceMembers.get(l)??new Set;d.add(u),t.namespaceMembers.set(l,d)}}}}}),$S(e.ast,t),t}function dF(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 $S(e,t){rr(e,{VariableDeclarator(n){if(!n.node.init)return;let r=Xo(n.node.init);if(r){if(ge.isIdentifier(n.node.id)){let o=Ho(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&Pp(t,i,o);return}if(ge.isObjectPattern(n.node.id)){let o=Ho(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&JS(n.node.id,o.namespaceMembers,t,n)}}}})}function US(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return rr(e,{ReferencedIdentifier(r){if(n){r.stop();return}fF(r)||!r.isIdentifier()||!VS(r,t)||pF(r,t)||mF(r)||(n=!0,r.stop())}}),n}function fF(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 VS(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)&&Ho(r.node,t,r)?r:null}function pF(e,t){let n=e.findParent(l=>l.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!OS(e,r))return!1;let o=VS(e,t);if(!o)return!1;if(Xo(r.node)===o.node)return!!Ho(r.node,t,r);let s=e.findParent(l=>l.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&OS(e,a)&&!!Ho(a.node,t,a)}function mF(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function OS(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Ho(e,t,n){let r=Xo(e);if(!r)return null;if(ge.isIdentifier(r)){let a=n.scope.getBinding(r.name);if(!a)return null;let l=t.namespaceMembers.get(a);return t.localBindings.has(a)?{local:!0,namespaceMembers:new Set,unsupported:!1}:l?{local:!1,namespaceMembers:new Set(l),unsupported:!1}:null}if(ge.isObjectExpression(r))return gF(r,t,n);let o=Cp(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?KS(s,o.slice(1).join(".")):null}function gF(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!ge.isObjectProperty(i))continue;let s=_p(i);if(!s||!ge.isExpression(i.value)){ge.isExpression(i.value)&&(o||=Ho(i.value,t,n)!==null);continue}let a=Ho(i.value,t,n);if(a){o||=a.unsupported,a.local&&r.add(s);for(let l of a.namespaceMembers)r.add(`${s}.${l}`)}}return r.size>0||o?{local:!1,namespaceMembers:r,unsupported:o}:null}function KS(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 Pp(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 JS(e,t,n,r){for(let o of e.properties){if(ge.isRestElement(o)){if(ge.isIdentifier(o.argument)){let l=r.scope.getBinding(o.argument.name);l&&Pp(n,l,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!ge.isObjectProperty(o))continue;let i=_p(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=KS(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=ge.isAssignmentPattern(o.value)?o.value.left:o.value;if(ge.isIdentifier(a)){let l=r.scope.getBinding(a.name);l&&Pp(n,l,s);continue}if(ge.isObjectPattern(a)&&s.namespaceMembers.size>0){JS(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function LS(e,t){if(!Wo(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 XS(e,t){let n=e.node.openingElement.name;if(ge.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=zS(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 zS(e){if(ge.isJSXIdentifier(e))return[e.name];if(ge.isJSXMemberExpression(e)){let t=zS(e.object);return t?[...t,e.property.name]:null}return null}function Al(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()&&ge.isIdentifier(n.node.id))return n.node.id.name}return null}function WS(e,t){let n=zt(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=Np({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 it(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 tt(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function yr(e,t){let n=tt(e);return!!(n&&Tn(t,n))}function Tn(e,t){return t.start>=e.start&&t.end<=e.end}function Hn(e,t){let n=Be(e,it(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:wl(e,t)}function Oi(e,t){let n=tt(t);return n?e.slice(n.start,n.end):""}function HS(e,t){return e.start===t.start&&e.end===t.end}function wl(e,t){let n=null;return rr(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 Tl(e,t){return Ap(e,t).length>0}function Ol(e,t){let n=tt(e.node),r=tt(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()&&!hF(o,n,r)))return!0;o=o.parentPath}return!1}function hF(e,t,n){let r=tt(e.node.consequent);if(r&&Tn(r,t)&&!Tn(r,n))return!1;let o=e.node.alternate?tt(e.node.alternate):null;return!(o&&Tn(o,t)&&!Tn(o,n))}function Ap(e,t){let n=tt(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=tt(o.node.consequent),a=tt(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()&&wp(o.node.operator)){let s=tt(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 wp(e){return e==="&&"||e==="||"||e==="??"}function GS(e,t){let n=tt(e.consequent);if(n&&Tn(n,t))return n;let r=tt(e.alternate);return r&&Tn(r,t)?r:null}function YS(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=>wi(a.file)));if(!t.has(wi(e.sourceFile))||!t.has(wi(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(wi(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=MS(e.sourceAst,e.sourceComponent);if(!n)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without an exported source component identity"};let r=[];for(let a of e.knownSourceFiles){let l=zt(a.content);if(!l)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component because a loaded source file cannot be parsed"};r.push({file:a.file,ast:l})}let o=DS(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let l=Np({ast:a.ast,file:a.file,sourceFile:e.sourceFile,sourceComponent:e.sourceComponent,componentIdentities:o});if(l.hasUnsafeReference)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component because the component has unsupported value usages"};i.push(...l.callSites)}if(i.length!==1)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without a single project-wide component call site"};let[s]=i;return!wn(s.file,e.targetFile)||Al(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}}import{SiteEditSetPropsParamsSchema as IF}from"@vcp-dev/platform-shared/contracts";function Ll(e){let{state:t,scope:n,operation:r,selectionRef:o,repeatTarget:i}=e;if(!t||t.status==="blocked")return{ok:!1,code:"readonly-property",reason:t?.diagnostic?.message??"No safe property write target is available"};if(t.status==="binding"){let s=t.target;if(s?.kind!=="value-binding"||!s.target.locator||n!=="selection"||r!=="set")return sa();let a=s.target,l=a.locator;if(a.sourceKind==="repeat-template"){let c=o?.instanceIndex;if(c===void 0)return sa();let u=yF(a,c,o?.instanceCount);if(!u)return sa();l=u}return{ok:!0,target:{kind:"value-binding",file:a.file,locator:l}}}return o?.instanceIndex!==void 0?n!=="selection"||!i?.ok?{ok:!1,code:"repeat-target-failed",reason:i&&!i.ok?i.reason:"No safe selected repeat property target is available"}:{ok:!0,target:{kind:"repeat-property",target:i}}:e.isRepeat&&n!=="template"||t.status==="direct"&&t.target?.kind!=="jsx-attribute"?sa():{ok:!0,target:{kind:"jsx-attribute"}}}function sa(){return{ok:!1,code:"unsupported-binding",reason:"Property does not have a safe typed binding write target for this scope and operation"}}function yF(e,t,n){if(!e.locator||!Number.isInteger(t)||t<0)return null;let r=e.collectionPathMap?.length??e.collectionIndexMap?.length;if(r!==void 0&&(t>=r||n!==void 0&&n!==r))return null;let o=e.collectionPathMap?.[t];if(o)return{...e.locator,path:o};let i=e.locator.path??[],s=i.findLastIndex(l=>l.kind==="index");if(s<0)return null;let a=i.map((l,c)=>c===s&&l.kind==="index"?{kind:"index",index:e.collectionIndexMap?.[t]??t}:l);return{...e.locator,path:a}}import*as xr from"@babel/types";import{SiteEditSetPropsParamsSchema as xF}from"@vcp-dev/platform-shared/contracts";function ZS(e){let t=e.changes??(e.change?[e.change]:[]);if(!xF.safeParse({kind:"set-props",scope:"selection",changes:t}).success)return aa("invalid-change","Repeat property changes are invalid");if(t.length!==1||t[0].name!==e.target.propertyName)return aa("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=ft(e.source,"value");if(!o.ok)return aa("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 l=Be(o.ast,a);if(!l.ok||!l.match.path.isObjectExpression())return aa("unsupported-object",`Repeat item ${s} is not a writable object expression`);let c=s===e.target.sourceItemIndex?bF(r):SF(l.match.path.node,r.name);if(!c)return aa("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:c})}return{ok:!0,steps:i}}function bF(e){return e.operation==="set"?{kind:"value",value:e.value}:{kind:"undefined"}}function SF(e,t){let n=e.properties.filter(i=>xr.isObjectProperty(i)&&EF(i.key)===t);if(n.length>1)return null;let r=n[0];if(!r)return{kind:"undefined"};if(!xr.isExpression(r.value))return null;let o=fr(r.value);return o.status==="undefined"?{kind:"undefined"}:o.status!=="resolved"?null:{kind:"value",value:o.value}}function EF(e){return xr.isIdentifier(e)?e.name:xr.isStringLiteral(e)?e.value:xr.isNumericLiteral(e)?String(e.value):null}function aa(e,t){return{ok:!1,errorCode:e,reason:t}}function qS(e){if(e.change.name!=="className"&&e.change.name!=="class")return ca("unsupported-owner",`No specialized property owner is available for '${e.change.name}'`);let t=e.classNameSource;if(!t||t.filePath!==e.node.file)return ca("owner-source-unavailable","className source details are unavailable for the selected node");if(e.change.name==="class"&&t.sourceKind==="missing")return ca("owner-source-unavailable","The class alias requires an existing className source");if(t.sourceKind==="expression")return ca("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 ca("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 ca(e,t){return{ok:!1,errorCode:e,reason:t}}async function eE(e){let t=IF.safeParse({kind:"set-props",scope:e.scope,changes:e.changes});if(!t.success)return fo("invalid-change","Typed property changes are invalid");if(e.node.importedFrom==="next/link"&&e.node.exportName==="default"){let r=t.data.changes.find(o=>o.name==="href");if(r&&(r.operation==="remove"||typeof r.value!="string"||r.value.trim().length===0))return fo("invalid-change","next/link requires a non-empty href; use the dedicated link-target operation to remove the link")}let n=[];for(let r of t.data.changes){let o=await vF(e,r);if(o){if(!o.ok)return fo("owner-plan-failed",o.reason);QS(n,o.steps);continue}let i=await e.getPropertyState(e.node.key,r.name,e.selectionRef);if(!i)return fo("missing-property-state",`No authoritative property state is available for '${r.name}'`);if(i.status==="blocked")return fo("readonly-property",i.diagnostic?.message??`Property '${r.name}' is not writable`);if(CF(i,r)||r.operation==="remove"&&i.status==="missing")continue;let s=e.selectionRef?.instanceIndex!==void 0&&i.status!=="binding"?await e.getRepeatPropertyTarget?.(e.node.key,r.name,e.selectionRef):void 0,a=Ll({state:i,scope:e.scope,operation:r.operation,selectionRef:e.selectionRef,repeatTarget:s});if(!a.ok)return fo(a.code,a.reason);let l=a.target;if(l.kind==="value-binding"&&r.operation==="set"){Tp(n,{type:"update-value",order:n.length,file:l.file,locator:l.locator,value:r.value});continue}if(l.kind==="repeat-property"){let c=ZS({source:e.getFileContent(l.target.sourceFile),target:l.target,changes:[r]});if(!c.ok)return fo("repeat-target-failed",c.reason);QS(n,c.steps);continue}Tp(n,{type:"set-property-changes",order:n.length,file:e.node.file,locator:kF(e.node),scope:e.scope,changes:[r]})}return n.forEach((r,o)=>{r.order=o}),_F(n)?fo("step-conflict","Property changes resolve to conflicting write steps"):{ok:!0,steps:n}}async function vF(e,t){return t.name!=="className"&&t.name!=="class"?null:qS({node:e.node,change:t,classNameSource:e.classNameSource})}function kF(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 _F(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 QS(e,t){for(let n of t)Tp(e,{...n,order:e.length})}function Tp(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 CF(e,t){if(t.operation!=="set"||e.status!=="direct")return!1;let n=e.attribute?.resolution;return n?.status==="resolved"?Op(n.value,t.value):e.attribute?.source===null&&e.attribute.value===t.value}function Op(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)=>Op(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=>Op(n[i],r[i]))}return!1}function fo(e,t){return{ok:!1,errorCode:e,reason:t}}import*as Fi from"@babel/types";import*as be from"@babel/types";function Lp(e,t,n){let r=Hn(t,n);return r?br(e,r):null}function br(e,t){let n=t.findParent(p=>p.isArrowFunctionExpression()||p.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(p=>p===r.node)!==0)return null;let a=i.get("callee");if(!a.isMemberExpression()&&!a.isOptionalMemberExpression())return null;let l=a.node,c=l.property;if(!be.isIdentifier(c)||c.name!=="map"||l.computed)return null;let u=a.get("object"),d=Oi(e,u.node),f=r.node.params.map(p=>Oi(e,p)),m=tt(i.node),g=tt(r.node);return!d||f.some(p=>p.length===0)||!m||!g?null:{callStart:m.start,callEnd:m.end,callbackStart:g.start,callbackEnd:g.end,collectionExpression:d,callbackParams:f,mapOperator:be.isOptionalMemberExpression(l)&&l.optional?"?.map":".map",collectionNeedsParens:Fl(u.node),callbackPath:r,collectionPath:u}}function la(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function RF(e,t){let n=tt(e.node);return n?PF(t).some(r=>{let o=tt(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function PF(e){let t=e.callbackPath.node.body;return be.isBlockStatement(t)?po(t.body):mo(t)}function po(e){let t=[];for(let n of e){if(be.isReturnStatement(n)){n.argument&&t.push(...mo(n.argument));continue}if(be.isBlockStatement(n)){t.push(...po(n.body));continue}if(be.isIfStatement(n)){let r=be.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...po(r)),n.alternate){let o=be.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...po(o))}continue}if(be.isSwitchStatement(n)){for(let r of n.cases)t.push(...po(r.consequent));continue}be.isTryStatement(n)&&(t.push(...po(n.block.body)),n.handler&&t.push(...po(n.handler.body.body)),n.finalizer&&t.push(...po(n.finalizer.body)))}return t}function mo(e){return be.isJSXElement(e)?NF(e)?tE(e.children):[e]:be.isJSXFragment(e)?tE(e.children):be.isParenthesizedExpression(e)||be.isTSAsExpression(e)||be.isTSSatisfiesExpression(e)||be.isTSNonNullExpression(e)||be.isTSTypeAssertion(e)?mo(e.expression):be.isConditionalExpression(e)?[...mo(e.consequent),...mo(e.alternate)]:be.isLogicalExpression(e)&&wp(e.operator)?mo(e.right):[]}function tE(e){return e.flatMap(t=>be.isJSXElement(t)||be.isJSXFragment(t)?mo(t):be.isJSXExpressionContainer(t)&&(be.isJSXElement(t.expression)||be.isJSXFragment(t.expression)||be.isConditionalExpression(t.expression)||be.isLogicalExpression(t.expression))?mo(t.expression):[])}function NF(e){let t=e.openingElement.name;return be.isJSXIdentifier(t)?t.name==="Fragment":be.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function nE(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function Fl(e){return!(be.isIdentifier(e)||be.isThisExpression(e)||be.isMemberExpression(e)||be.isOptionalMemberExpression(e)||be.isCallExpression(e)||be.isOptionalCallExpression(e))}function rE(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(be.isMemberExpression(n)||be.isOptionalMemberExpression(n))&&be.isIdentifier(n.property)&&n.property.name==="map"&&!n.computed}function Li(e,t){let n=zt(e);if(!n)return t.isRepeatItemRoot===!0;let r=Be(n,it(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:wl(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=br(e,o);return i?RF(o,i):t.isRepeatItemRoot===!0}function oE(e,t){let n=zt(e);if(!n)return!1;let r=Be(n,it(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:wl(n,t);return o?!!o.findParent(i=>{if(!i.isCallExpression()&&!i.isOptionalCallExpression())return!1;let s=i.node.callee;return(be.isMemberExpression(s)||be.isOptionalMemberExpression(s))&&be.isIdentifier(s.property)&&s.property.name==="map"}):!1}import*as ut from"@babel/types";function Fp(e){if(ut.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(ut.isJSXMemberExpression(e)){let t=e;for(;ut.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function AF(e,t){let n=tt(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);!a||yr(a.path.node,n)||go(a,i,t)||r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=Fp(i.node.name);s&&o(s,i)}}),[...r].sort()}function Dp(e,t,n){let r=zt(e);if(!r)return{ok:!0};let o=Be(r,it(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=Be(r,it(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};let s=Ss(o.match.path,i.match.path);if(Tl(s,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let a=AF(s,i.match.path);return a.length>0?{ok:!1,bindingNames:a}:{ok:!0}}function sE(e){let t=e;for(;ut.isTSQualifiedName(t);)t=t.left;return ut.isIdentifier(t)?t.name:null}function ua(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function Dl(e){let t=[],n=r=>{if(r){if(ut.isIdentifier(r)){t.push(r.name);return}if(ut.isObjectPattern(r)){for(let o of r.properties){if(ut.isRestElement(o)){n(o.argument);continue}ut.isObjectProperty(o)&&n(o.value)}return}if(ut.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(ut.isAssignmentPattern(r)){n(r.left);return}if(ut.isRestElement(r)){n(r.argument);return}ut.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function Mp(e,t){let n=tt(e.node),r=tt(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=iE(e),i=iE(t);if(!o||!i||!HS(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=GS(s.node,n);if(a&&!Tn(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=tt(s.node.right);if(a&&Tn(a,n)&&!Tn(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())&&rE(s)){let a=tt(s.node.body)??tt(s.node);if(a&&!Tn(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 iE(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?tt(t.node.argument):null;if(t.isArrowFunctionExpression()&&(ut.isJSXElement(t.node.body)||ut.isJSXFragment(t.node.body)||ut.isConditionalExpression(t.node.body)||ut.isLogicalExpression(t.node.body)))return tt(t.node.body);t=t.parentPath}return null}function go(e,t,n){return n.scope.getBinding(t)===e}function Bp(e,t,n,r={}){if(!r.preserveConditionalBoundary&&Tl(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=tt(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(l=>Dl(l)).map(l=>n.callbackPath.scope.getBinding(l)?.path.node).filter(Boolean)),s=new Set,a=(l,c)=>{let u=c.scope.getBinding(l);!u||yr(u.path.node,o)||i.has(u.path.node)||go(u,l,t)||s.add(l)};return e.traverse({ReferencedIdentifier(l){a(l.node.name,l)},JSXOpeningElement(l){let c=Fp(l.node.name);c&&a(c,l)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function jp(e,t,n){let r=tt(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>Dl(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return ua(e,s=>{let a=s.scope.getBinding(s.node.name);!a||yr(a.path.node,r)||o.has(a.path.node)||go(a,s.node.name,t)||i.add(s.node.name)}),i.size>0?{ok:!1,bindingNames:[...i].sort()}:{ok:!0}}function aE(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>Dl(a)).map(a=>e.callbackPath.scope.getBinding(a)?.path.node).filter(Boolean)),r=new Set,o=(a,l)=>{let c=l.scope.getBinding(a);!c||n.has(c.path.node)||go(c,a,t)||r.add(a)},i=e.callbackPath.get("params"),s=Array.isArray(i)?i:[i];for(let a of s)a.traverse({ReferencedIdentifier(l){o(l.node.name,l)},TSTypeReference(l){let c=l.node.typeName;if(Fi.isIdentifier(c))o(c.name,l);else{let u=sE(c);u&&o(u,l)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function $p(e,t){let n=tt(e.node),r=new Set;return ua(e,o=>{let i=o.scope.getBinding(o.node.name);i&&(n&&yr(i.path.node,n)||go(i,o.node.name,t)||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 cE(e){let t=[];for(let n of e.callbackPath.node.params){if(Fi.isIdentifier(n)){t.push(n.name);continue}if(Fi.isRestElement(n)&&Fi.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 lE(e,t){return{...e,callbackParams:t}}function Up(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function da(e,t,n,r){return n?.finalSource?.kind==="component-prop"||r?.allowUpstreamBindingRemoval&&n?.chain.some(i=>i.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"&&!r?.allowUpstreamBindingRemoval?"Cannot edit upstream-bound node structure with a generic node operation":null}function uE(e,t,n,r){return e.parentKey===t.key&&e.file===t.file&&n?.kind==="value-binding"&&n.file!==e.file&&n.sourceKind!=="repeat-template"&&r?.finalSource?.kind!=="component-prop"}function Go(e){return{file:e.file,component:e.component}}function wF(e){return e.target.kind==="node"?e.target.key:null}function TF(e){return"kind"in e&&e.kind==="page-composition"}function jl(e){return typeof e=="object"&&e!==null&&"kind"in e&&e.kind==="block-boundary"}function Ml(e){return!TF(e)&&!jl(e)}function zp(e,t){let n=Ul.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Ul.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Vp(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=ur(n,it(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function Hp(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 OF(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function LF(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 Kp(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function FF(e){let t=FS(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=Mp(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=DF({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=bE(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?Fl(o):!0}}}function DF(e){let t=tt(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||yr(a.path.node,t))return;let l=jF(s,a,t);if(l){if(l.hasDefault){o="Cannot move prop-backed repeat child because the collection prop has a default value that cannot be preserved safely";return}let c=UF(e.callSitePath,l.propName,e.source);if(!c.ok){o=c.reason;return}let u=MF(c.expression,l.remainingPath);if(!u){o="Cannot move prop-backed repeat child because the mapped prop path is not a portable expression";return}let d=$p(c.expressionPath,e.targetParentPath);if(!d.ok){o=d.reason??`Cannot move prop-backed repeat child because the mapped prop source is not visible at the target: ${d.bindingNames.join(", ")}`;return}n.set(`${l.range.start}:${l.range.end}`,{...l.range,text:u});return}go(a,s.node.name,e.targetParentPath)||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:VF(e.source,t,[...n.values()])}}function MF(e,t){if(t.length===0)return e;let n=bE(e);if(!n)return null;let r=Fl(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=BF(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function BF(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function jF(e,t,n){let r=$F(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=Pi(t,o);if(!i)return null;let s=r?.range??tt(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function $F(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!yr(n.node,t)||n.node.computed||!Ye.isIdentifier(n.node.property))return null;let r=tt(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function UF(e,t,n){let r=e.get("openingElement").get("attributes");if(r.some(l=>l.isJSXSpreadAttribute()))return{ok:!1,reason:"Cannot move prop-backed repeat child through spread props; use an explicit prop mapping"};let o=r.find(l=>l.isJSXAttribute()&&Ye.isJSXIdentifier(l.node.name)&&l.node.name.name===t);if(!o?.isJSXAttribute())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not passed explicitly`};let i=o.get("value");if(!i.isJSXExpressionContainer())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not an expression`};let s=i.get("expression");if(!s.isExpression())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not a usable expression`};let a=Oi(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 VF(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 bE(e){try{let n=xE.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=Ye.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&Ye.isExpression(r)?r:null}catch{return null}}function KF(e){let t=tt(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||yr(s.path.node,t))return;let a=dE(s,e.sourceFile,e.targetFile);if(a){let l=e.targetParentPath.scope.getBinding(a.localName);if(l){let u=dE(l,e.targetFile,e.targetFile);(!u||u.moduleFile!==a.moduleFile||!JF(u.importSpec,a.importSpec))&&r.add(a.localName);return}let c=n.get(a.moduleSpecifier)??[];c.some(u=>JSON.stringify(u)===JSON.stringify(a.importSpec))||c.push(a.importSpec),n.set(a.moduleSpecifier,c);return}r.add(i.node.name)};return ua(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 JF(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 dE(e,t,n){let r=XF(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=zo(t,i),a=i.startsWith(".")?zp(n,s):i;if(r.isImportDefaultSpecifier()){let l=r.node.local.name;return{localName:l,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"default",local:l}}}if(r.isImportNamespaceSpecifier()){let l=r.node.local.name;return{localName:l,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"namespace",local:l}}}if(r.isImportSpecifier()){let l=Ye.isIdentifier(r.node.imported)?r.node.imported.name:r.node.imported.value,c=r.node.local.name;return{localName:c,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"named",imported:l,local:c===l?void 0:c}}}return null}function XF(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function fE(e,t,n,r){let o=Ap(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let l=Oi(e,a.conditionPath.node);if(!l)return{sourceJsx:r,conditionPaths:[]};let c=zF(a.conditionPath,l);if(s.push(a.conditionPath),a.kind==="logical"){i=`${c} ${a.operator} ${HF(i)}`;continue}i=a.branch==="consequent"?`${c} ? ${i} : null`:`${c} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function zF(e,t){return WF(e.node)?t:`(${t})`}function WF(e){return Ye.isIdentifier(e)||Ye.isThisExpression(e)||Ye.isSuper(e)||Ye.isMemberExpression(e)||Ye.isOptionalMemberExpression(e)||Ye.isCallExpression(e)||Ye.isOptionalCallExpression(e)||Ye.isBooleanLiteral(e)||Ye.isNumericLiteral(e)||Ye.isStringLiteral(e)||Ye.isNullLiteral(e)||Ye.isUnaryExpression(e)}function HF(e){return e.trim().startsWith("<")?e:`(${e})`}var GF={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 Bl(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=GF[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 YF(e,t){for(let n of e.program.body){if(!Ye.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>Ye.isImportDefaultSpecifier(o));if(r&&Ye.isImportDefaultSpecifier(r))return r.local.name}return null}function ZF(e,t,n){for(let r of e.program.body){if(!Ye.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>Ye.isImportSpecifier(i)&&(Ye.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&Ye.isImportSpecifier(o))return o.local.name}return null}function pE(e){let t=new Set;return rr(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function mE(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function qF(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=Hp(e),o=zt(t);if(n.exportName!=="default"){let a=o?ZF(o,n.source,n.exportName):null;if(a)return{localName:a};let l=o?mE(r,pE(o)):r;return{localName:l,importStep:Jp(e,l)}}if(!o)return{localName:r,importStep:Jp(e,r)};let i=YF(o,n.source);if(i)return{localName:i};let s=mE(r,pE(o));return{localName:s,importStep:Jp(e,s)}}function QF(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??Hp(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 eD(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?tD(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function tD(e){return Object.fromEntries(Object.entries(e).filter(t=>Wp(t[1])))}function Wp(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(Wp):typeof e=="object"?Object.values(e).every(Wp):!1}function Jp(e,t=Hp(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 gE(e,t){if("kind"in e)return{parentNode:null,anchorNode:null,placement:e.relation};if(e.relation==="prepend"||e.relation==="append"){let o=t.getNode(e.parentKey);return{parentNode:o,anchorNode:null,placement:e.relation,...o?{}:{error:{errorCode:"locator-miss",reason:`Target parent '${e.parentKey}' not found in graph`}}}}if(!("anchorKey"in e))return{parentNode:null,anchorNode:null,placement:e.relation,error:{errorCode:"invalid-target",reason:`Sibling target '${e.relation}' requires an anchor`}};let n=t.getNode(e.anchorKey),r=t.getNode(e.parentKey);return n?r?n.parentKey!==r.key?{parentNode:r,anchorNode:n,placement:e.relation,error:{errorCode:"invalid-target",reason:`Target anchor '${n.key}' belongs to parent '${n.parentKey??"<root>"}', expected '${r.key}'`}}:{parentNode:r,anchorNode:n,placement:e.relation}:{parentNode:null,anchorNode:n,placement:e.relation,error:{errorCode:"locator-miss",reason:`Target parent '${e.parentKey}' not found in graph`}}:{parentNode:r,anchorNode:null,placement:e.relation,error:{errorCode:"locator-miss",reason:`Target anchor '${e.anchorKey}' not found in graph`}}}function nD(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function Di(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function Gp(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function fa(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:Gp(e,t.slice(0,n)),index:r.index}}return null}function Xp(e,t){return e.locator?e.collectionPathMap?.[t]?Gp(e.locator,e.collectionPathMap[t]):fa(e.locator)?oD(e.locator,iD(t,e.collectionIndexMap)):null:null}function rD(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:SE(o,t)}function SE(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=SE(r,t);return o===void 0?void 0:{[n.name]:o}}function oD(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},Gp(e,i)}return null}function iD(e,t){return t?.[e]??e}function hE(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 sD(e,t){return aD(e.root,t.root)&&lD(e.path??[],t.path??[])}function aD(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&&cD(e.sourceRange,t.sourceRange)}}function cD(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function lD(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 $l=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:Di(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:Di(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:Di(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:Di(t.kind,t.params.kind)};let r=t;if(jl(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page-block boundaries require the page-block resolver"};if(!Ml(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=gE(r.params.position,this.graph);if(o.error)return{ok:!1,errorCode:o.error.errorCode,reason:o.error.reason};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:Di(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"set-link-target":{if(t.params.kind!=="set-link-target")return{ok:!1,errorCode:"invalid-params",reason:Di(t.kind,t.params.kind)};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.planSetLinkTarget(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=wF(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):yE(i)}async planSetLinkTarget(t,n,r){if(r.tag!=="a"&&!(r.importedFrom==="next/link"&&r.exportName==="default"))return{ok:!1,errorCode:"capability-denied",reason:"Only native anchors and source-verified next/link nodes can be changed"};if(r.structuralPath.includes("#repeat:")||r.isRepeatRegion||r.isRepeatItemRoot)return{ok:!1,errorCode:"capability-denied",reason:"Link target changes are not supported inside repeat templates"};if(n.selectionRef?.instanceIndex!==void 0||(n.selectionRef?.instanceCount??1)>1)return{ok:!1,errorCode:"capability-denied",reason:"Link target changes require a single non-repeated selection"};if(n.params.changes.length>0){let o=await this.buildTypedPropertySteps({node:r,scope:"selection",changes:n.params.changes,selectionRef:n.selectionRef});if(!o.ok)return yE(o);if(o.steps.some(i=>i.type!=="set-property-changes"||i.file!==r.file))return{ok:!1,errorCode:"capability-denied",reason:"Link descriptions must have a direct, unique source in the selected file"}}return this.buildPlan(t,n,[{type:"set-link-target",order:0,file:r.file,locator:it(r),link:n.params.link,changes:n.params.changes}],this.graph.getCapability(r.key))}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?eE({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[l,c]of Object.entries(o)){if(c===void 0)continue;let u=await this.graph.getElementPropertyWriteTarget?.(r.key,l),d=r.attributes?.find(m=>m.name===l);if((await this.graph.getPropertyState?.(r.key,l,i))?.status==="blocked"||!u&&d?.source)return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite a derived or unresolved property '${l}'`};if(!(typeof d?.resolvedValue=="string"&&d.resolvedValue===c||d?.source===null&&d.value===c)){if(u?.kind==="external-entry")return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite readonly external property '${l}'`};if(u?.kind==="value-binding"&&u.locator){let m=u.locator;if(u.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let g=Xp(u,i.instanceIndex);if(!g)return{ok:!1,errorCode:"invalid-params",reason:"apply-style-draft could not resolve the selected repeat item"};m=g}s.push({order:n+s.length,file:u.file,type:"update-value",locator:m,value:c});continue}a.push({operation:"set",name:l,value:c})}}return a.length>0&&s.push({order:n+s.length,file:r.file,type:"set-property-changes",locator:it(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=Xp(o,i.instanceIndex);if(!a)return{ok:!1,errorCode:"invalid-params",reason:"update-text could not resolve the selected repeat item"};let l=this.coerceTextValueForValueTarget(o.file,a,r);return l.ok?{ok:!0,steps:[{order:0,file:o.file,type:"update-array-item",locator:a,value:l.value}]}:l}let s=this.coerceTextValueForValueTarget(o.file,o.locator,r);return s.ok?{ok:!0,steps:[{order:0,file:o.file,type:"update-value",locator:o.locator,value:s.value}]}:s}return{ok:!0,steps:o?.kind==="external-entry"?[{order:0,file:`external:${o.sourceId}`,type:"invoke-external-adapter",sourceType:o.sourceType,sourceId:o.sourceId,adapterId:o.adapterId,capability:"write-text",value:r}]:[{order:0,file:t.file,type:"update-text",locator:it(t),segmentIndex:n,newText:r}]}}coerceTextValueForValueTarget(t,n,r,o="update-text"){let i=this.graph.getFileContent(t),s=zt(i);if(!s)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not inspect the value source`};let a=Be(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!OF(a.match.path))return{ok:!0,value:r};let l=LF(r);return l===null?{ok:!1,errorCode:"invalid-params",reason:`${o} value must be a valid number for numeric source`}:{ok:!0,value:l}}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 l=Xp(o,i);if(!l)return{ok:!1,errorCode:"invalid-params",reason:"update-array-item could not resolve the selected repeat item"};let c=this.coerceTextValueForValueTarget(o.file,l,s,"update-array-item");return c.ok?this.isValueTargetUnchanged(o.file,l,c.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:l,value:c.value}],r):c}isValueTargetUnchanged(t,n,r){let o=zt(this.graph.getFileContent(t));if(!o)return!1;let i=Be(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){let s=this.graph.getTextProvenance?.(r.key,n.params.segmentIndex);if(s&&(s.editMode==="readonly"||s.editMode==="unsupported"))return{ok:!1,errorCode:"unsupported-operation",reason:"Text has no identity-preserving write target"};if(!o.canUpdateText)return{ok:!1,errorCode:"capability-denied",reason:"Cannot update text on this node"};let a=this.buildTextRewriteSteps(r,n.params.segmentIndex,n.params.value,i,n.selectionRef);return a.ok?this.buildPlan(t,n,a.steps,o):a}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 f=fa(d.locator);if(f)return this.buildPlan(t,n,[{order:0,file:d.file,type:"remove-bound-array-item",locator:f.locator,index:f.index}],o)}return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed node removal requires a writable array target"}}let s=da(r,i,this.graph.getTextProvenance?.(r.key,0)??null,{allowUpstreamBindingRemoval:!0});if(s)return{ok:!1,errorCode:"unsupported-operation",reason:s};let a=this.getRepeatBackedTemplateStructureReason(r);if(a)return{ok:!1,errorCode:"unsupported-operation",reason:a};let l=await this.getUpstreamBackedDescendantReason(r,{allowUpstreamBindingRemoval:!0});if(l)return{ok:!1,errorCode:"unsupported-operation",reason:l};let c=[{order:0,file:r.file,type:"remove-node",locator:it(r),removeWhitespace:!0}],u=this.buildRemoveComponentImportStep(r);return u&&c.push({...u,order:c.length}),this.buildPlan(t,n,c,o)}buildRemoveComponentImportStep(t,n=this.graph.getFileContent(t.file)){if(!t.importedFrom||!t.exportName||!t.tag||WS(n,t)>1)return null;let r=zp(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(!Ml(n.params.position))return jl(n.params.position)?{ok:!1,errorCode:"unsupported-operation",reason:"Page-block boundaries require the page-block resolver"}:{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,l=da(r,a,s!==null?this.graph.getTextProvenance?.(r.key,s)??null:null);if(l)return{ok:!1,errorCode:"unsupported-operation",reason:l};let c=await this.getUpstreamBackedDescendantReason(r);if(c)return{ok:!1,errorCode:"unsupported-operation",reason:c};let u=await this.planExternalBackedInsertChild(t,n,r,o,i,a);if(u)return u;let d=await this.planRepeatBackedInsertChild(t,n,r,o);if(d)return d;let f=this.getRepeatBackedTemplateStructureReason(r);if(f)return{ok:!1,errorCode:"unsupported-operation",reason:f};let m=PS(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=Bl(r,n.params.node);if(g)return{ok:!1,errorCode:"unsupported-operation",reason:g};let p=[],h=0,x=n.params.node.kind==="component-call"?qF(n.params.node,this.graph.getFileContent(r.file)):void 0,b=x?.importStep;return b&&p.push({order:h++,file:r.file,type:"add-import",moduleSpecifier:b.moduleSpecifier,imports:b.imports}),p.push({order:h++,file:r.file,type:"insert-child",parentLocator:it(r),node:{jsx:QF(n.params.node,x?.localName)},placement:n.params.position.relation,anchorLocator:i?it(i):void 0}),this.buildPlan(t,n,p,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!Ml(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 l=i?await this.graph.getTextWriteTarget(i.key,0):null;return this.buildPlan(t,n,[{order:0,file:`external:${a.sourceId}`,type:"invoke-external-adapter",sourceType:a.sourceType,sourceId:a.sourceId,adapterId:a.adapterId,capability:"insert-child",value:{operation:"insert-child",relation:n.params.position.relation,parentKey:r.key,anchorSourceId:l?.kind==="external-entry"?l.sourceId:null,node:eD(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(!Ml(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 l=fa(a.locator);if(!l)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let c=rD(a.locator,i.text);if(c===void 0)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child could not infer an item shape from the template"};let u=n.params.position.relation==="prepend"?hE(0,a.collectionIndexMap):hE(a.collectionIndexMap?.length??l.index+1,a.collectionIndexMap);return this.buildPlan(t,n,[{order:0,file:a.file,type:"insert-bound-array-item",locator:l.locator,index:u,value:c}],o)}async getUpstreamBackedDescendantReason(t,n){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=this.graph.getEditableTextSegmentIndex(o.key),s=i!==null?await this.graph.getTextWriteTarget(o.key,i):null,a=da(o,s,i!==null?this.graph.getTextProvenance?.(o.key,i)??null:null,n);if(a)return a;r.push(...this.graph.getChildNodes(o.key))}return null}getRepeatBackedTemplateStructureReason(t){if(t.isRepeatItemRoot)return Li(this.graph.getFileContent(t.file),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:")||oE(this.graph.getFileContent(t.file),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}planRepeatTemplateInternalMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&Li(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let l=this.graph.getFileContent(r.file),c=zt(l);if(!c)return null;let u=Hn(c,r),d=Hn(c,o);if(!u||!d)return null;let f=br(l,u),m=br(l,d);if(!la(f,m))return null;if(a&&(s==="before"||s==="after")){let p=Hn(c,a),h=p?br(l,p):null;if(!la(f,h))return null}if(Ol(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let g=Dp(l,r,o);return g.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:it(r),targetParentLocator:it(o),placement:s,anchorLocator:a?it(a):void 0,selectionContext:Go(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&&Li(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let l=this.graph.getFileContent(r.file),c=zt(l);if(!c)return null;let u=Hn(c,r),d=Hn(c,o);if(!u||!d)return null;let f=br(l,u);if(!f)return null;let m=br(l,d);if(la(f,m))return null;if(m&&!nE(m,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")){let S=Lp(l,c,a);if(m&&!la(m,S)||!m&&S)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 S=Bl(o,{kind:"native-tag",tag:r.tag});if(S)return{ok:!1,errorCode:"unsupported-operation",reason:S}}let g=Vp(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(Ol(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let p=fE(l,u,d,g);for(let S of p.conditionPaths){let E=jp(S,d,f);if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${E.bindingNames.join(", ")}`}}let h=Bp(u,d,f,{preserveConditionalBoundary:p.conditionPaths.length>0});if(!h.ok)return{ok:!1,errorCode:"unsupported-operation",reason:h.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${h.bindingNames.join(", ")}`};let x=aE(f,d);if(!x.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its callback parameters depend on bindings outside the target scope: ${x.bindingNames.join(", ")}`};let b=f;if(r.component!==o.component){let S=FF({source:l,ast:c,sourceContext:f,sourceNode:r,targetParent:o,targetParentPath:d});if(!S.ok)return{ok:!1,errorCode:"unsupported-operation",reason:S.reason};b=S.context}else{let S=$p(f.collectionPath,d);if(!S.ok)return{ok:!1,errorCode:"unsupported-operation",reason:S.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${S.bindingNames.join(", ")}`}}return this.buildPlan(t,n,[{order:0,file:r.file,type:"move-repeat-template-child",locator:it(r),targetParentLocator:it(o),placement:s,anchorLocator:a?it(a):void 0,repeatExpression:Up(b,p.sourceJsx),selectionContext:Go(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&Li(this.graph.getFileContent(r.file),r)||r.file===o.file)return null;let l=this.graph.getFileContent(r.file),c=this.graph.getFileContent(o.file),u=zt(l),d=zt(c);if(!u||!d)return null;let f=YS({knownSourceFiles:this.graph.getKnownSourceFiles?.(),routeEntryFiles:this.graph.getRouteEntryFiles?.(),sourceAst:u,sourceFile:r.file,targetFile:o.file,sourceComponent:r.component,targetComponent:o.component});if(!f.ok)return{ok:!1,errorCode:"unsupported-operation",reason:f.reason};let m=Hn(u,r),g=Hn(d,o);if(!m||!g)return null;let p=Mp(f.callSitePath,g);if(!p.ok)return{ok:!1,errorCode:"unsupported-operation",reason:p.reason};let h=br(l,m);if(!h)return null;if(br(c,g))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")&&Lp(c,d,a))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child relative to a repeat-template anchor outside the target scope"};if(r.tag&&r.tag.toLowerCase()===r.tag){let C=Bl(o,{kind:"native-tag",tag:r.tag});if(C)return{ok:!1,errorCode:"unsupported-operation",reason:C}}let b=Vp(this.graph,r);if(!b)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Ol(m,g))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let S=fE(l,m,g,b);for(let C of S.conditionPaths){let O=jp(C,g,h);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 E=Bp(m,g,h,{preserveConditionalBoundary:S.conditionPaths.length>0});if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:E.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${E.bindingNames.join(", ")}`};let v=KF({sourceFile:r.file,targetFile:o.file,sourceContext:h,targetParentPath:g});if(!v.ok)return{ok:!1,errorCode:"unsupported-operation",reason:v.reason};let N=cE(h);if(!N.ok)return{ok:!1,errorCode:"unsupported-operation",reason:N.reason};let I=lE(h,N.callbackParams),A=[{order:0,file:r.file,type:"remove-node",locator:it(r),removeWhitespace:!0}];for(let C of v.imports)A.push({order:A.length,file:o.file,type:"add-import",moduleSpecifier:C.moduleSpecifier,imports:C.imports});return A.push({order:A.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:it(o),expression:Up(I,S.sourceJsx),placement:s,anchorLocator:a?it(a):void 0,selectionContext:Go(o)}),this.buildPlan(t,n,A,i)}async planMoveNode(t,n,r,o){if(!o.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};if(jl(n.params.target))return{ok:!1,errorCode:"unsupported-operation",reason:"Page-block boundaries require the page-block resolver"};if("kind"in n.params.target&&n.params.target.kind==="source-sibling"){let S=n.params.target,E=this.graph.getNode(S.anchorKey);if(!E||r.file!==E.file||r.component!==E.component)return{ok:!1,errorCode:"locator-miss",reason:"Source sibling move requires a sibling in the same component file"};let v=this.graph.getFileVersion(r.file);if(n.documentVersion!==v)return{ok:!1,errorCode:"stale-version",reason:`Document version ${n.documentVersion} is stale or otherwise does not match source sibling file version (current: ${v})`};let N=this.graph.getFileContent(r.file),I=zt(N),A=I?Hn(I,r):null,C=I?Hn(I,E):null,O=A?.parentPath,L=C?.parentPath;if(!A||!C||!O||!L||O.node!==L.node||!O.isJSXFragment()&&!(O.isJSXElement()&&ht(O)))return{ok:!1,errorCode:"unsupported-operation",reason:"Source sibling move requires two direct children of the same transparent Fragment"};let X=O.node.loc;return X?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:it(r),targetParentLocator:{kind:"jsx-node",strategy:"source-range",sourceRange:{startLine:X.start.line,startColumn:X.start.column,endLine:X.end.line,endColumn:X.end.column}},placement:S.relation,anchorLocator:it(E),selectionContext:Go(r)}],o):{ok:!1,errorCode:"locator-miss",reason:"Source Fragment has no stable source range"}}let i=gE(n.params.target,this.graph);if(i.error)return{ok:!1,errorCode:i.error.errorCode,reason:i.error.reason};let s=i.parentNode;if(!s)return{ok:!1,errorCode:"locator-miss",reason:`Target parent for request '${n.id}' not found in graph`};let a=this.graph.getFileVersion(s.file);if(n.documentVersion!==a)return{ok:!1,errorCode:"stale-version",reason:`Document version ${n.documentVersion} is stale or otherwise does not match target parent version (current: ${a})`};if(nD(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 l=await this.graph.getTextWriteTarget(r.key,0);if(l?.kind==="external-entry"){let S=n.params.target.relation,E=i.anchorNode&&(S==="before"||S==="after")?await this.graph.getTextWriteTarget(i.anchorNode.key,0):null;return this.buildPlan(t,n,[{order:0,file:`external:${l.sourceId}`,type:"invoke-external-adapter",sourceType:l.sourceType,sourceId:l.sourceId,adapterId:l.adapterId,capability:"move-node",value:{operation:"move-node",relation:S,anchorSourceId:E?.kind==="external-entry"?E.sourceId:null,parentKey:"parentKey"in n.params.target?n.params.target.parentKey:null}}],o)}let c=r.file!==s.file,u=n.params.target.relation,d=i.anchorNode,f=this.graph.getTextProvenance?.(r.key,0)??null,m=da(r,l,f);if(m&&!Kp(m)&&!uE(r,s,l,f))return{ok:!1,errorCode:"unsupported-operation",reason:m};if(r.isRepeatItemRoot&&d?.isRepeatItemRoot&&r.repeatOwnerKey&&r.repeatOwnerKey===d.repeatOwnerKey&&(u==="before"||u==="after")){let S=l,E=await this.graph.getTextWriteTarget(d.key,0);if(S?.kind==="value-binding"&&E?.kind==="value-binding"&&S.locator&&E.locator){let v=fa(S.locator),N=fa(E.locator);if(v&&N&&S.file===E.file&&sD(v.locator,N.locator)){let I=v.index,A=N.index,C=u==="before"?A-(I<A?1:0):A+(I<A?0:1);return this.buildPlan(t,n,[{order:0,file:S.file,type:"move-array-item",locator:v.locator,fromIndex:I,toIndex:C}],o)}}}if(r.isRepeatItemRoot&&Li(this.graph.getFileContent(r.file),r))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed item outside its collection"};let g=this.getRepeatBackedTemplateStructureReason(r),p=Kp(m)?m:g;if(p&&Kp(p)){let S=this.planRepeatTemplateInternalMove(t,n,r,s,o,u,d);if(S)return S;let E=this.planRepeatTemplateHoistMove(t,n,r,s,o,u,d);if(E)return E;let v=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,u,d);return v||{ok:!1,errorCode:"unsupported-operation",reason:p}}if(g)return{ok:!1,errorCode:"unsupported-operation",reason:g};let h=await this.getUpstreamBackedDescendantReason(r);if(h)return{ok:!1,errorCode:"unsupported-operation",reason:h};if(r.tag&&r.tag.toLowerCase()===r.tag){let S=Bl(s,{kind:"native-tag",tag:r.tag});if(S)return{ok:!1,errorCode:"unsupported-operation",reason:S}}if(c)return this.planCrossFileMove(t,n,r,s,o,u,d);let x=Dp(this.graph.getFileContent(r.file),r,s);if(!x.ok)return{ok:!1,errorCode:"unsupported-operation",reason:x.reason??`Cannot move node because it depends on bindings outside the target scope: ${x.bindingNames.join(", ")}`};let b=[{order:0,file:r.file,type:"move-node",locator:it(r),targetParentLocator:it(s),placement:u,anchorLocator:d?it(d):void 0,selectionContext:Go(s)}];return this.buildPlan(t,n,b,o)}planCrossFileMove(t,n,r,o,i,s,a){let l=[],c=0,u=this.graph.getFileContent(r.file),d=Vp(this.graph,r)??`<${r.component} />`,f=NS(u,r);if(!f.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:f.reason??"Cannot move subtree across files"};if(l.push({order:c++,file:r.file,type:"remove-node",locator:it(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let g=r.tag??r.component,h={moduleSpecifier:zp(o.file,r.importedFrom),imports:r.exportName==="default"?[{kind:"default",local:g}]:[{kind:"named",imported:r.exportName,local:g===r.exportName?void 0:g}]};l.push({order:c++,file:o.file,type:"add-import",moduleSpecifier:h.moduleSpecifier,imports:h.imports}),l.push({order:c++,file:o.file,type:"insert-child",parentLocator:it(o),node:{jsx:d},placement:s,anchorLocator:a?it(a):void 0,selectionContext:Go(o)})}else l.push({order:c++,file:o.file,type:"insert-child",parentLocator:it(o),node:{jsx:d},placement:s,anchorLocator:a?it(a):void 0,selectionContext:Go(o)});let m=this.buildRemoveComponentImportStep(r,u);return m&&l.push({...m,order:c++}),this.buildPlan(t,n,l,i)}buildPlan(t,n,r,o){let s=[...new Set(r.map(a=>a.file))].map(a=>({file:a,content:this.graph.getFileContent(a),version:this.graph.getFileVersion(a),exists:!0,sha256:$e(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 yE(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 nm from"@babel/generator";import{parse as vD,parseExpression as kD}from"@babel/parser";import*as k from"@babel/types";import*as Sr from"@babel/types";import Yp from"@babel/generator";import*as ct from"@babel/types";var uD=typeof Yp=="function"?Yp:Yp.default,dD=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,fD=/^((?:https?:)?\/\/)[^/@\s]+@/i,pD=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function IE(e,t){let n=On(e.callee);if(!n)return null;if(n==="fetch")return Zp(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(EE(r))return Zp(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(EE(r))return Zp(e.arguments[0],r,t,["ky client contract"])}return null}function Zp(e,t,n,r){if(!e||ct.isSpreadElement(e)||ct.isJSXNamespacedName(e))return yD(t,n,r,"missing url argument");let o=pa(e);return{sourceKind:hD(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 pa(e){if(ct.isStringLiteral(e))return Yo(e.value);if(ct.isTemplateLiteral(e))return Yo(mD(e));if(ct.isBinaryExpression(e)&&e.operator==="+"){let t=pa(e.left),n=pa(e.right);return!t&&!n?void 0:Yo(`${t??qp(e.left)}${n??qp(e.right)}`)}if(ct.isMemberExpression(e)){let t=vE(e);if(t)return`env:${t}`}if(!(ct.isCallExpression(e)&&On(e.callee)==="new URL")){if(ct.isNewExpression(e)&&ct.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!ct.isSpreadElement(t)?pa(t):void 0,o=n&&!ct.isSpreadElement(n)?pa(n):void 0;return o&&r?Yo(`${o} + ${r}`):r??o}if(ct.isIdentifier(e))return`:${e.name}`}}function mD(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+=qp(r))}return t}function qp(e){if(ct.isIdentifier(e))return`:${e.name}`;if(ct.isMemberExpression(e)){let t=vE(e);if(t)return`env:${t}`}return`:${gD(e)}`}function gD(e){return uD(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function Yo(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(fD,"$1<redacted>@").replace(pD,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?dD.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function hD(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 yD(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function EE(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function vE(e){return!ct.isMemberExpression(e.object)||!ct.isIdentifier(e.object.object,{name:"process"})||!xD(e.object.property,"env")?null:ct.isIdentifier(e.property)?e.property.name:ct.isStringLiteral(e.property)?e.property.value:null}function xD(e,t){return ct.isIdentifier(e)&&e.name===t}function On(e){if(ct.isIdentifier(e))return e.name;if(ct.isMemberExpression(e)){let t=On(e.object),n=ct.isIdentifier(e.property)?e.property.name:ct.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var bD=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),SD=new Set(["getConfig","submit"]);function jr(e,t){let n=kE(On(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!bD.has(i))return null;let s=Qp(e,0),a=i==="getByUrl"||i==="getByUrlStrict",l=a?void 0:s,c=a?s??"/:record-url":l?`/collections/${l}`:"/collections/:collection";return{sourceKind:"vcp-cms-collection",sourceType:"cms-field",operation:i,...l?{collection:l}:{},endpointPattern:c,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(!SD.has(i))return null;let s=Qp(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=Qp(e,0)??ED(e,0,"path")??"/cms/:path",s=ID(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 kE(e,t){if(!e)return null;let n=e.indexOf("."),r=n<0?e:e.slice(0,n),o=n<0?"":e.slice(n),i=t.imports?.get(r);return i?i.importedName==="cms"&&/^(?:src\/)?lib\/cms(?:\/index)?\.[cm]?[jt]s$/.test(i.source)?`cms${o}`:i.importedName==="collections"&&/^(?:src\/)?lib\/cms\/collections\.[cm]?[jt]s$/.test(i.source)?`cms.collections${o}`:!o&&["cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(i.importedName)&&/^(?:src\/)?lib\/cms\/client\.[cm]?[jt]s$/.test(i.source)?i.importedName:null:null}function _E(e,t){let n=On(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 Vl(e,t){let n=On(e.callee),r=t?kE(n,t):n;return typeof r=="string"&&r.startsWith("cms.field.")}function Qp(e,t){let n=e.arguments[t];return Sr.isStringLiteral(n)?n.value:null}function ED(e,t,n){let r=e.arguments[t];if(!Sr.isObjectExpression(r))return null;for(let o of r.properties)if(Sr.isObjectProperty(o)&&!o.computed&&(Sr.isIdentifier(o.key)&&o.key.name===n||Sr.isStringLiteral(o.key)&&o.key.value===n)&&Sr.isStringLiteral(o.value))return o.value.value;return null}function ID(e){let t=/^\/collections\/([^/]+)(?:\/|$)/.exec(e)?.[1];return t&&/^[a-z0-9][a-z0-9_-]*$/i.test(t)?t:null}function Kl(e){return e.match(/^\/([a-z0-9][a-z0-9_-]*)\/[^/?#]+(?:[?#].*)?$/i)?.[1]??null}import*as jt from"@babel/types";var em=new WeakMap;function Er(e,t){let n=em.get(e)?.get(t);if(n!==void 0)return n;let r=new Set([t]),o=c=>{let u=c;for(;jt.isMemberExpression(u)||jt.isOptionalMemberExpression(u);)u=u.object;return jt.isIdentifier(u)?u.name:null},i=!0;for(;i;)i=!1,jt.traverseFast(e,c=>{if(!jt.isVariableDeclarator(c)||!c.init)return;let u=o(c.init);if(!(!u||!r.has(u)))for(let d of Object.keys(jt.getBindingIdentifiers(c.id)))r.has(d)||(r.add(d),i=!0)});let s=c=>{let u=o(c);return u?r.has(u):Object.keys(jt.getBindingIdentifiers(c)).some(d=>r.has(d))},a=!1;jt.traverseFast(e,c=>{(jt.isAssignmentExpression(c)&&s(c.left)||jt.isUpdateExpression(c)&&s(c.argument)||jt.isUnaryExpression(c,{operator:"delete"})&&s(c.argument))&&(a=!0)});let l=em.get(e)??new Map;return l.set(t,a),em.set(e,l),a}function CE(e=4096){if(!Number.isSafeInteger(e)||e<1)throw new RangeError("Re-export relation capacity must be positive.");let t=new Map,n=new Set,r=o=>{let i=t.get(o.fromFile),s=i?.get(o.exportName),a=s?.get(o.targetFile);a?.get(o.maxImportDepth)===o&&(a.delete(o.maxImportDepth),a.size===0&&s.delete(o.targetFile),s.size===0&&i.delete(o.exportName),i.size===0&&t.delete(o.fromFile),n.delete(o))};return{resolve(o,i){let{fromFile:s,exportName:a,targetFile:l,maxImportDepth:c}=o,u=t.get(s)?.get(a)?.get(l)?.get(c);if(u)return u.pending;let d=i();n.size>=e&&r(n.values().next().value);let f={fromFile:s,exportName:a,targetFile:l,maxImportDepth:c,pending:d},m=t.get(s)??new Map,g=m.get(a)??new Map,p=g.get(l)??new Map;return p.set(c,f),g.set(l,p),m.set(a,g),t.set(s,m),n.add(f),d.catch(()=>{r(f)}),d}}}import*as en from"@babel/types";import{posix as tm}from"node:path";function Mi(e,t,n=new Set){if(n.has(e))return;let r=new Set(n).add(e);if(en.isBooleanLiteral(e))return e.value;if(en.isUnaryExpression(e,{operator:"!"})){let c=Mi(e.argument,t,r);return c===void 0?void 0:!c}if(en.isLogicalExpression(e)){let c=Mi(e.left,t,r),u=Mi(e.right,t,r);if(e.operator==="&&")return c===!1||u===!1?!1:c===!0?u:void 0;if(e.operator==="||")return c===!0||u===!0?!0:c===!1?u:void 0}if(!en.isCallExpression(e)||!en.isIdentifier(e.callee))return;let o=t.imports.get(e.callee.name),i=o?.source.startsWith(".")&&t.file?tm.normalize(tm.join(tm.dirname(t.file),o.source)):o?.source;if(o?.importedName==="isProductionBuildPhase"&&/(?:^|\/)lib\/cms\/build-sample(?:\.[jt]s)?$/.test(i??""))return!1;let s=t.functions.get(e.callee.name);if(!s||n.has(s))return;let a=en.isExpression(s.body)?s.body:s.body.body.length===1&&en.isReturnStatement(s.body.body[0])?s.body.body[0].argument:null;if(!a||!en.isExpression(a))return;let l=s.params.flatMap(c=>en.isIdentifier(c)?[c.name]:[]);return Mi(a,{file:t.file,imports:new Map([...t.imports].filter(([c])=>!l.includes(c))),functions:new Map([...t.functions].filter(([c])=>!l.includes(c)))},r.add(s))}var BG=typeof nm=="function"?nm:nm.default,ME=new WeakMap;function BE(e){let t=new Map;return ME.set(t,new Map([...e].map(n=>[n.file,n]))),t}var _D={maxFunctionDepth:8,maxImportDepth:6},CD=new Set(["src","href","alt","poster","content","title","aria-label"]),RE=new WeakMap;function RD(e,t,n){let r=RE.get(t.fileCache);r||(r=new WeakMap,RE.set(t.fileCache,r));let o=r.get(e);if(!o){o={imported:[],local:new Map};let u=0;for(let d of e.elements.values()){let f={element:d,order:u++};d.importedFrom&&d.exportName&&o.imported.push(f);let m=o.local.get(d.sourceFile);m||(m=new Map,o.local.set(d.sourceFile,m));let g=m.get(d.tag)??[];g.push(f),m.set(d.tag,g)}r.set(e,o)}let i=o.local.get(t.file)?.get(n)??[],s=o.imported,a=[],l=0,c=0;for(;l<s.length||c<i.length;){let u=s[l],d=i[c];u&&(!d||u.order<d.order)?(a.push(u.element),l++):d&&(!u||d.order<u.order)?(a.push(d.element),c++):(a.push(u.element),l++,c++)}return a}async function Zl(e){if(!e.element.textSegments.some(s=>s.source||s.value.includes("("))&&!(e.element.attributes??[]).some(s=>(s.source||s.syntaxKind==="expression"&&s.resolution?.status!=="resolved")&&NE(s,e.element))&&!e.graph.regions.some(s=>s.ownerKey===e.element.identity.key&&(s.kind==="repeat-region"||s.kind==="conditional-region")))return{hasDynamicData:!1,bindings:[]};let t=e.fileCache??new Map,n=cm(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{..._D,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,paramArguments:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:nI(n,e.element.componentName),scopeFunction:lm(n,e.element.componentName)};await jE(e.element.componentName,e.graph,r);let o=[];o.push(...await wD(e.element,e.graph,r),...await TD(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await OD(s,e.element,e.graph,r);a&&o.push(...Gl(a,"text","children"))}for(let s of e.element.attributes??[]){let a=NE(s,e.element);if(!a)continue;let l=await VE(s.source,e.element,e.graph,r);if(!l&&s.syntaxKind==="expression"&&!(s.source&&Qo(s.source.base,e.element,e.graph))){let u=n.jsxElementsByRange.get(ql(e.element.sourceRange))?.openingElement.attributes.find(d=>k.isJSXAttribute(d)&&k.isJSXIdentifier(d.name,{name:s.name}));k.isJSXExpressionContainer(u?.value)&&k.isExpression(u.value.expression)&&!JE(u.value.expression,e.element,e.graph)&&(l=await xt(u.value.expression,r))}l&&o.push(...Gl(l,a,s.name))}let i=XD(o).sort(eI);return{hasDynamicData:i.length>0,bindings:i}}async function jE(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 c of RD(t,n,e)){if(c.sourceFile===n.file&&c.tag===e){s.push(c);continue}!c.importedFrom||!c.exportName||c.importedFrom===n.file&&c.exportName!==i||(c.importedFrom===n.file||await PD(c.importedFrom,c.exportName,n.file,n))&&s.push(c)}if(s.length===0)return;let a=new Map;for(let c of s){let u=`${n.file}#${e}<-${c.identity.key}`;if(!n.resolvingComponentProps.has(u)){n.resolvingComponentProps.add(u);try{let d=await UE(c.sourceFile,n);if(!d)continue;let f=xo(d,n,{importDepth:n.importDepth+1});f.paramSources.clear(),f.scopeVariables=nI(d,c.componentName),f.scopeFunction=lm(d,c.componentName),f.lexicalContext=void 0,await jE(c.componentName,t,f);let m=await ND(c,t,f);for(let[g,p]of m){if(!p)continue;let h=a.get(g)??[];h.push(p),a.set(g,h)}}finally{n.resolvingComponentProps.delete(u)}}}let l=new Map;for(let[c,u]of a){let d=tu(u),f=d.length===1?d[0]:am(d,n.file);f&&l.set(c,f)}AD(o,l,n)}var PE=new WeakMap;function PD(e,t,n,r){let o=PE.get(r.fileCache);return o||(o=CE(),PE.set(r.fileCache,o)),o.resolve({fromFile:e,exportName:t,targetFile:n,maxImportDepth:r.options.maxImportDepth},()=>$E(e,t,n,r))}async function $E(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 UE(e,r))?.imports.get(t);if(!s||!_t(s.source))return!1;let a=await dm(e,s.source,r.exists);return a?a===n?!0:$E(a,s.importedName,n,r,o):!1}async function ND(e,t,n){let r=new Map,o=n.analysis.jsxElementsByRange.get(ql(e.sourceRange));if(o)for(let s of o.openingElement.attributes)!k.isJSXAttribute(s)||!k.isJSXIdentifier(s.name)||!k.isJSXExpressionContainer(s.value)||!k.isExpression(s.value.expression)||r.set(s.name.name,s.value.expression);let i=new Map;for(let[s,a]of r){let l=e.attributes?.find(d=>d.name===s)?.source??null,u=(l?Qo(l.base,e,t):null)?await Ql(l,e,t,n):JE(a,e,t)?null:await xt(a,n);u&&i.set(s,u)}return i}function ql(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}async function UE(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 cm(e,r,t.fileCache)}function AD(e,t,n){if(k.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,Ui(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,Wt(o))}}function NE(e,t){return e.name==="dangerouslySetInnerHTML"?"richtext":CD.has(e.name)?"attribute":t.importedFrom||/^[A-Z]/.test(t.tag)?"component-prop":null}async function wD(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 eu(i.collectionSource,n);s&&r.push(...Gl(Ur(s),"repeat-region",i.collectionExpression))}return r}async function TD(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 eu(i.conditionSource,n);s&&r.push(...Gl(Ur(s),"conditional-region",i.conditionExpression))}return r}async function OD(e,t,n,r){if(!e.source){let i=r.analysis.jsxElementsByRange.get(ql(t.sourceRange))?.children.find(s=>k.isJSXExpressionContainer(s)&&s.loc?.start.line===e.sourceRange.startLine&&s.loc.start.column===e.sourceRange.startColumn&&s.loc.end.line===e.sourceRange.endLine&&s.loc.end.column===e.sourceRange.endColumn);return k.isJSXExpressionContainer(i)&&k.isCallExpression(i.expression)&&Vl(i.expression)?KE(i.expression,t,n,r):null}return VE(e.source,t,n,r)}async function VE(e,t,n,r){return e&&Qo(e.base,t,n)?Ql(e,t,n,r):eu(e,r)}async function Ql(e,t,n,r,o){if(!e)return null;let i=Qo(e.base,t,n,o);if(!i||i.candidate.itemParamName!==e.base)return null;let s=i.candidate.collectionSource,l=(s?Qo(s.base,t,n,i.region):null)?await Ql(s,t,n,r,i.region):s?await eu(s,r):await LD(i.candidate.collectionExpression,t,n,r,i.region);return l?$i(l,e.path,!0):null}async function LD(e,t,n,r,o){let i;try{i=kD(e,{plugins:["typescript","jsx"]})}catch{return null}return KE(i,t,n,r,o)}async function KE(e,t,n,r,o){let i=xo(r.analysis,r),s=new Set;k.traverseFast(e,a=>{k.isIdentifier(a)&&s.add(a.name)});for(let a of s){let l=Qo(a,t,n,o);if(!l)continue;if(l.candidate.itemParamName!==a)return null;let c=await Ql({kind:"identifier",expression:a,base:a,path:[]},t,n,r,o);if(!c)return null;i.paramSources.set(a,c)}return xt(e,i)}function Qo(e,t,n,r){let o=t.identity.key,i=null;for(;o;){for(let s of n.regions){if(s.kind!=="repeat-region"||!s.childKeys.includes(o)||r&&!AE(s.sourceRange,r.sourceRange))continue;let a=s.sourceCandidates?.find(l=>l.kind==="repeat-template"&&(l.itemParamName===e||l.indexParamName===e));a&&(!i||AE(i.region.sourceRange,s.sourceRange))&&(i={candidate:a,region:s})}o=n.elements.get(o)?.parentKey??null}return i}function AE(e,t){let n=e.startLine-t.startLine||e.startColumn-t.startColumn,r=e.endLine-t.endLine||e.endColumn-t.endColumn;return n<=0&&r>=0&&(n<0||r>0)}function JE(e,t,n){let r=!1;return k.traverseFast(e,o=>{!r&&k.isIdentifier(o)&&Qo(o.name,t,n)&&(r=!0)}),r}async function eu(e,t){if(!e)return null;let n=await im(e.base,t);return n?$i(n,e.path,!1):null}async function im(e,t){let n=t.paramSources.get(e);if(n)return Wt(n);if(t.variableCache.has(e))return zD(t.variableCache.get(e)??null);let r=yo(e,t);if(r&&r!==t)return im(e,r);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let o=await DD(e,t);if(o)return t.variableCache.set(e,Wt(o)),t.resolvingVariables.delete(e),o;let i=t.scopeVariables?.has(e),s=i?t.scopeVariables.get(e):r?null:t.analysis.variables.get(e);if(s){let l=k.isArrayExpression(s)&&s.elements.length===0?await FD(e,t):await xt(s,t);return t.variableCache.set(e,l?Wt(l):null),t.resolvingVariables.delete(e),l}if(i||r)return t.resolvingVariables.delete(e),t.variableCache.set(e,null),null;let a=t.analysis.imports.get(e);if(a&&t.importDepth<t.options.maxImportDepth){let l=await um(a,t);if(l){let c=xo(l,t,{importDepth:t.importDepth+1}),u=rI(a,l);if(u){let m=(await Zo(u,[],c)).returnSource;return t.variableCache.set(e,m?Wt(m):null),t.resolvingVariables.delete(e),m}let d=l.variables.get(a.importedName);if(d){let f=await xt(d,c);return t.variableCache.set(e,f?Wt(f):null),t.resolvingVariables.delete(e),f}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}function yo(e,t){return t.scopeVariables?.has(e)||t.scopeFunction?.params.some(n=>ho(n).includes(e))?t:t.lexicalContext?yo(e,t.lexicalContext):void 0}function Jl(e,t,n=new Set){if(k.isIdentifier(e)){let s=yo(e.name,t);if(s&&s!==t)return Jl(e,s,n)}if(n.has(e))return null;if(n.add(e),k.isStringLiteral(e))return e.value;if(!k.isIdentifier(e))return null;let r=yo(e.name,t),o=t.paramArguments.get(e.name);if(o)return Jl(o.expression,o.context,n);let i=t.scopeVariables?.has(e.name)?t.scopeVariables.get(e.name):r?null:t.analysis.variables.get(e.name);return i?Jl(i,t,n):null}function Ir(e,t,n=new Set){if(n.has(e))return null;let r=new Set(n).add(e);if(k.isStringLiteral(e))return e.value;if(k.isNumericLiteral(e))return String(e.value);if(k.isIdentifier(e)){if(/token|secret|password|authorization|cookie|credential/i.test(e.name))return":redacted";let o=yo(e.name,t),i=o??t,s=i.paramArguments.get(e.name),a=i.scopeVariables?.has(e.name)?i.scopeVariables.get(e.name):o?null:i.analysis.variables.get(e.name);return(s?Ir(s.expression,s.context,r):a?Ir(a,i,r):null)??`:${e.name}`}if(k.isBinaryExpression(e,{operator:"+"})){let o=Ir(e.left,t,r),i=Ir(e.right,t,r);return o!==null&&i!==null?o+i:null}if(k.isTemplateLiteral(e)){let o=e.quasis[0]?.value.cooked??"";for(let[i,s]of e.expressions.entries()){if(!k.isExpression(s))return null;o+=(Ir(s,t,r)??":param")+(e.quasis[i+1]?.value.cooked??"")}return o}if(k.isCallExpression(e)&&k.isIdentifier(e.callee)&&["encodeURIComponent","decodeURIComponent"].includes(e.callee.name)&&k.isExpression(e.arguments[0])){let o=Ir(e.arguments[0],t,r);if(o===null||o.startsWith(":"))return o;try{return e.callee.name==="encodeURIComponent"?encodeURIComponent(o):decodeURIComponent(o)}catch{return null}}return k.isTSAsExpression(e)||k.isTSNonNullExpression(e)||k.isParenthesizedExpression(e)?Ir(e.expression,t,r):null}async function FD(e,t){let n=t.scopeFunction;if(!n)return null;let r=[],o=!1,i=0,s=u=>{let d=!1;return k.traverseFast(u,f=>{k.isIdentifier(f,{name:e})&&(d=!0)}),d},a=u=>{let d=u;for(;k.isMemberExpression(d);)d=d.object;return k.isIdentifier(d,{name:e})},l=async(u,d)=>{if(!o){if(k.isFunction(u)){s(u)&&(o=!0);return}if(k.isVariableDeclarator(u)&&(ho(u.id).includes(e)&&i++,u.init&&s(u.init)&&(o=!0)),(k.isAssignmentExpression(u)||k.isUpdateExpression(u))&&a(k.isAssignmentExpression(u)?u.left:u.argument)){o=!0;return}if(k.isUnaryExpression(u,{operator:"delete"})&&a(u.argument)){o=!0;return}if(k.isCallExpression(u)){if(k.isMemberExpression(u.callee)&&k.isIdentifier(u.callee.object,{name:e})){if(!k.isIdentifier(u.callee.property,{name:"push"})||u.callee.computed||!u.arguments.length){o=!0;return}for(let f of u.arguments){let m=k.isSpreadElement(f)?f.argument:f,g=k.isExpression(m)?await xt(m,d):null;g?r.push(Hl(g)):o=!0}return}if(u.arguments.some(f=>s(f))){o=!0;return}}if(k.isForOfStatement(u)){let f=await xt(u.right,d),m=xo(d.analysis,d),g=k.isVariableDeclaration(u.left)?u.left.declarations[0]?.id:u.left;f&&g&&Wl(g,Hl(f),m),await l(u.body,m);return}for(let f of k.VISITOR_KEYS[u.type]??[]){let m=u[f];for(let g of Array.isArray(m)?m:[m])k.isNode(g)&&await l(g,d)}}};await l(n.body,t);let c=tu(r);return!o&&i===1&&c.length===1?Ur(c[0]):null}async function DD(e,t){let n=t.analysis.stateSetters.get(e);if(!n)return null;let r=t.analysis.stateSetterCandidates.get(n)??[];for(let o of r){let i=await xt(o,t);if(i)return i}return null}async function xt(e,t){if(k.isIdentifier(e))return im(e.name,t);if(k.isMemberExpression(e)||k.isOptionalMemberExpression(e)){let n=k.isMemberExpression(e)?_E(e,{file:t.file}):null;if(n)return qE(n);let r=await MD(e,t);if(!r)return null;let o=JD(e);return $i(r,o,!1)}if(k.isAwaitExpression(e))return k.isExpression(e.argument)?xt(e.argument,t):null;if((k.isCallExpression(e)||k.isOptionalCallExpression(e))&&(k.isMemberExpression(e.callee)||k.isOptionalMemberExpression(e.callee))&&!e.callee.computed&&k.isIdentifier(e.callee.property)&&["trim","trimStart","trimEnd"].includes(e.callee.property.name)&&e.arguments.length===0&&k.isExpression(e.callee.object))return qo(await xt(e.callee.object,t));if(k.isCallExpression(e))return zE(e,t);if(k.isObjectExpression(e)){let n=await HE(e,t);return Object.keys(n).length>0?Ui(n,t.file):null}if(k.isArrayExpression(e)){let n={};for(let[r,o]of e.elements.entries()){if(!k.isExpression(o))continue;let i=await xt(o,t);i&&(n[String(r)]=i)}return Object.keys(n).length?Ui(n,t.file):null}if(k.isConditionalExpression(e)){let n=await xt(e.consequent,t),r=await xt(e.alternate,t);return qo(om(n,r))}if(k.isLogicalExpression(e)){let n=await xt(e.left,t),r=await xt(e.right,t);return qo(om(n,r))}return k.isTSAsExpression(e)||k.isTSSatisfiesExpression(e)||k.isTSNonNullExpression(e)||k.isTypeCastExpression(e)||k.isParenthesizedExpression(e)?xt(e.expression,t):null}async function MD(e,t){let n=e;for(;k.isMemberExpression(n)||k.isOptionalMemberExpression(n);)n=n.object;return k.isExpression(n)?xt(n,t):null}async function XE(e,t,n=0){if(n>=t.options.maxFunctionDepth)return null;let r=yo(e,t);if(r){if(r.scopeFunction&&Er(r.scopeFunction,e))return null;let s=r.paramArguments.get(e);return s&&k.isIdentifier(s.expression)?XE(s.expression.name,s.context,n+1):null}let o=t.analysis.imports.get(e);if(!o||!["cms","collections","cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(o.importedName)||Er(t.analysis.ast,e))return null;let i=await dm(t.file,o.source,t.exists);return i?{...o,source:i}:null}async function zE(e,t){let n=e.arguments[0],r=k.isExpression(n)?Jl(n,t):null,i=On(e.callee)?.split(".")[0],s=i?await XE(i,t):null,a=r!==null&&!k.isStringLiteral(n)?{...e,arguments:[k.stringLiteral(r),...e.arguments.slice(1)]}:e;if(s&&["cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(s.importedName)&&k.isObjectExpression(n)){let x=WE(n,"path"),b=x&&Ir(x,t);b?.startsWith("/")&&(a={...e,arguments:[{...n,properties:n.properties.map(S=>k.isObjectProperty(S)&&ei(S)==="path"?{...S,value:k.stringLiteral(Yo(b))}:S)},...e.arguments.slice(1)]})}let l=jr(a,{file:t.file,imports:i&&s?new Map([[i,s]]):new Map});if(l){if(s&&["cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(s.importedName)&&l.endpointPattern==="/content/by-url"&&k.isObjectExpression(n)){let x=wE(n,"query"),b=k.isObjectExpression(x)?wE(x,"path"):null,S=b&&Ir(b,t),E=S&&Kl(S);E&&(l.collection=E,l.evidence.push({file:t.file,reason:"CMS collection namespace from the actual content request path"}))}if(k.isMemberExpression(e.callee)){let x=await $r(e.callee,t);if(x&&!Xl(x.node))return null;if(x&&Xl(x.node)){let b=await rm(e,t,{node:x.node,context:x.context});return b&&{...b,...b.sourceKind===l.sourceKind?{operation:l.operation}:{}}}}if((l.operation==="getByUrl"||l.operation==="getByUrlStrict")&&k.isExpression(n)){let x=Ir(n,t);x?.startsWith("/")&&(l.endpointPattern=Yo(x))}return qE(l)}if(On(e.callee)==="Promise.all"&&k.isArrayExpression(n))return xt(n,t);if(Vl(e)){if(!Vl(e,{file:t.file,imports:i&&s?new Map([[i,s]]):new Map})||!k.isExpression(e.callee))return null;let x=await $r(e.callee,t);if(x)return Xl(x.node)?rm(e,t,{node:x.node,context:x.context}):null;let b=e.arguments[0];if(b&&k.isExpression(b))return qo(await xt(b,t))}let c=await BD(e,t);if(c)return c;let u=IE(e,{file:t.file});if(u)return{sourceKind:u.sourceKind,sourceType:"api-field",endpointPattern:u.endpointPattern,valuePath:u.valuePath,confidence:u.confidence,readonly:!0,evidence:u.evidence};let d=await $D(e,t);if(d)return d;let f=await UD(e,t);if(f)return f;let m=await VD(e,t);if(m)return m;let g=await rm(e,t);if(g)return g;let p=[];for(let x of e.arguments)if(k.isExpression(x)){let b=await xt(x,t);b&&p.push(b)}let h=tu(p);return h.length===1?qo(h[0]):null}async function BD(e,t){let n=On(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=jD(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(k.isIdentifier(s)){let a=await ji(s.name,t);if(a)return(await Zo(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!k.isObjectExpression(r))return ma(t.file,`${n} without static options`);let o=WE(r,"queryFn");if(!o)return ma(t.file,`${n} without queryFn`);if(k.isIdentifier(o)){let i=await ji(o.name,t);return i?(await Zo(i.node,[],i.context)).returnSource:ma(t.file,`${n} queryFn unresolved`)}return k.isArrowFunctionExpression(o)||k.isFunctionExpression(o)?(await Zo(o,[],t)).returnSource:k.isCallExpression(o)?zE(o,t):null}function WE(e,t){for(let n of e.properties){if(!k.isObjectProperty(n)||!k.isExpression(n.value))continue;if(ei(n)===t)return n.value}return null}function wE(e,t){let n=new Set;for(let i of e.properties){if(!k.isObjectProperty(i)||i.computed)return null;let s=ei(i);if(!s||n.has(s))return null;n.add(s)}let r=e.properties.filter(i=>k.isObjectProperty(i)&&ei(i)===t);if(r.length!==1)return null;let o=r[0];return k.isObjectProperty(o)&&k.isExpression(o.value)?o.value:null}function jD(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 $D(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","reverse","toReversed"].includes(n))return null;let r=k.isExpression(e.callee.object)?await xt(e.callee.object,t):null;if(!r)return null;if(n!=="map")return Ur(r);let o=e.arguments[0];if(r.cmsCallerSources){let i=await Promise.all(r.cmsCallerSources.map(s=>TE(o,s,t)));return am(i,t.file)}return TE(o,r,t)}async function TE(e,t,n){if(k.isIdentifier(e)){let r=await ji(e.name,n);if(!r)return Ur(t);let o=await Zo(r.node,[t],r.context);return{...Ur(t),...o.objectReturnMap??o.returnSource?.fieldMap?{fieldMap:o.objectReturnMap??o.returnSource.fieldMap}:{}}}if(k.isArrowFunctionExpression(e)||k.isFunctionExpression(e)){let r=await Zo(e,[t],n);return{...Ur(t),...r.objectReturnMap??r.returnSource?.fieldMap?{fieldMap:r.objectReturnMap??r.returnSource.fieldMap}:{}}}return Ur(t)}async function UD(e,t){return!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property,{name:"json"})||!k.isExpression(e.callee.object)?null:xt(e.callee.object,t)}async function VD(e,t){return!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property,{name:"then"})||!k.isExpression(e.callee.object)?null:qo(await xt(e.callee.object,t))}async function rm(e,t,n){let r=n;if(!r&&k.isIdentifier(e.callee))r=await ji(e.callee.name,t)??void 0;else if(!r&&k.isMemberExpression(e.callee)){let s=await $r(e.callee,t);s&&Xl(s.node)&&(r={node:s.node,context:s.context})}if(!r)return null;let o=[];for(let s of e.arguments){if(!k.isExpression(s)){o.push(ma(t.file,`unsupported argument for ${On(e.callee)??"call"}`));continue}let a=await xt(s,t);o.push(a)}return(await Zo(r.node,o,r.context,{arguments:e.arguments,context:t})).returnSource}function Xl(e){return k.isFunctionDeclaration(e)||Yl(e)||k.isObjectMethod(e)&&e.kind==="method"}async function $r(e,t,n=new Set){let r={node:null,context:t};if(n.has(e)||n.size>=32)return r;let o=new Set(n).add(e);if(k.isTSAsExpression(e)||k.isTSSatisfiesExpression(e)||k.isTSNonNullExpression(e))return $r(e.expression,t,o);if(k.isIdentifier(e)){let i=yo(e.name,t),s=i??t;if(Er(i?.scopeFunction??t.analysis.ast,e.name))return r;let a=s.paramArguments.get(e.name);if(a)return $r(a.expression,a.context,o);let l=i?i.scopeVariables?.get(e.name):s.analysis.variables.get(e.name);if(l)return $r(l,s,o);if(i)return null;let c=s.analysis.functions.get(e.name);if(c)return{node:c,context:s};let u=s.analysis.imports.get(e.name);if(!u||s.importDepth>=s.options.maxImportDepth)return null;let d=await um(u,s);return d?$r(k.identifier(u.importedName),xo(d,s,{importDepth:s.importDepth+1}),o):null}if(k.isMemberExpression(e)&&k.isExpression(e.object)){let i=e.computed?k.isStringLiteral(e.property)?e.property.value:null:k.isIdentifier(e.property)?e.property.name:null;if(!i)return null;let s=await $r(e.object,t,o);if(!s)return null;if(!k.isObjectExpression(s.node))return{node:null,context:s.context};if(s.node.properties.some(c=>k.isSpreadElement(c)||c.computed))return{node:null,context:s.context};let a=s.node.properties.filter(c=>(k.isObjectMethod(c)||k.isObjectProperty(c))&&(k.isIdentifier(c.key)?c.key.name:k.isStringLiteral(c.key)?c.key.value:null)===i);if(a.length===0)return null;if(a.length!==1)return{node:null,context:s.context};let l=a[0];return k.isObjectMethod(l)?l.kind==="method"?{node:l,context:s.context}:null:k.isObjectProperty(l)&&k.isExpression(l.value)?$r(l.value,s.context,o):null}return{node:e,context:t}}async function ji(e,t,n=new Set){let r=t.paramArguments.get(e);if(r&&!n.has(r.expression)){if(n.add(r.expression),Yl(r.expression))return{node:r.expression,context:r.context};if(k.isIdentifier(r.expression))return ji(r.expression.name,r.context,n)}let o=t.analysis.functions.get(e);if(o)return{node:o,context:t};let i=t.analysis.imports.get(e);if(!i||t.importDepth>=t.options.maxImportDepth)return null;let s=await um(i,t);if(!s)return null;let a=xo(s,t,{importDepth:t.importDepth+1}),l=rI(i,s);return l?{node:l,context:a}:ji(i.importedName,a)}async function Zo(e,t,n,r){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let o=xo(n.analysis,n,{functionDepth:n.functionDepth+1}),i=n.analysis.functionParents.get(e),s=n;for(;s&&(s.analysis!==n.analysis||s.scopeFunction!==i);)s=s.lexicalContext;o.lexicalContext=s,o.paramSources=new Map,o.paramArguments=new Map,o.scopeVariables=n.analysis.functionVariables.get(e),o.scopeFunction=e,e.params.forEach((f,m)=>{for(let x of ho(f))o.paramSources.delete(x),o.paramArguments.delete(x);let g=k.isAssignmentPattern(f)?f.left:f,p=r?.arguments[m];k.isIdentifier(g)&&k.isExpression(p)&&r&&o.paramArguments.set(g.name,{expression:p,context:r.context});let h=t[m];h&&Wl(f,Hl(h),o)});let a=KD(e,o),l=a.map(YE).filter(f=>!ZE(f));if(a.length>1&&l.length>0&&l.every(f=>k.isObjectExpression(f))){let f=await GE(l,o);return{returnSource:Ui(f,n.file),objectReturnMap:f}}let c=null,u,d=!1;for(let f of a){let m=xo(n.analysis,o);if(k.isObjectExpression(f)){u={...u??{},...await HE(f,m)},c=c??Ui(u,n.file);continue}let g=await xt(f,m);if(g){if(!c){c=g;continue}let p=sm(c,g);if(!p){d=!0,c=null;continue}c=p}}return{returnSource:d?null:c,...u?{objectReturnMap:u}:{}}}function Wl(e,t,n){if(k.isIdentifier(e)){n.paramSources.set(e.name,Wt(t));return}if(k.isAssignmentPattern(e)){Wl(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=$i(t,[{kind:"property",name:r.key.name}],!0),i=k.isAssignmentPattern(r.value)?r.value.left:r.value;o&&Wl(i,o,n)}}function KD(e,t){if(k.isArrowFunctionExpression(e)&&k.isExpression(e.body))return[e.body];let n=[],r=e.body;if(!k.isBlockStatement(r))return n;let o=i=>{if(k.isFunction(i)&&i!==e)return;if(k.isReturnStatement(i)){i.argument&&k.isExpression(i.argument)&&n.push(i.argument);return}if(k.isIfStatement(i)){let a=Mi(i.test,{file:t.file,imports:new Map([...t.analysis.imports].filter(([l])=>!yo(l,t))),functions:t.analysis.functions});if(a!==void 0){a?o(i.consequent):i.alternate&&o(i.alternate);return}}let s=k.VISITOR_KEYS[i.type];for(let a of s??[]){let l=i[a];if(Array.isArray(l))for(let c of l)k.isNode(c)&&o(c);else k.isNode(l)&&o(l)}};return o(r),n}async function HE(e,t){let n={};for(let r of e.properties){if(!k.isObjectProperty(r))continue;let o=ei(r);if(!o||!k.isExpression(r.value))continue;let i=await xt(r.value,t);i&&(n[o]=i)}return n}async function GE(e,t){let n=[];for(let i of e){let s=new Map,a=!1;for(let l of i.properties){if(k.isObjectProperty(l)&&k.isExpression(l.value)){let c=ei(l);if(c!==null){s.set(c,YE(l.value));continue}}s.clear(),a=!0}n.push({properties:s,hasUnknownKeys:a})}let r=new Map,o=new Set(n.flatMap(({properties:i})=>[...i.keys()]));for(let i of o){if(n.some(({properties:l,hasUnknownKeys:c})=>c&&!l.has(i)))continue;let s=n.flatMap(({properties:l})=>{let c=l.get(i);return c&&!ZE(c)?[c]:[]});if(s.length===0)continue;if(s.every(l=>k.isObjectExpression(l))){let l=await GE(s,t);Object.keys(l).length&&r.set(i,Ui(l,t.file));continue}let a=null;for(let l of s){let c=await xt(l,t);if(a=c&&om(a,c),!a)break}a&&r.set(i,a)}return Object.fromEntries(r)}function YE(e){for(;k.isTSAsExpression(e)||k.isTSSatisfiesExpression(e)||k.isTSNonNullExpression(e)||k.isParenthesizedExpression(e);)e=e.expression;return e}function ZE(e){return k.isNullLiteral(e)||k.isArrayExpression(e)&&e.elements.length===0}function ei(e){return k.isIdentifier(e.key)&&!e.computed?e.key.name:k.isStringLiteral(e.key)?e.key.value:null}function JD(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 $i(e,t,n){if(t.length===0)return Wt(e);if(e.cmsCallerSources){let s=e.cmsCallerSources.map(a=>$i(a,t,n));return s.every(a=>a!==null)?am(s,e.evidence[0].file):null}let r=t[0],o=r?.kind==="property"?r.name:r?String(r.index):null;if(e.fieldMap&&o!==null){let s=e.fieldMap[o];return s?$i(s,t.slice(1),n):null}let i=Wt(e);if(i.sourceType==="cms-field"){let s=t.filter(l=>l.kind==="property").map(l=>l.name);if(s[0]==="data"&&s[1]==="items")return i.valuePath=Bi(i.valuePath,"data.items[]"),i.cmsFieldRoot=!1,i;let a=s[0]==="fields"?0:s[0]==="data"&&s[1]==="fields"?1:-1;return a>=0?(a===1&&(i.valuePath=Bi(i.valuePath,"data")),i.fieldPath=Bi(i.fieldPath,s.slice(a+1).join(".")),i.cmsFieldRoot=!0,i):i.cmsFieldRoot||n||i.fieldMap?(i.fieldPath=Bi(i.fieldPath,s.join(".")),i):(i.valuePath=Bi(i.valuePath,OE(t)),i)}return i.valuePath=Bi(i.valuePath,OE(t)),i}function OE(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function Bi(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function qE(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 Ur(e){let t=Wt(e);return t.cmsCallerSources=t.cmsCallerSources?.map(Ur),t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function Hl(e){let t=Wt(e);return t.cmsCallerSources=t.cmsCallerSources?.map(Hl),t.valuePath=void 0,t.sourceType==="cms-field"&&!t.fieldPath&&(t.cmsFieldRoot=!1),t}function qo(e){return e?{...Wt(e),...e.cmsCallerSources?{cmsCallerSources:e.cmsCallerSources.map(t=>qo(t))}:{},confidence:e.confidence==="unknown"?"unknown":"safe-derived",evidence:[...e.evidence,{file:e.evidence[0]?.file??"unknown",reason:"safe derived expression"}]}:null}function om(e,t){return e?t?sm(e,t):Wt(e):t?Wt(t):null}function sm(e,t){if(ga(e)!==ga(t))return null;let n=tI(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function tu(e){let t=new Map;for(let n of e){let r=ga(n),o=t.get(r);t.set(r,o?sm(o,n):Wt(n))}return[...t.values()]}function am(e,t){let n=tu(e.flatMap(r=>r.cmsCallerSources??[r]));return n.length===0||n.length>16||n.some(r=>r.sourceKind!=="vcp-cms-collection"||!r.collection||!["exact","safe-derived"].includes(r.confidence))?null:{...ma(t,"competing component callers"),cmsCallerSources:n}}function ga(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,ga(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,cmsCallerSources:e.cmsCallerSources?.map(ga).sort(),fieldMap:t})}function Ui(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 ma(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function LE(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 Gl(e,t,n){return e.cmsCallerSources?e.cmsCallerSources.map(r=>{let o=LE(r,t,n);return o.evidence.push({file:e.evidence[0].file,reason:"CMS shared component caller"}),o}):[LE(e,t,n)]}function QE(e){let t=[...e].sort(eI),n=t.filter(i=>!i.evidence.some(({reason:s})=>s==="CMS shared component caller")),r=n[0],o=[...new Set(n.flatMap(i=>i.sourceKind==="vcp-cms-collection"&&i.collection?[i.collection]:[]))];return{hasDynamicData:t.length>0,sourceKinds:[...new Set(t.map(i=>i.sourceKind))],...o.length>0?{collections:o}:{},...r?.endpointPattern?{primaryEndpoint:r.endpointPattern}:{},...r?.collection?{primaryCollection:r.collection}:{},...r?.fieldPath?{primaryFieldPath:r.fieldPath}:{}}}function XD(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 eI(e,t){return FE(e.targetKind)-FE(t.targetKind)||tI(e.confidence,t.confidence)||DE(e.sourceKind)-DE(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function FE(e){return{"repeat-region":0,"conditional-region":1,text:2,richtext:3,attribute:4,"component-prop":5}[e]}function DE(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function tI(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function cm(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=ME.get(n)?.get(e),i=o?.source===t?o.ast:vD(t,{sourceType:"module",plugins:["jsx","typescript"]}),s={file:e,source:t,ast:i,variables:new Map,functions:new Map,imports:new Map,stateSetters:new Map,stateSetterCandidates:new Map,jsxElementsByRange:new Map,functionVariables:new WeakMap,functionParents:new WeakMap},a=[],l=[];k.traverse(i,{enter(d){switch(k.isFunction(d)&&(s.functionParents.set(d,a.at(-1)??null),a.push(d)),d.type){case"CallExpression":l.push(d);break;case"JSXElement":{let f=d.loc;if(!f)return;let m=ql({startLine:f.start.line,startColumn:f.start.column,endLine:f.end.line,endColumn:f.end.column});s.jsxElementsByRange.has(m)||s.jsxElementsByRange.set(m,d);break}case"ImportDeclaration":{let f=d.source.value;for(let m of d.specifiers)k.isImportSpecifier(m)&&k.isIdentifier(m.local)?s.imports.set(m.local.name,{source:f,importedName:k.isIdentifier(m.imported)?m.imported.name:m.imported.value,localName:m.local.name,isDefault:!1}):k.isImportDefaultSpecifier(m)&&s.imports.set(m.local.name,{source:f,importedName:"default",localName:m.local.name,isDefault:!0});break}case"FunctionDeclaration":{d.id?.name&&s.functions.set(d.id.name,d);break}case"VariableDeclarator":{let f=a.at(-1),m=f&&(k.isFunctionDeclaration(f)||k.isFunctionExpression(f)||k.isArrowFunctionExpression(f)||k.isObjectMethod(f))?f:null,g=m?s.functionVariables.get(m)??new Map:s.variables;m&&!s.functionVariables.has(m)&&s.functionVariables.set(m,g);for(let[p,h]of zl(d.id,k.isExpression(d.init)?d.init:null))g.set(p,h);if(k.isArrayPattern(d.id)&&k.isCallExpression(d.init)&&On(d.init.callee)==="useState"){let[p,h]=d.id.elements;k.isIdentifier(p)&&k.isIdentifier(h)&&s.stateSetters.set(p.name,h.name)}k.isIdentifier(d.id)&&Yl(d.init)&&s.functions.set(d.id.name,d.init);break}case"ExportNamedDeclaration":{let f=d.declaration,m=d.source?.value;if(m)for(let g of d.specifiers){if(!k.isExportSpecifier(g))continue;let p=k.isIdentifier(g.exported)?g.exported.name:g.exported.value,h=g.local.name;s.imports.set(p,{source:m,importedName:h,localName:p,isDefault:h==="default"})}if(k.isFunctionDeclaration(f)&&f.id?.name&&s.functions.set(f.id.name,f),k.isVariableDeclaration(f))for(let g of f.declarations)k.isIdentifier(g.id)&&Yl(g.init)&&s.functions.set(g.id.name,g.init);break}case"ExportDefaultDeclaration":{let f=d.declaration;if((k.isFunctionDeclaration(f)||k.isFunctionExpression(f)||k.isArrowFunctionExpression(f))&&s.functions.set("default",f),k.isIdentifier(f)){let m=s.functions.get(f.name);m&&s.functions.set("default",m)}break}}},exit(d){k.isFunction(d)&&a.pop()}});let c=new Set(s.stateSetters.values()),u=(d,f)=>{let m=s.stateSetterCandidates.get(d)??[];m.push(f),s.stateSetterCandidates.set(d,m)};if(c.size>0)for(let d of l){let f=k.isIdentifier(d.callee)?d.callee.name:null;f&&c.has(f)&&k.isExpression(d.arguments[0])&&u(f,d.arguments[0]);let m=new Set;for(let g of d.arguments)k.isIdentifier(g)&&g.name!==f&&c.has(g.name)&&m.add(g.name);for(let g of m)u(g,d)}return n.set(e,s),s}function zl(e,t){return k.isIdentifier(e)?[[e.name,t]]:k.isAssignmentPattern(e)?zl(e.left,t):k.isArrayPattern(e)?e.elements.flatMap((n,r)=>n&&!k.isRestElement(n)?zl(n,t?k.memberExpression(t,k.numericLiteral(r),!0):null):[]):k.isObjectPattern(e)?e.properties.flatMap(n=>{if(!k.isObjectProperty(n)||n.computed)return[];let r=ei(n);return r?zl(n.value,t?k.memberExpression(t,k.stringLiteral(r),!0):null):[]}):[]}function ho(e){return!e||k.isVoidPattern(e)?[]:k.isIdentifier(e)?[e.name]:k.isObjectPattern(e)?e.properties.flatMap(t=>k.isObjectProperty(t)?ho(t.value):ho(t.argument)):k.isArrayPattern(e)?e.elements.flatMap(t=>t?ho(k.isRestElement(t)?t.argument:t):[]):k.isAssignmentPattern(e)?ho(e.left):k.isRestElement(e)?ho(e.argument):[]}function Yl(e){return k.isFunctionExpression(e)||k.isArrowFunctionExpression(e)}function nI(e,t){let n=lm(e,t);return n?e.functionVariables.get(n):void 0}function lm(e,t){return e.functions.get(t)??e.functions.get("default")}async function um(e,t){let n=await dm(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return cm(n,r,t.fileCache)}function rI(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function dm(e,t,n){return _t(t)?No(e,t,n):null}function xo(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),paramArguments:e===t.analysis?new Map(t.paramArguments):new Map,resolvingVariables:new Set,resolvingComponentProps:t.resolvingComponentProps,scopeVariables:e===t.analysis?t.scopeVariables:void 0,scopeFunction:e===t.analysis?t.scopeFunction:void 0,lexicalContext:e===t.analysis?t.lexicalContext:void 0}}function zD(e){return e?Wt(e):null}function Wt(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.cmsCallerSources?{cmsCallerSources:e.cmsCallerSources.map(Wt)}:{},...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,Wt(n)]))}:{}}}import*as hm from"@babel/parser";import gm from"@babel/traverse";import*as Se from"@babel/types";import{classifySiteEditPropertyName as WD}from"@vcp-dev/platform-shared/contracts";import*as lI from"@babel/parser";import fm from"@babel/traverse";import*as Te from"@babel/types";function ru(e,t){let n=[],r=e;for(;Te.isMemberExpression(r);){if(r.computed)if(Te.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(Te.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!Te.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!Te.isIdentifier(r)||r.name!==t?null:n}function oI(e){if(Te.isIdentifier(e))return{base:e.name,path:[]};if(!Te.isMemberExpression(e))return null;let t=[],n=e;for(;Te.isMemberExpression(n);){if(n.computed)if(Te.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(Te.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!Te.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return Te.isIdentifier(n)?{base:n.name,path:t}:null}function tn(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}var vr=Symbol("not-closed-literal");function nu(e){switch(e.type){case"StringLiteral":case"NumericLiteral":case"BooleanLiteral":return e.value;case"NullLiteral":return null;case"TemplateLiteral":return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:vr;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":return nu(e.expression);case"ArrayExpression":{let t=[];for(let n of e.elements){if(!n||Te.isSpreadElement(n))return vr;let r=nu(n);if(r===vr)return vr;t.push(r)}return t}case"ObjectExpression":{let t={};for(let n of e.properties){if(!Te.isObjectProperty(n)||n.computed||n.shorthand||!Te.isExpression(n.value))return vr;let r=Te.isIdentifier(n.key)?n.key.name:Te.isStringLiteral(n.key)?n.key.value:null;if(!r)return vr;let o=nu(n.value);if(o===vr)return vr;t[r]=o}return t}default:return vr}}function iI(e){let{resolveBindingTarget:t}=e;async function n(i,s,a,l,c,u,d){let f=nu(i);if(f!==vr)return f;if(!Te.isTemplateLiteral(i)){if(Te.isTSAsExpression(i)||Te.isTSSatisfiesExpression(i)||Te.isTSNonNullExpression(i))return await n(i.expression,s,a,l,c,u,d);if(Te.isIdentifier(i)){let m=s.getBinding(i.name);if(!m)return;let g=await t({currentFile:a,binding:m,readFile:l,exists:c,fileCache:u,visited:d});return g?.kind==="static"?g.value:void 0}if(Te.isArrayExpression(i)){let m=[];for(let g of i.elements){if(!g||Te.isSpreadElement(g))return;let p=await r(g,s,a,l,c,u,d);if(p===void 0)return;m.push(p)}return m}if(Te.isObjectExpression(i)){let m={};for(let g of i.properties){if(!Te.isObjectProperty(g)||g.computed)return;let p=null;if(Te.isIdentifier(g.key)?p=g.key.name:Te.isStringLiteral(g.key)&&(p=g.key.value),!p)return;if(g.shorthand){if(!Te.isIdentifier(g.value))return;let x=await r(g.value,s,a,l,c,u,d);if(x===void 0)return;m[p]=x;continue}if(!Te.isExpression(g.value))return;let h=await r(g.value,s,a,l,c,u,d);h!==void 0&&(m[p]=h)}return m}if(Te.isMemberExpression(i)){let m=await o(i,s,a,l,c,u,d);if(!m)return;let g=s.getBinding(m.base);if(!g)return;let p=await t({currentFile:a,binding:g,readFile:l,exists:c,fileCache:u,visited:d});return!p||p.kind!=="static"?void 0:tn(p.value,m.path)}}}async function r(i,s,a,l,c,u,d){if(!Te.isSpreadElement(i))return await n(i,s,a,l,c,u,d)}async function o(i,s,a,l,c,u,d){if(Te.isIdentifier(i))return{base:i.name,path:[]};if(!Te.isMemberExpression(i))return null;let f=[],m=i;for(;Te.isMemberExpression(m);){if(m.computed){let g=m.property;if(Te.isNumericLiteral(g))f.unshift({kind:"index",index:g.value});else if(Te.isStringLiteral(g))f.unshift({kind:"property",name:g.value});else{let p=Te.isExpression(g)?await n(g,s,a,l,c,u,d):void 0;if(typeof p=="string")f.unshift({kind:"property",name:p});else if(Number.isInteger(p))f.unshift({kind:"index",index:p});else return null}}else{if(!Te.isIdentifier(m.property))return null;f.unshift({kind:"property",name:m.property.name})}m=m.object}return Te.isIdentifier(m)?{base:m.name,path:f}:null}return{normalizeExpressionWithScope:o,evaluateStaticExpression:n}}var uI=typeof fm=="function"?fm:fm.default,sI=new WeakMap;function dI(e){try{return lI.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function ou(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=dI(n);return e.set(t,{source:n,ast:o}),o}function iu(e,t){return pm(ha(e).expressionRanges,t,!1)}function fI(e,t){return ha(e).exactExpressions.get(pI(t))??null}function su(e,t){return pm(ha(e).jsxRanges,t,!0)}function ha(e){let t=sI.get(e);if(t)return t;let n={expressions:[],expressionRanges:[],jsxRanges:[],exactExpressions:new Map};return uI(e,{Expression(r){let o=r;n.expressions.push(o);let i=aI(o,n.expressions.length-1);if(!i)return;n.expressionRanges.push(i);let s=pI(i.range),a=n.exactExpressions.get(s);(!a||i.span<=(a.node.end??0)-(a.node.start??0))&&n.exactExpressions.set(s,o)},JSXElement(r){let o=aI(r,n.jsxRanges.length);o&&n.jsxRanges.push(o)}}),n.expressionRanges.sort(cI),n.jsxRanges.sort(cI),sI.set(e,n),n}function aI(e,t){let n=ya(e.node);return n?{path:e,range:n,traversalIndex:t,span:(e.node.end??0)-(e.node.start??0)}:null}function pI(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}function cI(e,t){return e.range.startLine-t.range.startLine||e.range.startColumn-t.range.startColumn||e.traversalIndex-t.traversalIndex}function pm(e,t,n,r){let o=0,i=e.length;for(;o<i;){let l=o+Math.floor((i-o)/2),c=e[l].range;c.startLine<t.startLine||c.startLine===t.startLine&&c.startColumn<t.startColumn?o=l+1:i=l}let s=null,a=n?1/0:-1;for(let l=o;l<e.length;l++){let c=e[l],u=c.range;if(u.startLine>t.endLine||u.startLine===t.endLine&&u.startColumn>t.endColumn)break;if(u.endLine>t.endLine||u.endLine===t.endLine&&u.endColumn>t.endColumn||r&&!r(c.path))continue;((n?c.span<a:c.span>a)||c.span===a&&(!s||c.traversalIndex>s.traversalIndex))&&(s=c,a=c.span)}return s?.path??null}function ya(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 Vi(e,t){if(t)return mm(e,t);let n=oI(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function mm(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function xa(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of ha(e).expressions){if(mm(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function mI(e,t,n,r){return pm(ha(e).expressionRanges,r,!0,o=>mm(o.node,t)===n)}function Ki(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function Ji(e){let t=null;if(uI(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}async function or(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=dI(o),s={source:o,ast:i};return n.set(e,s),s}var ym=typeof gm=="function"?gm:gm.default;function xm(e){let t=WD(e.propertyName);if(t.owner!=="generic")return Sn("invalid-property",t.diagnostic?.message??`Property '${e.propertyName}' is not a generic property`);let n=e.selectionRef;if(!n)return Sn("missing-selection-ref","A repeat property target requires a complete selection reference");if(n.key!==e.element.identity.key)return Sn("selection-mismatch","Selection reference does not identify the requested element");if(n.instanceIndex===void 0)return Sn("missing-instance-index","A repeat property target requires an instance index");let r;try{r=hm.parse(e.source,{sourceType:"module",plugins:["typescript","jsx"]})}catch(h){return Sn("repeat-not-found",`Unable to parse repeat source: ${h instanceof Error?h.message:String(h)}`)}let o=HD(r,e.element.sourceRange);if(!o)return Sn("repeat-not-found","The selected element is not inside a supported map repeat");if(o.binding&&co(o.binding))return Sn("unsafe-collection","The repeat source is mutated outside the mapped expression");if(!Se.isIdentifier(o.callback.params[0]))return Sn("unsupported-callback","Repeat property materialization requires an identifier callback item");let i=GD(r,o.collection,e.file,e.sources);if(!i)return Sn("collection-not-found","The repeat collection is not a visible local static array");let{array:s,locator:a,sourceFile:l}=i,c=[],u=[];for(let[h,x]of s.elements.entries()){if(!x||!Se.isObjectExpression(x)||!SI(x))return Sn("unsafe-collection","Repeat materialization requires an array of local static objects without spreads");let b=[{kind:"index",index:h}];c.push(b),u.push({kind:"value",root:a.root,path:b})}let d=u.length;if(n.instanceCount!==void 0&&n.instanceCount!==d)return Sn("count-mismatch",`Selection reports ${n.instanceCount} instances but the source collection has ${d}`);let f=n.instanceIndex;if(f>=d)return Sn("index-out-of-range",`Selected repeat instance ${f} is outside the source collection`);let m=s.elements[f];if(!m||!Se.isObjectExpression(m))return Sn("unsafe-collection","Selected repeat item is not an object");let g=tM(e.element,e.propertyName),p=QD(m,e.propertyName);return p?{ok:!0,sourceFile:l,templateFile:e.file,collectionLocator:a,parentObjectLocators:u,selectedParentObjectLocator:u[f],sourceItemIndex:f,sourceItemPath:c[f],collectionIndexMap:Array.from({length:d},(h,x)=>x),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:p,selectedResolution:eM(m,e.propertyName),...g?{property:g}:{},selectionRef:n}:Sn("unsafe-property-source",`Property '${e.propertyName}' has a dynamic or unsupported source in the repeat item`)}function HD(e,t){let n=[];return ym(e,{CallExpression(r){let o=gI(r);o&&yI(o.callback,t)&&n.push({...o,span:hI(r.node)})},OptionalCallExpression(r){let o=gI(r);o&&yI(o.callback,t)&&n.push({...o,span:hI(r.node)})}}),n.sort((r,o)=>r.span-o.span),n[0]??null}function gI(e){let{node:t}=e,n=t.callee;if(!Se.isMemberExpression(n)&&!Se.isOptionalMemberExpression(n)||n.computed||!Se.isIdentifier(n.property)||n.property.name!=="map"||!Se.isExpression(n.object))return null;let r=t.arguments[0];return!r||!Se.isExpression(r)||!Se.isArrowFunctionExpression(r)&&!Se.isFunctionExpression(r)?null:{collection:n.object,callback:r,binding:Se.isIdentifier(n.object)?e.scope.getBinding(n.object.name):void 0}}function GD(e,t,n,r){let o=ba(t);if(o&&Se.isArrayExpression(o))return{array:o,locator:{kind:"value",root:{kind:"expression",sourceRange:II(o)}},sourceFile:n};if(!Se.isIdentifier(t))return null;let i=[];if(ym(e,{VariableDeclarator(s){Se.isIdentifier(s.node.id)&&s.node.id.name===t.name&&s.node.init&&i.push(s.node)}}),i.length===1){let s=ba(i[0].init);return!s||!Se.isArrayExpression(s)?null:{array:s,locator:{kind:"value",root:{kind:"binding",name:t.name}},sourceFile:n}}return YD(e,t.name,n,r)}function YD(e,t,n,r){if(!r)return null;for(let o of e.program.body){if(!Se.isImportDeclaration(o))continue;let i=o.specifiers.find(m=>m.local.name===t);if(!i||!Se.isStringLiteral(o.source)||!Se.isImportSpecifier(i))continue;let s=qD(n,o.source.value,r);if(!s)return null;let a=Se.isIdentifier(i.imported)?i.imported.name:i.imported.value,l=r.get(s);if(l===void 0)return null;let c;try{c=hm.parse(l,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}let u=Ji(c).getBinding(a);if(u&&co(u))return null;let d=ZD(c,a),f=d?ba(d):null;return!f||!Se.isArrayExpression(f)?null:{array:f,locator:{kind:"value",root:{kind:"binding",name:a}},sourceFile:s}}return null}function ZD(e,t){let n=null;return ym(e,{VariableDeclarator(r){n||!Se.isIdentifier(r.node.id)||r.node.id.name!==t||!r.node.init||!Se.isExpression(r.node.init)||(n=r.node.init)}}),n}function qD(e,t,n){let r=ar(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 ba(e){return Se.isParenthesizedExpression(e)?ba(e.expression):Se.isTSAsExpression(e)?bI(e.typeAnnotation)?ba(e.expression):null:Se.isTSSatisfiesExpression(e)?null:e}function bI(e){return Se.isTSTypeReference(e)&&Se.isIdentifier(e.typeName)&&e.typeName.name==="const"}function SI(e){return e.properties.every(t=>!Se.isObjectProperty(t)||t.computed||!Se.isExpression(t.value)?!1:au(t.value))}function au(e){if(Se.isTSAsExpression(e)&&bI(e.typeAnnotation))return au(e.expression);if(Se.isTSSatisfiesExpression(e))return!1;if(Se.isArrayExpression(e))return e.elements.every(n=>!n||Se.isSpreadElement(n)||!Se.isExpression(n)?!1:au(n));if(Se.isObjectExpression(e))return SI(e);let t=fr(e);return t.status==="resolved"||t.status==="undefined"}function QD(e,t){let n=e.properties.filter(o=>Se.isObjectProperty(o)&&EI(o.key)===t);if(n.length>1)return null;let r=n[0];return r?Se.isExpression(r.value)?au(r.value)?"static":Se.isIdentifier(r.value)||Se.isMemberExpression(r.value)?"binding":null:null:"missing"}function eM(e,t){let n=e.properties.filter(o=>Se.isObjectProperty(o)&&EI(o.key)===t);if(n.length>1)return{status:"unresolved"};let r=n[0];return!r||!Se.isExpression(r.value)?{status:"undefined"}:fr(r.value)}function tM(e,t){let n=e.attributes?.filter(r=>r.name===t)??[];return n.length===1?n[0]:void 0}function EI(e){return Se.isIdentifier(e)?e.name:Se.isStringLiteral(e)?e.value:Se.isNumericLiteral(e)?String(e.value):null}function II(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 hI(e){return e.start==null||e.end==null?Number.MAX_SAFE_INTEGER:e.end-e.start}function yI(e,t){let n=II(e);return xI(n.startLine,n.startColumn,t.startLine,t.startColumn)<=0&&xI(n.endLine,n.endColumn,t.endLine,t.endColumn)>=0}function xI(e,t,n,r){return e===n?t-r:e-n}function Sn(e,t){return{ok:!1,errorCode:e,reason:t}}import{classifySiteEditPropertyName as jM}from"@vcp-dev/platform-shared/contracts";import*as _e from"@babel/types";import Sa from"node:path";import*as ae from"@babel/types";function nM(e){return ae.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:ae.isMemberExpression(e.callee)&&ae.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function rM(e){if(!ae.isNewExpression(e)||!ae.isIdentifier(e.callee,{name:"Proxy"})||e.arguments.length!==2||!ae.isIdentifier(e.arguments[0])||!ae.isObjectExpression(e.arguments[1])||e.arguments[1].properties.length!==1)return null;let[t]=e.arguments[1].properties;if(!ae.isObjectMethod(t)||t.kind!=="method"||t.computed||t.async||t.generator||!ae.isIdentifier(t.key,{name:"get"})||t.params.length!==3||!t.params.every(ae.isIdentifier)||t.body.body.length!==2)return null;let[n,r,o]=t.params,[i,s]=t.body.body;if(ae.isIfStatement(i)&&ae.isBlockStatement(i.consequent)&&i.consequent.body.length!==1)return null;let a=ae.isIfStatement(i)?i.test:null,l=a&&ae.isLogicalExpression(a,{operator:"&&"})?a.right:null,c=ae.isIfStatement(i)?ae.isBlockStatement(i.consequent)?i.consequent.body[0]:i.consequent:null,u=ae.isReturnStatement(s)?s.argument:null;return!a||!ae.isLogicalExpression(a,{operator:"&&"})||!ae.isBinaryExpression(a.left,{operator:"==="})||!ae.isUnaryExpression(a.left.left,{operator:"typeof"})||!ae.isIdentifier(a.left.left.argument,{name:r.name})||!ae.isStringLiteral(a.left.right,{value:"string"})||!ae.isUnaryExpression(l,{operator:"!"})||!ae.isBinaryExpression(l.argument,{operator:"in"})||!ae.isIdentifier(l.argument.left,{name:r.name})||!ae.isIdentifier(l.argument.right,{name:n.name})||!ae.isReturnStatement(c)||!ae.isIfStatement(i)||i.alternate||!ae.isCallExpression(u)||!ae.isMemberExpression(u.callee)||!ae.isIdentifier(u.callee.object,{name:"Reflect"})||!ae.isIdentifier(u.callee.property,{name:"get"})||u.arguments.length!==3||!ae.isIdentifier(u.arguments[0],{name:n.name})||!ae.isIdentifier(u.arguments[1],{name:r.name})||!ae.isIdentifier(u.arguments[2],{name:o.name})?null:e.arguments[0].name}function oM(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()||!ae.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 vI(e,t){let n=oM(e.path);if(!n)return null;let r=Pi(e,t);return r?{...n,...r}:null}function kI(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}function bm(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"}}function Sm(e,t){for(let n of e.program.body){if(t==="default"&&ae.isExportDefaultDeclaration(n))return ae.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:(ae.isFunctionDeclaration(n.declaration)||ae.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if(ae.isExportNamedDeclaration(n)){if(n.declaration){if(ae.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if(ae.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if((ae.isFunctionDeclaration(n.declaration)||ae.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if((ae.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&ae.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}function _I(e){let{resolveExternalExpression:t,resolveCollectionCallTarget:n,evaluateStaticExpression:r,resolveSourceInfoProvenance:o,buildExpressionSourceInfo:i}=e;async function s(p){let{currentFile:h,binding:x,readFile:b,exists:S,fileCache:E,visited:v}=p,N=`${h}::${x.kind}::${x.identifier.name}`;if(v.has(N))return null;v.add(N);try{let I=await a({currentFile:h,binding:x,readFile:b,exists:S,fileCache:E,visited:v});if(I)return I;if(x.path.isImportSpecifier()||x.path.isImportDefaultSpecifier())return await m({currentFile:h,binding:x,readFile:b,exists:S,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,fileCache:E,visited:v});if(x.kind==="param")return null;if(x.path.isVariableDeclarator()){let A=x.path.node.init;if(!A||!ae.isExpression(A))return null;let C=rM(A);if(C&&!x.path.scope.getBinding("Proxy")&&!x.path.scope.getBinding("Reflect")){let X=x.path.scope.getBinding(C),j=X?await s({...p,binding:X}):null;if(j?.kind==="static"&&j.value!==null&&!Array.isArray(j.value)&&typeof j.value=="object")return j}let O=x.path.get("init");if(O&&!Array.isArray(O)&&O.isExpression()){let X=await t({currentFile:h,expressionPath:O,readFile:b,exists:S,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:E,visited:v});if(X)return X;if(O.isCallExpression()){let j=await n({currentFile:h,callPath:O,readFile:b,exists:S,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:E,visited:v});if(j)return j}}let L=await r(A,x.path.scope,h,b,S,E,v);return L===void 0?null:{kind:"static",file:h,root:{kind:"binding",name:x.identifier.name},value:L,sourceKind:"binding"}}if(x.path.isIdentifier()&&x.path.parentPath?.isExportDefaultDeclaration()){let A=x.path.parentPath.node.declaration;if(!ae.isExpression(A))return null;let C=await r(A,x.path.scope,h,b,S,E,v);return C===void 0?null:{kind:"static",file:h,root:{kind:"binding",name:x.identifier.name},value:C,sourceKind:"binding"}}return null}finally{v.delete(N)}}async function a(p){let{currentFile:h,binding:x,readFile:b,exists:S,fileCache:E,visited:v}=p;if(!x.path.isVariableDeclarator()||!x.path.get("id").isArrayPattern())return null;let N=x.path,I=N.node.init;if(!I||!ae.isCallExpression(I))return null;let A=nM(I);if(!A||!ae.isArrayPattern(N.node.id)||N.node.id.elements.findIndex(j=>ae.isIdentifier(j)&&j.name===x.identifier.name)!==0)return null;let O=A==="useReducer"?1:0,L=I.arguments[O];if(!L||!ae.isExpression(L))return null;let X=await r(L,N.scope,h,b,S,E,v);return X===void 0?null:{kind:"static",file:h,root:{kind:"hook-state",name:x.identifier.name,hook:A},value:X,sourceKind:"binding"}}async function l(p){let h=p.expressionPath.scope.getBinding(p.sourceInfo.base);if(!h||!h.constant||h.kind!=="param"||!p.graph)return null;let x=vI(h,p.sourceInfo);if(!x)return null;let b=[...p.graph.elements.values()].filter(E=>kI(E,p.currentFile,x.componentName,x.exportName));if(!b.length)return null;let S=[];for(let E of b){if(E.sourceFile!==b[0].sourceFile||E.componentName!==b[0].componentName||E.attributeSpreads?.length)return null;let v=await or(E.sourceFile,p.readFile,p.fileCache),N=v.ast?su(v.ast,E.sourceRange):null;if(!N)return null;let I=N.parentPath;for(;I&&!I.isFunction();){if(I.isJSXElement()){let J=I.node.openingElement.name;if(!ae.isJSXIdentifier(J)||!/^[a-z]/.test(J.name))return null}else if(!I.isJSXFragment()&&!I.isReturnStatement()&&!I.isBlockStatement())return null;I=I.parentPath}if(!I)return null;let A=N.get("openingElement").get("attributes").filter(J=>J.isJSXAttribute()&&ae.isJSXIdentifier(J.node.name,{name:x.propName}));if(A.length!==1)return null;let C=A[0];if(!C?.isJSXAttribute())return null;let O=C.get("value"),L=O.isJSXExpressionContainer()?O.get("expression"):O;if(!L.isExpression())return null;let X=await r(L.node,L.scope,E.sourceFile,p.readFile,p.exists,p.fileCache,p.visited),j=X===void 0?void 0:tn(X,x.remainingPath);if(j===void 0)return null;S.push(j)}return S}async function c(p){let h=vI(p.binding,p.sourceInfo);if(!h||!p.graph)return null;let x=["component-prop",p.currentFile,p.binding.identifier.start??p.binding.path.node.start??-1,h.componentName,h.propName].join(":");if(p.visited.has(x))return null;p.visited.add(x);try{return await u(p,h,p.graph)}finally{p.visited.delete(x)}}async function u(p,h,x){let b=[...x.elements.values()].filter(C=>kI(C,p.currentFile,h.componentName,h.exportName));if(b.length!==1)return null;let S=b[0],E=S.attributes?.find(C=>C.name===h.propName);if(E&&!E.source){let C=await d({caller:S,propName:h.propName,remainingPath:h.remainingPath,readFile:p.readFile,fileCache:p.fileCache});if(C)return bm(C,{componentName:h.componentName,propName:h.propName,file:S.sourceFile})}if(!E?.source){let C=await f({caller:S,propName:h.propName,remainingPath:h.remainingPath,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited});if(C)return bm(C,{componentName:h.componentName,propName:h.propName,file:S.sourceFile});let O=SS(p.binding,h.componentName,h.propName);if(!O||O.propName!==h.propName)return null;let L=await r(O.expressionPath.node,O.expressionPath.scope,p.currentFile,p.readFile,p.exists,p.fileCache,p.visited);if(L===void 0)return null;let X=h.remainingPath;return X.length>0&&tn(L,X)===void 0?null:{kind:"value",file:p.currentFile,root:{kind:"binding",name:h.propName},path:X,sourceKind:"binding",semanticKind:"component-prop",displayExpression:O.displayPath,chainPrefix:[{kind:"component-prop",file:p.currentFile,displayName:O.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let v=await or(S.sourceFile,p.readFile,p.fileCache);if(!v.ast)return null;let N=mI(v.ast,v.source,E.source.expression,E.sourceRange)??xa(v.ast,v.source,E.source.expression);if(!N)return null;let I={...E.source,expression:Ki(E.source.expression,h.remainingPath),path:[...E.source.path,...h.remainingPath]},A=await o({currentFile:S.sourceFile,expressionPath:N,sourceInfo:I,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited});return A?bm(A.kind==="external"?A:{...A,displayExpression:I.expression},{componentName:h.componentName,propName:h.propName,file:S.sourceFile}):null}async function d(p){let h=await or(p.caller.sourceFile,p.readFile,p.fileCache);if(!h.ast)return null;let x=su(h.ast,p.caller.sourceRange);if(!x)return null;let b=x.get("openingElement").get("attributes").find(N=>N.isJSXAttribute()&&N.node.name.type==="JSXIdentifier"&&N.node.name.name===p.propName);if(!b?.isJSXAttribute())return null;let S=b.get("value"),E=S.isStringLiteral()?S:S.isJSXExpressionContainer()?S.get("expression"):null;if(!E?.isExpression())return null;let v=ya(E.node);return v?{kind:"value",file:p.caller.sourceFile,root:{kind:"expression",sourceRange:v},path:p.remainingPath,sourceKind:"binding",semanticKind:"component-prop",displayExpression:p.propName,editMode:"upstream",diagnostics:[]}:null}async function f(p){let h=await or(p.caller.sourceFile,p.readFile,p.fileCache);if(!h.ast)return null;let x=su(h.ast,p.caller.sourceRange);if(!x)return null;let b=x.get("openingElement");for(let S of b.get("attributes")){if(!S.isJSXSpreadAttribute())continue;let E=S.get("argument");if(!E.isExpression())continue;let v=await i({expression:E.node,scope:E.scope,source:h.source,currentFile:p.caller.sourceFile,readFile:p.readFile,exists:p.exists,fileCache:p.fileCache,visited:p.visited});if(!v)continue;let N=[{kind:"property",name:p.propName},...p.remainingPath],I={...v,expression:Ki(v.expression,N),path:[...v.path,...N]},A=await o({currentFile:p.caller.sourceFile,expressionPath:E,sourceInfo:I,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited});if(A)return A.kind==="external"?A:{...A,displayExpression:I.expression}}return null}async function m(p){let{currentFile:h,binding:x,readFile:b,exists:S,fileCache:E,visited:v}=p,N=x.path.parentPath;if(!N||!N.isImportDeclaration())return null;let I=N.node.source.value;if(typeof I!="string")return null;let A=await No(h,I,S);if(!A)return null;if(x.path.isImportDefaultSpecifier()){let J=await or(A,b,E),Y=J.ast?Sm(J.ast,"default"):null,$=await g({file:A,exportName:"default",readFile:b,exists:S,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:E,visited:v});return!$||$.kind!=="static"?null:{kind:"static",file:Y?.kind==="default-expression"?$.file:A,root:Y?.kind==="default-expression"?$.root:{kind:"default-export"},value:$.value,sourceKind:"imported-binding"}}if(!x.path.isImportSpecifier())return null;let C=x.path.node.imported,O=ae.isIdentifier(C)?C.name:C.value,L=await or(A,b,E),X=L.ast?Sm(L.ast,O):null,j=await g({file:A,exportName:O,readFile:b,exists:S,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:E,visited:v});return j?j.kind==="external"?j:{kind:"static",file:X?.kind==="re-export"?j.file:A,root:X?.kind==="re-export"||j.root.kind==="binding"&&j.root.name!==X?.name?j.root:{kind:"named-export",name:O},value:j.value,sourceKind:"imported-binding"}:null}async function g(p){let{file:h,exportName:x,readFile:b,exists:S,fileCache:E,visited:v}=p,N=`export::${h}::${x}`;if(!v.has(N)){v.add(N);try{let I=await or(h,b,E);if(!I.ast)return;let A=Sm(I.ast,x);if(!A)return;if(A.kind==="re-export"){if(!A.source||!A.name)return;let X=await No(h,A.source,S);return X?g({...p,file:X,exportName:A.name}):void 0}let C=A.kind==="default-expression"?ae.isIdentifier(A.expression)?A.expression.name:void 0:A.name;if(!C)return;let O=Ji(I.ast).getBinding(C);if(!O)return;let L=await s({currentFile:h,binding:O,readFile:b,exists:S,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:E,visited:v});return L?.kind==="static"&&Array.isArray(L.value)&&co(O)?void 0:L??void 0}finally{v.delete(N)}}}return{resolveExportValue:g,resolveComponentPropBinding:c,resolveComponentPropValues:l,resolveBindingTarget:s}}import*as xe from"@babel/types";function Im(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=nr(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!iM(s,r)?null:{callPath:s,basePath:i}}function iM(e,t){let n=e.node.callee;return!xe.isMemberExpression(n)||!xe.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}function NI(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:Rl(r,t)}function CI(e,t){return e?xe.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}function RI(e,t,n,r,o){let i=xe.isExpression(e.body)?e.body:e.body.body.find(a=>xe.isReturnStatement(a))?.argument;if(!i||!xe.isExpression(i))return;let s=Em(i,t,n,r,o);return typeof s=="number"?s:void 0}function Em(e,t,n,r,o){if(xe.isNumericLiteral(e)||xe.isStringLiteral(e)||xe.isBooleanLiteral(e))return e.value;if(xe.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(xe.isMemberExpression(e)){let i=ru(e,t);if(i)return tn(r,i);let s=ru(e,n);return s?tn(o,s):void 0}if(xe.isBinaryExpression(e)&&e.operator==="-"){let i=xe.isExpression(e.left)?Em(e.left,t,n,r,o):void 0,s=xe.isExpression(e.right)?Em(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function sM(e){if(xe.isExpression(e.body))return e.body;for(let t of e.body.body)if(xe.isReturnStatement(t)&&t.argument&&xe.isExpression(t.argument))return t.argument;return null}function aM(e,t,n){let r=ti(e,t,n);return typeof r=="boolean"?r:void 0}function ti(e,t,n){if(xe.isStringLiteral(e)||xe.isNumericLiteral(e)||xe.isBooleanLiteral(e))return e.value;if(xe.isNullLiteral(e))return null;if(xe.isIdentifier(e))return e.name===t?n:void 0;if(xe.isMemberExpression(e)){let r=ru(e,t);return r?tn(n,r):void 0}if(xe.isUnaryExpression(e)&&e.operator==="!"){let r=ti(e.argument,t,n);return r===void 0?void 0:!r}if(xe.isLogicalExpression(e)){let r=ti(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&ti(e.right,t,n);if(e.operator==="||")return r||ti(e.right,t,n)}if(xe.isBinaryExpression(e)){let r=xe.isExpression(e.left)?ti(e.left,t,n):void 0,o=xe.isExpression(e.right)?ti(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 AI(e){let t=[],n=e;for(;xe.isMemberExpression(n)||xe.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(xe.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(xe.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(xe.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(xe.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return xe.isIdentifier(n)?{base:n.name,segments:t}:null}function wI(e){return e.some(t=>t.kind==="dynamic")}function PI(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}function TI(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 cM(e,t){let n=[],r=[];for(let o of t){let i=tn(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}}function OI(e){let{resolveBindingTarget:t,evaluateStaticExpression:n,buildExpressionSourceInfo:r,resolveSourceInfoProvenance:o,resolveComponentPropValues:i}=e;async function s(g){let{currentFile:p,callPath:h,readFile:x,exists:b,fileCache:S,visited:E}=g,v=h.node.callee;if(!xe.isMemberExpression(v)||!xe.isIdentifier(v.property)||v.property.name!=="map")return null;let N=h.get("callee");if(!N.isMemberExpression())return null;let I=N.get("object");if(Array.isArray(I)||!I.isExpression())return null;let A=await a({currentFile:p,expressionPath:I,readFile:x,exists:b,graph:g.graph,externalSourceResolvers:g.externalSourceResolvers,externalAdapters:g.externalAdapters,functionCallContracts:g.functionCallContracts,fileCache:S,visited:E});return!A||!Array.isArray(A.value)||A.value.length===0?null:A}async function a(g){let{currentFile:p,expressionPath:h,readFile:x,exists:b,fileCache:S,visited:E}=g;if(h.isIdentifier()){let v=h.scope.getBinding(h.node.name);if(!v||co(v,h.node))return null;let N=await t({currentFile:p,binding:v,readFile:x,exists:b,graph:g.graph,externalSourceResolvers:g.externalSourceResolvers,externalAdapters:g.externalAdapters,functionCallContracts:g.functionCallContracts,fileCache:S,visited:E});return N?.kind==="static"?N:null}if(h.isCallExpression())return c({currentFile:p,callPath:h,readFile:x,exists:b,graph:g.graph,externalSourceResolvers:g.externalSourceResolvers,externalAdapters:g.externalAdapters,functionCallContracts:g.functionCallContracts,fileCache:S,visited:E});if(h.isTSAsExpression()||h.isTSSatisfiesExpression()||h.isTSNonNullExpression()){let v=h.get("expression");if(!Array.isArray(v)&&v.isExpression())return a({...g,expressionPath:v})}if(h.isArrayExpression()){let v=ya(h.node);if(!v)return null;let N=await n(h.node,h.scope,p,x,b,S,E);return Array.isArray(N)?{kind:"static",file:p,root:{kind:"expression",sourceRange:v},value:N,sourceKind:"binding"}:null}if(h.isMemberExpression()){let v=await r({expression:h.node,scope:h.scope,currentFile:p,readFile:x,exists:b,fileCache:S,visited:E});if(!v)return null;let N=await o({currentFile:p,expressionPath:h,sourceInfo:v,readFile:x,exists:b,graph:g.graph,externalSourceResolvers:g.externalSourceResolvers,externalAdapters:g.externalAdapters,functionCallContracts:g.functionCallContracts,fileCache:S,visited:E});if(!N||N.kind==="external")return null;let I=await l({currentFile:p,expressionPath:h,provenance:N,readFile:x,exists:b,graph:g.graph,externalSourceResolvers:g.externalSourceResolvers,externalAdapters:g.externalAdapters,functionCallContracts:g.functionCallContracts,fileCache:S,visited:E});if(!I||I.kind!=="static")return null;if(N.collectionPathMap?.length){let C=cM(I.value,N.collectionPathMap);if(C)return{kind:"static",file:N.file,root:N.root,value:C.value,sourceKind:N.sourceKind,collectionPathMap:C.collectionPathMap}}let A=tn(I.value,N.path);return Array.isArray(A)?{kind:"static",file:N.file,root:N.root,value:A,sourceKind:N.sourceKind,pathPrefix:N.path,collectionIndexMap:N.collectionIndexMap,collectionPathMap:N.collectionPathMap}:null}return null}async function l(g){let{provenance:p}=g;if(p.root.kind==="binding"){let S=g.expressionPath.scope.getBinding(p.root.name);if(!S&&p.file!==g.currentFile){let E=await or(p.file,g.readFile,g.fileCache);S=E.ast?Ji(E.ast).getBinding(p.root.name):void 0}return!S||co(S,g.expressionPath.node)?null:await t({currentFile:p.file,binding:S,readFile:g.readFile,exists:g.exists,graph:g.graph,externalSourceResolvers:g.externalSourceResolvers,externalAdapters:g.externalAdapters,functionCallContracts:g.functionCallContracts,fileCache:g.fileCache,visited:g.visited})}if(p.root.kind!=="expression")return null;let h=await or(p.file,g.readFile,g.fileCache);if(!h.ast)return null;let x=fI(h.ast,p.root.sourceRange);if(!x)return null;let b=await n(x.node,x.scope,p.file,g.readFile,g.exists,g.fileCache,g.visited);return b===void 0?null:{kind:"static",file:p.file,root:p.root,value:b,sourceKind:p.sourceKind}}async function c(g){return await u(g)??await d(g)??await f(g)}async function u(g){let{callPath:p}=g,h=p.node.callee;if(!xe.isMemberExpression(h)||!xe.isIdentifier(h.property)||h.property.name!=="filter")return null;let x=p.get("callee");if(!x.isMemberExpression())return null;let b=x.get("object");if(Array.isArray(b)||!b.isExpression())return null;let S=await a({currentFile:g.currentFile,expressionPath:b,readFile:g.readFile,exists:g.exists,graph:g.graph,externalSourceResolvers:g.externalSourceResolvers,externalAdapters:g.externalAdapters,functionCallContracts:g.functionCallContracts,fileCache:g.fileCache,visited:g.visited});if(!S||!Array.isArray(S.value))return null;let[E]=p.node.arguments;if(!xe.isArrowFunctionExpression(E)&&!xe.isFunctionExpression(E))return null;let v=E.params[0];if(!xe.isIdentifier(v))return null;let N=sM(E);if(!N)return null;let I=[],A=[],C=[];for(let[O,L]of S.value.entries()){let X=aM(N,v.name,L);if(typeof X!="boolean")return null;if(X){I.push(L),A.push(S.collectionIndexMap?.[O]??O);let j=S.collectionPathMap?.[O];j&&C.push(j)}}return{...S,value:I,pathPrefix:S.pathPrefix,collectionIndexMap:A,...C.length>0?{collectionPathMap:C}:{}}}async function d(g){let{callPath:p}=g,h=p.node.callee;if(!xe.isMemberExpression(h)||!xe.isIdentifier(h.property)||h.property.name!=="slice")return null;let x=p.get("callee");if(!x.isMemberExpression())return null;let b=x.get("object");if(Array.isArray(b)||!b.isExpression())return null;let S=await a({currentFile:g.currentFile,expressionPath:b,readFile:g.readFile,exists:g.exists,graph:g.graph,externalSourceResolvers:g.externalSourceResolvers,externalAdapters:g.externalAdapters,functionCallContracts:g.functionCallContracts,fileCache:g.fileCache,visited:g.visited});if(!S||!Array.isArray(S.value))return null;let[E,v]=p.node.arguments,N=CI(E,0),I=CI(v,S.value.length);if(N===null||I===null)return null;let A=Math.max(0,N<0?S.value.length+N:N),C=Math.max(0,I<0?S.value.length+I:I),O=S.value.map((X,j)=>S.collectionIndexMap?.[j]??j).slice(A,C),L=S.collectionPathMap?.slice(A,C);return{...S,value:S.value.slice(A,C),pathPrefix:S.pathPrefix,collectionIndexMap:O,...L?{collectionPathMap:L}:{}}}async function f(g){let{callPath:p}=g,h=p.node.callee;if(!xe.isMemberExpression(h)||!xe.isIdentifier(h.property)||h.property.name!=="sort"&&h.property.name!=="toSorted")return null;let x=p.get("callee");if(!x.isMemberExpression())return null;let b=x.get("object");if(Array.isArray(b)||!b.isExpression())return null;let S=await a({currentFile:g.currentFile,expressionPath:b,readFile:g.readFile,exists:g.exists,graph:g.graph,externalSourceResolvers:g.externalSourceResolvers,externalAdapters:g.externalAdapters,functionCallContracts:g.functionCallContracts,fileCache:g.fileCache,visited:g.visited});if(!S||!Array.isArray(S.value))return null;let[E]=p.node.arguments;if(!xe.isArrowFunctionExpression(E)&&!xe.isFunctionExpression(E))return null;let[v,N]=E.params;if(!xe.isIdentifier(v)||!xe.isIdentifier(N))return null;let I=S.value.map((C,O)=>({value:C,sourceIndex:S.collectionIndexMap?.[O]??O,originalIndex:O})),A=[...I];for(let C of I)for(let O of I)if(RI(E,v.name,N.name,C.value,O.value)===void 0)return null;return A.sort((C,O)=>{let L=RI(E,v.name,N.name,C.value,O.value)??0;return L===0?C.originalIndex-O.originalIndex:L}),{...S,value:A.map(C=>C.value),pathPrefix:S.pathPrefix,collectionIndexMap:A.map(C=>C.sourceIndex),...S.collectionPathMap?{collectionPathMap:A.map(C=>S.collectionPathMap?.[C.originalIndex]).filter(C=>!!C)}:{}}}async function m(g){let p=null,h=!1,x,b=[];for(let E of g.segments){if(E.kind!=="dynamic")continue;let v=await r({expression:E.expression,scope:g.expressionPath.scope,source:g.fileCache.get(g.currentFile)?.source,currentFile:g.currentFile,readFile:g.readFile,exists:g.exists,fileCache:g.fileCache,visited:g.visited});if(!v)return null;let N=Im(g.expressionPath,v.base),I;if(N){h=!0;let A=await s({currentFile:g.currentFile,callPath:N.callPath,readFile:g.readFile,exists:g.exists,graph:g.graph,externalSourceResolvers:g.externalSourceResolvers,externalAdapters:g.externalAdapters,functionCallContracts:g.functionCallContracts,fileCache:g.fileCache,visited:g.visited});if(!A||!Array.isArray(A.value))return null;I=A.value.map((C,O)=>{let L=tn(A.value,[{kind:"index",index:O},...N.basePath,...v.path]);return PI(L)}),x??=A.collectionIndexMap}else{let A=await i({...g,sourceInfo:v});if(!A)return null;I=A.map(PI)}if(I.some(A=>A===null)||p!==null&&p!==I.length)return null;p=I.length,b.push(I)}if(p===null||p===0)return null;let S=[];for(let E=0;E<p;E+=1){let v=[...g.rootPath],N=0;for(let I of g.segments){if(I.kind==="dynamic"){let A=b[N]?.[E];if(!A)return null;v.push(A),N+=1;continue}v.push({...I})}S.push(v)}return{sourceKind:h||p>1?"repeat-template":"binding",...x?{collectionIndexMap:x}:{},collectionPathMap:S}}return{resolveRepeatCollectionTarget:s,resolveCollectionCallTarget:c,resolveDynamicMemberPathMap:m}}var{normalizeExpressionWithScope:lM,evaluateStaticExpression:cu}=iI({resolveBindingTarget:e=>lu(e)}),{resolveRepeatCollectionTarget:uM,resolveCollectionCallTarget:dM,resolveDynamicMemberPathMap:fM}=OI({resolveBindingTarget:e=>lu(e),evaluateStaticExpression:cu,buildExpressionSourceInfo:kr,resolveSourceInfoProvenance:Gn,resolveComponentPropValues:e=>gM(e)}),{resolveExportValue:pM,resolveComponentPropBinding:mM,resolveComponentPropValues:gM,resolveBindingTarget:lu}=_I({resolveExternalExpression:Nm,resolveCollectionCallTarget:dM,evaluateStaticExpression:cu,resolveSourceInfoProvenance:Gn,buildExpressionSourceInfo:kr});function VI(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}var LI=new WeakMap;function hM(e){let t=LI.get(e);return t||(t=new WeakMap,LI.set(e,t)),t}function FI(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 KI(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=ou(s,t,n);if(!a)return null;let l=iu(a,r.sourceRange);if(!l)return null;let c=await kr({expression:l.node,scope:l.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!c){let f=await Om({currentFile:t,expressionPath:l,readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:new Set});return f?_m(f,Vi(l.node,n)):null}let u=new Set,d=await BM({currentFile:t,expressionPath:l,segment:{...r,source:c},readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:u});return d?_m(d,c.expression):null}async function Xi(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=ou(i,t,n);if(!s)return null;let a=e.sourceRange?iu(s,e.sourceRange):e.expression!==void 0?xa(s,n,e.expression):null;if(!a)return null;let l=uu(a);if(!l.isIdentifier()&&!l.isMemberExpression())return null;let c=new Set,u=await kr({expression:l.node,scope:l.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:c}),d=u?await Gn({currentFile:t,expressionPath:l,sourceInfo:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:c}):await ZI({currentFile:t,expressionPath:l,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:c});return _m(d,e.expression??Vi(l.node,n))}async function Pm(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=ou(i,t,n);if(!s)return Ln("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?yM({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}):xM({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}async function kr(e){if(_e.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!_e.isMemberExpression(e.expression))return null;let t=await lM(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:Vi(e.expression,e.source),base:t.base,path:t.path}:null}function _m(e,t){if(!e||e.kind==="value"&&e.editMode==="readonly")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}:{}}}async function yM(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:l}=e,c=iu(r,o.sourceRange),u=c?await kr({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:i,exists:s,fileCache:a,visited:l}):null;if(!u){if(!c||c.isStringLiteral()||c.isTemplateLiteral()&&c.node.expressions.length===0)return DI(t,o.value);let f=await Om({currentFile:t,expressionPath:c,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:l});return f?f.kind==="external"?UI(t,f):Rm(t,Vi(c.node,n),f):bM({expression:c.node,scope:c.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:l,functionCallContracts:e.functionCallContracts})}if(!c)return Ln("unsupported-expression","Unable to locate text expression for provenance resolution");let d=await Gn({currentFile:t,expressionPath:c,sourceInfo:u,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:l});if(!d){let f=Cm(c.node);if(f)return Ln(f.code,f.message);let m=c.scope.getBinding(u.base);if(m?.path.isVariableDeclarator()){let g=Cm(m.path.node.init);if(g)return Ln(g.code,g.message)}return m?.path.isVariableDeclarator()&&_e.isCallExpression(m.path.node.init)?SM("unsupported-expression",HI(m.path.node.init,e.functionCallContracts)):Ln("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return d.kind==="external"?UI(t,d):Rm(t,u.expression,d)}async function xM(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:l}=e;if(!o.conditionSource)return Ln("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let c=xa(r,n,o.conditionExpression);if(!c)return Ln("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await Gn({currentFile:t,expressionPath:c,sourceInfo:o.conditionSource,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:l});if(!u)return Ln("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(u.kind==="external")return Ln("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let d=Rm(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 DI(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 bM(e){let t=await XI(e);if(t.length===0)return Ln("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(EM(e.expression))return JI(t);if(WI(e.expression))return Ln("unsupported-expression","i18n helpers require a static message id string");if(_e.isMemberExpression(e.expression)&&e.expression.computed&&!_e.isNumericLiteral(e.expression.property)&&!_e.isStringLiteral(e.expression.property))return Ln("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return Ln(n.code,n.message)}function Ln(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function SM(e,t){return JI([{code:e,message:t}])}function JI(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function EM(e){return _e.isCallExpression(e)||_e.isConditionalExpression(e)||_e.isLogicalExpression(e)||_e.isBinaryExpression(e)}function Ea(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 XI(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:l}=e,c=Cm(t);if(c)return[c];if(_e.isCallExpression(t))return[{code:"unsupported-expression",message:HI(t,l)}];if(_e.isMemberExpression(t)&&t.computed){let u=t.property;if(!_e.isNumericLiteral(u)&&!_e.isStringLiteral(u)){if(!_e.isExpression(u))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let f=await cu(u,n,r,o,i,s,a);if(typeof f!="string"&&!Number.isInteger(f))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}]}}return _e.isBinaryExpression(t)?Ea([...await vm(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):_e.isLogicalExpression(t)?Ea([...await vm(t.left,t.right,e),{code:"unsupported-expression",message:t.operator==="??"||t.operator==="||"?"Fallback expressions are recognized but remain readonly until a safer composition editing strategy is available":"Complex conditional expressions are recognized but remain readonly until a safer editing strategy is available"}]):_e.isConditionalExpression(t)?Ea([...await vm(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 Cm(e){return WI(e)?MI("i18n helpers require a static message id string"):CM(e)?MI("CMS helpers require static entry id and field path string arguments"):null}async function vm(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await XI({...t,expression:o}));return r}function IM(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:[vM(e.sourceType)]}}async function Nm(e){for(let n of AM){if(!BI(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return $I(jI(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(!BI(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return $I(jI(r),e.externalAdapters)}return null}function vM(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function kM(e){return{code:"external-source-readonly",message:e}}function MI(e){return{code:"unsupported-expression",message:e}}function Am(e){return!e||!_e.isCallExpression(e)?null:_e.isIdentifier(e.callee)?e.callee.name:_e.isMemberExpression(e.callee)&&!e.callee.computed&&_e.isIdentifier(e.callee.object)&&_e.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function BI(e,t){if(!t||t.length===0)return!0;let n=Am(e.node);return n?t.includes(n):!1}function jI(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:Ea(e.diagnostics??[])}:{match:e,diagnostics:[]}}function $I(e,t){let n=IM(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:Ea([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function _M(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!_e.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!_e.isStringLiteral(n)||!_e.isStringLiteral(r))return null;let o=n.value,i=r.value;return{sourceType:"cms-field",sourceId:`${o}:${i}`,file:`cms://${o}/${i.replace(/\./g,"/")}`,displayPath:`${o}.${i}`}}function CM(e){return!!e&&_e.isCallExpression(e)&&_e.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!_e.isStringLiteral(e.arguments[0])||!_e.isStringLiteral(e.arguments[1]))}function zI(e){if(!(!e||!_e.isCallExpression(e))){if(_e.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&_e.isStringLiteral(t)?t.value:null}if(_e.isMemberExpression(e.callee)&&!e.callee.computed&&_e.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&_e.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!_e.isObjectExpression(t))return null;for(let n of t.properties)if(_e.isObjectProperty(n)&&!n.computed&&(_e.isIdentifier(n.key)&&n.key.name==="id"||_e.isStringLiteral(n.key)&&n.key.value==="id")&&_e.isStringLiteral(n.value))return n.value.value;return null}}}function WI(e){return zI(e)===null}async function RM(e,t,n){let r=new Set,o=Sa.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=Sa.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"]:[Sa.posix.join(i,"locales"),Sa.posix.join(i,"messages")];for(let a of s){let l=Sa.posix.join(a,`${t}.json`);if(await n(l))return l}}return null}async function PM(e){let t=zI(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await RM(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function NM(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!_e.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!_e.isExpression(n))return null;let o=await cu(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:[kM("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var AM=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>_M(e)},{helperNames:["apiField"],resolve:e=>NM(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>PM({currentFile:e,expressionPath:t,exists:n})}];function wm(e){return{...e,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Derived display values are readonly because no identity-preserving write target exists"}]}}function UI(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 Rm(e,t,n){let r={kind:"value",root:n.root,path:n.path.length>0?n.path:[]},o=n.path.some(c=>c.kind==="index"),i=MM(n),s;n.semanticKind?s=n.semanticKind:i?s="config-entry":n.sourceKind==="repeat-template"?s="repeat-template":n.path.length===0?s=n.sourceKind==="imported-binding"?"imported-binding":"binding":s=o?"array-item":"object-field";let a=n.displayExpression??t,l=[...n.chainPrefix??[]];return n.sourceKind==="binding"?l.push({kind:"binding",file:n.file,displayName:n.root.kind==="binding"?n.root.name:a,canEditHere:n.editMode!=="readonly"}):n.sourceKind==="imported-binding"?l.push({kind:"imported-binding",file:n.file,displayName:n.root.kind==="named-export"?n.root.name:"default",canEditHere:n.editMode!=="readonly"}):n.sourceKind==="repeat-template"&&l.push({kind:"repeat-template",file:n.file,displayName:t,canEditHere:n.editMode!=="readonly"}),n.path.length>0&&n.sourceKind!=="repeat-template"&&l.push({kind:o?"array-item":"object-field",file:n.file,displayName:a,canEditHere:n.editMode!=="readonly"}),i&&l.push({kind:"config-entry",file:n.file,displayName:i.displayPath,canEditHere:n.editMode!=="readonly"}),{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:n.editMode==="readonly"?l.map(c=>({...c,canEditHere:!1})):l,confidence:n.sourceKind==="repeat-template"?"safe-derived":"exact",editMode:n.editMode??(n.file===e?"direct":"proxy"),diagnostics:n.diagnostics??[]}}var wM=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function Tm(e,t){let n=[...wM,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function HI(e,t){let n=e.callee;return _e.isIdentifier(n)&&Tm(n.name,t)?.purity==="side-effect"?`Helper "${n.name}" is registered as side-effectful and remains readonly`:"Function calls remain readonly because purity does not establish an identity-preserving write target"}async function Om(e){let t=await Nm(e);if(t)return t;let n=await GI({...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 kr({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 Gn({...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 FM(e)}async function GI(e){let t=await ir({...e,allowComposed:!1});if(t?.kind!=="source")return null;let n=uu(e.expressionPath);return n.isIdentifier()||n.isMemberExpression()?t.provenance:wm(t.provenance)}async function ir(e){let t=uu(e.expressionPath),n=LM(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 kr({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 Gn({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 kr({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 Gn({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 ir({...e,expressionPath:r,allowComposed:!0}),a=await ir({...e,expressionPath:o,allowComposed:!1}),l=await ir({...e,expressionPath:i,allowComposed:!1});return km(s,a,l)}if(t.isCallExpression())return TM({...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 ir({...e,expressionPath:r,allowComposed:!0}),s=await ir({...e,expressionPath:o,allowComposed:!0});return km(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 ir({...e,expressionPath:r,allowComposed:!0}),s=await ir({...e,expressionPath:o,allowComposed:!0});return km(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:ir({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function uu(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 TM(e){let t=Am(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:ir({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(_e.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:ir({...e,expressionPath:o,allowComposed:!1})}}return null}function km(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!OM(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function OM(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 LM(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function FM(e){if(!e.expressionPath.isCallExpression())return null;let t=Am(e.expressionPath.node);if(!t)return null;let n=Tm(t,e.functionCallContracts);if(!n||n.purity!=="pure")return null;let r=n.sourceArgIndex??0,o=e.expressionPath.get(`arguments.${r}`);if(!o||Array.isArray(o)||!o.isExpression())return null;let i=await YI({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});return i?wm(i):null}async function YI(e){let t=await Nm({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 kr({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 Gn({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 Om({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 DM(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!_e.isCallExpression(t))return null;let n=t.callee;if(!_e.isIdentifier(n))return null;let r=Tm(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}`);if(!s||Array.isArray(s)||!s.isExpression())return null;let a=await YI({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});return a?wm(a):null}function MM(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=Ki(t,e.path);return{sourceId:o,displayPath:o}}async function BM(e){let t=e.segment.source;return t?Gn({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 Gn(e){let t=e.sourceInfo,n=Im(e.expressionPath,t.base);if(n){let c=await uM({currentFile:e.currentFile,callPath:n.callPath,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,fileCache:e.fileCache,visited:e.visited});if(!c){let p=NI(n.callPath,[...n.basePath,...t.path]);return oa(p)?FI(e.currentFile,p.sourceId,p.displayPath):null}let u=TI(c,[...n.basePath,...t.path]),d=c.collectionIndexMap?.[0]??0,f=[...c.pathPrefix??[],{kind:"index",index:d},...n.basePath,...t.path],m=[{kind:"index",index:0},...n.basePath,...t.path];return tn(c.value,m)===void 0?null:{kind:"value",file:c.file,root:c.root,path:u?.[0]??f,sourceKind:"repeat-template",collectionIndexMap:c.collectionIndexMap,...u?{collectionPathMap:u}:{}}}let r=e.expressionPath.scope.getBinding(t.base);if(!r)return null;if(r.path.isImportNamespaceSpecifier()){let c=t.path[0],u=r.path.parentPath;if(!c||c.kind!=="property"||!u?.isImportDeclaration())return null;let d=await No(e.currentFile,u.node.source.value,e.exists);if(!d)return null;let f=await pM({file:d,exportName:c.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(!f||f.kind==="external")return null;let m=t.path.slice(1);return tn(f.value,m)===void 0?null:{kind:"value",file:f.file,root:f.root,path:m,sourceKind:"imported-binding",collectionIndexMap:f.collectionIndexMap}}let o=Sp(r);if(o){let c=o.expressionPath,u=await kr({expression:c.node,scope:c.scope,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(u){let d=await Gn({...e,expressionPath:c,sourceInfo:{...u,expression:Ki(u.expression,t.path),path:[...u.path,...t.path]}});if(d)return d}else if(r.constant){let d=`dynamic-alias:${e.currentFile}:${c.node.start}`;if(e.visited.has(d))return null;e.visited.add(d);try{let f=await ZI({...e,expressionPath:uu(c),memberSuffix:t.path});if(f?.kind==="value")return f}finally{e.visited.delete(d)}}if(t.path.length===0){let d=await GI({currentFile:e.currentFile,expressionPath:c,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(d)return d}}if(r.kind==="param")return mM({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 DM({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=_l(r,t.path,hM(e.fileCache));if(oa(s))return FI(e.currentFile,s.sourceId,s.displayPath);let a=await lu({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:tn(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}async function ZI(e){let t=AI(e.expressionPath.node);if(!t||!wI(t.segments))return null;let n=await Gn({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 fM({...e,rootPath:n.path,segments:t.segments});if(!r)return null;let o=r.collectionPathMap.map(i=>[...i,...e.memberSuffix??[]]);if(e.memberSuffix){let i=e.expressionPath.scope.getBinding(t.base),s=i?await lu({...e,binding:i}):null;if(s?.kind!=="static"||o.some(a=>tn(s.value,a.slice(n.path.length))===void 0))return null}return{...n,path:o[0]??n.path,sourceKind:r.sourceKind,displayExpression:Vi(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:o}}async function qI(e){let t=jM(e.propertyName);if(t.owner==="blocked")return bo(t.owner,t.diagnostic);if(t.owner==="class-name-source"||t.owner==="style")return bo(t.owner,{code:"owner-delegated",message:`Property '${e.propertyName}' is owned by ${t.owner}`});let n=e.element.attributes?.filter(c=>c.name===e.propertyName)??[];if(n.length>1)return bo("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 c of i)o.push({kind:"spread",order:c.order,spread:c,target:await UM(e,c)});o.sort((c,u)=>c.order-u.order);let s=o.at(-1);if(!s)return{status:"missing",owner:"generic"};if(o.filter(c=>c.kind==="spread"&&c.order>s.order).some(c=>!c.target))return bo("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}:bo("generic",{code:"ambiguous-property-source",message:`The final spread source for '${e.propertyName}' is not provably writable`});let l=o.filter(c=>c.kind==="spread"&&c.order<s.order);return e.operation==="remove"&&l.length>0?bo("generic",{code:"remove-exposes-spread",message:`Removing '${e.propertyName}' would expose an earlier spread source`}):$M(e,s.attribute)}async function $M(e,t){if(t.resolution&&t.resolution.status!=="resolved"&&!t.source){let r=await Xi({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}}:bo("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 Xi({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"?bo("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 UM(e,t){let n=t.source?.expression;if(!n)return;let r=await Xi({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:VM(r,e.propertyName)}}function VM(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 bo(e,t){return{status:"blocked",owner:e,...t?{diagnostic:t}:{}}}function QI(e){let t=new Map;for(let r of e.elements.values()){if(r.importedFrom===void 0)continue;let o=t.get(r.importedFrom);o||(o={candidates:[],keys:new Map},t.set(r.importedFrom,o)),o.candidates.push(r)}let n=r=>{if(ni(r.tag))return r.identity.key;let o=t.get(r.sourceFile);if(!o)return null;if(o.keys.has(r.componentName))return o.keys.get(r.componentName);let i=o.candidates.filter(a=>zM(a,r.componentName)),s=i.length===1?i[0].identity.key:null;return o.keys.set(r.componentName,s),s};return r=>KM({...r,graph:e},n)}function KM(e,t){let{key:n,element:r,graph:o,provenances:i}=e,s=XM(n,r,o,t),a=s?.tag??(ni(r.tag)?r.tag:r.componentName),l=s?.identity.key??t(r,o)??n,c=HM(s),u=GM(n,r,o,i,s),d=JM(n,r,o,i,l);return{componentName:a,instanceKey:l,templateOwner:WM(s??r,a),...c.length>0?{variantKeys:c}:{},...u.length>0?{slotKeys:u}:{},editableStrategy:d,impactScope:YM(d),alternativeStrategies:ZM(d)}}function JM(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return Lm(e,n)?"instance":!ni(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function XM(e,t,n,r){if(ni(t.tag))return t;let o=Lm(e,n);if(o)return o;let i=r(t,n);return i?n.elements.get(i)??null:null}function zM(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function WM(e,t){return ni(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function HM(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 GM(e,t,n,r,o){let i=new Set,s=Lm(e,n);s&&o?.identity.key===s.identity.key&&i.add("children");for(let a of r.values()){let l=a?.chain.find(u=>u.kind==="component-prop");if(!l)continue;let c=l.displayName.split(".").pop();c&&i.add(c)}return i.size===0&&ni(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function Lm(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(ni(r.tag))return r;n=r.parentKey}return null}function ni(e){return/^[A-Z]/.test(e)}function YM(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function ZM(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}function nv(e){let t=e.isRepeat??(e.graph?sB(e.element,e.graph):!1),n=e.propertyProvenance??new Map,r=e.repeatTargets??new Map,o=iB(e.element.attributes??[]),i=[...r.values()].some(u=>u.ok),s=o.map(u=>qM({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,l=(e.element.attributeSpreads??[]).slice().sort((u,d)=>u.order-d.order).map(u=>({raw:u.raw,sourceRange:aB(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."}]})),c=t&&e.selectionRef?.instanceIndex!==void 0&&i;return{documentVersion:e.documentVersion,...e.selectionRef?{selectionRef:e.selectionRef}:{},items:s,spreads:l,creation:t?{selection:c?"materialize":"unsupported",template:"unsupported"}:{selection:a?"unsupported":"direct",template:a?"unsupported":"direct"}}}function qM(e){let{attribute:t,provenance:n,repeatTarget:r}=e,o=e.selectionRef?.instanceIndex!==void 0&&r?.ok===!0?r:null,i=QM(t,n,e.isRepeat),s=["selection","template"].map(h=>({scope:h,result:Ll({state:n,scope:h,operation:"set",selectionRef:e.selectionRef,isRepeat:e.isRepeat,repeatTarget:r})})),a=s.find(({result:h})=>h.ok)?.result,l=a?.ok?a.target:void 0,c=l?.kind==="value-binding"&&o&&(JSON.stringify(l.locator.root)!==JSON.stringify(o.selectedParentObjectLocator.root)||JSON.stringify(l.locator.path??[])!==JSON.stringify([...o.selectedParentObjectLocator.path??[],{kind:"property",name:t.name}]))?null:o,u=eB(t,n,c,e.isRepeat),d=l?rB(l,e.element,t.name):void 0,f=s.filter(({result:h})=>h.ok).map(({scope:h})=>h),m=f.length>0?nB(n,o,e.element):"unsupported",g=o?"repeat-item":e.isRepeat?"repeat-template":"node",p=oB(t,n,r);if(f.length===0&&p.length===0){let h=s.find(({result:x})=>!x.ok)?.result;h&&!h.ok&&p.push({code:h.code,message:h.reason})}return{name:t.name,source:i,resolution:u,editMode:m,sourceScope:g,allowedWriteScopes:f,...d?{effectiveWriteTarget:d}:{},diagnostics:p}}function QM(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 eB(e,t,n,r){return n?ev(n.selectedResolution):t?.status==="blocked"?{status:"unresolved"}:r&&t?.status==="binding"?{status:"unresolved"}:ev(tB(e))}function tB(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 ev(e){return!e||e.status==="unresolved"?{status:"unresolved"}:e.status==="undefined"?{status:"undefined"}:{status:"resolved",value:e.value}}function nB(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 rB(e,t,n){return e.kind==="repeat-property"?{kind:"value-path",file:e.target.sourceFile,isProxy:e.target.sourceFile!==t.sourceFile,displayPath:tv({...e.target.selectedParentObjectLocator,path:[...e.target.selectedParentObjectLocator.path??[],{kind:"property",name:n}]})}:e.kind==="value-binding"?{kind:"value-path",file:e.file,isProxy:e.file!==t.sourceFile,displayPath:tv(e.locator)}:{kind:"jsx-node",file:t.sourceFile,isProxy:!1,displayPath:t.componentName+" > "+n}}function oB(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 iB(e){let t=new Set;return e.filter(n=>t.has(n.name)?!1:(t.add(n.name),!0))}function sB(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 tv(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 aB(e,t){if(!t)return{start:e.startColumn,end:e.endColumn};let n=t.split(`
7
7
  `),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)}}function cB(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var lB=160;function rv(e,t,n,r={}){let o=mi(e),i=[];for(let[s,a]of e.elements){let l=n.get(s),c={canUpdateText:r.canUpdateTextByKey?.get(s)??l?.canUpdateText??!1,canInsertChild:l?.canInsertChild??!1,canMove:l?.canMove??!1,canRemove:l?.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:c,...r.dynamicDataSummaryByKey?.get(s)?{dynamicDataSummary:r.dynamicDataSummaryByKey.get(s)}:{}})}return{composition:o,routeId:e.routeId,version:e.version,rootKeys:[...e.rootKeys],entries:i}}function ov(e,t,n,r,o,i,s,a,l,c,u){let d=mi(t),f=t.elements.get(e),m=n.nodes.get(e),g=r.get(e);if(!f||!m||!g)throw new Error(`Node not found: ${e}`);let p=lv(f.textSegments,s),h=uv(e,t,f,g,p),x=p?pB(p):void 0,b=mB(i,p),S=f.textSegments.map(I=>({index:I.index,value:I.value,editable:dv(I,g,s?.get(I.index)??null),source:o.get(I.index)??null})),E=av(f,t),v=f.childKeys.map(I=>{let A=t.elements.get(I);return A?{key:I,tag:A.tag,label:A.tag}:null}).filter(I=>I!==null),N=[];if(f.parentKey){let I=t.elements.get(f.parentKey);if(I)for(let A of I.childKeys){if(A===e)continue;let C=t.elements.get(A);C&&N.push({key:A,tag:C.tag,label:C.tag})}}return{composition:d,key:e,tag:f.tag,componentName:f.componentName,sourceFile:f.sourceFile,sourceLocator:sv(f),label:f.tag,capabilities:h,writeTarget:i,effectiveWriteTarget:b,provenanceChain:x,componentSemantic:l,styleSource:c,conditional:a,...u?{dynamicData:u}:{},textSegments:S,boundaryKind:f.boundaryKind,isOpaque:f.isOpaque,ancestors:E,children:v,siblings:N}}function iv(e,t,n,r,o,i,s,a){let l=mi(t),c=t.elements.get(e),u=n.nodes.get(e),d=r.get(e);if(!c||!u||!d)throw new Error(`Node not found: ${e}`);let f=lv(c.textSegments,i),m=uB(c);return{composition:l,key:e,tag:c.tag,...m?{linkSourceKind:m}:{},componentName:c.componentName,sourceFile:c.sourceFile,sourceLocator:sv(c),label:c.tag,capabilities:uv(e,t,c,d,f),provenanceChain:f?{editMode:f.editMode,diagnostics:f.diagnostics.map(g=>({code:g.code,message:g.message}))}:void 0,...s?{dynamicData:s}:{},...a?{properties:a}:{},textSegments:c.textSegments.map(g=>{let p=o.get(g.index);return{index:g.index,editable:dv(g,d,i?.get(g.index)??null),source:p?{kind:p.kind}:null}}),boundaryKind:c.boundaryKind,isOpaque:c.isOpaque,ancestors:av(c,t)}}function uB(e){if(e.tag==="a")return"native-anchor";if(e.importedFrom==="next/link"&&e.exportName==="default")return"next-link";if(e.tag==="Link")return"unsupported"}function sv(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:dB(e.sourceRange),structuralPath:e.identity.structuralPath,...fB(e.textSegments)}}function av(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 dB(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function fB(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,lB)}:{}}function cv(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 lv(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function uv(e,t,n,r,o){let i=n.identity.structuralPath.includes("#repeat:"),s=t.regions.some(u=>u.kind==="repeat-region"&&u.childKeys.includes(e)),a=o?.diagnostics.find(u=>u.code==="missing-adapter"||u.code==="external-source-readonly")?.code,l=r.canUpdateText?{mode:o?.editMode??"direct",reasonCode:a??(o?.editMode==="upstream"?"component-prop":o?.finalSource?.kind==="repeat-template"?"repeat-item-data":void 0)}:{mode:"unsupported",reasonCode:"capability-denied"},c=r.canUpdateText&&fv(l.mode);return{...r,canUpdateText:c,editModes:{updateText:l,insertChild:r.canInsertChild?{mode:"direct",reasonCode:i||s?"repeat-template":void 0}:{mode:"unsupported",reasonCode:"capability-denied"},move:r.canMove?{mode:s?"proxy":"direct",reasonCode:s?"repeat-collection":void 0}:{mode:"unsupported",reasonCode:"capability-denied"},remove:r.canRemove?{mode:s?"proxy":"direct",reasonCode:s?"repeat-collection":void 0}:{mode:"unsupported",reasonCode:"capability-denied"}}}}function dv(e,t,n){return!e.editable||!t.canUpdateText?!1:n?fv(n.editMode):!0}function fv(e){return e==="direct"||e==="proxy"||e==="upstream"}function pB(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 mB(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}:cB(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}}var Fm=["set-class-name-source","apply-style-draft"];function pv(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:Fm,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:Fm,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:Fm}}import mv from"node:path";function Mm(){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 hv(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=xB(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 l=t.has(a),c=n?await n(a):!1;if(l||c)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 du(e){let t=()=>gB(e);return e.mutex?e.mutex.runExclusive(t):t()}async function gB(e){let t=await hv(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=hB(e.overlay,t.plan),r;try{r=await e.buildCandidate({overlay:n,plan:t.plan})}catch(c){return{ok:!1,stage:"build",reason:"Candidate build failed.",error:c,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(c){return Dm({candidate:r,plan:t.plan,failedStage:"commit",error:c,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let s=r;try{let c=await e.validateCandidate({candidate:r,plan:t.plan,receipt:i});c!==void 0&&(s=c)}catch(c){return Dm({candidate:r,plan:t.plan,failedStage:"validate",error:c,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let a;try{a=await e.publishCandidate({candidate:s,plan:t.plan,history:o,receipt:i})}catch(c){return Dm({candidate:s,plan:t.plan,failedStage:"publish",error:c,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let l={candidate:s,plan:t.plan,history:o,receipt:i,published:a};try{await e.swapCandidate?.(l)}catch(c){return gv("swap",c,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(l)}catch(c){return gv("finalize",c,"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 hB(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 Dm(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:yB(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 gv(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function yB(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 xB(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)||mv.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=mv.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}}var bB=50,SB=8*1024*1024;function Sv(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??bB),s=Math.max(0,t.maxUndoBytes??SB);return{prepareRewritePlan:a,execute:l,executeFilePlan:c,undo:u,redo:d};async function a(I){let A=[...I.steps].sort((J,Y)=>J.order-Y.order),C=A.filter(J=>J.type!=="invoke-external-adapter");if(C.length!==A.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let O=new Set(C.map(J=>J.file)),L=await b(O),X=new Map(L.map(J=>[J.file,J.exists===!1?"":J.content])),j;for(let J of C){let Y=bv(J,X.get(J.file)??"");if(!Y.ok)return{ok:!1,errorCode:Y.errorCode,reason:Y.reason};X.set(J.file,Y.source),j=Y.selectionRef??j}return{ok:!0,filePlan:{operationId:I.operationId,kind:"source-edit",target:I.target,documentVersion:I.documentVersion,conflictPolicy:"compare-and-swap",edits:[...X].map(([J,Y])=>({operation:"upsert",file:J,content:Y,baseContentHash:L.find($=>$.file===J)?.sha256??null}))},...j?{selectionRef:j}:{}}}async function l(I){let A=[...I.steps].sort(($,ce)=>$.order-ce.order),C=A.filter($=>$.type!=="invoke-external-adapter"),O=A.filter($=>$.type==="invoke-external-adapter"),L=new Set(C.map($=>$.file));if(C.length>0&&O.length>0)return{ok:!1,operationId:I.operationId,errorCode:"unsupported-operation",reason:"Mixed local file rewrites and external adapter writes require an explicit compensation contract.",rolledBack:!1};if(C.length===0)return h(I,O);let X=await b(L),j=new Map;for(let $ of X)j.set($.file,$.exists===!1?"":$.content);let J;for(let $ of C){let ce=j.get($.file)??"",ue=bv($,ce);if(!ue.ok)return{ok:!1,operationId:I.operationId,errorCode:ue.errorCode,reason:ue.reason,rolledBack:!1};j.set($.file,ue.source),ue.selectionRef&&(J=ue.selectionRef)}let Y=await E([...j].map(([$,ce])=>({file:$,content:ce,exists:!0,version:0,sha256:$e(ce)})),X);return Y.ok===!1?{ok:!1,operationId:I.operationId,errorCode:Y.rolledBack?"writeback-failed":"rollback-failed",reason:Y.reason,rolledBack:Y.rolledBack}:(n.push({operationId:I.operationId,preSnapshots:X,postSnapshots:Y.snapshots,plan:I}),f(),r.length=0,{ok:!0,operationId:I.operationId,kind:I.kind,target:I.target,resultVersion:Math.max(...Y.snapshots.map($=>$.version)),affectedFiles:[...L],...J?{selectionRef:J}:{}})}async function c(I){let A=new Set(I.edits.map(Y=>Y.file)),C=await b(A),O=x(I,C);if(O)return{ok:!1,operationId:I.operationId,errorCode:"stale-version",reason:O.reason,affectedFiles:[O.file],rolledBack:!1};let L=new Map(C.map(Y=>[Y.file,Y])),X=I.edits.find(Y=>Y.operation==="create-only"&&L.get(Y.file)?.exists!==!1);if(X)return{ok:!1,operationId:I.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${X.file}`,affectedFiles:[X.file],rolledBack:!1};let j=I.edits.map(Y=>Y.operation==="delete"?{file:Y.file,content:"",exists:!1,version:0}:{file:Y.file,content:Y.content,exists:!0,version:0,sha256:$e(Y.content)}),J=await E(j,C,new Set(I.edits.filter(Y=>Y.operation==="create-only").map(Y=>Y.file)));return J.ok===!1?{ok:!1,operationId:I.operationId,errorCode:J.rolledBack?"writeback-failed":"rollback-failed",reason:J.reason,rolledBack:J.rolledBack}:(n.push({operationId:I.operationId,preSnapshots:C,postSnapshots:J.snapshots,plan:{operationId:I.operationId,kind:I.kind,target:I.target,documentVersion:I.documentVersion,steps:[],preSnapshots:C}}),f(),r.length=0,{ok:!0,operationId:I.operationId,kind:I.kind,target:I.target,resultVersion:Math.max(...J.snapshots.map(Y=>Y.version)),affectedFiles:[...A]})}async function u(){let I=n.at(-1);if(!I)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let A=await E(I.preSnapshots,I.postSnapshots);return A.ok===!1?{ok:!1,operationId:I.operationId,errorCode:A.rolledBack?"writeback-failed":"rollback-failed",reason:A.reason,rolledBack:A.rolledBack}:(n.pop(),r.push(I),{ok:!0,operationId:I.operationId,kind:I.plan.kind,target:I.plan.target,resultVersion:Math.max(...A.snapshots.map(C=>C.version)),affectedFiles:I.preSnapshots.map(C=>C.file)})}async function d(){let I=r.at(-1);if(!I)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let A=await E(I.postSnapshots,I.preSnapshots);return A.ok===!1?{ok:!1,operationId:I.operationId,errorCode:A.rolledBack?"writeback-failed":"rollback-failed",reason:A.reason,rolledBack:A.rolledBack}:(r.pop(),n.push(I),f(),{ok:!0,operationId:I.operationId,kind:I.plan.kind,target:I.plan.target,resultVersion:Math.max(...A.snapshots.map(C=>C.version)),affectedFiles:I.postSnapshots.map(C=>C.file)})}function f(){for(;n.length>i;)n.shift();for(;n.length>0&&m()>s;)n.shift()}function m(){return n.reduce((I,A)=>I+g(A),0)}function g(I){return p(I.preSnapshots)+p(I.postSnapshots)}function p(I){return I.reduce((A,C)=>A+C.file.length+C.content.length,0)}async function h(I,A){let C=[];for(let O of A){let L=O.capability??"write-text",X=o.find(J=>J.sourceType===O.sourceType&&(O.adapterId===void 0||J.adapterId===O.adapterId)&&(J.capabilities===void 0||J.capabilities.includes(L)));if(!X)return{ok:!1,operationId:I.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${O.sourceType}`,rolledBack:!1};let j=await X.execute(O);if(!j.ok)return{ok:!1,operationId:I.operationId,errorCode:"writeback-failed",reason:j.reason??`External adapter failed for ${O.sourceType}`,rolledBack:!1};C.push(O.file)}return{ok:!0,operationId:I.operationId,kind:I.kind,target:I.target,resultVersion:0,affectedFiles:C}}function x(I,A){if(I.conflictPolicy!=="compare-and-swap")return null;let C=new Map(A.map(O=>[O.file,O]));for(let O of I.edits){if(O.operation==="create-only")continue;if(O.baseContentHash===void 0)return{file:O.file,reason:`Source file ${O.file} is missing baseContentHash. Reopen the file before saving.`};let L=C.get(O.file),X=O.baseContentHash;if(X===null){if(L?.exists!==!1)return{file:O.file,reason:`Source file ${O.file} was created or changed before save.`};continue}if(!X)return{file:O.file,reason:`Source file ${O.file} is missing baseContentHash. Reopen the file before saving.`};if(L?.exists===!1||L?.sha256!==X)return{file:O.file,reason:`Source file ${O.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function b(I){let A=[];for(let C of I)A.push(await S(C));return A}async function S(I){if(!await e.exists(I))return{file:I,content:"",version:0,exists:!1};let C=Math.max(1,e.getVersion(I)),O=await e.readFile(I);return{file:I,content:O,version:C,exists:!0,sha256:$e(O)}}async function E(I,A,C=new Set){let O=[];try{for(let L of I){if(C.has(L.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive(L.file,L.content)}else await v(L);let X=e.bumpVersion(L.file);O.push(L.file),L.version=X}}catch(L){let X=await N(A.filter(J=>O.includes(J.file)));if(X.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${X.failedFiles.join(", ")}: ${xv(L)}`,rolledBack:!1,instanceConflict:yv(L)};let j=yv(L);return{ok:!1,reason:`${j?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${xv(L)}`,rolledBack:!0,instanceConflict:j}}return{ok:!0,snapshots:I.map(EB)}}async function v(I){if(I.exists===!1){await e.deleteFile(I.file);return}await e.writeFile(I.file,I.content)}async function N(I){let A=[];for(let C of I)try{await v(C),e.bumpVersion(C.file)}catch{A.push(C.file)}return A.length===0?{ok:!0}:{ok:!1,failedFiles:A}}}function yv(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function EB(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:$e(e.content)}:{}}}function xv(e){return e instanceof Error?e.message:String(e)}function bv(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 Yt(Kn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return Yt(pi({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return Yt(Mo({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return Yt(Vn({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return Yt(mc({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return Yt(Is({source:t,locator:e.locator,next:e.value}));case"update-array-item":return Yt(Is({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return Yt(Sc({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return Yt(gc({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return Yt(Ec({source:t,locator:e.locator,index:e.index}));case"move-array-item":return Yt(Ic({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return Yt(jo({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return Yt(hc({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 IB(e,t);case"set-property-changes":return Yt(yc({source:t,locator:e.locator,changes:e.changes}));case"set-link-target":return Yt(xc({source:t,locator:e.locator,link:e.link,changes:e.changes}));case"set-property-binding":return Yt(bc({source:t,locator:e.locator,name:e.name,object:e.object,property:e.property}));case"upsert-object-property":return Yt(kc({source:t,objectLocator:e.locator,name:e.name,value:e.value}));default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function IB(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!Ny(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!==$e(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:Py({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function Yt(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"}}}import{computeSiteEditCompositionKey as fu,SiteEditCompositionContextSchema as vB,SiteEditCompositionSelectorSchema as kB}from"@vcp-dev/platform-shared/contracts";var nn=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="SiteEditCompositionError"}};function Ev(e,t){throw new nn("INVALID_COMPOSITION",e,{value:t})}function pu(e){let t=vB.safeParse(e);return t.success?t.data:Ev("Invalid SiteEditCompositionContext.",e)}function Iv(e){let t=[],n=new Map,r=new Map;for(let c of e.compositions){let u=pu(c?.context);if(typeof c.entryFile!="string"||!c.entryFile)throw new nn("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=fu(u);if(n.has(d))throw new nn("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u});let f=r.get(c.entryFile);if(f)throw new nn("DUPLICATE_COMPOSITION",`Entry file ${c.entryFile} is registered more than once.`,{entryFile:c.entryFile,context:f});let m={context:u,entryFile:c.entryFile,key:d};t.push(m),n.set(d,m),r.set(c.entryFile,d)}if(t.length===0)throw new nn("INVALID_COMPOSITION","At least one composition must be registered.");let o=new Map;for(let c of e.initialDocumentVersions??[]){let u=pu(c?.composition);if(!Number.isInteger(c?.version)||(c?.version??-1)<0)throw new nn("INVALID_INITIAL_DOCUMENT_VERSION","Initial document version must be a non-negative integer.",{context:u,version:c?.version});let d=fu(u);if(!n.has(d))throw new nn("UNKNOWN_COMPOSITION","Initial document version references an unregistered composition.",{context:u,key:d});if(o.has(d))throw new nn("DUPLICATE_COMPOSITION","Initial document versions must contain each composition at most once.",{context:u,key:d});o.set(d,c.version)}function i(c){let u=kB.safeParse(c);if(!u.success)return Ev("Invalid SiteEditCompositionSelector.",c);let d=t.filter(({context:f})=>f.routeId===u.data.routeId&&(u.data.templateId===void 0?f.effectiveTemplateId===void 0:f.effectiveTemplateId===u.data.templateId));if(d.length===1)return d[0];throw d.length>1?new nn("AMBIGUOUS_COMPOSITION","The composition selector matches multiple registered contexts.",{selector:u.data}):new nn("UNKNOWN_COMPOSITION","The composition selector is not registered.",{selector:u.data})}function s(c){let u=pu(c),d=fu(u),f=n.get(d);if(!f)throw new nn("UNKNOWN_COMPOSITION","The composition context is not registered.",{context:u,key:d});return f}function a(c){let u=pu(c?.context);if(typeof c.entryFile!="string"||!c.entryFile)throw new nn("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=fu(u),f=n.get(d);if(f){if(f.entryFile===c.entryFile)return f;throw new nn("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u})}let m=[...n.values()].find(p=>p.entryFile===c.entryFile);if(m)throw new nn("DUPLICATE_COMPOSITION",`Entry file ${c.entryFile} is registered more than once.`,{entryFile:c.entryFile,context:m.context});let g={context:u,entryFile:c.entryFile,key:d};return t.push(g),n.set(d,g),g}function l(c){let u=n.get(c);if(!u)return;n.delete(c);let d=t.findIndex(f=>f.key===c);return d>=0&&t.splice(d,1),o.delete(c),u}return{entries:t,byKey:n,initialVersions:o,register:a,unregister:l,resolveSelector:i,resolveContext:s,getByKey:c=>n.get(c),routeIds:()=>[...new Set(t.map(({context:c})=>c.routeId))]}}function Bm(e){let t=new Map,n=new Map;return{readFile(r){let o=t.get(r);return o||(o=e.readFile(r),t.set(r,o)),o},exists(r){let o=n.get(r);return o||(o=e.exists(r),n.set(r,o)),o}}}async function vv(e,t){if(e.length===0)return[];if(e.length===1)return[await t(e[0])];let n=new Array(e.length),r=[],o=0,i=Array.from({length:Math.min(4,e.length)},async()=>{for(;o<e.length&&r.length===0;){let l=o++;try{n[l]=await t(e[l])}catch(c){r.push({index:l,error:c})}}}),s=await Promise.allSettled(i),a=r.sort((l,c)=>l.index-c.index)[0];if(a)throw a.error;for(let l of s)if(l.status==="rejected")throw l.reason;return n}import{composeSiteEditRepeatInstanceKey as _B,stripSiteEditRepeatInstanceKeys as kv}from"@vcp-dev/platform-shared/contracts";function _v(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=kv(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}}function CB(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 jm(e){return e?.map(t=>({...t}))}function $m(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionPathMap?.[t],r=jm(n??e.locator?.path);if(!n&&r){let o=e.collectionIndexMap?.[t]??t;for(let i=r.length-1;i>=0;i-=1){let s=r[i];if(s.kind==="index"){s.index=o;break}}}return{...e,path:jm(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>jm(o)??[])}}function Cv(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)=>_B(m,g),l=(m,g,p)=>{let h=o.get(m);if(!h)return a(m,p);let x=a(m,p),b={...h,key:x,parentKey:g,childKeys:[]};return i.push(b),b.childKeys=h.childKeys.flatMap(S=>c(S,p,x)),x},c=(m,g,p)=>{if(!r.has(m))return[l(m,p,g)];let h=d(m,g),x=[];for(let b=0;b<h;b+=1)x.push(l(m,p,[...g,b]));return x},u=Array.from(new Set([...e.rootKeys,...e.entries.filter(m=>m.parentKey===null).map(m=>m.key)]));for(let m of u){if(!r.has(m)){l(m,null,[]);continue}let g=d(m,[]);for(let p=0;p<g;p+=1)l(m,null,[p])}return{...e,rootKeys:[...e.rootKeys],entries:i};function d(m,g){let p=new Set;for(let h of f(m)){let x=n.get(h);if(x){for(let b of[...x.textTargets.values(),...x.elementPropertyTargets.values()])if(!(b?.kind!=="value-binding"||b.sourceKind!=="repeat-template"))for(let S of RB(b))S.length<=g.length||PB(S,g)&&p.add(S[g.length])}}return p.size>0?p.size:CB(n.get(m))}function f(m){let g=s.get(m);if(g)return g;let p=[m],h=o.get(m);for(let x of h?.childKeys??[])p.push(...f(x));return s.set(m,p),p}}function Rv(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function Pv(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((kv(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function RB(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 PB(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 Nv(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 l=i.childKeys.map(u=>o.get(u)).filter(u=>u!==void 0).map(u=>({key:u.key,tag:u.tag,label:u.label})),c=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:l,siblings:c}}function Av(e,t,n,r){if(!n)return{...e,key:t};let o=r??new Map(n.entries.map(l=>[l.key,l])),i=o.get(t);if(!i)return{...e,key:t};let s=[],a=i.parentKey;for(;a;){let l=o.get(a);if(!l)break;s.push({key:l.key,tag:l.tag,label:l.label}),a=l.parentKey}return s.reverse(),{...e,key:i.key,ancestors:s}}function wv(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function NB(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var Ia=class extends Error{constructor(t){let n=t.map(wv);super(NB(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function Tv(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof Ia?{routeId:e,message:n,diagnostics:t.diagnostics.map(wv)}:{routeId:e,message:n}}function Um(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function Vm(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function va(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function Ov(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function mu(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 Lv(e){let{journal:t,index:n,observedFileDigests:r}=e;if(r.length!==t.files.length)return"ambiguous";let o=t.files.every((c,u)=>c.preDigest===r[u]),i=t.files.every((c,u)=>c.postDigest===r[u]),s=t.historyTransition,a=n.digest===s.expectedIndexDigest,l=n.digest===s.publishedIndexDigest&&n.cursor===s.publishedCursor&&n.currentId===s.publishedCurrentId;return o&&a?"safely-uncommitted":i&&l?"durably-committed":"ambiguous"}var MB=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,BB=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],Fv=32,hu=256;function jB(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var Dv={maxEntries:50,maxBytes:8*1024*1024};function $B(){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 Rc(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}}}async function Mv(e,t){if(t.length===0)return[];let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return[]}if(!n||typeof n!="object")return[];let r=n.dependencies;return!r||typeof r!="object"||Array.isArray(r)?[]:t.filter(o=>{if(!Object.prototype.hasOwnProperty.call(r,o))return!1;let i=r[o];return typeof i=="string"&&i.trim().length>0})}function UB(){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>Dv.maxEntries||VB(e)>Dv.maxBytes;)e.shift()}}function VB(e){return e.reduce((t,n)=>t+KB(n),0)}function KB(e){return Bv(e.preSnapshots)+Bv(e.postSnapshots)+JB(e.provenance)}function JB(e){return e?new TextEncoder().encode(JSON.stringify(e)).byteLength:0}function Bv(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function jv(e,t){return{key:wB(e),composition:e,routeId:e.routeId,entryFile:t,graph:null,topology:null,capabilities:null,document:null,pageBlockIndex: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}}var yu=class extends Error{constructor(t){super(t.reason),this.result=t}},So=class extends Error{constructor(t){super(Um(t)),this.failedRoutes=t}};function XB(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=En(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(En(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}function Xv(e,t){let n=e.pageBlockIndex;if(!n||n.diagnostics.length>0)return;let r=[...n.bindings.values()].filter(t);return r.length===1?r[0]?.descriptor.rootRef:void 0}function zB(e,t,n){let r=t.root,o=i=>i===r.ownerMemberKey?n:i;return Xv(e,({root:i})=>i.ownerMemberKey===n&&i.rootRef.key===o(r.rootRef.key)&&i.callChain.length===r.callChain.length&&i.callChain.every((s,a)=>s.callLocator.key===o(r.callChain[a].callLocator.key)))}function WB(e,t,n){if(!n)return;let r=En(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 HB=/\.(?:[cm]?[jt]sx?)$/i,GB=/\.json$/i,YB=/\.(?:css|scss|sass)$/i,ZB=/\.mdx$/i,qB=/\.ya?ml$/i;function QB(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 ej(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function tj(e,t){let n=new Map;for(let i of t)n.set(i.path,i.operation==="delete"?{exists:!1}:{exists:!0,content:i.content});let r=new Map,o=new Map;return{async readFile(i){let s=n.get(i);if(s){if(!s.exists)throw new Error(`Source file not found: ${i}`);return s.content}let a=r.get(i);return a||(a=e.readFile(i),r.set(i,a)),a},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(i){let s=n.get(i);if(s)return s.exists;let a=o.get(i);return a||(a=e.exists(i),o.set(i,a)),a},async getFileInfo(i){let s=n.get(i);return s?s.exists?{path:i,sizeBytes:Buffer.byteLength(s.content,"utf8")}:null:e.getFileInfo?.(i)??null},async listFiles(i={}){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let s=zv(await e.listFiles(i)),a=new Map(s.files.map(c=>[c.path,c]));for(let[c,u]of n)if(nj(c,i.roots??[])){if(!u.exists){a.delete(c);continue}a.set(c,{path:c,sizeBytes:Buffer.byteLength(u.content,"utf8")})}let l=[...a.values()].sort((c,u)=>c.path.localeCompare(u.path));return s.truncated?{files:l,truncated:s.truncated}:l},getVersion(i){return e.getVersion(i)},bumpVersion(i){return e.getVersion(i)}}}function nj(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function zv(e){return Array.isArray(e)?{files:e}:e}function rj(e){if(!OB(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!==FB||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=TB(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(HB.test(e.path)){let t=cr({source:e.content,profile:wo({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(GB.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${ln(t)}`,details:{path:e.path}}}if(YB.test(e.path)){let t=$v({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(ZB.test(e.path)){let t=$v({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(qB.test(e.path))try{DB(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${ln(t)}`,details:{path:e.path}}}return{ok:!0}}function $v({content:e,path:t,profile:n}){let r=[],o=null,i=!1,s=!1,a=!1,l=!1,c=!0;for(let d=0;d<e.length;d+=1){let f=e[d]??"",m=e[d+1]??"";if(n==="mdx"&&c&&e.startsWith("```",d)){l=!l;let g=e.indexOf(`
8
8
  `,d);if(g===-1){c=!0;break}d=g,c=!0;continue}if(l){c=f===`
9
9
  `||f==="\r";continue}if(s){f==="*"&&m==="/"&&(s=!1,d+=1),c=f===`