croct 0.1.1 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +54 -54
- package/package.json +1 -4
package/index.js
CHANGED
|
@@ -52,9 +52,9 @@ ${b}`+te`
|
|
|
52
52
|
return null;
|
|
53
53
|
}
|
|
54
54
|
};
|
|
55
|
-
`,{overwrite:true});let
|
|
55
|
+
`,{overwrite:true});let I=`const contentMap = ${JSON.stringify(c,null,2).replace(/"(\.\/.*?)"/g,'() => import("$1.js")')};
|
|
56
56
|
|
|
57
|
-
`;await this.fileSystem.writeTextFile(this.fileSystem.joinPaths(p,"loadSlotContent.js"),
|
|
57
|
+
`;await this.fileSystem.writeTextFile(this.fileSystem.joinPaths(p,"loadSlotContent.js"),I+te`
|
|
58
58
|
const defaultLocale = ${JSON.stringify(r.defaultLocale)};
|
|
59
59
|
|
|
60
60
|
export function loadSlotContent(slotId, language = defaultLocale) {
|
|
@@ -103,7 +103,7 @@ ${b}`+te`
|
|
|
103
103
|
`:""),this}appendString(e,t){return this.append(t+e.replace(new RegExp(t,"g"),`\\${t}`)+t)}appendIndentation(){return this.write("",false)}appendName(e,t=true){return this.code+=o.formatName(e,t),this}writeValue(e,t){return this.appendIndentation().appendValue(e,t)}append(e){return this.code+=this.indentCode(e,false),this}appendValue(e,t){let{delimiter:n,stringKeys:r=false}=t;switch(typeof e){case "string":{let i=e.replace(new RegExp(n,"g"),`\\${n}`);return this.append(`${n}${i}${n}`)}case "number":case "boolean":return this.append(`${e}`);case "object":{if(e===null)return this.append("null");if(Array.isArray(e)){if(e.length===0)return this.append("[]");this.append("[").newLine().indent();for(let a=0;a<e.length;a++)this.appendIndentation().appendValue(e[a],t),a<e.length-1&&this.append(", ").newLine();return this.outdent().newLine().write("]",false)}let i=Object.entries(e);if(i.length===0)return this.append("{}");this.append("{").newLine().indent();for(let a=0;a<i.length;a++){let[s,p]=i[a];this.appendIndentation(),r||!isIdentifier(s)?this.appendValue(s,t):this.append(s),this.append(": ").appendValue(p,t),a<i.length-1&&this.append(", ").newLine();}return this.outdent().newLine().write("}",false)}default:return this.append("undefined")}}indentCode(e,t=true){let n=" ".repeat(this.indentationLevel*this.indentationSize);return (t?n:"")+e.replace(/\n/g,`
|
|
104
104
|
${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/[^a-z0-9]/gi,"_");return e.includes("_")?t?n[0].toUpperCase()+n.slice(1):n:n.replace(/(^[a-z_])|_([a-z])/gi,(r,i,a,s)=>t||s>0?(i??a).toUpperCase():(i??a).toLowerCase())}};function Jn(o){let e=o.split(/(?<![A-Z])(?=[A-Z])|_/),t=e[0];return [t[0].toUpperCase()+t.slice(1).toLowerCase(),...e.slice(1).map(i=>i.toLowerCase())].join(" ")}function ws(o){return o.normalize("NFD").toLocaleLowerCase().replace(/(^[^a-z]+|[^a-z0-9_ &-]+)/ig,"").split(/[^a-z0-9]+/i).filter(e=>e!=="").join("-")}function St(o){return Object.entries(o).sort(([,e],[,t])=>{let n=e.position??Number.MAX_SAFE_INTEGER,r=t.position??Number.MAX_SAFE_INTEGER;return n-r})}var Qn=class o{constructor({fileSystem:e,...t}){this.options=t,this.fileSystem=e;}generate(e){let t=this.generateSlotFile(e);return {files:[this.generatePageFile(e,t.path),t]}}generatePageFile(e,t){let n=this.createWriter();return this.writePageSnippet(n,e.definition.title??"Croct example",this.fileSystem.getRelativePath(this.fileSystem.getDirectoryName(this.options.pagePath),t).replace(/\\/g,"/")),{path:this.options.pagePath,language:"html",code:n.toString()}}writePageSnippet(e,t,n){e.write('<html lang="en">').write("<head>").indent().write('<meta charset="UTF-8">').write(`<title>${o.escapeEntities(t)}</title>`).write(`<script type="module" src="${n}"></script>`).outdent().write("</head>").write("<body>").indent().write(`<div id="${this.options.containerId}"></div>`).outdent().write("</body>").write("</html>",false);}generateSlotFile(e){let t=this.createWriter();return this.writeSlotSnippet(t,e),{path:this.options.slotPath,language:this.options.language,code:t.toString()}}writeSlotSnippet(e,t){e.write("import croct from '@croct/plug';"),e.newLine().write(`croct.plug({appId: '${this.options.appId}'});`).newLine(),this.renderListener(e,t);}renderListener(e,t){e.write("document.addEventListener('DOMContentLoaded', async () => {").indent(),e.write("const {content} = ",false).append(`await croct.fetch('${t.id}@${t.version}'`),this.options.fallbackContent!==void 0&&e.append(", {").indent().newLine().write("fallback: ",false).appendValue(this.options.fallbackContent,{delimiter:"'"}).newLine().outdent().write("}",false),e.append(");"),e.newLine(2).write(`document.querySelector('#${this.options.containerId}')`,false),this.options.language==="typescript"&&e.append("!"),e.append(".innerHTML = `").newLine().indent(),this.writeContentSnippet(e,t.definition,"content"),e.outdent().write("`;").outdent().write("});");}writeContentSnippet(e,t,n){switch(t.type){case "text":case "number":e.append(`\${${n}}`);break;case "boolean":t.label!==void 0?e.append(`\${${n} ? `).appendValue(t.label.true??"Yes",{delimiter:"'"}).append(" : ").appendValue(t.label.false??"No",{delimiter:"'"}).append("}"):e.append(`\${${n} ? 'Yes' : 'No'}`);break;case "list":{let r=t.itemLabel!==void 0?ht(t.itemLabel):"item";e.write("<ol>").indent().write(`\${${n}.map(${r} => \``).indent().write("<li>").indent();let i=o.isInline(t.items);i&&e.appendIndentation(),this.writeContentSnippet(e,t.items,r),i&&e.newLine(),e.outdent().write("</li>").outdent().write("`).join('')}").outdent().write("</ol>");break}case "structure":e.write("<ul>").indent();for(let[r,i]of St(t.attributes))i.private!==true&&(i.optional===true&&(e.write(`\${${n}.${r} && \``),e.indent()),this.writeAttributeSnippet(e,i,`${n}.${r}`),i.optional===true&&(e.outdent(),e.write("`}")));e.outdent().write("</ul>");break;case "union":for(let[r,i]of Object.entries(t.types))e.write(`\${${n}._type === '${r}' && \``).indent(),this.writeContentSnippet(e,i,n),e.outdent().write("`}");break}}writeAttributeSnippet(e,t,n){let r=t.type,i=t.label!==void 0?o.escapeEntities(t.label).replace(/`/g,"\\`"):Jn(n.split(".").pop());switch(r.type){case "boolean":case "text":case "number":{e.write("<li>",false).append(`<strong>${i}:</strong> `),this.writeContentSnippet(e,r,n),e.append("</li>").newLine();break}default:e.write("<li>").indent().write(`<strong>${i}</strong>`),this.writeContentSnippet(e,r,n),e.outdent().write("</li>");break}}static isInline(e){return ["number","text","boolean"].includes(e.type)}static escapeEntities(e){return e.replace(/([&<>])/g,t=>({"&":"&","<":"<",">":">"})[t]??t)}createWriter(){return new Me(this.options.indentationSize)}};var Bn=class o extends qe{constructor({bundlers:e,...t}){super(t),this.bundlers=e;}async generateSlotExampleFiles(e,t){let{configuration:n}=t,[r,i,a]=await Promise.all([this.isTypeScriptProject(),this.detectBundler(),this.workspaceApi.getApplication({organizationSlug:n.organization,workspaceSlug:n.workspace,applicationSlug:n.applications.development})]);if(a===null)throw new ee(`Development application ${n.applications.development} not found.`,{reason:"not_found"});let s=this.fileSystem.joinPaths(t.configuration.paths.examples,e.slug),c=new Qn({fileSystem:this.fileSystem,language:r?"typescript":"javascript",appId:a.publicId,fallbackContent:i===null?o.extractFallbackContent(e.content[t.configuration.defaultLocale],e.resolvedDefinition):void 0,containerId:"slot",slotPath:this.fileSystem.joinPaths(s,`slot.${r?"ts":"js"}`),pagePath:this.fileSystem.joinPaths(s,"index.html")}).generate({id:e.slug,version:e.version.major,definition:e.resolvedDefinition});return Promise.resolve(c.files)}static extractFallbackContent(e,t){switch(e.type){case "text":case "boolean":case "number":return e.value.type==="static"?e.value.value:e.value.default!==void 0?e.value.default:null;case "list":return e.items.map(n=>o.extractFallbackContent(n,t.items));case "structure":{let n=t,r={};for(let[i,a]of St(n.attributes)){if(a.private===true)continue;let s=o.extractFallbackContent(e.attributes[i],n.attributes[i].type);(a.optional!==true||s!==null)&&(r[i]=s);}return r}}}async detectBundler(){for(let e of this.bundlers)if(await this.packageManager.hasDirectDependency(e))return Promise.resolve(e);return Promise.resolve(null)}getInstallationPlan(e){return Promise.resolve({tasks:[],dependencies:["@croct/plug"],configuration:e.configuration})}};var Fe=class o{constructor(e,t){this.fileSystem=e,this.path=t;}getName(){return this.fileSystem.getBaseName(this.path)}exists(){return this.fileSystem.exists(this.path)}async hasVariable(e){let t=await this.read();if(t==="")return false;let n=o.escapeRegex(e);return new RegExp(`^${n}\\s*=`,"m").test(t)}async setVariables(e){let t=await this.read();try{for(let[n,r]of Object.entries(e))await this.setVariable(n,r);}catch(n){throw await this.write(t),n}}async setVariable(e,t){let n=await this.read(),r=o.escapeRegex(e);if(n==="")return this.write(`${e}=${t}`);let i=n.replace(new RegExp(`${r}\\s*=\\s*((?!['"\`]).*$|\`(?:\\.|[^\`])*\`|'(?:\\.|[^'])*'|"(?:\\.|[^"])*")`,"m"),`${e}=${t}`);return i!==n?this.write(i):this.write(`${n}${n.endsWith(`
|
|
105
105
|
`)?"":`
|
|
106
|
-
`}${e}=${t}`)}async write(e){await this.fileSystem.writeTextFile(this.path,e,{overwrite:true});}async read(){return await this.exists()?this.fileSystem.readTextFile(this.path):""}static escapeRegex(e){return e.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&")}};var It=class o{constructor({fileSystem:e,...t}){this.options=t,this.fileSystem=e;}generate(e){let t=o.replaceVariables(this.options.slotFilePath,e.id),n=o.replaceVariables(this.options.slotComponentName,e.id);return {files:[this.generatePageFile(e,{name:n,path:t,importPath:o.replaceVariables(this.options.slotImportPath,e.id),definition:e}),this.generateSlotFile(e,t,n)]}}generatePageFile(e,t){let n=this.createWriter(),r=o.replaceVariables(this.options.pageFilePath,e.id),i=o.replaceVariables(this.options.pageComponentName,e.id);return this.writePageSnippet(n,i,t),{path:r,language:this.options.language,code:n.toString()}}generateSlotFile(e,t,n){let r=this.createWriter();return this.writeSlotSnippet(r,e,n),{path:t,language:this.options.language,code:r.toString()}}writePageSnippet(e,t,n){this.writePageHeader(e,n),e.newLine(),this.writePageSignature(e,t),e.indent().write("return (").indent(),this.hasSuspenseBoundary()&&e.write('<Suspense fallback="\u2728 Personalizing...">').indent(),this.writeSlotRendering(e,n.name),this.hasSuspenseBoundary()&&e.outdent().write("</Suspense>"),e.outdent().write(");").outdent().write("}",false);}writeSlotRendering(e,t){e.write(`<${t} />`);}writePageSignature(e,t){e.write(this.options.language==="tsx"?`export default function ${t}(): ReactElement {`:`export default function ${t}() {`);}writePageHeader(e,t){switch(this.options.language){case "jsx":this.hasSuspenseBoundary()&&e.write("import {Suspense} from 'react';");break;case "tsx":e.write(this.hasSuspenseBoundary()?"import {type ReactElement, Suspense} from 'react';":"import type {ReactElement} from 'react';");break}e.write(`import ${t.name} from '${t.importPath}';`);}writeSlotSnippet(e,t,n){this.writeSlotHeader(e,t),this.writeSlotSignature(e,t,n),e.indent(),this.writeSlotFetch(e,t),e.write("return (").indent(),this.writeRenderingSnippet(e,t.definition,this.options.contentVariable),e.outdent().write(");").outdent().write("};");}writeSlotSignature(e,t,n){e.write(`export default ${this.isSlotFetchAsync()?"async ":""}function ${n}`,false),this.appendSlotParams(e,t),this.options.language==="tsx"&&e.append(`: ${this.isSlotFetchBlocking()?"Promise<ReactElement>":"ReactElement"}`),e.write(" {");}appendSlotParams(e,t){e.append("()");}writeRenderingSnippet(e,t,n){switch(t.type){case "number":case "text":e.append(`{${n}}`);break;case "boolean":t.label!==void 0?e.append(`{${n} ? `).appendValue(t.label.true??"Yes",{delimiter:"'"}).append(" : ").appendValue(t.label.false??"No",{delimiter:"'"}).append("}"):e.append(`{${n} ? 'Yes' : 'No'}`);break;case "list":{let r=t.itemLabel!==void 0?ht(t.itemLabel):"item";e.write("<ol>").indent().write(`{${n}.map((${r}, index) => (`).indent().write("<li key={index}>").indent();let i=o.isInline(t.items);i&&e.appendIndentation(),this.writeRenderingSnippet(e,t.items,r),i&&e.newLine(),e.outdent().write("</li>").outdent().write("))}").outdent().write("</ol>");break}case "structure":e.write("<ul>").indent();for(let[r,i]of St(t.attributes))i.private!==true&&(i.optional===true&&(e.write(`{${n}.${r} && (`),e.indent()),this.writeAttributeSnippet(e,{name:r,...i},n),i.optional===true&&(e.outdent(),e.write(")}")));e.outdent().write("</ul>");break;case "union":{let r=!n.includes(".");r&&e.write("<>").indent();for(let[i,a]of Object.entries(t.types))e.write(`{${n}._type === '${i}' && (`).indent(),this.writeRenderingSnippet(e,a,n),e.outdent().write(")}");r&&e.outdent().write("</>");break}}}writeAttributeSnippet(e,t,n){let r=t.type,i=o.escapeEntities(t.label??Jn(t.name));switch(r.type){case "boolean":case "text":case "number":{e.write("<li>",false).append(`<strong>${i}:</strong> `),this.writeRenderingSnippet(e,r,`${n}.${t.name}`),e.append("</li>").newLine();break}default:e.write("<li>").indent().write(`<strong>${i}</strong>`),this.writeRenderingSnippet(e,r,`${n}.${t.name}`),e.outdent().write("</li>");break}}static escapeEntities(e){return e.replace(/([&"<>])/g,t=>({"&":"&",'"':""","<":"<",">":">"})[t]??t)}createWriter(){return new Me(this.options.indentationSize)}static replaceVariables(e,t){return e.replace(/%name%/g,o.formatName(t,true)).replace(/%slug%/g,ws(t))}static formatName(e,t=false){return Me.formatName(e,t)}static isInline(e){return ["number","text","boolean"].includes(e.type)}};var xt=class extends It{writeSlotHeader(e){switch(this.options.language){case "jsx":e.write("import {useContent} from '@croct/plug-react';");break;case "tsx":e.write("import type {ReactElement} from 'react';"),e.write("import {useContent} from '@croct/plug-react';");break}e.newLine();}writeSlotFetch(e,t){let n=this.options.contentVariable;e.write(`const ${n} = useContent('${t.id}@${t.version}');`).newLine();}isSlotFetchAsync(){return false}isSlotFetchBlocking(){return false}hasSuspenseBoundary(){return false}};var Yn=class o extends qe{constructor(e){super(e),this.codemod=e.codemod,this.bundlers=e.bundlers,this.importResolver=e.importResolver;}async generateSlotExampleFiles(e,t){let n=await this.isTypeScriptProject(),r=this.fileSystem.joinPaths(t.configuration.paths.components,`%slug%${n?".tsx":".jsx"}`),i=this.fileSystem.joinPaths(t.configuration.paths.examples,`%slug%-example${n?".tsx":".jsx"}`);return new xt({fileSystem:this.fileSystem,language:await this.isTypeScriptProject()?"tsx":"jsx",contentVariable:"content",slotImportPath:await this.importResolver.getImportPath(r,this.fileSystem.getDirectoryName(i)),slotFilePath:r,slotComponentName:"%name%",pageFilePath:i,pageComponentName:"%name%Example"}).generate({id:e.slug,version:e.version.major,definition:e.resolvedDefinition}).files}async getInstallationPlan(e){let{configuration:t}=e,n=await this.getProjectInfo();return {dependencies:["@croct/plug-react"],tasks:this.getInstallationTasks({...e,project:n}),configuration:t}}async getProjectInfo(){let e="src",t=await this.getEnvVarProperty(),n=this.projectDirectory.get();return {typescript:await this.isTypeScriptProject(),sourceDirectory:e,provider:{file:await this.locateFile(...["App","main","index"].flatMap(r=>["js","jsx","ts","tsx"].map(i=>`${r}.${i}`)).map(r=>this.fileSystem.joinPaths(e,r)))},env:t===null?void 0:{property:t,productionFile:new Fe(this.fileSystem,this.fileSystem.joinPaths(n,".env.production")),developmentFile:new Fe(this.fileSystem,this.fileSystem.joinPaths(n,".env.development"))}}}getInstallationTasks(e){let t=[],n=e.project.env,{configuration:r}=e,i=null,a=()=>(i===null&&(i=Promise.all([this.workspaceApi.getApplication({organizationSlug:r.organization,workspaceSlug:r.workspace,applicationSlug:r.applications.development}),r.applications.production===void 0?null:this.workspaceApi.getApplication({organizationSlug:r.organization,workspaceSlug:r.workspace,applicationSlug:r.applications.production})]).then(([s,p])=>s===null?Promise.reject(new ee(`Development application ${r.applications.development} not found`,{reason:"not_found"})):{development:s.publicId,production:p?.publicId})),i);if(n!==void 0){let{developmentFile:s,productionFile:p,property:c}=n,l=c.split(".").pop();t.push({title:"Setup environment variables",task:async m=>{m.update("Setting up environment variables");try{let f=await a();await Promise.all([s.setVariable(l,f.development),f.production===void 0?Promise.resolve():p.setVariable(l,f.production)]),m.confirm("Environment variables updated");}catch(f){m.alert("Failed to update environment variables",d.formatMessage(f));}}});}return t.push({title:"Configure provider",task:async s=>{s.update("Configuring provider");let p=e.project.provider.file;try{p===null?s.alert("No root component found"):(s.update("Configuring provider"),await this.installProvider(p,{props:{appId:o.getAppIdProperty(await a(),n?.property)}}),s.confirm("Provider configured"));}catch(c){s.alert("Failed to install provider",d.formatMessage(c));}}}),t}async installProvider(e,t){await this.codemod.provider.apply(this.fileSystem.joinPaths(this.projectDirectory.get(),e),t);}async getEnvVarProperty(){for(let e of this.bundlers)if(await this.packageManager.hasDirectDependency(e.package))return `${e.prefix}CROCT_APP_ID`;return null}static getAppIdProperty(e,t){return t!==void 0?{type:"reference",path:t.split(".")}:e.production===void 0?{type:"literal",value:e.development}:{type:"ternary",condition:{operator:"===",left:{type:"reference",path:["process","env","NODE_ENV"]},right:{type:"literal",value:"production"}},consequent:{type:"literal",value:e.production},alternate:{type:"literal",value:e.development}}}};var He=class o extends d{constructor(e,t={}){super(e,t),Object.setPrototypeOf(this,o.prototype);}},Xn=class o extends He{constructor(e){super(e),Object.setPrototypeOf(this,o.prototype);}};function Ge(o,e,t){try{return parse$2(o,{...t,sourceType:"module",plugins:[...e,...t?.plugins??[]]})}catch{throw new Xn("The source code contains syntax errors.")}}function Ps(o){let e={locales:Array()},t;try{t=Ge(o,["jsx","typescript"]);}catch{return {i18n:e}}return traverse(t,{ObjectProperty:n=>{if(Ma(n.node.key)!=="i18n")return n.skip();let r=n.node.value;if(!g.isObjectExpression(r))return n.stop();for(let i of r.properties)if(g.isObjectProperty(i)&&Ma(i.key)==="locales"){let a=i.value;if(g.isArrayExpression(a))for(let s of a.elements)s!==null&&g.isStringLiteral(s)&&e.locales.push(s.value);}else if(g.isObjectProperty(i)&&Ma(i.key)==="defaultLocale"){let a=i.value;a!==null&&g.isStringLiteral(a)&&(e.defaultLocale=a.value);}return n.stop()}}),{i18n:e}}function Ma(o){return g.isIdentifier(o)?o.name:g.isStringLiteral(o)?o.value:null}var er=class extends It{constructor({fileSystem:e,router:t,...n}){super({fileSystem:e,contentVariable:t==="app"?"content":"props",...n}),this.nextOptions={router:t};}writeSlotHeader(e,t){switch(this.options.language){case "jsx":this.nextOptions.router==="app"&&(e.write("import {fetchContent} from '@croct/plug-next/server';"),e.newLine());break;case "tsx":if(e.write("import type {ReactElement} from 'react';"),this.nextOptions.router==="app"&&e.write("import {fetchContent} from '@croct/plug-next/server';"),this.nextOptions.router==="page"){e.write("import type {SlotContent} from '@croct/plug-next';"),e.newLine();let n=Me.formatName(t.id,true);e.write(`export type ${n}Props = SlotContent<'${t.id}@${t.version}'>;`);}e.newLine();break}}writeSlotFetch(e,t){if(this.nextOptions.router==="app"){let n=this.options.contentVariable;e.write(`const {${n}} = await fetchContent('${t.id}@${t.version}');`).newLine();}}writePageHeader(e,t){if(this.nextOptions.router==="app")return super.writePageHeader(e,t);let n=`${t.definition.id}@${t.definition.version}`;switch(this.options.language){case "jsx":e.write("import {fetchContent} from '@croct/plug-next/server';").write(`import ${t.name} from '${t.importPath}';`),e.newLine().write("export async function getServerSideProps(context) {").indent().write("return {").indent().write(`props: await fetchContent('${n}', {`).indent().write("route: context,").outdent().write("}),").outdent().write("}").outdent().write("}");break;case "tsx":e.write("import type {ReactElement} from 'react';"),e.write("import type {GetServerSideProps} from 'next';"),e.write("import {fetchContent} from '@croct/plug-next/server';"),e.write(`import ${t.name}, {type ${t.name}Props} from '${t.importPath}';`),e.newLine().write("type PageProps = {").indent().write(`content: ${t.name}Props,`).outdent().write("};").newLine().write("export const getServerSideProps: ",false).write("GetServerSideProps<PageProps> = async context => ({").indent().write(`props: await fetchContent('${n}', {`).indent().write("route: context,").outdent().write("}),").outdent().write("});");break}}writePageSignature(e,t){switch(this.nextOptions.router){case "app":super.writePageSignature(e,t);break;case "page":{e.write(this.options.language==="tsx"?"export default function Page({content}: PageProps): ReactElement {":"export default function Page({content}) {");break}}}appendSlotParams(e,t){if(this.nextOptions.router!=="page")return super.appendSlotParams(e,t);let n=Me.formatName(t.id,true),r=this.options.contentVariable;if(this.options.language==="jsx"){e.append(`(${r})`);return}e.append(`(${r}: ${n}Props)`);}writeSlotRendering(e,t){switch(this.nextOptions.router){case "app":super.writeSlotRendering(e,t);break;case "page":{e.write(`<${t} {...content} />`);break}}}isSlotFetchAsync(){return this.nextOptions.router==="app"}isSlotFetchBlocking(){return this.nextOptions.router==="app"}hasSuspenseBoundary(){return false}};var ne=class o extends d{constructor(e,t=[],n={}){super(e,{...n,details:n.details??t.map(r=>r.detail??r.title)}),Object.setPrototypeOf(this,o.prototype),this.problems=t;}isErrorType(e){return this.problems.some(t=>t.type===e)}isAccessDenied(e){return this.problems.some(t=>t.type==="https://croct.help/api/admin#access-denied"&&(e===void 0||t.reason===e))}};var xe=(t=>(t.DEVELOPMENT="DEVELOPMENT",t.PRODUCTION="PRODUCTION",t))(xe||{});(n=>{function o(r){switch(r){case "DEVELOPMENT":return "Development";case "PRODUCTION":return "Production"}}n.getLabel=o;function e(){return Object.values(n).filter(r=>typeof r=="string")}n.all=e;function t(r){let i=r.toUpperCase();if(!n.all().includes(i))throw new Error(`Invalid environment value "${r}".`);return i}n.fromValue=t;})(xe||={});var Ee=(n=>(n.READ_RESOURCES="RESOURCE_READ_ACCESS",n.ISSUE_TOKEN="TOKEN_ISSUE",n.EXPORT_DATA="DATA_EXPORT",n))(Ee||{});(n=>{function o(r){switch(r){case "RESOURCE_READ_ACCESS":return "Read resources";case "TOKEN_ISSUE":return "Issue tokens";case "DATA_EXPORT":return "Export data"}}n.getLabel=o;function e(){return Object.values(n).filter(r=>typeof r=="string")}n.all=e;function t(r){let i=r.toUpperCase();if(!n.all().includes(i))throw new Error(`Invalid permission value "${r}".`);return i}n.fromValue=t;})(Ee||={});var tr=class extends qe{constructor(e){super(e),this.codemod=e.codemod,this.importResolver=e.importResolver,this.userApi=e.userApi,this.applicationApi=e.applicationApi;}async generateSlotExampleFiles(e,t){let[n,r,i]=await Promise.all([this.detectRouter(),this.isTypeScriptProject(),this.isFallbackMode()]),a=await this.isTypeScriptProject(),s=this.fileSystem.joinPaths(t.configuration.paths.components,`%slug%${a?".tsx":".jsx"}`),p=this.fileSystem.joinPaths(t.configuration.paths.examples,"%slug%"),c=await this.importResolver.getImportPath(s,p),l=r?"tsx":"jsx";return (i?new xt({fileSystem:this.fileSystem,language:l,contentVariable:"content",slotImportPath:c,slotFilePath:s,slotComponentName:"%name%",pageFilePath:this.fileSystem.joinPaths(p,`index${a?".tsx":".jsx"}`),pageComponentName:"Page"}):new er({fileSystem:this.fileSystem,router:n==="page"?"page":"app",language:l,slotImportPath:c,slotFilePath:s,slotComponentName:"%name%",pageFilePath:this.fileSystem.joinPaths(p,`${n==="page"?"index":"page"}${r?".tsx":".jsx"}`),pageComponentName:"Page"})).generate({id:e.slug,version:e.version.major,definition:e.resolvedDefinition}).files}async getInstallationPlan(e){let{configuration:t,output:n}=e,[{i18n:r},i]=await Promise.all([this.getConfig(),this.getProjectInfo()]);i.fallbackMode&&n.announce({semantics:"warning",title:"Fallback mode",message:"Next.js SDK requires version 13 or newer, so React SDK will be installed instead."});let a=t.locales.filter(c=>r.locales.includes(c)||c===t.defaultLocale),s=a.length>0?a:r.locales,p=r.defaultLocale!==void 0&&s.includes(r.defaultLocale)?r.defaultLocale:t.defaultLocale;return {dependencies:[i.fallbackMode?"@croct/plug-react":"@croct/plug-next"],tasks:this.getInstallationTasks({...e,project:i}),configuration:{...t,locales:s,defaultLocale:p,paths:{...t.paths,examples:i.pageDirectory}}}}async getProjectInfo(){let[e,t,n]=await Promise.all([this.isTypeScriptProject(),this.getPageDirectory(),this.isFallbackMode()]),r={typescript:e,router:await this.detectRouter(t),sourceDirectory:t.startsWith("src")?"src":".",pageDirectory:t},[i,a]=await Promise.all([this.locateFile(...["middleware.js","middleware.ts"].map(c=>this.fileSystem.joinPaths(r.sourceDirectory,c))),this.locateFile(...(r.router==="app"?[this.fileSystem.joinPaths("app","layout.jsx"),this.fileSystem.joinPaths("app","layout.tsx")]:[this.fileSystem.joinPaths("pages","_app.jsx"),this.fileSystem.joinPaths("pages","_app.tsx")]).map(c=>this.fileSystem.joinPaths(r.sourceDirectory,c)))]),s=r.typescript?"ts":"js",p=this.projectDirectory.get();return {...r,fallbackMode:n,env:{localFile:new Fe(this.fileSystem,this.fileSystem.joinPaths(p,".env.local")),developmentFile:new Fe(this.fileSystem,this.fileSystem.joinPaths(p,".env.development")),productionFile:new Fe(this.fileSystem,this.fileSystem.joinPaths(p,".env.production"))},middleware:{file:i??this.fileSystem.joinPaths(r.sourceDirectory,`middleware.${s}`)},provider:{file:a??(r.router==="app"?this.fileSystem.joinPaths("app",`layout.${s}x`):this.fileSystem.joinPaths("pages",`_app.${s}x`))}}}getInstallationTasks(e){let t=[];return e.project.fallbackMode||t.push({title:"Configure middleware",task:async n=>{n.update("Configuring middleware");try{await this.updateCode(this.codemod.middleware,e.project.middleware.file),n.confirm("Middleware configured");}catch(r){n.alert("Failed to install middleware",d.formatMessage(r));}}}),t.push({title:"Configure provider",task:async n=>{n.update("Configuring provider");try{await this.installProvider({...e,notifier:n}),n.confirm("Provider configured");}catch(r){n.alert("Failed to install provider",d.formatMessage(r));}}}),t.push({title:"Setup environment variables",task:async n=>{n.update("Setting up environment variables");try{await this.updateEnvVariables({...e,notifier:n}),n.confirm("Environment variables updated");}catch(r){n.alert("Failed to update .env.local",d.formatMessage(r));}}}),t}installProvider(e){return this.updateCode(this.getProviderCodemod(e),e.project.provider.file,{typescript:e.project.typescript})}getProviderCodemod(e){return e.project.fallbackMode?this.codemod.fallbackProvider:e.project.router==="app"?this.codemod.appRouterProvider:this.codemod.pageRouterProvider}async updateCode(e,t,n){await e.apply(this.fileSystem.joinPaths(this.projectDirectory.get(),t),n);}async updateEnvVariables(e){let{project:{env:t},configuration:n,notifier:r}=e;if(!await t.localFile.hasVariable("CROCT_API_KEY")){r.update("Loading information");let[i,a,s]=await Promise.all([this.userApi.getUser(),this.workspaceApi.getApplication({organizationSlug:n.organization,workspaceSlug:n.workspace,applicationSlug:n.applications.development}),n.applications.production===void 0?null:this.workspaceApi.getApplication({organizationSlug:n.organization,workspaceSlug:n.workspace,applicationSlug:n.applications.production})]);if(a===null)throw new ee(`Development application \`${n.applications.development}\` not found.`,{reason:"not_found"});r.update("Creating API key");let p;try{p=await this.applicationApi.createApiKey({organizationSlug:n.organization,workspaceSlug:n.workspace,applicationSlug:a.slug,name:`${i.username} CLI`,permissions:["TOKEN_ISSUE"]});}catch(c){throw c instanceof d?new ee(c instanceof ne&&c.isAccessDenied()?"Your user does not have permission to create an API key":c.message,c.help):c}await t.localFile.setVariables({CROCT_API_KEY:p.secret}),await Promise.all([t.developmentFile.setVariables({NEXT_PUBLIC_CROCT_APP_ID:a.publicId}),s===null?Promise.resolve():t.productionFile.setVariables({NEXT_PUBLIC_CROCT_APP_ID:s.publicId})]);}}async detectRouter(e){return (e??await this.getPageDirectory()).endsWith("pages")?"page":"app"}async getPageDirectory(){return await this.locateFile("app",this.fileSystem.joinPaths("src","app"),"pages",this.fileSystem.joinPaths("src","pages"))??"app"}async getConfig(){let e=["js","mjs","ts","mts"].map(n=>`next.config.${n}`),t=await this.readFile(...e).catch(()=>null);return t===null?{i18n:{locales:[],defaultLocale:""}}:Ps(t)}async isFallbackMode(){return !await this.packageManager.hasDirectDependency("next",">=13")}};var rt=(n=>(n.NEXTJS="nextjs",n.REACT="react",n.JAVASCRIPT="javascript",n))(rt||{});(e=>{function o(t){switch(t){case "nextjs":return "Next.js";case "react":return "React";case "javascript":return "JavaScript"}}e.getName=o;})(rt||={});var nr=class{constructor(e){this.config=e;}async execute(e){let{configurationManager:t,platformProvider:n,sdkProvider:r,io:{output:i}}=this.config;if(e.override!==true&&await t.isInitialized())throw new d("Configuration file already exists, specify `override` to reconfigure.",{reason:"precondition"});let a=await n.get(),s=a!==null?`${rt.getName(a)} project`:"project";i.break(),i.announce({semantics:"neutral",title:"\u{1F44B} Welcome to Croct",alignment:"center",message:`Let's configure your ${s} to get started!`}),i.break();let p=await this.getOrganization({new:e.new==="organization"},e.organization);if(p===null)throw new d(`Organization not found: ${e.organization}`,{reason:"invalid_input"});let c=await this.getWorkspace({organization:p,new:e.new==="workspace"},e.workspace),l={organization:p,workspace:c,platform:a??"javascript",new:e.new==="application"},m=await this.getApplication({...l,environment:"DEVELOPMENT"},e.devApplication),f={organization:p.slug,workspace:c.slug,applications:{development:m.slug},defaultLocale:c.defaultLocale,locales:c.locales,slots:{},components:{},paths:{components:"",examples:""}},b=c.website??p.website??void 0;if(b!==void 0&&new URL(b).hostname!=="localhost"){let v=await this.getApplication({...l,environment:"PRODUCTION"},e.prodApplication);f.applications.production=v.slug;}let A=await r.get();if(A===null){await t.update({...f,paths:{components:"components",examples:"examples"}}),i.warn("No suitable SDK found, skipping project configuration");return}await t.update(await this.configure(A,f));}async getOrganization(e,t){let{form:n,api:r}=this.config,i=t===void 0?await n.organization.handle(e):await r.user.getOrganization(t).catch(a=>{if(a instanceof ne&&a.isAccessDenied())return null;throw a});if(i===null)throw new d(`No organization found with slug "${t}".`,{reason:"invalid_input"});return i}async getWorkspace(e,t){let{form:n,api:r}=this.config,i=t===void 0?await n.workspace.handle(e):await r.organization.getWorkspace({organizationSlug:e.organization.slug,workspaceSlug:t}).catch(a=>{if(a instanceof ne&&a.isAccessDenied())return null;throw a});if(i===null)throw new d(`No workspace found with slug "${t}".`,{reason:"invalid_input"});return i}async getApplication(e,t){let{form:n,api:r}=this.config,i=t===void 0?await n.application.handle(e):await r.workspace.getApplication({organizationSlug:e.organization.slug,workspaceSlug:e.workspace.slug,applicationSlug:t}).catch(a=>{if(a instanceof ne&&a.isAccessDenied())return null;throw a});if(i===null)throw new d(`No application found with slug "${t}".`,{reason:"invalid_input"});if(i.environment!==e.environment)throw new d(`No ${xe.getLabel(e.environment).toUpperCase()} application found with slug "${t}".`,{reason:"invalid_input"});return i}async getSlots(e,t){let{api:n,io:{output:r}}=this.config,i=r.notify("Loading slots"),a=await n.workspace.getSlots({organizationSlug:e,workspaceSlug:t});return i.stop(),Object.fromEntries(a.map(s=>[s.slug,`${s.version.major}`]))}async configure(e,t){let{skipConfirmation:n}=this.config;return e.setup({input:this.config.io.input===void 0||await n.get()?void 0:this.config.io.input,output:this.config.io.output,configuration:{...t,slots:await this.getSlots(t.organization,t.workspace)}})}};var rr=class{constructor(e){this.authenticator=e.authenticator;}async execute(e){await this.authenticator.logout(),await this.authenticator.login(e);}};var Qt=class{constructor({output:e,authenticator:t}){this.authenticator=t,this.output=e;}async execute(){await this.authenticator.logout(),this.output.confirm("Logged out");}};var it=class o extends d{constructor(e,t={}){super(e,{...t,reason:t.reason??"invalid_configuration"}),Object.setPrototypeOf(this,o.prototype);}};var ir=class o{static{this.CONFIGURATION_SCHEMA="https://schema.croct.com/json/v1/project.json";}constructor({fileSystem:e,projectDirectory:t,validator:n}){this.fileSystem=e,this.projectDirectory=t,this.validator=n;}isInitialized(){return this.fileSystem.exists(this.getConfigurationFilePath())}async load(){let e=await this.loadConfigurationFile();if(e.configuration===null)throw new it("Project configuration not found.",{reason:"not_found",suggestions:["Run `init` command to initialize the project"]});return e.configuration}async update(e){return this.updateConfigurationFile(await this.validateConfiguration(e))}async updateConfigurationFile(e){let t=await this.loadConfigurationFile(),r=this.applyConfigurationChanges(t,e).toString({indentationCharacter:"space",object:{indentationSize:2,leadingIndentation:true,trailingIndentation:true,entryIndentation:true,colonSpacing:true,commaSpacing:true},array:{indentationSize:2,entryIndentation:true,leadingIndentation:true,trailingIndentation:true,colonSpacing:true,commaSpacing:true}});try{await this.fileSystem.writeTextFile(t.path,r,{overwrite:!0});}catch{throw new Error(`Unable to write configuration file ${t.path}.`)}return e}applyConfigurationChanges(e,t){if(e.configuration===null||e.source===null)return JsonObjectNode$1.of({$schema:o.CONFIGURATION_SCHEMA,...t});let n=JsonParser$1.parse(e.source,JsonObjectNode$1);return n.update({$schema:n.has("$schema")?n.get("$schema").toJSON():void 0,...t}).cast(JsonObjectNode$1)}async loadConfigurationFile(){let e={path:this.getConfigurationFilePath(),source:null,configuration:null},t;try{e.source=await this.fileSystem.readTextFile(e.path),t=JsonParser$1.parse(e.source).toJSON();}catch{return e}return t!==null&&(e.configuration=await this.validateConfiguration(t,e),e.configuration?.$schema!==void 0&&delete e.configuration?.$schema),e}getConfigurationFilePath(){return this.fileSystem.joinPaths(this.projectDirectory.get(),"croct.json")}async validateConfiguration(e,t){let n=await this.validator.validate(e);if(!n.valid){let r=n.violations[0];throw new it(r.message,{details:[...t!==void 0?[`File: file://${t.path.replace(/\\/g,"/")}`]:[],`Violation path: ${r.path}`]})}return n.data}};var Bt=class{constructor(e){this.configuration=e;}async execute(e,...[t]){let{tokenProvider:n,endpoint:r}=this.configuration,i=n!==void 0?await n.getToken():null,a=await fetch(r,{method:"POST",headers:{accept:"application/json","content-type":"application/json",...i!==null?{Authorization:`Bearer ${i}`}:{}},body:JSON.stringify({query:e,variables:t})});return a.json().then(s=>{let{data:p,errors:c}=s;if(c!==void 0)throw new ne(c[0].message.replace(/"/g,"`"),c.map(({extensions:l})=>({...l,detail:l.detail?.replace(/"/g,"`")})));return {data:p,headers:a.headers}})}};function $a(o,e){return o.slice(0,o.indexOf("-",e-1)===e-1?e-1:e)}function*Yt({baseName:o,alwaysSuffixed:e=false}){let t=o.normalize("NFD").toLowerCase().replace(/[^a-z ]/g,"").trim().split(/\s+/);t.length===0&&t.push(String.fromCharCode(97+Math.floor(Math.random()*26))+Math.random().toString(36).substring(2,14));let n=t.slice(0,2).join("-");for(e||(yield $a(n,30),n.length<29&&t.length>2&&(yield $a(t.join("-"),30)));;){let r=Math.floor(Math.random()*1e4).toString();yield `${$a(n,30-r.length-1)}-${r}`;}}function ot(o){let{baseName:e,query:t,client:n,alwaysSuffixed:r}=o;return Tl({baseName:e,alwaysSuffixed:r},async i=>{let a=[i.next().value,i.next().value,i.next().value],{data:{checkAvailability:s}}=await n.execute(t,{...o.variables??{},slugFirstOption:a[0],slugSecondOption:a[1],slugThirdOption:a[2]}),p=[s.slugFirstOption,s.slugSecondOption,s.slugThirdOption];return a.find((c,l)=>p[l])??null})}async function Tl(o,e){let t=Yt(o),n;do n=await e(t);while(n===null);return n}var E=class extends String{constructor(e,t){super(e),this.value=e,this.__meta__=t;}toString(){return this.value}},ks=new E(`
|
|
106
|
+
`}${e}=${t}`)}async write(e){await this.fileSystem.writeTextFile(this.path,e,{overwrite:true});}async read(){return await this.exists()?this.fileSystem.readTextFile(this.path):""}static escapeRegex(e){return e.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&")}};var It=class o{constructor({fileSystem:e,...t}){this.options=t,this.fileSystem=e;}generate(e){let t=o.replaceVariables(this.options.slotFilePath,e.id),n=o.replaceVariables(this.options.slotComponentName,e.id);return {files:[this.generatePageFile(e,{name:n,path:t,importPath:o.replaceVariables(this.options.slotImportPath,e.id),definition:e}),this.generateSlotFile(e,t,n)]}}generatePageFile(e,t){let n=this.createWriter(),r=o.replaceVariables(this.options.pageFilePath,e.id),i=o.replaceVariables(this.options.pageComponentName,e.id);return this.writePageSnippet(n,i,t),{path:r,language:this.options.language,code:n.toString()}}generateSlotFile(e,t,n){let r=this.createWriter();return this.writeSlotSnippet(r,e,n),{path:t,language:this.options.language,code:r.toString()}}writePageSnippet(e,t,n){this.writePageHeader(e,n),e.newLine(),this.writePageSignature(e,t),e.indent().write("return (").indent(),this.hasSuspenseBoundary()&&e.write('<Suspense fallback="\u2728 Personalizing...">').indent(),this.writeSlotRendering(e,n.name),this.hasSuspenseBoundary()&&e.outdent().write("</Suspense>"),e.outdent().write(");").outdent().write("}",false);}writeSlotRendering(e,t){e.write(`<${t} />`);}writePageSignature(e,t){e.write(this.options.language==="tsx"?`export default function ${t}(): ReactElement {`:`export default function ${t}() {`);}writePageHeader(e,t){switch(this.options.language){case "jsx":this.hasSuspenseBoundary()&&e.write("import {Suspense} from 'react';");break;case "tsx":e.write(this.hasSuspenseBoundary()?"import {type ReactElement, Suspense} from 'react';":"import type {ReactElement} from 'react';");break}e.write(`import ${t.name} from '${t.importPath}';`);}writeSlotSnippet(e,t,n){this.writeSlotHeader(e,t),this.writeSlotSignature(e,t,n),e.indent(),this.writeSlotFetch(e,t),e.write("return (").indent(),this.writeRenderingSnippet(e,t.definition,this.options.contentVariable),e.outdent().write(");").outdent().write("};");}writeSlotSignature(e,t,n){e.write(`export default ${this.isSlotFetchAsync()?"async ":""}function ${n}`,false),this.appendSlotParams(e,t),this.options.language==="tsx"&&e.append(`: ${this.isSlotFetchBlocking()?"Promise<ReactElement>":"ReactElement"}`),e.write(" {");}appendSlotParams(e,t){e.append("()");}writeRenderingSnippet(e,t,n){switch(t.type){case "number":case "text":e.append(`{${n}}`);break;case "boolean":t.label!==void 0?e.append(`{${n} ? `).appendValue(t.label.true??"Yes",{delimiter:"'"}).append(" : ").appendValue(t.label.false??"No",{delimiter:"'"}).append("}"):e.append(`{${n} ? 'Yes' : 'No'}`);break;case "list":{let r=t.itemLabel!==void 0?ht(t.itemLabel):"item";e.write("<ol>").indent().write(`{${n}.map((${r}, index) => (`).indent().write("<li key={index}>").indent();let i=o.isInline(t.items);i&&e.appendIndentation(),this.writeRenderingSnippet(e,t.items,r),i&&e.newLine(),e.outdent().write("</li>").outdent().write("))}").outdent().write("</ol>");break}case "structure":e.write("<ul>").indent();for(let[r,i]of St(t.attributes))i.private!==true&&(i.optional===true&&(e.write(`{${n}.${r} && (`),e.indent()),this.writeAttributeSnippet(e,{name:r,...i},n),i.optional===true&&(e.outdent(),e.write(")}")));e.outdent().write("</ul>");break;case "union":{let r=!n.includes(".");r&&e.write("<>").indent();for(let[i,a]of Object.entries(t.types))e.write(`{${n}._type === '${i}' && (`).indent(),this.writeRenderingSnippet(e,a,n),e.outdent().write(")}");r&&e.outdent().write("</>");break}}}writeAttributeSnippet(e,t,n){let r=t.type,i=o.escapeEntities(t.label??Jn(t.name));switch(r.type){case "boolean":case "text":case "number":{e.write("<li>",false).append(`<strong>${i}:</strong> `),this.writeRenderingSnippet(e,r,`${n}.${t.name}`),e.append("</li>").newLine();break}default:e.write("<li>").indent().write(`<strong>${i}</strong>`),this.writeRenderingSnippet(e,r,`${n}.${t.name}`),e.outdent().write("</li>");break}}static escapeEntities(e){return e.replace(/([&"<>])/g,t=>({"&":"&",'"':""","<":"<",">":">"})[t]??t)}createWriter(){return new Me(this.options.indentationSize)}static replaceVariables(e,t){return e.replace(/%name%/g,o.formatName(t,true)).replace(/%slug%/g,ws(t))}static formatName(e,t=false){return Me.formatName(e,t)}static isInline(e){return ["number","text","boolean"].includes(e.type)}};var xt=class extends It{writeSlotHeader(e){switch(this.options.language){case "jsx":e.write("import {useContent} from '@croct/plug-react';");break;case "tsx":e.write("import type {ReactElement} from 'react';"),e.write("import {useContent} from '@croct/plug-react';");break}e.newLine();}writeSlotFetch(e,t){let n=this.options.contentVariable;e.write(`const ${n} = useContent('${t.id}@${t.version}');`).newLine();}isSlotFetchAsync(){return false}isSlotFetchBlocking(){return false}hasSuspenseBoundary(){return false}};var Yn=class o extends qe{constructor(e){super(e),this.codemod=e.codemod,this.bundlers=e.bundlers,this.importResolver=e.importResolver;}async generateSlotExampleFiles(e,t){let n=await this.isTypeScriptProject(),r=this.fileSystem.joinPaths(t.configuration.paths.components,`%slug%${n?".tsx":".jsx"}`),i=this.fileSystem.joinPaths(t.configuration.paths.examples,`%slug%-example${n?".tsx":".jsx"}`);return new xt({fileSystem:this.fileSystem,language:await this.isTypeScriptProject()?"tsx":"jsx",contentVariable:"content",slotImportPath:await this.importResolver.getImportPath(r,this.fileSystem.getDirectoryName(i)),slotFilePath:r,slotComponentName:"%name%",pageFilePath:i,pageComponentName:"%name%Example"}).generate({id:e.slug,version:e.version.major,definition:e.resolvedDefinition}).files}async getInstallationPlan(e){let{configuration:t}=e,n=await this.getProjectInfo();return {dependencies:["@croct/plug-react"],tasks:this.getInstallationTasks({...e,project:n}),configuration:t}}async getProjectInfo(){let e="src",t=await this.getEnvVarProperty(),n=this.projectDirectory.get();return {typescript:await this.isTypeScriptProject(),sourceDirectory:e,provider:{file:await this.locateFile(...["App","main","index"].flatMap(r=>["js","jsx","ts","tsx"].map(i=>`${r}.${i}`)).map(r=>this.fileSystem.joinPaths(e,r)))},env:t===null?void 0:{property:t,productionFile:new Fe(this.fileSystem,this.fileSystem.joinPaths(n,".env.production")),developmentFile:new Fe(this.fileSystem,this.fileSystem.joinPaths(n,".env.development"))}}}getInstallationTasks(e){let t=[],n=e.project.env,{configuration:r}=e,i=null,a=()=>(i===null&&(i=Promise.all([this.workspaceApi.getApplication({organizationSlug:r.organization,workspaceSlug:r.workspace,applicationSlug:r.applications.development}),r.applications.production===void 0?null:this.workspaceApi.getApplication({organizationSlug:r.organization,workspaceSlug:r.workspace,applicationSlug:r.applications.production})]).then(([s,p])=>s===null?Promise.reject(new ee(`Development application ${r.applications.development} not found`,{reason:"not_found"})):{development:s.publicId,production:p?.publicId})),i);if(n!==void 0){let{developmentFile:s,productionFile:p,property:c}=n,l=c.split(".").pop();t.push({title:"Setup environment variables",task:async m=>{m.update("Setting up environment variables");try{let f=await a();await Promise.all([s.setVariable(l,f.development),f.production===void 0?Promise.resolve():p.setVariable(l,f.production)]),m.confirm("Environment variables updated");}catch(f){m.alert("Failed to update environment variables",d.formatMessage(f));}}});}return t.push({title:"Configure provider",task:async s=>{s.update("Configuring provider");let p=e.project.provider.file;try{p===null?s.alert("No root component found"):(s.update("Configuring provider"),await this.installProvider(p,{props:{appId:o.getAppIdProperty(await a(),n?.property)}}),s.confirm("Provider configured"));}catch(c){s.alert("Failed to install provider",d.formatMessage(c));}}}),t}async installProvider(e,t){await this.codemod.provider.apply(this.fileSystem.joinPaths(this.projectDirectory.get(),e),t);}async getEnvVarProperty(){for(let e of this.bundlers)if(await this.packageManager.hasDirectDependency(e.package))return `${e.prefix}CROCT_APP_ID`;return null}static getAppIdProperty(e,t){return t!==void 0?{type:"reference",path:t.split(".")}:e.production===void 0?{type:"literal",value:e.development}:{type:"ternary",condition:{operator:"===",left:{type:"reference",path:["process","env","NODE_ENV"]},right:{type:"literal",value:"production"}},consequent:{type:"literal",value:e.production},alternate:{type:"literal",value:e.development}}}};var He=class o extends d{constructor(e,t={}){super(e,t),Object.setPrototypeOf(this,o.prototype);}},Xn=class o extends He{constructor(e){super(e),Object.setPrototypeOf(this,o.prototype);}};function Ge(o,e,t){try{return parse$2(o,{...t,sourceType:"module",plugins:[...e,...t?.plugins??[]]})}catch{throw new Xn("The source code contains syntax errors.")}}function Ps(o){let e={locales:Array()},t;try{t=Ge(o,["jsx","typescript"]);}catch{return {i18n:e}}return traverse(t,{ObjectProperty:n=>{if(Ma(n.node.key)!=="i18n")return n.skip();let r=n.node.value;if(!g.isObjectExpression(r))return n.stop();for(let i of r.properties)if(g.isObjectProperty(i)&&Ma(i.key)==="locales"){let a=i.value;if(g.isArrayExpression(a))for(let s of a.elements)s!==null&&g.isStringLiteral(s)&&e.locales.push(s.value);}else if(g.isObjectProperty(i)&&Ma(i.key)==="defaultLocale"){let a=i.value;a!==null&&g.isStringLiteral(a)&&(e.defaultLocale=a.value);}return n.stop()}}),{i18n:e}}function Ma(o){return g.isIdentifier(o)?o.name:g.isStringLiteral(o)?o.value:null}var er=class extends It{constructor({fileSystem:e,router:t,...n}){super({fileSystem:e,contentVariable:t==="app"?"content":"props",...n}),this.nextOptions={router:t};}writeSlotHeader(e,t){switch(this.options.language){case "jsx":this.nextOptions.router==="app"&&(e.write("import {fetchContent} from '@croct/plug-next/server';"),e.newLine());break;case "tsx":if(e.write("import type {ReactElement} from 'react';"),this.nextOptions.router==="app"&&e.write("import {fetchContent} from '@croct/plug-next/server';"),this.nextOptions.router==="page"){e.write("import type {SlotContent} from '@croct/plug-next';"),e.newLine();let n=Me.formatName(t.id,true);e.write(`export type ${n}Props = SlotContent<'${t.id}@${t.version}'>;`);}e.newLine();break}}writeSlotFetch(e,t){if(this.nextOptions.router==="app"){let n=this.options.contentVariable;e.write(`const {${n}} = await fetchContent('${t.id}@${t.version}');`).newLine();}}writePageHeader(e,t){if(this.nextOptions.router==="app")return super.writePageHeader(e,t);let n=`${t.definition.id}@${t.definition.version}`;switch(this.options.language){case "jsx":e.write("import {fetchContent} from '@croct/plug-next/server';").write(`import ${t.name} from '${t.importPath}';`),e.newLine().write("export async function getServerSideProps(context) {").indent().write("return {").indent().write(`props: await fetchContent('${n}', {`).indent().write("route: context,").outdent().write("}),").outdent().write("}").outdent().write("}");break;case "tsx":e.write("import type {ReactElement} from 'react';"),e.write("import type {GetServerSideProps} from 'next';"),e.write("import {fetchContent} from '@croct/plug-next/server';"),e.write(`import ${t.name}, {type ${t.name}Props} from '${t.importPath}';`),e.newLine().write("type PageProps = {").indent().write(`content: ${t.name}Props,`).outdent().write("};").newLine().write("export const getServerSideProps: ",false).write("GetServerSideProps<PageProps> = async context => ({").indent().write(`props: await fetchContent('${n}', {`).indent().write("route: context,").outdent().write("}),").outdent().write("});");break}}writePageSignature(e,t){switch(this.nextOptions.router){case "app":super.writePageSignature(e,t);break;case "page":{e.write(this.options.language==="tsx"?"export default function Page({content}: PageProps): ReactElement {":"export default function Page({content}) {");break}}}appendSlotParams(e,t){if(this.nextOptions.router!=="page")return super.appendSlotParams(e,t);let n=Me.formatName(t.id,true),r=this.options.contentVariable;if(this.options.language==="jsx"){e.append(`(${r})`);return}e.append(`(${r}: ${n}Props)`);}writeSlotRendering(e,t){switch(this.nextOptions.router){case "app":super.writeSlotRendering(e,t);break;case "page":{e.write(`<${t} {...content} />`);break}}}isSlotFetchAsync(){return this.nextOptions.router==="app"}isSlotFetchBlocking(){return this.nextOptions.router==="app"}hasSuspenseBoundary(){return false}};var ne=class o extends d{constructor(e,t=[],n={}){super(e,{...n,details:n.details??t.map(r=>r.detail??r.title)}),Object.setPrototypeOf(this,o.prototype),this.problems=t;}isErrorType(e){return this.problems.some(t=>t.type===e)}isAccessDenied(e){return this.problems.some(t=>t.type==="https://croct.help/api/admin#access-denied"&&(e===void 0||t.reason===e))}};var xe=(t=>(t.DEVELOPMENT="DEVELOPMENT",t.PRODUCTION="PRODUCTION",t))(xe||{});(n=>{function o(r){switch(r){case "DEVELOPMENT":return "Development";case "PRODUCTION":return "Production"}}n.getLabel=o;function e(){return Object.values(n).filter(r=>typeof r=="string")}n.all=e;function t(r){let i=r.toUpperCase();if(!n.all().includes(i))throw new Error(`Invalid environment value "${r}".`);return i}n.fromValue=t;})(xe||={});var Ee=(n=>(n.READ_RESOURCES="RESOURCE_READ_ACCESS",n.ISSUE_TOKEN="TOKEN_ISSUE",n.EXPORT_DATA="DATA_EXPORT",n))(Ee||{});(n=>{function o(r){switch(r){case "RESOURCE_READ_ACCESS":return "Read resources";case "TOKEN_ISSUE":return "Issue tokens";case "DATA_EXPORT":return "Export data"}}n.getLabel=o;function e(){return Object.values(n).filter(r=>typeof r=="string")}n.all=e;function t(r){let i=r.toUpperCase();if(!n.all().includes(i))throw new Error(`Invalid permission value "${r}".`);return i}n.fromValue=t;})(Ee||={});var tr=class extends qe{constructor(e){super(e),this.codemod=e.codemod,this.importResolver=e.importResolver,this.userApi=e.userApi,this.applicationApi=e.applicationApi;}async generateSlotExampleFiles(e,t){let[n,r,i]=await Promise.all([this.detectRouter(),this.isTypeScriptProject(),this.isFallbackMode()]),a=await this.isTypeScriptProject(),s=this.fileSystem.joinPaths(t.configuration.paths.components,`%slug%${a?".tsx":".jsx"}`),p=this.fileSystem.joinPaths(t.configuration.paths.examples,"%slug%"),c=await this.importResolver.getImportPath(s,p),l=r?"tsx":"jsx";return (i?new xt({fileSystem:this.fileSystem,language:l,contentVariable:"content",slotImportPath:c,slotFilePath:s,slotComponentName:"%name%",pageFilePath:this.fileSystem.joinPaths(p,`index${a?".tsx":".jsx"}`),pageComponentName:"Page"}):new er({fileSystem:this.fileSystem,router:n==="page"?"page":"app",language:l,slotImportPath:c,slotFilePath:s,slotComponentName:"%name%",pageFilePath:this.fileSystem.joinPaths(p,`${n==="page"?"index":"page"}${r?".tsx":".jsx"}`),pageComponentName:"Page"})).generate({id:e.slug,version:e.version.major,definition:e.resolvedDefinition}).files}async getInstallationPlan(e){let{configuration:t,output:n}=e,[{i18n:r},i]=await Promise.all([this.getConfig(),this.getProjectInfo()]);i.fallbackMode&&n.announce({semantics:"warning",title:"Fallback mode",message:"Next.js SDK requires version 13 or newer, so React SDK will be installed instead."});let a=t.locales.filter(c=>r.locales.includes(c)||c===t.defaultLocale),s=a.length>0?a:r.locales,p=r.defaultLocale!==void 0&&s.includes(r.defaultLocale)?r.defaultLocale:t.defaultLocale;return {dependencies:[i.fallbackMode?"@croct/plug-react":"@croct/plug-next"],tasks:this.getInstallationTasks({...e,project:i}),configuration:{...t,locales:s,defaultLocale:p,paths:{...t.paths,examples:i.pageDirectory}}}}async getProjectInfo(){let[e,t,n]=await Promise.all([this.isTypeScriptProject(),this.getPageDirectory(),this.isFallbackMode()]),r={typescript:e,router:await this.detectRouter(t),sourceDirectory:t.startsWith("src")?"src":".",pageDirectory:t},[i,a]=await Promise.all([this.locateFile(...["middleware.js","middleware.ts"].map(c=>this.fileSystem.joinPaths(r.sourceDirectory,c))),this.locateFile(...(r.router==="app"?[this.fileSystem.joinPaths("app","layout.jsx"),this.fileSystem.joinPaths("app","layout.tsx")]:[this.fileSystem.joinPaths("pages","_app.jsx"),this.fileSystem.joinPaths("pages","_app.tsx")]).map(c=>this.fileSystem.joinPaths(r.sourceDirectory,c)))]),s=r.typescript?"ts":"js",p=this.projectDirectory.get();return {...r,fallbackMode:n,env:{localFile:new Fe(this.fileSystem,this.fileSystem.joinPaths(p,".env.local")),developmentFile:new Fe(this.fileSystem,this.fileSystem.joinPaths(p,".env.development")),productionFile:new Fe(this.fileSystem,this.fileSystem.joinPaths(p,".env.production"))},middleware:{file:i??this.fileSystem.joinPaths(r.sourceDirectory,`middleware.${s}`)},provider:{file:a??(r.router==="app"?this.fileSystem.joinPaths("app",`layout.${s}x`):this.fileSystem.joinPaths("pages",`_app.${s}x`))}}}getInstallationTasks(e){let t=[];return e.project.fallbackMode||t.push({title:"Configure middleware",task:async n=>{n.update("Configuring middleware");try{await this.updateCode(this.codemod.middleware,e.project.middleware.file),n.confirm("Middleware configured");}catch(r){n.alert("Failed to install middleware",d.formatMessage(r));}}}),t.push({title:"Configure provider",task:async n=>{n.update("Configuring provider");try{await this.installProvider({...e,notifier:n}),n.confirm("Provider configured");}catch(r){n.alert("Failed to install provider",d.formatMessage(r));}}}),t.push({title:"Setup environment variables",task:async n=>{n.update("Setting up environment variables");try{await this.updateEnvVariables({...e,notifier:n}),n.confirm("Environment variables updated");}catch(r){n.alert("Failed to update .env.local",d.formatMessage(r));}}}),t}installProvider(e){return this.updateCode(this.getProviderCodemod(e),e.project.provider.file,{typescript:e.project.typescript})}getProviderCodemod(e){return e.project.fallbackMode?this.codemod.fallbackProvider:e.project.router==="app"?this.codemod.appRouterProvider:this.codemod.pageRouterProvider}async updateCode(e,t,n){await e.apply(this.fileSystem.joinPaths(this.projectDirectory.get(),t),n);}async updateEnvVariables(e){let{project:{env:t},configuration:n,notifier:r}=e;if(!await t.localFile.hasVariable("CROCT_API_KEY")){r.update("Loading information");let[i,a,s]=await Promise.all([this.userApi.getUser(),this.workspaceApi.getApplication({organizationSlug:n.organization,workspaceSlug:n.workspace,applicationSlug:n.applications.development}),n.applications.production===void 0?null:this.workspaceApi.getApplication({organizationSlug:n.organization,workspaceSlug:n.workspace,applicationSlug:n.applications.production})]);if(a===null)throw new ee(`Development application \`${n.applications.development}\` not found.`,{reason:"not_found"});r.update("Creating API key");let p;try{p=await this.applicationApi.createApiKey({organizationSlug:n.organization,workspaceSlug:n.workspace,applicationSlug:a.slug,name:`${i.username} CLI`,permissions:["TOKEN_ISSUE"]});}catch(c){throw c instanceof d?new ee(c instanceof ne&&c.isAccessDenied()?"Your user does not have permission to create an API key":c.message,c.help):c}await t.localFile.setVariables({CROCT_API_KEY:p.secret}),await Promise.all([t.developmentFile.setVariables({NEXT_PUBLIC_CROCT_APP_ID:a.publicId}),s===null?Promise.resolve():t.productionFile.setVariables({NEXT_PUBLIC_CROCT_APP_ID:s.publicId})]);}}async detectRouter(e){return (e??await this.getPageDirectory()).endsWith("pages")?"page":"app"}async getPageDirectory(){return await this.locateFile("app",this.fileSystem.joinPaths("src","app"),"pages",this.fileSystem.joinPaths("src","pages"))??"app"}async getConfig(){let e=["js","mjs","ts","mts"].map(n=>`next.config.${n}`),t=await this.readFile(...e).catch(()=>null);return t===null?{i18n:{locales:[],defaultLocale:""}}:Ps(t)}async isFallbackMode(){return !await this.packageManager.hasDirectDependency("next",">=13")}};var rt=(n=>(n.NEXTJS="nextjs",n.REACT="react",n.JAVASCRIPT="javascript",n))(rt||{});(e=>{function o(t){switch(t){case "nextjs":return "Next.js";case "react":return "React";case "javascript":return "JavaScript"}}e.getName=o;})(rt||={});var nr=class{constructor(e){this.config=e;}async execute(e){let{configurationManager:t,platformProvider:n,sdkProvider:r,io:{output:i}}=this.config;if(e.override!==true&&await t.isInitialized())throw new d("Configuration file already exists, specify `override` to reconfigure.",{reason:"precondition"});let a=await n.get(),s=a!==null?`${rt.getName(a)} project`:"project";i.break(),i.announce({semantics:"neutral",title:"\u{1F44B} Welcome to Croct",alignment:"center",message:`Let's configure your ${s} to get started!`}),i.break();let p=await this.getOrganization({new:e.new==="organization"},e.organization);if(p===null)throw new d(`Organization not found: ${e.organization}`,{reason:"invalid_input"});let c=await this.getWorkspace({organization:p,new:e.new==="workspace"},e.workspace),l={organization:p,workspace:c,platform:a??"javascript",new:e.new==="application"},m=await this.getApplication({...l,environment:"DEVELOPMENT"},e.devApplication),f={organization:p.slug,workspace:c.slug,applications:{development:m.slug},defaultLocale:c.defaultLocale,locales:c.locales,slots:{},components:{},paths:{components:"",examples:""}},b=c.website??p.website??void 0;if(b!==void 0&&new URL(b).hostname!=="localhost"){let I=await this.getApplication({...l,environment:"PRODUCTION"},e.prodApplication);f.applications.production=I.slug;}let A=await r.get();if(A===null){await t.update({...f,paths:{components:"components",examples:"examples"}}),i.warn("No suitable SDK found, skipping project configuration");return}await t.update(await this.configure(A,f));}async getOrganization(e,t){let{form:n,api:r}=this.config,i=t===void 0?await n.organization.handle(e):await r.user.getOrganization(t).catch(a=>{if(a instanceof ne&&a.isAccessDenied())return null;throw a});if(i===null)throw new d(`No organization found with slug "${t}".`,{reason:"invalid_input"});return i}async getWorkspace(e,t){let{form:n,api:r}=this.config,i=t===void 0?await n.workspace.handle(e):await r.organization.getWorkspace({organizationSlug:e.organization.slug,workspaceSlug:t}).catch(a=>{if(a instanceof ne&&a.isAccessDenied())return null;throw a});if(i===null)throw new d(`No workspace found with slug "${t}".`,{reason:"invalid_input"});return i}async getApplication(e,t){let{form:n,api:r}=this.config,i=t===void 0?await n.application.handle(e):await r.workspace.getApplication({organizationSlug:e.organization.slug,workspaceSlug:e.workspace.slug,applicationSlug:t}).catch(a=>{if(a instanceof ne&&a.isAccessDenied())return null;throw a});if(i===null)throw new d(`No application found with slug "${t}".`,{reason:"invalid_input"});if(i.environment!==e.environment)throw new d(`No ${xe.getLabel(e.environment).toUpperCase()} application found with slug "${t}".`,{reason:"invalid_input"});return i}async getSlots(e,t){let{api:n,io:{output:r}}=this.config,i=r.notify("Loading slots"),a=await n.workspace.getSlots({organizationSlug:e,workspaceSlug:t});return i.stop(),Object.fromEntries(a.map(s=>[s.slug,`${s.version.major}`]))}async configure(e,t){let{skipConfirmation:n}=this.config;return e.setup({input:this.config.io.input===void 0||await n.get()?void 0:this.config.io.input,output:this.config.io.output,configuration:{...t,slots:await this.getSlots(t.organization,t.workspace)}})}};var rr=class{constructor(e){this.authenticator=e.authenticator;}async execute(e){await this.authenticator.logout(),await this.authenticator.login(e);}};var Qt=class{constructor({output:e,authenticator:t}){this.authenticator=t,this.output=e;}async execute(){await this.authenticator.logout(),this.output.confirm("Logged out");}};var it=class o extends d{constructor(e,t={}){super(e,{...t,reason:t.reason??"invalid_configuration"}),Object.setPrototypeOf(this,o.prototype);}};var ir=class o{static{this.CONFIGURATION_SCHEMA="https://schema.croct.com/json/v1/project.json";}constructor({fileSystem:e,projectDirectory:t,validator:n}){this.fileSystem=e,this.projectDirectory=t,this.validator=n;}isInitialized(){return this.fileSystem.exists(this.getConfigurationFilePath())}async load(){let e=await this.loadConfigurationFile();if(e.configuration===null)throw new it("Project configuration not found.",{reason:"not_found",suggestions:["Run `init` command to initialize the project"]});return e.configuration}async update(e){return this.updateConfigurationFile(await this.validateConfiguration(e))}async updateConfigurationFile(e){let t=await this.loadConfigurationFile(),r=this.applyConfigurationChanges(t,e).toString({indentationCharacter:"space",object:{indentationSize:2,leadingIndentation:true,trailingIndentation:true,entryIndentation:true,colonSpacing:true,commaSpacing:true},array:{indentationSize:2,entryIndentation:true,leadingIndentation:true,trailingIndentation:true,colonSpacing:true,commaSpacing:true}});try{await this.fileSystem.writeTextFile(t.path,r,{overwrite:!0});}catch{throw new Error(`Unable to write configuration file ${t.path}.`)}return e}applyConfigurationChanges(e,t){if(e.configuration===null||e.source===null)return JsonObjectNode$1.of({$schema:o.CONFIGURATION_SCHEMA,...t});let n=JsonParser$1.parse(e.source,JsonObjectNode$1);return n.update({$schema:n.has("$schema")?n.get("$schema").toJSON():void 0,...t}).cast(JsonObjectNode$1)}async loadConfigurationFile(){let e={path:this.getConfigurationFilePath(),source:null,configuration:null},t;try{e.source=await this.fileSystem.readTextFile(e.path),t=JsonParser$1.parse(e.source).toJSON();}catch{return e}return t!==null&&(e.configuration=await this.validateConfiguration(t,e),e.configuration?.$schema!==void 0&&delete e.configuration?.$schema),e}getConfigurationFilePath(){return this.fileSystem.joinPaths(this.projectDirectory.get(),"croct.json")}async validateConfiguration(e,t){let n=await this.validator.validate(e);if(!n.valid){let r=n.violations[0];throw new it(r.message,{details:[...t!==void 0?[`File: file://${t.path.replace(/\\/g,"/")}`]:[],`Violation path: ${r.path}`]})}return n.data}};var Bt=class{constructor(e){this.configuration=e;}async execute(e,...[t]){let{tokenProvider:n,endpoint:r}=this.configuration,i=n!==void 0?await n.getToken():null,a=await fetch(r,{method:"POST",headers:{accept:"application/json","content-type":"application/json",...i!==null?{Authorization:`Bearer ${i}`}:{}},body:JSON.stringify({query:e,variables:t})});return a.json().then(s=>{let{data:p,errors:c}=s;if(c!==void 0)throw new ne(c[0].message.replace(/"/g,"`"),c.map(({extensions:l})=>({...l,detail:l.detail?.replace(/"/g,"`")})));return {data:p,headers:a.headers}})}};function $a(o,e){return o.slice(0,o.indexOf("-",e-1)===e-1?e-1:e)}function*Yt({baseName:o,alwaysSuffixed:e=false}){let t=o.normalize("NFD").toLowerCase().replace(/[^a-z ]/g,"").trim().split(/\s+/);t.length===0&&t.push(String.fromCharCode(97+Math.floor(Math.random()*26))+Math.random().toString(36).substring(2,14));let n=t.slice(0,2).join("-");for(e||(yield $a(n,30),n.length<29&&t.length>2&&(yield $a(t.join("-"),30)));;){let r=Math.floor(Math.random()*1e4).toString();yield `${$a(n,30-r.length-1)}-${r}`;}}function ot(o){let{baseName:e,query:t,client:n,alwaysSuffixed:r}=o;return Tl({baseName:e,alwaysSuffixed:r},async i=>{let a=[i.next().value,i.next().value,i.next().value],{data:{checkAvailability:s}}=await n.execute(t,{...o.variables??{},slugFirstOption:a[0],slugSecondOption:a[1],slugThirdOption:a[2]}),p=[s.slugFirstOption,s.slugSecondOption,s.slugThirdOption];return a.find((c,l)=>p[l])??null})}async function Tl(o,e){let t=Yt(o),n;do n=await e(t);while(n===null);return n}var E=class extends String{constructor(e,t){super(e),this.value=e,this.__meta__=t;}toString(){return this.value}},ks=new E(`
|
|
107
107
|
query ApplicationSlugAvailability($workspaceId: WorkspaceId!, $slugFirstOption: ReadableId!, $slugSecondOption: ReadableId!, $slugThirdOption: ReadableId!) {
|
|
108
108
|
checkAvailability {
|
|
109
109
|
slugFirstOption: applicationSlug(
|
|
@@ -902,7 +902,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
902
902
|
}
|
|
903
903
|
}
|
|
904
904
|
}
|
|
905
|
-
`);var Dl={"\n query ApplicationSlugAvailability(\n $workspaceId: WorkspaceId!\n $slugFirstOption: ReadableId!\n $slugSecondOption: ReadableId!\n $slugThirdOption: ReadableId!\n ) {\n checkAvailability {\n slugFirstOption: applicationSlug(workspaceId: $workspaceId, slug: $slugFirstOption)\n slugSecondOption: applicationSlug(workspaceId: $workspaceId, slug: $slugSecondOption)\n slugThirdOption: applicationSlug(workspaceId: $workspaceId, slug: $slugThirdOption)\n }\n }\n":ks,"\n query Applications($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n applications(first: 100) {\n edges {\n node {\n id\n publicId\n name\n slug\n logo\n website\n environment\n platform\n applicationStatus\n settings {\n timeZone\n }\n }\n }\n }\n }\n }\n }\n":As,"\n query Application($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $applicationSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n application(slug: $applicationSlug) {\n id\n publicId\n name\n slug\n logo\n website\n environment\n platform\n applicationStatus\n settings {\n timeZone\n }\n }\n }\n }\n }\n":Es,"\n mutation CreateApplication($workspaceId: WorkspaceId!, $payload: CreateWebApplicationPayload!) {\n createWebApplication(workspaceId: $workspaceId, payload: $payload) {\n id\n publicId\n name\n slug\n logo\n website\n environment\n platform\n applicationStatus\n settings {\n timeZone\n }\n }\n }\n":Rs,"\n mutation CreateApiKey($applicationId: ApplicationId!, $payload: CreateApiKeyPayload!) {\n createApiKey(applicationId: $applicationId, payload: $payload) {\n apiKey {\n id\n name\n permissions\n }\n apiKeyValue\n }\n }\n":Ts,"\n query Audiences($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n audiences(first: 100) {\n edges {\n node {\n id\n customId\n name\n criteria\n }\n }\n }\n }\n }\n }\n":Os,"\n query Audience(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId!,\n $audienceSlug: ReadableId!\n ) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n audience(customId: $audienceSlug) {\n id\n customId\n name\n criteria\n }\n }\n }\n }\n":Ds,"\n mutation SignIn($payload: SignInPayload!) {\n signIn(payload: $payload) {\n token\n }\n }\n":Ms,"\n mutation SignUp($payload: SignUpPayload!) {\n signUp(payload: $payload) {\n userId\n }\n }\n":Ns,"\n mutation IssueToken($payload: IssueTokenPayload!) {\n issueToken(payload: $payload) \n }\n":$s,"\n mutation ResetPassword($payload: ResetPasswordPayload!) {\n resetPassword(payload: $payload) {\n token\n }\n }\n":zs,"\n mutation RequestPasswordReset($email: String!, $sessionId: UserSessionId) {\n sendResetLink(email: $email, sessionId: $sessionId)\n }\n":_s,"\n mutation RetryActivation($email: String!, $sessionId: UserSessionId!) {\n retry {\n accountActivation(sessionId: $sessionId, email: $email)\n }\n }\n":Ls,"\n mutation CreateSession($redirectDestination: String) {\n createSession(redirectDestination: $redirectDestination)\n }\n":Fs,"\n mutation CloseSession($sessionId: UserSessionId!) {\n closeSession(sessionId: $sessionId) {\n __typename\n ... on CloseSessionRecoveryGrantedResult {\n recoveryToken\n }\n ... on CloseSessionAccessGrantedResult {\n accessToken\n }\n }\n }\n":js,"\n query Components($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n components(first: 100) {\n edges {\n node {\n id\n customId\n name\n description\n definition {\n definition,\n version {\n major\n minor\n }\n metadata {\n directReferences\n indirectReferences\n referenceMetadata {\n referenceName\n componentId\n }\n }\n }\n }\n }\n }\n }\n }\n }\n":Ws,"\n query Component(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId!,\n $componentSlug: ReadableId!,\n $majorVersion: Int\n ) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n component(customId: $componentSlug) {\n id\n customId\n name\n description\n definition(majorVersion: $majorVersion) {\n definition\n version {\n major\n minor\n }\n metadata {\n directReferences\n indirectReferences\n referenceMetadata {\n referenceName\n componentId\n }\n }\n }\n }\n }\n }\n }\n":Vs,"\n query Experience(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId!,\n $experienceId: ExperienceId!\n ) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n experience(id: $experienceId) {\n id,\n name,\n priority,\n status,\n hasExperiments,\n currentExperiment {\n id,\n name,\n crossDevice,\n goalId,\n traffic,\n status,\n variants {\n variantId\n name\n allocation\n baseline\n content {\n default {\n contents {\n slotId,\n content,\n locale,\n }\n },\n segmented {\n groupId,\n contents {\n slotId,\n content,\n locale,\n },\n audiences {\n audienceId\n }\n }\n }\n }\n }\n draft {\n priority,\n audiences {\n id,\n customId,\n },\n slots {\n slot {\n id,\n customId,\n }\n version {\n minor,\n major\n }\n },\n timeZone,\n content {\n default {\n contents {\n slotId,\n content,\n locale,\n }\n },\n segmented {\n groupId,\n contents {\n slotId,\n content,\n locale,\n },\n audiences {\n audienceId\n }\n }\n },\n experiment {\n name,\n crossDevice,\n goalId,\n traffic,\n variants {\n variantId\n name\n allocation\n baseline\n content {\n default {\n contents {\n slotId,\n content,\n locale,\n }\n },\n segmented {\n groupId,\n contents {\n slotId,\n content,\n locale,\n },\n audiences {\n audienceId\n }\n }\n }\n }\n }\n }\n settings {\n content {\n default {\n contents {\n slotId\n content,\n locale,\n }\n },\n segmented {\n groupId,\n contents {\n slotId,\n content,\n locale,\n },\n audiences {\n audienceId\n }\n }\n }\n audiences {\n id,\n customId,\n }\n slots {\n slot {\n id,\n customId,\n }\n version {\n minor,\n major\n }\n }\n }\n }\n }\n }\n }\n":Us,"\n query Experiences($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $status: [ExperienceStatus!]) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n experiences(first: 100, status: $status) {\n edges {\n node {\n id,\n name,\n priority,\n status,\n currentExperiment {\n name,\n },\n draft {\n priority,\n audiences {\n id,\n customId,\n },\n slots {\n slot {\n id,\n customId,\n }\n version {\n minor,\n major\n }\n },\n experiment {\n name,\n }\n }\n settings {\n audiences {\n id,\n customId\n }\n slots {\n slot {\n id,\n customId\n }\n version {\n minor,\n major\n }\n }\n }\n }\n }\n }\n }\n }\n }\n":qs,"\n query ResourceIdQuery(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId,\n $applicationSlug: ReadableId\n ) {\n organization(slug: $organizationSlug) {\n id\n workspace(slug: $workspaceSlug) {\n id\n application(slug: $applicationSlug) {\n id\n }\n }\n }\n }\n":Hs,"\n query Organization($slug: ReadableId!) {\n organization(slug: $slug) {\n id\n name\n slug\n type\n website\n logo\n email\n }\n }\n":Gs,"\n query Organizations {\n organizations(first: 100) {\n edges {\n node {\n id\n name\n slug\n type\n website\n logo\n email\n }\n }\n }\n }\n":Ks,"\n mutation SetupOrganization($payload: CreateConfiguredOrganizationPayload!) {\n createConfiguredOrganization(payload: $payload) {\n organization {\n id\n name\n slug\n type\n website\n logo\n email\n }\n }\n }\n":Zs,"\n query FindOrganizationSlug(\n $slugFirstOption: ReadableId!\n $slugSecondOption: ReadableId!\n $slugThirdOption: ReadableId!\n ) {\n checkAvailability {\n slugFirstOption: organizationSlug(slug: $slugFirstOption)\n slugSecondOption: organizationSlug(slug: $slugSecondOption)\n slugThirdOption: organizationSlug(slug: $slugThirdOption)\n }\n }\n":Js,"\n query OrganizationMetadata($url: String!) {\n websiteMetadata(url: $url){\n url\n siteName\n domain\n languages\n platform\n technologies {\n name\n }\n logo {\n data\n height\n width\n }\n }\n }\n":Qs,"\n query Slots($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n slots(first: 100) {\n edges {\n node {\n id\n customId\n name\n content {\n component {\n customId\n definition {\n version {\n major\n minor\n }\n metadata {\n directReferences\n indirectReferences\n referenceMetadata {\n referenceName\n componentId\n }\n }\n }\n }\n version {\n major\n minor\n }\n componentDefinition {\n resolvedDefinition\n }\n default {\n content\n locale\n }\n }\n }\n }\n }\n }\n }\n }\n":Bs,"\n query Slot(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId!,\n $slotSlug: ReadableId!,\n $majorVersion: Int\n ) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n slot(customId: $slotSlug) {\n id\n customId\n name\n content(majorVersion: $majorVersion) {\n component {\n customId\n definition {\n version {\n major\n minor\n }\n metadata {\n directReferences\n indirectReferences\n referenceMetadata {\n referenceName\n componentId\n }\n }\n }\n }\n version {\n major\n minor\n }\n componentDefinition {\n resolvedDefinition\n }\n default {\n content\n locale\n }\n }\n }\n }\n }\n }\n":Ys,"\n query SlotStaticContent(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId!,\n $slotSlug: ReadableId!\n $majorVersion: Int\n ) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n slot(customId: $slotSlug) {\n staticContent(majorVersion: $majorVersion) {\n locale\n content\n }\n }\n }\n }\n }\n":Xs,"\n mutation GenerateTyping($workspaceId: WorkspaceId!, $payload: GenerateTypingPayload!) {\n generateTyping(workspaceId: $workspaceId, payload: $payload)\n }\n":ep,"\n query User {\n userAccount {\n id\n user {\n username\n email\n profile {\n firstName\n lastName\n expertise\n }\n }\n }\n }\n":tp,"\n query Username(\n $slugFirstOption: ReadableId!\n $slugSecondOption: ReadableId!\n $slugThirdOption: ReadableId!\n ) {\n checkAvailability {\n slugFirstOption: username(username: $slugFirstOption)\n slugSecondOption: username(username: $slugSecondOption)\n slugThirdOption: username(username: $slugThirdOption)\n }\n }\n":np,"\n query UserEmail($email: String!) {\n checkAvailability {\n email(email: $email)\n }\n }\n":rp,"\n mutation AcceptInvitation($invitationId: InvitationId!) {\n acceptInvitation(invitationId: $invitationId) {\n id\n }\n }\n":ip,"\n query Invitations {\n invitations(first: 100) {\n edges {\n node {\n id\n invitationTime\n organization {\n id\n name\n slug\n type\n website\n logo\n email\n }\n }\n }\n }\n }\n":op,"\n query Workspace($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n id\n name\n slug\n logo\n website\n timeZone\n defaultLocale\n locales {\n edges {\n node {\n code\n }\n }\n }\n }\n }\n }\n":ap,"\n query Workspaces($organizationSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspaces(first: 100) {\n edges {\n node {\n id\n name\n slug\n logo\n website\n timeZone\n defaultLocale\n locales {\n edges {\n node {\n code\n }\n }\n }\n }\n }\n }\n }\n }\n":sp,"\n mutation CreateWorkspace($organizationId: OrganizationId!, $payload: CreateWorkspacePayload!) {\n createWorkspace(organizationId: $organizationId, payload: $payload) {\n id\n name\n slug\n logo\n website\n timeZone\n defaultLocale\n locales {\n edges {\n node {\n code\n }\n }\n }\n }\n }\n":pp,"\n query FindWorkspaceSlug(\n $organizationId: OrganizationId!\n $slugFirstOption: ReadableId!\n $slugSecondOption: ReadableId!\n $slugThirdOption: ReadableId!\n ) {\n checkAvailability {\n slugFirstOption: workspaceSlug(organizationId: $organizationId, slug: $slugFirstOption)\n slugSecondOption: workspaceSlug(organizationId: $organizationId, slug: $slugSecondOption)\n slugThirdOption: workspaceSlug(organizationId: $organizationId, slug: $slugThirdOption)\n }\n }\n":cp,"\n query WorkspaceFeatures($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n quotas {\n audience\n remainingAudiences\n component\n remainingComponents\n slot\n remainingSlots,\n experience\n remainingExperiences\n experiment\n remainingExperiments\n dynamicAttributesPerContent\n audiencesPerExperience\n }\n capabilities {\n features(requiredFeatures: [\n EXPERIMENT,\n CROSS_DEVICE_EXPERIMENT,\n API_DATA_EXPORT\n ])\n }\n } \n }\n }\n":lp,"\n mutation CreateResources($workspaceId: WorkspaceId!, $payload: CreateWorkspaceResourcePayload!) {\n createWorkspaceResources(workspaceId: $workspaceId, payload: $payload) {\n slots\n components\n audiences\n experiences {\n id,\n experimentId\n }\n }\n }\n":up};function x(o){return Dl[o]??{}}var mp=x(`
|
|
905
|
+
`);var Dl={"\n query ApplicationSlugAvailability(\n $workspaceId: WorkspaceId!\n $slugFirstOption: ReadableId!\n $slugSecondOption: ReadableId!\n $slugThirdOption: ReadableId!\n ) {\n checkAvailability {\n slugFirstOption: applicationSlug(workspaceId: $workspaceId, slug: $slugFirstOption)\n slugSecondOption: applicationSlug(workspaceId: $workspaceId, slug: $slugSecondOption)\n slugThirdOption: applicationSlug(workspaceId: $workspaceId, slug: $slugThirdOption)\n }\n }\n":ks,"\n query Applications($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n applications(first: 100) {\n edges {\n node {\n id\n publicId\n name\n slug\n logo\n website\n environment\n platform\n applicationStatus\n settings {\n timeZone\n }\n }\n }\n }\n }\n }\n }\n":As,"\n query Application($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $applicationSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n application(slug: $applicationSlug) {\n id\n publicId\n name\n slug\n logo\n website\n environment\n platform\n applicationStatus\n settings {\n timeZone\n }\n }\n }\n }\n }\n":Es,"\n mutation CreateApplication($workspaceId: WorkspaceId!, $payload: CreateWebApplicationPayload!) {\n createWebApplication(workspaceId: $workspaceId, payload: $payload) {\n id\n publicId\n name\n slug\n logo\n website\n environment\n platform\n applicationStatus\n settings {\n timeZone\n }\n }\n }\n":Rs,"\n mutation CreateApiKey($applicationId: ApplicationId!, $payload: CreateApiKeyPayload!) {\n createApiKey(applicationId: $applicationId, payload: $payload) {\n apiKey {\n id\n name\n permissions\n }\n apiKeyValue\n }\n }\n":Ts,"\n query Audiences($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n audiences(first: 100) {\n edges {\n node {\n id\n customId\n name\n criteria\n }\n }\n }\n }\n }\n }\n":Os,"\n query Audience(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId!,\n $audienceSlug: ReadableId!\n ) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n audience(customId: $audienceSlug) {\n id\n customId\n name\n criteria\n }\n }\n }\n }\n":Ds,"\n mutation SignIn($payload: SignInPayload!) {\n signIn(payload: $payload) {\n token\n }\n }\n":Ms,"\n mutation SignUp($payload: SignUpPayload!) {\n signUp(payload: $payload) {\n userId\n }\n }\n":Ns,"\n mutation IssueToken($payload: IssueTokenPayload!) {\n issueToken(payload: $payload) \n }\n":$s,"\n mutation ResetPassword($payload: ResetPasswordPayload!) {\n resetPassword(payload: $payload) {\n token\n }\n }\n":zs,"\n mutation RequestPasswordReset($email: String!, $sessionId: UserSessionId) {\n sendResetLink(email: $email, sessionId: $sessionId)\n }\n":_s,"\n mutation RetryActivation($email: String!, $sessionId: UserSessionId!) {\n retry {\n accountActivation(sessionId: $sessionId, email: $email)\n }\n }\n":Ls,"\n mutation CreateSession($redirectDestination: String) {\n createSession(redirectDestination: $redirectDestination)\n }\n":Fs,"\n mutation CloseSession($sessionId: UserSessionId!) {\n closeSession(sessionId: $sessionId) {\n __typename\n ... on CloseSessionRecoveryGrantedResult {\n recoveryToken\n }\n ... on CloseSessionAccessGrantedResult {\n accessToken\n }\n }\n }\n":js,"\n query Components($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n components(first: 100) {\n edges {\n node {\n id\n customId\n name\n description\n definition {\n definition,\n version {\n major\n minor\n }\n metadata {\n directReferences\n indirectReferences\n referenceMetadata {\n referenceName\n componentId\n }\n }\n }\n }\n }\n }\n }\n }\n }\n":Ws,"\n query Component(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId!,\n $componentSlug: ReadableId!,\n $majorVersion: Int\n ) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n component(customId: $componentSlug) {\n id\n customId\n name\n description\n definition(majorVersion: $majorVersion) {\n definition\n version {\n major\n minor\n }\n metadata {\n directReferences\n indirectReferences\n referenceMetadata {\n referenceName\n componentId\n }\n }\n }\n }\n }\n }\n }\n":Vs,"\n query Experience(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId!,\n $experienceId: ExperienceId!\n ) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n experience(id: $experienceId) {\n id,\n name,\n priority,\n status,\n hasExperiments,\n currentExperiment {\n id,\n name,\n crossDevice,\n goalId,\n traffic,\n status,\n variants {\n variantId\n name\n allocation\n baseline\n content {\n default {\n contents {\n slotId,\n content,\n locale,\n }\n },\n segmented {\n groupId,\n contents {\n slotId,\n content,\n locale,\n },\n audiences {\n audienceId\n }\n }\n }\n }\n }\n draft {\n priority,\n audiences {\n id,\n customId,\n },\n slots {\n slot {\n id,\n customId,\n }\n version {\n minor,\n major\n }\n },\n timeZone,\n content {\n default {\n contents {\n slotId,\n content,\n locale,\n }\n },\n segmented {\n groupId,\n contents {\n slotId,\n content,\n locale,\n },\n audiences {\n audienceId\n }\n }\n },\n experiment {\n name,\n crossDevice,\n goalId,\n traffic,\n variants {\n variantId\n name\n allocation\n baseline\n content {\n default {\n contents {\n slotId,\n content,\n locale,\n }\n },\n segmented {\n groupId,\n contents {\n slotId,\n content,\n locale,\n },\n audiences {\n audienceId\n }\n }\n }\n }\n }\n }\n settings {\n content {\n default {\n contents {\n slotId\n content,\n locale,\n }\n },\n segmented {\n groupId,\n contents {\n slotId,\n content,\n locale,\n },\n audiences {\n audienceId\n }\n }\n }\n audiences {\n id,\n customId,\n }\n slots {\n slot {\n id,\n customId,\n }\n version {\n minor,\n major\n }\n }\n }\n }\n }\n }\n }\n":Us,"\n query Experiences($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $status: [ExperienceStatus!]) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n experiences(first: 100, status: $status) {\n edges {\n node {\n id,\n name,\n priority,\n status,\n currentExperiment {\n name,\n },\n draft {\n priority,\n audiences {\n id,\n customId,\n },\n slots {\n slot {\n id,\n customId,\n }\n version {\n minor,\n major\n }\n },\n experiment {\n name,\n }\n }\n settings {\n audiences {\n id,\n customId\n }\n slots {\n slot {\n id,\n customId\n }\n version {\n minor,\n major\n }\n }\n }\n }\n }\n }\n }\n }\n }\n":qs,"\n query ResourceIdQuery(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId,\n $applicationSlug: ReadableId\n ) {\n organization(slug: $organizationSlug) {\n id\n workspace(slug: $workspaceSlug) {\n id\n application(slug: $applicationSlug) {\n id\n }\n }\n }\n }\n":Hs,"\n query Organization($slug: ReadableId!) {\n organization(slug: $slug) {\n id\n name\n slug\n type\n website\n logo\n email\n }\n }\n":Gs,"\n query Organizations {\n organizations(first: 100) {\n edges {\n node {\n id\n name\n slug\n type\n website\n logo\n email\n }\n }\n }\n }\n":Ks,"\n mutation SetupOrganization($payload: CreateConfiguredOrganizationPayload!) {\n createConfiguredOrganization(payload: $payload) {\n organization {\n id\n name\n slug\n type\n website\n logo\n email\n }\n }\n }\n":Zs,"\n query FindOrganizationSlug(\n $slugFirstOption: ReadableId!\n $slugSecondOption: ReadableId!\n $slugThirdOption: ReadableId!\n ) {\n checkAvailability {\n slugFirstOption: organizationSlug(slug: $slugFirstOption)\n slugSecondOption: organizationSlug(slug: $slugSecondOption)\n slugThirdOption: organizationSlug(slug: $slugThirdOption)\n }\n }\n":Js,"\n query OrganizationMetadata($url: String!) {\n websiteMetadata(url: $url){\n url\n siteName\n domain\n languages\n platform\n technologies {\n name\n }\n logo {\n data\n height\n width\n }\n }\n }\n":Qs,"\n query Slots($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n slots(first: 100) {\n edges {\n node {\n id\n customId\n name\n content {\n component {\n customId\n definition {\n version {\n major\n minor\n }\n metadata {\n directReferences\n indirectReferences\n referenceMetadata {\n referenceName\n componentId\n }\n }\n }\n }\n version {\n major\n minor\n }\n componentDefinition {\n resolvedDefinition\n }\n default {\n content\n locale\n }\n }\n }\n }\n }\n }\n }\n }\n":Bs,"\n query Slot(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId!,\n $slotSlug: ReadableId!,\n $majorVersion: Int\n ) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n slot(customId: $slotSlug) {\n id\n customId\n name\n content(majorVersion: $majorVersion) {\n component {\n customId\n definition {\n version {\n major\n minor\n }\n metadata {\n directReferences\n indirectReferences\n referenceMetadata {\n referenceName\n componentId\n }\n }\n }\n }\n version {\n major\n minor\n }\n componentDefinition {\n resolvedDefinition\n }\n default {\n content\n locale\n }\n }\n }\n }\n }\n }\n":Ys,"\n query SlotStaticContent(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId!,\n $slotSlug: ReadableId!\n $majorVersion: Int\n ) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n slot(customId: $slotSlug) {\n staticContent(majorVersion: $majorVersion) {\n locale\n content\n }\n }\n }\n }\n }\n":Xs,"\n mutation GenerateTyping($workspaceId: WorkspaceId!, $payload: GenerateTypingPayload!) {\n generateTyping(workspaceId: $workspaceId, payload: $payload)\n }\n":ep,"\n query User {\n userAccount {\n id\n user {\n username\n email\n profile {\n firstName\n lastName\n expertise\n }\n }\n }\n }\n":tp,"\n query Username(\n $slugFirstOption: ReadableId!\n $slugSecondOption: ReadableId!\n $slugThirdOption: ReadableId!\n ) {\n checkAvailability {\n slugFirstOption: username(username: $slugFirstOption)\n slugSecondOption: username(username: $slugSecondOption)\n slugThirdOption: username(username: $slugThirdOption)\n }\n }\n":np,"\n query UserEmail($email: String!) {\n checkAvailability {\n email(email: $email)\n }\n }\n":rp,"\n mutation AcceptInvitation($invitationId: InvitationId!) {\n acceptInvitation(invitationId: $invitationId) {\n id\n }\n }\n":ip,"\n query Invitations {\n invitations(first: 100) {\n edges {\n node {\n id\n invitationTime\n organization {\n id\n name\n slug\n type\n website\n logo\n email\n }\n }\n }\n }\n }\n":op,"\n query Workspace($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n id\n name\n slug\n logo\n website\n timeZone\n defaultLocale\n locales {\n edges {\n node {\n code\n }\n }\n }\n }\n }\n }\n":ap,"\n query Workspaces($organizationSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspaces(first: 100) {\n edges {\n node {\n id\n name\n slug\n logo\n website\n timeZone\n defaultLocale\n locales {\n edges {\n node {\n code\n }\n }\n }\n }\n }\n }\n }\n }\n":sp,"\n mutation CreateWorkspace($organizationId: OrganizationId!, $payload: CreateWorkspacePayload!) {\n createWorkspace(organizationId: $organizationId, payload: $payload) {\n id\n name\n slug\n logo\n website\n timeZone\n defaultLocale\n locales {\n edges {\n node {\n code\n }\n }\n }\n }\n }\n":pp,"\n query FindWorkspaceSlug(\n $organizationId: OrganizationId!\n $slugFirstOption: ReadableId!\n $slugSecondOption: ReadableId!\n $slugThirdOption: ReadableId!\n ) {\n checkAvailability {\n slugFirstOption: workspaceSlug(organizationId: $organizationId, slug: $slugFirstOption)\n slugSecondOption: workspaceSlug(organizationId: $organizationId, slug: $slugSecondOption)\n slugThirdOption: workspaceSlug(organizationId: $organizationId, slug: $slugThirdOption)\n }\n }\n":cp,"\n query WorkspaceFeatures($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n quotas {\n audience\n remainingAudiences\n component\n remainingComponents\n slot\n remainingSlots,\n experience\n remainingExperiences\n experiment\n remainingExperiments\n dynamicAttributesPerContent\n audiencesPerExperience\n }\n capabilities {\n features(requiredFeatures: [\n EXPERIMENT,\n CROSS_DEVICE_EXPERIMENT,\n API_DATA_EXPORT\n ])\n }\n } \n }\n }\n":lp,"\n mutation CreateResources($workspaceId: WorkspaceId!, $payload: CreateWorkspaceResourcePayload!) {\n createWorkspaceResources(workspaceId: $workspaceId, payload: $payload) {\n slots\n components\n audiences\n experiences {\n id,\n experimentId\n }\n }\n }\n":up};function v(o){return Dl[o]??{}}var mp=v(`
|
|
906
906
|
query ResourceIdQuery(
|
|
907
907
|
$organizationSlug: ReadableId!,
|
|
908
908
|
$workspaceSlug: ReadableId,
|
|
@@ -918,7 +918,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
918
918
|
}
|
|
919
919
|
}
|
|
920
920
|
}
|
|
921
|
-
`),dp=
|
|
921
|
+
`),dp=v(`
|
|
922
922
|
query Organization($slug: ReadableId!) {
|
|
923
923
|
organization(slug: $slug) {
|
|
924
924
|
id
|
|
@@ -930,7 +930,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
930
930
|
email
|
|
931
931
|
}
|
|
932
932
|
}
|
|
933
|
-
`),gp=
|
|
933
|
+
`),gp=v(`
|
|
934
934
|
query Organizations {
|
|
935
935
|
organizations(first: 100) {
|
|
936
936
|
edges {
|
|
@@ -946,7 +946,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
946
946
|
}
|
|
947
947
|
}
|
|
948
948
|
}
|
|
949
|
-
`),fp=
|
|
949
|
+
`),fp=v(`
|
|
950
950
|
mutation SetupOrganization($payload: CreateConfiguredOrganizationPayload!) {
|
|
951
951
|
createConfiguredOrganization(payload: $payload) {
|
|
952
952
|
organization {
|
|
@@ -960,7 +960,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
960
960
|
}
|
|
961
961
|
}
|
|
962
962
|
}
|
|
963
|
-
`),yp=
|
|
963
|
+
`),yp=v(`
|
|
964
964
|
query FindOrganizationSlug(
|
|
965
965
|
$slugFirstOption: ReadableId!
|
|
966
966
|
$slugSecondOption: ReadableId!
|
|
@@ -972,7 +972,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
972
972
|
slugThirdOption: organizationSlug(slug: $slugThirdOption)
|
|
973
973
|
}
|
|
974
974
|
}
|
|
975
|
-
`),hp=
|
|
975
|
+
`),hp=v(`
|
|
976
976
|
query OrganizationMetadata($url: String!) {
|
|
977
977
|
websiteMetadata(url: $url){
|
|
978
978
|
url
|
|
@@ -990,7 +990,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
990
990
|
}
|
|
991
991
|
}
|
|
992
992
|
}
|
|
993
|
-
`);var Sp=
|
|
993
|
+
`);var Sp=v(`
|
|
994
994
|
query User {
|
|
995
995
|
userAccount {
|
|
996
996
|
id
|
|
@@ -1005,7 +1005,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1005
1005
|
}
|
|
1006
1006
|
}
|
|
1007
1007
|
}
|
|
1008
|
-
`),bp=
|
|
1008
|
+
`),bp=v(`
|
|
1009
1009
|
query Username(
|
|
1010
1010
|
$slugFirstOption: ReadableId!
|
|
1011
1011
|
$slugSecondOption: ReadableId!
|
|
@@ -1017,19 +1017,19 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1017
1017
|
slugThirdOption: username(username: $slugThirdOption)
|
|
1018
1018
|
}
|
|
1019
1019
|
}
|
|
1020
|
-
`),Ip=
|
|
1020
|
+
`),Ip=v(`
|
|
1021
1021
|
query UserEmail($email: String!) {
|
|
1022
1022
|
checkAvailability {
|
|
1023
1023
|
email(email: $email)
|
|
1024
1024
|
}
|
|
1025
1025
|
}
|
|
1026
|
-
`),xp=
|
|
1026
|
+
`),xp=v(`
|
|
1027
1027
|
mutation AcceptInvitation($invitationId: InvitationId!) {
|
|
1028
1028
|
acceptInvitation(invitationId: $invitationId) {
|
|
1029
1029
|
id
|
|
1030
1030
|
}
|
|
1031
1031
|
}
|
|
1032
|
-
`),vp=
|
|
1032
|
+
`),vp=v(`
|
|
1033
1033
|
query Invitations {
|
|
1034
1034
|
invitations(first: 100) {
|
|
1035
1035
|
edges {
|
|
@@ -1049,43 +1049,43 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1049
1049
|
}
|
|
1050
1050
|
}
|
|
1051
1051
|
}
|
|
1052
|
-
`);var wp=
|
|
1052
|
+
`);var wp=v(`
|
|
1053
1053
|
mutation SignIn($payload: SignInPayload!) {
|
|
1054
1054
|
signIn(payload: $payload) {
|
|
1055
1055
|
token
|
|
1056
1056
|
}
|
|
1057
1057
|
}
|
|
1058
|
-
`),Pp=
|
|
1058
|
+
`),Pp=v(`
|
|
1059
1059
|
mutation SignUp($payload: SignUpPayload!) {
|
|
1060
1060
|
signUp(payload: $payload) {
|
|
1061
1061
|
userId
|
|
1062
1062
|
}
|
|
1063
1063
|
}
|
|
1064
|
-
`),Cp=
|
|
1064
|
+
`),Cp=v(`
|
|
1065
1065
|
mutation IssueToken($payload: IssueTokenPayload!) {
|
|
1066
1066
|
issueToken(payload: $payload)
|
|
1067
1067
|
}
|
|
1068
|
-
`),kp=
|
|
1068
|
+
`),kp=v(`
|
|
1069
1069
|
mutation ResetPassword($payload: ResetPasswordPayload!) {
|
|
1070
1070
|
resetPassword(payload: $payload) {
|
|
1071
1071
|
token
|
|
1072
1072
|
}
|
|
1073
1073
|
}
|
|
1074
|
-
`),Ap=
|
|
1074
|
+
`),Ap=v(`
|
|
1075
1075
|
mutation RequestPasswordReset($email: String!, $sessionId: UserSessionId) {
|
|
1076
1076
|
sendResetLink(email: $email, sessionId: $sessionId)
|
|
1077
1077
|
}
|
|
1078
|
-
`),Ep=
|
|
1078
|
+
`),Ep=v(`
|
|
1079
1079
|
mutation RetryActivation($email: String!, $sessionId: UserSessionId!) {
|
|
1080
1080
|
retry {
|
|
1081
1081
|
accountActivation(sessionId: $sessionId, email: $email)
|
|
1082
1082
|
}
|
|
1083
1083
|
}
|
|
1084
|
-
`),Rp=
|
|
1084
|
+
`),Rp=v(`
|
|
1085
1085
|
mutation CreateSession($redirectDestination: String) {
|
|
1086
1086
|
createSession(redirectDestination: $redirectDestination)
|
|
1087
1087
|
}
|
|
1088
|
-
`),Tp=
|
|
1088
|
+
`),Tp=v(`
|
|
1089
1089
|
mutation CloseSession($sessionId: UserSessionId!) {
|
|
1090
1090
|
closeSession(sessionId: $sessionId) {
|
|
1091
1091
|
__typename
|
|
@@ -1097,7 +1097,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1097
1097
|
}
|
|
1098
1098
|
}
|
|
1099
1099
|
}
|
|
1100
|
-
`);var Xt=class o{constructor(e){this.client=e;}async getUser(){let{data:e}=await this.client.execute(Sp),{id:t,user:n}=e.userAccount,{profile:{lastName:r=null}}=n;return {id:t,username:n.profile.firstName,email:n.email,firstName:n.profile.firstName,expertise:n.profile.expertise,...r!==null?{lastName:r}:{}}}async isEmailRegistered(e){let{data:t}=await this.client.execute(Ip,{email:e});return !t.checkAvailability.email}async requestPasswordReset(e){await this.client.execute(Ap,{email:e.email,sessionId:e.sessionId});}async resetPassword(e){let{data:t}=await this.client.execute(kp,{payload:{password:e.password,token:e.token}});return t.resetPassword.token}async retryActivation(e){await this.client.execute(Ep,{email:e.email,sessionId:e.sessionId});}async registerUser(e){await this.client.execute(Pp,{payload:{username:await this.generateUsername(`${e.firstName} ${e.lastName??""}`.trim()),email:e.email,password:e.password,firstName:e.firstName,lastName:e.lastName,expertise:e.expertise,sessionId:e.sessionId,bypassOnboarding:true}});}async createSession(e){let{data:t}=await this.client.execute(Rp,{redirectDestination:e?.destination});return t.createSession}async closeSession(e){let{data:t}=await this.client.execute(Tp,{sessionId:e});switch(t.closeSession.__typename){case "CloseSessionAccessGrantedResult":return {status:"access-granted",accessToken:t.closeSession.accessToken};case "CloseSessionRecoveryGrantedResult":return {status:"recovery-granted",recoveryToken:t.closeSession.recoveryToken};case "CloseSessionPendingResult":return {status:"pending"}}}async signIn(e){let{data:t}=await this.client.execute(wp,{payload:{email:e.email,password:e.password,duration:e.duration,remember:false}});return t.signIn.token}async issueToken(e){let{data:t}=await this.client.execute(Cp,{payload:{duration:e.duration}});return t.issueToken}async getOrganization(e){let{data:t}=await this.client.execute(dp,{slug:e}),n=t.organization??null;return n===null?null:o.normalizeOrganization(n)}async getOrganizations(){let{data:e}=await this.client.execute(gp);return (e.organizations.edges??[]).flatMap(n=>{let r=n?.node??null;return r===null||r.slug==="demo"?[]:[o.normalizeOrganization(r)]})}async setupOrganization(e){let{data:t}=await this.client.execute(fp,{payload:await this.getOrganizationSetupPayload(e)}),{organization:n}=t.createConfiguredOrganization,{logo:r=null,website:i=null}=n;return {id:n.id,name:n.name,slug:n.slug,type:n.type,email:n.email,...r!==null?{logo:r}:{},...i!==null?{website:i}:{}}}async getOrganizationSetupPayload(e){let t=new URL(e.website),n=await this.getUser(),r=`${n.firstName} ${n.lastName??""}`.trim();if(t.hostname.toLowerCase()==="localhost")return {locale:e.locale,timeZone:e.timeZone,acceptedTerms:true,organization:{website:t.origin,email:n.email,name:"Personal organization",slug:await this.generateOrganizationSlug(r,true),type:"PERSONAL"},workspace:{name:"Personal workspace",slug:Yt({baseName:r,alwaysSuffixed:true}).next().value,website:t.origin},applications:[{environment:"DEVELOPMENT",name:"Website",slug:"website-dev",website:t.origin,platform:"JAVASCRIPT"}],audiences:[],components:[],experiences:[],slots:[],redirectUrl:e.redirectUrl};let i=await this.getOrganizationMetadata(t),a=`${t.protocol}//${i.domain}`,s=i.logo!==null&&i.logo!==void 0&&i.logo.width>=64&&i.logo.height>=64?i.logo.data:void 0;return {locale:i.languages[0]??e.locale,timeZone:e.timeZone,acceptedTerms:true,organization:{website:a,email:n.email,name:i.siteName,slug:await this.generateOrganizationSlug(i.siteName,false),type:"BUSINESS",logo:s},workspace:{name:i.siteName,slug:Yt({baseName:i.siteName,alwaysSuffixed:false}).next().value,logo:s,website:a},applications:[{environment:"PRODUCTION",name:"Website",slug:"website-prod",website:t.origin,platform:i.platform},{environment:"DEVELOPMENT",name:"Website",slug:"website-dev",website:t.origin,platform:i.platform}],audiences:[],components:[],experiences:[],slots:[],redirectUrl:e.redirectUrl}}async getInvitations(){let{data:e}=await this.client.execute(vp);return (e.invitations.edges??[]).flatMap(n=>{let r=n?.node??null;return r===null?[]:[{id:r.id,invitationTime:r.invitationTime,organization:o.normalizeOrganization(r.organization)}]})}async acceptInvitation(e){await this.client.execute(xp,{invitationId:e});}static normalizeOrganization(e){let{logo:t=null,website:n=null}=e;return {id:e.id,name:e.name,slug:e.slug,type:e.type,email:e.email,...t!==null?{logo:t}:{},...n!==null?{website:n}:{}}}async getOrganizationMetadata(e){let{data:t}=await this.client.execute(hp,{url:e.toString()});return t.websiteMetadata}generateOrganizationSlug(e,t=false){return ot({query:yp,baseName:e,client:this.client,alwaysSuffixed:t})}generateUsername(e){return ot({query:bp,baseName:e,client:this.client,alwaysSuffixed:false})}};var Op=
|
|
1100
|
+
`);var Xt=class o{constructor(e){this.client=e;}async getUser(){let{data:e}=await this.client.execute(Sp),{id:t,user:n}=e.userAccount,{profile:{lastName:r=null}}=n;return {id:t,username:n.profile.firstName,email:n.email,firstName:n.profile.firstName,expertise:n.profile.expertise,...r!==null?{lastName:r}:{}}}async isEmailRegistered(e){let{data:t}=await this.client.execute(Ip,{email:e});return !t.checkAvailability.email}async requestPasswordReset(e){await this.client.execute(Ap,{email:e.email,sessionId:e.sessionId});}async resetPassword(e){let{data:t}=await this.client.execute(kp,{payload:{password:e.password,token:e.token}});return t.resetPassword.token}async retryActivation(e){await this.client.execute(Ep,{email:e.email,sessionId:e.sessionId});}async registerUser(e){await this.client.execute(Pp,{payload:{username:await this.generateUsername(`${e.firstName} ${e.lastName??""}`.trim()),email:e.email,password:e.password,firstName:e.firstName,lastName:e.lastName,expertise:e.expertise,sessionId:e.sessionId,bypassOnboarding:true}});}async createSession(e){let{data:t}=await this.client.execute(Rp,{redirectDestination:e?.destination});return t.createSession}async closeSession(e){let{data:t}=await this.client.execute(Tp,{sessionId:e});switch(t.closeSession.__typename){case "CloseSessionAccessGrantedResult":return {status:"access-granted",accessToken:t.closeSession.accessToken};case "CloseSessionRecoveryGrantedResult":return {status:"recovery-granted",recoveryToken:t.closeSession.recoveryToken};case "CloseSessionPendingResult":return {status:"pending"}}}async signIn(e){let{data:t}=await this.client.execute(wp,{payload:{email:e.email,password:e.password,duration:e.duration,remember:false}});return t.signIn.token}async issueToken(e){let{data:t}=await this.client.execute(Cp,{payload:{duration:e.duration}});return t.issueToken}async getOrganization(e){let{data:t}=await this.client.execute(dp,{slug:e}),n=t.organization??null;return n===null?null:o.normalizeOrganization(n)}async getOrganizations(){let{data:e}=await this.client.execute(gp);return (e.organizations.edges??[]).flatMap(n=>{let r=n?.node??null;return r===null||r.slug==="demo"?[]:[o.normalizeOrganization(r)]})}async setupOrganization(e){let{data:t}=await this.client.execute(fp,{payload:await this.getOrganizationSetupPayload(e)}),{organization:n}=t.createConfiguredOrganization,{logo:r=null,website:i=null}=n;return {id:n.id,name:n.name,slug:n.slug,type:n.type,email:n.email,...r!==null?{logo:r}:{},...i!==null?{website:i}:{}}}async getOrganizationSetupPayload(e){let t=new URL(e.website),n=await this.getUser(),r=`${n.firstName} ${n.lastName??""}`.trim();if(t.hostname.toLowerCase()==="localhost")return {locale:e.locale,timeZone:e.timeZone,acceptedTerms:true,organization:{website:t.origin,email:n.email,name:"Personal organization",slug:await this.generateOrganizationSlug(r,true),type:"PERSONAL"},workspace:{name:"Personal workspace",slug:Yt({baseName:r,alwaysSuffixed:true}).next().value,website:t.origin},applications:[{environment:"DEVELOPMENT",name:"Website",slug:"website-dev",website:t.origin,platform:"JAVASCRIPT"}],audiences:[],components:[],experiences:[],slots:[],redirectUrl:e.redirectUrl};let i=await this.getOrganizationMetadata(t),a=`${t.protocol}//${i.domain}`,s=i.logo!==null&&i.logo!==void 0&&i.logo.width>=64&&i.logo.height>=64?i.logo.data:void 0;return {locale:i.languages[0]??e.locale,timeZone:e.timeZone,acceptedTerms:true,organization:{website:a,email:n.email,name:i.siteName,slug:await this.generateOrganizationSlug(i.siteName,false),type:"BUSINESS",logo:s},workspace:{name:i.siteName,slug:Yt({baseName:i.siteName,alwaysSuffixed:false}).next().value,logo:s,website:a},applications:[{environment:"PRODUCTION",name:"Website",slug:"website-prod",website:t.origin,platform:i.platform},{environment:"DEVELOPMENT",name:"Website",slug:"website-dev",website:t.origin,platform:i.platform}],audiences:[],components:[],experiences:[],slots:[],redirectUrl:e.redirectUrl}}async getInvitations(){let{data:e}=await this.client.execute(vp);return (e.invitations.edges??[]).flatMap(n=>{let r=n?.node??null;return r===null?[]:[{id:r.id,invitationTime:r.invitationTime,organization:o.normalizeOrganization(r.organization)}]})}async acceptInvitation(e){await this.client.execute(xp,{invitationId:e});}static normalizeOrganization(e){let{logo:t=null,website:n=null}=e;return {id:e.id,name:e.name,slug:e.slug,type:e.type,email:e.email,...t!==null?{logo:t}:{},...n!==null?{website:n}:{}}}async getOrganizationMetadata(e){let{data:t}=await this.client.execute(hp,{url:e.toString()});return t.websiteMetadata}generateOrganizationSlug(e,t=false){return ot({query:yp,baseName:e,client:this.client,alwaysSuffixed:t})}generateUsername(e){return ot({query:bp,baseName:e,client:this.client,alwaysSuffixed:false})}};var Op=v(`
|
|
1101
1101
|
query Workspace($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
|
|
1102
1102
|
organization(slug: $organizationSlug) {
|
|
1103
1103
|
workspace(slug: $workspaceSlug) {
|
|
@@ -1118,7 +1118,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1118
1118
|
}
|
|
1119
1119
|
}
|
|
1120
1120
|
}
|
|
1121
|
-
`),Dp=
|
|
1121
|
+
`),Dp=v(`
|
|
1122
1122
|
query Workspaces($organizationSlug: ReadableId!) {
|
|
1123
1123
|
organization(slug: $organizationSlug) {
|
|
1124
1124
|
workspaces(first: 100) {
|
|
@@ -1143,7 +1143,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1143
1143
|
}
|
|
1144
1144
|
}
|
|
1145
1145
|
}
|
|
1146
|
-
`),Mp=
|
|
1146
|
+
`),Mp=v(`
|
|
1147
1147
|
mutation CreateWorkspace($organizationId: OrganizationId!, $payload: CreateWorkspacePayload!) {
|
|
1148
1148
|
createWorkspace(organizationId: $organizationId, payload: $payload) {
|
|
1149
1149
|
id
|
|
@@ -1162,7 +1162,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1162
1162
|
}
|
|
1163
1163
|
}
|
|
1164
1164
|
}
|
|
1165
|
-
`),Np=
|
|
1165
|
+
`),Np=v(`
|
|
1166
1166
|
query FindWorkspaceSlug(
|
|
1167
1167
|
$organizationId: OrganizationId!
|
|
1168
1168
|
$slugFirstOption: ReadableId!
|
|
@@ -1175,7 +1175,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1175
1175
|
slugThirdOption: workspaceSlug(organizationId: $organizationId, slug: $slugThirdOption)
|
|
1176
1176
|
}
|
|
1177
1177
|
}
|
|
1178
|
-
`),$p=
|
|
1178
|
+
`),$p=v(`
|
|
1179
1179
|
query WorkspaceFeatures($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
|
|
1180
1180
|
organization(slug: $organizationSlug) {
|
|
1181
1181
|
workspace(slug: $workspaceSlug) {
|
|
@@ -1203,7 +1203,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1203
1203
|
}
|
|
1204
1204
|
}
|
|
1205
1205
|
}
|
|
1206
|
-
`),zp=
|
|
1206
|
+
`),zp=v(`
|
|
1207
1207
|
mutation CreateResources($workspaceId: WorkspaceId!, $payload: CreateWorkspaceResourcePayload!) {
|
|
1208
1208
|
createWorkspaceResources(workspaceId: $workspaceId, payload: $payload) {
|
|
1209
1209
|
slots
|
|
@@ -1215,7 +1215,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1215
1215
|
}
|
|
1216
1216
|
}
|
|
1217
1217
|
}
|
|
1218
|
-
`);var or=class o{constructor(e,t){this.client=e,this.hierarchyResolver=t;}async getWorkspace(e){let{data:t}=await this.client.execute(Op,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),n=t.organization?.workspace??null;return n===null?null:o.normalizeWorkspace(n)}async getWorkspaces(e){let{data:t}=await this.client.execute(Dp,{organizationSlug:e.organizationSlug});return (t.organization?.workspaces.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeWorkspace(i)]})}static normalizeWorkspace(e){let{logo:t=null,website:n=null,locales:{edges:r=[]}}=e;return {id:e.id,name:e.name,slug:e.slug,timeZone:e.timeZone,defaultLocale:e.defaultLocale,locales:r?.flatMap(i=>{let a=i?.node?.code??null;return a===null?[]:[a]})??[],...t!==null?{logo:t}:{},...n!==null?{website:n}:{}}}async createWorkspace(e){let t=await this.hierarchyResolver.getHierarchy({organizationSlug:e.organizationSlug}),{data:n}=await this.client.execute(Mp,{organizationId:t.organizationId,payload:{name:e.name,slug:await this.generateWorkspaceSlug(t.organizationId,e.name),timeZone:e.timeZone,defaultLocale:e.defaultLocale,website:e.website}}),r=n.createWorkspace,{logo:i=null,website:a=null,locales:{edges:s=[]}}=r;return {id:r.id,name:r.name,slug:r.slug,timeZone:r.timeZone,defaultLocale:r.defaultLocale,locales:s?.flatMap(p=>{let c=p?.node?.code??null;return c===null?[]:[c]})??[],...i!==null?{logo:i}:{},...a!==null?{website:a}:{}}}generateWorkspaceSlug(e,t){return ot({query:Np,baseName:t,client:this.client,variables:{organizationId:e}})}};var _p=
|
|
1218
|
+
`);var or=class o{constructor(e,t){this.client=e,this.hierarchyResolver=t;}async getWorkspace(e){let{data:t}=await this.client.execute(Op,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),n=t.organization?.workspace??null;return n===null?null:o.normalizeWorkspace(n)}async getWorkspaces(e){let{data:t}=await this.client.execute(Dp,{organizationSlug:e.organizationSlug});return (t.organization?.workspaces.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeWorkspace(i)]})}static normalizeWorkspace(e){let{logo:t=null,website:n=null,locales:{edges:r=[]}}=e;return {id:e.id,name:e.name,slug:e.slug,timeZone:e.timeZone,defaultLocale:e.defaultLocale,locales:r?.flatMap(i=>{let a=i?.node?.code??null;return a===null?[]:[a]})??[],...t!==null?{logo:t}:{},...n!==null?{website:n}:{}}}async createWorkspace(e){let t=await this.hierarchyResolver.getHierarchy({organizationSlug:e.organizationSlug}),{data:n}=await this.client.execute(Mp,{organizationId:t.organizationId,payload:{name:e.name,slug:await this.generateWorkspaceSlug(t.organizationId,e.name),timeZone:e.timeZone,defaultLocale:e.defaultLocale,website:e.website}}),r=n.createWorkspace,{logo:i=null,website:a=null,locales:{edges:s=[]}}=r;return {id:r.id,name:r.name,slug:r.slug,timeZone:r.timeZone,defaultLocale:r.defaultLocale,locales:s?.flatMap(p=>{let c=p?.node?.code??null;return c===null?[]:[c]})??[],...i!==null?{logo:i}:{},...a!==null?{website:a}:{}}}generateWorkspaceSlug(e,t){return ot({query:Np,baseName:t,client:this.client,variables:{organizationId:e}})}};var _p=v(`
|
|
1219
1219
|
query Audiences($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
|
|
1220
1220
|
organization(slug: $organizationSlug) {
|
|
1221
1221
|
workspace(slug: $workspaceSlug) {
|
|
@@ -1232,7 +1232,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1232
1232
|
}
|
|
1233
1233
|
}
|
|
1234
1234
|
}
|
|
1235
|
-
`),Lp=
|
|
1235
|
+
`),Lp=v(`
|
|
1236
1236
|
query Audience(
|
|
1237
1237
|
$organizationSlug: ReadableId!,
|
|
1238
1238
|
$workspaceSlug: ReadableId!,
|
|
@@ -1249,7 +1249,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1249
1249
|
}
|
|
1250
1250
|
}
|
|
1251
1251
|
}
|
|
1252
|
-
`);var Fp=
|
|
1252
|
+
`);var Fp=v(`
|
|
1253
1253
|
query Slots($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
|
|
1254
1254
|
organization(slug: $organizationSlug) {
|
|
1255
1255
|
workspace(slug: $workspaceSlug) {
|
|
@@ -1295,7 +1295,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1295
1295
|
}
|
|
1296
1296
|
}
|
|
1297
1297
|
}
|
|
1298
|
-
`),jp=
|
|
1298
|
+
`),jp=v(`
|
|
1299
1299
|
query Slot(
|
|
1300
1300
|
$organizationSlug: ReadableId!,
|
|
1301
1301
|
$workspaceSlug: ReadableId!,
|
|
@@ -1342,7 +1342,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1342
1342
|
}
|
|
1343
1343
|
}
|
|
1344
1344
|
}
|
|
1345
|
-
`),Wp=
|
|
1345
|
+
`),Wp=v(`
|
|
1346
1346
|
query SlotStaticContent(
|
|
1347
1347
|
$organizationSlug: ReadableId!,
|
|
1348
1348
|
$workspaceSlug: ReadableId!,
|
|
@@ -1360,7 +1360,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1360
1360
|
}
|
|
1361
1361
|
}
|
|
1362
1362
|
}
|
|
1363
|
-
`);var Vp=
|
|
1363
|
+
`);var Vp=v(`
|
|
1364
1364
|
query ApplicationSlugAvailability(
|
|
1365
1365
|
$workspaceId: WorkspaceId!
|
|
1366
1366
|
$slugFirstOption: ReadableId!
|
|
@@ -1373,7 +1373,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1373
1373
|
slugThirdOption: applicationSlug(workspaceId: $workspaceId, slug: $slugThirdOption)
|
|
1374
1374
|
}
|
|
1375
1375
|
}
|
|
1376
|
-
`),Up=
|
|
1376
|
+
`),Up=v(`
|
|
1377
1377
|
query Applications($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
|
|
1378
1378
|
organization(slug: $organizationSlug) {
|
|
1379
1379
|
workspace(slug: $workspaceSlug) {
|
|
@@ -1398,7 +1398,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1398
1398
|
}
|
|
1399
1399
|
}
|
|
1400
1400
|
}
|
|
1401
|
-
`),qp=
|
|
1401
|
+
`),qp=v(`
|
|
1402
1402
|
query Application($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $applicationSlug: ReadableId!) {
|
|
1403
1403
|
organization(slug: $organizationSlug) {
|
|
1404
1404
|
workspace(slug: $workspaceSlug) {
|
|
@@ -1419,7 +1419,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1419
1419
|
}
|
|
1420
1420
|
}
|
|
1421
1421
|
}
|
|
1422
|
-
`),Hp=
|
|
1422
|
+
`),Hp=v(`
|
|
1423
1423
|
mutation CreateApplication($workspaceId: WorkspaceId!, $payload: CreateWebApplicationPayload!) {
|
|
1424
1424
|
createWebApplication(workspaceId: $workspaceId, payload: $payload) {
|
|
1425
1425
|
id
|
|
@@ -1436,7 +1436,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1436
1436
|
}
|
|
1437
1437
|
}
|
|
1438
1438
|
}
|
|
1439
|
-
`),Gp=
|
|
1439
|
+
`),Gp=v(`
|
|
1440
1440
|
mutation CreateApiKey($applicationId: ApplicationId!, $payload: CreateApiKeyPayload!) {
|
|
1441
1441
|
createApiKey(applicationId: $applicationId, payload: $payload) {
|
|
1442
1442
|
apiKey {
|
|
@@ -1447,7 +1447,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1447
1447
|
apiKeyValue
|
|
1448
1448
|
}
|
|
1449
1449
|
}
|
|
1450
|
-
`);var Kp=
|
|
1450
|
+
`);var Kp=v(`
|
|
1451
1451
|
query Components($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
|
|
1452
1452
|
organization(slug: $organizationSlug) {
|
|
1453
1453
|
workspace(slug: $workspaceSlug) {
|
|
@@ -1479,7 +1479,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1479
1479
|
}
|
|
1480
1480
|
}
|
|
1481
1481
|
}
|
|
1482
|
-
`),Zp=
|
|
1482
|
+
`),Zp=v(`
|
|
1483
1483
|
query Component(
|
|
1484
1484
|
$organizationSlug: ReadableId!,
|
|
1485
1485
|
$workspaceSlug: ReadableId!,
|
|
@@ -1512,7 +1512,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1512
1512
|
}
|
|
1513
1513
|
}
|
|
1514
1514
|
}
|
|
1515
|
-
`);var Jp=
|
|
1515
|
+
`);var Jp=v(`
|
|
1516
1516
|
query Experience(
|
|
1517
1517
|
$organizationSlug: ReadableId!,
|
|
1518
1518
|
$workspaceSlug: ReadableId!,
|
|
@@ -1670,7 +1670,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1670
1670
|
}
|
|
1671
1671
|
}
|
|
1672
1672
|
}
|
|
1673
|
-
`),Qp=
|
|
1673
|
+
`),Qp=v(`
|
|
1674
1674
|
query Experiences($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $status: [ExperienceStatus!]) {
|
|
1675
1675
|
organization(slug: $organizationSlug) {
|
|
1676
1676
|
workspace(slug: $workspaceSlug) {
|
|
@@ -1726,11 +1726,11 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1726
1726
|
}
|
|
1727
1727
|
}
|
|
1728
1728
|
}
|
|
1729
|
-
`);var Bp=
|
|
1729
|
+
`);var Bp=v(`
|
|
1730
1730
|
mutation GenerateTyping($workspaceId: WorkspaceId!, $payload: GenerateTypingPayload!) {
|
|
1731
1731
|
generateTyping(workspaceId: $workspaceId, payload: $payload)
|
|
1732
1732
|
}
|
|
1733
|
-
`);function vt(o){return {model:o,api:Object.fromEntries(Object.entries(o).map(([e,t])=>[t,e]))}}var _a=vt({javascript:"JAVASCRIPT",react:"REACT",nextjs:"NEXT"}),La=vt({DEVELOPMENT:"DEVELOPMENT",PRODUCTION:"PRODUCTION"}),Yp=vt({NEVER_RECEIVED_TRAFFIC:"NEVER_RECEIVED_TRAFFIC",NOT_RECEIVING_TRAFFIC:"NOT_RECEIVING_TRAFFIC",RECEIVING_TRAFFIC:"RECEIVING_TRAFFIC"}),$l=vt({PLUG_JS:"PLUG_JS"}),Fa=vt({DRAFT:"DRAFT",ACTIVE:"ACTIVE",SCHEDULED:"SCHEDULED",PAUSED:"PAUSED",ARCHIVED:"ARCHIVED"}),zl=vt({DRAFT:"DRAFT",ACTIVE:"ACTIVE",SCHEDULED:"SCHEDULED",PAUSED:"PAUSED",FINISHED:"FINISHED",INDIRECTLY_PAUSED:"INDIRECTLY_PAUSED"}),ar=class o{constructor(e,t){this.client=e,this.hierarchyResolver=t;}async getFeatures(e){let{data:t}=await this.client.execute($p,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),n=t.organization?.workspace??null;if(n===null)return null;let{quotas:r,capabilities:{features:i}}=n;return {quotas:{audiences:r.audience,remainingAudiences:r.remainingAudiences,components:r.component,remainingComponents:r.remainingComponents,slots:r.slot,remainingSlots:r.remainingSlots,experiences:r.experience,remainingExperiences:r.remainingExperiences,experiments:r.experiment,remainingExperiments:r.remainingExperiments,dynamicAttributesPerContent:r.dynamicAttributesPerContent,audiencesPerExperience:r.audiencesPerExperience},features:{crossDevice:i.includes("CROSS_DEVICE_EXPERIMENT"),dataExport:i.includes("API_DATA_EXPORT")}}}async getApplications(e){let{data:t}=await this.client.execute(Up,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.applications.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeApplication(i)]})}async getApplication(e){let{data:t}=await this.client.execute(qp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,applicationSlug:e.applicationSlug}),n=t.organization?.workspace?.application??null;return n===null?null:o.normalizeApplication(n)}static normalizeApplication(e){let{logo:t=null}=e;return {id:e.id,name:e.name,slug:e.slug,timeZone:e.settings.timeZone,website:e.website,environment:La.api[e.environment],platform:_a.api[e.platform??"JAVASCRIPT"],publicId:e.publicId,trafficStatus:Yp.api[e.applicationStatus],...t!==null?{logo:t}:{}}}async createApplication(e){let t=await this.hierarchyResolver.getHierarchy({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),{data:n}=await this.client.execute(Hp,{workspaceId:t.workspaceId,payload:{name:e.name,website:e.website,environment:La.model[e.environment],platform:_a.model[e.platform],timeZone:e.timeZone,slug:await this.generateApplicationSlug(t.workspaceId,e.name,e.environment)}}),r=n.createWebApplication,{logo:i=null}=r;return {id:r.id,name:r.name,slug:r.slug,timeZone:r.settings.timeZone,website:r.website,environment:La.api[r.environment],platform:_a.api[r.platform??"JAVASCRIPT"],publicId:r.publicId,trafficStatus:Yp.api[r.applicationStatus],...i!==null?{logo:i}:{}}}async getAudiences(e){let{data:t}=await this.client.execute(_p,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.audiences.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeAudience(i)]})}async getAudience(e){let{data:t}=await this.client.execute(Lp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,audienceSlug:e.audienceSlug}),n=t.organization?.workspace?.audience??null;return n===null?null:o.normalizeAudience(n)}static normalizeAudience(e){return {id:e.id,name:e.name,slug:e.customId,criteria:e.criteria}}async getComponents(e){let{data:t}=await this.client.execute(Kp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.components.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeComponent(i)]})}async getComponent(e){let{data:t}=await this.client.execute(Zp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,componentSlug:e.componentSlug,majorVersion:e.majorVersion}),n=t.organization?.workspace?.component??null;return n===null?null:o.normalizeComponent(n)}static normalizeComponent(e){let{definition:t,metadata:{directReferences:n,indirectReferences:r,referenceMetadata:i}}=e.definition,a=e.description??null;return {id:e.id,name:e.name,slug:e.customId,...a!==null?{description:a}:{},definition:t,version:{major:e.definition.version.major,minor:e.definition.version.minor},metadata:{directReferences:n.map(s=>i.find(({componentId:p})=>p===s)?.referenceName??s),indirectReferences:r.map(s=>i.find(({componentId:p})=>p===s)?.referenceName??s)}}}async getSlots(e){let{data:t}=await this.client.execute(Fp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.slots.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeSlot(i)]})}async getSlot(e){let{data:t}=await this.client.execute(jp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,slotSlug:e.slotSlug,majorVersion:e.majorVersion}),n=t.organization?.workspace?.slot??null;return n===null?null:o.normalizeSlot(n)}static normalizeSlot(e){let{component:t=null}=e.content,n=t?.definition.metadata??null;return {id:e.id,name:e.name,slug:e.customId,...t!==null&&n!==null?{component:{slug:t.customId,version:{major:t.definition.version.major,minor:t.definition.version.minor},metadata:{directReferences:n.directReferences.map(r=>n.referenceMetadata.find(({componentId:i})=>i===r)?.referenceName??r),indirectReferences:n.indirectReferences.map(r=>n.referenceMetadata.find(({componentId:i})=>i===r)?.referenceName??r)}}}:{},version:{major:e.content.version.major,minor:e.content.version.minor},resolvedDefinition:e.content.componentDefinition.resolvedDefinition,content:Object.fromEntries(e.content.default.map(({locale:r,content:i})=>[r,i]))}}async getSlotStaticContent(e,t){let{data:n}=await this.client.execute(Wp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,slotSlug:e.slotSlug,majorVersion:t});return (n.organization?.workspace?.slot?.staticContent??[]).map(i=>({locale:i.locale,content:i.content}))}async generateTypes(e){let t=await this.hierarchyResolver.getHierarchy({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),{data:n}=await this.client.execute(Bp,{workspaceId:t.workspaceId,payload:{target:$l.model[e.target],components:e.components,slots:e.slots}});return n.generateTyping}async getExperiences(e){let{data:t}=await this.client.execute(Qp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,status:e.status===void 0?void 0:(Array.isArray(e.status)?e.status:[e.status]).map(r=>Fa.model[r])});return (t.organization?.workspace?.experiences.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeExperience(i)]})}async getExperience(e){let{data:t}=await this.client.execute(Jp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,experienceId:e.experienceId}),n=t.organization?.workspace?.experience??null;return n===null?null:o.normalizeExperienceDetails(n)}static normalizeExperience(e){let t=e.settings?.audiences??e.draft?.audiences??[],n=e.settings?.slots??e.draft?.slots??[],r=e.currentExperiment?.name??e.draft?.experiment?.name??null;return {id:e.id,name:e.name,priority:e.priority??e.draft?.priority??0,status:Fa.api[e.status],audiences:t.map(i=>i.customId),slots:n.flatMap(({slot:i=null})=>i===null?[]:[i.customId]),...r!==null?{experiment:{name:r}}:{}}}static normalizeExperienceDetails(e){let t=e.settings?.audiences??e.draft?.audiences??[],n=e.settings?.slots??e.draft?.slots??[],r=e.currentExperiment??e.draft?.experiment??null,{name:i=null,goalId:a=null,crossDevice:s=null,traffic:p=null}=r??{},c=Object.fromEntries(n.flatMap(({slot:l=null})=>l===null?[]:[[l.id,l.customId]]));return {id:e.id,name:e.name,priority:e.priority??e.draft?.priority??0,status:Fa.api[e.status],hasExperiments:e.hasExperiments,audiences:t.map(l=>l.customId),slots:Object.values(c),...r!==null?{experiment:{...i!==null?{name:i}:{},...a!==null?{goalId:a}:{},...s!==null?{crossDevice:s}:{},...p!==null?{traffic:p}:{},..."status"in r?{status:zl.api[r.status]}:{},variants:(r.variants??[]).map(l=>{let m=l.variantId,f=l.name??null,b=l.allocation??null;return {...m!==null?{id:m}:{},...f!==null?{name:f}:{},...b!==null?{allocation:b}:{},baseline:l.baseline===true,content:{default:o.normalizeLocalizedContent(l.content?.default.contents??[],c),segmented:(l.content?.segmented??[]).map(A=>({id:A.groupId,audiences:A.audiences.map(v=>v.audienceId),content:o.normalizeLocalizedContent(A.contents,c)}))}}})}}:{},content:{default:o.normalizeLocalizedContent(e.settings?.content.default.contents??e.draft?.content?.default.contents??[],c),segmented:(e.settings?.content.segmented??e.draft?.content?.segmented??[]).map(l=>({id:l.groupId,audiences:l.audiences.map(({audienceId:m})=>t.find(({id:f})=>f===m)?.customId??m),content:o.normalizeLocalizedContent(l.contents,c)}))}}}static normalizeLocalizedContent(e,t){let n={};for(let r of e){let{locale:i,slotId:a}=r,s=t[a];s!==void 0&&(n[s]===void 0&&(n[s]={}),n[s][i]=r.content);}return n}async createResources(e){let t=await this.hierarchyResolver.getHierarchy({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),n={components:Object.entries(e.components??{}).map(([i,a])=>({customId:i,name:a.name,description:a.description,definition:a.definition})),slots:Object.entries(e.slots??{}).map(([i,a])=>({customId:i,name:a.name,component:a.component,defaultContent:Object.entries(a.content).map(([s,p])=>({locale:s,content:p}))})),audiences:Object.entries(e.audiences??{}).map(([i,a])=>({customId:i,name:a.name,criteria:a.criteria})),experiences:(e.experiences??[]).map(i=>{let a=i.experiment??null;return {name:i.name,audiences:i.audiences,slots:i.slots,experiment:a!==null?{name:a.name,goalId:a.goalId,traffic:a.traffic,crossDevice:a.crossDevice===true,variants:a.variants.map(s=>({id:randomUUID(),name:s.name??"",baseline:s.baseline===true,allocation:s.allocation??0,content:o.createContentVariantGroup(s.content)}))}:void 0,content:o.createContentVariantGroup(i.content),validate:true,publish:i.draft===false}})},{data:{createWorkspaceResources:r}}=await this.client.execute(zp,{workspaceId:t.workspaceId,payload:n});return {components:Object.fromEntries(n.components.map(({customId:i},a)=>[i,r.components[a]])),slots:Object.fromEntries(n.slots.map(({customId:i},a)=>[i,r.slots[a]])),audiences:Object.fromEntries(n.audiences.map(({customId:i},a)=>[i,r.audiences[a]])),experiences:r.experiences.map(i=>({experienceId:i.id,experimentId:i.experimentId??null}))}}static createContentVariantGroup(e){return {default:{id:randomUUID(),contents:o.createSlotContentMap(e.default)},segmented:e.segmented.map(t=>({id:randomUUID(),audiences:t.audiences,contents:o.createSlotContentMap(t.content)}))}}static createSlotContentMap(e){return Object.entries(e).flatMap(([t,n])=>Object.entries(n).map(([r,i])=>({slot:t,locale:r,content:i})))}generateApplicationSlug(e,t,n){return ot({query:Vp,baseName:`${t} ${n.slice(0,3).toLowerCase()}`,client:this.client,variables:{workspaceId:e}})}};var at;(t=>{function o(){return Intl.DateTimeFormat().resolvedOptions().locale.toLowerCase()}t.getLocale=o;function e(){return Intl.DateTimeFormat().resolvedOptions().timeZone}t.getTimeZone=e;})(at||={});var wt=class o{constructor(e){this.config=e;}static prompt(e){return new o(e).handle()}handle(){let{input:e,validate:t}=this.config;return e.prompt({message:this.config.label,default:this.config.default??"https://",validate:n=>URL.canParse(n)?t!==void 0?t(n):true:"Invalid URL"})}};var sr=class o{constructor(e){this.config=e;}async handle(e={}){let{userApi:t,output:n,input:r}=this.config;if(e.new!==true){let c=n.notify("Loading organizations"),l=await t.getOrganizations(),m=o.getDefaultOrganization(l,e.default);if(m!==null)return c.confirm(`Organization: ${m.name}`),m;if(c.stop(),l.length>0)return r.select({message:"Select organization",options:l.map(f=>({value:f,label:f.name}))})}let i=at.getTimeZone(),a=at.getLocale();n.inform("Setting up a new organization"),n.inform("*By continuing, you agree to our [Terms of Service](https://croct.link/terms-of-service)*");let s=await wt.prompt({input:r,label:"Organization website"}),p=this.notify("Setting up organization");try{let c=await t.setupOrganization({website:s,locale:a,timeZone:i});return p.confirm(`Organization: ${c.name}`),c}finally{p.stop();}}notify(e){let{output:t}=this.config,n=["Visiting website","Detecting tech stack","Configuring organization","Creating workspace","Configuring applications","Setting up organization"],r=t.notify(e),i=0,a=setInterval(()=>{i>=n.length?clearInterval(a):r.update(n[i++]);},3e3);return {confirm:(s,p)=>{clearInterval(a),r.confirm(s,p);},stop:s=>{clearInterval(a),r.stop(s);}}}static getDefaultOrganization(e,t){return e.length===1?e[0]:t!==void 0?e.find(({slug:n})=>n===t)??null:null}};var Ne=class o{constructor(e){this.config=e;}static prompt(e){return new o(e).handle()}handle(){let{input:e,validator:t,minimumLength:n=2,maximumLength:r=30}=this.config;return e.prompt({message:this.config.label,default:this.config.default,validate:i=>/(^\s|\s$|\s{2,})/.test(i)?"No leading, trailing, or multiple spaces.":i.length<n?`Minimum of ${n} characters`:i.length>r?`Maximum of ${r} characters`:t?.(i)??true})}};var pr=class o{constructor(e){this.config=e;}async handle(e){let{organizationApi:t,output:n,input:r}=this.config,{organization:i}=e;if(e.new===false){let a=n.notify("Loading workspaces"),s=await t.getWorkspaces({organizationSlug:i.slug}),p=o.getDefaultWorkspace(s,e.default);if(p!==null)return a.confirm(`Workspace: ${p.name}`),p;if(a.stop(),s.length>0)return r.select({message:"Select workspace",options:s.map(c=>({value:c,label:c.name}))})}return this.setupWorkspace(i,e.new===true)}async setupWorkspace(e,t){let{organizationApi:n,input:r,output:i}=this.config,a=t?await Ne.prompt({input:r,label:"Workspace name",default:e.name}):e.name,s=at.getLocale(),p=at.getTimeZone(),c=i.notify("Creating workspace");try{let l=await n.createWorkspace({organizationSlug:e.slug,name:a,website:e.website,defaultLocale:s,timeZone:p});return c.confirm(`Workspace: ${l.name}`),l}finally{c.stop();}}static getDefaultWorkspace(e,t){return e.length===1?e[0]:t!==void 0?e.find(({slug:n})=>n===t)??null:null}};var cr=class o{constructor(e){this.config=e;}async handle(e){let{workspaceApi:t,output:n,input:r}=this.config,{organization:i,workspace:a,environment:s}=e,p=n.notify("Loading applications"),c=await t.getApplications({workspaceSlug:a.slug,organizationSlug:i.slug}),l=c.filter(m=>m.environment===s&&(e.default??m.slug)===m.slug);if(p.stop(),l.length===0||e.new===true)return this.setupApplication(e,c);if(l.length===1){let m=l[0];return n.confirm(o.formatSelection(m)),m}return r.select({message:s==="DEVELOPMENT"?"Select development application":"Select production application",options:l.map(m=>({value:m,label:m.name}))})}async setupApplication(e,t){let{workspaceApi:n,output:r,input:i}=this.config,{organization:a,workspace:s,platform:p,environment:c}=e,l=e.new===true,m=l?await Ne.prompt({input:i,label:"Application name",default:"Website",validator:v=>t.every(y=>y.name.toLowerCase()!==v.toLowerCase()||y.environment!==c)||"Name already in use"}):"Website",f=s.website??a.website??void 0,b=l||!o.isValidProductionUrl(f)?await wt.prompt({input:i,label:"Application website",default:f,validate:o.isValidProductionUrl}):f,A=r.notify("Configuring application");try{let v=await n.createApplication({organizationSlug:a.slug,workspaceSlug:s.slug,name:m,website:b,environment:c,platform:p,timeZone:s.timeZone});return A.confirm(o.formatSelection(v)),v}finally{A.stop();}}static isValidProductionUrl(e){return e!==void 0&&new URL(e).hostname!=="localhost"}static formatSelection(e){return e.environment==="DEVELOPMENT"?`Development application: ${e.name} (${e.slug})`:`Production application: ${e.name} (${e.slug})`}};var lr=class{constructor(e,t){this.client=e,this.hierarchyResolver=t;}async createApiKey(e){let t=await this.hierarchyResolver.getHierarchy({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,applicationSlug:e.applicationSlug}),{data:n}=await this.client.execute(Gp,{applicationId:t.applicationId,payload:{name:e.name,permissions:e.permissions}}),{apiKey:r}=n.createApiKey;return {id:r.id,name:r.name,permissions:r.permissions.map(Ee.fromValue),secret:n.createApiKey.apiKeyValue}}};var Ke=class o{constructor(e){this.config=e;}static prompt(e){return new o(e).handle()}handle(){let{input:e}=this.config;return e.prompt({message:this.config.label,validate:t=>t.length>255?"The email must be less than 255 characters":/^([A-Z0-9_+-]+\.?)*[A-Z0-9_+-]@([A-Z0-9][A-Z0-9-]*\.)+[A-Z]{2,}$/i.test(t)?true:"Please enter a valid email"})}};var ur=class{constructor(e){this.config=e;}getToken(){return Promise.resolve(null)}login(e={}){if(e.username===void 0||e.password===void 0)return this.loginInteractively(e);let{form:t}=this.config;return t.signIn.handle({email:e.username,password:e.password})}async loginInteractively(e){let{input:t,output:n,userApi:r,form:i}=this.config,a=e.username??await Ke.prompt({input:t,label:"Enter your email"}),s=n.notify("Finding account"),p=await r.isEmailRegistered(a);return s.stop(),p?(e.password===void 0&&n.inform("Account found, please sign in"),i.signIn.handle({email:a,password:e.password,retry:true})):(n.inform("New account, please sign up"),i.signUp.handle({email:a}))}logout(){return Promise.resolve()}};var Ze=class o{constructor(e){this.config=e;}static prompt(e){return new o(e).handle()}handle(){let{input:e}=this.config;return e.prompt({message:this.config.label,type:"password",validate:this.config.validator??(t=>t.length>0?true:"Please enter your password")})}};var mr=class{constructor(e){this.config=e;}handle(e){return this.login(e.email,e.password,e.retry)}async login(e,t,n=false){let{input:r,output:i,userApi:a}=this.config,s=e??await Ke.prompt({input:this.config.input,label:"Enter your email"}),p=t,c="retry-password";for(;c==="retry-password";){let l=p??await Ze.prompt({input:r,label:"Password"});p=void 0;let m=i.notify("Checking credentials");try{let f=await a.signIn({email:s,password:l,duration:this.config.tokenDuration});return m.confirm("Logged in"),f}catch(f){if(f instanceof ne){if(f.isAccessDenied("UNVERIFIED_USER")){if(!n)throw new d("Email not verified.",{reason:"access_denied",cause:f,suggestions:["Access your email and click on the activation link"]});m.warn("Email not verified"),c=await r.confirm({message:"Resend activation link?",default:true})?"retry-activation":"cancel";continue}if(f.isAccessDenied("BAD_CREDENTIALS")){if(!n)throw new d("Username or password is incorrect.",{reason:"access_denied",cause:f,suggestions:["Check your credentials or reset your password"]});m.alert("Wrong password"),c=await r.select({message:"What would you like to do?",default:"retry-password",options:[{label:"Try again",value:"retry-password"},{label:"Recover password",value:"reset-password"},...e===void 0?[{label:"Enter a different email",value:"change-email"}]:[],{label:"Cancel",value:"cancel"}]});continue}}throw m.stop(),f}}switch(c){case "change-email":return this.login();case "retry-activation":return this.retryActivation(s);case "reset-password":return this.resetPassword(s);case "cancel":default:return i.exit()}}async retryActivation(e){let{output:t,userApi:n,emailLinkGenerator:{verification:r}}=this.config,i=t.notify("Sending email"),a=await n.createSession({destination:this.config.verificationLinkDestination.accountActivation});await n.retryActivation({email:e,sessionId:a}),i.confirm(`Link sent to \`${e}\``);let s=await this.getInboxLink(r,e),p=this.waitToken(a);return s!==null&&await t.open(s),p}async resetPassword(e){let{output:t,userApi:n,emailLinkGenerator:{recovery:r}}=this.config,i=t.notify("Sending link to reset password"),a=await n.createSession({destination:this.config.verificationLinkDestination.passwordReset});await n.requestPasswordReset({email:e,sessionId:a}),i.confirm(`Link sent to \`${e}\``);let s=await this.getInboxLink(r,e),p=this.waitToken(a);return s!==null&&await t.open(s),n.resetPassword({token:await p,password:await this.createPassword()})}async createPassword(){let{input:e,output:t}=this.config,n=null;for(;n===null;){let r=await Ze.prompt({input:e,label:"Enter your new password"}),i=await Ze.prompt({input:e,label:"Confirm your new password"});if(r!==i){t.warn("Passwords do not match, please try again");continue}n=r;}return n}async getInboxLink(e,t){let{input:n}=this.config,r=await e(t);return r!==null&&await n.confirm({message:"Open your inbox?",default:true})?r.toString():null}async waitToken(e){let{output:t,listener:n}=this.config,r=t.notify("Waiting for confirmation"),i=await n.wait(e);return r.confirm("Login completed"),i}};var dr=class{constructor(e){this.config=e;}async handle(e){let{input:t,output:n,listener:r,userApi:i}=this.config;n.inform("*By continuing, you agree to our [Terms of Use](https://croct.link/terms-of-use) and [Privacy Policy](https://croct.link/privacy)*");let a=await Ne.prompt({input:t,minimumLength:2,maximumLength:30,label:"Name"}),[s,p]=a.replace(/\s+/g," ").trim().split(" "),c=e.email??await Ke.prompt({input:t,label:"Email"}),l=await Ze.prompt({input:t,label:"Password",validator:y=>/[A-Z]/.test(y)?/[a-z]/.test(y)?/[^A-Za-z]/.test(y)?y.length<8?"Minimum of 8 characters":y.length>256?"Maximum of 256 characters":true:"Must contain a special character":"Must contain a lowercase letter":"Must contain an uppercase letter"}),m=i.createSession({destination:this.config.verificationLinkDestination}),f=n.notify("Creating account");await i.registerUser({sessionId:await m,email:c,password:l,firstName:s,lastName:p,expertise:e.expertise??"ENGINEERING"}),f.confirm(`Link to verify sent to \`${c}\``);let b=await this.config.emailLinkGenerator(c).then(async y=>y!==null&&await t.confirm({message:"Open your inbox?",default:true})?y.toString():null);f=n.notify("Waiting for account activation");let A=r.wait(await m);b!==null&&await n.open(b);let v=await A;return f.confirm("Account activated"),v}};var gr=class{constructor(e){this.config=e;}async execute(e){let{output:t,pageForm:n,userApi:r}=this.config,i=await this.config.configurationManager.load(),a=await n.handle({page:e.page,organizationSlug:i.organization,workspaceSlug:i.workspace,devApplicationSlug:i.applications.development,prodApplicationSlug:i.applications.production}),s=t.notify("Logging in..."),p=await r.issueToken({duration:this.config.adminTokenDuration});s.stop();let c=new URL(a.startsWith("/")?a.slice(1):a,this.config.adminUrl);c.searchParams.set(this.config.adminTokenParameter,p),await t.open(c.toString());}};function ge(o,e){let t=[],n=null;if(traverse(o,{ImportDeclaration:i=>{let{node:a}=i;if(a.source.value!==e.moduleName)return i.skip();t.push({declaration:a});let s=a.importKind??"value";for(let p of a.specifiers)if(!(!g.isImportSpecifier(p)||Ll(p.imported)!==e.importName)){if(s==="value"&&(p.importKind===null||p.importKind===e.type)||s==="type"&&e.type==="type")return n=p.local.name,i.stop();t.unshift({declaration:a,specifier:p,localName:p.local.name});}return i.skip()}}),n!==null)return {modified:false,localName:n};if(t.length>0){for(let i of t){let{declaration:a}=i;if(a.importKind==="type"&&e.type==="value"){a.importKind="value";for(let s of a.specifiers)g.isImportSpecifier(s)&&s!==i.specifier&&(s.importKind="type");if(i.localName===void 0){let s=g.importSpecifier(g.identifier(e.localName??e.importName),g.identifier(e.importName));s.importKind=e.type,a.specifiers.push(s);}return {modified:true,localName:i.localName??e.importName}}if(i.specifier!==void 0&&i.specifier.importKind==="type"&&e.type==="value")return i.specifier.importKind="value",{modified:true,localName:i.localName}}for(let{declaration:i}of t){let a=i.importKind??"value";if(a==="value"||a===e.type){let s=g.importSpecifier(g.identifier(e.localName??e.importName),g.identifier(e.importName));return a!==e.type&&(s.importKind="type"),i.specifiers.push(s),{modified:true,localName:e.localName??e.importName}}}}let r=g.importDeclaration([g.importSpecifier(g.identifier(e.localName??e.importName),g.identifier(e.importName))],g.stringLiteral(e.moduleName));return e.type==="type"&&(r.importKind="type"),o.program.body.unshift(r),{modified:true,localName:e.localName??e.importName}}function Ll(o){return g.isIdentifier(o)?o.name:o.value}function Ct(o,e){let t=typeof o=="string"?Ge(o,["jsx","typescript"]):o,n=null;return traverse(t,{ImportDeclaration:r=>{let{node:i}=r;if(!fr(i.source.value,e.moduleName))return r.skip();for(let a of i.specifiers??[]){if(g.isImportDefaultSpecifier(a)){fr("default",e.importName)&&(n=a.local.name);continue}if(g.isImportSpecifier(a)&&fr(a.imported,e.importName))return n=a.local.name,r.skip()}return r.skip()}}),n}function fr(o,e){return typeof o!="string"?fr(g.isIdentifier(o)?o.name:o.value,e):typeof e=="string"?o===e:e.test(o)}function yr(o){let e=[];for(let[t,n]of Object.entries(o))e.push(g.jsxAttribute(g.jsxIdentifier(t),g.jsxExpressionContainer(st(n))));return e}function st(o){switch(o.type){case "reference":return o.path.length<2?g.identifier(o.path[0]):o.path.slice(2).reduce((e,t)=>g.memberExpression(e,g.identifier(t)),g.memberExpression(g.identifier(o.path[0]),g.identifier(o.path[1])));case "literal":return typeof o.value=="string"?g.stringLiteral(o.value):typeof o.value=="number"?g.numericLiteral(o.value):typeof o.value=="boolean"?g.booleanLiteral(o.value):g.nullLiteral();case "comparison":return g.binaryExpression(o.operator,st(o.left),st(o.right));case "ternary":return g.conditionalExpression(g.binaryExpression(o.condition.operator,st(o.condition.left),st(o.condition.right)),st(o.consequent),st(o.alternate))}}var pt=class o{constructor(e){this.configuration=e;}apply(e,t){let n=Ct(e,{importName:this.configuration.wrapper.component,moduleName:this.configuration.wrapper.module}),r=n??this.configuration.wrapper.component,i=[],a=1;if(traverse(e,{ExportDefaultDeclaration:p=>(a=this.wrapDeclaration(p.node.declaration,r,e,t),p.stop()),ExportNamedDeclaration:p=>(i.push(p.node),p.skip())}),a===1&&this.configuration?.fallbackToNamedExports===true)for(let p of i){if(g.isFunctionDeclaration(p.declaration)&&(a=this.wrapBlockStatement(p.declaration.body,r,e,t),a===0))break;if(g.isVariableDeclaration(p.declaration)){let{declarations:c}=p.declaration;if(c.some(m=>g.isIdentifier(m.init)||g.isArrowFunctionExpression(m.init)||g.isFunctionExpression(m.init)?this.wrapDeclaration(m.init,r,e,t)===0:false)){a=0;break}}for(let c of p.specifiers??[])if(g.isExportSpecifier(c)){let l=this.findComponentDeclaration(e,c.local.name);if(l!==null&&g.isVariableDeclarator(l)&&g.isExpression(l.init)&&(a=this.wrapDeclaration(l.init,r,e,t),a===0))break}if(a===0)break}if(a===0&&n===null){let{body:p}=e.program;g.isImportDeclaration(p[0])||p.unshift(g.emptyStatement()),ge(e,{type:"value",moduleName:this.configuration.wrapper.module,importName:this.configuration.wrapper.component});}let s=this.configuration?.fallbackCodemod;return a===1&&s!==void 0?s.apply(e,t):Promise.resolve({modified:a===0,result:e})}wrapDeclaration(e,t,n,r){if(g.isArrowFunctionExpression(e)){if(g.isBlockStatement(e.body))return this.wrapBlockStatement(e.body,t,n,r);let i=this.insertWrapper(e.body,t,n,r);return i.result!==0?i.result:(e.body=i.node,0)}if(g.isFunctionExpression(e)||g.isFunctionDeclaration(e))return this.wrapBlockStatement(e.body,t,n,r);if(g.isIdentifier(e)){let i=this.findComponentDeclaration(n,e.name);if(i!==null)if(g.isVariableDeclarator(i)){let a=i.init??null;if(a!==null)return this.wrapDeclaration(a,t,n,r)}else return this.wrapBlockStatement(i.body,t,n,r)}return 1}wrapBlockStatement(e,t,n,r){let i=o.findReturnStatement(e),a=i?.argument??null;if(i!==null&&a!==null){let s=this.insertWrapper(a,t,n,r);return s.result!==0?s.result:(i.argument=g.parenthesizedExpression(s.node),0)}return 1}insertWrapper(e,t,n,r){if(this.containsElement(e,t))return {result:2,node:e};let i=this.findTargetChildren(n,e);if(i!==null){let{parent:a,index:s}=i,p=[...a.children??[]],c=p.splice(s,1)[0];return i.parent.children=p.length===0?[g.jsxText(`
|
|
1733
|
+
`);function vt(o){return {model:o,api:Object.fromEntries(Object.entries(o).map(([e,t])=>[t,e]))}}var _a=vt({javascript:"JAVASCRIPT",react:"REACT",nextjs:"NEXT"}),La=vt({DEVELOPMENT:"DEVELOPMENT",PRODUCTION:"PRODUCTION"}),Yp=vt({NEVER_RECEIVED_TRAFFIC:"NEVER_RECEIVED_TRAFFIC",NOT_RECEIVING_TRAFFIC:"NOT_RECEIVING_TRAFFIC",RECEIVING_TRAFFIC:"RECEIVING_TRAFFIC"}),$l=vt({PLUG_JS:"PLUG_JS"}),Fa=vt({DRAFT:"DRAFT",ACTIVE:"ACTIVE",SCHEDULED:"SCHEDULED",PAUSED:"PAUSED",ARCHIVED:"ARCHIVED"}),zl=vt({DRAFT:"DRAFT",ACTIVE:"ACTIVE",SCHEDULED:"SCHEDULED",PAUSED:"PAUSED",FINISHED:"FINISHED",INDIRECTLY_PAUSED:"INDIRECTLY_PAUSED"}),ar=class o{constructor(e,t){this.client=e,this.hierarchyResolver=t;}async getFeatures(e){let{data:t}=await this.client.execute($p,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),n=t.organization?.workspace??null;if(n===null)return null;let{quotas:r,capabilities:{features:i}}=n;return {quotas:{audiences:r.audience,remainingAudiences:r.remainingAudiences,components:r.component,remainingComponents:r.remainingComponents,slots:r.slot,remainingSlots:r.remainingSlots,experiences:r.experience,remainingExperiences:r.remainingExperiences,experiments:r.experiment,remainingExperiments:r.remainingExperiments,dynamicAttributesPerContent:r.dynamicAttributesPerContent,audiencesPerExperience:r.audiencesPerExperience},features:{crossDevice:i.includes("CROSS_DEVICE_EXPERIMENT"),dataExport:i.includes("API_DATA_EXPORT")}}}async getApplications(e){let{data:t}=await this.client.execute(Up,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.applications.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeApplication(i)]})}async getApplication(e){let{data:t}=await this.client.execute(qp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,applicationSlug:e.applicationSlug}),n=t.organization?.workspace?.application??null;return n===null?null:o.normalizeApplication(n)}static normalizeApplication(e){let{logo:t=null}=e;return {id:e.id,name:e.name,slug:e.slug,timeZone:e.settings.timeZone,website:e.website,environment:La.api[e.environment],platform:_a.api[e.platform??"JAVASCRIPT"],publicId:e.publicId,trafficStatus:Yp.api[e.applicationStatus],...t!==null?{logo:t}:{}}}async createApplication(e){let t=await this.hierarchyResolver.getHierarchy({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),{data:n}=await this.client.execute(Hp,{workspaceId:t.workspaceId,payload:{name:e.name,website:e.website,environment:La.model[e.environment],platform:_a.model[e.platform],timeZone:e.timeZone,slug:await this.generateApplicationSlug(t.workspaceId,e.name,e.environment)}}),r=n.createWebApplication,{logo:i=null}=r;return {id:r.id,name:r.name,slug:r.slug,timeZone:r.settings.timeZone,website:r.website,environment:La.api[r.environment],platform:_a.api[r.platform??"JAVASCRIPT"],publicId:r.publicId,trafficStatus:Yp.api[r.applicationStatus],...i!==null?{logo:i}:{}}}async getAudiences(e){let{data:t}=await this.client.execute(_p,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.audiences.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeAudience(i)]})}async getAudience(e){let{data:t}=await this.client.execute(Lp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,audienceSlug:e.audienceSlug}),n=t.organization?.workspace?.audience??null;return n===null?null:o.normalizeAudience(n)}static normalizeAudience(e){return {id:e.id,name:e.name,slug:e.customId,criteria:e.criteria}}async getComponents(e){let{data:t}=await this.client.execute(Kp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.components.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeComponent(i)]})}async getComponent(e){let{data:t}=await this.client.execute(Zp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,componentSlug:e.componentSlug,majorVersion:e.majorVersion}),n=t.organization?.workspace?.component??null;return n===null?null:o.normalizeComponent(n)}static normalizeComponent(e){let{definition:t,metadata:{directReferences:n,indirectReferences:r,referenceMetadata:i}}=e.definition,a=e.description??null;return {id:e.id,name:e.name,slug:e.customId,...a!==null?{description:a}:{},definition:t,version:{major:e.definition.version.major,minor:e.definition.version.minor},metadata:{directReferences:n.map(s=>i.find(({componentId:p})=>p===s)?.referenceName??s),indirectReferences:r.map(s=>i.find(({componentId:p})=>p===s)?.referenceName??s)}}}async getSlots(e){let{data:t}=await this.client.execute(Fp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.slots.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeSlot(i)]})}async getSlot(e){let{data:t}=await this.client.execute(jp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,slotSlug:e.slotSlug,majorVersion:e.majorVersion}),n=t.organization?.workspace?.slot??null;return n===null?null:o.normalizeSlot(n)}static normalizeSlot(e){let{component:t=null}=e.content,n=t?.definition.metadata??null;return {id:e.id,name:e.name,slug:e.customId,...t!==null&&n!==null?{component:{slug:t.customId,version:{major:t.definition.version.major,minor:t.definition.version.minor},metadata:{directReferences:n.directReferences.map(r=>n.referenceMetadata.find(({componentId:i})=>i===r)?.referenceName??r),indirectReferences:n.indirectReferences.map(r=>n.referenceMetadata.find(({componentId:i})=>i===r)?.referenceName??r)}}}:{},version:{major:e.content.version.major,minor:e.content.version.minor},resolvedDefinition:e.content.componentDefinition.resolvedDefinition,content:Object.fromEntries(e.content.default.map(({locale:r,content:i})=>[r,i]))}}async getSlotStaticContent(e,t){let{data:n}=await this.client.execute(Wp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,slotSlug:e.slotSlug,majorVersion:t});return (n.organization?.workspace?.slot?.staticContent??[]).map(i=>({locale:i.locale,content:i.content}))}async generateTypes(e){let t=await this.hierarchyResolver.getHierarchy({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),{data:n}=await this.client.execute(Bp,{workspaceId:t.workspaceId,payload:{target:$l.model[e.target],components:e.components,slots:e.slots}});return n.generateTyping}async getExperiences(e){let{data:t}=await this.client.execute(Qp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,status:e.status===void 0?void 0:(Array.isArray(e.status)?e.status:[e.status]).map(r=>Fa.model[r])});return (t.organization?.workspace?.experiences.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeExperience(i)]})}async getExperience(e){let{data:t}=await this.client.execute(Jp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,experienceId:e.experienceId}),n=t.organization?.workspace?.experience??null;return n===null?null:o.normalizeExperienceDetails(n)}static normalizeExperience(e){let t=e.settings?.audiences??e.draft?.audiences??[],n=e.settings?.slots??e.draft?.slots??[],r=e.currentExperiment?.name??e.draft?.experiment?.name??null;return {id:e.id,name:e.name,priority:e.priority??e.draft?.priority??0,status:Fa.api[e.status],audiences:t.map(i=>i.customId),slots:n.flatMap(({slot:i=null})=>i===null?[]:[i.customId]),...r!==null?{experiment:{name:r}}:{}}}static normalizeExperienceDetails(e){let t=e.settings?.audiences??e.draft?.audiences??[],n=e.settings?.slots??e.draft?.slots??[],r=e.currentExperiment??e.draft?.experiment??null,{name:i=null,goalId:a=null,crossDevice:s=null,traffic:p=null}=r??{},c=Object.fromEntries(n.flatMap(({slot:l=null})=>l===null?[]:[[l.id,l.customId]]));return {id:e.id,name:e.name,priority:e.priority??e.draft?.priority??0,status:Fa.api[e.status],hasExperiments:e.hasExperiments,audiences:t.map(l=>l.customId),slots:Object.values(c),...r!==null?{experiment:{...i!==null?{name:i}:{},...a!==null?{goalId:a}:{},...s!==null?{crossDevice:s}:{},...p!==null?{traffic:p}:{},..."status"in r?{status:zl.api[r.status]}:{},variants:(r.variants??[]).map(l=>{let m=l.variantId,f=l.name??null,b=l.allocation??null;return {...m!==null?{id:m}:{},...f!==null?{name:f}:{},...b!==null?{allocation:b}:{},baseline:l.baseline===true,content:{default:o.normalizeLocalizedContent(l.content?.default.contents??[],c),segmented:(l.content?.segmented??[]).map(A=>({id:A.groupId,audiences:A.audiences.map(I=>I.audienceId),content:o.normalizeLocalizedContent(A.contents,c)}))}}})}}:{},content:{default:o.normalizeLocalizedContent(e.settings?.content.default.contents??e.draft?.content?.default.contents??[],c),segmented:(e.settings?.content.segmented??e.draft?.content?.segmented??[]).map(l=>({id:l.groupId,audiences:l.audiences.map(({audienceId:m})=>t.find(({id:f})=>f===m)?.customId??m),content:o.normalizeLocalizedContent(l.contents,c)}))}}}static normalizeLocalizedContent(e,t){let n={};for(let r of e){let{locale:i,slotId:a}=r,s=t[a];s!==void 0&&(n[s]===void 0&&(n[s]={}),n[s][i]=r.content);}return n}async createResources(e){let t=await this.hierarchyResolver.getHierarchy({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),n={components:Object.entries(e.components??{}).map(([i,a])=>({customId:i,name:a.name,description:a.description,definition:a.definition})),slots:Object.entries(e.slots??{}).map(([i,a])=>({customId:i,name:a.name,component:a.component,defaultContent:Object.entries(a.content).map(([s,p])=>({locale:s,content:p}))})),audiences:Object.entries(e.audiences??{}).map(([i,a])=>({customId:i,name:a.name,criteria:a.criteria})),experiences:(e.experiences??[]).map(i=>{let a=i.experiment??null;return {name:i.name,audiences:i.audiences,slots:i.slots,experiment:a!==null?{name:a.name,goalId:a.goalId,traffic:a.traffic,crossDevice:a.crossDevice===true,variants:a.variants.map(s=>({id:randomUUID(),name:s.name??"",baseline:s.baseline===true,allocation:s.allocation??0,content:o.createContentVariantGroup(s.content)}))}:void 0,content:o.createContentVariantGroup(i.content),validate:true,publish:i.draft===false}})},{data:{createWorkspaceResources:r}}=await this.client.execute(zp,{workspaceId:t.workspaceId,payload:n});return {components:Object.fromEntries(n.components.map(({customId:i},a)=>[i,r.components[a]])),slots:Object.fromEntries(n.slots.map(({customId:i},a)=>[i,r.slots[a]])),audiences:Object.fromEntries(n.audiences.map(({customId:i},a)=>[i,r.audiences[a]])),experiences:r.experiences.map(i=>({experienceId:i.id,experimentId:i.experimentId??null}))}}static createContentVariantGroup(e){return {default:{id:randomUUID(),contents:o.createSlotContentMap(e.default)},segmented:e.segmented.map(t=>({id:randomUUID(),audiences:t.audiences,contents:o.createSlotContentMap(t.content)}))}}static createSlotContentMap(e){return Object.entries(e).flatMap(([t,n])=>Object.entries(n).map(([r,i])=>({slot:t,locale:r,content:i})))}generateApplicationSlug(e,t,n){return ot({query:Vp,baseName:`${t} ${n.slice(0,3).toLowerCase()}`,client:this.client,variables:{workspaceId:e}})}};var at;(t=>{function o(){return Intl.DateTimeFormat().resolvedOptions().locale.toLowerCase()}t.getLocale=o;function e(){return Intl.DateTimeFormat().resolvedOptions().timeZone}t.getTimeZone=e;})(at||={});var wt=class o{constructor(e){this.config=e;}static prompt(e){return new o(e).handle()}handle(){let{input:e,validate:t}=this.config;return e.prompt({message:this.config.label,default:this.config.default??"https://",validate:n=>URL.canParse(n)?t!==void 0?t(n):true:"Invalid URL"})}};var sr=class{constructor(e){this.config=e;}async handle(e={}){let{userApi:t,output:n,input:r}=this.config;if(e.new!==true){let c=n.notify("Loading organizations"),l=[];if(e.default!==void 0){let m=await t.getOrganization(e.default);m!==null&&l.push(m);}if(l.length===0&&l.push(...await t.getOrganizations()),l.length===1){let m=l[0];return c.confirm(`Organization: ${m.name}`),m}if(c.stop(),l.length>0)return r.select({message:"Select organization",options:l.map(m=>({value:m,label:m.name}))})}let i=at.getTimeZone(),a=at.getLocale();n.inform("Setting up a new organization"),n.inform("*By continuing, you agree to our [Terms of Service](https://croct.link/terms-of-service)*");let s=await wt.prompt({input:r,label:"Organization website"}),p=this.notify("Setting up organization");try{let c=await t.setupOrganization({website:s,locale:a,timeZone:i});return p.confirm(`Organization: ${c.name}`),c}finally{p.stop();}}notify(e){let{output:t}=this.config,n=["Visiting website","Detecting tech stack","Configuring organization","Creating workspace","Configuring applications","Setting up organization"],r=t.notify(e),i=0,a=setInterval(()=>{i>=n.length?clearInterval(a):r.update(n[i++]);},3e3);return {confirm:(s,p)=>{clearInterval(a),r.confirm(s,p);},stop:s=>{clearInterval(a),r.stop(s);}}}};var Ne=class o{constructor(e){this.config=e;}static prompt(e){return new o(e).handle()}handle(){let{input:e,validator:t,minimumLength:n=2,maximumLength:r=30}=this.config;return e.prompt({message:this.config.label,default:this.config.default,validate:i=>/(^\s|\s$|\s{2,})/.test(i)?"No leading, trailing, or multiple spaces.":i.length<n?`Minimum of ${n} characters`:i.length>r?`Maximum of ${r} characters`:t?.(i)??true})}};var pr=class o{constructor(e){this.config=e;}async handle(e){let{organizationApi:t,output:n,input:r}=this.config,{organization:i}=e;if(e.new===false){let a=n.notify("Loading workspaces"),s=await t.getWorkspaces({organizationSlug:i.slug}),p=o.getDefaultWorkspace(s,e.default);if(p!==null)return a.confirm(`Workspace: ${p.name}`),p;if(a.stop(),s.length>0)return r.select({message:"Select workspace",options:s.map(c=>({value:c,label:c.name}))})}return this.setupWorkspace(i,e.new===true)}async setupWorkspace(e,t){let{organizationApi:n,input:r,output:i}=this.config,a=t?await Ne.prompt({input:r,label:"Workspace name",default:e.name}):e.name,s=at.getLocale(),p=at.getTimeZone(),c=i.notify("Creating workspace");try{let l=await n.createWorkspace({organizationSlug:e.slug,name:a,website:e.website,defaultLocale:s,timeZone:p});return c.confirm(`Workspace: ${l.name}`),l}finally{c.stop();}}static getDefaultWorkspace(e,t){return e.length===1?e[0]:t!==void 0?e.find(({slug:n})=>n===t)??null:null}};var cr=class o{constructor(e){this.config=e;}async handle(e){let{workspaceApi:t,output:n,input:r}=this.config,{organization:i,workspace:a,environment:s}=e,p=n.notify("Loading applications"),c=await t.getApplications({workspaceSlug:a.slug,organizationSlug:i.slug}),l=c.filter(m=>m.environment===s&&(e.default??m.slug)===m.slug);if(p.stop(),l.length===0||e.new===true)return this.setupApplication(e,c);if(l.length===1){let m=l[0];return n.confirm(o.formatSelection(m)),m}return r.select({message:s==="DEVELOPMENT"?"Select development application":"Select production application",options:l.map(m=>({value:m,label:m.name}))})}async setupApplication(e,t){let{workspaceApi:n,output:r,input:i}=this.config,{organization:a,workspace:s,platform:p,environment:c}=e,l=e.new===true,m=l?await Ne.prompt({input:i,label:"Application name",default:"Website",validator:I=>t.every(y=>y.name.toLowerCase()!==I.toLowerCase()||y.environment!==c)||"Name already in use"}):"Website",f=s.website??a.website??void 0,b=l||!o.isValidUrl(f,c)?await wt.prompt({input:i,label:"Application website",default:f,validate:I=>URL.canParse(I)?o.isValidUrl(I,c)?true:"Production URL must not be localhost":"Invalid URL"}):f,A=r.notify("Configuring application");try{let I=await n.createApplication({organizationSlug:a.slug,workspaceSlug:s.slug,name:m,website:b,environment:c,platform:p,timeZone:s.timeZone});return A.confirm(o.formatSelection(I)),I}finally{A.stop();}}static isValidUrl(e,t){return e===void 0||!URL.canParse(e)?false:t!=="PRODUCTION"||new URL(e).hostname!=="localhost"}static formatSelection(e){return e.environment==="DEVELOPMENT"?`Development application: ${e.name} (${e.slug})`:`Production application: ${e.name} (${e.slug})`}};var lr=class{constructor(e,t){this.client=e,this.hierarchyResolver=t;}async createApiKey(e){let t=await this.hierarchyResolver.getHierarchy({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,applicationSlug:e.applicationSlug}),{data:n}=await this.client.execute(Gp,{applicationId:t.applicationId,payload:{name:e.name,permissions:e.permissions}}),{apiKey:r}=n.createApiKey;return {id:r.id,name:r.name,permissions:r.permissions.map(Ee.fromValue),secret:n.createApiKey.apiKeyValue}}};var Ke=class o{constructor(e){this.config=e;}static prompt(e){return new o(e).handle()}handle(){let{input:e}=this.config;return e.prompt({message:this.config.label,validate:t=>t.length>255?"The email must be less than 255 characters":/^([A-Z0-9_+-]+\.?)*[A-Z0-9_+-]@([A-Z0-9][A-Z0-9-]*\.)+[A-Z]{2,}$/i.test(t)?true:"Please enter a valid email"})}};var ur=class{constructor(e){this.config=e;}getToken(){return Promise.resolve(null)}login(e={}){if(e.username===void 0||e.password===void 0)return this.loginInteractively(e);let{form:t}=this.config;return t.signIn.handle({email:e.username,password:e.password})}async loginInteractively(e){let{input:t,output:n,userApi:r,form:i}=this.config,a=e.username??await Ke.prompt({input:t,label:"Enter your email"}),s=n.notify("Finding account"),p=await r.isEmailRegistered(a);return s.stop(),p?(e.password===void 0&&n.inform("Account found, please sign in"),i.signIn.handle({email:a,password:e.password,retry:true})):(n.inform("New account, please sign up"),i.signUp.handle({email:a}))}logout(){return Promise.resolve()}};var Ze=class o{constructor(e){this.config=e;}static prompt(e){return new o(e).handle()}handle(){let{input:e}=this.config;return e.prompt({message:this.config.label,type:"password",validate:this.config.validator??(t=>t.length>0?true:"Please enter your password")})}};var mr=class{constructor(e){this.config=e;}handle(e){return this.login(e.email,e.password,e.retry)}async login(e,t,n=false){let{input:r,output:i,userApi:a}=this.config,s=e??await Ke.prompt({input:this.config.input,label:"Enter your email"}),p=t,c="retry-password";for(;c==="retry-password";){let l=p??await Ze.prompt({input:r,label:"Password"});p=void 0;let m=i.notify("Checking credentials");try{let f=await a.signIn({email:s,password:l,duration:this.config.tokenDuration});return m.confirm("Logged in"),f}catch(f){if(f instanceof ne){if(f.isAccessDenied("UNVERIFIED_USER")){if(!n)throw new d("Email not verified.",{reason:"access_denied",cause:f,suggestions:["Access your email and click on the activation link"]});m.warn("Email not verified"),c=await r.confirm({message:"Resend activation link?",default:true})?"retry-activation":"cancel";continue}if(f.isAccessDenied("BAD_CREDENTIALS")){if(!n)throw new d("Username or password is incorrect.",{reason:"access_denied",cause:f,suggestions:["Check your credentials or reset your password"]});m.alert("Wrong password"),c=await r.select({message:"What would you like to do?",default:"retry-password",options:[{label:"Try again",value:"retry-password"},{label:"Recover password",value:"reset-password"},...e===void 0?[{label:"Enter a different email",value:"change-email"}]:[],{label:"Cancel",value:"cancel"}]});continue}}throw m.stop(),f}}switch(c){case "change-email":return this.login();case "retry-activation":return this.retryActivation(s);case "reset-password":return this.resetPassword(s);case "cancel":default:return i.exit()}}async retryActivation(e){let{output:t,userApi:n,emailLinkGenerator:{verification:r}}=this.config,i=t.notify("Sending email"),a=await n.createSession({destination:this.config.verificationLinkDestination.accountActivation});await n.retryActivation({email:e,sessionId:a}),i.confirm(`Link sent to \`${e}\``);let s=await this.getInboxLink(r,e),p=this.waitToken(a);return s!==null&&await t.open(s),p}async resetPassword(e){let{output:t,userApi:n,emailLinkGenerator:{recovery:r}}=this.config,i=t.notify("Sending link to reset password"),a=await n.createSession({destination:this.config.verificationLinkDestination.passwordReset});await n.requestPasswordReset({email:e,sessionId:a}),i.confirm(`Link sent to \`${e}\``);let s=await this.getInboxLink(r,e),p=this.waitToken(a);return s!==null&&await t.open(s),n.resetPassword({token:await p,password:await this.createPassword()})}async createPassword(){let{input:e,output:t}=this.config,n=null;for(;n===null;){let r=await Ze.prompt({input:e,label:"Enter your new password"}),i=await Ze.prompt({input:e,label:"Confirm your new password"});if(r!==i){t.warn("Passwords do not match, please try again");continue}n=r;}return n}async getInboxLink(e,t){let{input:n}=this.config,r=await e(t);return r!==null&&await n.confirm({message:"Open your inbox?",default:true})?r.toString():null}async waitToken(e){let{output:t,listener:n}=this.config,r=t.notify("Waiting for confirmation"),i=await n.wait(e);return r.confirm("Login completed"),i}};var dr=class{constructor(e){this.config=e;}async handle(e){let{input:t,output:n,listener:r,userApi:i}=this.config;n.inform("*By continuing, you agree to our [Terms of Use](https://croct.link/terms-of-use) and [Privacy Policy](https://croct.link/privacy)*");let a=await Ne.prompt({input:t,minimumLength:2,maximumLength:30,label:"Name"}),[s,p]=a.replace(/\s+/g," ").trim().split(" "),c=e.email??await Ke.prompt({input:t,label:"Email"}),l=await Ze.prompt({input:t,label:"Password",validator:y=>/[A-Z]/.test(y)?/[a-z]/.test(y)?/[^A-Za-z]/.test(y)?y.length<8?"Minimum of 8 characters":y.length>256?"Maximum of 256 characters":true:"Must contain a special character":"Must contain a lowercase letter":"Must contain an uppercase letter"}),m=i.createSession({destination:this.config.verificationLinkDestination}),f=n.notify("Creating account");await i.registerUser({sessionId:await m,email:c,password:l,firstName:s,lastName:p,expertise:e.expertise??"ENGINEERING"}),f.confirm(`Link to verify sent to \`${c}\``);let b=await this.config.emailLinkGenerator(c).then(async y=>y!==null&&await t.confirm({message:"Open your inbox?",default:true})?y.toString():null);f=n.notify("Waiting for account activation");let A=r.wait(await m);b!==null&&await n.open(b);let I=await A;return f.confirm("Account activated"),I}};var gr=class{constructor(e){this.config=e;}async execute(e){let{output:t,pageForm:n,userApi:r}=this.config,i=await this.config.configurationManager.load(),a=await n.handle({page:e.page,organizationSlug:i.organization,workspaceSlug:i.workspace,devApplicationSlug:i.applications.development,prodApplicationSlug:i.applications.production}),s=t.notify("Logging in..."),p=await r.issueToken({duration:this.config.adminTokenDuration});s.stop();let c=new URL(a.startsWith("/")?a.slice(1):a,this.config.adminUrl);c.searchParams.set(this.config.adminTokenParameter,p),await t.open(c.toString());}};function ge(o,e){let t=[],n=null;if(traverse(o,{ImportDeclaration:i=>{let{node:a}=i;if(a.source.value!==e.moduleName)return i.skip();t.push({declaration:a});let s=a.importKind??"value";for(let p of a.specifiers)if(!(!g.isImportSpecifier(p)||Ll(p.imported)!==e.importName)){if(s==="value"&&(p.importKind===null||p.importKind===e.type)||s==="type"&&e.type==="type")return n=p.local.name,i.stop();t.unshift({declaration:a,specifier:p,localName:p.local.name});}return i.skip()}}),n!==null)return {modified:false,localName:n};if(t.length>0){for(let i of t){let{declaration:a}=i;if(a.importKind==="type"&&e.type==="value"){a.importKind="value";for(let s of a.specifiers)g.isImportSpecifier(s)&&s!==i.specifier&&(s.importKind="type");if(i.localName===void 0){let s=g.importSpecifier(g.identifier(e.localName??e.importName),g.identifier(e.importName));s.importKind=e.type,a.specifiers.push(s);}return {modified:true,localName:i.localName??e.importName}}if(i.specifier!==void 0&&i.specifier.importKind==="type"&&e.type==="value")return i.specifier.importKind="value",{modified:true,localName:i.localName}}for(let{declaration:i}of t){let a=i.importKind??"value";if(a==="value"||a===e.type){let s=g.importSpecifier(g.identifier(e.localName??e.importName),g.identifier(e.importName));return a!==e.type&&(s.importKind="type"),i.specifiers.push(s),{modified:true,localName:e.localName??e.importName}}}}let r=g.importDeclaration([g.importSpecifier(g.identifier(e.localName??e.importName),g.identifier(e.importName))],g.stringLiteral(e.moduleName));return e.type==="type"&&(r.importKind="type"),o.program.body.unshift(r),{modified:true,localName:e.localName??e.importName}}function Ll(o){return g.isIdentifier(o)?o.name:o.value}function Ct(o,e){let t=typeof o=="string"?Ge(o,["jsx","typescript"]):o,n=null;return traverse(t,{ImportDeclaration:r=>{let{node:i}=r;if(!fr(i.source.value,e.moduleName))return r.skip();for(let a of i.specifiers??[]){if(g.isImportDefaultSpecifier(a)){fr("default",e.importName)&&(n=a.local.name);continue}if(g.isImportSpecifier(a)&&fr(a.imported,e.importName))return n=a.local.name,r.skip()}return r.skip()}}),n}function fr(o,e){return typeof o!="string"?fr(g.isIdentifier(o)?o.name:o.value,e):typeof e=="string"?o===e:e.test(o)}function yr(o){let e=[];for(let[t,n]of Object.entries(o))e.push(g.jsxAttribute(g.jsxIdentifier(t),g.jsxExpressionContainer(st(n))));return e}function st(o){switch(o.type){case "reference":return o.path.length<2?g.identifier(o.path[0]):o.path.slice(2).reduce((e,t)=>g.memberExpression(e,g.identifier(t)),g.memberExpression(g.identifier(o.path[0]),g.identifier(o.path[1])));case "literal":return typeof o.value=="string"?g.stringLiteral(o.value):typeof o.value=="number"?g.numericLiteral(o.value):typeof o.value=="boolean"?g.booleanLiteral(o.value):g.nullLiteral();case "comparison":return g.binaryExpression(o.operator,st(o.left),st(o.right));case "ternary":return g.conditionalExpression(g.binaryExpression(o.condition.operator,st(o.condition.left),st(o.condition.right)),st(o.consequent),st(o.alternate))}}var pt=class o{constructor(e){this.configuration=e;}apply(e,t){let n=Ct(e,{importName:this.configuration.wrapper.component,moduleName:this.configuration.wrapper.module}),r=n??this.configuration.wrapper.component,i=[],a=1;if(traverse(e,{ExportDefaultDeclaration:p=>(a=this.wrapDeclaration(p.node.declaration,r,e,t),p.stop()),ExportNamedDeclaration:p=>(i.push(p.node),p.skip())}),a===1&&this.configuration?.fallbackToNamedExports===true)for(let p of i){if(g.isFunctionDeclaration(p.declaration)&&(a=this.wrapBlockStatement(p.declaration.body,r,e,t),a===0))break;if(g.isVariableDeclaration(p.declaration)){let{declarations:c}=p.declaration;if(c.some(m=>g.isIdentifier(m.init)||g.isArrowFunctionExpression(m.init)||g.isFunctionExpression(m.init)?this.wrapDeclaration(m.init,r,e,t)===0:false)){a=0;break}}for(let c of p.specifiers??[])if(g.isExportSpecifier(c)){let l=this.findComponentDeclaration(e,c.local.name);if(l!==null&&g.isVariableDeclarator(l)&&g.isExpression(l.init)&&(a=this.wrapDeclaration(l.init,r,e,t),a===0))break}if(a===0)break}if(a===0&&n===null){let{body:p}=e.program;g.isImportDeclaration(p[0])||p.unshift(g.emptyStatement()),ge(e,{type:"value",moduleName:this.configuration.wrapper.module,importName:this.configuration.wrapper.component});}let s=this.configuration?.fallbackCodemod;return a===1&&s!==void 0?s.apply(e,t):Promise.resolve({modified:a===0,result:e})}wrapDeclaration(e,t,n,r){if(g.isArrowFunctionExpression(e)){if(g.isBlockStatement(e.body))return this.wrapBlockStatement(e.body,t,n,r);let i=this.insertWrapper(e.body,t,n,r);return i.result!==0?i.result:(e.body=i.node,0)}if(g.isFunctionExpression(e)||g.isFunctionDeclaration(e))return this.wrapBlockStatement(e.body,t,n,r);if(g.isIdentifier(e)){let i=this.findComponentDeclaration(n,e.name);if(i!==null)if(g.isVariableDeclarator(i)){let a=i.init??null;if(a!==null)return this.wrapDeclaration(a,t,n,r)}else return this.wrapBlockStatement(i.body,t,n,r)}return 1}wrapBlockStatement(e,t,n,r){let i=o.findReturnStatement(e),a=i?.argument??null;if(i!==null&&a!==null){let s=this.insertWrapper(a,t,n,r);return s.result!==0?s.result:(i.argument=g.parenthesizedExpression(s.node),0)}return 1}insertWrapper(e,t,n,r){if(this.containsElement(e,t))return {result:2,node:e};let i=this.findTargetChildren(n,e);if(i!==null){let{parent:a,index:s}=i,p=[...a.children??[]],c=p.splice(s,1)[0];return i.parent.children=p.length===0?[g.jsxText(`
|
|
1734
1734
|
`),this.wrapElement(c,t,r),g.jsxText(`
|
|
1735
1735
|
`)]:[...p.slice(0,s),this.wrapElement(c,t,r),...p.slice(s)],{result:0,node:e}}return g.isJSXText(e)||g.isJSXExpressionContainer(e)||g.isJSXSpreadChild(e)||g.isJSXElement(e)||g.isJSXFragment(e)?{result:0,node:this.wrapElement(e,t,r)}:{result:1,node:e}}wrapElement(e,t,n){return e.extra?.parenthesized===true&&(e.extra.parenthesized=false),g.jsxElement(g.jsxOpeningElement(g.jsxIdentifier(t??this.configuration.wrapper.component),this.getProviderProps(n)),g.jsxClosingElement(g.jsxIdentifier(t??this.configuration.wrapper.component)),[g.jsxText(`
|
|
1736
1736
|
`),e,g.jsxText(`
|
|
@@ -1762,14 +1762,14 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1762
1762
|
${t}
|
|
1763
1763
|
[Window]::SetForegroundWindow(${r})
|
|
1764
1764
|
[Window]::ShowWindow(${r}, 9)
|
|
1765
|
-
`;this.runCommand({name:"powershell",arguments:["-Command",`& {${i}}`]});}}runCommand(e){let{commandExecutor:t,timeout:n}=this.configuration;try{let r=t.runSync(e,{timeout:n});return r.exitCode!==0?null:r.output.trim()}catch{return null}}};var Dr=class{constructor(e){this.detector=e.detector,this.templates=e.templates;}async generate(e){let t=await this.detector.detect(e.recipient);return t===null||this.templates[t]===void 0?null:this.templates[t].generate(e)}};var Mr=class{constructor(...e){this.detectors=e;}async detect(e){for(let t of this.detectors){let n=await t.detect(e);if(n!==null)return n}return null}};var Nr=class o{static{this.DEFAULT_DOMAINS={google:["gmail.com","googlemail.com","google.com"],yahoo:[/yahoo\.com(?:\.\w+)?/,"yahoo.co.uk","yahoo.fr","yahoo.it","ymail.com","rocketmail.com"],microsoft:["outlook.com","live.com","hotmail.com","msn.com","passport.com","passport.net"],proton:["proton.me","protonmail.com"],icloud:["icloud.com"]};}constructor(e=o.DEFAULT_DOMAINS){this.domains=e;}detect(e){let t=e.toLowerCase().split("@")[1];for(let[n,r]of Object.entries(this.domains))if(r.some(a=>typeof a=="string"?a===t:a.test(t)))return Promise.resolve(n);return Promise.resolve(null)}};var $r=class o{static{this.DEFAULT_DOMAINS={google:["google.com"],microsoft:["outlook.com"]};}constructor(e=o.DEFAULT_DOMAINS){this.domains=e;}async detect(e){let t=e.toLowerCase().split("@")[1],n=await this.lookup(t);for(let[r,i]of Object.entries(this.domains))for(let a of i)for(let s of n)if(s.endsWith(`.${a}.`))return r;return null}async lookup(e){let t=new URL("https://dns.google.com/resolve");t.searchParams.set("type","MX"),t.searchParams.set("name",e);let n;try{n=await fetch(t).then(r=>{if(!r.ok)throw new Error("Failed to lookup domain");return r.json()});}catch{return []}return n.Answer===void 0?[]:n.Answer.map(r=>r.data)}};var Et=ft(Kt()),zr=class o{generate(e){return new URL(`https://mail.google.com/mail${o.formatFilters(e)}`)}static formatFilters(e){let t=[`to:${e.recipient}`],n=`/u/${e.recipient}`;if(e.sender!==void 0&&t.push(`from:${e.sender}`),e.subject!==void 0&&t.push(`subject:${e.subject}`),e.timestamp!==void 0){let r=Et.TimeZone.of(Intl.DateTimeFormat().resolvedOptions().timeZone),i=Et.Instant.ofEpochSecond(e.timestamp),a=Et.LocalDateTime.ofInstant(i,r).getLocalDate();t.push(`after:${a}`);}return t.push("in:anywhere"),n+=`/#search/${t.map(r=>encodeURIComponent(r)).join("+")}`,n}};var _r=class{generate(e){return new URL("https://www.icloud.com/mail")}};var Lr=class{generate(e){let t=new URL("https://outlook.live.com/mail");return e.recipient!==void 0&&t.searchParams.append("login_hint",e.recipient),t}};var Fr=class o{generate(e){return new URL(`https://mail.proton.me/u/0/all-mail${o.formatFilters(e)}`)}static formatFilters(e){let t=new URLSearchParams;return t.set("to",e.recipient),e.sender!==void 0&&t.set("from",e.sender),e.timestamp!==void 0&&t.set("begin",e.timestamp.toFixed(0)),e.subject!==void 0&&t.set("keyword",e.subject),`#${t.toString()}`}};var jr=class o{generate(e){return new URL(`https://mail.yahoo.com/d/search${o.formatFilters(e)}`)}static formatFilters(e){let t=[`to:${e.recipient}`];return e.sender!==void 0&&t.push(`from:${e.sender}`),e.subject!==void 0&&t.push(`subject:${e.subject}`),e.timestamp!==void 0&&t.push(`after:"${new Date(e.timestamp*1e3).toISOString().split("T")[0]}"`),t.length===0?"":`/keyword=${t.join(" ")}`}};var pn=class{constructor(e){this.config=e;}async execute(e){let{fileSystem:t,io:n}=this.config,r=await this.createTemplate(e.empty??false),i=e.file??t.joinPaths(".","template.json5");try{let a=!1;await t.exists(i)&&(a=await n.input?.confirm({message:`Overwrite existing file at \`${i}\`?`,default:!1})??!1),await t.writeTextFile(i,JSON.stringify(r,null,2),{overwrite:a});}catch(a){throw new d("Failed to write template file",{reason:"other",cause:a})}n.output.confirm(`Template created at \`${i}\``);}async createTemplate(e){return {$schema:"https://schema.croct.com/json/v1/template.json",title:"My template",actions:e?[{name:"print",semantic:"info",title:"Empty template",message:"Edit this template to define your actions."}]:[{name:"create-resource",resources:await this.exportResources()}]}}async exportResources(){let{configurationManager:e,templateForm:t}=this.config,n=await e.load(),r=await t.handle({organizationSlug:n.organization,workspaceSlug:n.workspace}),i={audiences:Object.fromEntries(r.audiences.map(a=>[a.slug,{name:a.name,criteria:a.criteria}])),components:Object.fromEntries(r.components.map(a=>[a.slug,{name:a.name,description:a.description,definition:a.definition}])),slots:Object.fromEntries(r.slots.map(a=>[a.slug,{name:a.name,component:a.component?.slug??"",content:a.content}])),experiences:r.experiences.map(a=>{let{experiment:s}=a,p=s!==void 0?{name:s.name??"",goalId:s.goalId,crossDevice:s.crossDevice,traffic:s.traffic??1,variants:s.variants.map(c=>({name:c.name??"",content:c.content,baseline:c.baseline,allocation:c.allocation??1e3/s.variants.length}))}:void 0;return {name:a.name,draft:a.status==="DRAFT",audiences:a.audiences,slots:a.slots,content:a.content,...p!==void 0?{experiment:p}:{}}})};for(let[a,s]of Object.entries(i))typeof s=="object"&&s!==null&&(Array.isArray(s)&&s.length===0||Object.keys(s).length===0)&&delete i[a];return i}};var Wr=class{constructor(e){this.config=e;}async handle(e){let{input:t,form:n}=this.config,r={components:[],slots:[],audiences:[],experiences:[]},i=new Set,a=new Set,s=await n.experience.handle({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,confirmation:"Do you want to include experiences?"});if(s.length>0){for(let c of s.flatMap(l=>l.audiences))i.add(c);for(let c of s.flatMap(l=>l.slots))a.add(c);r.experiences=s,s.some(c=>c.experiment!==void 0)&&(await t.confirm({message:"Include experiments?",default:false})||(r.experiences=r.experiences.map(c=>{let{experiment:l,...m}=c;return m})));}r.slots=await n.slot.handle({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,selected:[...a],selectionConfirmation:{message:a.size>0?"Do you want to include other slots?":"Do you want to include slots?",default:false}});let p=new Set(r.slots.map(c=>c.component?.slug??""));return r.components=await n.component.handle({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,includeDependencies:true,selected:[...p],selectionConfirmation:{message:p.size>0?"Do you want to include other components?":"Do you want to include components?",default:false}}),r.audiences=await n.audience.handle({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,selected:[...i],selectionConfirmation:{message:i.size>0?"Do you want to include other audiences?":"Do you want to include audiences?",default:false}}),r}};var Vr=class{constructor(e){this.config=e;}async handle(e){let{output:t,input:n,workspaceApi:r}=this.config,i=t.notify("Loading experiences"),a=await r.getExperiences({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});i.stop();let{confirmation:s}=e;if(a.length===0||s!==void 0&&!await n.confirm({message:s}))return [];let p=await n.selectMultiple({message:"Select experiences",options:a.map(l=>({value:l,label:l.name}))});i=t.notify("Loading details");let c=await Promise.all(p.flatMap(async({id:l})=>{let m=await r.getExperience({experienceId:l,organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return m===null?[]:[m]}));return i.stop(),c.flat()}};var Ur=class{constructor(e){this.config=e;}async handle(e){let{output:t,input:n}=this.config,r=t.notify("Loading audiences"),i=await this.getAudiences(e,e.allowed);r.stop();let a=e.preselected??[];if(a.length>0)return i.filter(({slug:p})=>a.includes(p));let s=e.selected??[];return i.length===0||s.length>0&&i.every(({slug:p})=>s.includes(p))?i.filter(({slug:p})=>s.includes(p)):e.selectionConfirmation!==void 0&&!await n.confirm(e.selectionConfirmation)?i.filter(({slug:c})=>s.includes(c)):n.selectMultiple({message:"Select audiences",options:i.map(p=>{let c=s.includes(p.slug);return {value:p,label:p.name,disabled:c,selected:c}})})}async getAudiences(e,t){let{workspaceApi:n}=this.config,r=await n.getAudiences({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return t===void 0?r:r.filter(({slug:i})=>t.includes(i))}};var I=class o extends d{constructor(e,{tracing:t,...n}={}){super(e,n),this.tracing=t??[],Object.setPrototypeOf(this,o.prototype);}static fromCause(e,t={}){let{message:n,...r}=t;if(!(e instanceof Error))return new o(n??d.formatMessage(e),{...r,cause:e});let i=new o(n??e.message,{cause:e,...e instanceof d?e.help:{},...r,tracing:[...r.tracing??[],...e instanceof o?e.tracing:[]]});return i.stack=e.stack,i}};var Rt=class{constructor(e){this.variables={};this.input=e.input,this.output=e.output,this.baseUrl=e.baseUrl;}getVariables(){return structuredClone(this.variables)}set(e,t){this.variables[e]=t;}};var qr=class{constructor(e){this.config=e;}async getOptions(e){let{templateProvider:t}=this.config;return (await t.get(await this.resolveUrl(e))).value.options??{}}async execute(e){let{action:t,io:n}=this.config,{template:r,options:i}=e,a=await this.resolveUrl(r);return t.execute({template:a.toString(),options:i},new Rt({input:n.input,output:n.output,baseUrl:a}))}async resolveUrl(e){let{fileSystem:t}=this.config,n=e;if(URL.canParse(e)){let r=new URL(e);if(r.protocol!=="file:")return r;n=t.normalizeSeparators(r.pathname);}try{return new URL(`file://${await t.getRealPath(n)}`)}catch(r){throw new I(`Template file not found at \`${n}\`.`,{reason:"invalid_input",cause:r,suggestions:["Check the file path and try again."]})}}};function Tt(o,e){if(URL.canParse(o))return new URL(o);let t=new URL(e.href.replace(/^(.*:)(?!\/)/,"$1/"));return new URL(o,t)}var Hr=class{constructor(e){this.config=e;}async execute(e,t){let{fileSystem:n}=this.config,{input:r}=t,i=Tt(e.source,t.baseUrl);if(i.protocol==="file:"&&t.baseUrl.protocol!=="file:")throw new I("File URL is not allowed from remote sources for security reasons.",{reason:"precondition",details:[`Source URL: ${i}`]});let a=n.normalizeSeparators(e.destination),{output:s}=t,p=s?.notify("Downloading sources");try{await this.download(i,a,e.filter!==void 0?new Minimatch(e.filter):void 0,r);}finally{p?.stop();}e.result?.destination!==void 0&&t.set(e.result.destination,a);}async download(e,t,n,r){let{provider:i,fileSystem:a,codemod:s}=this.config,{value:p}=await i.get(e),c=[];for await(let l of p){let m=a.normalizeSeparators(l.name);if(!(a.isAbsolutePath(m)||!a.isSubPath(t,m))&&!(n!==void 0&&!n.match(m))){if(l.name=a.joinPaths(t,m),l.type==="link"||l.type==="symlink"){let f=a.normalizeSeparators(l.target);if(a.isAbsolutePath(f)||!a.isSubPath(t,f))continue;l.target=f;}c.push(l);}}if(c.length!==0){if(await a.exists(t)){if(c.length===1&&c[0].type==="file"){if(await a.exists(c[0].name)&&await r?.confirm({message:`File ${c[0].name} already exists. Do you want to overwrite it?`,default:false})!==true)throw new I("Destination file already exists.",{reason:"precondition",details:[`File: ${c[0].name}`],suggestions:["Delete the file"]})}else if(!await a.isDirectory(t)||!await a.isEmptyDirectory(t)){if(await r?.confirm({message:`Directory ${t} is not empty. Do you want to clear it?`,default:false})!==true)throw new I("Destination directory is not empty.",{reason:"precondition",details:[`Directory: ${t}`],suggestions:["Clear the directory"]});await a.delete(t,{recursive:true});}}await a.createDirectory(t,{recursive:true});for(let l of c)await a.create(l);for(let l of c)l.type==="file"&&await s.apply(await a.getRealPath(l.name));}}};var Gr=class{constructor({packageManager:e}){this.packageManager=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Installing dependencies");try{await this.packageManager.addDependencies(e.dependencies,e.development===!0);}catch(i){throw I.fromCause(i)}finally{r?.stop();}}};var Kr=class{constructor({projectDirectory:e,fileSystem:t,matcherProvider:n}){this.projectDirectory=e,this.fileSystem=t,this.matcherProvider=n;}async execute(e,t){let{output:n}=t,r=n?.notify("Locating files");try{await this.findMatches(e,t);}finally{r?.stop();}}async findMatches(e,t){let n=await this.findMatch(e.path,e);e.result!==void 0&&t.set(e.result,n);}async findMatch(e,t){let n=await this.matcherProvider.get(e),r=[];for await(let i of this.fileSystem.list(this.projectDirectory.get(),t.depth))if(await n.test(i.name)){if(t.matcher===void 0)r.push(i.name);else if(i.type==="file"){let a=await new Response(i.content).text();this.matches(a,t.matcher)&&r.push(i.name);}if(t.limit!==void 0&&r.length>=t.limit)break}return r}matches(e,t){if("pattern"in t)return new RegExp(t.pattern,t.caseSensitive===true?"i":void 0).test(e);switch(t.type){case "and":return t.matchers.every(n=>this.matches(e,n));case "or":return t.matchers.some(n=>this.matches(e,n))}}};var Zr=class{constructor({fileSystem:e}){this.fileSystem=e;}async execute(e,t){let{output:n}=t,r=n.notify("Replacing file content");try{await this.replaceFiles(e);}finally{r.stop();}}async replaceFiles(e){for(let{path:t,replacements:n}of e.files)if(await this.fileSystem.exists(t))try{await this.fileSystem.writeTextFile(t,this.replaceContent(await this.fileSystem.readTextFile(t),n),{overwrite:!0});}catch(r){throw I.fromCause(r)}}replaceContent(e,t){let n=e;for(let{pattern:r,caseSensitive:i,value:a}of t){let s=i===true?"gi":"g";n=n.replaceAll(new RegExp(r,s),`${a}`);}return n}};var Jr=class{constructor({installer:e}){this.installer=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Installing slots");try{await this.installer(e.slots,e.example===!0);}catch(i){throw I.fromCause(i)}finally{r?.stop();}}};var Qr=class{constructor({installer:e}){this.installer=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Installing components");try{await this.installer(e.components);}catch(i){throw I.fromCause(i)}finally{r?.stop();}}};var Br=class{constructor(e){this.runner=e;}async execute(e,t){try{await this.run(e.action,t);}catch(n){if(e.else===void 0)throw e.help===void 0?n:I.fromCause(n,{...e.help,reason:"precondition"});await this.run(e.else,t);}finally{e.finally!==void 0&&await this.run(e.finally,t);}}run(e,t){return this.runner.execute({actions:e},t)}};var U=class o extends d{constructor(e,t={}){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var Be=class{constructor(e){this.provider=e;}get action(){return Promise.resolve(this.provider.get()).catch(e=>{throw e instanceof U?new I(e.message,e.help):e})}async execute(e,t){return (await this.action).execute(e,t)}};var Yr=class{constructor(e){this.manager=e;}isInitialized(){return this.manager.isInitialized()}load(){return this.configuration===void 0&&(this.configuration=this.manager.load()),this.configuration}update(e){return this.configuration=this.manager.update(e),this.configuration}};var Ga;(r=>{function o(i){let a=new Set(Object.values(i.slots??{}).map(m=>m.component)??[]),s=new Set(i.experiences?.flatMap(m=>m.slots)??[]),p=new Set(i.experiences?.flatMap(m=>m.audiences)??[]),c=(i.experiences??[]).map(m=>({name:m.name,maximumAudiencesPerExperience:m.audiences.length,crossDevice:m.experiment?.crossDevice===true,...e(m)})),l=new Set;for(let m of Object.values(i.slots??{}))for(let f of Object.keys(m.content))l.add(f);for(let m of c){for(let f of m.locales)l.add(f);for(let f of m.audiences)p.add(f);for(let f of m.slots)s.add(f);}return {components:a,slots:s,audiences:p,locales:l,experiences:c}}r.analyze=o;function e(i){let a=t(i.content);for(let s of i.experiment?.variants??[]){let p=t(s.content);p.audiences.forEach(c=>a.audiences.add(c)),p.slots.forEach(c=>a.slots.add(c));}return {...a}}function t(i){let a=new Set,s=new Set,p=0;for(let[m,f]of Object.entries(i.default)){a.add(m);for(let[b,A]of Object.entries(f))s.add(b),p=Math.max(p,n(A));}let c=new Set,l=0;for(let m of i.segmented){for(let f of m.audiences)c.add(f);l=Math.max(l,m.audiences.length);for(let[f,b]of Object.entries(m.content)){a.add(f);for(let[A,v]of Object.entries(b))s.add(A),p=Math.max(p,n(v));}}return {slots:a,audiences:c,locales:s,audiencesPerExperience:l,dynamicContentPerContent:p}}function n(i){switch(i.type){case "boolean":case "text":case "number":return i.value.type==="dynamic"?1:0;case "structure":return Object.values(i.attributes).map(n).reduce((a,s)=>a+s,0);case "list":return i.items.map(n).reduce((a,s)=>a+s,0)}}})(Ga||={});var Xr=class{constructor(e){this.refactoring=e;}refactor(e){return {components:Object.fromEntries(Object.entries(e.components??{}).map(([t,n])=>[this.refactoring.componentMapping[t]??t,n])),slots:Object.fromEntries(Object.entries(e.slots??{}).map(([t,n])=>[this.refactoring.slotMapping[t]??t,this.refactorSlotContent(n)])),audiences:Object.fromEntries(Object.entries(e.audiences??{}).map(([t,n])=>[this.refactoring.audienceMapping[t]??t,n])),experiences:e.experiences?.map(t=>this.refactorExperience(t))??[]}}refactorSlotContent(e){return {...e,component:this.refactoring.componentMapping[e.component]??e.component,content:this.refactorLocalizedContentMap(e.content)}}refactorExperience(e){return {...e,audiences:e.audiences.map(t=>this.refactoring.audienceMapping[t]??t),slots:e.slots.map(t=>this.refactoring.slotMapping[t]??t),experiment:e.experiment!==void 0?{...e.experiment,crossDevice:(e.experiment.crossDevice??false)&&this.refactoring.isCrossDeviceFeatureEnabled}:void 0,content:this.refactorPersonalizedContent(e.content,e.audiences.slice(0,this.refactoring.maximumAudiencePerExperience))}}refactorPersonalizedContent(e,t){return {default:this.refactorSlotContentMap(e.default),segmented:e.segmented.flatMap(n=>{let r=n.audiences.filter(i=>t.includes(i));return r.length===0?[]:{audiences:r,content:this.refactorSlotContentMap(n.content)}})}}refactorSlotContentMap(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[this.refactoring.slotMapping[t]??t,this.refactorLocalizedContentMap(n)]))}refactorLocalizedContentMap(e){return Object.fromEntries(Object.entries(e).flatMap(([t,n])=>{let r=this.refactoring.localeMapping[t];return r===null||r!==void 0&&e[r]!==void 0?[]:[[r??t,this.refactorContent(n,{dynamicAttributesPerContent:this.refactoring.dynamicAttributesPerContent})]]}))}refactorContent(e,t){switch(e.type){case "boolean":case "text":case "number":return e.value.type==="dynamic"&&t.dynamicAttributesPerContent>0&&t.dynamicAttributesPerContent--,e.value.type==="static"||t.dynamicAttributesPerContent>0?e:{...e,value:{type:"static",value:e.value.default}};case "structure":return {...e,attributes:Object.fromEntries(Object.entries(e.attributes).map(([n,r])=>[n,this.refactorContent(r,t)]))};case "list":return {...e,items:e.items.map(n=>this.refactorContent(n,t))}}}};var ei=class o{constructor(e){this.config=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Analyzing resources"),i=Ga.analyze(e.resources);this.checkMissingResources({...i,locales:new Set},e.resources);let{configurationManager:a,api:{workspace:s}}=this.config,p=await a.load(),c=await this.getProjectInfo(p),l=await this.createPlan(e.resources,i,c);r?.update("Creating resources");let m=await s.createResources({organizationSlug:p.organization,workspaceSlug:p.workspace,...l.resources});if(r?.stop(),n!==void 0){let f=o.getWarnings(i,c.workspace);if(f.length>0)for(let b of f)n.warn(`${b}`);}e.result!==void 0&&o.setVariables(e.result,l,m,t);}async createPlan(e,t,n){let{mappingForm:r,matcher:i}=this.config,a=await i.match({resources:e,workspaceSlug:n.configuration.workspace,organizationSlug:n.configuration.organization}),s=Object.entries(a.audiences).filter(v=>!("id"in v[1])),p=Object.entries(a.components).filter(v=>!("id"in v[1])),c=Object.entries(a.slots).filter(v=>!("id"in v[1])),l=a.experiences.filter(v=>!("id"in v)),m=l.flatMap(v=>v.experiment===void 0?[]:[v.experiment]);await this.checkRequiredQuota(n,{components:p.length,slots:c.length,audiences:s.length,experiences:l.length,experiments:m.length});let f=await r.handle({organizationSlug:n.configuration.organization,workspaceSlug:n.configuration.workspace,resources:{audiences:s.map(([v])=>v),components:p.map(([v])=>v),slots:c.map(([v])=>v)}}),b={},{workspace:A}=n;for(let v of t.locales)A.locales.includes(v)||(b[v]=A.defaultLocale);return {matches:a,mapping:f,resources:new Xr({componentMapping:f.components,audienceMapping:f.audiences,slotMapping:f.slots,dynamicAttributesPerContent:A.quotas.dynamicAttributesPerContent,maximumAudiencePerExperience:A.quotas.audiencesPerExperience,isCrossDeviceFeatureEnabled:A.features.crossDevice,localeMapping:b}).refactor({components:Object.fromEntries(p),slots:Object.fromEntries(c),audiences:Object.fromEntries(s),experiences:l})}}async getProjectInfo(e){let{api:t}=this.config,[n,r]=await Promise.all([t.organization.getWorkspace({organizationSlug:e.organization,workspaceSlug:e.workspace}),t.workspace.getFeatures({organizationSlug:e.organization,workspaceSlug:e.workspace})]);if(n==null||r==null)throw new d("Workspace not found",{title:"Invalid configuration",reason:"invalid_configuration",details:["The workspace defined in the configuration does not exist"],suggestions:["Check the configuration file"]});return {configuration:e,workspace:{...n,...r}}}async checkRequiredQuota(e,t){let{api:{user:n}}=this.config;for(let[r,i]of Object.entries(t)){let a=o.getRemainingQuota(e.workspace,r);if(a<i){let s=await n.getUser().catch(()=>({email:void 0})),p=new URL("https://croct.com/contact/support");throw p.searchParams.set("subject","limit-increase"),p.searchParams.set("organization",e.configuration.organization),p.searchParams.set("message",`I need more quota for ${r}`),s.email!==void 0&&p.searchParams.set("email",s.email),new d(`Not enough ${r} quota available in your workspace.`,{title:"Insufficient quota",reason:"precondition",links:[{label:"Request more quota",url:p.toString()}],details:[`Available: ${a}`,`Required: ${i}`],suggestions:[`Free up quota by removing unused ${r}`,"Request additional quota from support"]})}}}checkMissingResources(e,t){let n=this.findMissingResources(e,t);for(let[r,i]of Object.entries(n))if(i.size>0)throw new d(`Some ${r} referenced in the template are missing`,{title:"Invalid template",reason:"invalid_input",details:[`Missing ${r}: ${Array.from(i).join(", ")}`],suggestions:["Report this issue to the template author"]})}findMissingResources(e,t){let n=new Set(e.components),r=new Set(e.slots),i=new Set(e.audiences),a=new Set(e.locales);for(let s of Object.keys(t.components??{}))n.delete(s);for(let s of Object.keys(t.slots??{}))r.delete(s);for(let s of Object.keys(t.audiences??{}))i.delete(s);return {components:n,slots:r,audiences:i,locales:a}}static getRemainingQuota(e,t){let n=t.charAt(0).toUpperCase()+t.slice(1);return e.quotas[`remaining${n}`]}static getWarnings(e,t){let n=[];return Math.max(...e.experiences.map(s=>s.dynamicContentPerContent))>t.quotas.dynamicAttributesPerContent&&n.push("Some dynamic values have been removed from the content to fit the workspace quota"),Math.max(...e.experiences.map(s=>s.audiencesPerExperience))>t.quotas.audiencesPerExperience&&n.push("Some audiences have been removed from the experiences to fit the workspace quota"),Array.from(e.locales).filter(s=>!t.locales.includes(s)).length>0&&n.push("Content in unsupported locales have been mapped to default or dropped"),!t.features.crossDevice&&e.experiences.some(s=>s.crossDevice)&&n.push("Cross-device experiments have been disabled "),n}static setVariables(e,t,n,r){if(e.audiences!==void 0)for(let[i]of Object.entries(t.matches.audiences??{}))e.audiences[i]!==void 0&&r.set(e.audiences[i],t.mapping.audiences[i]??i);if(e.components!==void 0)for(let[i]of Object.entries(t.matches.components??{})){let a=e.components[i];if(a!==void 0){let s=t.mapping.components[i]??i,p=t.matches.components[i]??{};a.id!==void 0&&r.set(a.id,s),a.version!==void 0&&r.set(a.version,"version"in p?p.version.major:1);}}if(e.slots!==void 0)for(let[i]of Object.entries(t.matches.slots??{})){let a=e.slots[i];if(a!==void 0){let s=t.mapping.slots[i]??i,p=t.matches.slots[i]??{};a.id!==void 0&&r.set(a.id,s),a.version!==void 0&&r.set(a.version,"version"in p?p.version.major:1);}}if(e.experiences!==void 0){let{experiences:i}=t.matches,a=0;for(let[s,p]of i.entries()){e.experiences[s]!==void 0&&r.set(e.experiences[s],"id"in p?p.id:n.experiences[a].experienceId);let c=p.experiment!==void 0&&"id"in p.experiment?p.experiment.id:n.experiences[a].experimentId;c!==void 0&&e.experiments?.[s]!==void 0&&r.set(e.experiments[s],c),"id"in p||a++;}}}};var Ot=class o{constructor(e){this.config=e;}static prompt(e){return new o(e).handle()}handle(){let{input:e,unavailableSlugs:t=[],default:n}=this.config;return e.prompt({message:this.config.label,default:n,validate:r=>/^[a-z]+(-?[a-z0-9]+)*$/i.test(r)?t.includes(r)?"The entered slug is already in use.":true:"The slug must start with a letter and contain only letters, numbers, and hyphens."})}};var ti=class{constructor(e){this.config=e;}async handle(e){let{input:t,workspaceApi:n}=this.config,{resources:r,...i}=e,a=r.slots??[],s=r.components??[],p=r.audiences??[],[c,l,m]=await Promise.all([a.length>0?n.getSlots(i):new Array,s.length>0?n.getComponents(i):new Array,p.length>0?n.getAudiences(i):new Array]),f=s.filter(j=>l.some(T=>T.slug===j)),b={};if(f.length>0){let j=l.map(T=>T.slug);for(let T of f){let H=await Ot.prompt({input:t,default:T,unavailableSlugs:j,label:`Component \`${T}\` already exists, enter a new component ID:`});j.push(H),b[T]=H;}}let A=a.filter(j=>c.some(T=>T.slug===j)),v={};if(A.length>0){let j=c.map(T=>T.slug);for(let T of A){let H=await Ot.prompt({input:t,default:T,unavailableSlugs:j,label:`Slot \`${T}\` already exists, enter a new slot ID:`});j.push(H),v[T]=H;}}let y=p.filter(j=>m.some(T=>T.slug===j)),M={};if(y.length>0){let j=m.map(T=>T.slug);for(let T of y){let H=await Ot.prompt({input:t,default:T,unavailableSlugs:j,label:`Audience \`${T}\` already exists, enter a new audience ID:`});j.push(H),M[T]=H;}}return {components:b,slots:v,audiences:M}}};var ni=class o{constructor(e){this.config=e;}async match(e){let{resources:t,...n}=e,[r,i,a,s]=await Promise.all([this.mapComponents(t.components??{},n),this.mapSlots(t.slots??{},n),this.mapAudiences(t.audiences??{},n),this.mapExperiences(t.experiences??[],n)]);return {components:r,slots:i,audiences:a,experiences:s}}async mapAudiences(e,t){let{workspaceApi:n}=this.config,r=await Promise.all(Object.keys(e).map(async a=>[a,await n.getAudience({...t,audienceSlug:a})])),i={};for(let[a,s]of r)i[a]=s===null||!o.isSimilarAudience(e[a],s)?e[a]:s;return i}async mapComponents(e,t){let{workspaceApi:n}=this.config,r=await Promise.all(Object.keys(e).map(async a=>[a,await n.getComponent({...t,componentSlug:a})])),i={};for(let[a,s]of r)i[a]=s===null||!o.isSimilarComponent(e[a],s)?e[a]:s;return i}async mapSlots(e,t){let{workspaceApi:n}=this.config,r=await Promise.all(Object.keys(e).map(async a=>[a,await n.getSlot({...t,slotSlug:a})])),i={};for(let[a,s]of r)i[a]=s===null||!o.isSimilarSlot(e[a],s)?e[a]:s;return i}async mapExperiences(e,t){let{workspaceApi:n}=this.config,i=(await n.getExperiences({...t,status:["ACTIVE","PAUSED","DRAFT"]})).map(a=>{let s=null;function p(){return s===null&&(s=n.getExperience({...t,experienceId:a.id})),s}return {...a,details:{get content(){return p().then(c=>c?.content??null)},get experiment(){return p().then(c=>c?.experiment??null)}}}});return Promise.all(e.map(async a=>{for(let s of i)if(await this.matchesExperience(a,s)){let{details:p,...c}=s;return c}return a}))}async matchesExperience(e,t){if((e.draft===true?"DRAFT":"ACTIVE")!==t.status||!deepEqual(e.audiences,t.audiences)||!deepEqual(e.slots,t.slots)||e.experiment!==void 0&&t.experiment===void 0)return false;let[r,i=null]=await Promise.all([t.details.content,t.details.experiment]);return e.experiment!==void 0&&(i===null||e.experiment.goalId!==i.goalId||e.experiment.traffic!==i.traffic||e.experiment.crossDevice!==i.crossDevice||!o.isSimilarExperimentContent(e.experiment.variants,i.variants))?false:o.isSimilarPersonalizedContent(e.content,r??{default:{},segmented:[]})}static isSimilarAudience(e,t){return e.criteria===t.criteria}static isSimilarComponent(e,t){return deepEqual(e.definition,t.definition)}static isSimilarSlot(e,t){return e.component===t.component?.slug&&Object.values(e.content).some(n=>Object.values(t.content).some(r=>deepEqual(n,r)))}static isSimilarExperimentContent(e,t){return e.length!==t.length?false:e.some((n,r)=>deepEqual(n,t[r]))}static isSimilarPersonalizedContent(e,t){if(o.isSimilarSlotContent(e.default,t.default))return true;for(let n of e.segmented)for(let r of t.segmented)if(deepEqual(n.audiences,r.audiences)&&o.isSimilarSlotContent(n.content,r.content))return true;return false}static isSimilarSlotContent(e,t){for(let[n,r]of Object.entries(e)){let i=t[n];if(i!==void 0){for(let a of Object.values(r))if(Object.values(i).some(s=>deepEqual(a,s)))return true}}return false}};var W=class o extends U{constructor(e,{url:t,...n}){super(e,n),Object.setPrototypeOf(this,o.prototype),this.url=t;}},$e=class o extends W{constructor(e,t){super(e,{...t,reason:t.reason??"not_found"}),Object.setPrototypeOf(this,o.prototype);}};var ri=class o{async get(e){if(!["http:","https:"].includes(e.protocol))throw new W("Unsupported protocol.",{reason:"not_supported",url:e});let t=await fetch(e);if(t.status===404)throw new $e("Resource not found.",{url:e});if(!o.isSuccessful(t))throw new W(t.statusText,{url:e});return {url:e,value:t}}static isSuccessful(e){return e.ok&&e.body!==null}};var ii=class{constructor({packageManager:e}){this.packageManager=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Checking dependencies"),i;try{i=await Promise.all(e.dependencies.map(s=>this.checkRequirement(s)));}finally{r?.stop();}let a=[];if(e.result!==void 0)for(let s of i){if(e.result[s.dependency]!==void 0){t.set(e.result[s.dependency],s.issue===void 0);continue}s.issue!==void 0&&a.push(s);}if(a.length>0){let{message:s,...p}=e.help??{};throw new I(s??"Missing required dependencies.",{...p,details:a.map(({dependency:c,issue:l})=>`\`${c}\`: ${l}`)})}}async checkRequirement(e){let{name:t,version:n,optional:r=false}=e;if(r&&(n===void 0||!await this.packageManager.hasDirectDependency(t))||await this.packageManager.hasDirectDependency(t,n))return {dependency:t};let i=await this.packageManager.getDependency(t);return {dependency:t,issue:i===null?"not installed":`version \`${n}\` is required, found \`${i.version??"unknown"}\``}}};var Dt=class{constructor({dataProvider:e,registryProvider:t,baseUrl:n}){this.dataProvider=e,this.registryProvider=t,this.baseUrl=n;}async get(e){return this.dataProvider.get(await this.resolveUrl(e))}async resolveUrl(e){for(let{pattern:t,destination:n}of await this.loadMappings(e)){let r=e.href.match(typeof t=="string"?new RegExp(t):t);if(r!==null)return n instanceof URL?n:new URL(n.replace(/\$([0-9]+)/g,(i,a)=>r[Number.parseInt(a,10)]),this.baseUrl)}return e}async loadMappings(e){let t=await this.registryProvider.get(e);return Array.isArray(t)?t:t.value}};var Ye=class o{static{this.EXPECTED_ERROR_REASONS=["not_supported","not_found"];}constructor(...e){this.providers=e;}async get(e){for(let t of this.providers)try{return await t.get(e)}catch(n){if(!o.isExpectedError(n))throw n}throw new $e("Resource not found.",{url:e})}static isExpectedError(e){return e instanceof W&&o.EXPECTED_ERROR_REASONS.includes(e.reason)}};var oi=class o{constructor(e){this.fileSystem=e;}supports(e){return Promise.resolve(o.supportsUrl(e))}get(e){if(!o.supportsUrl(e))throw new W(`Unsupported protocol "${e.protocol}".`,{reason:"not_supported",url:e});return Promise.resolve({url:e,value:this.fileSystem.list(this.fileSystem.normalizeSeparators(e.pathname))})}static supportsUrl(e){return e.protocol==="file:"}};var cn=class o{static{this.PROTOCOL="github:";}static{this.API_HOST="api.github.com";}static{this.RAW_HOST="raw.github.com";}static{this.MAIN_HOST="github.com";}constructor(e){this.provider=e;}async get(e){let t=this.parseUrl(e);if(t===null)throw new W("Unsupported GitHub URL.",{reason:"not_supported",url:e});let n=this.resolveFile(t),{value:r}=await this.provider.get(n.url);return {url:t.canonicalUrl,value:n.url.hostname===o.RAW_HOST?this.extractFile(r,n):this.extractTarball(r,n)}}async*extractTarball(e,t){let n=eu.extract();Readable.fromWeb(e.body).pipe(tu()).pipe(n);let r=o.removeTrailSlash(t.path??"");for await(let i of n){let{header:a}=i;i.resume();let s=o.removeTrailSlash(a.name.split("/").slice(1).join("/"));if(s===""||!s.startsWith(r)||i.header.type==="directory"&&s===r)continue;let p=s;switch(r.length>0&&s.length>r.length&&(p=s.slice(r.length+1)),a.type){case "file":yield {type:"file",name:p,content:i};break;case "directory":yield {type:"directory",name:p};break;case "link":yield {type:"link",name:p,target:a.linkname};break;case "symlink":yield {type:"symlink",name:p,target:a.linkname};break}if(p===r)break}}async*extractFile(e,t){yield {type:"file",name:t.url.pathname.split("/").pop(),content:Readable.fromWeb(e.body)};}resolveFile(e){let{username:t,repository:n,path:r}=e,i=e.ref??"HEAD";return {...e,url:new URL(r!==null&&/\..+$/.test(r)?`https://${o.RAW_HOST}/${t}/${n}/${i}/${r}`:`https://${o.API_HOST}/repos/${t}/${n}/tarball/${i}`)}}parseUrl(e){if(!o.isUrlSupported(e))return null;let t,n,r=null,i,a=e.pathname.replace(/^\/+/,"").split("/"),s=null;return e.hostname===o.MAIN_HOST?(s=e,[t=null,n=null,,r=null,...i]=a):[t=null,n=null,...i]=a,t===null||n===null?null:(s===null&&(s=new URL(`https://${o.MAIN_HOST}`),s.pathname=`/${t}/${n}/blob/master/${i.join("/")}`),{canonicalUrl:s,username:t,repository:n,ref:r,path:i!==void 0&&i.length>0?i.join("/"):null})}static isUrlSupported(e){return e.protocol==="https:"?e.hostname===o.MAIN_HOST:e.protocol===o.PROTOCOL}static removeTrailSlash(e){return e.replace(/\/$/,"")}};var ln=class o{constructor(e){this.provider=e;}async get(e){if(!o.supportsUrl(e))throw new W("Unsupported URL.",{reason:"not_supported",url:e});let{value:t,...n}=await this.provider.get(e);return {...n,value:this.yield(t,e)}}static supportsUrl(e){return e.pathname!=="/"}async*yield(e,t){yield {type:"file",name:t.pathname.split("/").pop(),content:Readable.fromWeb(e.body)};}};var B=class{constructor(e){this.schema=e;}async validate(e){let t=await this.schema.safeParseAsync(e);if(t.success)return {valid:true,data:t.data};let{error:n}=t;return {valid:false,violations:n.issues.map(r=>({path:r.path.reduce((i,a)=>typeof a=="string"?i===""?a:`${i}.${a}`:`${i}[${a}]`,""),message:r.message}))}}};var ru=z.object({name:z.string(),version:z.string().optional(),dependencies:z.record(z.string()).optional(),devDependencies:z.record(z.string()).optional(),bin:z.record(z.string()).optional(),scripts:z.record(z.string()).optional(),packageManager:z.string().optional()}),un=class extends B{constructor(){super(ru);}};var ai=z.string().regex(/^[a-z]+(-?[a-z0-9]+)*$/i,"An identifier must start with a letter and contain only letters, numbers, and hyphens."),sc=z.string().regex(/^[a-z]{2,3}([-_][a-z]{2,3})?$/i,"Locale must be in the form of en, en_US, or en-US."),pc=z.string().refine(O.isValid,"Version must be exact (1), range (1 - 2), or set (1 || 2).").refine(o=>{try{return O.parse(o).getCardinality()<=5}catch{return false}},"Version range must not exceed 5 major versions."),iu=z.strictObject({$schema:z.string().optional(),organization:ai,workspace:ai,applications:z.strictObject({development:ai,production:ai.optional()}),locales:z.array(sc),defaultLocale:sc,slots:z.record(pc),components:z.record(pc),paths:z.strictObject({components:z.string(),examples:z.string(),content:z.string().optional()})}).refine(o=>o.locales.includes(o.defaultLocale),{message:"The default locale is not included in the list of locales.",path:["defaultLocale"]}),si=class extends B{constructor(){super(iu);}};var Mt=class{constructor({provider:e,validator:t}){this.provider=e,this.validator=t;}async get(e){let{value:t,...n}=await this.provider.get(e),r=await this.validator.validate(t);if(!r.valid){let i=r.violations.map(a=>` \u2022 **${a.path}**: ${a.message}`).join(`
|
|
1765
|
+
`;this.runCommand({name:"powershell",arguments:["-Command",`& {${i}}`]});}}runCommand(e){let{commandExecutor:t,timeout:n}=this.configuration;try{let r=t.runSync(e,{timeout:n});return r.exitCode!==0?null:r.output.trim()}catch{return null}}};var Dr=class{constructor(e){this.detector=e.detector,this.templates=e.templates;}async generate(e){let t=await this.detector.detect(e.recipient);return t===null||this.templates[t]===void 0?null:this.templates[t].generate(e)}};var Mr=class{constructor(...e){this.detectors=e;}async detect(e){for(let t of this.detectors){let n=await t.detect(e);if(n!==null)return n}return null}};var Nr=class o{static{this.DEFAULT_DOMAINS={google:["gmail.com","googlemail.com","google.com"],yahoo:[/yahoo\.com(?:\.\w+)?/,"yahoo.co.uk","yahoo.fr","yahoo.it","ymail.com","rocketmail.com"],microsoft:["outlook.com","live.com","hotmail.com","msn.com","passport.com","passport.net"],proton:["proton.me","protonmail.com"],icloud:["icloud.com"]};}constructor(e=o.DEFAULT_DOMAINS){this.domains=e;}detect(e){let t=e.toLowerCase().split("@")[1];for(let[n,r]of Object.entries(this.domains))if(r.some(a=>typeof a=="string"?a===t:a.test(t)))return Promise.resolve(n);return Promise.resolve(null)}};var $r=class o{static{this.DEFAULT_DOMAINS={google:["google.com"],microsoft:["outlook.com"]};}constructor(e=o.DEFAULT_DOMAINS){this.domains=e;}async detect(e){let t=e.toLowerCase().split("@")[1],n=await this.lookup(t);for(let[r,i]of Object.entries(this.domains))for(let a of i)for(let s of n)if(s.endsWith(`.${a}.`))return r;return null}async lookup(e){let t=new URL("https://dns.google.com/resolve");t.searchParams.set("type","MX"),t.searchParams.set("name",e);let n;try{n=await fetch(t).then(r=>{if(!r.ok)throw new Error("Failed to lookup domain");return r.json()});}catch{return []}return n.Answer===void 0?[]:n.Answer.map(r=>r.data)}};var Et=ft(Kt()),zr=class o{generate(e){return new URL(`https://mail.google.com/mail${o.formatFilters(e)}`)}static formatFilters(e){let t=[`to:${e.recipient}`],n=`/u/${e.recipient}`;if(e.sender!==void 0&&t.push(`from:${e.sender}`),e.subject!==void 0&&t.push(`subject:${e.subject}`),e.timestamp!==void 0){let r=Et.TimeZone.of(Intl.DateTimeFormat().resolvedOptions().timeZone),i=Et.Instant.ofEpochSecond(e.timestamp),a=Et.LocalDateTime.ofInstant(i,r).getLocalDate();t.push(`after:${a}`);}return t.push("in:anywhere"),n+=`/#search/${t.map(r=>encodeURIComponent(r)).join("+")}`,n}};var _r=class{generate(e){return new URL("https://www.icloud.com/mail")}};var Lr=class{generate(e){let t=new URL("https://outlook.live.com/mail");return e.recipient!==void 0&&t.searchParams.append("login_hint",e.recipient),t}};var Fr=class o{generate(e){return new URL(`https://mail.proton.me/u/0/all-mail${o.formatFilters(e)}`)}static formatFilters(e){let t=new URLSearchParams;return t.set("to",e.recipient),e.sender!==void 0&&t.set("from",e.sender),e.timestamp!==void 0&&t.set("begin",e.timestamp.toFixed(0)),e.subject!==void 0&&t.set("keyword",e.subject),`#${t.toString()}`}};var jr=class o{generate(e){return new URL(`https://mail.yahoo.com/d/search${o.formatFilters(e)}`)}static formatFilters(e){let t=[`to:${e.recipient}`];return e.sender!==void 0&&t.push(`from:${e.sender}`),e.subject!==void 0&&t.push(`subject:${e.subject}`),e.timestamp!==void 0&&t.push(`after:"${new Date(e.timestamp*1e3).toISOString().split("T")[0]}"`),t.length===0?"":`/keyword=${t.join(" ")}`}};var pn=class{constructor(e){this.config=e;}async execute(e){let{fileSystem:t,io:n}=this.config,r=await this.createTemplate(e.empty??false),i=e.file??t.joinPaths(".","template.json5");try{let a=!1;await t.exists(i)&&(a=await n.input?.confirm({message:`Overwrite existing file at \`${i}\`?`,default:!1})??!1),await t.writeTextFile(i,JSON.stringify(r,null,2),{overwrite:a});}catch(a){throw new d("Failed to write template file",{reason:"other",cause:a})}n.output.confirm(`Template created at \`${i}\``);}async createTemplate(e){return {$schema:"https://schema.croct.com/json/v1/template.json",title:"My template",actions:e?[{name:"print",semantic:"info",title:"Empty template",message:"Edit this template to define your actions."}]:[{name:"create-resource",resources:await this.exportResources()}]}}async exportResources(){let{configurationManager:e,templateForm:t}=this.config,n=await e.load(),r=await t.handle({organizationSlug:n.organization,workspaceSlug:n.workspace}),i={audiences:Object.fromEntries(r.audiences.map(a=>[a.slug,{name:a.name,criteria:a.criteria}])),components:Object.fromEntries(r.components.map(a=>[a.slug,{name:a.name,description:a.description,definition:a.definition}])),slots:Object.fromEntries(r.slots.map(a=>[a.slug,{name:a.name,component:a.component?.slug??"",content:a.content}])),experiences:r.experiences.map(a=>{let{experiment:s}=a,p=s!==void 0?{name:s.name??"",goalId:s.goalId,crossDevice:s.crossDevice,traffic:s.traffic??1,variants:s.variants.map(c=>({name:c.name??"",content:c.content,baseline:c.baseline,allocation:c.allocation??1e3/s.variants.length}))}:void 0;return {name:a.name,draft:a.status==="DRAFT",audiences:a.audiences,slots:a.slots,content:a.content,...p!==void 0?{experiment:p}:{}}})};for(let[a,s]of Object.entries(i))typeof s=="object"&&s!==null&&(Array.isArray(s)&&s.length===0||Object.keys(s).length===0)&&delete i[a];return i}};var Wr=class{constructor(e){this.config=e;}async handle(e){let{input:t,form:n}=this.config,r={components:[],slots:[],audiences:[],experiences:[]},i=new Set,a=new Set,s=await n.experience.handle({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,confirmation:"Do you want to include experiences?"});if(s.length>0){for(let c of s.flatMap(l=>l.audiences))i.add(c);for(let c of s.flatMap(l=>l.slots))a.add(c);r.experiences=s,s.some(c=>c.experiment!==void 0)&&(await t.confirm({message:"Include experiments?",default:false})||(r.experiences=r.experiences.map(c=>{let{experiment:l,...m}=c;return m})));}r.slots=await n.slot.handle({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,selected:[...a],selectionConfirmation:{message:a.size>0?"Do you want to include other slots?":"Do you want to include slots?",default:false}});let p=new Set(r.slots.map(c=>c.component?.slug??""));return r.components=await n.component.handle({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,includeDependencies:true,selected:[...p],selectionConfirmation:{message:p.size>0?"Do you want to include other components?":"Do you want to include components?",default:false}}),r.audiences=await n.audience.handle({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,selected:[...i],selectionConfirmation:{message:i.size>0?"Do you want to include other audiences?":"Do you want to include audiences?",default:false}}),r}};var Vr=class{constructor(e){this.config=e;}async handle(e){let{output:t,input:n,workspaceApi:r}=this.config,i=t.notify("Loading experiences"),a=await r.getExperiences({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});i.stop();let{confirmation:s}=e;if(a.length===0||s!==void 0&&!await n.confirm({message:s}))return [];let p=await n.selectMultiple({message:"Select experiences",options:a.map(l=>({value:l,label:l.name}))});i=t.notify("Loading details");let c=await Promise.all(p.flatMap(async({id:l})=>{let m=await r.getExperience({experienceId:l,organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return m===null?[]:[m]}));return i.stop(),c.flat()}};var Ur=class{constructor(e){this.config=e;}async handle(e){let{output:t,input:n}=this.config,r=t.notify("Loading audiences"),i=await this.getAudiences(e,e.allowed);r.stop();let a=e.preselected??[];if(a.length>0)return i.filter(({slug:p})=>a.includes(p));let s=e.selected??[];return i.length===0||s.length>0&&i.every(({slug:p})=>s.includes(p))?i.filter(({slug:p})=>s.includes(p)):e.selectionConfirmation!==void 0&&!await n.confirm(e.selectionConfirmation)?i.filter(({slug:c})=>s.includes(c)):n.selectMultiple({message:"Select audiences",options:i.map(p=>{let c=s.includes(p.slug);return {value:p,label:p.name,disabled:c,selected:c}})})}async getAudiences(e,t){let{workspaceApi:n}=this.config,r=await n.getAudiences({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return t===void 0?r:r.filter(({slug:i})=>t.includes(i))}};var x=class o extends d{constructor(e,{tracing:t,...n}={}){super(e,n),this.tracing=t??[],Object.setPrototypeOf(this,o.prototype);}static fromCause(e,t={}){let{message:n,...r}=t;if(!(e instanceof Error))return new o(n??d.formatMessage(e),{...r,cause:e});let i=new o(n??e.message,{cause:e,...e instanceof d?e.help:{},...r,tracing:[...r.tracing??[],...e instanceof o?e.tracing:[]]});return i.stack=e.stack,i}};var Rt=class{constructor(e){this.variables={};this.input=e.input,this.output=e.output,this.baseUrl=e.baseUrl;}getVariables(){return structuredClone(this.variables)}set(e,t){this.variables[e]=t;}};var qr=class{constructor(e){this.config=e;}async getOptions(e){let{templateProvider:t}=this.config;return (await t.get(await this.resolveUrl(e))).value.options??{}}async execute(e){let{action:t,io:n}=this.config,{template:r,options:i}=e,a=await this.resolveUrl(r);return t.execute({template:a.toString(),options:i},new Rt({input:n.input,output:n.output,baseUrl:a}))}async resolveUrl(e){let{fileSystem:t}=this.config,n=e;if(URL.canParse(e)){let r=new URL(e);if(r.protocol!=="file:")return r;n=t.normalizeSeparators(r.pathname);}try{return new URL(`file://${await t.getRealPath(n)}`)}catch(r){throw new x(`Template file not found at \`${n}\`.`,{reason:"invalid_input",cause:r,suggestions:["Check the file path and try again."]})}}};function Tt(o,e){if(URL.canParse(o))return new URL(o);let t=new URL(e.href.replace(/^(.*:)(?!\/)/,"$1/"));return new URL(o,t)}var Hr=class{constructor(e){this.config=e;}async execute(e,t){let{fileSystem:n}=this.config,{input:r}=t,i=Tt(e.source,t.baseUrl);if(i.protocol==="file:"&&t.baseUrl.protocol!=="file:")throw new x("File URL is not allowed from remote sources for security reasons.",{reason:"precondition",details:[`Source URL: ${i}`]});let a=n.normalizeSeparators(e.destination),{output:s}=t,p=s?.notify("Downloading sources");try{await this.download(i,a,e.filter!==void 0?new Minimatch(e.filter):void 0,r);}finally{p?.stop();}e.result?.destination!==void 0&&t.set(e.result.destination,a);}async download(e,t,n,r){let{provider:i,fileSystem:a,codemod:s}=this.config,{value:p}=await i.get(e),c=[];for await(let l of p){let m=a.normalizeSeparators(l.name);if(!(a.isAbsolutePath(m)||!a.isSubPath(t,m))&&!(n!==void 0&&!n.match(m))){if(l.name=a.joinPaths(t,m),l.type==="link"||l.type==="symlink"){let f=a.normalizeSeparators(l.target);if(a.isAbsolutePath(f)||!a.isSubPath(t,f))continue;l.target=f;}c.push(l);}}if(c.length!==0){if(await a.exists(t)){if(c.length===1&&c[0].type==="file"){if(await a.exists(c[0].name)&&await r?.confirm({message:`File ${c[0].name} already exists. Do you want to overwrite it?`,default:false})!==true)throw new x("Destination file already exists.",{reason:"precondition",details:[`File: ${c[0].name}`],suggestions:["Delete the file"]})}else if(!await a.isDirectory(t)||!await a.isEmptyDirectory(t)){if(await r?.confirm({message:`Directory ${t} is not empty. Do you want to clear it?`,default:false})!==true)throw new x("Destination directory is not empty.",{reason:"precondition",details:[`Directory: ${t}`],suggestions:["Clear the directory"]});await a.delete(t,{recursive:true});}}await a.createDirectory(t,{recursive:true});for(let l of c)await a.create(l);for(let l of c)l.type==="file"&&await s.apply(await a.getRealPath(l.name));}}};var Gr=class{constructor({packageManager:e}){this.packageManager=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Installing dependencies");try{await this.packageManager.addDependencies(e.dependencies,e.development===!0);}catch(i){throw x.fromCause(i)}finally{r?.stop();}}};var Kr=class{constructor({projectDirectory:e,fileSystem:t,matcherProvider:n}){this.projectDirectory=e,this.fileSystem=t,this.matcherProvider=n;}async execute(e,t){let{output:n}=t,r=n?.notify("Locating files");try{await this.findMatches(e,t);}finally{r?.stop();}}async findMatches(e,t){let n=await this.findMatch(e.path,e);e.result!==void 0&&t.set(e.result,n);}async findMatch(e,t){let n=await this.matcherProvider.get(e),r=[];for await(let i of this.fileSystem.list(this.projectDirectory.get(),t.depth))if(await n.test(i.name)){if(t.matcher===void 0)r.push(i.name);else if(i.type==="file"){let a=await new Response(i.content).text();this.matches(a,t.matcher)&&r.push(i.name);}if(t.limit!==void 0&&r.length>=t.limit)break}return r}matches(e,t){if("pattern"in t)return new RegExp(t.pattern,t.caseSensitive===true?"i":void 0).test(e);switch(t.type){case "and":return t.matchers.every(n=>this.matches(e,n));case "or":return t.matchers.some(n=>this.matches(e,n))}}};var Zr=class{constructor({fileSystem:e}){this.fileSystem=e;}async execute(e,t){let{output:n}=t,r=n.notify("Replacing file content");try{await this.replaceFiles(e);}finally{r.stop();}}async replaceFiles(e){for(let{path:t,replacements:n}of e.files)if(await this.fileSystem.exists(t))try{await this.fileSystem.writeTextFile(t,this.replaceContent(await this.fileSystem.readTextFile(t),n),{overwrite:!0});}catch(r){throw x.fromCause(r)}}replaceContent(e,t){let n=e;for(let{pattern:r,caseSensitive:i,value:a}of t){let s=i===true?"gi":"g";n=n.replaceAll(new RegExp(r,s),`${a}`);}return n}};var Jr=class{constructor({installer:e}){this.installer=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Installing slots");try{await this.installer(e.slots,e.example===!0);}catch(i){throw x.fromCause(i)}finally{r?.stop();}}};var Qr=class{constructor({installer:e}){this.installer=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Installing components");try{await this.installer(e.components);}catch(i){throw x.fromCause(i)}finally{r?.stop();}}};var Br=class{constructor(e){this.runner=e;}async execute(e,t){try{await this.run(e.action,t);}catch(n){if(e.else===void 0)throw e.help===void 0?n:x.fromCause(n,{...e.help,reason:"precondition"});await this.run(e.else,t);}finally{e.finally!==void 0&&await this.run(e.finally,t);}}run(e,t){return this.runner.execute({actions:e},t)}};var U=class o extends d{constructor(e,t={}){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var Be=class{constructor(e){this.provider=e;}get action(){return Promise.resolve(this.provider.get()).catch(e=>{throw e instanceof U?new x(e.message,e.help):e})}async execute(e,t){return (await this.action).execute(e,t)}};var Yr=class{constructor(e){this.manager=e;}isInitialized(){return this.manager.isInitialized()}load(){return this.configuration===void 0&&(this.configuration=this.manager.load()),this.configuration}update(e){return this.configuration=this.manager.update(e),this.configuration}};var Ga;(r=>{function o(i){let a=new Set(Object.values(i.slots??{}).map(m=>m.component)??[]),s=new Set(i.experiences?.flatMap(m=>m.slots)??[]),p=new Set(i.experiences?.flatMap(m=>m.audiences)??[]),c=(i.experiences??[]).map(m=>({name:m.name,maximumAudiencesPerExperience:m.audiences.length,crossDevice:m.experiment?.crossDevice===true,...e(m)})),l=new Set;for(let m of Object.values(i.slots??{}))for(let f of Object.keys(m.content))l.add(f);for(let m of c){for(let f of m.locales)l.add(f);for(let f of m.audiences)p.add(f);for(let f of m.slots)s.add(f);}return {components:a,slots:s,audiences:p,locales:l,experiences:c}}r.analyze=o;function e(i){let a=t(i.content);for(let s of i.experiment?.variants??[]){let p=t(s.content);p.audiences.forEach(c=>a.audiences.add(c)),p.slots.forEach(c=>a.slots.add(c));}return {...a}}function t(i){let a=new Set,s=new Set,p=0;for(let[m,f]of Object.entries(i.default)){a.add(m);for(let[b,A]of Object.entries(f))s.add(b),p=Math.max(p,n(A));}let c=new Set,l=0;for(let m of i.segmented){for(let f of m.audiences)c.add(f);l=Math.max(l,m.audiences.length);for(let[f,b]of Object.entries(m.content)){a.add(f);for(let[A,I]of Object.entries(b))s.add(A),p=Math.max(p,n(I));}}return {slots:a,audiences:c,locales:s,audiencesPerExperience:l,dynamicContentPerContent:p}}function n(i){switch(i.type){case "boolean":case "text":case "number":return i.value.type==="dynamic"?1:0;case "structure":return Object.values(i.attributes).map(n).reduce((a,s)=>a+s,0);case "list":return i.items.map(n).reduce((a,s)=>a+s,0)}}})(Ga||={});var Xr=class{constructor(e){this.refactoring=e;}refactor(e){return {components:Object.fromEntries(Object.entries(e.components??{}).map(([t,n])=>[this.refactoring.componentMapping[t]??t,n])),slots:Object.fromEntries(Object.entries(e.slots??{}).map(([t,n])=>[this.refactoring.slotMapping[t]??t,this.refactorSlotContent(n)])),audiences:Object.fromEntries(Object.entries(e.audiences??{}).map(([t,n])=>[this.refactoring.audienceMapping[t]??t,n])),experiences:e.experiences?.map(t=>this.refactorExperience(t))??[]}}refactorSlotContent(e){return {...e,component:this.refactoring.componentMapping[e.component]??e.component,content:this.refactorLocalizedContentMap(e.content)}}refactorExperience(e){return {...e,audiences:e.audiences.map(t=>this.refactoring.audienceMapping[t]??t),slots:e.slots.map(t=>this.refactoring.slotMapping[t]??t),experiment:e.experiment!==void 0?{...e.experiment,crossDevice:(e.experiment.crossDevice??false)&&this.refactoring.isCrossDeviceFeatureEnabled}:void 0,content:this.refactorPersonalizedContent(e.content,e.audiences.slice(0,this.refactoring.maximumAudiencePerExperience))}}refactorPersonalizedContent(e,t){return {default:this.refactorSlotContentMap(e.default),segmented:e.segmented.flatMap(n=>{let r=n.audiences.filter(i=>t.includes(i));return r.length===0?[]:{audiences:r,content:this.refactorSlotContentMap(n.content)}})}}refactorSlotContentMap(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[this.refactoring.slotMapping[t]??t,this.refactorLocalizedContentMap(n)]))}refactorLocalizedContentMap(e){return Object.fromEntries(Object.entries(e).flatMap(([t,n])=>{let r=this.refactoring.localeMapping[t];return r===null||r!==void 0&&e[r]!==void 0?[]:[[r??t,this.refactorContent(n,{dynamicAttributesPerContent:this.refactoring.dynamicAttributesPerContent})]]}))}refactorContent(e,t){switch(e.type){case "boolean":case "text":case "number":return e.value.type==="dynamic"&&t.dynamicAttributesPerContent>0&&t.dynamicAttributesPerContent--,e.value.type==="static"||t.dynamicAttributesPerContent>0?e:{...e,value:{type:"static",value:e.value.default}};case "structure":return {...e,attributes:Object.fromEntries(Object.entries(e.attributes).map(([n,r])=>[n,this.refactorContent(r,t)]))};case "list":return {...e,items:e.items.map(n=>this.refactorContent(n,t))}}}};var ei=class o{constructor(e){this.config=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Analyzing resources"),i=Ga.analyze(e.resources);this.checkMissingResources({...i,locales:new Set},e.resources);let{configurationManager:a,api:{workspace:s}}=this.config,p=await a.load(),c=await this.getProjectInfo(p),l=await this.createPlan(e.resources,i,c);r?.update("Creating resources");let m=await s.createResources({organizationSlug:p.organization,workspaceSlug:p.workspace,...l.resources});if(r?.stop(),n!==void 0){let f=o.getWarnings(i,c.workspace);if(f.length>0)for(let b of f)n.warn(`${b}`);}e.result!==void 0&&o.setVariables(e.result,l,m,t);}async createPlan(e,t,n){let{mappingForm:r,matcher:i}=this.config,a=await i.match({resources:e,workspaceSlug:n.configuration.workspace,organizationSlug:n.configuration.organization}),s=Object.entries(a.audiences).filter(I=>!("id"in I[1])),p=Object.entries(a.components).filter(I=>!("id"in I[1])),c=Object.entries(a.slots).filter(I=>!("id"in I[1])),l=a.experiences.filter(I=>!("id"in I)),m=l.flatMap(I=>I.experiment===void 0?[]:[I.experiment]);await this.checkRequiredQuota(n,{components:p.length,slots:c.length,audiences:s.length,experiences:l.length,experiments:m.length});let f=await r.handle({organizationSlug:n.configuration.organization,workspaceSlug:n.configuration.workspace,resources:{audiences:s.map(([I])=>I),components:p.map(([I])=>I),slots:c.map(([I])=>I)}}),b={},{workspace:A}=n;for(let I of t.locales)A.locales.includes(I)||(b[I]=A.defaultLocale);return {matches:a,mapping:f,resources:new Xr({componentMapping:f.components,audienceMapping:f.audiences,slotMapping:f.slots,dynamicAttributesPerContent:A.quotas.dynamicAttributesPerContent,maximumAudiencePerExperience:A.quotas.audiencesPerExperience,isCrossDeviceFeatureEnabled:A.features.crossDevice,localeMapping:b}).refactor({components:Object.fromEntries(p),slots:Object.fromEntries(c),audiences:Object.fromEntries(s),experiences:l})}}async getProjectInfo(e){let{api:t}=this.config,[n,r]=await Promise.all([t.organization.getWorkspace({organizationSlug:e.organization,workspaceSlug:e.workspace}),t.workspace.getFeatures({organizationSlug:e.organization,workspaceSlug:e.workspace})]);if(n==null||r==null)throw new d("Workspace not found",{title:"Invalid configuration",reason:"invalid_configuration",details:["The workspace defined in the configuration does not exist"],suggestions:["Check the configuration file"]});return {configuration:e,workspace:{...n,...r}}}async checkRequiredQuota(e,t){let{api:{user:n}}=this.config;for(let[r,i]of Object.entries(t)){let a=o.getRemainingQuota(e.workspace,r);if(a<i){let s=await n.getUser().catch(()=>({email:void 0})),p=new URL("https://croct.com/contact/support");throw p.searchParams.set("subject","limit-increase"),p.searchParams.set("organization",e.configuration.organization),p.searchParams.set("message",`I need more quota for ${r}`),s.email!==void 0&&p.searchParams.set("email",s.email),new d(`Not enough ${r} quota available in your workspace.`,{title:"Insufficient quota",reason:"precondition",links:[{label:"Request more quota",url:p.toString()}],details:[`Available: ${a}`,`Required: ${i}`],suggestions:[`Free up quota by removing unused ${r}`,"Request additional quota from support"]})}}}checkMissingResources(e,t){let n=this.findMissingResources(e,t);for(let[r,i]of Object.entries(n))if(i.size>0)throw new d(`Some ${r} referenced in the template are missing`,{title:"Invalid template",reason:"invalid_input",details:[`Missing ${r}: ${Array.from(i).join(", ")}`],suggestions:["Report this issue to the template author"]})}findMissingResources(e,t){let n=new Set(e.components),r=new Set(e.slots),i=new Set(e.audiences),a=new Set(e.locales);for(let s of Object.keys(t.components??{}))n.delete(s);for(let s of Object.keys(t.slots??{}))r.delete(s);for(let s of Object.keys(t.audiences??{}))i.delete(s);return {components:n,slots:r,audiences:i,locales:a}}static getRemainingQuota(e,t){let n=t.charAt(0).toUpperCase()+t.slice(1);return e.quotas[`remaining${n}`]}static getWarnings(e,t){let n=[];return Math.max(...e.experiences.map(s=>s.dynamicContentPerContent))>t.quotas.dynamicAttributesPerContent&&n.push("Some dynamic values have been removed from the content to fit the workspace quota"),Math.max(...e.experiences.map(s=>s.audiencesPerExperience))>t.quotas.audiencesPerExperience&&n.push("Some audiences have been removed from the experiences to fit the workspace quota"),Array.from(e.locales).filter(s=>!t.locales.includes(s)).length>0&&n.push("Content in unsupported locales have been mapped to default or dropped"),!t.features.crossDevice&&e.experiences.some(s=>s.crossDevice)&&n.push("Cross-device experiments have been disabled "),n}static setVariables(e,t,n,r){if(e.audiences!==void 0)for(let[i]of Object.entries(t.matches.audiences??{}))e.audiences[i]!==void 0&&r.set(e.audiences[i],t.mapping.audiences[i]??i);if(e.components!==void 0)for(let[i]of Object.entries(t.matches.components??{})){let a=e.components[i];if(a!==void 0){let s=t.mapping.components[i]??i,p=t.matches.components[i]??{};a.id!==void 0&&r.set(a.id,s),a.version!==void 0&&r.set(a.version,"version"in p?p.version.major:1);}}if(e.slots!==void 0)for(let[i]of Object.entries(t.matches.slots??{})){let a=e.slots[i];if(a!==void 0){let s=t.mapping.slots[i]??i,p=t.matches.slots[i]??{};a.id!==void 0&&r.set(a.id,s),a.version!==void 0&&r.set(a.version,"version"in p?p.version.major:1);}}if(e.experiences!==void 0){let{experiences:i}=t.matches,a=0;for(let[s,p]of i.entries()){e.experiences[s]!==void 0&&r.set(e.experiences[s],"id"in p?p.id:n.experiences[a].experienceId);let c=p.experiment!==void 0&&"id"in p.experiment?p.experiment.id:n.experiences[a].experimentId;c!==void 0&&e.experiments?.[s]!==void 0&&r.set(e.experiments[s],c),"id"in p||a++;}}}};var Ot=class o{constructor(e){this.config=e;}static prompt(e){return new o(e).handle()}handle(){let{input:e,unavailableSlugs:t=[],default:n}=this.config;return e.prompt({message:this.config.label,default:n,validate:r=>/^[a-z]+(-?[a-z0-9]+)*$/i.test(r)?t.includes(r)?"The entered slug is already in use.":true:"The slug must start with a letter and contain only letters, numbers, and hyphens."})}};var ti=class{constructor(e){this.config=e;}async handle(e){let{input:t,workspaceApi:n}=this.config,{resources:r,...i}=e,a=r.slots??[],s=r.components??[],p=r.audiences??[],[c,l,m]=await Promise.all([a.length>0?n.getSlots(i):new Array,s.length>0?n.getComponents(i):new Array,p.length>0?n.getAudiences(i):new Array]),f=s.filter(j=>l.some(T=>T.slug===j)),b={};if(f.length>0){let j=l.map(T=>T.slug);for(let T of f){let H=await Ot.prompt({input:t,default:T,unavailableSlugs:j,label:`Component \`${T}\` already exists, enter a new component ID:`});j.push(H),b[T]=H;}}let A=a.filter(j=>c.some(T=>T.slug===j)),I={};if(A.length>0){let j=c.map(T=>T.slug);for(let T of A){let H=await Ot.prompt({input:t,default:T,unavailableSlugs:j,label:`Slot \`${T}\` already exists, enter a new slot ID:`});j.push(H),I[T]=H;}}let y=p.filter(j=>m.some(T=>T.slug===j)),M={};if(y.length>0){let j=m.map(T=>T.slug);for(let T of y){let H=await Ot.prompt({input:t,default:T,unavailableSlugs:j,label:`Audience \`${T}\` already exists, enter a new audience ID:`});j.push(H),M[T]=H;}}return {components:b,slots:I,audiences:M}}};var ni=class o{constructor(e){this.config=e;}async match(e){let{resources:t,...n}=e,[r,i,a,s]=await Promise.all([this.mapComponents(t.components??{},n),this.mapSlots(t.slots??{},n),this.mapAudiences(t.audiences??{},n),this.mapExperiences(t.experiences??[],n)]);return {components:r,slots:i,audiences:a,experiences:s}}async mapAudiences(e,t){let{workspaceApi:n}=this.config,r=await Promise.all(Object.keys(e).map(async a=>[a,await n.getAudience({...t,audienceSlug:a})])),i={};for(let[a,s]of r)i[a]=s===null||!o.isSimilarAudience(e[a],s)?e[a]:s;return i}async mapComponents(e,t){let{workspaceApi:n}=this.config,r=await Promise.all(Object.keys(e).map(async a=>[a,await n.getComponent({...t,componentSlug:a})])),i={};for(let[a,s]of r)i[a]=s===null||!o.isSimilarComponent(e[a],s)?e[a]:s;return i}async mapSlots(e,t){let{workspaceApi:n}=this.config,r=await Promise.all(Object.keys(e).map(async a=>[a,await n.getSlot({...t,slotSlug:a})])),i={};for(let[a,s]of r)i[a]=s===null||!o.isSimilarSlot(e[a],s)?e[a]:s;return i}async mapExperiences(e,t){let{workspaceApi:n}=this.config,i=(await n.getExperiences({...t,status:["ACTIVE","PAUSED","DRAFT"]})).map(a=>{let s=null;function p(){return s===null&&(s=n.getExperience({...t,experienceId:a.id})),s}return {...a,details:{get content(){return p().then(c=>c?.content??null)},get experiment(){return p().then(c=>c?.experiment??null)}}}});return Promise.all(e.map(async a=>{for(let s of i)if(await this.matchesExperience(a,s)){let{details:p,...c}=s;return c}return a}))}async matchesExperience(e,t){if((e.draft===true?"DRAFT":"ACTIVE")!==t.status||!deepEqual(e.audiences,t.audiences)||!deepEqual(e.slots,t.slots)||e.experiment!==void 0&&t.experiment===void 0)return false;let[r,i=null]=await Promise.all([t.details.content,t.details.experiment]);return e.experiment!==void 0&&(i===null||e.experiment.goalId!==i.goalId||e.experiment.traffic!==i.traffic||e.experiment.crossDevice!==i.crossDevice||!o.isSimilarExperimentContent(e.experiment.variants,i.variants))?false:o.isSimilarPersonalizedContent(e.content,r??{default:{},segmented:[]})}static isSimilarAudience(e,t){return e.criteria===t.criteria}static isSimilarComponent(e,t){return deepEqual(e.definition,t.definition)}static isSimilarSlot(e,t){return e.component===t.component?.slug&&Object.values(e.content).some(n=>Object.values(t.content).some(r=>deepEqual(n,r)))}static isSimilarExperimentContent(e,t){return e.length!==t.length?false:e.some((n,r)=>deepEqual(n,t[r]))}static isSimilarPersonalizedContent(e,t){if(o.isSimilarSlotContent(e.default,t.default))return true;for(let n of e.segmented)for(let r of t.segmented)if(deepEqual(n.audiences,r.audiences)&&o.isSimilarSlotContent(n.content,r.content))return true;return false}static isSimilarSlotContent(e,t){for(let[n,r]of Object.entries(e)){let i=t[n];if(i!==void 0){for(let a of Object.values(r))if(Object.values(i).some(s=>deepEqual(a,s)))return true}}return false}};var W=class o extends U{constructor(e,{url:t,...n}){super(e,n),Object.setPrototypeOf(this,o.prototype),this.url=t;}},$e=class o extends W{constructor(e,t){super(e,{...t,reason:t.reason??"not_found"}),Object.setPrototypeOf(this,o.prototype);}};var ri=class o{async get(e){if(!["http:","https:"].includes(e.protocol))throw new W("Unsupported protocol.",{reason:"not_supported",url:e});let t=await fetch(e);if(t.status===404)throw new $e("Resource not found.",{url:e});if(!o.isSuccessful(t))throw new W(t.statusText,{url:e});return {url:e,value:t}}static isSuccessful(e){return e.ok&&e.body!==null}};var ii=class{constructor({packageManager:e}){this.packageManager=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Checking dependencies"),i;try{i=await Promise.all(e.dependencies.map(s=>this.checkRequirement(s)));}finally{r?.stop();}let a=[];if(e.result!==void 0)for(let s of i){if(e.result[s.dependency]!==void 0){t.set(e.result[s.dependency],s.issue===void 0);continue}s.issue!==void 0&&a.push(s);}if(a.length>0){let{message:s,...p}=e.help??{};throw new x(s??"Missing required dependencies.",{...p,details:a.map(({dependency:c,issue:l})=>`\`${c}\`: ${l}`)})}}async checkRequirement(e){let{name:t,version:n,optional:r=false}=e;if(r&&(n===void 0||!await this.packageManager.hasDirectDependency(t))||await this.packageManager.hasDirectDependency(t,n))return {dependency:t};let i=await this.packageManager.getDependency(t);return {dependency:t,issue:i===null?"not installed":`version \`${n}\` is required, found \`${i.version??"unknown"}\``}}};var Dt=class{constructor({dataProvider:e,registryProvider:t,baseUrl:n}){this.dataProvider=e,this.registryProvider=t,this.baseUrl=n;}async get(e){return this.dataProvider.get(await this.resolveUrl(e))}async resolveUrl(e){for(let{pattern:t,destination:n}of await this.loadMappings(e)){let r=e.href.match(typeof t=="string"?new RegExp(t):t);if(r!==null)return n instanceof URL?n:new URL(n.replace(/\$([0-9]+)/g,(i,a)=>r[Number.parseInt(a,10)]),this.baseUrl)}return e}async loadMappings(e){let t=await this.registryProvider.get(e);return Array.isArray(t)?t:t.value}};var Ye=class o{static{this.EXPECTED_ERROR_REASONS=["not_supported","not_found"];}constructor(...e){this.providers=e;}async get(e){for(let t of this.providers)try{return await t.get(e)}catch(n){if(!o.isExpectedError(n))throw n}throw new $e("Resource not found.",{url:e})}static isExpectedError(e){return e instanceof W&&o.EXPECTED_ERROR_REASONS.includes(e.reason)}};var oi=class o{constructor(e){this.fileSystem=e;}supports(e){return Promise.resolve(o.supportsUrl(e))}get(e){if(!o.supportsUrl(e))throw new W(`Unsupported protocol "${e.protocol}".`,{reason:"not_supported",url:e});return Promise.resolve({url:e,value:this.fileSystem.list(this.fileSystem.normalizeSeparators(e.pathname))})}static supportsUrl(e){return e.protocol==="file:"}};var cn=class o{static{this.PROTOCOL="github:";}static{this.API_HOST="api.github.com";}static{this.RAW_HOST="raw.github.com";}static{this.MAIN_HOST="github.com";}constructor(e){this.provider=e;}async get(e){let t=this.parseUrl(e);if(t===null)throw new W("Unsupported GitHub URL.",{reason:"not_supported",url:e});let n=this.resolveFile(t),{value:r}=await this.provider.get(n.url);return {url:t.canonicalUrl,value:n.url.hostname===o.RAW_HOST?this.extractFile(r,n):this.extractTarball(r,n)}}async*extractTarball(e,t){let n=eu.extract();Readable.fromWeb(e.body).pipe(tu()).pipe(n);let r=o.removeTrailSlash(t.path??"");for await(let i of n){let{header:a}=i;i.resume();let s=o.removeTrailSlash(a.name.split("/").slice(1).join("/"));if(s===""||!s.startsWith(r)||i.header.type==="directory"&&s===r)continue;let p=s;switch(r.length>0&&s.length>r.length&&(p=s.slice(r.length+1)),a.type){case "file":yield {type:"file",name:p,content:i};break;case "directory":yield {type:"directory",name:p};break;case "link":yield {type:"link",name:p,target:a.linkname};break;case "symlink":yield {type:"symlink",name:p,target:a.linkname};break}if(p===r)break}}async*extractFile(e,t){yield {type:"file",name:t.url.pathname.split("/").pop(),content:Readable.fromWeb(e.body)};}resolveFile(e){let{username:t,repository:n,path:r}=e,i=e.ref??"HEAD";return {...e,url:new URL(r!==null&&/\..+$/.test(r)?`https://${o.RAW_HOST}/${t}/${n}/${i}/${r}`:`https://${o.API_HOST}/repos/${t}/${n}/tarball/${i}`)}}parseUrl(e){if(!o.isUrlSupported(e))return null;let t,n,r=null,i,a=e.pathname.replace(/^\/+/,"").split("/"),s=null;return e.hostname===o.MAIN_HOST?(s=e,[t=null,n=null,,r=null,...i]=a):[t=null,n=null,...i]=a,t===null||n===null?null:(s===null&&(s=new URL(`https://${o.MAIN_HOST}`),s.pathname=`/${t}/${n}/blob/master/${i.join("/")}`),{canonicalUrl:s,username:t,repository:n,ref:r,path:i!==void 0&&i.length>0?i.join("/"):null})}static isUrlSupported(e){return e.protocol==="https:"?e.hostname===o.MAIN_HOST:e.protocol===o.PROTOCOL}static removeTrailSlash(e){return e.replace(/\/$/,"")}};var ln=class o{constructor(e){this.provider=e;}async get(e){if(!o.supportsUrl(e))throw new W("Unsupported URL.",{reason:"not_supported",url:e});let{value:t,...n}=await this.provider.get(e);return {...n,value:this.yield(t,e)}}static supportsUrl(e){return e.pathname!=="/"}async*yield(e,t){yield {type:"file",name:t.pathname.split("/").pop(),content:Readable.fromWeb(e.body)};}};var B=class{constructor(e){this.schema=e;}async validate(e){let t=await this.schema.safeParseAsync(e);if(t.success)return {valid:true,data:t.data};let{error:n}=t;return {valid:false,violations:n.issues.map(r=>({path:r.path.reduce((i,a)=>typeof a=="string"?i===""?a:`${i}.${a}`:`${i}[${a}]`,""),message:r.message}))}}};var ru=z.object({name:z.string(),version:z.string().optional(),dependencies:z.record(z.string()).optional(),devDependencies:z.record(z.string()).optional(),bin:z.record(z.string()).optional(),scripts:z.record(z.string()).optional(),packageManager:z.string().optional()}),un=class extends B{constructor(){super(ru);}};var ai=z.string().regex(/^[a-z]+(-?[a-z0-9]+)*$/i,"An identifier must start with a letter and contain only letters, numbers, and hyphens."),sc=z.string().regex(/^[a-z]{2,3}([-_][a-z]{2,3})?$/i,"Locale must be in the form of en, en_US, or en-US."),pc=z.string().refine(O.isValid,"Version must be exact (1), range (1 - 2), or set (1 || 2).").refine(o=>{try{return O.parse(o).getCardinality()<=5}catch{return false}},"Version range must not exceed 5 major versions."),iu=z.strictObject({$schema:z.string().optional(),organization:ai,workspace:ai,applications:z.strictObject({development:ai,production:ai.optional()}),locales:z.array(sc),defaultLocale:sc,slots:z.record(pc),components:z.record(pc),paths:z.strictObject({components:z.string(),examples:z.string(),content:z.string().optional()})}).refine(o=>o.locales.includes(o.defaultLocale),{message:"The default locale is not included in the list of locales.",path:["defaultLocale"]}),si=class extends B{constructor(){super(iu);}};var Mt=class{constructor({provider:e,validator:t}){this.provider=e,this.validator=t;}async get(e){let{value:t,...n}=await this.provider.get(e),r=await this.validator.validate(t);if(!r.valid){let i=r.violations.map(a=>` \u2022 **${a.path}**: ${a.message}`).join(`
|
|
1766
1766
|
|
|
1767
1767
|
`);throw new W(`The response data is invalid:
|
|
1768
1768
|
|
|
1769
1769
|
${i}`,{reason:"invalid_input",url:e})}return {...n,value:r.data}}};var mt=class{constructor(e){this.provider=e;}async get(e){let{value:t,...n}=await this.provider.get(e),r=await t.next();if(r.done===true||r.value.type!=="file")throw new $e("File not found.",{url:e});return {...n,value:await new Response(r.value.content).text()}}};var mn=class{constructor(e){this.provider=e;}async get(e){let{value:t,...n}=await this.provider.get(e);try{return {...n,value:JsonParser$1.parse(t).toJSON()}}catch(r){throw new W("Malformed JSON.",{reason:"precondition",url:e,cause:r})}}};var au=z.strictObject({pattern:z.string().refine(o=>{try{return new RegExp(o),!0}catch{return {message:"Invalid regular expression."}}}),destination:z.string()}),su=z.array(au),ci=class extends B{constructor(){super(su);}};var dn=class{constructor({fileSystem:e,directory:t,useKeyAsFileName:n}){this.fileSystem=e,this.directory=t,this.useKeyAsFileName=n??false;}async delete(e){await this.fileSystem.delete(this.getCacheFile(e));}async get(e,t){try{return await this.fileSystem.readTextFile(this.getCacheFile(e))}catch{return t(e)}}async set(e,t){return await this.fileSystem.exists(this.directory)||await this.fileSystem.createDirectory(this.directory,{recursive:true}),this.fileSystem.writeTextFile(this.getCacheFile(e),t,{overwrite:true})}getCacheFile(e){return this.fileSystem.joinPaths(this.directory,this.useKeyAsFileName?e:createHash("md5").update(e).digest("hex"))}};var gn=class{constructor({provider:e,resourceCache:t,errorCache:n}){this.provider=e,this.resourceCache=t,this.errorCache=n;}async get(e){let t=await this.errorCache?.get(e.toString(),()=>Promise.resolve());return t!==void 0?Promise.reject(t):this.resourceCache.get(e.toString(),async()=>{try{return await this.provider.get(e)}catch(n){throw this.errorCache?.set(e.toString(),n),n}})}};var Nt;(e=>{function o(...t){return t.reduce((n,r)=>Object.defineProperties(n,Object.getOwnPropertyDescriptors(r)),{})}e.merge=o;})(Nt||={});var $=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var li=class o{constructor(e={}){this.cache=new Map;this.configuration=e;}static{this.ALLOWED_ARRAY_PROPERTIES=["length"];}static{this.ALLOWED_ARRAY_METHODS=["slice","join"];}static{this.ALLOWED_STRING_PROPERTIES=["length"];}static{this.ALLOWED_STRING_METHODS=["slice","includes","startsWith","endsWith","toLowerCase","toUpperCase"];}static{this.LITERALS={true:true,false:false,null:null};}static{this.UNARY_OPERATORS={"!":{evaluate:async e=>!await fn(e)},"-":{evaluate:async e=>-await J(e)},"+":{evaluate:async e=>+await J(e)}};}static{this.BINARY_OPERATORS={"||":{precedence:1,evaluate:async(e,t)=>await fn(e)||fn(t)},"??":{precedence:1,evaluate:async(e,t)=>await e()??t()},"&&":{precedence:2,evaluate:async(e,t)=>await fn(e)&&fn(t)},"==":{precedence:6,evaluate:async(e,t)=>await e()==await t()},"===":{precedence:6,evaluate:async(e,t)=>await e()===await t()},"!=":{precedence:6,evaluate:async(e,t)=>await e()!=await t()},"!==":{precedence:6,evaluate:async(e,t)=>await e()!==await t()},"<":{precedence:7,evaluate:async(e,t)=>await J(e)<await J(t)},">":{precedence:7,evaluate:async(e,t)=>await J(e)>await J(t)},"<=":{precedence:7,evaluate:async(e,t)=>await J(e)<=await J(t)},">=":{precedence:7,evaluate:async(e,t)=>await J(e)>=await J(t)},"+":{precedence:9,evaluate:async(e,t)=>{let[n,r]=await Promise.all([e(),t()]);if(typeof n=="string"||typeof r=="string")return `${n}${r}`;if(typeof n!="number"||typeof r!="number")throw new $(`Operands must be numbers or strings, got ${d.describeType(n)} and ${d.describeType(r)}.`);return n+r}},"-":{precedence:9,evaluate:async(e,t)=>await J(e)-await J(t)},"*":{precedence:10,evaluate:async(e,t)=>await J(e)*await J(t)},"/":{precedence:10,evaluate:async(e,t)=>await J(e)/await J(t)},"%":{precedence:10,evaluate:async(e,t)=>await J(e)%await J(t)},"**":{precedence:11,evaluate:async(e,t)=>(await J(e))**await J(t)}};}evaluate(e,t){return this.evaluateExpression(this.parse(e),t)}parse(e){let t=this.cache.get(e);if(t!==void 0)return t;Ue.plugins.register(cu),Ue.plugins.register(lu),Ue.removeAllUnaryOps();for(let r of Object.keys(o.UNARY_OPERATORS))Ue.addUnaryOp(r);Ue.removeAllBinaryOps();for(let[r,{precedence:i}]of Object.entries(o.BINARY_OPERATORS))Ue.addBinaryOp(r,i);Ue.removeAllLiterals();for(let[r,i]of Object.entries(o.LITERALS))Ue.addLiteral(r,i);let n;try{n=Ue(e);}catch(r){throw new $("Malformed expression.",{cause:r,details:[`Expression: ${e}`]})}return this.cache.set(e,n),n}async evaluateExpression(e,t){switch(true){case Q(e,"Literal"):return e.value;case Q(e,"ThisExpression"):case Q(e,"Identifier"):{let n=e.type==="ThisExpression"?"this":e.name,r=t?.variables?.[n];if(r===void 0)throw new $(`Variable \`${n}\` is unknown.`);return r}case Q(e,"ArrayExpression"):return (await Promise.all(e.elements.map(r=>{if(r===null)return [];if(Q(r,"SpreadElement")){let i=this.evaluateExpression(r.argument,t);if(!(i instanceof Promise)&&!Array.isArray(i))throw new $(`Spread expression must evaluate to an array, got ${d.describeType(i)}.`);return i}return [this.evaluateExpression(r,t)]}))).flat();case Q(e,"ObjectExpression"):return Object.fromEntries(await Promise.all(e.properties.flatMap(async n=>{if(Q(n,"SpreadElement")){let i=await this.evaluateExpression(n.argument,t);if(typeof i!="object"||i===null)throw new $(`Spread expression must evaluate to an object, got ${d.describeType(i)}.`);return Object.entries(i)}return n.value===void 0&&Q(n.key,"Identifier")?[n.key.name,await this.evaluateExpression(n.key,t)]:[[Q(n.key,"Identifier")?n.key.name:this.evaluateExpression(n.key,t).then(i=>{if(typeof i!="string"&&typeof i!="number")throw new $(`Property name must be a string or a number, got ${d.describeType(i)}.`);return i}),await this.evaluateExpression(n.value,t)]]})));case Q(e,"UnaryExpression"):return o.UNARY_OPERATORS[e.operator].evaluate(()=>this.evaluateExpression(e.argument,t));case Q(e,"BinaryExpression"):return o.BINARY_OPERATORS[e.operator].evaluate(()=>this.evaluateExpression(e.left,t),()=>this.evaluateExpression(e.right,t));case Q(e,"MemberExpression"):{let n=await this.evaluateExpression(e.object,t);if(typeof n!="object"||n===null)throw new $("Cannot access property of a non-object.");let r=Q(e.property,"Identifier")?e.property.name:await this.evaluateExpression(e.property,t);if(typeof r=="number"){if(!Array.isArray(n))throw new $("Cannot access array index of a non-array.");if(r<0||r>=n.length)throw new $("Array index is out of bounds.");return n[r]}if(typeof r!="string")throw new $(`Property name must be a string, got ${d.describeType(r)}.`);if(!o.isPropertyAllowed(n,r))throw new $(`Property \`${r}\` does not exist or is not accessible.`);return n[r]}case Q(e,"CallExpression"):return (await this.getCallee(e.callee,t))(...await Promise.all(e.arguments.flatMap(r=>{let i=this.resolve(this.evaluateExpression(r,t));if(Q(r,"SpreadElement")){if(!Array.isArray(i))throw new $(`Spread argument must evaluate to an array, got ${d.describeType(i)}.`);return i}return [i]})));case Q(e,"ConditionalExpression"):return await this.evaluateExpression(e.test,t)?this.evaluateExpression(e.consequent,t):this.evaluateExpression(e.alternate,t);default:throw new $(`Unexpected expression type \`${e.type}\`.`)}}async getCallee(e,t){if(Q(e,"Identifier")){let n=t?.functions?.[e.name]??this.configuration.functions?.[e.name];if(n===void 0)throw new $(`Function \`${e.name}\` does not exist.`);return n}if(Q(e,"MemberExpression")){let n=await this.evaluateExpression(e.object,t),r=Q(e.property,"Identifier")?e.property.name:await this.evaluateExpression(e.property,t);if(typeof r!="string")throw new $(`Method name must be a string, got ${d.describeType(r)}.`);if(!o.isMethodAllowed(n,r))throw new $(`Method \`${r}\` does not exist or is not accessible.`);return n[r].bind(n)}throw new $("Callee is not callable.")}static isMethodAllowed(e,t){return typeof e=="string"?o.ALLOWED_STRING_METHODS.includes(t):Array.isArray(e)?o.ALLOWED_ARRAY_METHODS.includes(t):false}static isPropertyAllowed(e,t){return typeof e=="string"?o.ALLOWED_STRING_PROPERTIES.includes(t):Array.isArray(e)?o.ALLOWED_ARRAY_PROPERTIES.includes(t):typeof e=="object"&&e!==null&&Object.hasOwn(e,t)&&e[t]!==void 0}async resolve(e){if(!(e instanceof Promise)&&(typeof e!="object"||e===null))return e;let t=await e;if(Array.isArray(t))return Promise.all(t.map(n=>this.resolve(n)));if(typeof t=="object"&&t!==null){let n=Object.fromEntries(await Promise.all(Object.entries(t).flatMap(([r,i])=>i===void 0?[]:[[r,this.resolve(i)]])));return Object.isFrozen(t)?Object.freeze(n):Object.isSealed(t)&&Object.seal(n),n}return t}};function Q(o,e){return o.type===e}async function J(o){let e=await o();if(typeof e!="number")throw new $(`Number expected, got ${d.describeType(e)}.`);return e}async function fn(o){let e=await o();if(typeof e!="boolean")throw new $(`Boolean expected, got ${d.describeType(e)}.`);return e}var $t=z.strictObject({description:z.string(),required:z.boolean().optional()}),uu=z.union([z.string(),z.number(),z.boolean(),z.null()]),ui=z.lazy(()=>z.union([uu,z.array(ui),z.record(ui)])),mu=z.discriminatedUnion("type",[$t.extend({type:z.literal("reference"),default:z.string().optional()}),$t.extend({type:z.literal("string"),options:z.array(z.string()).optional(),default:z.string().optional()}),$t.extend({type:z.literal("number"),default:z.number().optional()}),$t.extend({type:z.literal("boolean"),default:z.boolean().optional()}),$t.extend({type:z.literal("array"),default:z.array(ui).optional()}),$t.extend({type:z.literal("object"),default:z.record(z.string(),ui).optional()})]),du=z.strictObject({$schema:z.string().optional(),title:z.string().min(1).optional(),description:z.string().optional(),options:z.record(z.string().min(1),mu).optional(),actions:z.array(z.any())}),yn=class extends B{constructor(){super(du);}};var mi=class o{constructor(e){this.resolving=[];this.config=e;}async execute(e,t){let{output:n}=t,r=n.notify("Loading template");try{await this.importTemplate(e,t);}finally{r.stop();}}async importTemplate(e,t){let{value:n,url:r}=await this.loadTemplate(e.template,t.baseUrl),i=await this.getInputValues(n,e.options);if(this.resolving.includes(r.href)){let s=[...this.resolving,r.href].map((p,c)=>` ${c+1}. ${p}`).join(`
|
|
1770
|
-
`);throw new
|
|
1770
|
+
`);throw new x(`Circular dependency detected while loading templates:
|
|
1771
1771
|
|
|
1772
|
-
${s}`,{reason:"invalid_input"})}this.resolving.push(r.toString());let a=new Rt({input:t.input,output:t.output,baseUrl:r});o.shareVariables(i.references,t,a);try{await this.run(n,i.values,a);}finally{this.resolving.pop();}o.shareVariables(i.references,a,t);}async getInputValues(e,t={}){let n={},r=[];for(let[i,a]of Object.entries(e.options??{})){let s=t[i];if(s===void 0&&a.required===true)throw new
|
|
1772
|
+
${s}`,{reason:"invalid_input"})}this.resolving.push(r.toString());let a=new Rt({input:t.input,output:t.output,baseUrl:r});o.shareVariables(i.references,t,a);try{await this.run(n,i.values,a);}finally{this.resolving.pop();}o.shareVariables(i.references,a,t);}async getInputValues(e,t={}){let n={},r=[];for(let[i,a]of Object.entries(e.options??{})){let s=t[i];if(s===void 0&&a.required===true)throw new x(`Missing required option \`${i}\`.`,{reason:"invalid_input"});let p=await(s??a.resolveDefault?.(this.config.variables));p!==void 0&&(a.type==="reference"?(o.checkOptionValue(i,p,{...a,type:"string"}),r.push(p)):o.checkOptionValue(i,p,a),n[i]=p);}return {values:n,references:r}}async run(e,t,n){let{runner:r,variables:i}=this.config,{output:a}=n;for(let{resolve:s}of e.actions){let p=a.notify("Resolving options"),c;try{c=await s(Nt.merge(i,{options:t,get this(){return n.getVariables()}}));}catch(l){throw x.fromCause(l,{message:"Unable to resolve action definition."})}finally{p.stop();}await r.execute({actions:[c]},n);}}async loadTemplate(e,t){let n=this.config.templateProvider,r=Tt(e,t);try{return await n.get(r)}catch(i){throw i instanceof $e?new d(`No template found at \`${r}\`.`,{cause:i,reason:"invalid_input",suggestions:["Check if the template path or URL is correct and try again."]}):i}}static checkOptionValue(e,t,n){switch(n.type){case "number":case "string":case "boolean":{if(typeof t!==n.type)throw new x(`Expected value of type ${n.type} for option \`${e}\`, but got ${d.describeType(t)}.`,{reason:"invalid_input"});if(n.type==="string"&&n.options!==void 0&&!n.options.includes(t))throw new x(`Invalid value for option \`${e}\`.`,{reason:"invalid_input",details:[`Allowed values: \`${n.options.join("`, `")}\`.`]});break}case "array":{if(!Array.isArray(t))throw new x(`Expected value of type ${n.type} for option \`${e}\`,but got ${d.describeType(t)}.`,{reason:"invalid_input"});break}case "object":{if(typeof t!="object"||t===null)throw new x(`Expected value of type ${n.type} for option \`${e}\`,but got ${d.describeType(t)}.`,{reason:"invalid_input"});break}}}static shareVariables(e,t,n){let r=t.getVariables();for(let i of e)r[i]!==void 0&&n.set(i,r[i]);}};var L=class{constructor(e){this.configuration=e;}async execute(e,t){let{action:n,validator:r}=this.configuration,i=await r.validate(e);if(!i.valid){let a=i.violations.map(s=>(s.path===""?s.message:`**${s.path}**: ${s.message}`).replace(/'/g,"`"));throw new x("Invalid action options.",{reason:"invalid_input",details:a})}await n.execute(i.data,t);}};var hn;(n=>{let o=Symbol("source");function e(r){return r[o]??null}n.get=e;function t(r,i){r[o]=i;}n.set=t;})(hn||={});var di=class o{constructor(e,t){this.cursor=0;this.chars=[...e],this.index=t.index,this.line=t.line,this.column=t.column;}static parse(e,t){return [...o.from(e,t)]}static from(e,t){return new o(o.getExpression(e),t??(e instanceof JsonPrimitiveNode?e.location.start:{index:0,line:1,column:1}))}static getExpression(e){return typeof e=="string"?e:e instanceof JsonPrimitiveNode?e.value:e.token.value}get position(){return {index:this.index,line:this.line,column:this.column}}done(){return this.cursor>=this.chars.length}[Symbol.iterator](){return this}next(){return {done:this.done(),value:this.consume()}}consume(){if(this.done())return this.createLiteralFragment("",this.position);let e=this.position,t=0,n=0,r=0,i="";for(;this.cursor<this.chars.length;){let a=this.chars[this.cursor],s=a==="$"&&this.chars[this.cursor+1]==="{";if(!(r+t+n>0)&&s&&i.length>0)return this.createLiteralFragment(i,e);if(this.cursor++,this.index++,a===`
|
|
1773
1773
|
`?(this.line++,this.column=1):this.column++,i+=a,t>0||n>0)a==="\\"?(i+=this.chars[this.cursor],this.cursor++,this.index++,this.column++):t>0&&a==="'"?t--:n>0&&a==='"'&&n--;else if(r>0){if(a==="'"?t++:a==='"'?n++:a==="{"?r++:a==="}"&&r--,r===0)return this.createExpressionFragment(i,e)}else s&&(i+=this.chars[this.cursor],r++,this.cursor++,this.index++,this.column++);}if(t>0||n>0)throw new d("Unbalanced quotes in template string.",{details:[`Location: line ${e.line}, column ${e.column}`]});if(r>0)throw new d("Unbalanced braces in template string.",{details:[`Location: line ${e.line}, column ${e.column}`]});return this.createLiteralFragment(i,e)}createLiteralFragment(e,t){return {type:"literal",source:e,location:{start:t,end:this.position}}}createExpressionFragment(e,t){return {type:"expression",source:e,expression:e.slice(2,-1).trim(),location:{start:t,end:this.position}}}};var re=class o extends Promise{#t;#n;#e;constructor(e,t=false){super(()=>{}),this.#t=e,this.#n=t;}static from(e){return new o(e)}static transient(e){return new o(e,true)}get promise(){if(this.#e!==void 0)return this.#e;let e=new Promise(t=>{t(this.#t());});return this.#n||(this.#e=e),e}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e)}};var we=class o extends W{constructor(e,{violations:t,...n}){super(e,n),this.violations=t,Object.setPrototypeOf(this,o.prototype);}},gi=class o{constructor({evaluator:e,validator:t,templateProvider:n,fileProvider:r}){this.loading=[];this.evaluator=e,this.validator=t,this.templateProvider=n,this.fileProvider=r;}async get(e){let{url:t,value:n}=await this.templateProvider.get(e),r;try{r=o.cleanJson(JsonParser$1.parse(n,JsonObjectNode$1));}catch(f){throw new we("Failed to parse the JSON template.",{reason:"invalid_input",url:t,cause:f,violations:[{path:"",message:d.formatMessage(f)}]})}let i=r.toJSON(),a=await this.validator.validate(i);if(!a.valid){let f=a.violations.map(b=>` \u2022 **${b.path}**: ${b.message}`).join(`
|
|
1774
1774
|
|
|
1775
1775
|
`);throw new we(`The template contains errors:
|
|
@@ -1777,12 +1777,12 @@ ${s}`,{reason:"invalid_input"})}this.resolving.push(r.toString());let a=new Rt({
|
|
|
1777
1777
|
${f}`,{reason:"invalid_input",url:t,violations:a.violations})}let{options:s,actions:p,...c}=a.data,l=r.get("actions",JsonArrayNode$1),m=this.parseOptions(r,s,t);return {url:t,value:{...c,...m!==void 0?{options:m}:{},actions:l.elements.map(f=>({resolve:b=>this.resolve(f,b,t)}))}}}parseOptions(e,t,n){if(t===void 0)return;let r=e.get("options",JsonObjectNode$1);return Object.fromEntries(Object.entries(t).map(([i,a])=>{if(a.default===void 0)return [i,a];let s=r.get(i,JsonObjectNode$1).get("default");return [i,{...a,resolveDefault:p=>this.resolve(s,p,n)}]}))}resolve(e,t,n,r=""){return e instanceof JsonArrayNode$1?e.elements.map((i,a)=>this.resolve(i,t,n,`${r}[${a}]`)):e instanceof JsonObjectNode$1?re.transient(async()=>{let i=Object.fromEntries(await Promise.all(e.properties.map(async a=>{let s=await this.interpolate(a.key,t,n,r);if(typeof s!="string"&&typeof s!="number"){let c=a.key.location.start;throw new we("Unexpected object key type.",{url:n,reason:"invalid_input",violations:[{path:r,message:`Expected object key to resolve to string or number at line ${c.line}, column ${c.column} but got ${d.describeType(s)}.`}]})}let p=r===""?`${s}`:`${r}.${s}`;return [s,re.transient(()=>this.resolve(a.value,t,n,p))]})));return hn.set(i,{url:n,start:e.location.start,end:e.location.end}),i}):e instanceof JsonPrimitiveNode&&typeof e.value=="string"?re.transient(()=>this.interpolate(e,t,n,r)):e.toJSON()}interpolate(e,t,n,r){let i=di.parse(e);if(i.length===1){let a=i[0];return a.type==="literal"?a.source:this.evaluate(o.createExpressionNode(a),t,n,r)}return Promise.all(i.map(async a=>{if(a.type==="literal")return a.source;let s=o.createExpressionNode(a),p=await this.evaluate(s,t,n,r);if(p!==null&&!["string","number","boolean"].includes(typeof p)){let c=e.location.start;throw new we("Unexpected expression result.",{reason:"invalid_input",url:n,violations:[{path:r,message:`Expected expression \`${a.expression}\` to resolve to null, string, number, or boolean value at line ${c.line}, column ${c.column}, but got ${d.describeType(p)}.`}]})}return `${p??""}`})).then(a=>a.join(""))}async evaluate(e,t,n,r){let i=(e instanceof JsonIdentifierNode?e.token.value:e.value).trim();try{return await this.evaluator.evaluate(i,{variables:t,functions:{import:(a,s)=>{if(typeof a!="string"){let p=e.location.start;throw new $("Invalid argument for function `import`.",{reason:"invalid_input",details:[`The \`url\` argument of the \`import\` function must be a string, but got ${d.describeType(a)} at line ${p.line}, column ${p.column}.`]})}if(s!==void 0&&(typeof s!="object"||s===null||Array.isArray(s))){let p=e.location.start;throw new $("Invalid argument for function `import`.",{reason:"invalid_input",details:[`The \`properties\` argument of the \`import\` function must be an object, but got ${d.describeType(a)} at line ${p.line}, column ${p.column}.`]})}return this.import(Tt(a,n),s===void 0?t:Nt.merge(t,{this:Promise.resolve(t.this).then(p=>typeof p=="object"&&p!==null&&!Array.isArray(p)?Nt.merge(p,s):s)}),n,r)}}})}catch(a){let s=e.location.start;throw new we("Failed to evaluate expression.",{reason:"invalid_input",url:n,cause:a,violations:[{path:r,message:`Evaluation of \`${i}\` at line ${s.line}, column ${s.column} failed because ${d.formatCause(a)}`}]})}}async import(e,t,n,r){if(e.protocol==="file:"&&n.protocol!=="file:")throw new we("Unsafe import URL.",{reason:"precondition",url:e,violations:[{path:r,message:"File URL is not allowed from remote sources for security reasons."}]});if(this.loading.includes(e.toString())){let p=[...this.loading,e.href].map((c,l)=>` ${l+1}. ${c}`).join(`
|
|
1778
1778
|
`);throw new we(`Circular dependency detected while loading templates:
|
|
1779
1779
|
|
|
1780
|
-
${p}`,{reason:"invalid_input",url:e,violations:[{path:r,message:"Imported template creates a circular dependency."}]})}let{url:i,value:a}=await this.fileProvider.get(e),s;try{s=o.cleanJson(JsonParser$1.parse(a));}catch(p){throw new we("Failed to parse referenced JSON.",{reason:"invalid_input",cause:p,url:i,violations:[{path:r,message:d.formatMessage(p)}]})}this.loading.push(i.toString());try{return this.resolve(s,t,i,r)}finally{this.loading.pop();}}static createExpressionNode(e){return new JsonPrimitiveNode({value:e.expression,location:e.location,token:new JsonTokenNode({type:JsonTokenType.STRING,value:e.source,location:e.location})})}static cleanJson(e){if(e instanceof JsonPrimitiveNode)return e;if(e instanceof JsonArrayNode$1){for(let t of e.elements)this.cleanJson(t);return e}if(e instanceof JsonObjectNode$1)for(let t of e.properties){let n=t.key.toJSON();n==="$schema"?e.delete(n):this.cleanJson(t.value);}return e}};var Ja=Symbol("any-property"),mc=Symbol("any-index"),bn=Symbol("passthrough"),zt=Symbol("resolve"),w=class o extends B{async validate(e){let t=this.findPassthroughPaths(this.schema),n;try{n=await this.resolveOptions(e,t);}catch(r){if(r instanceof we)return {valid:false,violations:r.violations};throw r}return super.validate(n).then(r=>(r.valid&&o.restoreSymbols(n,r.data),r))}async resolveOptions(e,t,n=[]){if(typeof e!="object"||e===null||o.isPassthroughPath(n,t))return e;if(e instanceof Promise)return this.resolveOptions(await e,t,n);if(Array.isArray(e)){let r=new Array(e.length),i=new Array(e.length);for(let[a,s]of e.entries()){let p=[...n,a];o.isPassthroughPath(p,t)?i[a]=s:r[a]=this.resolveOptions(await s,t,p);}for(let[a,s]of (await Promise.all(r)).entries())s!==void 0&&(i[a]=s);return i}return {...e,...Object.fromEntries(await Promise.all(Object.entries(e).map(async([r,i])=>{let a=[...n,r];return o.isPassthroughPath(a,t)?[r,i]:[r,await this.resolveOptions(await i,t,a)]})))}}static isPassthroughPath(e,t){for(let n of t)if(n.length===e.length+1)for(let[r,i]of n.entries()){let a=typeof e[r]=="number"?mc:Ja;if(r<e.length?i!==e[r]&&i!==a:i!==zt&&i!==bn)break;if(r===n.length-1)return i===bn}return false}findPassthroughPaths(e,t=[]){if(e instanceof ZodPromise)return [[...t,bn]];if(e instanceof ZodOptional)return this.findPassthroughPaths(e.unwrap(),t);if(e instanceof ZodTuple)return [[...t,zt],...e.items.flatMap((n,r)=>this.findPassthroughPaths(n,[...t,r]))];if(e instanceof ZodArray)return [[...t,zt],...this.findPassthroughPaths(e.element,[...t,mc])];if(e instanceof ZodRecord)return [[...t,zt],...this.findPassthroughPaths(e.valueSchema,[...t,Ja])];if(e instanceof ZodObject){let n=[[...t,zt],...Object.entries(e.shape).flatMap(([r,i])=>this.findPassthroughPaths(i,[...t,r]))];return e._def.unknownKeys==="passthrough"&&n.push([...t,Ja,bn]),n}if(e instanceof ZodEffects){let n=e.innerType();return n instanceof ZodAny?[[...t,bn]]:this.findPassthroughPaths(n,t)}return e instanceof ZodPipeline?this.findPassthroughPaths(e._def.out,t):e instanceof ZodUnion||e instanceof ZodDiscriminatedUnion?e.options.flatMap(n=>this.findPassthroughPaths(n,t)):[[...t,zt]]}static restoreSymbols(e,t){if(Array.isArray(e)&&Array.isArray(t)){for(let[n,r]of e.entries())n<t.length&&o.restoreSymbols(r,t[n]);return}if(!(!uc(e)||!uc(t))){for(let n of Object.getOwnPropertySymbols(e))Object.assign(t,{[n]:e[n]});for(let[n,r]of Object.entries(e))n in t&&o.restoreSymbols(r,t[n]);}}};var Eu=z.strictObject({action:z.instanceof(Promise),else:z.instanceof(Promise).optional(),finally:z.instanceof(Promise).optional(),help:z.strictObject({message:z.string().min(1).optional(),links:z.array(z.strictObject({url:z.string().url(),label:z.string().min(1)})).optional(),suggestions:z.array(z.string().min(1)).optional()}).optional()}),fi=class extends w{constructor(){super(Eu);}};var Ru=z.strictObject({name:z.string().min(1),version:z.string().min(1).optional(),optional:z.boolean().optional()}),Tu=z.strictObject({dependencies:z.array(Ru),help:z.strictObject({message:z.string().min(1).optional(),links:z.array(z.strictObject({url:z.string().url(),label:z.string().min(1)})).optional(),suggestions:z.array(z.string().min(1)).optional()}).optional(),result:z.record(z.string().min(1)).optional()}),yi=class extends w{constructor(){super(Tu);}};var Ou=z.strictObject({source:z.string().min(1),filter:z.string().min(1).optional(),destination:z.string().min(1),result:z.strictObject({destination:z.string().min(1).optional()}).optional()}),hi=class extends w{constructor(){super(Ou);}};var Du=z.strictObject({dependencies:z.array(z.string().min(1)).min(1),development:z.boolean().optional()}),bi=class extends w{constructor(){super(Du);}};var Mu=z.strictObject({pattern:z.string().min(1),caseSensitive:z.boolean().optional()}),dc=z.union([Mu,z.strictObject({type:z.enum(["and","or"]),matchers:z.array(z.lazy(()=>dc)).min(1)})]),Nu=z.strictObject({path:z.string().min(1),matcher:dc.optional(),limit:z.number().int().positive().optional(),depth:z.number().int().nonnegative().optional(),result:z.string().optional()}),Ii=class extends w{constructor(){super(Nu);}};var $u=z.strictObject({files:z.array(z.strictObject({path:z.string(),replacements:z.array(z.strictObject({pattern:z.string().refine(o=>{try{return new RegExp(o),!0}catch{return {message:"Invalid regular expression pattern"}}}),caseSensitive:z.boolean().optional(),value:z.union([z.string(),z.number()])})).min(1)})).min(1)}),xi=class extends w{constructor(){super($u);}};var zu=z.strictObject({slots:z.array(z.string().min(1)).min(1),example:z.boolean().optional()}),wi=class extends w{constructor(){super(zu);}};var _u=z.strictObject({components:z.array(z.string().min(1)).min(1)}),Pi=class extends w{constructor(){super(_u);}};var Lu=z.strictObject({name:z.string().min(1),criteria:z.string().min(1)}),dt=z.strictObject({title:z.string().optional(),description:z.string().optional()}),Fu=dt.extend({type:z.literal("boolean"),label:z.strictObject({true:z.string(),false:z.string()}).optional(),default:z.boolean().optional()}),ju=z.strictObject({label:z.string().optional(),description:z.string().optional(),default:z.boolean().optional(),position:z.number().optional()}),Wu=dt.extend({type:z.literal("text"),minimumLength:z.number().optional(),maximumLength:z.number().optional(),format:z.string().optional(),pattern:z.string().optional(),choices:z.record(ju).optional()}),Vu=dt.extend({type:z.literal("number"),integer:z.boolean().optional(),minimum:z.number().optional(),maximum:z.number().optional()}),Uu=z.lazy(()=>z.strictObject({type:z.lazy(()=>Sc),label:z.string().optional(),description:z.string().optional(),optional:z.boolean().optional(),private:z.boolean().optional(),position:z.number().optional()})),Ya=dt.extend({type:z.literal("structure"),attributes:z.record(z.string(),Uu)}),qu=dt.extend({type:z.literal("list"),items:z.lazy(()=>Sc),itemLabel:z.string().optional(),minimumLength:z.number().optional(),maximumLength:z.number().optional()}),Hu=z.union([z.string(),z.number(),z.boolean(),z.null()]),Ba=z.lazy(()=>z.union([Hu,z.array(Ba),z.record(Ba)])),yc=dt.extend({type:z.literal("reference"),id:z.string(),properties:z.record(z.string(),Ba).optional()}),hc=dt.extend({type:z.literal("union"),types:z.record(z.string(),z.discriminatedUnion("type",[Ya,yc]))}),Sc=z.discriminatedUnion("type",[Fu,Wu,Vu,Ya,qu,hc,yc]),Gu=z.discriminatedUnion("type",[Ya,hc]),Ku=z.strictObject({name:z.string().min(1),description:z.string().min(1).optional(),definition:Gu}),Zu=z.union([z.strictObject({type:z.literal("static"),value:z.string()}),z.strictObject({type:z.literal("dynamic"),expression:z.string(),nullable:z.literal(false),default:z.string()}),z.strictObject({type:z.literal("dynamic"),expression:z.string(),nullable:z.literal(true),default:z.string().optional()})]),Ju=z.union([z.strictObject({type:z.literal("static"),value:z.number()}),z.strictObject({type:z.literal("dynamic"),nullable:z.literal(false),default:z.number(),expression:z.string()}),z.strictObject({type:z.literal("dynamic"),nullable:z.literal(true),default:z.number().optional(),expression:z.string()})]),Qu=z.union([z.strictObject({type:z.literal("static"),value:z.boolean()}),z.strictObject({type:z.literal("dynamic"),nullable:z.literal(false),default:z.boolean(),expression:z.string()}),z.strictObject({type:z.literal("dynamic"),nullable:z.literal(true),default:z.boolean().optional(),expression:z.string()})]),Bu=z.strictObject({type:z.literal("text"),value:Zu}),Yu=z.strictObject({type:z.literal("number"),value:Ju}),Xu=z.strictObject({type:z.literal("boolean"),value:Qu}),bc=z.strictObject({type:z.literal("structure"),name:z.string().optional(),attributes:z.record(z.string(),z.lazy(()=>Ic))}),em=z.strictObject({type:z.literal("list"),items:z.array(z.lazy(()=>Ic))}),Ic=z.discriminatedUnion("type",[Bu,Yu,Xu,bc,em]),Xa=z.record(z.string(),bc),tm=z.strictObject({name:z.string().min(1),component:z.string().min(1),content:Xa}),xc=z.record(z.string(),Xa),nm=z.strictObject({audiences:z.array(z.string()),content:xc}),vc=z.strictObject({default:xc,segmented:z.array(nm)}),rm=z.strictObject({name:z.string(),content:vc,baseline:z.boolean().optional(),allocation:z.number().min(0).max(1)}),im=z.strictObject({name:z.string(),draft:z.boolean().optional(),audiences:z.array(z.string()),slots:z.array(z.string()),experiment:z.strictObject({name:z.string(),goalId:z.string().optional(),crossDevice:z.boolean().optional(),traffic:z.number().min(0).max(1),variants:z.array(rm),content:Xa}).optional(),content:vc}),om=z.record(z.string().min(1),z.string().min(1)),gc=z.record(z.number().nonnegative(),z.string().min(1)),fc=z.record(z.string().min(1),z.strictObject({id:z.string().min(1).optional(),version:z.string().min(1).optional()})),am=z.strictObject({resources:z.strictObject({audiences:z.record(z.string().min(1),Lu).optional(),components:z.record(z.string().min(1),Ku).optional(),slots:z.record(z.string().min(1),tm).optional(),experiences:z.array(im).optional()}),result:z.strictObject({audiences:om.optional(),components:fc.optional(),slots:fc.optional(),experiences:gc.optional(),experiments:gc.optional()}).optional()}),Ci=class extends w{constructor(){super(am);}};var sm=z.union([z.string(),z.number(),z.boolean(),z.null()]),es=z.lazy(()=>z.union([sm,z.array(es),z.record(es)])),pm=z.strictObject({template:z.string().min(1),options:z.record(z.string().min(1),es).optional()}),ki=class extends w{constructor(){super(pm);}};var Ai=class{constructor({formatter:e}){this.formatter=e;}async execute(e,t){let{output:n}=t,r=n.notify("Formatting code");try{await this.formatter.format(e.files);}catch(i){throw I.fromCause(i)}finally{r.stop();}}};var cm=z.strictObject({files:z.array(z.string().min(1)).min(1)}),Ei=class extends w{constructor(){super(cm);}};var Lt=class{constructor(e){this.discriminator=e.discriminator,this.mapping=e.mapping;}async get(){let e=await this.discriminator(),t=this.mapping[e];if(t===void 0)throw new U(`No value found for discriminator "${String(e)}".`,{reason:"not_supported"});return t instanceof Function?t():t.get()}};var Ri=class{constructor(e){this.runner=e;}execute(e,t){return e.condition?this.run(e.then,t):e.else!==void 0?this.run(e.else,t):Promise.resolve()}run(e,t){return this.runner.execute({actions:e},t)}};var lm=z.strictObject({condition:z.boolean(),then:z.instanceof(Promise),else:z.instanceof(Promise).optional()}),Oi=class extends w{constructor(){super(lm);}};var Di=class{execute(e,t){let n=t.output,r=e.semantic??"neutral";return e.title===void 0?n.log(e.message,r):n.announce({semantics:r,title:e.title,message:e.message}),Promise.resolve()}};var um=z.strictObject({semantic:z.enum(["neutral","info","error","warning","success"]).optional(),title:z.string().optional(),message:z.string()}),Ni=class extends w{constructor(){super(um);}};var $i=class{execute(e){let{message:t,...n}=e;throw new I(t,{...n,reason:"precondition"})}};var mm=z.strictObject({title:z.string().min(1).optional(),message:z.string().min(1),links:z.array(z.strictObject({label:z.string().min(1),url:z.string().url()})).optional(),suggestions:z.array(z.string().min(1)).optional(),details:z.array(z.string().min(1)).optional()}),zi=class extends w{constructor(){super(mm);}};var _i=class{constructor({url:e,provider:t}){this.url=e,this.provider=t;}get(){return this.provider.get(this.url)}};var In=class{constructor(e){this.data=e;}get(){return Promise.resolve(this.data)}};var Li=class{constructor({packageManager:e,parsers:t,factory:n}){this.packageManager=e,this.parsers=t,this.factory=n;}async get(){let e=await this.packageManager.getScripts();for(let[t,n]of Object.entries(e))for(let r of this.parsers){let i=r.parse(n);if(i!==null)return this.factory.create({...i,command:await this.packageManager.getScriptCommand(t)})}throw new U("No server found.")}};var Fi=class{parse(e){if(!e.includes("next dev"))return null;let t=e.match(/(?:-p|--port)\s*(\d+)/),n=e.match(/(?:-H|--hostname)\s*(\S+)/),r=t!==null?Number.parseInt(t[1],10):null,i=n!==null?n[1]:"localhost";return {protocol:e.includes("-https")?"https":"http",host:i,...r!==null?{port:r}:{},defaultPort:3e3}}};var ji=class{parse(e){if(!e.includes("vite"))return null;let t=e.match(/--port\s*(\d+)/),n=e.match(/--host\s*(\S+)/),r=t!==null?Number.parseInt(t[1],10):null;return {protocol:"http",host:n!==null?n[1]:"localhost",...r!==null?{port:r}:{},defaultPort:5173}}};var Wi=class{parse(e){if(!e.includes("parcel"))return null;let t=e.match(/(?:-p|--port)\s*(\d+)/),n=e.match(/--host\s*(\S+)/),r=t!==null?Number.parseInt(t[1],10):null,i=n!==null?n[1]:"localhost";return {protocol:e.includes("--https")?"https":"http",host:i,...r!==null?{port:r}:{},defaultPort:1234}}};var Vi=class{parse(e){if(!e.includes("react-scripts start"))return null;let t=e.match(/PORT=(\d+)/),n=e.match(/HOST=(\S+)/),r=e.match(/HTTPS=(\S+)/),i=t!==null?Number.parseInt(t[1],10):null,a=n!==null?n[1]:"localhost";return {protocol:r!==null&&r[1]==="true"?"https":"http",host:a,...i!==null?{port:i}:{},defaultPort:5173}}};var Ui=class{async execute(e,t){let{input:n}=t,r=n===void 0?this.getDefaultValue(e):await this.prompt(e,n);if(r===void 0)throw new I("Action requires user input.",{reason:"precondition",suggestions:["Retry in interactive mode"]});e.result!==void 0&&t.set(e.result,r);}getDefaultValue(e){switch(e.type){case "confirmation":return e.default;case "choice":return e.default;case "multi-choice":{let t=e.options.flatMap(n=>n.selected===true?[n.value]:[]);return t.length===0?void 0:t}case "text":return e.default;default:return}}prompt(e,t){switch(e.type){case "confirmation":return t.confirm(e);case "choice":return t.select(e);case "multi-choice":return t.selectMultiple(e);case "text":{let{required:n=false,...r}=e;return t.prompt({...r,validate:i=>n&&i===""?"This value is required.":true})}case "keypress":return t.wait(e)}}};var xn=z.strictObject({result:z.string().optional()}),dm=xn.extend({type:z.literal("confirmation"),message:z.string(),default:z.boolean().optional()}),ns=z.string(),gm=z.preprocess(o=>typeof o=="string"?{value:o,label:o}:o,z.strictObject({value:ns,label:z.string().min(1).optional(),disabled:z.boolean().optional()})).transform(o=>({...o,label:o.label??o.value.toString()})),fm=xn.extend({type:z.literal("choice"),message:z.string(),options:z.array(gm),default:ns.optional()}),ym=z.preprocess(o=>typeof o=="string"?{value:o,label:o}:o,z.strictObject({value:ns,label:z.string().min(1).optional(),selected:z.boolean().optional(),disabled:z.boolean().optional()})).transform(o=>({...o,label:o.label??o.value.toString()})),hm=xn.extend({type:z.literal("multi-choice"),message:z.string(),min:z.number().optional(),max:z.number().optional(),options:z.array(ym)}),Sm=xn.extend({type:z.literal("text"),message:z.string(),default:z.string().optional(),required:z.boolean().optional()}),bm=xn.extend({type:z.literal("keypress"),message:z.string(),key:z.union([z.literal("enter"),z.literal("space"),z.string().length(1)]).optional()}),Im=z.discriminatedUnion("type",[dm,fm,hm,Sm,bm]),qi=class extends w{constructor(){super(Im);}};var Hi=class{constructor({serverProvider:e}){this.provider=e;}async execute(e,t){let{output:n}=t,r=n.notify("Checking server"),i;try{i=await this.startServer(r);}finally{r.stop();}e.result?.url!==void 0&&t.set(e.result.url,i.url.toString()),e.result?.owned!==void 0&&t.set(e.result.owned,i.owned);}async startServer(e){let t=await this.provider.get();if(t===null)throw new d("No server detected.");let n=await t.getStatus();return n.running?{url:n.url,owned:false}:(e.update("Starting server"),{url:await t.start(),owned:true})}};var xm=z.strictObject({result:z.strictObject({url:z.string().optional(),owned:z.string().optional()}).optional()}),Ki=class extends w{constructor(){super(xm);}};var Zi=class{constructor(e){this.actions=e;}async execute(e,t){for(let n of Array.isArray(e.actions)?e.actions:[e.actions])try{await this.run(n,t);}catch(r){throw I.fromCause(r,{tracing:[{name:n.name,source:hn.get(n)??void 0}]})}}run({name:e,...t},n){let r=this.actions[e];if(r===void 0)throw new I(`Unsupported action \`${e}\`.`,{reason:"invalid_input"});return r.execute(t,n)}};var wc=z.object({name:z.string().min(1)}).passthrough(),vm=z.strictObject({actions:z.union([wc,z.array(wc)])}),Ji=class extends w{constructor(){super(vm);}};var Qi=class{async execute(e,t){let{output:n}=t;await n.open(e.url);}};var wm=z.strictObject({url:z.string().url()}),Bi=class extends w{constructor(){super(wm);}};var Pm=z.union([z.string(),z.number(),z.boolean(),z.null()]),rs=z.lazy(()=>z.union([Pm,z.array(rs),z.record(rs)])),Cm=z.strictObject({variables:z.record(z.string(),rs)}),Yi=class extends w{constructor(){super(Cm);}};var Xi=class{execute(e,t){for(let[n,r]of Object.entries(e.variables))t.set(n,r);return Promise.resolve()}};var eo=class{constructor({serverProvider:e}){this.provider=e;}async execute(e,t){let{output:n}=t,r=n.notify("Stopping server"),i=await this.provider.get();if(i===null)throw new d("No server detected.");try{await i.stop();}finally{r.stop();}}};var Am=z.strictObject({}),to=class extends w{constructor(){super(Am);}};var Ft=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var no=class{constructor(e){this.configuration=e;}async getStatus(){let e=await this.findAddress();return e===null?{running:false}:{running:true,url:e}}async start(){let{commandExecutor:e,command:t,workingDirectory:n,processObserver:r}=this.configuration;try{this.execution=e.run(t,{workingDirectory:n.get()});}catch(s){throw new Ft("Failed to start server.",{cause:s})}let i=()=>this.stop();if(this.execution.onExit(()=>{this.execution=void 0,r.off("exit",i);}),!this.execution.running)throw new Ft("Failed to start server.");r.on("exit",i);let a=await this.waitStart();if(a===null)throw new Ft("Server is unreachable.");return a}async stop(){await this?.execution?.kill("SIGINT"),this.execution=void 0;}async waitStart(){let{startupCheckDelay:e,startupTimeout:t}=this.configuration,n=new AbortController;setTimeout(()=>n.abort(),t).unref();let i=()=>new Promise(a=>{setTimeout(a,e);});do{let a=await this.findAddress(n);if(a!==null)return a;await i();}while(!n.signal.aborted);return null}async findAddress(e){let{lookupTimeout:t,lookupMaxPorts:n,server:{protocol:r,host:i,port:a,defaultPort:s}}=this.configuration,p=a??s,c=a??s+n-1,l=new AbortController;e!==void 0&&e.signal.addEventListener("abort",()=>l.abort()),setTimeout(()=>l.abort(),t).unref();let f=new URL(`${r}://${i}`);for(let b=p;b<=c;b++){try{return f.port=b.toString(),await fetch(f,{method:"HEAD",signal:l.signal}),f}catch{}if(l.signal.aborted)break}return null}};var ro=class{constructor(e){this.configuration=e;}create(e){return new no({...this.configuration,command:e.command,server:{protocol:e.protocol,host:e.host,defaultPort:e.defaultPort,port:e.port}})}};var Em=z.strictObject({path:z.string()}),io=class extends w{constructor(){super(Em);}};var oo=class{constructor({fileSystem:e,rootDirectory:t,currentDirectory:n}){this.fileSystem=e,this.rootDirectory=t,this.currentDirectory=n;}execute(e){let t=this.fileSystem.isAbsolutePath(e.path)?e.path:this.fileSystem.joinPaths(this.currentDirectory.get(),e.path);if(!this.fileSystem.isSubPath(this.rootDirectory,t))throw new I("Cannot change to a directory outside the current working directory.",{reason:"precondition",details:[`Working directory: ${this.rootDirectory}`,`Target directory: ${t}`]});return this.currentDirectory.setCurrentDirectory(t),Promise.resolve()}};var ao=class{constructor(){this.lines=[[]];this.cursor={row:0,column:0};this.ansiSequence="";this.lines=[[]];}buffer(e){for(let t=0;t<e.length;t++){let n=e[t];if(n==="\\x1b"){this.ansiSequence="\\x1b";continue}if(this.ansiSequence.length>0){this.ansiSequence+=n,/[A-Za-z]/.test(n)&&(this.processAnsiSequence(this.ansiSequence),this.ansiSequence="");continue}if(n==="\r"){this.cursor.column=0;continue}if(n===`
|
|
1780
|
+
${p}`,{reason:"invalid_input",url:e,violations:[{path:r,message:"Imported template creates a circular dependency."}]})}let{url:i,value:a}=await this.fileProvider.get(e),s;try{s=o.cleanJson(JsonParser$1.parse(a));}catch(p){throw new we("Failed to parse referenced JSON.",{reason:"invalid_input",cause:p,url:i,violations:[{path:r,message:d.formatMessage(p)}]})}this.loading.push(i.toString());try{return this.resolve(s,t,i,r)}finally{this.loading.pop();}}static createExpressionNode(e){return new JsonPrimitiveNode({value:e.expression,location:e.location,token:new JsonTokenNode({type:JsonTokenType.STRING,value:e.source,location:e.location})})}static cleanJson(e){if(e instanceof JsonPrimitiveNode)return e;if(e instanceof JsonArrayNode$1){for(let t of e.elements)this.cleanJson(t);return e}if(e instanceof JsonObjectNode$1)for(let t of e.properties){let n=t.key.toJSON();n==="$schema"?e.delete(n):this.cleanJson(t.value);}return e}};var Ja=Symbol("any-property"),mc=Symbol("any-index"),bn=Symbol("passthrough"),zt=Symbol("resolve"),w=class o extends B{async validate(e){let t=this.findPassthroughPaths(this.schema),n;try{n=await this.resolveOptions(e,t);}catch(r){if(r instanceof we)return {valid:false,violations:r.violations};throw r}return super.validate(n).then(r=>(r.valid&&o.restoreSymbols(n,r.data),r))}async resolveOptions(e,t,n=[]){if(typeof e!="object"||e===null||o.isPassthroughPath(n,t))return e;if(e instanceof Promise)return this.resolveOptions(await e,t,n);if(Array.isArray(e)){let r=new Array(e.length),i=new Array(e.length);for(let[a,s]of e.entries()){let p=[...n,a];o.isPassthroughPath(p,t)?i[a]=s:r[a]=this.resolveOptions(await s,t,p);}for(let[a,s]of (await Promise.all(r)).entries())s!==void 0&&(i[a]=s);return i}return {...e,...Object.fromEntries(await Promise.all(Object.entries(e).map(async([r,i])=>{let a=[...n,r];return o.isPassthroughPath(a,t)?[r,i]:[r,await this.resolveOptions(await i,t,a)]})))}}static isPassthroughPath(e,t){for(let n of t)if(n.length===e.length+1)for(let[r,i]of n.entries()){let a=typeof e[r]=="number"?mc:Ja;if(r<e.length?i!==e[r]&&i!==a:i!==zt&&i!==bn)break;if(r===n.length-1)return i===bn}return false}findPassthroughPaths(e,t=[]){if(e instanceof ZodPromise)return [[...t,bn]];if(e instanceof ZodOptional)return this.findPassthroughPaths(e.unwrap(),t);if(e instanceof ZodTuple)return [[...t,zt],...e.items.flatMap((n,r)=>this.findPassthroughPaths(n,[...t,r]))];if(e instanceof ZodArray)return [[...t,zt],...this.findPassthroughPaths(e.element,[...t,mc])];if(e instanceof ZodRecord)return [[...t,zt],...this.findPassthroughPaths(e.valueSchema,[...t,Ja])];if(e instanceof ZodObject){let n=[[...t,zt],...Object.entries(e.shape).flatMap(([r,i])=>this.findPassthroughPaths(i,[...t,r]))];return e._def.unknownKeys==="passthrough"&&n.push([...t,Ja,bn]),n}if(e instanceof ZodEffects){let n=e.innerType();return n instanceof ZodAny?[[...t,bn]]:this.findPassthroughPaths(n,t)}return e instanceof ZodPipeline?this.findPassthroughPaths(e._def.out,t):e instanceof ZodUnion||e instanceof ZodDiscriminatedUnion?e.options.flatMap(n=>this.findPassthroughPaths(n,t)):[[...t,zt]]}static restoreSymbols(e,t){if(Array.isArray(e)&&Array.isArray(t)){for(let[n,r]of e.entries())n<t.length&&o.restoreSymbols(r,t[n]);return}if(!(!uc(e)||!uc(t))){for(let n of Object.getOwnPropertySymbols(e))Object.assign(t,{[n]:e[n]});for(let[n,r]of Object.entries(e))n in t&&o.restoreSymbols(r,t[n]);}}};var Eu=z.strictObject({action:z.instanceof(Promise),else:z.instanceof(Promise).optional(),finally:z.instanceof(Promise).optional(),help:z.strictObject({message:z.string().min(1).optional(),links:z.array(z.strictObject({url:z.string().url(),label:z.string().min(1)})).optional(),suggestions:z.array(z.string().min(1)).optional()}).optional()}),fi=class extends w{constructor(){super(Eu);}};var Ru=z.strictObject({name:z.string().min(1),version:z.string().min(1).optional(),optional:z.boolean().optional()}),Tu=z.strictObject({dependencies:z.array(Ru),help:z.strictObject({message:z.string().min(1).optional(),links:z.array(z.strictObject({url:z.string().url(),label:z.string().min(1)})).optional(),suggestions:z.array(z.string().min(1)).optional()}).optional(),result:z.record(z.string().min(1)).optional()}),yi=class extends w{constructor(){super(Tu);}};var Ou=z.strictObject({source:z.string().min(1),filter:z.string().min(1).optional(),destination:z.string().min(1),result:z.strictObject({destination:z.string().min(1).optional()}).optional()}),hi=class extends w{constructor(){super(Ou);}};var Du=z.strictObject({dependencies:z.array(z.string().min(1)).min(1),development:z.boolean().optional()}),bi=class extends w{constructor(){super(Du);}};var Mu=z.strictObject({pattern:z.string().min(1),caseSensitive:z.boolean().optional()}),dc=z.union([Mu,z.strictObject({type:z.enum(["and","or"]),matchers:z.array(z.lazy(()=>dc)).min(1)})]),Nu=z.strictObject({path:z.string().min(1),matcher:dc.optional(),limit:z.number().int().positive().optional(),depth:z.number().int().nonnegative().optional(),result:z.string().optional()}),Ii=class extends w{constructor(){super(Nu);}};var $u=z.strictObject({files:z.array(z.strictObject({path:z.string(),replacements:z.array(z.strictObject({pattern:z.string().refine(o=>{try{return new RegExp(o),!0}catch{return {message:"Invalid regular expression pattern"}}}),caseSensitive:z.boolean().optional(),value:z.union([z.string(),z.number()])})).min(1)})).min(1)}),xi=class extends w{constructor(){super($u);}};var zu=z.strictObject({slots:z.array(z.string().min(1)).min(1),example:z.boolean().optional()}),wi=class extends w{constructor(){super(zu);}};var _u=z.strictObject({components:z.array(z.string().min(1)).min(1)}),Pi=class extends w{constructor(){super(_u);}};var Lu=z.strictObject({name:z.string().min(1),criteria:z.string().min(1)}),dt=z.strictObject({title:z.string().optional(),description:z.string().optional()}),Fu=dt.extend({type:z.literal("boolean"),label:z.strictObject({true:z.string(),false:z.string()}).optional(),default:z.boolean().optional()}),ju=z.strictObject({label:z.string().optional(),description:z.string().optional(),default:z.boolean().optional(),position:z.number().optional()}),Wu=dt.extend({type:z.literal("text"),minimumLength:z.number().optional(),maximumLength:z.number().optional(),format:z.string().optional(),pattern:z.string().optional(),choices:z.record(ju).optional()}),Vu=dt.extend({type:z.literal("number"),integer:z.boolean().optional(),minimum:z.number().optional(),maximum:z.number().optional()}),Uu=z.lazy(()=>z.strictObject({type:z.lazy(()=>Sc),label:z.string().optional(),description:z.string().optional(),optional:z.boolean().optional(),private:z.boolean().optional(),position:z.number().optional()})),Ya=dt.extend({type:z.literal("structure"),attributes:z.record(z.string(),Uu)}),qu=dt.extend({type:z.literal("list"),items:z.lazy(()=>Sc),itemLabel:z.string().optional(),minimumLength:z.number().optional(),maximumLength:z.number().optional()}),Hu=z.union([z.string(),z.number(),z.boolean(),z.null()]),Ba=z.lazy(()=>z.union([Hu,z.array(Ba),z.record(Ba)])),yc=dt.extend({type:z.literal("reference"),id:z.string(),properties:z.record(z.string(),Ba).optional()}),hc=dt.extend({type:z.literal("union"),types:z.record(z.string(),z.discriminatedUnion("type",[Ya,yc]))}),Sc=z.discriminatedUnion("type",[Fu,Wu,Vu,Ya,qu,hc,yc]),Gu=z.discriminatedUnion("type",[Ya,hc]),Ku=z.strictObject({name:z.string().min(1),description:z.string().min(1).optional(),definition:Gu}),Zu=z.union([z.strictObject({type:z.literal("static"),value:z.string()}),z.strictObject({type:z.literal("dynamic"),expression:z.string(),nullable:z.literal(false),default:z.string()}),z.strictObject({type:z.literal("dynamic"),expression:z.string(),nullable:z.literal(true),default:z.string().optional()})]),Ju=z.union([z.strictObject({type:z.literal("static"),value:z.number()}),z.strictObject({type:z.literal("dynamic"),nullable:z.literal(false),default:z.number(),expression:z.string()}),z.strictObject({type:z.literal("dynamic"),nullable:z.literal(true),default:z.number().optional(),expression:z.string()})]),Qu=z.union([z.strictObject({type:z.literal("static"),value:z.boolean()}),z.strictObject({type:z.literal("dynamic"),nullable:z.literal(false),default:z.boolean(),expression:z.string()}),z.strictObject({type:z.literal("dynamic"),nullable:z.literal(true),default:z.boolean().optional(),expression:z.string()})]),Bu=z.strictObject({type:z.literal("text"),value:Zu}),Yu=z.strictObject({type:z.literal("number"),value:Ju}),Xu=z.strictObject({type:z.literal("boolean"),value:Qu}),bc=z.strictObject({type:z.literal("structure"),name:z.string().optional(),attributes:z.record(z.string(),z.lazy(()=>Ic))}),em=z.strictObject({type:z.literal("list"),items:z.array(z.lazy(()=>Ic))}),Ic=z.discriminatedUnion("type",[Bu,Yu,Xu,bc,em]),Xa=z.record(z.string(),bc),tm=z.strictObject({name:z.string().min(1),component:z.string().min(1),content:Xa}),xc=z.record(z.string(),Xa),nm=z.strictObject({audiences:z.array(z.string()),content:xc}),vc=z.strictObject({default:xc,segmented:z.array(nm)}),rm=z.strictObject({name:z.string(),content:vc,baseline:z.boolean().optional(),allocation:z.number().min(0).max(1)}),im=z.strictObject({name:z.string(),draft:z.boolean().optional(),audiences:z.array(z.string()),slots:z.array(z.string()),experiment:z.strictObject({name:z.string(),goalId:z.string().optional(),crossDevice:z.boolean().optional(),traffic:z.number().min(0).max(1),variants:z.array(rm),content:Xa}).optional(),content:vc}),om=z.record(z.string().min(1),z.string().min(1)),gc=z.record(z.number().nonnegative(),z.string().min(1)),fc=z.record(z.string().min(1),z.strictObject({id:z.string().min(1).optional(),version:z.string().min(1).optional()})),am=z.strictObject({resources:z.strictObject({audiences:z.record(z.string().min(1),Lu).optional(),components:z.record(z.string().min(1),Ku).optional(),slots:z.record(z.string().min(1),tm).optional(),experiences:z.array(im).optional()}),result:z.strictObject({audiences:om.optional(),components:fc.optional(),slots:fc.optional(),experiences:gc.optional(),experiments:gc.optional()}).optional()}),Ci=class extends w{constructor(){super(am);}};var sm=z.union([z.string(),z.number(),z.boolean(),z.null()]),es=z.lazy(()=>z.union([sm,z.array(es),z.record(es)])),pm=z.strictObject({template:z.string().min(1),options:z.record(z.string().min(1),es).optional()}),ki=class extends w{constructor(){super(pm);}};var Ai=class{constructor({formatter:e}){this.formatter=e;}async execute(e,t){let{output:n}=t,r=n.notify("Formatting code");try{await this.formatter.format(e.files);}catch(i){throw x.fromCause(i)}finally{r.stop();}}};var cm=z.strictObject({files:z.array(z.string().min(1)).min(1)}),Ei=class extends w{constructor(){super(cm);}};var Lt=class{constructor(e){this.discriminator=e.discriminator,this.mapping=e.mapping;}async get(){let e=await this.discriminator(),t=this.mapping[e];if(t===void 0)throw new U(`No value found for discriminator "${String(e)}".`,{reason:"not_supported"});return t instanceof Function?t():t.get()}};var Ri=class{constructor(e){this.runner=e;}execute(e,t){return e.condition?this.run(e.then,t):e.else!==void 0?this.run(e.else,t):Promise.resolve()}run(e,t){return this.runner.execute({actions:e},t)}};var lm=z.strictObject({condition:z.boolean(),then:z.instanceof(Promise),else:z.instanceof(Promise).optional()}),Oi=class extends w{constructor(){super(lm);}};var Di=class{execute(e,t){let n=t.output,r=e.semantic??"neutral";return e.title===void 0?n.log(e.message,r):n.announce({semantics:r,title:e.title,message:e.message}),Promise.resolve()}};var um=z.strictObject({semantic:z.enum(["neutral","info","error","warning","success"]).optional(),title:z.string().optional(),message:z.string()}),Ni=class extends w{constructor(){super(um);}};var $i=class{execute(e){let{message:t,...n}=e;throw new x(t,{...n,reason:"precondition"})}};var mm=z.strictObject({title:z.string().min(1).optional(),message:z.string().min(1),links:z.array(z.strictObject({label:z.string().min(1),url:z.string().url()})).optional(),suggestions:z.array(z.string().min(1)).optional(),details:z.array(z.string().min(1)).optional()}),zi=class extends w{constructor(){super(mm);}};var _i=class{constructor({url:e,provider:t}){this.url=e,this.provider=t;}get(){return this.provider.get(this.url)}};var In=class{constructor(e){this.data=e;}get(){return Promise.resolve(this.data)}};var Li=class{constructor({packageManager:e,parsers:t,factory:n}){this.packageManager=e,this.parsers=t,this.factory=n;}async get(){let e=await this.packageManager.getScripts();for(let[t,n]of Object.entries(e))for(let r of this.parsers){let i=r.parse(n);if(i!==null)return this.factory.create({...i,command:await this.packageManager.getScriptCommand(t)})}throw new U("No server found.")}};var Fi=class{parse(e){if(!e.includes("next dev"))return null;let t=e.match(/(?:-p|--port)\s*(\d+)/),n=e.match(/(?:-H|--hostname)\s*(\S+)/),r=t!==null?Number.parseInt(t[1],10):null,i=n!==null?n[1]:"localhost";return {protocol:e.includes("-https")?"https":"http",host:i,...r!==null?{port:r}:{},defaultPort:3e3}}};var ji=class{parse(e){if(!e.includes("vite"))return null;let t=e.match(/--port\s*(\d+)/),n=e.match(/--host\s*(\S+)/),r=t!==null?Number.parseInt(t[1],10):null;return {protocol:"http",host:n!==null?n[1]:"localhost",...r!==null?{port:r}:{},defaultPort:5173}}};var Wi=class{parse(e){if(!e.includes("parcel"))return null;let t=e.match(/(?:-p|--port)\s*(\d+)/),n=e.match(/--host\s*(\S+)/),r=t!==null?Number.parseInt(t[1],10):null,i=n!==null?n[1]:"localhost";return {protocol:e.includes("--https")?"https":"http",host:i,...r!==null?{port:r}:{},defaultPort:1234}}};var Vi=class{parse(e){if(!e.includes("react-scripts start"))return null;let t=e.match(/PORT=(\d+)/),n=e.match(/HOST=(\S+)/),r=e.match(/HTTPS=(\S+)/),i=t!==null?Number.parseInt(t[1],10):null,a=n!==null?n[1]:"localhost";return {protocol:r!==null&&r[1]==="true"?"https":"http",host:a,...i!==null?{port:i}:{},defaultPort:5173}}};var Ui=class{async execute(e,t){let{input:n}=t,r=n===void 0?this.getDefaultValue(e):await this.prompt(e,n);if(r===void 0)throw new x("Action requires user input.",{reason:"precondition",suggestions:["Retry in interactive mode"]});e.result!==void 0&&t.set(e.result,r);}getDefaultValue(e){switch(e.type){case "confirmation":return e.default;case "choice":return e.default;case "multi-choice":{let t=e.options.flatMap(n=>n.selected===true?[n.value]:[]);return t.length===0?void 0:t}case "text":return e.default;default:return}}prompt(e,t){switch(e.type){case "confirmation":return t.confirm(e);case "choice":return t.select(e);case "multi-choice":return t.selectMultiple(e);case "text":{let{required:n=false,...r}=e;return t.prompt({...r,validate:i=>n&&i===""?"This value is required.":true})}case "keypress":return t.wait(e)}}};var xn=z.strictObject({result:z.string().optional()}),dm=xn.extend({type:z.literal("confirmation"),message:z.string(),default:z.boolean().optional()}),ns=z.string(),gm=z.preprocess(o=>typeof o=="string"?{value:o,label:o}:o,z.strictObject({value:ns,label:z.string().min(1).optional(),disabled:z.boolean().optional()})).transform(o=>({...o,label:o.label??o.value.toString()})),fm=xn.extend({type:z.literal("choice"),message:z.string(),options:z.array(gm),default:ns.optional()}),ym=z.preprocess(o=>typeof o=="string"?{value:o,label:o}:o,z.strictObject({value:ns,label:z.string().min(1).optional(),selected:z.boolean().optional(),disabled:z.boolean().optional()})).transform(o=>({...o,label:o.label??o.value.toString()})),hm=xn.extend({type:z.literal("multi-choice"),message:z.string(),min:z.number().optional(),max:z.number().optional(),options:z.array(ym)}),Sm=xn.extend({type:z.literal("text"),message:z.string(),default:z.string().optional(),required:z.boolean().optional()}),bm=xn.extend({type:z.literal("keypress"),message:z.string(),key:z.union([z.literal("enter"),z.literal("space"),z.string().length(1)]).optional()}),Im=z.discriminatedUnion("type",[dm,fm,hm,Sm,bm]),qi=class extends w{constructor(){super(Im);}};var Hi=class{constructor({serverProvider:e}){this.provider=e;}async execute(e,t){let{output:n}=t,r=n.notify("Checking server"),i;try{i=await this.startServer(r);}finally{r.stop();}e.result?.url!==void 0&&t.set(e.result.url,i.url.toString()),e.result?.owned!==void 0&&t.set(e.result.owned,i.owned);}async startServer(e){let t=await this.provider.get();if(t===null)throw new d("No server detected.");let n=await t.getStatus();return n.running?{url:n.url,owned:false}:(e.update("Starting server"),{url:await t.start(),owned:true})}};var xm=z.strictObject({result:z.strictObject({url:z.string().optional(),owned:z.string().optional()}).optional()}),Ki=class extends w{constructor(){super(xm);}};var Zi=class{constructor(e){this.actions=e;}async execute(e,t){for(let n of Array.isArray(e.actions)?e.actions:[e.actions])try{await this.run(n,t);}catch(r){throw x.fromCause(r,{tracing:[{name:n.name,source:hn.get(n)??void 0}]})}}run({name:e,...t},n){let r=this.actions[e];if(r===void 0)throw new x(`Unsupported action \`${e}\`.`,{reason:"invalid_input"});return r.execute(t,n)}};var wc=z.object({name:z.string().min(1)}).passthrough(),vm=z.strictObject({actions:z.union([wc,z.array(wc)])}),Ji=class extends w{constructor(){super(vm);}};var Qi=class{async execute(e,t){let{output:n}=t;await n.open(e.url);}};var wm=z.strictObject({url:z.string().url()}),Bi=class extends w{constructor(){super(wm);}};var Pm=z.union([z.string(),z.number(),z.boolean(),z.null()]),rs=z.lazy(()=>z.union([Pm,z.array(rs),z.record(rs)])),Cm=z.strictObject({variables:z.record(z.string(),rs)}),Yi=class extends w{constructor(){super(Cm);}};var Xi=class{execute(e,t){for(let[n,r]of Object.entries(e.variables))t.set(n,r);return Promise.resolve()}};var eo=class{constructor({serverProvider:e}){this.provider=e;}async execute(e,t){let{output:n}=t,r=n.notify("Stopping server"),i=await this.provider.get();if(i===null)throw new d("No server detected.");try{await i.stop();}finally{r.stop();}}};var Am=z.strictObject({}),to=class extends w{constructor(){super(Am);}};var Ft=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var no=class{constructor(e){this.configuration=e;}async getStatus(){let e=await this.findAddress();return e===null?{running:false}:{running:true,url:e}}async start(){let{commandExecutor:e,command:t,workingDirectory:n,processObserver:r}=this.configuration;try{this.execution=e.run(t,{workingDirectory:n.get()});}catch(s){throw new Ft("Failed to start server.",{cause:s})}let i=()=>this.stop();if(this.execution.onExit(()=>{this.execution=void 0,r.off("exit",i);}),!this.execution.running)throw new Ft("Failed to start server.");r.on("exit",i);let a=await this.waitStart();if(a===null)throw new Ft("Server is unreachable.");return a}async stop(){await this?.execution?.kill("SIGINT"),this.execution=void 0;}async waitStart(){let{startupCheckDelay:e,startupTimeout:t}=this.configuration,n=new AbortController;setTimeout(()=>n.abort(),t).unref();let i=()=>new Promise(a=>{setTimeout(a,e);});do{let a=await this.findAddress(n);if(a!==null)return a;await i();}while(!n.signal.aborted);return null}async findAddress(e){let{lookupTimeout:t,lookupMaxPorts:n,server:{protocol:r,host:i,port:a,defaultPort:s}}=this.configuration,p=a??s,c=a??s+n-1,l=new AbortController;e!==void 0&&e.signal.addEventListener("abort",()=>l.abort()),setTimeout(()=>l.abort(),t).unref();let f=new URL(`${r}://${i}`);for(let b=p;b<=c;b++){try{return f.port=b.toString(),await fetch(f,{method:"HEAD",signal:l.signal}),f}catch{}if(l.signal.aborted)break}return null}};var ro=class{constructor(e){this.configuration=e;}create(e){return new no({...this.configuration,command:e.command,server:{protocol:e.protocol,host:e.host,defaultPort:e.defaultPort,port:e.port}})}};var Em=z.strictObject({path:z.string()}),io=class extends w{constructor(){super(Em);}};var oo=class{constructor({fileSystem:e,rootDirectory:t,currentDirectory:n}){this.fileSystem=e,this.rootDirectory=t,this.currentDirectory=n;}execute(e){let t=this.fileSystem.isAbsolutePath(e.path)?e.path:this.fileSystem.joinPaths(this.currentDirectory.get(),e.path);if(!this.fileSystem.isSubPath(this.rootDirectory,t))throw new x("Cannot change to a directory outside the current working directory.",{reason:"precondition",details:[`Working directory: ${this.rootDirectory}`,`Target directory: ${t}`]});return this.currentDirectory.setCurrentDirectory(t),Promise.resolve()}};var ao=class{constructor(){this.lines=[[]];this.cursor={row:0,column:0};this.ansiSequence="";this.lines=[[]];}buffer(e){for(let t=0;t<e.length;t++){let n=e[t];if(n==="\\x1b"){this.ansiSequence="\\x1b";continue}if(this.ansiSequence.length>0){this.ansiSequence+=n,/[A-Za-z]/.test(n)&&(this.processAnsiSequence(this.ansiSequence),this.ansiSequence="");continue}if(n==="\r"){this.cursor.column=0;continue}if(n===`
|
|
1781
1781
|
`){this.cursor.row++,this.cursor.column=0,this.resize(this.cursor.row);continue}for(this.resize(this.cursor.row);this.lines[this.cursor.row].length<this.cursor.column;)this.lines[this.cursor.row].push(" ");this.lines[this.cursor.row][this.cursor.column]=n,this.cursor.column++;}}processAnsiSequence(e){let t=e.match(/^\\x1b\[(\d*;?\d*)?([A-Za-z])$/);if(t===null)return;let[,n,r]=t,i=n?.split(";").map(a=>a===""?0:Number.parseInt(a,10))??[];switch(r){case "A":this.cursor.row=Math.max(0,this.cursor.row-(i[0]??1));break;case "B":this.cursor.row+=i[0]??1,this.resize(this.cursor.row);break;case "C":this.cursor.column+=i[0]??1;break;case "D":this.cursor.column=Math.max(0,this.cursor.column-(i[0]??1));break;case "K":i[0]===2?this.lines[this.cursor.row]=[]:i[0]===0&&(this.lines[this.cursor.row]=this.lines[this.cursor.row].slice(0,this.cursor.column));break;case "J":i[0]===2?(this.lines=[[]],this.cursor={row:0,column:0}):i[0]===0&&(this.lines=this.lines.slice(0,this.cursor.row+1),this.lines[this.cursor.row]=this.lines[this.cursor.row].slice(0,this.cursor.column));break;default:this.resize(this.cursor.row),this.lines[this.cursor.row].push(e);break}}resize(e){for(;this.lines.length<=e;)this.lines.push([]);}toString(){return this.lines.map(e=>e.join("")).join(`
|
|
1782
1782
|
`).trim()}toRawString(){return Rm(this.toString())}};var so=class o{static{this.INPUT_MAP={"[space]":" ","[enter]":`
|
|
1783
|
-
`,"[down]":"\x1B[A","[up]":"\x1B[B","[left]":"\x1B[C","[right]":"\x1B[D","[backspace]":"\b"};}constructor(e){this.configuration=e;}async execute(e,t){let{input:n,output:r}=t,{sourceChecker:i}=this.configuration,s=await(await this.getPackageManager(e.runner)).getPackageCommand(e.package,e.arguments),p=[s.name.split(/[\\/]/).pop(),...s.arguments??[]].join(" ");if(!await i.test(t.baseUrl)){if(n===void 0)throw new
|
|
1783
|
+
`,"[down]":"\x1B[A","[up]":"\x1B[B","[left]":"\x1B[C","[right]":"\x1B[D","[backspace]":"\b"};}constructor(e){this.configuration=e;}async execute(e,t){let{input:n,output:r}=t,{sourceChecker:i}=this.configuration,s=await(await this.getPackageManager(e.runner)).getPackageCommand(e.package,e.arguments),p=[s.name.split(/[\\/]/).pop(),...s.arguments??[]].join(" ");if(!await i.test(t.baseUrl)){if(n===void 0)throw new x("Action requires explicit user confirmation.",{reason:"precondition",details:["Retry in interactive mode."]});if(r.warn(`This template will run the command \`${p}\``),!await n.confirm({message:"Continue?",default:true}))throw new x("Permission to run command denied.",{reason:"precondition",details:[`Command: ${p}`]})}let c=r.notify(`Running \`${p}\``);try{await this.executeCommand(s,e.interactions);}catch(l){throw x.fromCause(l)}finally{c.stop();}}getPackageManager(e){return e===void 0?this.configuration.packageManager:this.configuration.packageManagerProvider.get(e)}async executeCommand(e,t=[]){let{workingDirectory:n,commandExecutor:r,commandTimeout:i}=this.configuration,a=r.run(e,{workingDirectory:n.get(),timeout:i}),s=[...t];s.length===0&&await a.endWriting();let p=new ao;for await(let m of a.output){p.buffer(m);for(let[f,b]of s.entries()){let A=p.toRawString();if(b.pattern===true?new RegExp(b.when).test(A):A.includes(b.when)){b.always!==true&&s.splice(f,1);for(let y of b.then??[])await a.write(o.INPUT_MAP[y]??y);b.final===true&&(await a.endWriting(),s.length=0);break}}}let c=-1,l;try{c=await a.wait();}catch(m){l=m;}if(c!==0)throw new x(`Command failed with output:
|
|
1784
1784
|
|
|
1785
|
-
${p.toString()}`,{reason:"unexpected_result",cause:l})}};var Tm=z.strictObject({package:z.string(),arguments:z.array(z.string()).optional(),runner:z.string().optional(),interactions:z.array(z.object({when:z.string(),pattern:z.boolean().optional(),always:z.boolean().optional(),then:z.array(z.string()).min(1).optional(),final:z.boolean().optional()}).superRefine((o,e)=>{if(o.then===void 0&&o.final===void 0&&e.addIssue({code:z.ZodIssueCode.custom,message:"Either `then` or `final` must be defined"}),o.final===true&&o.always===true&&e.addIssue({code:z.ZodIssueCode.custom,path:["always"],message:"Final interactions must have `always` set to `false`"}),o.pattern===true)try{new RegExp(o.when);}catch{e.addIssue({code:z.ZodIssueCode.custom,path:["pattern"],message:"The `when` field must be a valid regular expression"});}})).min(1).optional().refine(o=>o===void 0||o.some(e=>e.final===true),{message:"At least one interaction must have `final` set to `true`"})}),po=class extends w{constructor(){super(Tm);}};var Se=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var Xe=class{constructor(e){this.projectDirectory=e.projectDirectory,this.fileSystem=e.fileSystem,this.agent=e.agent,this.packageValidator=e.packageValidator;}isInstalled(){return this.agent.isInstalled()}isProject(){return this.fileSystem.exists(this.getProjectManifestPath())}addDependencies(e,t){return this.agent.addDependencies(e,t)}installDependencies(){return this.agent.installDependencies()}getPackageCommand(e,t=[]){return this.agent.getPackageCommand(e,t)}getScriptCommand(e,t=[]){return this.agent.getScriptCommand(e,t)}async hasDirectDependency(e,t){let n=await this.readManifest(this.getProjectManifestPath());if(n===null)return false;let r=n.dependencies?.[e]??n.devDependencies?.[e];return r===void 0?false:t===void 0||kc.satisfies(r,t)}async hasDependency(e,t){let n=await this.getDependency(e);return n===null?false:t===void 0||n.version!==null&&kc.satisfies(n.version,t)}async getDependency(e){let t=this.getPackageManifestPath(e),n=await this.readManifest(t);return n===null?null:{name:n.name,version:n.version??null,directory:this.fileSystem.getDirectoryName(t),metadata:n}}async getScripts(){let e=await this.readManifest(this.getProjectManifestPath());return e===null?{}:e.scripts??{}}async addScript(e,t){let n=this.getProjectManifestPath();if(!await this.fileSystem.exists(n))throw new Se("Package file not found in the project.",{reason:"precondition",details:[`File: ${n}`]});let r=await this.fileSystem.readTextFile(n),i=JsonParser$1.parse(r,JsonObjectNode$1);if(i.has("scripts")){let a=i.get("scripts",JsonObjectNode$1),s=t;if(a.has(e)){let c=a.get(e).toJSON();if(typeof c=="string"&&c.includes(t))return;s=`${c} && ${t}`;}a.set(e,s);}else i.set("scripts",{[e]:t});await this.fileSystem.writeTextFile(n,i.toString(),{overwrite:true});}getPackageManifestPath(e){return this.fileSystem.joinPaths(this.projectDirectory.get(),"node_modules",e,"package.json")}getProjectManifestPath(){return this.fileSystem.joinPaths(this.projectDirectory.get(),"package.json")}async readManifest(e){if(!await this.fileSystem.exists(e))return null;let t;try{t=JSON.parse(await this.fileSystem.readTextFile(e));}catch{return null}let n=await this.packageValidator.validate(t);return n.valid?n.data:null}};var ze=class{constructor(e){this.projectDirectory=e.projectDirectory,this.commandRunner=e.commandExecutor,this.executableLocator=e.executableLocator;}isInstalled(){return this.installed===void 0&&(this.installed=this.getExecutable(this.getCommandName()).then(e=>e!==null)),this.installed}addDependencies(e,t=false){return this.run(this.createAddDependencyCommand(e,t))}installDependencies(){return this.run(this.createInstallDependenciesCommand())}getPackageCommand(e,t){return this.createPackageCommand(e,t)}getScriptCommand(e,t){return this.createScriptCommand(e,t)}async run(e,t={}){if(!await this.isInstalled())throw new Se(`Package manager \`${this.getCommandName()}\` is not installed.`);if(await this.commandRunner.run(e,{...t,workingDirectory:this.projectDirectory.get()}).wait()!==0)throw new Se(`Failed to run \`${e.name}\` command.`)}getExecutable(e){return this.executableLocator.locate(e)}};var co=class extends ze{getCommandName(){return "npm"}createPackageCommand(e,t=[]){return Promise.resolve(this.getCommand("npx",["--yes",e,...t]))}createScriptCommand(e,t=[]){return Promise.resolve(this.getCommand(this.getCommandName(),["run",e,...t.length>0?["--",...t]:[]]))}createAddDependencyCommand(e,t){return this.getCommand(this.getCommandName(),["install",...t?["--save-dev"]:[],...e])}createInstallDependenciesCommand(){return this.getCommand(this.getCommandName(),["install"])}getCommand(e,t=[]){return {name:e,arguments:t}}};var lo=class extends ze{getCommandName(){return "yarn"}createPackageCommand(e,t=[]){return Promise.resolve(this.getCommand("npx",["--yes",e,...t]))}createScriptCommand(e,t=[]){return Promise.resolve(this.getCommand(this.getCommandName(),["run",e,...t]))}createAddDependencyCommand(e,t){return this.getCommand(this.getCommandName(),["add",...t?["--dev"]:[],...e])}createInstallDependenciesCommand(){return this.getCommand(this.getCommandName(),["install"])}getCommand(e,t=[]){return {name:e,arguments:t}}};var uo=class extends ze{getCommandName(){return "bun"}createPackageCommand(e,t=[]){return Promise.resolve(this.getCommand(["x",e,...t]))}createScriptCommand(e,t=[]){return Promise.resolve(this.getCommand(["run",e,...t]))}createAddDependencyCommand(e,t){return this.getCommand(["install",...t?["--dev"]:[],...e])}createInstallDependenciesCommand(){return this.getCommand(["install"])}getCommand(e=[]){return {name:this.getCommandName(),arguments:e}}};var mo=class extends ze{getCommandName(){return "pnpm"}createPackageCommand(e,t=[]){return Promise.resolve(this.getCommand(["dlx",e,...t]))}createScriptCommand(e,t=[]){return Promise.resolve(this.getCommand(["run",e,...t]))}createAddDependencyCommand(e,t){return this.getCommand(["install",...t?["--save-dev"]:[],...e])}createInstallDependenciesCommand(){return this.getCommand(["install"])}getCommand(e=[]){return {name:this.getCommandName(),arguments:e}}};var go=class o{constructor({fileSystem:e,tsconfigValidator:t}){this.fileSystem=e,this.tsConfigValidator=t;}async load(e,t={}){let{fileNames:n=["tsconfig.json","jsconfig.json"]}=t,r=await this.fileSystem.getRealPath(e),i=await this.locateConfig(e,n,true);if(i===null)return null;let a=await this.resolveConfig({rootDirectory:r,configPath:i,fileNames:n,targetDirectories:(t.sourcePaths??[]).map(s=>this.fileSystem.isAbsolutePath(s)?s:this.fileSystem.joinPaths(r,s))});return a===null?null:{rootConfigPath:a.rootConfigPath,matchedConfigPath:a.matchedConfigPath,baseUrl:this.fileSystem.joinPaths(this.fileSystem.getDirectoryName(a.matchedConfigPath),a.compilerOptions?.baseUrl??"."),paths:a.compilerOptions?.paths??{}}}async locateConfig(e,t,n=false){for(let i of t){let a=this.fileSystem.joinPaths(e,i);if(await this.fileSystem.exists(a))return a}if(!n)return null;let r=this.fileSystem.getDirectoryName(e);return r===e?null:this.locateConfig(r,t)}async resolveConfig(e){let{configPath:t,fileNames:n,rootDirectory:r,targetDirectories:i}=e,a=await this.parseConfig(t);if(a?.extends!==void 0){let s=await this.locateParentConfig(r,this.fileSystem.getDirectoryName(t),a.extends);if(s!==null){let p=await this.resolveConfig({...e,configPath:s});p!==null&&(a=o.mergeConfig(a,p));}}if(a?.references!==void 0&&i.length>0){let{references:s,...p}=a;for(let c of a.references){let l=this.fileSystem.joinPaths(this.fileSystem.getDirectoryName(t),c.path),m=l.endsWith(".json")?l:await this.locateConfig(l,n);if(m===null)continue;let f=await this.resolveConfig({...e,configPath:m});if(f?.include!==void 0)for(let b of i){let A=this.fileSystem.joinPaths("./",this.fileSystem.getRelativePath(this.fileSystem.getDirectoryName(m),b));for(let v of f.include){let y=new Minimatch(v,{partial:true,magicalBraces:true});if(!y.hasMagic()&&!v.includes(".")&&(y=new Minimatch(`${v.replace(/\/?$/,"")}/**/*`,{partial:true})),y.match(A))return o.mergeConfig({...f,rootConfigPath:a.rootConfigPath},p)}}}}return a}async locateParentConfig(e,t,n){let r=n;r.endsWith(".json")||(r+=".json");let i=this.fileSystem.joinPaths(t,r);if(await this.fileSystem.exists(i))return i;let a=this.fileSystem.joinPaths(e,"node_modules",r);return await this.fileSystem.exists(a)?a:null}async parseConfig(e){let t;try{t=JsonParser$1.parse(await this.fileSystem.readTextFile(e)).toJSON();}catch{return null}let n=await this.tsConfigValidator.validate(t);return n.valid?{rootConfigPath:e,matchedConfigPath:e,...n.data}:null}static mergeConfig(e,t){return {...t,...e,compilerOptions:{...t.compilerOptions,...e.compilerOptions}}}};var fo=class{constructor({projectDirectory:e,fileSystem:t,tsConfigLoader:n}){this.projectDirectory=e,this.fileSystem=t,this.tsConfigLoader=n;}async getImportPath(e,t){let n=this.projectDirectory.get(),r=await this.tsConfigLoader.load(n,{sourcePaths:[this.fileSystem.joinPaths(n,t)]}),i=/\.m(?:js|ts)?$/.test(e)?e:e.replace(/\.(ts|js)x?$/,""),a=this.fileSystem.joinPaths(n,i);if(r!==null){let p=0,c=null;for(let[l,m]of Object.entries(r.paths)){let f=this.fileSystem.normalizeSeparators(l.replace(/\*$/,""));for(let b of m){let A=b.replace(/\*$/,""),v=this.fileSystem.joinPaths(r.baseUrl,A);if(a.startsWith(v)){let y=A.length;if(y>p){p=y;let M=a.slice(v.length).replace(/^[\\/]+/,"");c=f+M;}}}}if(c!==null)return Promise.resolve(c.replace(/\\+/g,"/"))}let s=this.fileSystem.getRelativePath(this.fileSystem.joinPaths(n,t),this.fileSystem.joinPaths(n,i));return Promise.resolve(s.replace(/\\/g,"/"))}};var Mm=z.object({extends:z.string().optional(),references:z.array(z.object({path:z.string()})).optional(),include:z.array(z.string()).optional(),compilerOptions:z.object({baseUrl:z.string().optional(),paths:z.record(z.array(z.string())).optional()}).optional()}),yo=class extends B{constructor(){super(Mm);}};var wn=class{constructor(e){this.provider=e;}get manager(){return Promise.resolve(this.provider.get()).catch(e=>{throw e instanceof U?new Se(e.message,e.help):e})}async isInstalled(){return (await this.manager).isInstalled()}async isProject(){return (await this.manager).isProject()}async hasDependency(e,t){return (await this.manager).hasDependency(e,t)}async hasDirectDependency(e,t){return (await this.manager).hasDirectDependency(e,t)}async getDependency(e){return (await this.manager).getDependency(e)}async addDependencies(e,t){return (await this.manager).addDependencies(e,t)}async installDependencies(){return (await this.manager).installDependencies()}async getScripts(){return (await this.manager).getScripts()}async addScript(e,t){return (await this.manager).addScript(e,t)}async getScriptCommand(e,t){return (await this.manager).getScriptCommand(e,t)}async getPackageCommand(e,t){return (await this.manager).getPackageCommand(e,t)}};var ho=class{constructor(e){this.map=e;}supports(e){return this.map.has(e)}get(e){let t=this.map.get(e);if(t===void 0)throw new U(`No value found for key \`${e}\`.`,{reason:"not_found"});return Promise.resolve(t)}};var So=class{isInstalled(){return Promise.resolve(false)}addDependencies(){return this.fail()}installDependencies(){return this.fail()}getPackageCommand(){return this.fail()}getScriptCommand(){return this.fail()}fail(){throw new Se("The package manager is not installed")}};var jt=class{constructor(e,t){this.provider=e,this.fallback=t;}async get(...e){let t=await this.provider.get(...e)??null;return t!==null?t:this.fallback.get(...e)}};var Oe=class{constructor(e){this.callback=e;}get(...e){return this.callback(...e)}};var Wt=class{constructor(e){this.candidates=e.candidates;}async get(...e){for(let{condition:t,value:n}of this.candidates)try{if(await t.test(...e))return typeof n=="object"&&n!==null&&"get"in n?n.get(...e):n}catch{}return null}};var Pn=class{constructor({fileSystem:e,files:t}){this.fileSystem=e,this.files=t;}async test(){return (await Promise.all(this.files.map(t=>this.fileSystem.exists(t)))).some(t=>t)}};var Cn=class{constructor({packageManager:e,dependencies:t}){this.packageManager=e,this.dependencies=t;}async test(){return (await Promise.all(this.dependencies.map(t=>this.packageManager.hasDirectDependency(t)))).some(t=>t)}};var bo=class{constructor({packageManager:e}){this.packageManager=e;}test(){return this.packageManager.isProject()}};var et=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var Io=class{constructor(){this.open=true;this.queue=[];}async*[Symbol.asyncIterator](){let e=await this.next();for(;e.done!==true;)yield e.value,e=await this.next();}next(){return this.queue.length>0?Promise.resolve({done:false,value:this.queue.shift()}):this.open?new Promise(e=>{this.resolve=()=>{this.resolve=void 0,this.queue.length===0?e({done:true,value:void 0}):e({done:false,value:this.queue.shift()});};}):Promise.resolve({done:true,value:void 0})}push(e){this.queue.push(e),this.resolve?.();}close(){this.open=false,this.resolve?.();}};var xo=class{constructor({currentDirectory:e}={}){this.currentDirectory=e;}run(e,t={}){let n=t.timeout!==void 0?AbortSignal.timeout(t.timeout):void 0,r=spawn(e.name,e.arguments,{stdio:["pipe","pipe","pipe"],cwd:t?.workingDirectory??this.currentDirectory?.get(),signal:n}),i=[];r.on("error",c=>{for(let l of i)l(n?.aborted===true?new et("Command timed out.",{reason:"precondition",cause:c}):new et("Failed to run command.",{cause:c}));});let a=new Io;r.stdout.on("data",c=>{a.push(c.toString());}),r.stderr.on("data",c=>{a.push(c.toString());});let s=null,p=[];return r.on("exit",c=>{a.close(),s=c??1;for(let l of p)l(s);}),{output:a,get running(){return s===null},onExit:c=>(p.push(c),()=>{let l=p.indexOf(c);l!==-1&&p.splice(l,1);}),write:c=>new Promise((l,m)=>{r.stdin.write(c,f=>{f===null?l():m(f);});}),endWriting:()=>new Promise(c=>{if(s!==null){c();return}r.stdin.end(c);}),read:async()=>{let c="";for await(let l of a)c+=l;return c},wait:()=>new Promise((c,l)=>{if(s!==null){c(s);return}i.push(l),r.on("exit",m=>{c(m??1);});}),kill:c=>new Promise((l,m)=>{if(s!==null){l();return}r.stdout.destroy(),r.stderr.destroy(),r.stdin.destroy(),r.kill(c)?(l(),s=1):m(new et("Failed to kill the subprocess."));})}}runSync(e,t={}){let n=t.timeout!==void 0?AbortSignal.timeout(t.timeout):void 0,r=spawnSync(e.name,e.arguments,{stdio:["ignore","pipe","pipe"],cwd:t?.workingDirectory??this.currentDirectory?.get(),signal:n});if(r.error!==void 0){let{error:s}=r;throw n?.aborted===true?new et("Command timed out.",{reason:"precondition",cause:s}):new et("Failed to run command.",{cause:s})}let i=r.stdout.toString(),a=r.stderr.toString();return i!==""&&a!==""&&(i=`${i}
|
|
1785
|
+
${p.toString()}`,{reason:"unexpected_result",cause:l})}};var Tm=z.strictObject({package:z.string(),arguments:z.array(z.string()).optional(),runner:z.string().optional(),interactions:z.array(z.object({when:z.string(),pattern:z.boolean().optional(),always:z.boolean().optional(),then:z.array(z.string()).min(1).optional(),final:z.boolean().optional()}).superRefine((o,e)=>{if(o.then===void 0&&o.final===void 0&&e.addIssue({code:z.ZodIssueCode.custom,message:"Either `then` or `final` must be defined"}),o.final===true&&o.always===true&&e.addIssue({code:z.ZodIssueCode.custom,path:["always"],message:"Final interactions must have `always` set to `false`"}),o.pattern===true)try{new RegExp(o.when);}catch{e.addIssue({code:z.ZodIssueCode.custom,path:["pattern"],message:"The `when` field must be a valid regular expression"});}})).min(1).optional().refine(o=>o===void 0||o.some(e=>e.final===true),{message:"At least one interaction must have `final` set to `true`"})}),po=class extends w{constructor(){super(Tm);}};var Se=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var Xe=class{constructor(e){this.projectDirectory=e.projectDirectory,this.fileSystem=e.fileSystem,this.agent=e.agent,this.packageValidator=e.packageValidator;}isInstalled(){return this.agent.isInstalled()}isProject(){return this.fileSystem.exists(this.getProjectManifestPath())}addDependencies(e,t){return this.agent.addDependencies(e,t)}installDependencies(){return this.agent.installDependencies()}getPackageCommand(e,t=[]){return this.agent.getPackageCommand(e,t)}getScriptCommand(e,t=[]){return this.agent.getScriptCommand(e,t)}async hasDirectDependency(e,t){let n=await this.readManifest(this.getProjectManifestPath());if(n===null)return false;let r=n.dependencies?.[e]??n.devDependencies?.[e];return r===void 0?false:t===void 0||kc.satisfies(r,t)}async hasDependency(e,t){let n=await this.getDependency(e);return n===null?false:t===void 0||n.version!==null&&kc.satisfies(n.version,t)}async getDependency(e){let t=this.getPackageManifestPath(e),n=await this.readManifest(t);return n===null?null:{name:n.name,version:n.version??null,directory:this.fileSystem.getDirectoryName(t),metadata:n}}async getScripts(){let e=await this.readManifest(this.getProjectManifestPath());return e===null?{}:e.scripts??{}}async addScript(e,t){let n=this.getProjectManifestPath();if(!await this.fileSystem.exists(n))throw new Se("Package file not found in the project.",{reason:"precondition",details:[`File: ${n}`]});let r=await this.fileSystem.readTextFile(n),i=JsonParser$1.parse(r,JsonObjectNode$1);if(i.has("scripts")){let a=i.get("scripts",JsonObjectNode$1),s=t;if(a.has(e)){let c=a.get(e).toJSON();if(typeof c=="string"&&c.includes(t))return;s=`${c} && ${t}`;}a.set(e,s);}else i.set("scripts",{[e]:t});await this.fileSystem.writeTextFile(n,i.toString(),{overwrite:true});}getPackageManifestPath(e){return this.fileSystem.joinPaths(this.projectDirectory.get(),"node_modules",e,"package.json")}getProjectManifestPath(){return this.fileSystem.joinPaths(this.projectDirectory.get(),"package.json")}async readManifest(e){if(!await this.fileSystem.exists(e))return null;let t;try{t=JSON.parse(await this.fileSystem.readTextFile(e));}catch{return null}let n=await this.packageValidator.validate(t);return n.valid?n.data:null}};var ze=class{constructor(e){this.projectDirectory=e.projectDirectory,this.commandRunner=e.commandExecutor,this.executableLocator=e.executableLocator;}isInstalled(){return this.installed===void 0&&(this.installed=this.getExecutable(this.getCommandName()).then(e=>e!==null)),this.installed}addDependencies(e,t=false){return this.run(this.createAddDependencyCommand(e,t))}installDependencies(){return this.run(this.createInstallDependenciesCommand())}getPackageCommand(e,t){return this.createPackageCommand(e,t)}getScriptCommand(e,t){return this.createScriptCommand(e,t)}async run(e,t={}){if(!await this.isInstalled())throw new Se(`Package manager \`${this.getCommandName()}\` is not installed.`);if(await this.commandRunner.run(e,{...t,workingDirectory:this.projectDirectory.get()}).wait()!==0)throw new Se(`Failed to run \`${e.name}\` command.`)}getExecutable(e){return this.executableLocator.locate(e)}};var co=class extends ze{getCommandName(){return "npm"}createPackageCommand(e,t=[]){return Promise.resolve(this.getCommand("npx",["--yes",e,...t]))}createScriptCommand(e,t=[]){return Promise.resolve(this.getCommand(this.getCommandName(),["run",e,...t.length>0?["--",...t]:[]]))}createAddDependencyCommand(e,t){return this.getCommand(this.getCommandName(),["install",...t?["--save-dev"]:[],...e])}createInstallDependenciesCommand(){return this.getCommand(this.getCommandName(),["install"])}getCommand(e,t=[]){return {name:e,arguments:t}}};var lo=class extends ze{getCommandName(){return "yarn"}createPackageCommand(e,t=[]){return Promise.resolve(this.getCommand("npx",["--yes",e,...t]))}createScriptCommand(e,t=[]){return Promise.resolve(this.getCommand(this.getCommandName(),["run",e,...t]))}createAddDependencyCommand(e,t){return this.getCommand(this.getCommandName(),["add",...t?["--dev"]:[],...e])}createInstallDependenciesCommand(){return this.getCommand(this.getCommandName(),["install"])}getCommand(e,t=[]){return {name:e,arguments:t}}};var uo=class extends ze{getCommandName(){return "bun"}createPackageCommand(e,t=[]){return Promise.resolve(this.getCommand(["x",e,...t]))}createScriptCommand(e,t=[]){return Promise.resolve(this.getCommand(["run",e,...t]))}createAddDependencyCommand(e,t){return this.getCommand(["install",...t?["--dev"]:[],...e])}createInstallDependenciesCommand(){return this.getCommand(["install"])}getCommand(e=[]){return {name:this.getCommandName(),arguments:e}}};var mo=class extends ze{getCommandName(){return "pnpm"}createPackageCommand(e,t=[]){return Promise.resolve(this.getCommand(["dlx",e,...t]))}createScriptCommand(e,t=[]){return Promise.resolve(this.getCommand(["run",e,...t]))}createAddDependencyCommand(e,t){return this.getCommand(["install",...t?["--save-dev"]:[],...e])}createInstallDependenciesCommand(){return this.getCommand(["install"])}getCommand(e=[]){return {name:this.getCommandName(),arguments:e}}};var go=class o{constructor({fileSystem:e,tsconfigValidator:t}){this.fileSystem=e,this.tsConfigValidator=t;}async load(e,t={}){let{fileNames:n=["tsconfig.json","jsconfig.json"]}=t,r=await this.fileSystem.getRealPath(e),i=await this.locateConfig(e,n,true);if(i===null)return null;let a=await this.resolveConfig({rootDirectory:r,configPath:i,fileNames:n,targetDirectories:(t.sourcePaths??[]).map(s=>this.fileSystem.isAbsolutePath(s)?s:this.fileSystem.joinPaths(r,s))});return a===null?null:{rootConfigPath:a.rootConfigPath,matchedConfigPath:a.matchedConfigPath,baseUrl:this.fileSystem.joinPaths(this.fileSystem.getDirectoryName(a.matchedConfigPath),a.compilerOptions?.baseUrl??"."),paths:a.compilerOptions?.paths??{}}}async locateConfig(e,t,n=false){for(let i of t){let a=this.fileSystem.joinPaths(e,i);if(await this.fileSystem.exists(a))return a}if(!n)return null;let r=this.fileSystem.getDirectoryName(e);return r===e?null:this.locateConfig(r,t)}async resolveConfig(e){let{configPath:t,fileNames:n,rootDirectory:r,targetDirectories:i}=e,a=await this.parseConfig(t);if(a?.extends!==void 0){let s=await this.locateParentConfig(r,this.fileSystem.getDirectoryName(t),a.extends);if(s!==null){let p=await this.resolveConfig({...e,configPath:s});p!==null&&(a=o.mergeConfig(a,p));}}if(a?.references!==void 0&&i.length>0){let{references:s,...p}=a;for(let c of a.references){let l=this.fileSystem.joinPaths(this.fileSystem.getDirectoryName(t),c.path),m=l.endsWith(".json")?l:await this.locateConfig(l,n);if(m===null)continue;let f=await this.resolveConfig({...e,configPath:m});if(f?.include!==void 0)for(let b of i){let A=this.fileSystem.joinPaths("./",this.fileSystem.getRelativePath(this.fileSystem.getDirectoryName(m),b));for(let I of f.include){let y=new Minimatch(I,{partial:true,magicalBraces:true});if(!y.hasMagic()&&!I.includes(".")&&(y=new Minimatch(`${I.replace(/\/?$/,"")}/**/*`,{partial:true})),y.match(A))return o.mergeConfig({...f,rootConfigPath:a.rootConfigPath},p)}}}}return a}async locateParentConfig(e,t,n){let r=n;r.endsWith(".json")||(r+=".json");let i=this.fileSystem.joinPaths(t,r);if(await this.fileSystem.exists(i))return i;let a=this.fileSystem.joinPaths(e,"node_modules",r);return await this.fileSystem.exists(a)?a:null}async parseConfig(e){let t;try{t=JsonParser$1.parse(await this.fileSystem.readTextFile(e)).toJSON();}catch{return null}let n=await this.tsConfigValidator.validate(t);return n.valid?{rootConfigPath:e,matchedConfigPath:e,...n.data}:null}static mergeConfig(e,t){return {...t,...e,compilerOptions:{...t.compilerOptions,...e.compilerOptions}}}};var fo=class{constructor({projectDirectory:e,fileSystem:t,tsConfigLoader:n}){this.projectDirectory=e,this.fileSystem=t,this.tsConfigLoader=n;}async getImportPath(e,t){let n=this.projectDirectory.get(),r=await this.tsConfigLoader.load(n,{sourcePaths:[this.fileSystem.joinPaths(n,t)]}),i=/\.m(?:js|ts)?$/.test(e)?e:e.replace(/\.(ts|js)x?$/,""),a=this.fileSystem.joinPaths(n,i);if(r!==null){let p=0,c=null;for(let[l,m]of Object.entries(r.paths)){let f=this.fileSystem.normalizeSeparators(l.replace(/\*$/,""));for(let b of m){let A=b.replace(/\*$/,""),I=this.fileSystem.joinPaths(r.baseUrl,A);if(a.startsWith(I)){let y=A.length;if(y>p){p=y;let M=a.slice(I.length).replace(/^[\\/]+/,"");c=f+M;}}}}if(c!==null)return Promise.resolve(c.replace(/\\+/g,"/"))}let s=this.fileSystem.getRelativePath(this.fileSystem.joinPaths(n,t),this.fileSystem.joinPaths(n,i));return Promise.resolve(s.replace(/\\/g,"/"))}};var Mm=z.object({extends:z.string().optional(),references:z.array(z.object({path:z.string()})).optional(),include:z.array(z.string()).optional(),compilerOptions:z.object({baseUrl:z.string().optional(),paths:z.record(z.array(z.string())).optional()}).optional()}),yo=class extends B{constructor(){super(Mm);}};var wn=class{constructor(e){this.provider=e;}get manager(){return Promise.resolve(this.provider.get()).catch(e=>{throw e instanceof U?new Se(e.message,e.help):e})}async isInstalled(){return (await this.manager).isInstalled()}async isProject(){return (await this.manager).isProject()}async hasDependency(e,t){return (await this.manager).hasDependency(e,t)}async hasDirectDependency(e,t){return (await this.manager).hasDirectDependency(e,t)}async getDependency(e){return (await this.manager).getDependency(e)}async addDependencies(e,t){return (await this.manager).addDependencies(e,t)}async installDependencies(){return (await this.manager).installDependencies()}async getScripts(){return (await this.manager).getScripts()}async addScript(e,t){return (await this.manager).addScript(e,t)}async getScriptCommand(e,t){return (await this.manager).getScriptCommand(e,t)}async getPackageCommand(e,t){return (await this.manager).getPackageCommand(e,t)}};var ho=class{constructor(e){this.map=e;}supports(e){return this.map.has(e)}get(e){let t=this.map.get(e);if(t===void 0)throw new U(`No value found for key \`${e}\`.`,{reason:"not_found"});return Promise.resolve(t)}};var So=class{isInstalled(){return Promise.resolve(false)}addDependencies(){return this.fail()}installDependencies(){return this.fail()}getPackageCommand(){return this.fail()}getScriptCommand(){return this.fail()}fail(){throw new Se("The package manager is not installed")}};var jt=class{constructor(e,t){this.provider=e,this.fallback=t;}async get(...e){let t=await this.provider.get(...e)??null;return t!==null?t:this.fallback.get(...e)}};var Oe=class{constructor(e){this.callback=e;}get(...e){return this.callback(...e)}};var Wt=class{constructor(e){this.candidates=e.candidates;}async get(...e){for(let{condition:t,value:n}of this.candidates)try{if(await t.test(...e))return typeof n=="object"&&n!==null&&"get"in n?n.get(...e):n}catch{}return null}};var Pn=class{constructor({fileSystem:e,files:t}){this.fileSystem=e,this.files=t;}async test(){return (await Promise.all(this.files.map(t=>this.fileSystem.exists(t)))).some(t=>t)}};var Cn=class{constructor({packageManager:e,dependencies:t}){this.packageManager=e,this.dependencies=t;}async test(){return (await Promise.all(this.dependencies.map(t=>this.packageManager.hasDirectDependency(t)))).some(t=>t)}};var bo=class{constructor({packageManager:e}){this.packageManager=e;}test(){return this.packageManager.isProject()}};var et=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var Io=class{constructor(){this.open=true;this.queue=[];}async*[Symbol.asyncIterator](){let e=await this.next();for(;e.done!==true;)yield e.value,e=await this.next();}next(){return this.queue.length>0?Promise.resolve({done:false,value:this.queue.shift()}):this.open?new Promise(e=>{this.resolve=()=>{this.resolve=void 0,this.queue.length===0?e({done:true,value:void 0}):e({done:false,value:this.queue.shift()});};}):Promise.resolve({done:true,value:void 0})}push(e){this.queue.push(e),this.resolve?.();}close(){this.open=false,this.resolve?.();}};var xo=class{constructor({currentDirectory:e}={}){this.currentDirectory=e;}run(e,t={}){let n=t.timeout!==void 0?AbortSignal.timeout(t.timeout):void 0,r=spawn(e.name,e.arguments,{shell:true,stdio:["pipe","pipe","pipe"],cwd:t?.workingDirectory??this.currentDirectory?.get(),signal:n}),i=[];r.on("error",c=>{for(let l of i)l(n?.aborted===true?new et("Command timed out.",{reason:"precondition",cause:c}):new et(`Failed to run command: ${d.formatCause(c)}`,{cause:c}));});let a=new Io;r.stdout.on("data",c=>{a.push(c.toString());}),r.stderr.on("data",c=>{a.push(c.toString());});let s=null,p=[];return r.on("exit",c=>{a.close(),s=c??1;for(let l of p)l(s);}),{output:a,get running(){return s===null},onExit:c=>(p.push(c),()=>{let l=p.indexOf(c);l!==-1&&p.splice(l,1);}),write:c=>new Promise((l,m)=>{r.stdin.write(c,f=>{f===null?l():m(f);});}),endWriting:()=>new Promise(c=>{if(s!==null){c();return}r.stdin.end(c);}),read:async()=>{let c="";for await(let l of a)c+=l;return c},wait:()=>new Promise((c,l)=>{if(s!==null){c(s);return}i.push(l),r.on("exit",m=>{c(m??1);});}),kill:c=>new Promise((l,m)=>{if(s!==null){l();return}r.stdout.destroy(),r.stderr.destroy(),r.stdin.destroy(),r.kill(c)?(l(),s=1):m(new et("Failed to kill the subprocess."));})}}runSync(e,t={}){let n=t.timeout!==void 0?AbortSignal.timeout(t.timeout):void 0,r=spawnSync(e.name,e.arguments,{stdio:["ignore","pipe","pipe"],cwd:t?.workingDirectory??this.currentDirectory?.get(),signal:n});if(r.error!==void 0){let{error:s}=r;throw n?.aborted===true?new et("Command timed out.",{reason:"precondition",cause:s}):new et(`Failed to run command: ${d.formatCause(s)}`,{cause:s})}let i=r.stdout.toString(),a=r.stderr.toString();return i!==""&&a!==""&&(i=`${i}
|
|
1786
1786
|
${a}`),{exitCode:r.status??1,output:i}}};var vo=class{constructor(e){this.provider=e;}async format(e){return (await this.formatter).format(e)}get formatter(){return Promise.resolve(this.provider.get()).catch(e=>{throw e instanceof U?new Se(e.message,e.help):e})}};var wo=class{constructor(e){this.provider=e;}get sdk(){return Promise.resolve(this.provider.get()).catch(e=>{throw e instanceof U?new ee(e.message,e.help):e})}async setup(e){return (await this.sdk).setup(e)}async update(e,t){return (await this.sdk).update(e,t)}async generateSlotExample(e,t){return (await this.sdk).generateSlotExample(e,t)}};var kn=class{constructor(e,t){this.valueProvider=e,this.keyProvider=t;}async get(...e){if(this.keyProvider!==void 0){let t=this.key;if(this.key=await this.keyProvider.get(...e),t===this.key&&this.value!==void 0)return this.value}else if(this.value!==void 0)return this.value;return this.value=Promise.resolve(this.valueProvider.get(...e)),this.value}};var Po=class o{constructor(e){this.instances=new Map;this.factory=e;}create(e){let t=o.getServerId(e),n=this.instances.get(t);if(n!==void 0)return n;let r=this.factory.create(e);return this.instances.set(t,r),r}static getServerId({command:e,...t}){let n=new URL(`${t.protocol}://${t.host}`);return n.port=`${t.port??t.defaultPort}`,n.searchParams.set("command",e.name),e.arguments!==void 0&&e.arguments.length>0&&n.searchParams.set("args",e.arguments.join(",")),n.toString()}};var Co=class o{constructor(e){this.matcher=e;}static fromPattern(e){return new o(new Minimatch(e))}test(e){return Promise.resolve(this.matcher.match(e))}};var ko=class{constructor(...e){this.predicates=e;}async test(...e){for(let t of this.predicates)if(!await t.test(...e))return false;return true}};var An=class{constructor(e){this.predicate=e;}async test(...e){return !await this.predicate.test(...e)}};var Ao=class o{constructor(e){this.filter=e;}static fromPatterns(...e){return new o(_m().add(e))}test(e){return Promise.resolve(this.filter.ignores(e))}};var Eo=class{constructor(e){this.predicate=e;}get(...e){return this.predicate.test(...e)}};var En=class{constructor(e){this.input=e;}confirm(e){return e.default!==void 0?Promise.resolve(e.default):this.input.confirm(e)}prompt(e){return e.default!==void 0?Promise.resolve(e.default):this.input.prompt(e)}select(e){return e.default!==void 0?Promise.resolve(e.default):this.input.select(e)}selectMultiple(e){let t=e.options.filter(n=>n.selected===true);return t.length>0&&(e.min===void 0||t.length>=e.min)?Promise.resolve(t.map(n=>n.value)):this.input.selectMultiple(e)}wait(e){return this.input.wait(e)}};var Rn=class{constructor(...e){this.predicates=e;}async test(...e){for(let t of this.predicates)if(await t.test(...e))return true;return false}};var is={};Hc(is,{basename:()=>Fm,dirname:()=>jm,ext:()=>Lm});var Lm=o=>{if(typeof o!="string")throw new $(`The \`path\` argument of the \`ext\` function must be a string, but got ${d.describeType(o)}.`);return o.split(".").pop()??""},Fm=o=>{if(typeof o!="string")throw new $(`The \`path\` argument of the \`basename\` function must be a string, but got ${d.describeType(o)}.`);return o.split(/[\\/]/).pop()??""},jm=o=>{if(typeof o!="string")throw new $(`The \`path\` argument of the \`dirname\` function must be a string, but got ${d.describeType(o)}.`);return o.replace(/[\\/][^\\/]*$/,"")};var Ro=class{constructor(e){this.runner=e;}async execute(e,t){for(;await e.condition;)await this.run(e.actions,t);}run(e,t){return this.runner.execute({actions:e},t)}};var Wm=z.strictObject({condition:z.instanceof(Promise),actions:z.instanceof(Promise)}),To=class extends w{constructor(){super(Wm);}};var q=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var Oo=class o{constructor({fileSystem:e,commandExecutor:t,appDirectory:n}){this.fileSystem=e,this.commandExecutor=t,this.appDirectory=n;}async isRegistered(e){return await this.findLauncher(e)!==null}async register(e){if(!await this.isRegistered(e.protocol))try{await this.install(e);}catch(t){throw new q("Failed to register protocol handler.",{cause:t})}}async unregister(e){let t=await this.findLauncher(e);if(t===null)return;let n=this.getLauncherAppPath(e);if(t!==n)throw new q(`Application registered for protocol \`${e}\` is externally managed.`,{reason:"precondition"});try{await this.fileSystem.delete(n,{recursive:!0}),await this.fileSystem.delete(this.getHandlerAppPath(e),{recursive:!0});}catch(r){throw new q("Failed to unregister protocol handler.",{cause:r})}}async install(e){let t=this.getLauncherAppPath(e.protocol),n=this.getHandlerAppPath(e.protocol),r=this.createLauncherApp(e,n),i=this.createHandlerApp(e),a=await this.fileSystem.createTemporaryDirectory("protocol"),s=this.fileSystem.joinPaths(a,"launcher.scpt"),p=this.fileSystem.joinPaths(a,"handler.scpt");await this.fileSystem.writeTextFile(s,r),await this.fileSystem.writeTextFile(p,i),await this.fileSystem.createDirectory(this.appDirectory,{recursive:true}),await this.execute({name:"osacompile",arguments:["-o",t,s]}),await this.execute({name:"osacompile",arguments:["-o",n,p]}),await this.execute({name:"plutil",arguments:["-insert","CFBundleURLTypes","-json",JSON.stringify([{CFBundleURLName:o.formatId(e.id),CFBundleURLSchemes:[e.protocol]}]),`${t}/Contents/Info.plist`]}),await this.execute({name:"open",arguments:["-g",t]});}async findLauncher(e){let n=(await this.execute({name:"osascript",arguments:["-e",te`
|
|
1787
1787
|
use AppleScript version "2.4"
|
|
1788
1788
|
use framework "Foundation"
|
|
@@ -1817,7 +1817,7 @@ ${a}`),{exitCode:r.status??1,output:i}}};var vo=class{constructor(e){this.provid
|
|
|
1817
1817
|
StartupNotify=false
|
|
1818
1818
|
Terminal=true
|
|
1819
1819
|
MimeType=x-scheme-handler/${e.protocol}
|
|
1820
|
-
`}getDesktopEntryPath(e){return this.fileSystem.joinPaths(this.getApplicationPath(),`${e}.desktop`)}getApplicationPath(){return this.fileSystem.joinPaths(this.homeDirectory,".local","share","applications")}};var No=class{constructor(e){this.config=e;}async execute({url:e}){if(!URL.canParse(e))throw new d("The URL is not valid.",{reason:"invalid_input"});let t=new URL(e);if(!this.isValidUrl(t))throw new d("The URL is not supported.",{reason:"invalid_input"});let{input:n,output:r}=this.config.io;if(n===void 0)throw new d("Deep links requires explicit user interaction.",{reason:"precondition",details:["Retry in interactive mode."]});let i=this.parseArguments(t);r.announce({semantics:"neutral",title:"\u{1F517} Croct link",message:"You just opened a link to a `Croct CLI` command.",alignment:"center"});let a=i.join(" ");r.inform(`The command is \`${a}\``),await n.confirm({message:"Continue?",default:true})&&(await this.selectDirectory(n),await this.config.program(i));}async selectDirectory(e){let{workingDirectory:t,configurationProvider:n,fileSystem:r,io:{output:i}}=this.config,a=t.get(),{projectPaths:s}=await n.get(),p="";if(s.length>0){let c=r.getDirectoryName(s[0]);p=await e.select({message:"Where should this command run?",options:[{label:`${a} (current)`,value:""},{label:c,value:c},...s.map(l=>({value:l,label:l}))]});}else i.inform(`You are currently in \`${a}\``),await e.confirm({message:"Run the command from the current directory?",default:true})||await e.prompt({message:"Where do you want to run the command from?",default:a,validate:async c=>await r.isDirectory(c)?true:"Enter a valid directory path."});p!==""&&t.setCurrentDirectory(p);}parseArguments(e){let t=[];for(let r of (e.hostname+e.pathname).split("/"))r!==""&&t.push(r);let n=[];for(let[r,i]of e.searchParams){if(r==="arg"){n.push(i);continue}if(i===""){t.push(`-${r.length===1?"":"-"}${r}`);continue}t.push(`--${r}`),t.push(i);}return t.push(...n),t}isValidUrl(e){return e.protocol===`${this.config.protocol}:`&&e.username===""&&e.password===""&&e.port===""&&e.hash===""}};var Vm=z.strictObject({projectPaths:z.array(z.string().min(1)),isDeepLinkingEnabled:z.boolean().optional()}),zo=class extends B{constructor(){super(Vm);}};var _o=class{constructor({manager:e,workingDirectory:t,store:n}){this.manager=e,this.workingDirectory=t,this.store=n;}isInitialized(){return this.manager.isInitialized()}async load(){let e=await this.manager.load();return await this.updateIndex(),e}update(e){return Promise.all([this.manager.update(e),this.updateIndex()]).then(([t])=>t)}async updateIndex(){let e=await this.store.get();await this.store.save({...e,projectPaths:[this.workingDirectory.get(),...e.projectPaths]});}};var Lo=class{constructor(e){this.fileSystem=e.fileSystem,this.executablePaths=e.executablePaths,this.executableExtensions=e.executableExtensions??[],this.executableCache=e.cache??new NoopCache;}locate(e){return this.executableCache.get(e,t=>this.findPath(t))}async findPath(e){for(let t of this.executablePaths)for(let n of ["",...this.executableExtensions]){let r=this.fileSystem.joinPaths(t,e+n.toLowerCase());if(r!==null&&await this.fileSystem.exists(r))return r}return null}};var Fo=class{constructor(e){this.projectDirectory=e.projectDirectory,this.fileSystem=e.fileSystem,this.packageManager=e.packageManager;}async test(){return (await this.getPreferredPackageManager())?.includes(this.packageManager)===true}async getPreferredPackageManager(){let e=this.fileSystem.joinPaths(this.projectDirectory.get(),"package.json");if(!await this.fileSystem.exists(e))return null;let t;try{t=JSON.parse(await this.fileSystem.readTextFile(e));}catch{return null}return typeof t=="object"&&t!==null&&"packageManager"in t&&typeof t.packageManager=="string"?t.packageManager:null}};var Tn=class{constructor(e){this.config=e;}async execute(){try{await this.enableDeepLinks();}catch{}}async enableDeepLinks(){let{cliPackage:e,packageManager:t,protocolRegistryProvider:n,protocolHandler:r,io:{output:i,input:a}}=this.config,s=await n.get();if(s===null||a===void 0)return;let[p,c]=await Promise.all([s.isRegistered(r.protocol),t.isInstalled()]);if(p||!c||!await a.confirm({message:"Turn on deep links to streamline your experience?",default:true}))return;let l=i.notify("Enabling deep links...");try{let m=await t.getPackageCommand(e,["open","$url"]);await s.register({...r,command:`${m.name} ${(m.arguments??[]).join(" ")}`}),i.confirm("Deep links enabled");}finally{l.stop();}}};var jo=class{constructor(e){this.process=e.process,this.variable=e.variable,this.value=e.value;}test(){let e=this.process.getEnvValue(this.variable);return e===null?false:this.value?.test(e)===true}};var Wo=class{constructor(...e){this.providers=e;}async get(...e){for(let t of this.providers){let n=await t.get(...e)??null;if(n!==null)return n}return null}};var Vo=class{constructor(e){this.config=e;}async handle(){let{input:e,output:t,userApi:n}=this.config,r=await n.getInvitations();if(r.length!==0){if(r.length===1){let{id:i,organization:a}=r[0];await e.confirm({message:`${a.name} has invited you to join. Accept?`,default:true})&&await n.acceptInvitation(i);return}r.length>1&&t.inform(`You have ${r.length} pending invitations:`);for(let{id:i,organization:a}of r)await e.confirm({message:`Accept invitation to join ${a.name}?`,default:true})&&await n.acceptInvitation(i);}}};var Uo=class{constructor(e){this.authenticator=e.authenticator,this.invitationForm=e.invitationForm;}getToken(){return this.authenticator.getToken()}async login(e){let t=await this.authenticator.login(e);return await this.invitationForm.handle({}),t}logout(){return this.authenticator.logout()}};var qo=class o{static{this.EMPTY_SETTINGS={projectPaths:[]};}constructor({fileSystem:e,validator:t,filePath:n}){this.fileSystem=e,this.validator=t,this.filePath=n;}async get(){if(!await this.fileSystem.exists(this.filePath))return o.EMPTY_SETTINGS;let e;try{e=await this.fileSystem.readTextFile(this.filePath);}catch{return o.EMPTY_SETTINGS}let t=await this.validator.validate(JSON.parse(e));return t.valid?t.data:o.EMPTY_SETTINGS}save(e){return this.fileSystem.writeTextFile(this.filePath,JSON.stringify(e),{overwrite:true})}};var Ho=class{constructor({fileSystem:e,store:t}){this.fileSystem=e,this.store=t;}async get(){return this.normalizeSettings(await this.store.get())}async save(e){return this.store.save(await this.normalizeSettings(e))}async normalizeSettings(e){return {...e,projectPaths:(await Promise.all([...new Set(e.projectPaths)].map(async t=>await this.fileSystem.exists(t)?[t]:[]))).flat()}}};var Go=class{constructor(e){this.config=e;}async execute(e){let{configurationManager:t,api:n,fileSystem:r,io:i}=this.config,a=await t.load(),s=e.environment??await i.input.select({message:"Which environment?",options:xe.all().map(y=>({label:xe.getLabel(y),value:y}))}),p=s==="PRODUCTION"?a.applications.production:a.applications.development;if(p===void 0)throw new d(`No ${xe.getLabel(s).toLowerCase()} application found in the project configuration.`,{reason:"invalid_input"});let c=i.output.notify("Loading information"),l=e.name??`${(await n.user.getUser()).username} (CLI)`,m=await n.workspace.getFeatures({organizationSlug:a.organization,workspaceSlug:a.workspace});if(c.stop(),e.permissions?.includes("DATA_EXPORT")===true&&m?.features.dataExport!==true)throw new d("The workspace does not have the data export feature enabled.",{reason:"invalid_input"});let f=e.name??await Ne.prompt({input:i.input,label:"API key name",default:l}),b=e.permissions??await i.input.selectMultiple({message:"Select permissions",min:1,options:Ee.all().map(y=>({label:Ee.getLabel(y),value:y,disabled:y==="DATA_EXPORT"&&m?.features.dataExport!==true}))}),A=await n.application.createApiKey({organizationSlug:a.organization,workspaceSlug:a.workspace,applicationSlug:p,name:f,permissions:b});if(e.copy===true||await i.input.confirm({message:"Copy to clipboard?",default:false})){await qm.write(A.secret),i.output.confirm("API key copied to clipboard");return}let v=`api-key-${A.id}.txt`;await r.writeTextFile(v,A.secret),i.output.confirm(`API key saved to \`${v}\``);}};var Rc=ft(Kt());var Ko=class{constructor({apiKey:e,clock:t,tokenDuration:n}){this.apiKey=e,this.clock=t,this.tokenDuration=n;}getToken(){return Promise.resolve(this.token?.toString()??null)}async login(){return this.token=await this.issueToken(),this.token.toString()}logout(){return this.token=void 0,Promise.resolve()}async issueToken(){let e=Rc.Instant.now(this.clock).getSeconds();return Token.of({kid:await this.apiKey.getIdentifierHash(),alg:"ES256",typ:"JWT"},{iat:e,nbf:e,exp:e+this.tokenDuration,iss:"cli.croct.com",aud:"app.croct.com",scope:["ADMIN"]}).signedWith(this.apiKey)}};var Zo=class{constructor(e){this.currentDirectory=e;}get(){return this.currentDirectory}setCurrentDirectory(e){this.currentDirectory=e;}toString(){return this.get()}};var Jo=class{constructor(e){this.process=e;}get(){return this.process.getCurrentDirectory()}setCurrentDirectory(e){this.process.changeDirectory(e);}toString(){return this.get()}};var Qo=class{constructor({authenticator:e,cacheKey:t,cacheProvider:n}){this.authenticator=e,this.cacheKey=t,this.cacheProvider=n;}getToken(){return this.cacheProvider.get(this.cacheKey,()=>this.authenticator.getToken())}async login(e){let t=await this.authenticator.login(e);return await this.cacheProvider.set(this.cacheKey,t),t}async logout(){await this.authenticator.logout(),await this.cacheProvider.delete(this.cacheKey);}};var Tc=ft(Kt());var Bo=class{constructor(e){this.revalidating=new Map;this.clock=e.clock,this.clockSkewTolerance=e.clockSkewTolerance,this.cacheProvider=e.cacheProvider,this.tokenFreshPeriod=e.tokenFreshPeriod,this.tokenIssuer=e.tokenIssuer;}async get(e,t){let n=await this.cacheProvider.get(e,async()=>await t(e)??"");if(n==="")return null;let r=this.parseToken(n);if(r!==null){let i=this.clockSkewTolerance,a=this.clock.getInstant().getSeconds();if(!r.isValidNow(a-i)&&!r.isValidNow(a+i))return null;this.revalidateToken(e,r).catch(()=>{});}return n}set(e,t){return this.cacheProvider.set(e,t)}delete(e){return this.cacheProvider.delete(e)}async revalidateToken(e,t){let n=this.clock.getInstant();if(this.revalidating.has(e))return;let r=t.getIssueTime(),i=Tc.Instant.ofEpochSecond(r+this.tokenFreshPeriod);n.isAfter(i)&&await this.renewToken(e,t);}async renewToken(e,t){let n=this.tokenIssuer(t);this.revalidating.set(e,true);try{await this.cacheProvider.set(e,await n);}finally{this.revalidating.delete(e);}}parseToken(e){let t;try{t=Token.parse(e);}catch{return null}return t}};var Yo=class{constructor(e){this.api=e.api,this.pollingInterval=e.pollingInterval;}async wait(e){let t=await this.api.closeSession(e);for(;t.status==="pending";)await this.delay(),t=await this.api.closeSession(e);switch(t.status){case "access-granted":return t.accessToken;case "recovery-granted":return t.recoveryToken}}delay(){return new Promise(e=>{setTimeout(e,this.pollingInterval);})}};var Xo=class o{constructor(e){this.boxenStyle=e??{titleAlignment:"center",borderStyle:"round",padding:{top:1,bottom:1,right:2,left:2}};}formatCallout(e){return Oc(X(e.message),{...this.boxenStyle,title:X(e.title,{basic:true}),textAlignment:e.alignment,borderColor:Zt[e.semantics]})}formatError(e){return Oc(o.formatErrorBody(e),{...this.boxenStyle,title:o.formatErrorTitle(e),borderColor:"red"})}static formatErrorTitle(e){return e instanceof d?{access_denied:"Access denied",invalid_configuration:"Invalid configuration",invalid_input:"Invalid input",not_found:"Not found",not_supported:"Not supported",precondition:"Precondition failed",unexpected_result:"Unexpected result",other:"Error"}[e.reason]:"Unexpected error"}static formatErrorBody(e){let t=X(d.formatMessage(e));if(e instanceof d){t+=o.formatErrorDetails(e);let{cause:n}=e.help;n!==void 0&&!o.isCauseReported(e.message,n)&&(t+=`
|
|
1820
|
+
`}getDesktopEntryPath(e){return this.fileSystem.joinPaths(this.getApplicationPath(),`${e}.desktop`)}getApplicationPath(){return this.fileSystem.joinPaths(this.homeDirectory,".local","share","applications")}};var No=class{constructor(e){this.config=e;}async execute({url:e}){if(!URL.canParse(e))throw new d("The URL is not valid.",{reason:"invalid_input"});let t=new URL(e);if(!this.isValidUrl(t))throw new d("The URL is not supported.",{reason:"invalid_input"});let{input:n,output:r}=this.config.io;if(n===void 0)throw new d("Deep links requires explicit user interaction.",{reason:"precondition",details:["Retry in interactive mode."]});let i=this.parseArguments(t);r.announce({semantics:"neutral",title:"\u{1F517} Croct link",message:"You just opened a link to a `Croct CLI` command.",alignment:"center"});let a=i.join(" ");r.inform(`The command is \`${a}\``),await n.confirm({message:"Continue?",default:true})&&(await this.selectDirectory(n),await this.config.program(i));}async selectDirectory(e){let{workingDirectory:t,configurationProvider:n,fileSystem:r,io:{output:i}}=this.config,a=t.get(),{projectPaths:s}=await n.get(),p="";if(s.length>0){let c=r.getDirectoryName(s[0]);p=await e.select({message:"Where should this command run?",options:[{label:`${a} (current)`,value:""},{label:c,value:c},...s.map(l=>({value:l,label:l}))]});}else i.inform(`You are currently in \`${a}\``),await e.confirm({message:"Run the command from the current directory?",default:true})||await e.prompt({message:"Where do you want to run the command from?",default:a,validate:async c=>await r.isDirectory(c)?true:"Enter a valid directory path."});p!==""&&t.setCurrentDirectory(p);}parseArguments(e){let t=[];for(let r of (e.hostname+e.pathname).split("/"))r!==""&&t.push(r);let n=[];for(let[r,i]of e.searchParams){if(r==="arg"){n.push(i);continue}if(i===""){t.push(`-${r.length===1?"":"-"}${r}`);continue}t.push(`--${r}`),t.push(i);}return t.push(...n),t}isValidUrl(e){return e.protocol===`${this.config.protocol}:`&&e.username===""&&e.password===""&&e.port===""&&e.hash===""}};var Vm=z.strictObject({projectPaths:z.array(z.string().min(1)),isDeepLinkingEnabled:z.boolean().optional()}),zo=class extends B{constructor(){super(Vm);}};var _o=class{constructor({manager:e,workingDirectory:t,store:n}){this.manager=e,this.workingDirectory=t,this.store=n;}isInitialized(){return this.manager.isInitialized()}async load(){let e=await this.manager.load();return await this.updateIndex(),e}update(e){return Promise.all([this.manager.update(e),this.updateIndex()]).then(([t])=>t)}async updateIndex(){let e=await this.store.get();await this.store.save({...e,projectPaths:[this.workingDirectory.get(),...e.projectPaths]});}};var Lo=class{constructor(e){this.fileSystem=e.fileSystem,this.executablePaths=e.executablePaths,this.executableExtensions=e.executableExtensions??[],this.executableCache=e.cache??new NoopCache;}locate(e){return this.executableCache.get(e,t=>this.findPath(t))}async findPath(e){for(let t of this.executablePaths)for(let n of ["",...this.executableExtensions]){let r=this.fileSystem.joinPaths(t,e+n.toLowerCase());if(r!==null&&await this.fileSystem.exists(r))return r}return null}};var Fo=class{constructor(e){this.projectDirectory=e.projectDirectory,this.fileSystem=e.fileSystem,this.packageManager=e.packageManager;}async test(){return (await this.getPreferredPackageManager())?.includes(this.packageManager)===true}async getPreferredPackageManager(){let e=this.fileSystem.joinPaths(this.projectDirectory.get(),"package.json");if(!await this.fileSystem.exists(e))return null;let t;try{t=JSON.parse(await this.fileSystem.readTextFile(e));}catch{return null}return typeof t=="object"&&t!==null&&"packageManager"in t&&typeof t.packageManager=="string"?t.packageManager:null}};var Tn=class{constructor(e){this.config=e;}async execute(){try{await this.enableDeepLinks();}catch{}}async enableDeepLinks(){let{cliPackage:e,packageManager:t,protocolRegistryProvider:n,protocolHandler:r,io:{output:i,input:a}}=this.config,s=await n.get();if(s===null||a===void 0)return;let[p,c]=await Promise.all([s.isRegistered(r.protocol),t.isInstalled()]);if(p||!c||!await a.confirm({message:"Turn on deep links to streamline your experience?",default:true}))return;let l=i.notify("Enabling deep links...");try{let m=await t.getPackageCommand(e,["open","$url"]);await s.register({...r,command:`${m.name} ${(m.arguments??[]).join(" ")}`}),i.confirm("Deep links enabled");}finally{l.stop();}}};var jo=class{constructor(e){this.process=e.process,this.variable=e.variable,this.value=e.value;}test(){let e=this.process.getEnvValue(this.variable);return e===null?false:this.value?.test(e)===true}};var Wo=class{constructor(...e){this.providers=e;}async get(...e){for(let t of this.providers){let n=await t.get(...e)??null;if(n!==null)return n}return null}};var Vo=class{constructor(e){this.config=e;}async handle(){let{input:e,output:t,userApi:n}=this.config,r=await n.getInvitations();if(r.length!==0){if(r.length===1){let{id:i,organization:a}=r[0];await e.confirm({message:`${a.name} has invited you to join. Accept?`,default:true})&&await n.acceptInvitation(i);return}r.length>1&&t.inform(`You have ${r.length} pending invitations:`);for(let{id:i,organization:a}of r)await e.confirm({message:`Accept invitation to join ${a.name}?`,default:true})&&await n.acceptInvitation(i);}}};var Uo=class{constructor(e){this.authenticator=e.authenticator,this.invitationForm=e.invitationForm;}getToken(){return this.authenticator.getToken()}async login(e){let t=await this.authenticator.login(e);return await this.invitationForm.handle({}),t}logout(){return this.authenticator.logout()}};var qo=class o{static{this.EMPTY_SETTINGS={projectPaths:[]};}constructor({fileSystem:e,validator:t,filePath:n}){this.fileSystem=e,this.validator=t,this.filePath=n;}async get(){if(!await this.fileSystem.exists(this.filePath))return o.EMPTY_SETTINGS;let e;try{e=await this.fileSystem.readTextFile(this.filePath);}catch{return o.EMPTY_SETTINGS}let t=await this.validator.validate(JSON.parse(e));return t.valid?t.data:o.EMPTY_SETTINGS}save(e){return this.fileSystem.writeTextFile(this.filePath,JSON.stringify(e),{overwrite:true})}};var Ho=class{constructor({fileSystem:e,store:t}){this.fileSystem=e,this.store=t;}async get(){return this.normalizeSettings(await this.store.get())}async save(e){return this.store.save(await this.normalizeSettings(e))}async normalizeSettings(e){return {...e,projectPaths:(await Promise.all([...new Set(e.projectPaths)].map(async t=>await this.fileSystem.exists(t)?[t]:[]))).flat()}}};var Go=class{constructor(e){this.config=e;}async execute(e){let{configurationManager:t,api:n,fileSystem:r,io:i}=this.config,a=await t.load(),s=e.environment??await i.input.select({message:"Which environment?",options:xe.all().map(y=>({label:xe.getLabel(y),value:y}))}),p=s==="PRODUCTION"?a.applications.production:a.applications.development;if(p===void 0)throw new d(`No ${xe.getLabel(s).toLowerCase()} application found in the project configuration.`,{reason:"invalid_input"});let c=i.output.notify("Loading information"),l=e.name??`${(await n.user.getUser()).username} (CLI)`,m=await n.workspace.getFeatures({organizationSlug:a.organization,workspaceSlug:a.workspace});if(c.stop(),e.permissions?.includes("DATA_EXPORT")===true&&m?.features.dataExport!==true)throw new d("The workspace does not have the data export feature enabled.",{reason:"invalid_input"});let f=e.name??await Ne.prompt({input:i.input,label:"API key name",default:l}),b=e.permissions??await i.input.selectMultiple({message:"Select permissions",min:1,options:Ee.all().map(y=>({label:Ee.getLabel(y),value:y,disabled:y==="DATA_EXPORT"&&m?.features.dataExport!==true}))}),A=await n.application.createApiKey({organizationSlug:a.organization,workspaceSlug:a.workspace,applicationSlug:p,name:f,permissions:b});if(e.copy===true||await i.input.confirm({message:"Copy to clipboard?",default:false})){await qm.write(A.secret),i.output.confirm("API key copied to clipboard");return}let I=`api-key-${A.id}.txt`;await r.writeTextFile(I,A.secret),i.output.confirm(`API key saved to \`${I}\``);}};var Rc=ft(Kt());var Ko=class{constructor({apiKey:e,clock:t,tokenDuration:n}){this.apiKey=e,this.clock=t,this.tokenDuration=n;}getToken(){return Promise.resolve(this.token?.toString()??null)}async login(){return this.token=await this.issueToken(),this.token.toString()}logout(){return this.token=void 0,Promise.resolve()}async issueToken(){let e=Rc.Instant.now(this.clock).getSeconds();return Token.of({kid:await this.apiKey.getIdentifierHash(),alg:"ES256",typ:"JWT"},{iat:e,nbf:e,exp:e+this.tokenDuration,iss:"cli.croct.com",aud:"app.croct.com",scope:["ADMIN"]}).signedWith(this.apiKey)}};var Zo=class{constructor(e){this.currentDirectory=e;}get(){return this.currentDirectory}setCurrentDirectory(e){this.currentDirectory=e;}toString(){return this.get()}};var Jo=class{constructor(e){this.process=e;}get(){return this.process.getCurrentDirectory()}setCurrentDirectory(e){this.process.changeDirectory(e);}toString(){return this.get()}};var Qo=class{constructor({authenticator:e,cacheKey:t,cacheProvider:n}){this.authenticator=e,this.cacheKey=t,this.cacheProvider=n;}getToken(){return this.cacheProvider.get(this.cacheKey,()=>this.authenticator.getToken())}async login(e){let t=await this.authenticator.login(e);return await this.cacheProvider.set(this.cacheKey,t),t}async logout(){await this.authenticator.logout(),await this.cacheProvider.delete(this.cacheKey);}};var Tc=ft(Kt());var Bo=class{constructor(e){this.revalidating=new Map;this.clock=e.clock,this.clockSkewTolerance=e.clockSkewTolerance,this.cacheProvider=e.cacheProvider,this.tokenFreshPeriod=e.tokenFreshPeriod,this.tokenIssuer=e.tokenIssuer;}async get(e,t){let n=await this.cacheProvider.get(e,async()=>await t(e)??"");if(n==="")return null;let r=this.parseToken(n);if(r!==null){let i=this.clockSkewTolerance,a=this.clock.getInstant().getSeconds();if(!r.isValidNow(a-i)&&!r.isValidNow(a+i))return null;this.revalidateToken(e,r).catch(()=>{});}return n}set(e,t){return this.cacheProvider.set(e,t)}delete(e){return this.cacheProvider.delete(e)}async revalidateToken(e,t){let n=this.clock.getInstant();if(this.revalidating.has(e))return;let r=t.getIssueTime(),i=Tc.Instant.ofEpochSecond(r+this.tokenFreshPeriod);n.isAfter(i)&&await this.renewToken(e,t);}async renewToken(e,t){let n=this.tokenIssuer(t);this.revalidating.set(e,true);try{await this.cacheProvider.set(e,await n);}finally{this.revalidating.delete(e);}}parseToken(e){let t;try{t=Token.parse(e);}catch{return null}return t}};var Yo=class{constructor(e){this.api=e.api,this.pollingInterval=e.pollingInterval;}async wait(e){let t=await this.api.closeSession(e);for(;t.status==="pending";)await this.delay(),t=await this.api.closeSession(e);switch(t.status){case "access-granted":return t.accessToken;case "recovery-granted":return t.recoveryToken}}delay(){return new Promise(e=>{setTimeout(e,this.pollingInterval);})}};var Xo=class o{constructor(e){this.boxenStyle=e??{titleAlignment:"center",borderStyle:"round",padding:{top:1,bottom:1,right:2,left:2}};}formatCallout(e){return Oc(X(e.message),{...this.boxenStyle,title:X(e.title,{basic:true}),textAlignment:e.alignment,borderColor:Zt[e.semantics]})}formatError(e){return Oc(o.formatErrorBody(e),{...this.boxenStyle,title:o.formatErrorTitle(e),borderColor:"red"})}static formatErrorTitle(e){return e instanceof d?{access_denied:"Access denied",invalid_configuration:"Invalid configuration",invalid_input:"Invalid input",not_found:"Not found",not_supported:"Not supported",precondition:"Precondition failed",unexpected_result:"Unexpected result",other:"Error"}[e.reason]:"Unexpected error"}static formatErrorBody(e){let t=X(d.formatMessage(e));if(e instanceof d){t+=o.formatErrorDetails(e);let{cause:n}=e.help;n!==void 0&&!o.isCauseReported(e.message,n)&&(t+=`
|
|
1821
1821
|
|
|
1822
1822
|
\u{1F6A8} ${nt.bold("Cause")}
|
|
1823
1823
|
`,t+=`${X(d.formatMessage(e.help.cause))}`),t+=o.formatErrorSuggestions(e),t+=o.formatErrorUsefulLinks(e);}return (!(e instanceof d)||e.reason==="other"&&e.help.cause instanceof Error)&&(t+=o.formatStackTrace(e)),t}static isCauseReported(e,t){return e.toLowerCase().includes(d.formatMessage(t).toLowerCase())}static formatErrorDetails(e){let t="",{details:n}=e.help;return n!==void 0&&(t+=`
|
|
@@ -1837,12 +1837,12 @@ ${t.join(`
|
|
|
1837
1837
|
|
|
1838
1838
|
\u{1F517} ${nt.bold("Useful links")}
|
|
1839
1839
|
`,n+=t.map(({label:r,url:i})=>` \u2022 ${fl(r,i,{fallback:()=>`${r}: ${i}`})}`).join(`
|
|
1840
|
-
`)),n}};var ea=class{constructor(){this.listeners={};}on(e,t){this.listeners[e]===void 0&&(this.listeners[e]=new Set),this.listeners[e].add(t);}off(e,t){this.listeners[e]!==void 0&&this.listeners[e].delete(t);}async emit(e,...t){this.listeners[e]!==void 0&&await Promise.all(Array.from(this.listeners[e]).map(n=>n(...t)));}};var ta=class{constructor(){this.eventDispatcher=new ea;_e.on("SIGTERM",()=>this.exit()),_e.on("SIGINT",()=>this.exit());}getCurrentDirectory(){return _e.cwd()}getEnvValue(e){return _e.env[e]??null}getEnvList(e){return this.getEnvValue(e)?.split(delimiter)??null}getPlatform(){return _e.platform}getStandardError(){return _e.stderr}getStandardInput(){return _e.stdin}getStandardOutput(){return _e.stdout}on(e,t){this.eventDispatcher.on(e,t);}off(e,t){this.eventDispatcher.off(e,t);}async exit(e){return await this.eventDispatcher.emit("exit").catch(()=>{}),_e.exit(e)}changeDirectory(e){_e.chdir(e);}};var na=class{constructor({callback:e}){this.callback=e;}async execute(e,t){try{return await this.callback(e,t)}catch(n){if(!(n instanceof I))throw I.fromCause(n)}}};var Qm=z.strictObject({}),ra=class extends w{constructor(){super(Qm);}};var ia=class o{static{this.REPOSITORY_PATTERNS=[/git\+(https:\/\/.+)\.git$/];}constructor(e){this.metadataProvider=e;}async get(e){let t=this.getMetadataUrl(e);if(t===null)throw new W("Unsupported NPM URL.",{reason:"not_supported",url:e});let{value:n}=await this.metadataProvider.get(t),r=o.getRepositoryUrl(n.repository);return r===null?{url:e,value:[]}:{url:r,value:[{pattern:".*",destination:r}]}}static getRepositoryUrl(e){for(let t of o.REPOSITORY_PATTERNS){let n=t.exec(e.url);if(n!==null)return new URL(`${n[1]}/`)}return null}getMetadataUrl(e){if(e.protocol!=="npm:")return null;let t=e.pathname.slice(1);return new URL(`https://registry.npmjs.org/${t}/latest`)}};var oa=class o{constructor({provider:e,reader:t}){this.provider=e,this.reader=t;}static text(e){return new o({provider:e,reader:t=>t.text()})}static json(e){return new o({provider:e,reader:t=>t.json()})}static blob(e){return new o({provider:e,reader:t=>t.blob()})}async get(e){let t=await this.provider.get(e),n;try{n=await this.reader(new Response(t.value.body));}catch(r){throw new W("Failed to read response body.",{reason:"unexpected_result",url:e,cause:r})}return {url:t.url,value:n}}};var Bm=z.object({name:z.string(),repository:z.object({type:z.string(),url:z.string()})}),aa=class extends B{constructor(){super(Bm);}};var pa=class{constructor({provider:e,logger:t,label:n}){this.provider=e,this.logger=t,this.label=n;}get(e){return this.logger.nest({message:`\`${this.label??this.provider.constructor.name}\``,level:LogLevel.DEBUG},()=>this.trace(e))}async trace(e){this.logger.log({message:`URL: ${e}`,level:LogLevel.DEBUG});try{let t=await this.provider.get(e);return this.logger.log({message:"No errors",level:LogLevel.DEBUG}),t}catch(t){throw this.logger.log({message:`Error: ${d.formatMessage(t)}`,level:LogLevel.DEBUG}),t}}};var ca=class{constructor(e){this.storage=new AsyncLocalStorage;this.logger=e;}nest(e,t){let n=this.storage.getStore();if(n!==void 0)return this.logNested(n,e,t);let r={level:0,logs:[]};return this.storage.run(r,()=>this.logNested(r,e,t))}async logNested(e,t,n){this.buffer(e,{...t,message:`\u250C\u2500 ${t.message}`}),e.level++;try{return await n()}finally{e.level--,this.buffer(e,{...t,message:"\u2514\u2500"}),e.level===0&&(e.logs.forEach(r=>this.logger.log(r)),e.logs=[]);}}log(e){let t=this.storage.getStore();if(t!==void 0){this.buffer(t,e);return}this.logger.log(e);}buffer(e,t){e.logs.push({...t,message:`${e.level>0?`${"\u2502 ".repeat(e.level-1)}\u2502 `:""}${t.message}`});}};var la=class{constructor(e){this.output=e;}log(e){switch(e.level){case "debug":this.output.debug(e.message);break;case "info":this.output.inform(e.message);break;case "warning":this.output.warn(e.message);break;case "error":this.output.alert(e.message);}}};var ua=class o{static{this.PREFIX="?/";}constructor(e){this.rootPath=e.rootPath,this.importResolver=e.importResolver,this.exportMatcher=e.exportMatcher,this.importCodemod=e.importCodemod,this.fileSystem=e.fileSystem,this.maxSearchDepth=e.maxSearchDepth;}apply(e){return this.importCodemod.apply(e,{transformer:t=>{if(!t.source.startsWith(o.PREFIX))return;let n=t.source.slice(o.PREFIX.length);return this.resolvePath(t,n,e)}})}async resolvePath(e,t,n){let r=new Minimatch(t);for await(let i of this.fileSystem.list(this.rootPath.get(),this.maxSearchDepth))if(i.type==="file"&&r.match(i.name)&&await this.exportMatcher.test(await new Response(i.content).text(),e))return this.importResolver.getImportPath(i.name,n);throw new He(`Unable to resolve import \`${t}\` from \`${n}\`.`,{reason:"not_found"})}};var ma=class{constructor({codemods:e}){this.codemods=e;}apply(e,t){let[,n]=Object.entries(this.codemods).find(([r])=>minimatch(e,r))??[];return n===void 0?Promise.resolve({modified:false,result:e}):n.apply(e,t)}};function Dc(o){let e=typeof o=="string"?Ge(o,["jsx","typescript"]):o,t=[];return traverse(e,{ExportDeclaration:n=>{let{node:r}=n;if(g.isExportNamedDeclaration(r))if(r.specifiers.length>0)for(let i of r.specifiers)g.isExportSpecifier(i)?(!g.isIdentifier(i.exported)||i.exported.name!=="default")&&t.push(g.isIdentifier(i.exported)?i.exported.name:i.exported.value):g.isExportNamespaceSpecifier(i)&&g.isIdentifier(i.exported)&&t.push(i.exported.name);else if(g.isVariableDeclaration(r.declaration))for(let i of r.declaration.declarations)g.isVariableDeclarator(i)&&g.isIdentifier(i.id)&&t.push(i.id.name);else typeof r.declaration=="object"&&r.declaration!==null&&"id"in r.declaration&&g.isIdentifier(r.declaration.id)&&t.push(r.declaration.id.name);return n.skip()}}),t}async function Mc(o,e){let t=[];return traverse(o,{ImportDeclaration:n=>{let{node:r}=n,i=Promise.resolve(e(rd(r)));return i!==void 0&&t.push(i.then(a=>typeof a=="string"&&r.source.value!==a?(r.source.value=a,true):false)),n.skip()}}),(await Promise.all(t)).some(n=>n)}function rd(o){let e={names:[],source:o.source.value};for(let t of o.specifiers)g.isImportSpecifier(t)&&e.names.push(g.isIdentifier(t.imported)?t.imported.name:t.imported.value);return e}var ga=class{async apply(e,t){let n=await Mc(e,t.transformer);return {result:e,modified:n}}};var fa=class{constructor(...e){this.codemods=e;}async apply(e,t){let n=e,r=false;for(let i of this.codemods){let a=await i.apply(n,t);n=a.result,r=r||a.modified;}return {modified:r,result:n}}};var ya=class o{constructor(e,t){this.client=e,this.cache=t;}getHierarchy(e){return this.cache.get(o.getHierarchyKey(e),async()=>{let t=await this.resolveHierarchy(e);return await this.saveCache(e,t),t})}async resolveHierarchy(e){let{data:{organization:t}}=await this.client.execute(mp,e),n=t?.id,r=t?.workspace?.id,i=t?.workspace?.application?.id;return o.checkMissing("organization",e.organizationSlug,n),"workspaceSlug"in e?(o.checkMissing("workspace",e.workspaceSlug,r),"applicationSlug"in e?(o.checkMissing("application",e.applicationSlug,i),{organizationId:n,workspaceId:r,applicationId:i}):{organizationId:n,workspaceId:r}):{organizationId:n}}async saveCache(e,t){let n=[this.setCache({organizationSlug:e.organizationSlug},{organizationId:t.organizationId})];"workspaceId"in t&&"workspaceSlug"in e&&n.push(this.setCache({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug},{organizationId:t.organizationId,workspaceId:t.workspaceId})),"applicationId"in t&&"applicationSlug"in e&&n.push(this.setCache({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,applicationSlug:e.applicationSlug},{organizationId:t.organizationId,workspaceId:t.workspaceId,applicationId:t.applicationId})),await Promise.all(n);}setCache(e,t){return this.cache.set(o.getHierarchyKey(e),t)}static getHierarchyKey(e){let t=[`organization:${e.organizationSlug}`];return "workspaceSlug"in e&&t.push(`workspace:${e.workspaceSlug}`),"applicationSlug"in e&&t.push(`application${e.applicationSlug}`),t.join("/")}static checkMissing(e,t,n){if(n===void 0)throw new ne(`No ${e} found with slug "${t}".`,[],{reason:"not_found"})}};var ha=class{constructor(...e){this.registries=e;}async isRegistered(e){for(let t of this.registries)if(!await t.isRegistered(e))return false;return true}async register(e){for(let t of this.registries)await t.register(e);}async unregister(e){for(let t of this.registries)await t.unregister(e);}};var Sa=class o{constructor(e){this.registry=e;}isRegistered(e){return this.registry.isRegistered(e)}async register(e){try{await this.registry.register(e);}catch(t){o.handleError(t);}}async unregister(e){try{await this.registry.unregister(e);}catch(t){o.handleError(t);}}static handleError(e){if(!(e instanceof q))throw e}};var ba=class o{static{this.PREFERENCES=['user_pref("network.protocol-handler.expose.%protocol%", false);','user_pref("network.protocol-handler.external.%protocol%", true);'];}constructor({fileSystem:e,appDirectory:t}){this.fileSystem=e,this.profileDirectory=t;}static fromSystem(e,t){switch(e.getPlatform()){case "win32":{let n=e.getEnvValue("APPDATA")??e.getEnvValue("USERPROFILE");if(n===null)throw new q("Cannot determine the user profile directory.",{reason:"precondition"});return o.windows({fileSystem:t.fileSystem,appDataDirectory:n})}case "darwin":{let n=e.getEnvValue("HOME");if(n===null)throw new q("Cannot determine the user home directory.",{reason:"precondition"});return o.macOs({fileSystem:t.fileSystem,homeDirectory:n})}case "linux":{let n=e.getEnvValue("HOME");if(n===null)throw new q("Cannot determine the user home directory.",{reason:"precondition"});return o.linux({fileSystem:t.fileSystem,homeDirectory:n})}default:throw new q(`Platform \`${e.getPlatform()}\` is not supported.`,{reason:"not_supported"})}}static windows(e){return new o({fileSystem:e.fileSystem,appDirectory:e.fileSystem.joinPaths(e.appDataDirectory,"Mozilla","Firefox")})}static macOs(e){return new o({fileSystem:e.fileSystem,appDirectory:e.fileSystem.joinPaths(e.homeDirectory,"Library","Application Support","Firefox")})}static linux(e){return new o({fileSystem:e.fileSystem,appDirectory:e.fileSystem.joinPaths(e.homeDirectory,"snap","firefox","common",".mozilla","firefox")})}async isRegistered(e){let t=await this.getPreferencesFilePath();if(t===null)return false;let n=await this.fileSystem.readTextFile(t).catch(()=>"");for(let r of this.getPreferences(e))if(!n.includes(r))return false;return true}async register(e){if(await this.isRegistered(e.protocol))return;let t=await this.getPreferencesFilePath();if(t===null)throw new q("Cannot find the default profile file.",{reason:"precondition"});let r=`${await this.fileSystem.readTextFile(t).catch(()=>"")}
|
|
1840
|
+
`)),n}};var ea=class{constructor(){this.listeners={};}on(e,t){this.listeners[e]===void 0&&(this.listeners[e]=new Set),this.listeners[e].add(t);}off(e,t){this.listeners[e]!==void 0&&this.listeners[e].delete(t);}async emit(e,...t){this.listeners[e]!==void 0&&await Promise.all(Array.from(this.listeners[e]).map(n=>n(...t)));}};var ta=class{constructor(){this.eventDispatcher=new ea;_e.on("SIGTERM",()=>this.exit()),_e.on("SIGINT",()=>this.exit());}getCurrentDirectory(){return _e.cwd()}getEnvValue(e){return _e.env[e]??null}getEnvList(e){return this.getEnvValue(e)?.split(delimiter)??null}getPlatform(){return _e.platform}getStandardError(){return _e.stderr}getStandardInput(){return _e.stdin}getStandardOutput(){return _e.stdout}on(e,t){this.eventDispatcher.on(e,t);}off(e,t){this.eventDispatcher.off(e,t);}async exit(e){return await this.eventDispatcher.emit("exit").catch(()=>{}),_e.exit(e)}changeDirectory(e){_e.chdir(e);}};var na=class{constructor({callback:e}){this.callback=e;}async execute(e,t){try{return await this.callback(e,t)}catch(n){if(!(n instanceof x))throw x.fromCause(n)}}};var Qm=z.strictObject({}),ra=class extends w{constructor(){super(Qm);}};var ia=class o{static{this.REPOSITORY_PATTERNS=[/git\+(https:\/\/.+)\.git$/];}constructor(e){this.metadataProvider=e;}async get(e){let t=this.getMetadataUrl(e);if(t===null)throw new W("Unsupported NPM URL.",{reason:"not_supported",url:e});let{value:n}=await this.metadataProvider.get(t),r=o.getRepositoryUrl(n.repository);return r===null?{url:e,value:[]}:{url:r,value:[{pattern:".*",destination:r}]}}static getRepositoryUrl(e){for(let t of o.REPOSITORY_PATTERNS){let n=t.exec(e.url);if(n!==null)return new URL(`${n[1]}/`)}return null}getMetadataUrl(e){if(e.protocol!=="npm:")return null;let t=e.pathname.slice(1);return new URL(`https://registry.npmjs.org/${t}/latest`)}};var oa=class o{constructor({provider:e,reader:t}){this.provider=e,this.reader=t;}static text(e){return new o({provider:e,reader:t=>t.text()})}static json(e){return new o({provider:e,reader:t=>t.json()})}static blob(e){return new o({provider:e,reader:t=>t.blob()})}async get(e){let t=await this.provider.get(e),n;try{n=await this.reader(new Response(t.value.body));}catch(r){throw new W("Failed to read response body.",{reason:"unexpected_result",url:e,cause:r})}return {url:t.url,value:n}}};var Bm=z.object({name:z.string(),repository:z.object({type:z.string(),url:z.string()})}),aa=class extends B{constructor(){super(Bm);}};var pa=class{constructor({provider:e,logger:t,label:n}){this.provider=e,this.logger=t,this.label=n;}get(e){return this.logger.nest({message:`\`${this.label??this.provider.constructor.name}\``,level:LogLevel.DEBUG},()=>this.trace(e))}async trace(e){this.logger.log({message:`URL: ${e}`,level:LogLevel.DEBUG});try{let t=await this.provider.get(e);return this.logger.log({message:"No errors",level:LogLevel.DEBUG}),t}catch(t){throw this.logger.log({message:`Error: ${d.formatMessage(t)}`,level:LogLevel.DEBUG}),t}}};var ca=class{constructor(e){this.storage=new AsyncLocalStorage;this.logger=e;}nest(e,t){let n=this.storage.getStore();if(n!==void 0)return this.logNested(n,e,t);let r={level:0,logs:[]};return this.storage.run(r,()=>this.logNested(r,e,t))}async logNested(e,t,n){this.buffer(e,{...t,message:`\u250C\u2500 ${t.message}`}),e.level++;try{return await n()}finally{e.level--,this.buffer(e,{...t,message:"\u2514\u2500"}),e.level===0&&(e.logs.forEach(r=>this.logger.log(r)),e.logs=[]);}}log(e){let t=this.storage.getStore();if(t!==void 0){this.buffer(t,e);return}this.logger.log(e);}buffer(e,t){e.logs.push({...t,message:`${e.level>0?`${"\u2502 ".repeat(e.level-1)}\u2502 `:""}${t.message}`});}};var la=class{constructor(e){this.output=e;}log(e){switch(e.level){case "debug":this.output.debug(e.message);break;case "info":this.output.inform(e.message);break;case "warning":this.output.warn(e.message);break;case "error":this.output.alert(e.message);}}};var ua=class o{static{this.PREFIX="?/";}constructor(e){this.rootPath=e.rootPath,this.importResolver=e.importResolver,this.exportMatcher=e.exportMatcher,this.importCodemod=e.importCodemod,this.fileSystem=e.fileSystem,this.maxSearchDepth=e.maxSearchDepth;}apply(e){return this.importCodemod.apply(e,{transformer:t=>{if(!t.source.startsWith(o.PREFIX))return;let n=t.source.slice(o.PREFIX.length);return this.resolvePath(t,n,e)}})}async resolvePath(e,t,n){let r=new Minimatch(t);for await(let i of this.fileSystem.list(this.rootPath.get(),this.maxSearchDepth))if(i.type==="file"&&r.match(i.name)&&await this.exportMatcher.test(await new Response(i.content).text(),e))return this.importResolver.getImportPath(i.name,n);throw new He(`Unable to resolve import \`${t}\` from \`${n}\`.`,{reason:"not_found"})}};var ma=class{constructor({codemods:e}){this.codemods=e;}apply(e,t){let[,n]=Object.entries(this.codemods).find(([r])=>minimatch(e,r))??[];return n===void 0?Promise.resolve({modified:false,result:e}):n.apply(e,t)}};function Dc(o){let e=typeof o=="string"?Ge(o,["jsx","typescript"]):o,t=[];return traverse(e,{ExportDeclaration:n=>{let{node:r}=n;if(g.isExportNamedDeclaration(r))if(r.specifiers.length>0)for(let i of r.specifiers)g.isExportSpecifier(i)?(!g.isIdentifier(i.exported)||i.exported.name!=="default")&&t.push(g.isIdentifier(i.exported)?i.exported.name:i.exported.value):g.isExportNamespaceSpecifier(i)&&g.isIdentifier(i.exported)&&t.push(i.exported.name);else if(g.isVariableDeclaration(r.declaration))for(let i of r.declaration.declarations)g.isVariableDeclarator(i)&&g.isIdentifier(i.id)&&t.push(i.id.name);else typeof r.declaration=="object"&&r.declaration!==null&&"id"in r.declaration&&g.isIdentifier(r.declaration.id)&&t.push(r.declaration.id.name);return n.skip()}}),t}async function Mc(o,e){let t=[];return traverse(o,{ImportDeclaration:n=>{let{node:r}=n,i=Promise.resolve(e(rd(r)));return i!==void 0&&t.push(i.then(a=>typeof a=="string"&&r.source.value!==a?(r.source.value=a,true):false)),n.skip()}}),(await Promise.all(t)).some(n=>n)}function rd(o){let e={names:[],source:o.source.value};for(let t of o.specifiers)g.isImportSpecifier(t)&&e.names.push(g.isIdentifier(t.imported)?t.imported.name:t.imported.value);return e}var ga=class{async apply(e,t){let n=await Mc(e,t.transformer);return {result:e,modified:n}}};var fa=class{constructor(...e){this.codemods=e;}async apply(e,t){let n=e,r=false;for(let i of this.codemods){let a=await i.apply(n,t);n=a.result,r=r||a.modified;}return {modified:r,result:n}}};var ya=class o{constructor(e,t){this.client=e,this.cache=t;}getHierarchy(e){return this.cache.get(o.getHierarchyKey(e),async()=>{let t=await this.resolveHierarchy(e);return await this.saveCache(e,t),t})}async resolveHierarchy(e){let{data:{organization:t}}=await this.client.execute(mp,e),n=t?.id,r=t?.workspace?.id,i=t?.workspace?.application?.id;return o.checkMissing("organization",e.organizationSlug,n),"workspaceSlug"in e?(o.checkMissing("workspace",e.workspaceSlug,r),"applicationSlug"in e?(o.checkMissing("application",e.applicationSlug,i),{organizationId:n,workspaceId:r,applicationId:i}):{organizationId:n,workspaceId:r}):{organizationId:n}}async saveCache(e,t){let n=[this.setCache({organizationSlug:e.organizationSlug},{organizationId:t.organizationId})];"workspaceId"in t&&"workspaceSlug"in e&&n.push(this.setCache({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug},{organizationId:t.organizationId,workspaceId:t.workspaceId})),"applicationId"in t&&"applicationSlug"in e&&n.push(this.setCache({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,applicationSlug:e.applicationSlug},{organizationId:t.organizationId,workspaceId:t.workspaceId,applicationId:t.applicationId})),await Promise.all(n);}setCache(e,t){return this.cache.set(o.getHierarchyKey(e),t)}static getHierarchyKey(e){let t=[`organization:${e.organizationSlug}`];return "workspaceSlug"in e&&t.push(`workspace:${e.workspaceSlug}`),"applicationSlug"in e&&t.push(`application${e.applicationSlug}`),t.join("/")}static checkMissing(e,t,n){if(n===void 0)throw new ne(`No ${e} found with slug "${t}".`,[],{reason:"not_found"})}};var ha=class{constructor(...e){this.registries=e;}async isRegistered(e){for(let t of this.registries)if(!await t.isRegistered(e))return false;return true}async register(e){for(let t of this.registries)await t.register(e);}async unregister(e){for(let t of this.registries)await t.unregister(e);}};var Sa=class o{constructor(e){this.registry=e;}isRegistered(e){return this.registry.isRegistered(e)}async register(e){try{await this.registry.register(e);}catch(t){o.handleError(t);}}async unregister(e){try{await this.registry.unregister(e);}catch(t){o.handleError(t);}}static handleError(e){if(!(e instanceof q))throw e}};var ba=class o{static{this.PREFERENCES=['user_pref("network.protocol-handler.expose.%protocol%", false);','user_pref("network.protocol-handler.external.%protocol%", true);'];}constructor({fileSystem:e,appDirectory:t}){this.fileSystem=e,this.profileDirectory=t;}static fromSystem(e,t){switch(e.getPlatform()){case "win32":{let n=e.getEnvValue("APPDATA")??e.getEnvValue("USERPROFILE");if(n===null)throw new q("Cannot determine the user profile directory.",{reason:"precondition"});return o.windows({fileSystem:t.fileSystem,appDataDirectory:n})}case "darwin":{let n=e.getEnvValue("HOME");if(n===null)throw new q("Cannot determine the user home directory.",{reason:"precondition"});return o.macOs({fileSystem:t.fileSystem,homeDirectory:n})}case "linux":{let n=e.getEnvValue("HOME");if(n===null)throw new q("Cannot determine the user home directory.",{reason:"precondition"});return o.linux({fileSystem:t.fileSystem,homeDirectory:n})}default:throw new q(`Platform \`${e.getPlatform()}\` is not supported.`,{reason:"not_supported"})}}static windows(e){return new o({fileSystem:e.fileSystem,appDirectory:e.fileSystem.joinPaths(e.appDataDirectory,"Mozilla","Firefox")})}static macOs(e){return new o({fileSystem:e.fileSystem,appDirectory:e.fileSystem.joinPaths(e.homeDirectory,"Library","Application Support","Firefox")})}static linux(e){return new o({fileSystem:e.fileSystem,appDirectory:e.fileSystem.joinPaths(e.homeDirectory,"snap","firefox","common",".mozilla","firefox")})}async isRegistered(e){let t=await this.getPreferencesFilePath();if(t===null)return false;let n=await this.fileSystem.readTextFile(t).catch(()=>"");for(let r of this.getPreferences(e))if(!n.includes(r))return false;return true}async register(e){if(await this.isRegistered(e.protocol))return;let t=await this.getPreferencesFilePath();if(t===null)throw new q("Cannot find the default profile file.",{reason:"precondition"});let r=`${await this.fileSystem.readTextFile(t).catch(()=>"")}
|
|
1841
1841
|
${this.getPreferences(e.protocol).join(`
|
|
1842
1842
|
`)}`;await this.fileSystem.writeTextFile(t,r,{overwrite:true});}async unregister(e){if(!await this.isRegistered(e))return;let t=await this.getPreferencesFilePath();if(t===null)return;let r=(await this.fileSystem.readTextFile(t).catch(()=>"")).split(`
|
|
1843
1843
|
`).filter(i=>!this.getPreferences(e).includes(i)).join(`
|
|
1844
|
-
`);await this.fileSystem.writeTextFile(t,r,{overwrite:true});}async getPreferencesFilePath(){let e=this.getPath("profiles.ini");if(!await this.fileSystem.exists(e))return null;let t=Object.values(parse$1(await this.fileSystem.readTextFile(e))),n=[],r=[];for(let a of t)a.Default!==void 0&&n.push(a.Default),a.Path!==void 0&&(a.Default==="1"?r.unshift(a.Path):r.push(a.Path));if(r.length===0)return null;let i=r[0];for(let a of r)if(n.includes(a)){i=a;break}return this.getPath(this.fileSystem.joinPaths(i,"user.js"))}getPath(e){return this.fileSystem.joinPaths(this.profileDirectory,e)}getPreferences(e){return o.PREFERENCES.map(t=>t.replace(/%protocol%/g,e))}};var Ia=class o{constructor(e){this.instances=new Map;this.configuration=e,this.skipPrompts=e.skipPrompts,this.initialDirectory=e.directories.current??e.process.getCurrentDirectory(),this.workingDirectory=new Zo(this.initialDirectory);}static{this.READ_ONLY_COMMANDS=new Set([Tn,rn,on,kt,At,tn,nn,pn,Qt]);}static fromDefaults(e){let t=ad("com.croct.cli"),n=new ta;return new o({program:e.program??(()=>{throw new d("CLI is running in standalone mode.")}),process:e.process??n,quiet:e.quiet??false,debug:e.debug??false,interactive:e.interactive??!sd.isCI,apiKey:e.apiKey,skipPrompts:e.skipPrompts??false,adminTokenDuration:e.adminTokenDuration??7*gt.LocalTime.SECONDS_PER_DAY,apiKeyTokenDuration:e.apiKeyTokenDuration??30*gt.LocalTime.SECONDS_PER_MINUTE,cliTokenDuration:e.cliTokenDuration??90*gt.LocalTime.SECONDS_PER_DAY,cliTokenFreshPeriod:e.cliTokenFreshPeriod??15*gt.LocalTime.SECONDS_PER_DAY,cliTokenIssuer:e.cliTokenIssuer??"croct.com",deepLinkProtocol:e.deepLinkProtocol??"croct",templateRegistryUrl:e.templateRegistryUrl??new URL("github:/croct-tech/templates/templates/registry.json5"),adminUrl:e.adminUrl??new URL("https://app.croct.com"),adminTokenParameter:e.adminTokenParameter??"accessToken",adminGraphqlEndpoint:e?.adminGraphqlEndpoint??new URL("https://app.croct.com/graphql"),directories:{current:e.directories?.current??n.getCurrentDirectory(),config:e.directories?.config??t.config(),cache:e.directories?.cache??t.cache(),data:e.directories?.data??t.data(),home:e.directories?.home??homedir()},verificationLinkDestination:{accountActivation:e.verificationLinkDestination?.accountActivation??"./cli",passwordReset:e.verificationLinkDestination?.passwordReset??"./cli"},emailSubject:{passwordReset:e.emailSubject?.passwordReset??"Forgot password",accountActivation:e.emailSubject?.accountActivation??"Welcome to Croct"}})}welcome(e){return this.execute(new Tn({packageManager:this.getNodePackageManager(),protocolRegistryProvider:this.getProtocolRegistryProvider(),cliPackage:"croct@latest",protocolHandler:{id:"com.croct.cli",name:"croct-cli",protocol:this.configuration.deepLinkProtocol},io:{input:this.getInput(),output:this.getOutput()}}),e)}open(e){return this.execute(new No({program:this.configuration.program,protocol:this.configuration.deepLinkProtocol,configurationProvider:this.getCliConfigurationStore(),workingDirectory:new Jo(this.configuration.process),fileSystem:this.getFileSystem(),io:{input:this.getInput(),output:this.getOutput()}}),e)}init(e){return this.execute(new nr({sdkProvider:this.getSdkProvider(),platformProvider:this.getPlatformProvider(),configurationManager:this.getConfigurationManager(),skipConfirmation:new Eo(new Rn(new An(new Pn({fileSystem:this.getFileSystem(),files:[".git"]})))),api:{user:this.getUserApi(),organization:this.getOrganizationApi(),workspace:this.getWorkspaceApi()},form:{organization:new sr({input:this.getFormInput(),output:this.getOutput(),userApi:this.getUserApi()}),workspace:new pr({input:this.getFormInput(),output:this.getOutput(),organizationApi:this.getOrganizationApi()}),application:new cr({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})},io:{input:this.getInput(),output:this.getOutput()}}),e)}install(e){return this.execute(new rn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),io:{input:this.getInput(),output:this.getOutput()}}),e)}upgrade(e){return this.execute(new on({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),form:{slotForm:new Je({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),componentForm:new Qe({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})},io:{input:this.getInput(),output:this.getOutput()}}),e)}addSlot(e){return this.execute(new kt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new Je({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}removeSlot(e){return this.execute(new tn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),slotForm:new Je({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}addComponent(e){return this.execute(new At({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new Qe({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}removeComponent(e){return this.execute(new nn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new Qe({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}login(e){return this.execute(new rr({authenticator:this.getAuthenticator()}),e)}logout(){return this.execute(new Qt({authenticator:this.getAuthenticator(),output:this.getOutput()}),{})}admin(e){return this.execute(new gr({output:this.getOutput(),pageForm:new Pr({input:this.getFormInput()}),configurationManager:this.getConfigurationManager(),userApi:this.getUserApi(),adminUrl:this.configuration.adminUrl,adminTokenParameter:this.configuration.adminTokenParameter,adminTokenDuration:this.configuration.adminTokenDuration}),e)}createTemplate(e){return this.execute(new pn({configurationManager:this.getConfigurationManager(),fileSystem:this.getFileSystem(),templateForm:new Wr({input:this.getFormInput(),form:{component:new Qe({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),slot:new Je({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),experience:new Vr({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),audience:new Ur({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})}}),io:{input:this.getInput(),output:this.getOutput()}}),e)}useTemplate(e){return this.execute(this.getUseTemplateCommand(),e)}async getTemplateOptions(e){let t=this.getUseTemplateCommand(),r=this.getOutput().notify("Loading template");try{return await t.getOptions(e)}finally{r.stop();}}getUseTemplateCommand(){return new qr({templateProvider:new Mt({provider:new mn(this.getTemplateProvider()),validator:new yn}),fileSystem:this.getFileSystem(),action:this.getImportAction(),io:{input:this.getInput(),output:this.getOutput()}})}createApiKey(e){return this.execute(new Go({fileSystem:this.getFileSystem(),configurationManager:this.getConfigurationManager(),api:{user:this.getUserApi(),workspace:this.getWorkspaceApi(),application:this.getApplicationApi()},io:{input:this.getFormInput(),output:this.getOutput()}}),e)}getFormInput(e){return this.getInput()??this.getNonInteractiveInput(e)}getNonInteractiveInput(e){return new En(new kr(e??{message:"Input is not available in non-interactive mode."}))}getInput(){if(this.configuration.interactive)return this.share(this.getInput,()=>{let e=this.getOutput(),t=new Gn({input:this.configuration.process.getStandardInput(),output:this.configuration.process.getStandardOutput(),onAbort:()=>e.exit(),onInteractionStart:()=>e.suspend(),onInteractionEnd:()=>e.resume()});return this.skipPrompts?new En(t):t})}getNonInteractiveOutput(e=false){let{configuration:t}=this;return new Jt({output:t.process.getStandardOutput(),formatter:this.getLogFormatter(),interactive:false,quiet:e,onExit:()=>t.process.exit(),linkOpener:async n=>{await Nc(n,{wait:true});}})}getHierarchicalLogger(){return this.share(this.getHierarchicalLogger,()=>new ca(this.getLogger()))}getLogger(){return this.share(this.getLogger,()=>{let e=new la(this.getOutput());return this.configuration.debug?e:new FilteredLogger(e,LogLevel.WARNING)})}getOutput(){return this.share(this.getOutput,()=>{let{configuration:e}=this;return new Jt({output:e.process.getStandardOutput(),formatter:this.getLogFormatter(),interactive:this.configuration.interactive,quiet:this.configuration.quiet,onExit:()=>e.process.exit(),linkOpener:async t=>{await Nc(t);}})})}getLogFormatter(){return this.share(this.getLogFormatter,()=>new Xo)}getTemplateProvider(){return this.share(this.getTemplateProvider,()=>{let e=n=>new Ye(...["template.json5","template.json"].map(r=>new Dt({dataProvider:n,registryProvider:new In([{pattern:/^(https:\/\/(?:www\.)?github.com\/[^/]+\/[^/]+)\/?$/,destination:`$1/blob/main/${r}`},{pattern:/^(.+?:\/*[^/]+(\/+[^/.]+|\/[^/]+(?=\/))*)\/*$/,destination:`$1/${r}`}])}))),t=this.traceProvider({provider:this.getHttpProvider()});return this.traceProvider({label:"TemplateProvider",provider:new gn({resourceCache:new AutoSaveCache(new InMemoryCache),errorCache:new InMemoryCache,provider:new Ye(new Dt({dataProvider:this.traceProvider({label:"ResourceProvider",provider:e(new mt(new Ye(this.traceProvider({provider:new cn(t)}),this.traceProvider({provider:new ln(t)}))))}),registryProvider:this.traceProvider({label:"NpmRegistryProvider",provider:new ia(new Mt({provider:oa.json(this.traceProvider({provider:this.getHttpProvider()})),validator:new aa}))})}),e(new mt(this.getFileProvider())))})})})}getFileProvider(){return this.share(this.getFileProvider,()=>{let e=this.traceProvider({provider:this.getHttpProvider()}),t=this.traceProvider({provider:new oi(this.getFileSystem())}),n=new Ye(t,this.traceProvider({provider:new cn(e)}),this.traceProvider({provider:new ln(e)}));return this.traceProvider({label:"FileProvider",provider:new Ye(t,this.traceProvider({provider:new Dt({baseUrl:new URL("./",this.configuration.templateRegistryUrl),dataProvider:this.traceProvider({label:"ResourceProvider",provider:n}),registryProvider:new _i({url:this.configuration.templateRegistryUrl,provider:this.traceProvider({label:"GlobalRegistryProvider",provider:new gn({errorCache:new InMemoryCache,resourceCache:new AutoSaveCache(new InMemoryCache),provider:new Mt({provider:new mn(new mt(n)),validator:new ci})})})})})}))})})}traceProvider({provider:e,label:t}){return new pa({label:t,provider:e,logger:this.getHierarchicalLogger()})}getImportAction(){return this.share(this.getImportAction,()=>{let e=this.getFileSystem(),t={run:new L({action:new Be(new Oe(()=>new Zi(t))),validator:new Ji}),try:new L({action:new Be(new Oe(()=>new Br(t.run))),validator:new fi}),test:new L({action:new Be(new Oe(()=>new Ri(t.run))),validator:new Oi}),repeat:new L({action:new Be(new Oe(()=>new Ro(t.run))),validator:new To}),print:new L({action:new Di,validator:new Ni}),fail:new L({action:new $i,validator:new zi}),define:new L({action:new Xi,validator:new Yi}),prompt:new L({action:new Ui,validator:new qi}),"change-directory":new L({action:new oo({fileSystem:e,rootDirectory:this.initialDirectory,currentDirectory:this.workingDirectory}),validator:new io}),"open-link":new L({action:new Qi,validator:new Bi}),"start-server":new L({action:new Hi({serverProvider:this.getServerProvider()}),validator:new Ki}),"stop-server":new L({action:new eo({serverProvider:this.getServerProvider()}),validator:new to}),"execute-package":new L({action:new so({packageManager:this.getPackageManager(),packageManagerProvider:this.getPackageManagerRegistry(),workingDirectory:this.workingDirectory,commandExecutor:this.getCommandExecutor(),commandTimeout:2*60*1e3,sourceChecker:{test:n=>n.protocol==="file:"||`${n}`.startsWith("https://github.com/croct-tech")}}),validator:new po}),"check-dependencies":new L({action:new ii({packageManager:this.getPackageManager()}),validator:new yi}),download:new L({action:new Hr({fileSystem:e,provider:this.getFileProvider(),codemod:new ma({codemods:{"**/*.{js,jsx,ts,tsx}":new fa(new ua({fileSystem:e,rootPath:this.workingDirectory,maxSearchDepth:10,importResolver:this.getNodeImportResolver(),importCodemod:new Ve({fileSystem:e,codemod:new je({languages:["typescript","jsx"],codemod:new ga})}),exportMatcher:{test:(n,{names:r})=>r.length===0?true:Dc(n).some(i=>r.includes(i))}}),new We(this.getJavaScriptFormatter()))}})}),validator:new hi}),"add-dependency":new L({action:new Gr({packageManager:this.getPackageManager()}),validator:new bi}),"locate-file":new L({action:new Kr({projectDirectory:this.workingDirectory,fileSystem:e,matcherProvider:{get:async n=>{let r=e.joinPaths(this.workingDirectory.get(),".gitignore"),i=Co.fromPattern(n);if(await e.exists(r)){let a=await e.readTextFile(r);return new ko(new An(Ao.fromPatterns(a)),i)}return i}}}),validator:new Ii}),"replace-file-content":new L({action:new Zr({fileSystem:e}),validator:new xi}),initialize:new L({action:new na({callback:()=>this.init({})}),validator:new ra}),"add-slot":new L({action:new Jr({installer:(n,r)=>{let i=this.getNonInteractiveOutput(true);return this.execute(new kt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new Je({input:this.getNonInteractiveInput(),output:i,workspaceApi:this.getWorkspaceApi()}),io:{output:i}}),{slots:n,example:r})}}),validator:new wi}),"add-component":new L({action:new Qr({installer:n=>{let r=this.getNonInteractiveOutput(true);return this.execute(new At({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new Qe({input:this.getNonInteractiveInput(),output:r,workspaceApi:this.getWorkspaceApi()}),io:{output:r}}),{components:n})}}),validator:new Pi}),"create-resource":new L({action:new ei({configurationManager:this.getConfigurationManager(),matcher:new ni({workspaceApi:this.getWorkspaceApi()}),api:{user:this.getUserApi(),workspace:this.getWorkspaceApi(),organization:this.getOrganizationApi()},mappingForm:new ti({input:this.getFormInput({message:"Some resource IDs are in use and interactive mode is required to assign new ones.",suggestions:["Retry in interactive mode"]}),workspaceApi:this.getWorkspaceApi()})}),validator:new Ci}),"format-code":new L({action:new Ai({formatter:this.getCodeFormatter()}),validator:new Ei}),import:new L({action:new Be(new Oe(()=>new mi({runner:t.run,templateProvider:new gi({evaluator:new li({functions:is}),validator:new yn,templateProvider:this.getTemplateProvider(),fileProvider:new mt(this.getFileProvider())}),variables:this.getActionVariables()}))),validator:new ki})};return t.import})}getActionVariables(){let e=t=>new URL(t,this.configuration.adminUrl).toString();return {project:{features:re.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{features:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),quotas:re.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{quotas:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),organization:re.transient(async()=>{let{organization:t}=await this.getConfigurationManager().load();return {slug:t,url:e(`organizations/${t}`)}}),workspace:re.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load();return {slug:n,url:e(`organizations/${t}/workspaces/${n}`)}}),application:re.transient(async()=>{let{organization:t,workspace:n,applications:r}=await this.getConfigurationManager().load(),i=`organizations/${t}/workspaces/${n}/applications/`;return {development:{slug:r.development,url:e(i+r.development)},production:{slug:r.production,url:e(i+r.production)}}}),path:{example:re.transient(async()=>(await this.getConfigurationManager().load()).paths.examples),component:re.transient(async()=>(await this.getConfigurationManager().load()).paths.components)},platform:re.transient(async()=>await this.getPlatformProvider().get()??"unknown"),server:re.transient(async()=>{let n=await this.getServerProvider().get();if(n===null)return null;try{let r=await n.getStatus();if(r.running)return {running:!0,url:r.url.toString()}}catch{}return {running:false}})}}}getHttpProvider(){return this.share(this.getHttpProvider,()=>new ri)}getAuthenticator(){return this.share(this.getAuthenticator,()=>{if(this.configuration.apiKey!==void 0)return new Ko({apiKey:this.configuration.apiKey,clock:this.getClock(),tokenDuration:this.configuration.apiKeyTokenDuration});let e=this.getFormInput(),t=new ur({input:e,output:this.getOutput(),userApi:this.getUserApi(true),form:{signIn:new mr({input:e,output:this.getOutput(),userApi:this.getUserApi(true),listener:this.getTokenListener(),tokenDuration:this.configuration.cliTokenDuration,emailLinkGenerator:{recovery:this.createEmailLinkGenerator(this.configuration.emailSubject.passwordReset),verification:this.createEmailLinkGenerator(this.configuration.emailSubject.accountActivation)},verificationLinkDestination:{accountActivation:this.configuration.verificationLinkDestination.accountActivation,passwordReset:this.configuration.verificationLinkDestination.passwordReset}}),signUp:new dr({input:e,output:this.getOutput(),userApi:this.getUserApi(true),listener:this.getTokenListener(),emailLinkGenerator:this.createEmailLinkGenerator(this.configuration.emailSubject.accountActivation),verificationLinkDestination:this.configuration.verificationLinkDestination.accountActivation})}}),n=this.getUserApi(true),r=new Qo({cacheKey:"token",cacheProvider:new Bo({clock:this.getClock(),clockSkewTolerance:5,tokenFreshPeriod:this.configuration.cliTokenFreshPeriod,tokenIssuer:()=>n.issueToken({duration:this.configuration.cliTokenDuration}),cacheProvider:new dn({fileSystem:this.getFileSystem(),directory:this.configuration.directories.config,useKeyAsFileName:true})}),authenticator:new Ar({default:this.configuration.interactive?t:new Cr({authenticator:t,instruction:{message:"Authentication required.",suggestions:["Run `login` to authenticate"],reason:"precondition"}}),credentials:t})});return this.configuration.interactive?new Uo({authenticator:r,invitationForm:new Vo({output:this.getOutput(),input:e,userApi:this.getUserApi(true)})}):r})}getSdk(){return this.share(this.getSdk,()=>{let e=new jt(this.getSdkProvider(),new Oe(()=>{throw new U("No suitable SDK detected.",{reason:"not_supported",suggestions:["Make sure you are running the command in the project root directory."]})}));return new wo(e)})}getSdkProvider(){return this.share(this.getSdkProvider,()=>{let e=this.getJavaScriptFormatter(),t=this.getFileSystem(),n=this.getNodeImportResolver(),r={projectDirectory:this.workingDirectory,packageManager:this.getNodePackageManager(),fileSystem:t,formatter:e,workspaceApi:this.getWorkspaceApi(),tsConfigLoader:this.getTsConfigLoader()},i=Symbol("unknown");return new Lt({discriminator:async()=>await this.getPlatformProvider().get()??i,mapping:{javascript:()=>new Bn({...r,bundlers:["vite","parcel","tsup","rollup"]}),react:()=>new Yn({...r,importResolver:n,codemod:{provider:new We(e,new Ve({fileSystem:this.getFileSystem(),codemod:new je({languages:["typescript","jsx"],codemod:new pt({fallbackToNamedExports:true,wrapper:{module:"@croct/plug-react",component:"CroctProvider"},targets:{variable:"children"}})})}))},bundlers:[{package:"react-scripts",prefix:"process.env.REACT_APP_"},{package:"vite",prefix:"import.meta.env.VITE_"},{package:"parcel",prefix:"process.env."}]}),nextjs:()=>{let a={appId:{type:"reference",path:["process","env","NEXT_PUBLIC_CROCT_APP_ID"]},debug:{type:"comparison",operator:"===",left:{type:"reference",path:["process","env","NEXT_PUBLIC_CROCT_DEBUG"]},right:{type:"literal",value:"true"}}};return new tr({...r,userApi:this.getUserApi(),applicationApi:this.getApplicationApi(),importResolver:n,codemod:{middleware:new We(e,new Ve({fileSystem:this.getFileSystem(),codemod:new je({languages:["typescript","jsx"],codemod:new br({import:{module:"@croct/plug-next/middleware",middlewareName:"middleware",middlewareFactoryName:"withCroct",configName:"config",matcherName:"matcher",matcherLocalName:"croctMatcher"}})})})),appRouterProvider:new We(e,new Ve({fileSystem:this.getFileSystem(),codemod:new je({languages:["typescript","jsx"],codemod:new pt({fallbackToNamedExports:false,fallbackCodemod:new Ir({provider:{component:"CroctProvider",module:"@croct/plug-next/CroctProvider"}}),wrapper:{module:"@croct/plug-next/CroctProvider",component:"CroctProvider"},targets:{variable:"children"}})})})),pageRouterProvider:new We(e,new Ve({fileSystem:this.getFileSystem(),codemod:new je({languages:["typescript","jsx"],codemod:new pt({fallbackToNamedExports:false,fallbackCodemod:new en({provider:{component:"CroctProvider",module:"@croct/plug-next/CroctProvider"}}),wrapper:{module:"@croct/plug-next/CroctProvider",component:"CroctProvider"},targets:{component:"Component"}})})})),fallbackProvider:new We(e,new Ve({fileSystem:this.getFileSystem(),codemod:new je({languages:["typescript","jsx"],codemod:new pt({fallbackToNamedExports:false,fallbackCodemod:new en({provider:{component:"CroctProvider",module:"@croct/plug-react",props:a}}),wrapper:{module:"@croct/plug-react",component:"CroctProvider",props:a},targets:{component:"Component"}})})}))}})},[i]:()=>null}})})}getCodeFormatter(){return this.share(this.getCodeFormatter,()=>{let e=Symbol("unknown");return new vo(new Lt({discriminator:async()=>await this.getPlatformProvider().get()??e,mapping:{javascript:()=>this.getJavaScriptFormatter(),react:()=>this.getJavaScriptFormatter(),nextjs:()=>this.getJavaScriptFormatter(),[e]:()=>{throw new U("No code formatter detected.",{reason:"not_supported",suggestions:["Make sure you are running the command in the project root directory."]})}}}))})}share(e,t){let n=this.instances.get(e);if(n===void 0){let r=t();return this.instances.set(e,r),r}return n}getPackageManagerRegistry(){return this.share(this.getPackageManagerRegistry,()=>new ho(new Map(Object.entries(this.getPackageManagers()))))}getPackageManagers(){return this.getNodePackageManagers()}getPackageManager(){return this.share(this.getPackageManager,()=>new wn(new jt(this.getNodePackageManagerProvider(),new Oe(()=>{throw new U("No package manager detected.",{reason:"not_supported",suggestions:["Make sure you are running the command in the project root directory.","Initialize your project and retry the command."]})}))))}getNodePackageManager(){return this.share(this.getNodePackageManager,()=>{let e=this.getNodePackageManagers();return new wn(new jt(this.getNodePackageManagerProvider(),new In(e.npm)))})}getNodePackageManagerProvider(){return this.share(this.getNodePackageManagerProvider,()=>{let e=this.getNodePackageManagers(),t=this.getFileSystem(),n={npm:["package-lock.json"],yarn:["yarn.lock"],bun:["bun.lock","bun.lockb"],pnpm:["pnpm-lock.yaml"]};return new kn(new Wo(new Wt({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new jo({process:this.configuration.process,variable:"npm_config_user_agent",value:new RegExp(`^${r}`)})}))}),new Wt({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new Rn(new Fo({packageManager:r,fileSystem:t,projectDirectory:this.workingDirectory}),new Pn({fileSystem:t,files:n[r]}))}))})),this.workingDirectory)})}getNodePackageManagers(){return this.share(this.getNodePackageManagers,()=>{let e=this.getFileSystem(),t={projectDirectory:this.workingDirectory,fileSystem:e,commandExecutor:this.getCommandExecutor(),executableLocator:this.getExecutableLocator()},n=new un,r={fileSystem:e,projectDirectory:this.workingDirectory,packageValidator:n};return {npm:new Xe({...r,agent:new co(t)}),yarn:new Xe({...r,agent:new lo(t)}),bun:new Xe({...r,agent:new uo(t)}),pnpm:new Xe({...r,agent:new mo(t)})}})}getNodeServerProvider(){return this.share(this.getNodeServerProvider,()=>new Li({packageManager:this.getNodePackageManager(),factory:this.getServerFactory(),parsers:[new Fi,new ji,new Wi,new Vi]}))}getServerProvider(){return this.share(this.getServerProvider,()=>{let e=Symbol("unknown");return new Lt({discriminator:async()=>await this.getPlatformProvider().get()??e,mapping:{javascript:()=>this.getNodeServerProvider().get(),react:()=>this.getNodeServerProvider().get(),nextjs:()=>this.getNodeServerProvider().get(),[e]:()=>null}})})}getServerFactory(){return this.share(this.getServerFactory,()=>new Po(new ro({commandExecutor:this.getCommandExecutor(),workingDirectory:this.workingDirectory,startupTimeout:2e4,startupCheckDelay:1500,lookupMaxPorts:30,lookupTimeout:2e3,processObserver:this.configuration.process})))}getJavaScriptFormatter(){return this.share(this.getJavaScriptFormatter,()=>new vr({commandExecutor:this.getCommandExecutor(),workingDirectory:this.workingDirectory,packageManager:this.getNodePackageManager(),fileSystem:this.getFileSystem(),timeout:1e4,tools:[{package:"eslint",bin:"eslint",args:e=>["--fix",...e]},{package:"prettier",args:e=>["--write",...e]},{package:"@biomejs/biome",bin:"biome",args:e=>["format","--write",...e]}]}))}getNodeImportResolver(){return this.share(this.getNodeImportResolver,()=>new fo({fileSystem:this.getFileSystem(),tsConfigLoader:this.getTsConfigLoader(),projectDirectory:this.workingDirectory}))}getTsConfigLoader(){return this.share(this.getTsConfigLoader,()=>new go({fileSystem:this.getFileSystem(),tsconfigValidator:new yo}))}getCommandExecutor(){return this.share(this.getCommandExecutor,()=>new xo)}getExecutableLocator(){return this.share(this.getExecutableLocator,()=>{let{process:e}=this.configuration;return new Lo({fileSystem:this.getFileSystem(),cache:new AutoSaveCache(new InMemoryCache),executablePaths:e.getEnvList("PATH")??[],executableExtensions:e.getEnvList("PATHEXT")??[]})})}getPlatformProvider(){return this.share(this.getPlatformProvider,()=>{let e=new Xe({projectDirectory:this.workingDirectory,packageValidator:new un,fileSystem:this.getFileSystem(),agent:new So});return new kn(new Wt({candidates:[{value:"nextjs",condition:new Cn({packageManager:e,dependencies:["next"]})},{value:"react",condition:new Cn({packageManager:e,dependencies:["react"]})},{value:"javascript",condition:new bo({packageManager:e})}]}),this.workingDirectory)})}getConfigurationManager(){return this.share(this.getConfigurationManager,()=>{let e=this.getOutput(),t=new ir({fileSystem:this.getFileSystem(),validator:new si,projectDirectory:this.workingDirectory});return new _o({workingDirectory:this.workingDirectory,store:this.getCliConfigurationStore(),manager:new Yr(this.configuration.interactive&&!this.isReadOnlyMode()?new wr({manager:t,initializer:{initialize:async()=>{await this.init({}),e.break();}}}):t)})})}getUserApi(e=false){return e?new Xt(this.getGraphqlClient(true)):this.share(this.getUserApi,()=>new Xt(this.getGraphqlClient()))}getOrganizationApi(){return this.share(this.getOrganizationApi,()=>new or(this.getGraphqlClient(),this.getHierarchyResolver()))}getWorkspaceApi(){return this.share(this.getWorkspaceApi,()=>new ar(this.getGraphqlClient(),this.getHierarchyResolver()))}getApplicationApi(){return this.share(this.getApplicationApi,()=>new lr(this.getGraphqlClient(),this.getHierarchyResolver()))}getHierarchyResolver(){return this.share(this.getHierarchyResolver,()=>{let e=this.getFileSystem();return new ya(this.getGraphqlClient(),AdaptedCache.transformValues(new dn({fileSystem:e,directory:e.joinPaths(this.configuration.directories.cache,"hierarchy")}),AdaptedCache.jsonSerializer(),AdaptedCache.jsonDeserializer()))})}getGraphqlClient(e=false){return e?new Bt({endpoint:this.configuration.adminGraphqlEndpoint,tokenProvider:{getToken:()=>this.getAuthenticator().getToken()}}):this.share(this.getGraphqlClient,()=>{let t=this.getAuthenticator();return new Bt({endpoint:this.configuration.adminGraphqlEndpoint,tokenProvider:{getToken:async()=>await t.getToken()??t.login({method:"default"})}})})}getTokenListener(){return this.share(this.getTokenListener,()=>{let{configuration:e}=this;return new Or({platform:e.process.getPlatform(),commandExecutor:this.getCommandExecutor(),timeout:2e3,listener:new Yo({api:this.getUserApi(true),pollingInterval:1e3})})})}getFileSystem(){return this.share(this.getFileSystem,()=>new Tr({workingDirectory:this.workingDirectory,defaultEncoding:"utf-8"}))}createEmailLinkGenerator(e){let t=this.getEmailLinkGenerator(),n=this.getClock();return r=>t.generate({recipient:r,sender:"croct.com",subject:e,timestamp:gt.Instant.now(n).getSeconds()})}getEmailLinkGenerator(){return this.share(this.getEmailLinkGenerator,()=>new Dr({detector:new Mr(new Nr,new $r),templates:{google:new zr,icloud:new _r,microsoft:new Lr,proton:new Fr,yahoo:new jr}}))}getClock(){return $c.SystemClock.UTC}getProtocolRegistryProvider(){return this.share(this.getProtocolRegistryProvider,()=>new Oe(()=>{let e=this.getFileSystem(),{process:t}=this.configuration;switch(t.getPlatform()){case "darwin":return new ha(new Oo({fileSystem:e,appDirectory:e.joinPaths(this.configuration.directories.data,"apps"),commandExecutor:this.getCommandExecutor()}),new Sa(ba.macOs({fileSystem:e,homeDirectory:this.configuration.directories.home})));case "win32":return new Do({commandExecutor:this.getCommandExecutor()});case "linux":return new Mo({fileSystem:e,homeDirectory:this.configuration.directories.home,commandExecutor:this.getCommandExecutor()});default:return null}}))}getCliConfigurationStore(){return this.share(this.getCliConfigurationStore,()=>{let e=this.getFileSystem();return new Ho({fileSystem:e,store:new qo({fileSystem:e,validator:new zo,filePath:e.joinPaths(this.configuration.directories.config,"config.json")})})})}async execute(e,t){if(this.isReadOnlyMode()&&!o.READ_ONLY_COMMANDS.has(e.constructor))return this.reportError(new d("This command does not support API key authentication.",{reason:"precondition",suggestions:["Run the command without specifying an API key."]}));try{await e.execute(t);}catch(n){let r=o.handleError(n);return n instanceof Error&&r instanceof Error&&(r.stack=n.stack),this.reportError(r)}}isReadOnlyMode(){return this.configuration.apiKey!==void 0}reportError(e){let t=this.getOutput();return t.report(o.handleError(e)),t.exit()}static handleError(e){switch(true){case e instanceof ne:if(e.isAccessDenied())return new d("Your user lacks the necessary permissions to complete this operation.",{reason:"access_denied",details:e.problems.map(t=>t.detail??t.title),suggestions:["Contact your organization or workspace administrator for assistance."],cause:e});break;case e instanceof I:if(e.tracing.length>0){let t=e.tracing.map(({name:n,source:r},i)=>{let a=r!==void 0?` at ${o.getSourceLocation(r)}`:"";return `${" ".repeat(i+1)}\u21B3 \`${n}\`${a}`}).join(`
|
|
1844
|
+
`);await this.fileSystem.writeTextFile(t,r,{overwrite:true});}async getPreferencesFilePath(){let e=this.getPath("profiles.ini");if(!await this.fileSystem.exists(e))return null;let t=Object.values(parse$1(await this.fileSystem.readTextFile(e))),n=[],r=[];for(let a of t)a.Default!==void 0&&n.push(a.Default),a.Path!==void 0&&(a.Default==="1"?r.unshift(a.Path):r.push(a.Path));if(r.length===0)return null;let i=r[0];for(let a of r)if(n.includes(a)){i=a;break}return this.getPath(this.fileSystem.joinPaths(i,"user.js"))}getPath(e){return this.fileSystem.joinPaths(this.profileDirectory,e)}getPreferences(e){return o.PREFERENCES.map(t=>t.replace(/%protocol%/g,e))}};var Ia=class o{constructor(e){this.instances=new Map;this.configuration=e,this.skipPrompts=e.skipPrompts,this.initialDirectory=e.directories.current??e.process.getCurrentDirectory(),this.workingDirectory=new Zo(this.initialDirectory);}static{this.READ_ONLY_COMMANDS=new Set([Tn,rn,on,kt,At,tn,nn,pn,Qt]);}static fromDefaults(e){let t=ad("com.croct.cli"),n=new ta;return new o({program:e.program??(()=>{throw new d("CLI is running in standalone mode.")}),process:e.process??n,quiet:e.quiet??false,debug:e.debug??false,interactive:e.interactive??!sd.isCI,apiKey:e.apiKey,skipPrompts:e.skipPrompts??false,adminTokenDuration:e.adminTokenDuration??7*gt.LocalTime.SECONDS_PER_DAY,apiKeyTokenDuration:e.apiKeyTokenDuration??30*gt.LocalTime.SECONDS_PER_MINUTE,cliTokenDuration:e.cliTokenDuration??90*gt.LocalTime.SECONDS_PER_DAY,cliTokenFreshPeriod:e.cliTokenFreshPeriod??15*gt.LocalTime.SECONDS_PER_DAY,cliTokenIssuer:e.cliTokenIssuer??"croct.com",deepLinkProtocol:e.deepLinkProtocol??"croct",templateRegistryUrl:e.templateRegistryUrl??new URL("github:/croct-tech/templates/templates/registry.json5"),adminUrl:e.adminUrl??new URL("https://app.croct.com"),adminTokenParameter:e.adminTokenParameter??"accessToken",adminGraphqlEndpoint:e?.adminGraphqlEndpoint??new URL("https://app.croct.com/graphql"),directories:{current:e.directories?.current??n.getCurrentDirectory(),config:e.directories?.config??t.config(),cache:e.directories?.cache??t.cache(),data:e.directories?.data??t.data(),home:e.directories?.home??homedir()},verificationLinkDestination:{accountActivation:e.verificationLinkDestination?.accountActivation??"./cli",passwordReset:e.verificationLinkDestination?.passwordReset??"./cli"},emailSubject:{passwordReset:e.emailSubject?.passwordReset??"Forgot password",accountActivation:e.emailSubject?.accountActivation??"Welcome to Croct"}})}welcome(e){return this.execute(new Tn({packageManager:this.getNodePackageManager(),protocolRegistryProvider:this.getProtocolRegistryProvider(),cliPackage:"croct@latest",protocolHandler:{id:"com.croct.cli",name:"croct-cli",protocol:this.configuration.deepLinkProtocol},io:{input:this.getInput(),output:this.getOutput()}}),e)}open(e){return this.execute(new No({program:this.configuration.program,protocol:this.configuration.deepLinkProtocol,configurationProvider:this.getCliConfigurationStore(),workingDirectory:new Jo(this.configuration.process),fileSystem:this.getFileSystem(),io:{input:this.getInput(),output:this.getOutput()}}),e)}init(e){return this.execute(new nr({sdkProvider:this.getSdkProvider(),platformProvider:this.getPlatformProvider(),configurationManager:this.getConfigurationManager(),skipConfirmation:new Eo(new Rn(new An(new Pn({fileSystem:this.getFileSystem(),files:[".git"]})))),api:{user:this.getUserApi(),organization:this.getOrganizationApi(),workspace:this.getWorkspaceApi()},form:{organization:new sr({input:this.getFormInput(),output:this.getOutput(),userApi:this.getUserApi()}),workspace:new pr({input:this.getFormInput(),output:this.getOutput(),organizationApi:this.getOrganizationApi()}),application:new cr({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})},io:{input:this.getInput(),output:this.getOutput()}}),e)}install(e){return this.execute(new rn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),io:{input:this.getInput(),output:this.getOutput()}}),e)}upgrade(e){return this.execute(new on({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),form:{slotForm:new Je({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),componentForm:new Qe({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})},io:{input:this.getInput(),output:this.getOutput()}}),e)}addSlot(e){return this.execute(new kt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new Je({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}removeSlot(e){return this.execute(new tn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),slotForm:new Je({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}addComponent(e){return this.execute(new At({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new Qe({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}removeComponent(e){return this.execute(new nn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new Qe({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}login(e){return this.execute(new rr({authenticator:this.getAuthenticator()}),e)}logout(){return this.execute(new Qt({authenticator:this.getAuthenticator(),output:this.getOutput()}),{})}admin(e){return this.execute(new gr({output:this.getOutput(),pageForm:new Pr({input:this.getFormInput()}),configurationManager:this.getConfigurationManager(),userApi:this.getUserApi(),adminUrl:this.configuration.adminUrl,adminTokenParameter:this.configuration.adminTokenParameter,adminTokenDuration:this.configuration.adminTokenDuration}),e)}createTemplate(e){return this.execute(new pn({configurationManager:this.getConfigurationManager(),fileSystem:this.getFileSystem(),templateForm:new Wr({input:this.getFormInput(),form:{component:new Qe({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),slot:new Je({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),experience:new Vr({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),audience:new Ur({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})}}),io:{input:this.getInput(),output:this.getOutput()}}),e)}useTemplate(e){return this.execute(this.getUseTemplateCommand(),e)}async getTemplateOptions(e){let t=this.getUseTemplateCommand(),r=this.getOutput().notify("Loading template");try{return await t.getOptions(e)}finally{r.stop();}}getUseTemplateCommand(){return new qr({templateProvider:new Mt({provider:new mn(this.getTemplateProvider()),validator:new yn}),fileSystem:this.getFileSystem(),action:this.getImportAction(),io:{input:this.getInput(),output:this.getOutput()}})}createApiKey(e){return this.execute(new Go({fileSystem:this.getFileSystem(),configurationManager:this.getConfigurationManager(),api:{user:this.getUserApi(),workspace:this.getWorkspaceApi(),application:this.getApplicationApi()},io:{input:this.getFormInput(),output:this.getOutput()}}),e)}getFormInput(e){return this.getInput()??this.getNonInteractiveInput(e)}getNonInteractiveInput(e){return new En(new kr(e??{message:"Input is not available in non-interactive mode."}))}getInput(){if(this.configuration.interactive)return this.share(this.getInput,()=>{let e=this.getOutput(),t=new Gn({input:this.configuration.process.getStandardInput(),output:this.configuration.process.getStandardOutput(),onAbort:()=>e.exit(),onInteractionStart:()=>e.suspend(),onInteractionEnd:()=>e.resume()});return this.skipPrompts?new En(t):t})}getNonInteractiveOutput(e=false){let{configuration:t}=this;return new Jt({output:t.process.getStandardOutput(),formatter:this.getLogFormatter(),interactive:false,quiet:e,onExit:()=>t.process.exit(),linkOpener:async n=>{await Nc(n,{wait:true});}})}getHierarchicalLogger(){return this.share(this.getHierarchicalLogger,()=>new ca(this.getLogger()))}getLogger(){return this.share(this.getLogger,()=>{let e=new la(this.getOutput());return this.configuration.debug?e:new FilteredLogger(e,LogLevel.WARNING)})}getOutput(){return this.share(this.getOutput,()=>{let{configuration:e}=this;return new Jt({output:e.process.getStandardOutput(),formatter:this.getLogFormatter(),interactive:this.configuration.interactive,quiet:this.configuration.quiet,onExit:()=>e.process.exit(),linkOpener:async t=>{await Nc(t);}})})}getLogFormatter(){return this.share(this.getLogFormatter,()=>new Xo)}getTemplateProvider(){return this.share(this.getTemplateProvider,()=>{let e=n=>new Ye(...["template.json5","template.json"].map(r=>new Dt({dataProvider:n,registryProvider:new In([{pattern:/^(https:\/\/(?:www\.)?github.com\/[^/]+\/[^/]+)\/?$/,destination:`$1/blob/main/${r}`},{pattern:/^(.+?:\/*[^/]+(\/+[^/.]+|\/[^/]+(?=\/))*)\/*$/,destination:`$1/${r}`}])}))),t=this.traceProvider({provider:this.getHttpProvider()});return this.traceProvider({label:"TemplateProvider",provider:new gn({resourceCache:new AutoSaveCache(new InMemoryCache),errorCache:new InMemoryCache,provider:new Ye(new Dt({dataProvider:this.traceProvider({label:"ResourceProvider",provider:e(new mt(new Ye(this.traceProvider({provider:new cn(t)}),this.traceProvider({provider:new ln(t)}))))}),registryProvider:this.traceProvider({label:"NpmRegistryProvider",provider:new ia(new Mt({provider:oa.json(this.traceProvider({provider:this.getHttpProvider()})),validator:new aa}))})}),e(new mt(this.getFileProvider())))})})})}getFileProvider(){return this.share(this.getFileProvider,()=>{let e=this.traceProvider({provider:this.getHttpProvider()}),t=this.traceProvider({provider:new oi(this.getFileSystem())}),n=new Ye(t,this.traceProvider({provider:new cn(e)}),this.traceProvider({provider:new ln(e)}));return this.traceProvider({label:"FileProvider",provider:new Ye(t,this.traceProvider({provider:new Dt({baseUrl:new URL("./",this.configuration.templateRegistryUrl),dataProvider:this.traceProvider({label:"ResourceProvider",provider:n}),registryProvider:new _i({url:this.configuration.templateRegistryUrl,provider:this.traceProvider({label:"GlobalRegistryProvider",provider:new gn({errorCache:new InMemoryCache,resourceCache:new AutoSaveCache(new InMemoryCache),provider:new Mt({provider:new mn(new mt(n)),validator:new ci})})})})})}))})})}traceProvider({provider:e,label:t}){return new pa({label:t,provider:e,logger:this.getHierarchicalLogger()})}getImportAction(){return this.share(this.getImportAction,()=>{let e=this.getFileSystem(),t={run:new L({action:new Be(new Oe(()=>new Zi(t))),validator:new Ji}),try:new L({action:new Be(new Oe(()=>new Br(t.run))),validator:new fi}),test:new L({action:new Be(new Oe(()=>new Ri(t.run))),validator:new Oi}),repeat:new L({action:new Be(new Oe(()=>new Ro(t.run))),validator:new To}),print:new L({action:new Di,validator:new Ni}),fail:new L({action:new $i,validator:new zi}),define:new L({action:new Xi,validator:new Yi}),prompt:new L({action:new Ui,validator:new qi}),"change-directory":new L({action:new oo({fileSystem:e,rootDirectory:this.initialDirectory,currentDirectory:this.workingDirectory}),validator:new io}),"open-link":new L({action:new Qi,validator:new Bi}),"start-server":new L({action:new Hi({serverProvider:this.getServerProvider()}),validator:new Ki}),"stop-server":new L({action:new eo({serverProvider:this.getServerProvider()}),validator:new to}),"execute-package":new L({action:new so({packageManager:this.getPackageManager(),packageManagerProvider:this.getPackageManagerRegistry(),workingDirectory:this.workingDirectory,commandExecutor:this.getCommandExecutor(),commandTimeout:2*60*1e3,sourceChecker:{test:n=>n.protocol==="file:"||`${n}`.startsWith("https://github.com/croct-tech")}}),validator:new po}),"check-dependencies":new L({action:new ii({packageManager:this.getPackageManager()}),validator:new yi}),download:new L({action:new Hr({fileSystem:e,provider:this.getFileProvider(),codemod:new ma({codemods:{"**/*.{js,jsx,ts,tsx}":new fa(new ua({fileSystem:e,rootPath:this.workingDirectory,maxSearchDepth:10,importResolver:this.getNodeImportResolver(),importCodemod:new Ve({fileSystem:e,codemod:new je({languages:["typescript","jsx"],codemod:new ga})}),exportMatcher:{test:(n,{names:r})=>r.length===0?true:Dc(n).some(i=>r.includes(i))}}),new We(this.getJavaScriptFormatter()))}})}),validator:new hi}),"add-dependency":new L({action:new Gr({packageManager:this.getPackageManager()}),validator:new bi}),"locate-file":new L({action:new Kr({projectDirectory:this.workingDirectory,fileSystem:e,matcherProvider:{get:async n=>{let r=e.joinPaths(this.workingDirectory.get(),".gitignore"),i=Co.fromPattern(n);if(await e.exists(r)){let a=await e.readTextFile(r);return new ko(new An(Ao.fromPatterns(a)),i)}return i}}}),validator:new Ii}),"replace-file-content":new L({action:new Zr({fileSystem:e}),validator:new xi}),initialize:new L({action:new na({callback:()=>this.init({})}),validator:new ra}),"add-slot":new L({action:new Jr({installer:(n,r)=>{let i=this.getNonInteractiveOutput(true);return this.execute(new kt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new Je({input:this.getNonInteractiveInput(),output:i,workspaceApi:this.getWorkspaceApi()}),io:{output:i}}),{slots:n,example:r})}}),validator:new wi}),"add-component":new L({action:new Qr({installer:n=>{let r=this.getNonInteractiveOutput(true);return this.execute(new At({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new Qe({input:this.getNonInteractiveInput(),output:r,workspaceApi:this.getWorkspaceApi()}),io:{output:r}}),{components:n})}}),validator:new Pi}),"create-resource":new L({action:new ei({configurationManager:this.getConfigurationManager(),matcher:new ni({workspaceApi:this.getWorkspaceApi()}),api:{user:this.getUserApi(),workspace:this.getWorkspaceApi(),organization:this.getOrganizationApi()},mappingForm:new ti({input:this.getFormInput({message:"Some resource IDs are in use and interactive mode is required to assign new ones.",suggestions:["Retry in interactive mode"]}),workspaceApi:this.getWorkspaceApi()})}),validator:new Ci}),"format-code":new L({action:new Ai({formatter:this.getCodeFormatter()}),validator:new Ei}),import:new L({action:new Be(new Oe(()=>new mi({runner:t.run,templateProvider:new gi({evaluator:new li({functions:is}),validator:new yn,templateProvider:this.getTemplateProvider(),fileProvider:new mt(this.getFileProvider())}),variables:this.getActionVariables()}))),validator:new ki})};return t.import})}getActionVariables(){let e=t=>new URL(t,this.configuration.adminUrl).toString();return {project:{features:re.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{features:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),quotas:re.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{quotas:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),organization:re.transient(async()=>{let{organization:t}=await this.getConfigurationManager().load();return {slug:t,url:e(`organizations/${t}`)}}),workspace:re.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load();return {slug:n,url:e(`organizations/${t}/workspaces/${n}`)}}),application:re.transient(async()=>{let{organization:t,workspace:n,applications:r}=await this.getConfigurationManager().load(),i=`organizations/${t}/workspaces/${n}/applications/`;return {development:{slug:r.development,url:e(i+r.development)},production:{slug:r.production,url:e(i+r.production)}}}),path:{example:re.transient(async()=>(await this.getConfigurationManager().load()).paths.examples),component:re.transient(async()=>(await this.getConfigurationManager().load()).paths.components)},platform:re.transient(async()=>await this.getPlatformProvider().get()??"unknown"),server:re.transient(async()=>{let n=await this.getServerProvider().get();if(n===null)return null;try{let r=await n.getStatus();if(r.running)return {running:!0,url:r.url.toString()}}catch{}return {running:false}})}}}getHttpProvider(){return this.share(this.getHttpProvider,()=>new ri)}getAuthenticator(){return this.share(this.getAuthenticator,()=>{if(this.configuration.apiKey!==void 0)return new Ko({apiKey:this.configuration.apiKey,clock:this.getClock(),tokenDuration:this.configuration.apiKeyTokenDuration});let e=this.getFormInput(),t=new ur({input:e,output:this.getOutput(),userApi:this.getUserApi(true),form:{signIn:new mr({input:e,output:this.getOutput(),userApi:this.getUserApi(true),listener:this.getTokenListener(),tokenDuration:this.configuration.cliTokenDuration,emailLinkGenerator:{recovery:this.createEmailLinkGenerator(this.configuration.emailSubject.passwordReset),verification:this.createEmailLinkGenerator(this.configuration.emailSubject.accountActivation)},verificationLinkDestination:{accountActivation:this.configuration.verificationLinkDestination.accountActivation,passwordReset:this.configuration.verificationLinkDestination.passwordReset}}),signUp:new dr({input:e,output:this.getOutput(),userApi:this.getUserApi(true),listener:this.getTokenListener(),emailLinkGenerator:this.createEmailLinkGenerator(this.configuration.emailSubject.accountActivation),verificationLinkDestination:this.configuration.verificationLinkDestination.accountActivation})}}),n=this.getUserApi(true),r=new Qo({cacheKey:"token",cacheProvider:new Bo({clock:this.getClock(),clockSkewTolerance:5,tokenFreshPeriod:this.configuration.cliTokenFreshPeriod,tokenIssuer:()=>n.issueToken({duration:this.configuration.cliTokenDuration}),cacheProvider:new dn({fileSystem:this.getFileSystem(),directory:this.configuration.directories.config,useKeyAsFileName:true})}),authenticator:new Ar({default:this.configuration.interactive?t:new Cr({authenticator:t,instruction:{message:"Authentication required.",suggestions:["Run `login` to authenticate"],reason:"precondition"}}),credentials:t})});return this.configuration.interactive?new Uo({authenticator:r,invitationForm:new Vo({output:this.getOutput(),input:e,userApi:this.getUserApi(true)})}):r})}getSdk(){return this.share(this.getSdk,()=>{let e=new jt(this.getSdkProvider(),new Oe(()=>{throw new U("No suitable SDK detected.",{reason:"not_supported",suggestions:["Make sure you are running the command in the project root directory."]})}));return new wo(e)})}getSdkProvider(){return this.share(this.getSdkProvider,()=>{let e=this.getJavaScriptFormatter(),t=this.getFileSystem(),n=this.getNodeImportResolver(),r={projectDirectory:this.workingDirectory,packageManager:this.getNodePackageManager(),fileSystem:t,formatter:e,workspaceApi:this.getWorkspaceApi(),tsConfigLoader:this.getTsConfigLoader()},i=Symbol("unknown");return new Lt({discriminator:async()=>await this.getPlatformProvider().get()??i,mapping:{javascript:()=>new Bn({...r,bundlers:["vite","parcel","tsup","rollup"]}),react:()=>new Yn({...r,importResolver:n,codemod:{provider:new We(e,new Ve({fileSystem:this.getFileSystem(),codemod:new je({languages:["typescript","jsx"],codemod:new pt({fallbackToNamedExports:true,wrapper:{module:"@croct/plug-react",component:"CroctProvider"},targets:{variable:"children"}})})}))},bundlers:[{package:"react-scripts",prefix:"process.env.REACT_APP_"},{package:"vite",prefix:"import.meta.env.VITE_"},{package:"parcel",prefix:"process.env."}]}),nextjs:()=>{let a={appId:{type:"reference",path:["process","env","NEXT_PUBLIC_CROCT_APP_ID"]},debug:{type:"comparison",operator:"===",left:{type:"reference",path:["process","env","NEXT_PUBLIC_CROCT_DEBUG"]},right:{type:"literal",value:"true"}}};return new tr({...r,userApi:this.getUserApi(),applicationApi:this.getApplicationApi(),importResolver:n,codemod:{middleware:new We(e,new Ve({fileSystem:this.getFileSystem(),codemod:new je({languages:["typescript","jsx"],codemod:new br({import:{module:"@croct/plug-next/middleware",middlewareName:"middleware",middlewareFactoryName:"withCroct",configName:"config",matcherName:"matcher",matcherLocalName:"croctMatcher"}})})})),appRouterProvider:new We(e,new Ve({fileSystem:this.getFileSystem(),codemod:new je({languages:["typescript","jsx"],codemod:new pt({fallbackToNamedExports:false,fallbackCodemod:new Ir({provider:{component:"CroctProvider",module:"@croct/plug-next/CroctProvider"}}),wrapper:{module:"@croct/plug-next/CroctProvider",component:"CroctProvider"},targets:{variable:"children"}})})})),pageRouterProvider:new We(e,new Ve({fileSystem:this.getFileSystem(),codemod:new je({languages:["typescript","jsx"],codemod:new pt({fallbackToNamedExports:false,fallbackCodemod:new en({provider:{component:"CroctProvider",module:"@croct/plug-next/CroctProvider"}}),wrapper:{module:"@croct/plug-next/CroctProvider",component:"CroctProvider"},targets:{component:"Component"}})})})),fallbackProvider:new We(e,new Ve({fileSystem:this.getFileSystem(),codemod:new je({languages:["typescript","jsx"],codemod:new pt({fallbackToNamedExports:false,fallbackCodemod:new en({provider:{component:"CroctProvider",module:"@croct/plug-react",props:a}}),wrapper:{module:"@croct/plug-react",component:"CroctProvider",props:a},targets:{component:"Component"}})})}))}})},[i]:()=>null}})})}getCodeFormatter(){return this.share(this.getCodeFormatter,()=>{let e=Symbol("unknown");return new vo(new Lt({discriminator:async()=>await this.getPlatformProvider().get()??e,mapping:{javascript:()=>this.getJavaScriptFormatter(),react:()=>this.getJavaScriptFormatter(),nextjs:()=>this.getJavaScriptFormatter(),[e]:()=>{throw new U("No code formatter detected.",{reason:"not_supported",suggestions:["Make sure you are running the command in the project root directory."]})}}}))})}share(e,t){let n=this.instances.get(e);if(n===void 0){let r=t();return this.instances.set(e,r),r}return n}getPackageManagerRegistry(){return this.share(this.getPackageManagerRegistry,()=>new ho(new Map(Object.entries(this.getPackageManagers()))))}getPackageManagers(){return this.getNodePackageManagers()}getPackageManager(){return this.share(this.getPackageManager,()=>new wn(new jt(this.getNodePackageManagerProvider(),new Oe(()=>{throw new U("No package manager detected.",{reason:"not_supported",suggestions:["Make sure you are running the command in the project root directory.","Initialize your project and retry the command."]})}))))}getNodePackageManager(){return this.share(this.getNodePackageManager,()=>{let e=this.getNodePackageManagers();return new wn(new jt(this.getNodePackageManagerProvider(),new In(e.npm)))})}getNodePackageManagerProvider(){return this.share(this.getNodePackageManagerProvider,()=>{let e=this.getNodePackageManagers(),t=this.getFileSystem(),n={npm:["package-lock.json"],yarn:["yarn.lock"],bun:["bun.lock","bun.lockb"],pnpm:["pnpm-lock.yaml"]};return new kn(new Wo(new Wt({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new jo({process:this.configuration.process,variable:"npm_config_user_agent",value:new RegExp(`^${r}`)})}))}),new Wt({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new Rn(new Fo({packageManager:r,fileSystem:t,projectDirectory:this.workingDirectory}),new Pn({fileSystem:t,files:n[r]}))}))})),this.workingDirectory)})}getNodePackageManagers(){return this.share(this.getNodePackageManagers,()=>{let e=this.getFileSystem(),t={projectDirectory:this.workingDirectory,fileSystem:e,commandExecutor:this.getCommandExecutor(),executableLocator:this.getExecutableLocator()},n=new un,r={fileSystem:e,projectDirectory:this.workingDirectory,packageValidator:n};return {npm:new Xe({...r,agent:new co(t)}),yarn:new Xe({...r,agent:new lo(t)}),bun:new Xe({...r,agent:new uo(t)}),pnpm:new Xe({...r,agent:new mo(t)})}})}getNodeServerProvider(){return this.share(this.getNodeServerProvider,()=>new Li({packageManager:this.getNodePackageManager(),factory:this.getServerFactory(),parsers:[new Fi,new ji,new Wi,new Vi]}))}getServerProvider(){return this.share(this.getServerProvider,()=>{let e=Symbol("unknown");return new Lt({discriminator:async()=>await this.getPlatformProvider().get()??e,mapping:{javascript:()=>this.getNodeServerProvider().get(),react:()=>this.getNodeServerProvider().get(),nextjs:()=>this.getNodeServerProvider().get(),[e]:()=>null}})})}getServerFactory(){return this.share(this.getServerFactory,()=>new Po(new ro({commandExecutor:this.getCommandExecutor(),workingDirectory:this.workingDirectory,startupTimeout:2e4,startupCheckDelay:1500,lookupMaxPorts:30,lookupTimeout:2e3,processObserver:this.configuration.process})))}getJavaScriptFormatter(){return this.share(this.getJavaScriptFormatter,()=>new vr({commandExecutor:this.getCommandExecutor(),workingDirectory:this.workingDirectory,packageManager:this.getNodePackageManager(),fileSystem:this.getFileSystem(),timeout:1e4,tools:[{package:"eslint",bin:"eslint",args:e=>["--fix",...e]},{package:"prettier",args:e=>["--write",...e]},{package:"@biomejs/biome",bin:"biome",args:e=>["format","--write",...e]}]}))}getNodeImportResolver(){return this.share(this.getNodeImportResolver,()=>new fo({fileSystem:this.getFileSystem(),tsConfigLoader:this.getTsConfigLoader(),projectDirectory:this.workingDirectory}))}getTsConfigLoader(){return this.share(this.getTsConfigLoader,()=>new go({fileSystem:this.getFileSystem(),tsconfigValidator:new yo}))}getCommandExecutor(){return this.share(this.getCommandExecutor,()=>new xo)}getExecutableLocator(){return this.share(this.getExecutableLocator,()=>{let{process:e}=this.configuration;return new Lo({fileSystem:this.getFileSystem(),cache:new AutoSaveCache(new InMemoryCache),executablePaths:e.getEnvList("PATH")??[],executableExtensions:e.getEnvList("PATHEXT")??[]})})}getPlatformProvider(){return this.share(this.getPlatformProvider,()=>{let e=new Xe({projectDirectory:this.workingDirectory,packageValidator:new un,fileSystem:this.getFileSystem(),agent:new So});return new kn(new Wt({candidates:[{value:"nextjs",condition:new Cn({packageManager:e,dependencies:["next"]})},{value:"react",condition:new Cn({packageManager:e,dependencies:["react"]})},{value:"javascript",condition:new bo({packageManager:e})}]}),this.workingDirectory)})}getConfigurationManager(){return this.share(this.getConfigurationManager,()=>{let e=this.getOutput(),t=new ir({fileSystem:this.getFileSystem(),validator:new si,projectDirectory:this.workingDirectory});return new _o({workingDirectory:this.workingDirectory,store:this.getCliConfigurationStore(),manager:new Yr(this.configuration.interactive&&!this.isReadOnlyMode()?new wr({manager:t,initializer:{initialize:async()=>{await this.init({}),e.break();}}}):t)})})}getUserApi(e=false){return e?new Xt(this.getGraphqlClient(true)):this.share(this.getUserApi,()=>new Xt(this.getGraphqlClient()))}getOrganizationApi(){return this.share(this.getOrganizationApi,()=>new or(this.getGraphqlClient(),this.getHierarchyResolver()))}getWorkspaceApi(){return this.share(this.getWorkspaceApi,()=>new ar(this.getGraphqlClient(),this.getHierarchyResolver()))}getApplicationApi(){return this.share(this.getApplicationApi,()=>new lr(this.getGraphqlClient(),this.getHierarchyResolver()))}getHierarchyResolver(){return this.share(this.getHierarchyResolver,()=>{let e=this.getFileSystem();return new ya(this.getGraphqlClient(),AdaptedCache.transformValues(new dn({fileSystem:e,directory:e.joinPaths(this.configuration.directories.cache,"hierarchy")}),AdaptedCache.jsonSerializer(),AdaptedCache.jsonDeserializer()))})}getGraphqlClient(e=false){return e?new Bt({endpoint:this.configuration.adminGraphqlEndpoint,tokenProvider:{getToken:()=>this.getAuthenticator().getToken()}}):this.share(this.getGraphqlClient,()=>{let t=this.getAuthenticator();return new Bt({endpoint:this.configuration.adminGraphqlEndpoint,tokenProvider:{getToken:async()=>await t.getToken()??t.login({method:"default"})}})})}getTokenListener(){return this.share(this.getTokenListener,()=>{let{configuration:e}=this;return new Or({platform:e.process.getPlatform(),commandExecutor:this.getCommandExecutor(),timeout:2e3,listener:new Yo({api:this.getUserApi(true),pollingInterval:1e3})})})}getFileSystem(){return this.share(this.getFileSystem,()=>new Tr({workingDirectory:this.workingDirectory,defaultEncoding:"utf-8"}))}createEmailLinkGenerator(e){let t=this.getEmailLinkGenerator(),n=this.getClock();return r=>t.generate({recipient:r,sender:"croct.com",subject:e,timestamp:gt.Instant.now(n).getSeconds()})}getEmailLinkGenerator(){return this.share(this.getEmailLinkGenerator,()=>new Dr({detector:new Mr(new Nr,new $r),templates:{google:new zr,icloud:new _r,microsoft:new Lr,proton:new Fr,yahoo:new jr}}))}getClock(){return $c.SystemClock.UTC}getProtocolRegistryProvider(){return this.share(this.getProtocolRegistryProvider,()=>new Oe(()=>{let e=this.getFileSystem(),{process:t}=this.configuration;switch(t.getPlatform()){case "darwin":return new ha(new Oo({fileSystem:e,appDirectory:e.joinPaths(this.configuration.directories.data,"apps"),commandExecutor:this.getCommandExecutor()}),new Sa(ba.macOs({fileSystem:e,homeDirectory:this.configuration.directories.home})));case "win32":return new Do({commandExecutor:this.getCommandExecutor()});case "linux":return new Mo({fileSystem:e,homeDirectory:this.configuration.directories.home,commandExecutor:this.getCommandExecutor()});default:return null}}))}getCliConfigurationStore(){return this.share(this.getCliConfigurationStore,()=>{let e=this.getFileSystem();return new Ho({fileSystem:e,store:new qo({fileSystem:e,validator:new zo,filePath:e.joinPaths(this.configuration.directories.config,"config.json")})})})}async execute(e,t){if(this.isReadOnlyMode()&&!o.READ_ONLY_COMMANDS.has(e.constructor))return this.reportError(new d("This command does not support API key authentication.",{reason:"precondition",suggestions:["Run the command without specifying an API key."]}));try{await e.execute(t);}catch(n){let r=o.handleError(n);return n instanceof Error&&r instanceof Error&&(r.stack=n.stack),this.reportError(r)}}isReadOnlyMode(){return this.configuration.apiKey!==void 0}reportError(e){let t=this.getOutput();return t.report(o.handleError(e)),t.exit()}static handleError(e){switch(true){case e instanceof ne:if(e.isAccessDenied())return new d("Your user lacks the necessary permissions to complete this operation.",{reason:"access_denied",details:e.problems.map(t=>t.detail??t.title),suggestions:["Contact your organization or workspace administrator for assistance."],cause:e});break;case e instanceof x:if(e.tracing.length>0){let t=e.tracing.map(({name:n,source:r},i)=>{let a=r!==void 0?` at ${o.getSourceLocation(r)}`:"";return `${" ".repeat(i+1)}\u21B3 \`${n}\`${a}`}).join(`
|
|
1845
1845
|
`);return new d(`${e.message}
|
|
1846
1846
|
|
|
1847
1847
|
\u25B6\uFE0F **Trace**
|
|
1848
|
-
${t}`,e.help)}break;case e instanceof it:return new d(e.message,{...e.help,suggestions:["Run `init` to create a new configuration."]})}return e}static getSourceLocation(e){return e.url.protocol==="file:"?`${e.url}:${e.start.line}:${e.start.column}`:e.url.hostname==="github.com"?`${e.url}#L${e.start.line}-L${e.end.line}`:`${e.url}#${e.start.line}:${e.start.column}-${e.end.line}:${e.end.column}`}};var zc={version:"0.1.
|
|
1848
|
+
${t}`,e.help)}break;case e instanceof it:return new d(e.message,{...e.help,suggestions:["Run `init` to create a new configuration."]})}return e}static getSourceLocation(e){return e.url.protocol==="file:"?`${e.url}:${e.start.line}:${e.start.column}`:e.url.hostname==="github.com"?`${e.url}#L${e.start.line}-L${e.end.line}`:`${e.url}#${e.start.line}:${e.start.column}-${e.end.line}:${e.end.column}`}};var zc={version:"0.1.3"};function _c(o){let e=new ds().name("croct").description("Manage your Croct projects").enablePositionalOptions().option("--cwd <path>","The working directory.",y=>{try{return realpathSync(y)}catch{throw new Le("The path does not exist.")}}).addOption(new se("--api-key <key>","The API key to use for authentication.").env("CROCT_API_KEY").argParser(y=>{try{return ApiKey.parse(y)}catch{throw new Le("The API key is malformed.")}})).option("--registry <url>","The template registry.",y=>{if(!URL.canParse(y))throw new Le("Malformed URL.");return y}).option("--no-interaction","Disable interaction mode.").addOption(new se("-s, --skip-prompts","Skip prompts with default options.").default(false)).addOption(new se("-q, --quiet","Disable output messages.").default(false).implies({interaction:false})).option("--debug","Enable debug mode.").version(zc.version,"-v, --version","Display the version number.").helpOption("-h, --help","Display help for a command.").helpCommand("help [command]","Display help for a command.");e.command("open <url>").description("Open a deep link.").action(async y=>{await o.cli?.open({url:y});});let t=e.command("login").description("Authenticate your user."),n=new se("-u, --username <username>","The email."),r=new se("-p, --password <password>","The password.");t.command("credentials",{isDefault:true}).description("Authenticate using credentials.").addOption(o.interactive?n:n.makeOptionMandatory()).addOption(o.interactive?r:r.makeOptionMandatory()).action(async y=>{await o.cli?.login({method:"credentials",username:y.username,password:y.password});}),e.command("logout").description("Logout the current user.").action(async()=>{await o.cli?.logout();}),e.command("admin").argument("[page...]","The name of the page or path to open.").description("Log in and open the admin panel.").action(async y=>{await o.cli?.admin({page:y!==void 0?y.join(" "):o.interactive?void 0:"/"});});let i=new se("--wor <workspace-slug>","The workspace slug."),a=new se("--org <organization-slug>","The organization slug."),s=new se("--dev-app <application-slug>","The development application slug."),p=new se("--prod-app <application-slug>","The production application slug.");e.command("init").description("Configure the project.").option("-o, --override","Override any existing configuration.").addOption(new se("-n, --new <resource>","The resources to create.").choices(["organization","org","workspace","wor","application","app"])).addOption(new se("-s, --sdk <platform>","The SDK to use.").choices(["javascript","react","next"])).addOption(o.interactive?a:a.makeOptionMandatory()).addOption(o.interactive?i:i.makeOptionMandatory()).addOption(o.interactive?s:s.makeOptionMandatory()).addOption(p).action(async y=>{await o.cli?.init({override:y.override,new:(()=>{switch(y.new){case "organization":case "org":return "organization";case "workspace":case "wor":return "workspace";case "application":case "app":return "application";default:return}})(),sdk:y.sdk,organization:y.org,workspace:y.wor,devApplication:y.devApp,prodApplication:y.prodApp});}),e.command("install").description("Install content and types.").action(async()=>{await o.cli?.install({});}),e.command("update").description("Update content and types.").action(async()=>{await o.cli?.install({clean:true});}),e.command("upgrade").description("Upgrade components and slots to the latest version.").option("-s, --slots <slots...>","The slots to upgrade.").option("-c, --components <components...>","The components to upgrade.").action(async y=>{await o.cli?.upgrade({slots:y.slots??(y.components!==void 0?[]:void 0),components:y.components??(y.slots!==void 0?[]:void 0)});});let c=e.command("add").description("Add a resource to your project.");c.command("slot").description("Add a slot to your project.").argument(o.interactive?"[slots...]":"<slots...>").option("-e, --example","Generate an implementation example.").action(async(y,M)=>{await o.cli?.addSlot({slots:y,example:M.example});}),c.command("component").description("Add a component to your project.").argument(o.interactive?"[components...]":"<components...>").action(async y=>{await o.cli?.addComponent({components:y});});let l=e.command("remove").description("Remove a resource from your project.");l.command("slot").description("Remove a slot from your project.").argument(o.interactive?"[slots...]":"<slots...>").action(async y=>{await o.cli?.removeSlot({slots:y});}),l.command("component").description("Remove a component from your project.").argument(o.interactive?"[components...]":"<components...>").action(async y=>{await o.cli?.removeComponent({components:y});});let m=e.command("create").description("Create a resource in your project.");m.command("template").description("Create a template from your project.").addArgument(new gs("<path>","The path to the file.").argOptional()).option("-e, --empty","Create an empty template.").action(async(y,M)=>{await o.cli?.createTemplate({file:y,empty:M.empty});});let f=new se("--permissions <permissions...>","The permissions of the API key.").argParser(y=>y.split(",").map(M=>{try{return Ee.fromValue(M)}catch{throw new Le(`Unknown permission "${M}".`)}})),b=new se("--env <environment>","The environment of the API key.").choices(["prod","dev"]).argParser(y=>y==="prod"?"PRODUCTION":"DEVELOPMENT");m.command("api-key").description("Create an API key.").option("--name <name>","The name of the API key.").addOption(o.interactive?f:f.makeOptionMandatory()).addOption(o.interactive?b:b.makeOptionMandatory()).option("-c, --copy","Copy the API key to the clipboard.").action(async y=>{await o.cli?.createApiKey({name:y.name,permissions:y.permissions,environment:y.env,copy:y.copy});});let A={},I=e.command("use").description("Use a template.").argument("template","The path to the template.").passThroughOptions(o.cli===void 0).allowUnknownOption(o.cli===void 0||o.template===null).action(async(y,M)=>{await o.cli?.useTemplate({template:y,options:Object.fromEntries(Object.entries(M).map(([j,T])=>[A[j],T]))});});for(let[y,M]of Object.entries(o.template??{})){let j=`--${y}${M.type!=="boolean"?" <value>":""}`,T=new se(j,M.description).makeOptionMandatory(M.required===true);switch(M.type){case "string":M.options!==void 0&&M.options.length>0&&T.choices(M.options);break;case "number":T.argParser(H=>{let be=Number.parseFloat(H);if(Number.isNaN(be))throw new Le("The value must be a number.");return be});break;case "array":T.argParser(H=>{let be;try{be=JSON.parse(H);}catch{}if(be===void 0||!Array.isArray(be))throw new Le("The value must be a JSON array.");return H.split(",")});break;case "object":T.argParser(H=>{let be;try{be=JSON.parse(H);}catch{throw new Le("The JSON is malformed.")}if(typeof be!="object"||be===null)throw new Le("The value must be a JSON object.")});break}A[T.attributeName()]=y,I.addOption(T);}return e}function dd(o){let e=["use","help use"];for(let t of e){let n=t.split(" ").length;if(o.length>n&&o.slice(0,n).join(" ")===t&&(o[n]??"")!=="")return o[n]}return null}async function ps(o=process.argv,e=true){let t=_c({interactive:true}).parse(o),n=t.opts(),r=Ia.fromDefaults({program:p=>ps(t.args.slice(0,2).concat(p)),quiet:n.quiet,debug:n.debug,interactive:n.interaction?void 0:false,apiKey:n.apiKey,skipPrompts:n.skipPrompts===true,templateRegistryUrl:n.registry===void 0?void 0:new URL(n.registry)}),i=dd(t.args),a=i!==null?await r.getTemplateOptions(i).catch(()=>null):void 0,s=_c({cli:r,interactive:n.interaction,template:a});e&&await r.welcome({}),await s.parseAsync(o);}ps();
|