croct 0.3.4 → 0.3.5
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 +3 -3
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -1762,7 +1762,7 @@ ${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 $r=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 zr=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 _r=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 Lr=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 Ot=ht(Zt()),Fr=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=Ot.TimeZone.of(Intl.DateTimeFormat().resolvedOptions().timeZone),i=Ot.Instant.ofEpochSecond(e.timestamp),a=Ot.LocalDateTime.ofInstant(i,r).getLocalDate();t.push(`after:${a}`);}return t.push("in:anywhere"),n+=`/#search/${t.map(r=>encodeURIComponent(r)).join("+")}`,n}};var jr=class{generate(e){return new URL("https://www.icloud.com/mail")}};var Wr=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 Ur=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 Vr=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 cn=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",description:"My template description",actions:e?[{name:"print",semantics:"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,schema: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 qr=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,...u}=c;return u})));}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 Hr=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 u=await r.getExperience({experienceId:l,organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return u===null?[]:[u]}));return i.stop(),c.flat()}};var Gr=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 Tt=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 Kr=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 Tt({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.replace(/(?<=^[a-z]+:\/*)([^/.:]+)/i,i=>i.replace(/@/g,"%40")));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 Dt(o,e){if(URL.canParse(o))return new URL(o);let t=new URL(e.href.replace(/^(.*:)(?!\/)/,"$1/"));return new URL(o,t)}var Zr=class{constructor(e){this.config=e;}async execute(e,t){let{fileSystem:n}=this.config,{input:r}=t,i=Dt(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,{...e,destination:a},r);}finally{p?.stop();}e.result?.destination!==void 0&&t.set(e.result.destination,a);}async download(e,t,n){let{provider:r,fileSystem:i,codemod:a}=this.config,{destination:s,overwrite:p=false}=t,c=t.filter!==void 0?new Minimatch(t.filter):void 0,{value:l}=await r.get(e),u=[],f=Object.fromEntries(Object.entries(t.mapping??{}).map(([h,w])=>[i.normalizeSeparators(h),i.normalizeSeparators(w)]));for await(let h of l){let w=this.resolvePath(i.normalizeSeparators(h.name),f);if(!(i.isAbsolutePath(w)||!i.isSubPath(s,w))&&!(c!==void 0&&!c.match(w))){if(h.name=i.joinPaths(s,w),h.type==="link"||h.type==="symlink"){let x=i.normalizeSeparators(h.target);if(i.isAbsolutePath(x)||!i.isSubPath(s,x))continue;h.target=x;}u.push(h);}}if(u.length!==0){await this.createDirectory(u,s,p,n);for(let h of u)await i.create(h);for(let h of u)h.type==="file"&&await a.apply(await i.getRealPath(h.name));}}resolvePath(e,t){if(e in t)return t[e];let{fileSystem:n}=this.config,r="",i=e,a=n.getSeparator();for(let[s,p]of Object.entries(t)){let c=s.endsWith(a)?s:s+a;e.startsWith(c)&&c.length>r.length&&(r=c,i=n.joinPaths(p,e.slice(c.length)));}return i}async createDirectory(e,t,n,r){let{fileSystem:i}=this.config;if(!await i.exists(t))return i.createDirectory(t,{recursive:true});if(e.length===1&&e[0].type==="file"){if(!n&&await i.exists(e[0].name)&&await r?.confirm({message:`File ${e[0].name} already exists. Do you want to overwrite it?`,default:false})!==true)throw new I("Destination file already exists.",{reason:"precondition",details:[`File: ${e[0].name}`],suggestions:["Delete the file"]});return}if(await i.isDirectory(t)){if(!n&&!await i.isEmptyDirectory(t)&&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"]})}else if(await r?.confirm({message:`Destination ${t} is not a directory. Do you want to delete it?`,default:false})!==true)throw new I("Destination is not a directory.",{reason:"precondition",details:[`Path: ${t}`],suggestions:["Delete the file"]});await i.delete(t,{recursive:true}),await i.createDirectory(t,{recursive:true});}};var Jr=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 Qr=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){t.set(e.result,await this.findMatch(e.path,e));}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 Br=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 Yr=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 Xr=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 ei=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 et=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 ti=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 Za;(r=>{function o(i){let a=new Set(Object.values(i.slots??{}).map(u=>u.component)??[]),s=new Set(i.experiences?.flatMap(u=>u.slots)??[]),p=new Set(i.experiences?.flatMap(u=>u.audiences)??[]),c=(i.experiences??[]).map(u=>({name:u.name,maximumAudiencesPerExperience:u.audiences.length,crossDevice:u.experiment?.crossDevice===true,...e(u)})),l=new Set;for(let u of Object.values(i.slots??{}))for(let f of Object.keys(u.content))l.add(f);for(let u of c){for(let f of u.locales)l.add(f);for(let f of u.audiences)p.add(f);for(let f of u.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[u,f]of Object.entries(i.default??{})){a.add(u);for(let[h,w]of Object.entries(f))s.add(h),p=Math.max(p,n(w));}let c=new Set,l=0;for(let u of i.segmented??[]){for(let f of u.audiences)c.add(f);l=Math.max(l,u.audiences.length);for(let[f,h]of Object.entries(u.content)){a.add(f);for(let[w,x]of Object.entries(h))s.add(w),p=Math.max(p,n(x));}}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)}}})(Za||={});var ni=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,schema:this.refactorSchema(n.schema)}])),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))??[]}}refactorSchema(e){switch(e.type){case "boolean":case "text":case "number":return e;case "structure":return {...e,attributes:Object.fromEntries(Object.entries(e.attributes).map(([t,n])=>[t,{...n,type:this.refactorSchema(n.type)}]))};case "list":return {...e,items:this.refactorSchema(e.items)};case "union":return {...e,types:Object.fromEntries(Object.entries(e.types).map(([t,n])=>[t,this.refactorSchema(n)]))};case "reference":return {...e,id:this.refactoring.componentMapping[e.id]??e.id}}}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 ri=class o{constructor(e){this.config=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Analyzing resources"),i=Za.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 u=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 h of f)n.warn(`${h}`);}e.result!==void 0&&o.setVariables(e.result,l,u,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(x=>!("id"in x[1])),p=Object.entries(a.components).filter(x=>!("id"in x[1])),c=Object.entries(a.slots).filter(x=>!("id"in x[1])),l=a.experiences.filter(x=>!("id"in x)),u=l.flatMap(x=>x.experiment===void 0?[]:[x.experiment]);await this.checkRequiredQuota(n,{components:p.length,slots:c.length,audiences:s.length,experiences:l.length,experiments:u.length});let f=await r.handle({organizationSlug:n.configuration.organization,workspaceSlug:n.configuration.workspace,resources:{audiences:s.map(([x])=>x),components:p.map(([x])=>x),slots:c.map(([x])=>x)}}),h={},{workspace:w}=n;for(let x of t.locales)w.locales.includes(x)||(h[x]=w.defaultLocale);return {matches:a,mapping:f,resources:new ni({componentMapping:f.components,audienceMapping:f.audiences,slotMapping:f.slots,dynamicAttributesPerContent:w.quotas.dynamicAttributesPerContent,maximumAudiencePerExperience:w.quotas.audiencesPerExperience,isCrossDeviceFeatureEnabled:w.features.crossDevice,localeMapping:h}).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 Mt=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 ii=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,u]=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(y=>l.some(E=>E.slug===y)),h={};if(f.length>0){let y=l.map(E=>E.slug);for(let E of f){let B=await Mt.prompt({input:t,default:E,unavailableSlugs:y,label:`Component \`${E}\` already exists, enter a new component ID:`});y.push(B),h[E]=B;}}let w=a.filter(y=>c.some(E=>E.slug===y)),x={};if(w.length>0){let y=c.map(E=>E.slug);for(let E of w){let B=await Mt.prompt({input:t,default:E,unavailableSlugs:y,label:`Slot \`${E}\` already exists, enter a new slot ID:`});y.push(B),x[E]=B;}}let M=p.filter(y=>u.some(E=>E.slug===y)),Q={};if(M.length>0){let y=u.map(E=>E.slug);for(let E of M){let B=await Mt.prompt({input:t,default:E,unavailableSlugs:y,label:`Audience \`${E}\` already exists, enter a new audience ID:`});y.push(B),Q[E]=B;}}return {components:h,slots:x,audiences:Q}}};var oi=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.schema,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 j=class o extends U{constructor(e,{url:t,...n}){super(e,n),Object.setPrototypeOf(this,o.prototype),this.url=t;}},ze=class o extends j{constructor(e,t){super(e,{...t,reason:t.reason??"not_found"}),Object.setPrototypeOf(this,o.prototype);}};var ai=class o{async get(e){if(!["http:","https:"].includes(e.protocol))throw new j("Unsupported protocol.",{reason:"not_supported",url:e});let t=await fetch(e);if(t.status===404)throw new ze("Resource not found.",{url:e});if(!o.isSuccessful(t))throw new j(t.statusText,{url:e});return {url:e,value:t}}static isSuccessful(e){return e.ok&&e.body!==null}};var si=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 Nt=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 tt=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 ze("Resource not found.",{url:e})}static isExpectedError(e){return e instanceof j&&o.EXPECTED_ERROR_REASONS.includes(e.reason)}};var pi=class o{constructor(e){this.fileSystem=e;}supports(e){return Promise.resolve(o.supportsUrl(e))}get(e){if(!o.supportsUrl(e))throw new j(`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 ln=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 j("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=tu.extract();Readable.fromWeb(e.body).pipe(nu()).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 un=class o{constructor(e){this.provider=e;}async get(e){if(!o.supportsUrl(e))throw new j("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 Y=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 iu=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()}),mn=class extends Y{constructor(){super(iu);}};var ci=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(D.isValid,"Version must be exact (1), range (1 - 2), or set (1, 2).").refine(o=>{try{return D.parse(o).getCardinality()<=5}catch{return false}},"Version range must not exceed 5 major versions."),ou=z.strictObject({$schema:z.string().optional(),organization:ci,workspace:ci,applications:z.strictObject({development:ci,production:ci.optional()}),locales:z.array(sc).min(1),defaultLocale:sc,slots:z.record(pc).default({}),components:z.record(pc).default({}),paths:z.strictObject({source:z.string().optional(),utilities:z.string().optional(),components:z.string().optional(),examples:z.string().optional(),content:z.string().optional()}).optional()}).refine(o=>o.locales.includes(o.defaultLocale),{message:"The default locale is not included in the list of locales.",path:["defaultLocale"]}),li=class extends Y{constructor(){super(ou);}};var $t=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 $r=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 zr=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 _r=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 Lr=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 Ot=ht(Zt()),Fr=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=Ot.TimeZone.of(Intl.DateTimeFormat().resolvedOptions().timeZone),i=Ot.Instant.ofEpochSecond(e.timestamp),a=Ot.LocalDateTime.ofInstant(i,r).getLocalDate();t.push(`after:${a}`);}return t.push("in:anywhere"),n+=`/#search/${t.map(r=>encodeURIComponent(r)).join("+")}`,n}};var jr=class{generate(e){return new URL("https://www.icloud.com/mail")}};var Wr=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 Ur=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 Vr=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 cn=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",description:"My template description",actions:e?[{name:"print",semantics:"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,schema: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 qr=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,...u}=c;return u})));}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 Hr=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 u=await r.getExperience({experienceId:l,organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return u===null?[]:[u]}));return i.stop(),c.flat()}};var Gr=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 Tt=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 Kr=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 Tt({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.replace(/(?<=^[a-z]+:\/*)([^/.:]+)/i,i=>i.replace(/@/g,"%40")));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 Dt(o,e){if(URL.canParse(o))return new URL(o);let t=new URL(e.href.replace(/^(.*:)(?!\/)/,"$1/"));return new URL(o,t)}var Zr=class{constructor(e){this.config=e;}async execute(e,t){let{fileSystem:n}=this.config,{input:r}=t,i=Dt(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,{...e,destination:a},r);}finally{p?.stop();}e.result?.destination!==void 0&&t.set(e.result.destination,a);}async download(e,t,n){let{provider:r,fileSystem:i,codemod:a}=this.config,{destination:s,overwrite:p=false}=t,c=t.filter!==void 0?new Minimatch(t.filter):void 0,{value:l}=await r.get(e),u=[],f=Object.fromEntries(Object.entries(t.mapping??{}).map(([h,w])=>[i.normalizeSeparators(h),i.normalizeSeparators(w)]));for await(let h of l){let w=this.resolvePath(i.normalizeSeparators(h.name),f);if(!(i.isAbsolutePath(w)||!i.isSubPath(s,w))&&!(c!==void 0&&!c.match(w))){if(h.name=i.joinPaths(s,w),h.type==="link"||h.type==="symlink"){let x=i.normalizeSeparators(h.target);if(i.isAbsolutePath(x)||!i.isSubPath(s,x))continue;h.target=x;}u.push(h);}}if(u.length!==0){await this.createDirectory(u,s,p,n);for(let h of u)await i.create(h);for(let h of u)h.type==="file"&&await a.apply(await i.getRealPath(h.name));}}resolvePath(e,t){if(e in t)return t[e];let{fileSystem:n}=this.config,r="",i=e,a=n.getSeparator();for(let[s,p]of Object.entries(t)){let c=s.endsWith(a)?s:s+a;e.startsWith(c)&&c.length>r.length&&(r=c,i=n.joinPaths(p,e.slice(c.length)));}return i}async createDirectory(e,t,n,r){let{fileSystem:i}=this.config;if(!await i.exists(t))return i.createDirectory(t,{recursive:true});if(e.length===1&&e[0].type==="file"){if(!n&&await i.exists(e[0].name)&&await r?.confirm({message:`File ${e[0].name} already exists. Do you want to overwrite it?`,default:false})!==true)throw new I("Destination file already exists.",{reason:"precondition",details:[`File: ${e[0].name}`],suggestions:["Delete the file"]});return}if(await i.isDirectory(t)){if(!n&&!await i.isEmptyDirectory(t)&&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"]})}else if(await r?.confirm({message:`Destination ${t} is not a directory. Do you want to delete it?`,default:false})!==true)throw new I("Destination is not a directory.",{reason:"precondition",details:[`Path: ${t}`],suggestions:["Delete the file"]});await i.delete(t,{recursive:true}),await i.createDirectory(t,{recursive:true});}};var Jr=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 Qr=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){t.set(e.result,await this.findMatch(e.path,e));}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 Br=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 Yr=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 Xr=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 ei=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 et=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 ti=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 Za;(r=>{function o(i){let a=new Set(Object.values(i.slots??{}).map(u=>u.component)??[]),s=new Set(i.experiences?.flatMap(u=>u.slots)??[]),p=new Set(i.experiences?.flatMap(u=>u.audiences)??[]),c=(i.experiences??[]).map(u=>({name:u.name,maximumAudiencesPerExperience:u.audiences.length,crossDevice:u.experiment?.crossDevice===true,...e(u)})),l=new Set;for(let u of Object.values(i.slots??{}))for(let f of Object.keys(u.content))l.add(f);for(let u of c){for(let f of u.locales)l.add(f);for(let f of u.audiences)p.add(f);for(let f of u.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[u,f]of Object.entries(i.default??{})){a.add(u);for(let[h,w]of Object.entries(f))s.add(h),p=Math.max(p,n(w));}let c=new Set,l=0;for(let u of i.segmented??[]){for(let f of u.audiences)c.add(f);l=Math.max(l,u.audiences.length);for(let[f,h]of Object.entries(u.content)){a.add(f);for(let[w,x]of Object.entries(h))s.add(w),p=Math.max(p,n(x));}}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)}}})(Za||={});var ni=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,schema:this.refactorSchema(n.schema)}])),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))??[]}}refactorSchema(e){switch(e.type){case "boolean":case "text":case "number":return e;case "structure":return {...e,attributes:Object.fromEntries(Object.entries(e.attributes).map(([t,n])=>[t,{...n,type:this.refactorSchema(n.type)}]))};case "list":return {...e,items:this.refactorSchema(e.items)};case "union":return {...e,types:Object.fromEntries(Object.entries(e.types).map(([t,n])=>[t,this.refactorSchema(n)]))};case "reference":return {...e,id:this.refactoring.componentMapping[e.id]??e.id}}}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 ri=class o{constructor(e){this.config=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Analyzing resources"),i=Za.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 u=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 h of f)n.warn(`${h}`);}e.result!==void 0&&o.setVariables(e.result,l,u,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(x=>!("id"in x[1])),p=Object.entries(a.components).filter(x=>!("id"in x[1])),c=Object.entries(a.slots).filter(x=>!("id"in x[1])),l=a.experiences.filter(x=>!("id"in x)),u=l.flatMap(x=>x.experiment===void 0?[]:[x.experiment]);await this.checkRequiredQuota(n,{components:p.length,slots:c.length,audiences:s.length,experiences:l.length,experiments:u.length});let f=await r.handle({organizationSlug:n.configuration.organization,workspaceSlug:n.configuration.workspace,resources:{audiences:s.map(([x])=>x),components:p.map(([x])=>x),slots:c.map(([x])=>x)}}),h={},{workspace:w}=n;for(let x of t.locales)w.locales.includes(x)||(h[x]=w.defaultLocale);return {matches:a,mapping:f,resources:new ni({componentMapping:f.components,audienceMapping:f.audiences,slotMapping:f.slots,dynamicAttributesPerContent:w.quotas.dynamicAttributesPerContent,maximumAudiencePerExperience:w.quotas.audiencesPerExperience,isCrossDeviceFeatureEnabled:w.features.crossDevice,localeMapping:h}).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 Mt=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 ii=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,u]=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(y=>l.some(E=>E.slug===y)),h={};if(f.length>0){let y=l.map(E=>E.slug);for(let E of f){let B=await Mt.prompt({input:t,default:E,unavailableSlugs:y,label:`Component \`${E}\` already exists, enter a new component ID:`});y.push(B),h[E]=B;}}let w=a.filter(y=>c.some(E=>E.slug===y)),x={};if(w.length>0){let y=c.map(E=>E.slug);for(let E of w){let B=await Mt.prompt({input:t,default:E,unavailableSlugs:y,label:`Slot \`${E}\` already exists, enter a new slot ID:`});y.push(B),x[E]=B;}}let M=p.filter(y=>u.some(E=>E.slug===y)),Q={};if(M.length>0){let y=u.map(E=>E.slug);for(let E of M){let B=await Mt.prompt({input:t,default:E,unavailableSlugs:y,label:`Audience \`${E}\` already exists, enter a new audience ID:`});y.push(B),Q[E]=B;}}return {components:h,slots:x,audiences:Q}}};var oi=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.schema,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 j=class o extends U{constructor(e,{url:t,...n}){super(e,n),Object.setPrototypeOf(this,o.prototype),this.url=t;}},ze=class o extends j{constructor(e,t){super(e,{...t,reason:t.reason??"not_found"}),Object.setPrototypeOf(this,o.prototype);}};var ai=class o{async get(e){if(!["http:","https:"].includes(e.protocol))throw new j("Unsupported protocol.",{reason:"not_supported",url:e});let t=await fetch(e);if(t.status===404)throw new ze("Resource not found.",{url:e});if(!o.isSuccessful(t))throw new j(t.statusText,{url:e});return {url:e,value:t}}static isSuccessful(e){return e.ok&&e.body!==null}};var si=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=[];for(let s of i){if(e?.result?.[s.dependency]!==void 0){t.set(e.result[s.dependency],s.satisfied);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(n===void 0){let a=await this.packageManager.hasDirectDependency(t);if(a||r)return {dependency:t,satisfied:a}}else {let a=await this.packageManager.hasDirectDependency(t,n);if(a||r)return {dependency:t,satisfied:a}}let i=await this.packageManager.getDependency(t);return {dependency:t,satisfied:false,issue:i===null?"not installed":`${n!==void 0?`version \`${n}\` is required`:""}found \`${i.version??"unknown"}\``}}};var Nt=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 tt=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 ze("Resource not found.",{url:e})}static isExpectedError(e){return e instanceof j&&o.EXPECTED_ERROR_REASONS.includes(e.reason)}};var pi=class o{constructor(e){this.fileSystem=e;}supports(e){return Promise.resolve(o.supportsUrl(e))}get(e){if(!o.supportsUrl(e))throw new j(`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 ln=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 j("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=tu.extract();Readable.fromWeb(e.body).pipe(nu()).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 un=class o{constructor(e){this.provider=e;}async get(e){if(!o.supportsUrl(e))throw new j("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 Y=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 iu=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()}),mn=class extends Y{constructor(){super(iu);}};var ci=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(D.isValid,"Version must be exact (1), range (1 - 2), or set (1, 2).").refine(o=>{try{return D.parse(o).getCardinality()<=5}catch{return false}},"Version range must not exceed 5 major versions."),ou=z.strictObject({$schema:z.string().optional(),organization:ci,workspace:ci,applications:z.strictObject({development:ci,production:ci.optional()}),locales:z.array(sc).min(1),defaultLocale:sc,slots:z.record(pc).default({}),components:z.record(pc).default({}),paths:z.strictObject({source:z.string().optional(),utilities:z.string().optional(),components:z.string().optional(),examples:z.string().optional(),content:z.string().optional()}).optional()}).refine(o=>o.locales.includes(o.defaultLocale),{message:"The default locale is not included in the list of locales.",path:["defaultLocale"]}),li=class extends Y{constructor(){super(ou);}};var $t=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 j(`The response data is invalid:
|
|
1768
1768
|
|
|
@@ -1839,8 +1839,8 @@ ${t.join(`
|
|
|
1839
1839
|
${this.getPreferences(e.protocol).join(`
|
|
1840
1840
|
`)}`;await this.fileSystem.writeTextFile(n,s,{overwrite:true});let p=o.parseHandlers(a);p.schemes[e.protocol]={ask:true,action:2,handlers:[{name:e.name,path:this.configuration.appPath}]},await this.fileSystem.writeTextFile(r,JSON.stringify(p),{overwrite:true});}async unregister(e){if(!await this.isRegistered(e))return;let t=await this.getProfilePath();if(t===null)return;let n=this.getUserPreferencesFilePath(t),r=this.getHandlersFilePath(t),[i,a]=await Promise.all([await this.fileSystem.readTextFile(n).catch(()=>""),this.fileSystem.readTextFile(r).catch(()=>"")]),s=i.split(`
|
|
1841
1841
|
`).filter(c=>!this.getPreferences(e).includes(c)).join(`
|
|
1842
|
-
`);await this.fileSystem.writeTextFile(n,s,{overwrite:true});let p=o.parseHandlers(a);p.schemes[e]!==void 0&&(delete p.schemes[e],await this.fileSystem.writeTextFile(r,JSON.stringify(p),{overwrite:true}));}getUserPreferencesFilePath(e){return this.fileSystem.joinPaths(e,"user.js")}getHandlersFilePath(e){return this.fileSystem.joinPaths(e,"handlers.json")}async getProfilePath(){let e=this.getPath("profiles.ini");if(!await this.fileSystem.exists(e))return null;let t=Object.values(parse(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(i)}getPath(e){return this.fileSystem.joinPaths(this.profileDirectory,e)}getPreferences(e){return o.PREFERENCES.map(t=>t.replace(/%protocol%/g,e))}static parseHandlers(e){let t;try{t=JSON.parse(e);}catch{return {schemes:{}}}return typeof t!="object"||t===null?{schemes:{}}:!("schemes"in t)||typeof t.schemes!="object"||t.schemes===null?{...t,schemes:{}}:t}};var Sa=class{constructor(e){this.config=e;}async execute(e){let{protocolRegistryProvider:t,io:{output:n}}=this.config,r=await t.get();if(r===null){["optionally-enable","optionally-update"].includes(e.operation)||n.alert("Deep linking is not available on your platform.");return}try{await this.apply(r,e);}catch(i){n.alert(`Deep link error: ${d.formatCause(i)}`);}}apply(e,t){let{io:{output:n}}=this.config;switch(t.operation){case "optionally-enable":return this.optionallyEnable(e,n);case "optionally-update":return this.optionallyUpdate(e,n);case "disable":return this.disable(e,false,n);case "enable":return this.enable(e,false,n)}}async optionallyEnable(e,t){let{protocolHandler:n,io:{input:r}}=this.config;if(!await e.isRegistered(n.protocol)&&await r?.confirm({message:"Turn on deep links to streamline your experience?",default:false})===true)return this.enable(e,true,t)}async enable(e,t,n){let{cliPackage:r,packageManager:i,protocolHandler:a}=this.config;if(!t&&await e.isRegistered(a.protocol)){n?.inform("Deep links are already enabled");return}let s=n?.notify("Enabling deep links");try{let p=await i.getPackageCommand(r,["open","$url"]);await e.register({...a,command:`${p.name} ${(p.arguments??[]).join(" ")}`}),s?.confirm("Deep links enabled");}finally{s?.stop();}}async disable(e,t,n){let{protocolHandler:r}=this.config;if(!t&&!await e.isRegistered(r.protocol)){n?.inform("Deep links are not enabled");return}let i=n?.notify("Disabling deep links");try{await e.unregister(r.protocol),i?.confirm("Deep links disabled");}finally{i?.stop();}}async optionallyUpdate(e,t){let{protocolHandler:n}=this.config;if(!await e.isRegistered(n.protocol))return this.optionallyEnable(e,t);let r=t?.notify("Updating deep links");try{await this.disable(e,!0),await this.enable(e,!0),r?.confirm("Deep links updated");}finally{r?.stop();}}};var ba=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),u=l.endsWith(".json")?l:await this.locateConfig(l,n);if(u===null)continue;let f=await this.resolveConfig({...e,configPath:u});if(f?.include!==void 0)for(let h of i){let w=this.fileSystem.joinPaths("./",this.fileSystem.getRelativePath(this.fileSystem.getDirectoryName(u),h));for(let x of f.include){let M=new Minimatch(x,{partial:true,magicalBraces:true});if(!M.hasMagic()&&!x.includes(".")&&(M=new Minimatch(`${x.replace(/\/?$/,"")}/**/*`,{partial:true})),M.match(w))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.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 Ia=class{constructor({commandExecutor:e,executableLocator:t}){this.executableLocator=t,this.commandExecutor=e;}async run(e,t={}){let n=await this.executableLocator.locate(e.name);if(n===null)throw new Fe(`Unable to locate executable for command \`${e.name}\`.`);return this.commandExecutor.run({...e,name:n},t)}};var xa=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 Ko(this.initialDirectory);}static{this.READ_ONLY_COMMANDS=new Set([Mn,on,an,Et,Rt,nn,rn,cn,Bt]);}static fromDefaults(e){let t=pd("com.croct.cli"),n=new ea;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??!cd.isCI,version:e.version??"0.0.0",apiKey:e.apiKey,skipPrompts:e.skipPrompts??false,adminTokenDuration:e.adminTokenDuration??7*yt.LocalTime.SECONDS_PER_DAY,apiKeyTokenDuration:e.apiKeyTokenDuration??30*yt.LocalTime.SECONDS_PER_MINUTE,cliTokenDuration:e.cliTokenDuration??90*yt.LocalTime.SECONDS_PER_DAY,cliTokenFreshPeriod:e.cliTokenFreshPeriod??15*yt.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 Mn({version:this.configuration.version,configurationProvider:this.getCliConfigurationProvider(),deepLinkInstaller:t=>this.deepLink({operation:t?"optionally-update":"optionally-enable"})}),e)}deepLink(e){return this.execute(new Sa({packageManager:this.getNodePackageManager(),protocolRegistryProvider:this.getProtocolRegistryProvider(),configurationProvider:this.getCliConfigurationProvider(),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.getCliConfigurationProvider(),workingDirectory:new Zo(this.configuration.process),fileSystem:this.getFileSystem(),io:{input:this.getInput(),output:this.getOutput()}}),e)}init(e){return this.execute(new or({sdkProvider:this.getSdkProvider(),platformProvider:this.getPlatformProvider(),configurationManager:this.getConfigurationManager(),skipConfirmation:new Eo(new Tn(new Rn(new kn({fileSystem:this.getFileSystem(),files:[".git"]})))),api:{user:this.getUserApi(),organization:this.getOrganizationApi(),workspace:this.getWorkspaceApi()},form:{organization:new lr({input:this.getFormInput(),output:this.getOutput(),userApi:this.getUserApi()}),workspace:new ur({input:this.getFormInput(),output:this.getOutput(),organizationApi:this.getOrganizationApi()}),application:new mr({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),slot:new Ge({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})},io:{input:this.getInput(),output:this.getOutput()}}),e)}install(e){return this.execute(new on({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),io:{input:this.getInput(),output:this.getOutput()}}),e)}upgrade(e){return this.execute(new an({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),form:{slotForm:new Ge({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),componentForm:new Xe({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})},io:{input:this.getInput(),output:this.getOutput()}}),e)}addSlot(e){return this.execute(new Et({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new Ge({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}removeSlot(e){return this.execute(new nn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),slotForm:new Ge({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}addComponent(e){return this.execute(new Rt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new Xe({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}removeComponent(e){return this.execute(new rn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new Xe({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}login(e){return this.execute(new ar({authenticator:this.getAuthenticator()}),e)}logout(){return this.execute(new Bt({authenticator:this.getAuthenticator(),output:this.getOutput()}),{})}admin(e){return this.execute(new hr({output:this.getOutput(),pageForm:new Ar({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 cn({configurationManager:this.getConfigurationManager(),fileSystem:this.getFileSystem(),templateForm:new qr({input:this.getFormInput(),form:{component:new Xe({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),slot:new Ge({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),experience:new Hr({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),audience:new Gr({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 options");try{return await t.getOptions(e)}finally{r.stop();}}getUseTemplateCommand(){return new Kr({templateProvider:new $t({provider:new dn(this.getTemplateProvider()),validator:new bn}),fileSystem:this.getFileSystem(),action:this.getImportAction(),io:{input:this.getInput(),output:this.getOutput()}})}createApiKey(e){return this.execute(new Ho({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 On(new Rr(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 Jn({input:this.configuration.process.getStandardInput(),output:this.configuration.process.getStandardOutput(),onAbort:()=>e.exit(),onInteractionStart:()=>e.suspend(),onInteractionEnd:()=>e.resume()});return this.skipPrompts?new On(t):t})}getNonInteractiveOutput(e=false){let{configuration:t}=this;return new Qt({output:t.process.getStandardOutput(),formatter:this.getLogFormatter(),interactive:false,quiet:e,onExit:()=>t.process.exit(),linkOpener:async n=>{await $c(n,{wait:true});}})}getHierarchicalLogger(){return this.share(this.getHierarchicalLogger,()=>new pa(this.getLogger()))}getLogger(){return this.share(this.getLogger,()=>{let e=new ca(this.getOutput());return this.configuration.debug?e:new FilteredLogger(e,LogLevel.WARNING)})}getOutput(){return this.share(this.getOutput,()=>{let{configuration:e}=this;return new Qt({output:e.process.getStandardOutput(),formatter:this.getLogFormatter(),interactive:this.configuration.interactive,quiet:this.configuration.quiet,onExit:()=>e.process.exit(),linkOpener:async t=>{await $c(t);}})})}getLogFormatter(){return this.share(this.getLogFormatter,()=>new Yo)}getTemplateProvider(){return this.share(this.getTemplateProvider,()=>{let e=n=>new tt(...["template.json5","template.json"].map(r=>new Nt({dataProvider:n,registryProvider:new wn([{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 fn({resourceCache:new AutoSaveCache(new InMemoryCache),errorCache:new InMemoryCache,provider:new tt(new Nt({dataProvider:this.traceProvider({label:"ResourceProvider",provider:e(new gt(new tt(this.traceProvider({provider:new ln(t)}),this.traceProvider({provider:new un(t)}))))}),registryProvider:this.traceProvider({label:"NpmRegistryProvider",provider:new ra(new $t({provider:ia.json(this.traceProvider({provider:this.getHttpProvider()})),validator:new oa}))})}),e(new gt(this.getFileProvider())))})})})}getFileProvider(){return this.share(this.getFileProvider,()=>{let e=this.traceProvider({provider:this.getHttpProvider()}),t=this.traceProvider({provider:new pi(this.getFileSystem())}),n=new tt(t,this.traceProvider({provider:new ln(e)}),this.traceProvider({provider:new un(e)}));return this.traceProvider({label:"FileProvider",provider:new tt(t,this.traceProvider({provider:new Nt({baseUrl:new URL("./",this.configuration.templateRegistryUrl),dataProvider:this.traceProvider({label:"ResourceProvider",provider:n}),registryProvider:new Fi({url:this.configuration.templateRegistryUrl,provider:this.traceProvider({label:"GlobalRegistryProvider",provider:new fn({errorCache:new InMemoryCache,resourceCache:new AutoSaveCache(new InMemoryCache),provider:new $t({provider:new dn(new gt(n)),validator:new mi})})})})})}))})})}traceProvider({provider:e,label:t}){return new sa({label:t,provider:e,logger:this.getHierarchicalLogger()})}getImportAction(){return this.share(this.getImportAction,()=>{let e=this.getFileSystem(),t={run:new L({action:new et(new Te(()=>new Qi(t))),validator:new Bi}),try:new L({action:new et(new Te(()=>new ei(t.run))),validator:new hi}),test:new L({action:new et(new Te(()=>new Ti(t.run))),validator:new Mi}),repeat:new L({action:new et(new Te(()=>new Ro(t.run))),validator:new Oo}),print:new L({action:new Ni,validator:new zi}),fail:new L({action:new _i,validator:new Li}),define:new L({action:new to,validator:new eo}),prompt:new L({action:new Hi,validator:new Gi}),"change-directory":new L({action:new so({fileSystem:e,rootDirectory:this.initialDirectory,currentDirectory:this.workingDirectory}),validator:new ao}),"open-link":new L({action:new Yi,validator:new Xi}),"start-server":new L({action:new Ki({serverProvider:this.getServerProvider()}),validator:new Ji}),"stop-server":new L({action:new no({serverProvider:this.getServerProvider()}),validator:new ro}),"execute-package":new L({action:new po({packageManager:this.getPackageManager(),packageManagerProvider:this.getPackageManagerRegistry(),workingDirectory:this.workingDirectory,commandExecutor:this.getAsynchronousCommandExecutor(),commandTimeout:3*60*1e3,sourceChecker:{test:n=>n.protocol==="file:"||`${n}`.startsWith("https://github.com/croct-tech")}}),validator:new co}),"check-dependency":new L({action:new si({packageManager:this.getPackageManager()}),validator:new Si}),download:new L({action:new Zr({fileSystem:e,provider:this.getFileProvider(),codemod:new ua({codemods:{"**/*.{js,jsx,ts,tsx}":new ga(new la({fileSystem:e,rootPath:this.workingDirectory,maxSearchDepth:10,importResolver:this.getNodeImportResolver(),importCodemod:new He({fileSystem:e,codemod:new Ve({languages:["typescript","jsx"],codemod:new da})}),exportMatcher:{test:(n,{names:r})=>r.length===0?true:Dc(n).some(i=>r.includes(i))}}),new qe(this.getJavaScriptFormatter()))}})}),validator:new bi}),"add-dependency":new L({action:new Jr({packageManager:this.getPackageManager()}),validator:new xi}),"locate-file":new L({action:new Qr({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 Rn(Ao.fromPatterns(a)),i)}return i}}}),validator:new vi}),"replace-file-content":new L({action:new Br({fileSystem:e}),validator:new wi}),initialize:new L({action:new ta({callback:()=>this.init({})}),validator:new na}),"add-slot":new L({action:new Yr({installer:(n,r)=>{let i=this.getNonInteractiveOutput(true);return this.execute(new Et({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new Ge({input:this.getNonInteractiveInput(),output:i,workspaceApi:this.getWorkspaceApi()}),io:{output:i}}),{slots:n,example:r})}}),validator:new Ci}),"add-component":new L({action:new Xr({installer:n=>{let r=this.getNonInteractiveOutput(true);return this.execute(new Rt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new Xe({input:this.getNonInteractiveInput(),output:r,workspaceApi:this.getWorkspaceApi()}),io:{output:r}}),{components:n})}}),validator:new ki}),"create-resource":new L({action:new ri({configurationManager:this.getConfigurationManager(),matcher:new oi({workspaceApi:this.getWorkspaceApi()}),api:{user:this.getUserApi(),workspace:this.getWorkspaceApi(),organization:this.getOrganizationApi()},mappingForm:new ii({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 Ai}),"format-code":new L({action:new Ri({formatter:this.getCodeFormatter()}),validator:new Oi}),import:new L({action:new et(new Te(()=>new gi({runner:t.run,templateProvider:new yi({evaluator:new di({functions:os}),validator:new bn,templateProvider:this.getTemplateProvider(),fileProvider:new gt(this.getFileProvider())}),variables:this.getActionVariables()}))),validator:new Ei})};return t.import})}getActionVariables(){let e=t=>new URL(t,this.configuration.adminUrl).toString();return {project:{features:ce.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{features:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),quotas:ce.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{quotas:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),organization:ce.transient(async()=>{let{organization:t}=await this.getConfigurationManager().load();return {slug:t,url:e(`organizations/${t}`)}}),workspace:ce.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load();return {slug:n,url:e(`organizations/${t}/workspaces/${n}`)}}),application:ce.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:ce.transient(async()=>{let t=this.getSdk(),n=await this.getConfigurationManager().load();return t.getPaths(n)}),platform:ce.transient(async()=>await this.getPlatformProvider().get()??"unknown"),server:ce.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 ai)}getAuthenticator(){return this.share(this.getAuthenticator,()=>{if(this.configuration.apiKey!==void 0)return new Go({apiKey:this.configuration.apiKey,clock:this.getClock(),tokenDuration:this.configuration.apiKeyTokenDuration});let e=this.getFormInput(),t=new gr({input:e,output:this.getOutput(),userApi:this.getUserApi(true),form:{signIn:new fr({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 yr({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 Jo({cacheKey:"token",cacheProvider:new Qo({clock:this.getClock(),clockSkewTolerance:5,tokenFreshPeriod:this.configuration.cliTokenFreshPeriod,tokenIssuer:()=>n.issueToken({duration:this.configuration.cliTokenDuration}),cacheProvider:new gn({fileSystem:this.getFileSystem(),directory:this.configuration.directories.config,useKeyAsFileName:true})}),authenticator:new Or({default:this.configuration.interactive?t:new Er({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 Wo({output:this.getOutput(),input:e,userApi:this.getUserApi(true)})}):r})}getSdk(){return this.share(this.getSdk,()=>{let e=new Wt(this.getSdkProvider(),new Te(()=>{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 Ft({discriminator:async()=>await this.getPlatformProvider().get()??i,mapping:{javascript:()=>new er({...r,bundlers:["vite","parcel","tsup","rollup"]}),react:()=>new tr({...r,importResolver:n,codemod:{provider:new qe(e,new He({fileSystem:this.getFileSystem(),codemod:new Ve({languages:["typescript","jsx"],codemod:new lt({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 ir({...r,userApi:this.getUserApi(),applicationApi:this.getApplicationApi(),importResolver:n,codemod:{middleware:new qe(e,new He({fileSystem:this.getFileSystem(),codemod:new Ve({languages:["typescript","jsx"],codemod:new vr({import:{module:"@croct/plug-next/middleware",middlewareName:"middleware",middlewareFactoryName:"withCroct",configName:"config",matcherName:"matcher",matcherLocalName:"croctMatcher"}})})})),appRouterProvider:new qe(e,new He({fileSystem:this.getFileSystem(),codemod:new Ve({languages:["typescript","jsx"],codemod:new lt({fallbackToNamedExports:false,fallbackCodemod:new wr({provider:{component:"CroctProvider",module:"@croct/plug-next/CroctProvider"}}),wrapper:{module:"@croct/plug-next/CroctProvider",component:"CroctProvider"},targets:{variable:"children"}})})})),pageRouterProvider:new qe(e,new He({fileSystem:this.getFileSystem(),codemod:new Ve({languages:["typescript","jsx"],codemod:new lt({fallbackToNamedExports:false,fallbackCodemod:new tn({provider:{component:"CroctProvider",module:"@croct/plug-next/CroctProvider"}}),wrapper:{module:"@croct/plug-next/CroctProvider",component:"CroctProvider"},targets:{component:"Component"}})})})),fallbackProvider:new qe(e,new He({fileSystem:this.getFileSystem(),codemod:new Ve({languages:["typescript","jsx"],codemod:new lt({fallbackToNamedExports:false,fallbackCodemod:new tn({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 Ft({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 Cn(new Wt(this.getNodePackageManagerProvider(),new Te(()=>{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 Cn(new Wt(this.getNodePackageManagerProvider(),new wn(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 En(new jo(new Ut({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new Fo({process:this.configuration.process,variable:"npm_config_user_agent",value:new RegExp(`^${r}`)})}))}),new Ut({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new Tn(new Lo({packageManager:r,fileSystem:t,projectDirectory:this.workingDirectory}),new kn({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.getAsynchronousCommandExecutor(),executableLocator:this.getExecutableLocator()},n=new mn,r={fileSystem:e,projectDirectory:this.workingDirectory,packageValidator:n};return {npm:new nt({...r,agent:new lo(t)}),yarn:new nt({...r,agent:new uo(t)}),bun:new nt({...r,agent:new mo(t)}),pnpm:new nt({...r,agent:new go(t)})}})}getNodeServerProvider(){return this.share(this.getNodeServerProvider,()=>new ji({packageManager:this.getNodePackageManager(),factory:this.getServerFactory(),parsers:[new Wi,new Ui,new Vi,new qi]}))}getServerProvider(){return this.share(this.getServerProvider,()=>{let e=Symbol("unknown");return new Ft({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 oo({commandExecutor:this.getAsynchronousCommandExecutor(),workingDirectory:this.workingDirectory,startupTimeout:2e4,startupCheckDelay:1500,lookupMaxPorts:30,lookupTimeout:2e3,processObserver:this.configuration.process})))}getJavaScriptFormatter(){return this.share(this.getJavaScriptFormatter,()=>new Cr({commandExecutor:this.getAsynchronousCommandExecutor(),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 ba({fileSystem:this.getFileSystem(),tsconfigValidator:new yo}))}getAsynchronousCommandExecutor(){return this.share(this.getAsynchronousCommandExecutor,()=>new Ia({executableLocator:this.getExecutableLocator(),commandExecutor:this.getCommandExecutor()}))}getSynchronousCommandExecutor(){return this.getCommandExecutor()}getCommandExecutor(){return this.share(this.getCommandExecutor,()=>new xo({currentDirectory:this.workingDirectory,windows:this.configuration.process.getPlatform()==="win32"}))}getExecutableLocator(){return this.share(this.getExecutableLocator,()=>{let{process:e}=this.configuration;return new _o({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 nt({projectDirectory:this.workingDirectory,packageValidator:new mn,fileSystem:this.getFileSystem(),agent:new So});return new En(new Ut({candidates:[{value:"nextjs",condition:new An({packageManager:e,dependencies:["next"]})},{value:"react",condition:new An({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 sr({fileSystem:this.getFileSystem(),validator:new li,projectDirectory:this.workingDirectory});return new zo({workingDirectory:this.workingDirectory,configurationProvider:this.getCliConfigurationProvider(),manager:new ti(this.configuration.interactive&&!this.isReadOnlyMode()?new kr({manager:t,initializer:{initialize:async()=>{await this.init({}),e.break();}}}):t)})})}getUserApi(e=false){return e?new en(this.getGraphqlClient(true)):this.share(this.getUserApi,()=>new en(this.getGraphqlClient()))}getOrganizationApi(){return this.share(this.getOrganizationApi,()=>new pr(this.getGraphqlClient(),this.getHierarchyResolver()))}getWorkspaceApi(){return this.share(this.getWorkspaceApi,()=>new cr(this.getGraphqlClient(),this.getHierarchyResolver()))}getApplicationApi(){return this.share(this.getApplicationApi,()=>new dr(this.getGraphqlClient(),this.getHierarchyResolver()))}getHierarchyResolver(){return this.share(this.getHierarchyResolver,()=>{let e=this.getFileSystem();return new fa(this.getGraphqlClient(),AdaptedCache.transformValues(new gn({fileSystem:e,directory:e.joinPaths(this.configuration.directories.cache,"hierarchy")}),AdaptedCache.jsonSerializer(),AdaptedCache.jsonDeserializer()))})}getGraphqlClient(e=false){return e?new Yt({endpoint:this.configuration.adminGraphqlEndpoint,tokenProvider:{getToken:()=>this.getAuthenticator().getToken()}}):this.share(this.getGraphqlClient,()=>{let t=this.getAuthenticator();return new Yt({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 Nr({platform:e.process.getPlatform(),commandExecutor:this.getSynchronousCommandExecutor(),timeout:2e3,listener:new Bo({api:this.getUserApi(true),pollingInterval:1e3})})})}getFileSystem(){return this.share(this.getFileSystem,()=>new Mr({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:yt.Instant.now(n).getSeconds()})}getEmailLinkGenerator(){return this.share(this.getEmailLinkGenerator,()=>new $r({detector:new zr(new _r,new Lr),templates:{google:new Fr,icloud:new jr,microsoft:new Wr,proton:new Ur,yahoo:new Vr}}))}getClock(){return zc.SystemClock.UTC}getProtocolRegistryProvider(){return this.share(this.getProtocolRegistryProvider,()=>new Te(()=>{let e=this.getFileSystem(),{process:t}=this.configuration;switch(t.getPlatform()){case "darwin":{let n=e.joinPaths(this.configuration.directories.data,"apps");return new ya({output:this.getOutput(),macOsRegistry:new To({fileSystem:e,appDirectory:n,commandExecutor:this.getAsynchronousCommandExecutor()}),firefoxRegistry:ha.macOs({fileSystem:e,homeDirectory:this.configuration.directories.home,appPath:e.joinPaths(n,`${this.configuration.deepLinkProtocol}.app`)})})}case "win32":return new Do({commandExecutor:this.getAsynchronousCommandExecutor()});case "linux":return new Mo({fileSystem:e,homeDirectory:this.configuration.directories.home,commandExecutor:this.getAsynchronousCommandExecutor()});default:return null}}))}getCliConfigurationProvider(){return this.share(this.getCliConfigurationProvider,()=>{let e=this.getFileSystem();return new qo({fileSystem:e,configurationProvider:new Vo({fileSystem:e,validator:new $o,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 re: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(`
|
|
1842
|
+
`);await this.fileSystem.writeTextFile(n,s,{overwrite:true});let p=o.parseHandlers(a);p.schemes[e]!==void 0&&(delete p.schemes[e],await this.fileSystem.writeTextFile(r,JSON.stringify(p),{overwrite:true}));}getUserPreferencesFilePath(e){return this.fileSystem.joinPaths(e,"user.js")}getHandlersFilePath(e){return this.fileSystem.joinPaths(e,"handlers.json")}async getProfilePath(){let e=this.getPath("profiles.ini");if(!await this.fileSystem.exists(e))return null;let t=Object.values(parse(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(i)}getPath(e){return this.fileSystem.joinPaths(this.profileDirectory,e)}getPreferences(e){return o.PREFERENCES.map(t=>t.replace(/%protocol%/g,e))}static parseHandlers(e){let t;try{t=JSON.parse(e);}catch{return {schemes:{}}}return typeof t!="object"||t===null?{schemes:{}}:!("schemes"in t)||typeof t.schemes!="object"||t.schemes===null?{...t,schemes:{}}:t}};var Sa=class{constructor(e){this.config=e;}async execute(e){let{protocolRegistryProvider:t,io:{output:n}}=this.config,r=await t.get();if(r===null){["optionally-enable","optionally-update"].includes(e.operation)||n.alert("Deep linking is not available on your platform.");return}try{await this.apply(r,e);}catch(i){n.alert(`Deep link error: ${d.formatCause(i)}`);}}apply(e,t){let{io:{output:n}}=this.config;switch(t.operation){case "optionally-enable":return this.optionallyEnable(e,n);case "optionally-update":return this.optionallyUpdate(e,n);case "disable":return this.disable(e,false,n);case "enable":return this.enable(e,false,n)}}async optionallyEnable(e,t){let{protocolHandler:n,io:{input:r}}=this.config;if(!await e.isRegistered(n.protocol)&&await r?.confirm({message:"Turn on deep links to streamline your experience?",default:false})===true)return this.enable(e,true,t)}async enable(e,t,n){let{cliPackage:r,packageManager:i,protocolHandler:a}=this.config;if(!t&&await e.isRegistered(a.protocol)){n?.inform("Deep links are already enabled");return}let s=n?.notify("Enabling deep links");try{let p=await i.getPackageCommand(r,["open","$url"]);await e.register({...a,command:`${p.name} ${(p.arguments??[]).join(" ")}`}),s?.confirm("Deep links enabled");}finally{s?.stop();}}async disable(e,t,n){let{protocolHandler:r}=this.config;if(!t&&!await e.isRegistered(r.protocol)){n?.inform("Deep links are not enabled");return}let i=n?.notify("Disabling deep links");try{await e.unregister(r.protocol),i?.confirm("Deep links disabled");}finally{i?.stop();}}async optionallyUpdate(e,t){let{protocolHandler:n}=this.config;if(!await e.isRegistered(n.protocol))return this.optionallyEnable(e,t);let r=t?.notify("Updating deep links");try{await this.disable(e,!0),await this.enable(e,!0),r?.confirm("Deep links updated");}finally{r?.stop();}}};var ba=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),u=l.endsWith(".json")?l:await this.locateConfig(l,n);if(u===null)continue;let f=await this.resolveConfig({...e,configPath:u});if(f?.include!==void 0)for(let h of i){let w=this.fileSystem.joinPaths("./",this.fileSystem.getRelativePath(this.fileSystem.getDirectoryName(u),h));for(let x of f.include){let M=new Minimatch(x,{partial:true,magicalBraces:true});if(!M.hasMagic()&&!x.includes(".")&&(M=new Minimatch(`${x.replace(/\/?$/,"")}/**/*`,{partial:true})),M.match(w))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.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 Ia=class{constructor({commandExecutor:e,executableLocator:t}){this.executableLocator=t,this.commandExecutor=e;}async run(e,t={}){let n=await this.executableLocator.locate(e.name);if(n===null)throw new Fe(`Unable to locate executable for command \`${e.name}\`.`);return this.commandExecutor.run({...e,name:n},t)}};var xa=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 Ko(this.initialDirectory);}static{this.READ_ONLY_COMMANDS=new Set([Mn,on,an,Et,Rt,nn,rn,cn,Bt]);}static fromDefaults(e){let t=pd("com.croct.cli"),n=new ea;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??!cd.isCI,version:e.version??"0.0.0",apiKey:e.apiKey,skipPrompts:e.skipPrompts??false,adminTokenDuration:e.adminTokenDuration??7*yt.LocalTime.SECONDS_PER_DAY,apiKeyTokenDuration:e.apiKeyTokenDuration??30*yt.LocalTime.SECONDS_PER_MINUTE,cliTokenDuration:e.cliTokenDuration??90*yt.LocalTime.SECONDS_PER_DAY,cliTokenFreshPeriod:e.cliTokenFreshPeriod??15*yt.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 Mn({version:this.configuration.version,configurationProvider:this.getCliConfigurationProvider(),deepLinkInstaller:t=>this.deepLink({operation:t?"optionally-update":"optionally-enable"})}),e)}deepLink(e){return this.execute(new Sa({packageManager:this.getNodePackageManager(),protocolRegistryProvider:this.getProtocolRegistryProvider(),configurationProvider:this.getCliConfigurationProvider(),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.getCliConfigurationProvider(),workingDirectory:new Zo(this.configuration.process),fileSystem:this.getFileSystem(),io:{input:this.getInput(),output:this.getOutput()}}),e)}init(e){return this.execute(new or({sdkProvider:this.getSdkProvider(),platformProvider:this.getPlatformProvider(),configurationManager:this.getConfigurationManager(),skipConfirmation:new Eo(new Tn(new Rn(new kn({fileSystem:this.getFileSystem(),files:[".git"]})))),api:{user:this.getUserApi(),organization:this.getOrganizationApi(),workspace:this.getWorkspaceApi()},form:{organization:new lr({input:this.getFormInput(),output:this.getOutput(),userApi:this.getUserApi()}),workspace:new ur({input:this.getFormInput(),output:this.getOutput(),organizationApi:this.getOrganizationApi()}),application:new mr({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),slot:new Ge({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})},io:{input:this.getInput(),output:this.getOutput()}}),e)}install(e){return this.execute(new on({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),io:{input:this.getInput(),output:this.getOutput()}}),e)}upgrade(e){return this.execute(new an({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),form:{slotForm:new Ge({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),componentForm:new Xe({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})},io:{input:this.getInput(),output:this.getOutput()}}),e)}addSlot(e){return this.execute(new Et({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new Ge({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}removeSlot(e){return this.execute(new nn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),slotForm:new Ge({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}addComponent(e){return this.execute(new Rt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new Xe({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}removeComponent(e){return this.execute(new rn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new Xe({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}login(e){return this.execute(new ar({authenticator:this.getAuthenticator()}),e)}logout(){return this.execute(new Bt({authenticator:this.getAuthenticator(),output:this.getOutput()}),{})}admin(e){return this.execute(new hr({output:this.getOutput(),pageForm:new Ar({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 cn({configurationManager:this.getConfigurationManager(),fileSystem:this.getFileSystem(),templateForm:new qr({input:this.getFormInput(),form:{component:new Xe({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),slot:new Ge({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),experience:new Hr({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),audience:new Gr({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 options");try{return await t.getOptions(e)}finally{r.stop();}}getUseTemplateCommand(){return new Kr({templateProvider:new $t({provider:new dn(this.getTemplateProvider()),validator:new bn}),fileSystem:this.getFileSystem(),action:this.getImportAction(),io:{input:this.getInput(),output:this.getOutput()}})}createApiKey(e){return this.execute(new Ho({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 On(new Rr(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 Jn({input:this.configuration.process.getStandardInput(),output:this.configuration.process.getStandardOutput(),onAbort:()=>e.exit(),onInteractionStart:()=>e.suspend(),onInteractionEnd:()=>e.resume()});return this.skipPrompts?new On(t):t})}getNonInteractiveOutput(e=false){let{configuration:t}=this;return new Qt({output:t.process.getStandardOutput(),formatter:this.getLogFormatter(),interactive:false,quiet:e,onExit:()=>t.process.exit(),linkOpener:async n=>{await $c(n,{wait:true});}})}getHierarchicalLogger(){return this.share(this.getHierarchicalLogger,()=>new pa(this.getLogger()))}getLogger(){return this.share(this.getLogger,()=>{let e=new ca(this.getOutput());return this.configuration.debug?e:new FilteredLogger(e,LogLevel.WARNING)})}getOutput(){return this.share(this.getOutput,()=>{let{configuration:e}=this;return new Qt({output:e.process.getStandardOutput(),formatter:this.getLogFormatter(),interactive:this.configuration.interactive,quiet:this.configuration.quiet,onExit:()=>e.process.exit(),linkOpener:async t=>{await $c(t);}})})}getLogFormatter(){return this.share(this.getLogFormatter,()=>new Yo)}getTemplateProvider(){return this.share(this.getTemplateProvider,()=>{let e=n=>new tt(...["template.json5","template.json"].map(r=>new Nt({dataProvider:n,registryProvider:new wn([{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 fn({resourceCache:new AutoSaveCache(new InMemoryCache),errorCache:new InMemoryCache,provider:new tt(new Nt({dataProvider:this.traceProvider({label:"ResourceProvider",provider:e(new gt(new tt(this.traceProvider({provider:new ln(t)}),this.traceProvider({provider:new un(t)}))))}),registryProvider:this.traceProvider({label:"NpmRegistryProvider",provider:new ra(new $t({provider:ia.json(this.traceProvider({provider:this.getHttpProvider()})),validator:new oa}))})}),e(new gt(this.getFileProvider())))})})})}getFileProvider(){return this.share(this.getFileProvider,()=>{let e=this.traceProvider({provider:this.getHttpProvider()}),t=this.traceProvider({provider:new pi(this.getFileSystem())}),n=new tt(t,this.traceProvider({provider:new ln(e)}),this.traceProvider({provider:new un(e)}));return this.traceProvider({label:"FileProvider",provider:new tt(t,this.traceProvider({provider:new Nt({baseUrl:new URL("./",this.configuration.templateRegistryUrl),dataProvider:this.traceProvider({label:"ResourceProvider",provider:n}),registryProvider:new Fi({url:this.configuration.templateRegistryUrl,provider:this.traceProvider({label:"GlobalRegistryProvider",provider:new fn({errorCache:new InMemoryCache,resourceCache:new AutoSaveCache(new InMemoryCache),provider:new $t({provider:new dn(new gt(n)),validator:new mi})})})})})}))})})}traceProvider({provider:e,label:t}){return new sa({label:t,provider:e,logger:this.getHierarchicalLogger()})}getImportAction(){return this.share(this.getImportAction,()=>{let e=this.getFileSystem(),t={run:new L({action:new et(new Te(()=>new Qi(t))),validator:new Bi}),try:new L({action:new et(new Te(()=>new ei(t.run))),validator:new hi}),test:new L({action:new et(new Te(()=>new Ti(t.run))),validator:new Mi}),repeat:new L({action:new et(new Te(()=>new Ro(t.run))),validator:new Oo}),print:new L({action:new Ni,validator:new zi}),fail:new L({action:new _i,validator:new Li}),define:new L({action:new to,validator:new eo}),prompt:new L({action:new Hi,validator:new Gi}),"change-directory":new L({action:new so({fileSystem:e,rootDirectory:this.initialDirectory,currentDirectory:this.workingDirectory}),validator:new ao}),"open-link":new L({action:new Yi,validator:new Xi}),"start-server":new L({action:new Ki({serverProvider:this.getServerProvider()}),validator:new Ji}),"stop-server":new L({action:new no({serverProvider:this.getServerProvider()}),validator:new ro}),"execute-package":new L({action:new po({packageManager:this.getPackageManager(),packageManagerProvider:this.getPackageManagerRegistry(),workingDirectory:this.workingDirectory,commandExecutor:this.getAsynchronousCommandExecutor(),commandTimeout:3*60*1e3,sourceChecker:{test:n=>n.protocol==="file:"||`${n}`.startsWith("https://github.com/croct-tech")}}),validator:new co}),"check-dependency":new L({action:new si({packageManager:this.getPackageManager()}),validator:new Si}),download:new L({action:new Zr({fileSystem:e,provider:this.getFileProvider(),codemod:new ua({codemods:{"**/*.{js,jsx,ts,tsx}":new ga(new la({fileSystem:e,rootPath:this.workingDirectory,maxSearchDepth:10,importResolver:this.getNodeImportResolver(),importCodemod:new He({fileSystem:e,codemod:new Ve({languages:["typescript","jsx"],codemod:new da})}),exportMatcher:{test:(n,{names:r})=>r.length===0?true:Dc(n).some(i=>r.includes(i))}}),new qe(this.getJavaScriptFormatter()))}})}),validator:new bi}),"add-dependency":new L({action:new Jr({packageManager:this.getPackageManager()}),validator:new xi}),"locate-file":new L({action:new Qr({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 Rn(Ao.fromPatterns(a)),i)}return i}}}),validator:new vi}),"replace-file-content":new L({action:new Br({fileSystem:e}),validator:new wi}),initialize:new L({action:new ta({callback:async()=>{if(!await this.getConfigurationManager().isInitialized())return this.init({})}}),validator:new na}),"add-slot":new L({action:new Yr({installer:(n,r)=>{let i=this.getNonInteractiveOutput(true);return this.execute(new Et({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new Ge({input:this.getNonInteractiveInput(),output:i,workspaceApi:this.getWorkspaceApi()}),io:{output:i}}),{slots:n,example:r})}}),validator:new Ci}),"add-component":new L({action:new Xr({installer:n=>{let r=this.getNonInteractiveOutput(true);return this.execute(new Rt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new Xe({input:this.getNonInteractiveInput(),output:r,workspaceApi:this.getWorkspaceApi()}),io:{output:r}}),{components:n})}}),validator:new ki}),"create-resource":new L({action:new ri({configurationManager:this.getConfigurationManager(),matcher:new oi({workspaceApi:this.getWorkspaceApi()}),api:{user:this.getUserApi(),workspace:this.getWorkspaceApi(),organization:this.getOrganizationApi()},mappingForm:new ii({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 Ai}),"format-code":new L({action:new Ri({formatter:this.getCodeFormatter()}),validator:new Oi}),import:new L({action:new et(new Te(()=>new gi({runner:t.run,templateProvider:new yi({evaluator:new di({functions:os}),validator:new bn,templateProvider:this.getTemplateProvider(),fileProvider:new gt(this.getFileProvider())}),variables:this.getActionVariables()}))),validator:new Ei})};return t.import})}getActionVariables(){let e=t=>new URL(t,this.configuration.adminUrl).toString();return {project:{features:ce.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{features:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),quotas:ce.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{quotas:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),organization:ce.transient(async()=>{let{organization:t}=await this.getConfigurationManager().load();return {slug:t,url:e(`organizations/${t}`)}}),workspace:ce.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load();return {slug:n,url:e(`organizations/${t}/workspaces/${n}`)}}),application:ce.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:ce.transient(async()=>{let t=this.getSdk(),n=await this.getConfigurationManager().load();return t.getPaths(n)}),platform:ce.transient(async()=>await this.getPlatformProvider().get()??"unknown"),server:ce.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 ai)}getAuthenticator(){return this.share(this.getAuthenticator,()=>{if(this.configuration.apiKey!==void 0)return new Go({apiKey:this.configuration.apiKey,clock:this.getClock(),tokenDuration:this.configuration.apiKeyTokenDuration});let e=this.getFormInput(),t=new gr({input:e,output:this.getOutput(),userApi:this.getUserApi(true),form:{signIn:new fr({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 yr({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 Jo({cacheKey:"token",cacheProvider:new Qo({clock:this.getClock(),clockSkewTolerance:5,tokenFreshPeriod:this.configuration.cliTokenFreshPeriod,tokenIssuer:()=>n.issueToken({duration:this.configuration.cliTokenDuration}),cacheProvider:new gn({fileSystem:this.getFileSystem(),directory:this.configuration.directories.config,useKeyAsFileName:true})}),authenticator:new Or({default:this.configuration.interactive?t:new Er({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 Wo({output:this.getOutput(),input:e,userApi:this.getUserApi(true)})}):r})}getSdk(){return this.share(this.getSdk,()=>{let e=new Wt(this.getSdkProvider(),new Te(()=>{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 Ft({discriminator:async()=>await this.getPlatformProvider().get()??i,mapping:{javascript:()=>new er({...r,bundlers:["vite","parcel","tsup","rollup"]}),react:()=>new tr({...r,importResolver:n,codemod:{provider:new qe(e,new He({fileSystem:this.getFileSystem(),codemod:new Ve({languages:["typescript","jsx"],codemod:new lt({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 ir({...r,userApi:this.getUserApi(),applicationApi:this.getApplicationApi(),importResolver:n,codemod:{middleware:new qe(e,new He({fileSystem:this.getFileSystem(),codemod:new Ve({languages:["typescript","jsx"],codemod:new vr({import:{module:"@croct/plug-next/middleware",middlewareName:"middleware",middlewareFactoryName:"withCroct",configName:"config",matcherName:"matcher",matcherLocalName:"croctMatcher"}})})})),appRouterProvider:new qe(e,new He({fileSystem:this.getFileSystem(),codemod:new Ve({languages:["typescript","jsx"],codemod:new lt({fallbackToNamedExports:false,fallbackCodemod:new wr({provider:{component:"CroctProvider",module:"@croct/plug-next/CroctProvider"}}),wrapper:{module:"@croct/plug-next/CroctProvider",component:"CroctProvider"},targets:{variable:"children"}})})})),pageRouterProvider:new qe(e,new He({fileSystem:this.getFileSystem(),codemod:new Ve({languages:["typescript","jsx"],codemod:new lt({fallbackToNamedExports:false,fallbackCodemod:new tn({provider:{component:"CroctProvider",module:"@croct/plug-next/CroctProvider"}}),wrapper:{module:"@croct/plug-next/CroctProvider",component:"CroctProvider"},targets:{component:"Component"}})})})),fallbackProvider:new qe(e,new He({fileSystem:this.getFileSystem(),codemod:new Ve({languages:["typescript","jsx"],codemod:new lt({fallbackToNamedExports:false,fallbackCodemod:new tn({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 Ft({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 Cn(new Wt(this.getNodePackageManagerProvider(),new Te(()=>{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 Cn(new Wt(this.getNodePackageManagerProvider(),new wn(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 En(new jo(new Ut({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new Fo({process:this.configuration.process,variable:"npm_config_user_agent",value:new RegExp(`^${r}`)})}))}),new Ut({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new Tn(new Lo({packageManager:r,fileSystem:t,projectDirectory:this.workingDirectory}),new kn({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.getAsynchronousCommandExecutor(),executableLocator:this.getExecutableLocator()},n=new mn,r={fileSystem:e,projectDirectory:this.workingDirectory,packageValidator:n};return {npm:new nt({...r,agent:new lo(t)}),yarn:new nt({...r,agent:new uo(t)}),bun:new nt({...r,agent:new mo(t)}),pnpm:new nt({...r,agent:new go(t)})}})}getNodeServerProvider(){return this.share(this.getNodeServerProvider,()=>new ji({packageManager:this.getNodePackageManager(),factory:this.getServerFactory(),parsers:[new Wi,new Ui,new Vi,new qi]}))}getServerProvider(){return this.share(this.getServerProvider,()=>{let e=Symbol("unknown");return new Ft({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 oo({commandExecutor:this.getAsynchronousCommandExecutor(),workingDirectory:this.workingDirectory,startupTimeout:2e4,startupCheckDelay:1500,lookupMaxPorts:30,lookupTimeout:2e3,processObserver:this.configuration.process})))}getJavaScriptFormatter(){return this.share(this.getJavaScriptFormatter,()=>new Cr({commandExecutor:this.getAsynchronousCommandExecutor(),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 ba({fileSystem:this.getFileSystem(),tsconfigValidator:new yo}))}getAsynchronousCommandExecutor(){return this.share(this.getAsynchronousCommandExecutor,()=>new Ia({executableLocator:this.getExecutableLocator(),commandExecutor:this.getCommandExecutor()}))}getSynchronousCommandExecutor(){return this.getCommandExecutor()}getCommandExecutor(){return this.share(this.getCommandExecutor,()=>new xo({currentDirectory:this.workingDirectory,windows:this.configuration.process.getPlatform()==="win32"}))}getExecutableLocator(){return this.share(this.getExecutableLocator,()=>{let{process:e}=this.configuration;return new _o({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 nt({projectDirectory:this.workingDirectory,packageValidator:new mn,fileSystem:this.getFileSystem(),agent:new So});return new En(new Ut({candidates:[{value:"nextjs",condition:new An({packageManager:e,dependencies:["next"]})},{value:"react",condition:new An({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 sr({fileSystem:this.getFileSystem(),validator:new li,projectDirectory:this.workingDirectory});return new zo({workingDirectory:this.workingDirectory,configurationProvider:this.getCliConfigurationProvider(),manager:new ti(this.configuration.interactive&&!this.isReadOnlyMode()?new kr({manager:t,initializer:{initialize:async()=>{await this.init({}),e.break();}}}):t)})})}getUserApi(e=false){return e?new en(this.getGraphqlClient(true)):this.share(this.getUserApi,()=>new en(this.getGraphqlClient()))}getOrganizationApi(){return this.share(this.getOrganizationApi,()=>new pr(this.getGraphqlClient(),this.getHierarchyResolver()))}getWorkspaceApi(){return this.share(this.getWorkspaceApi,()=>new cr(this.getGraphqlClient(),this.getHierarchyResolver()))}getApplicationApi(){return this.share(this.getApplicationApi,()=>new dr(this.getGraphqlClient(),this.getHierarchyResolver()))}getHierarchyResolver(){return this.share(this.getHierarchyResolver,()=>{let e=this.getFileSystem();return new fa(this.getGraphqlClient(),AdaptedCache.transformValues(new gn({fileSystem:e,directory:e.joinPaths(this.configuration.directories.cache,"hierarchy")}),AdaptedCache.jsonSerializer(),AdaptedCache.jsonDeserializer()))})}getGraphqlClient(e=false){return e?new Yt({endpoint:this.configuration.adminGraphqlEndpoint,tokenProvider:{getToken:()=>this.getAuthenticator().getToken()}}):this.share(this.getGraphqlClient,()=>{let t=this.getAuthenticator();return new Yt({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 Nr({platform:e.process.getPlatform(),commandExecutor:this.getSynchronousCommandExecutor(),timeout:2e3,listener:new Bo({api:this.getUserApi(true),pollingInterval:1e3})})})}getFileSystem(){return this.share(this.getFileSystem,()=>new Mr({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:yt.Instant.now(n).getSeconds()})}getEmailLinkGenerator(){return this.share(this.getEmailLinkGenerator,()=>new $r({detector:new zr(new _r,new Lr),templates:{google:new Fr,icloud:new jr,microsoft:new Wr,proton:new Ur,yahoo:new Vr}}))}getClock(){return zc.SystemClock.UTC}getProtocolRegistryProvider(){return this.share(this.getProtocolRegistryProvider,()=>new Te(()=>{let e=this.getFileSystem(),{process:t}=this.configuration;switch(t.getPlatform()){case "darwin":{let n=e.joinPaths(this.configuration.directories.data,"apps");return new ya({output:this.getOutput(),macOsRegistry:new To({fileSystem:e,appDirectory:n,commandExecutor:this.getAsynchronousCommandExecutor()}),firefoxRegistry:ha.macOs({fileSystem:e,homeDirectory:this.configuration.directories.home,appPath:e.joinPaths(n,`${this.configuration.deepLinkProtocol}.app`)})})}case "win32":return new Do({commandExecutor:this.getAsynchronousCommandExecutor()});case "linux":return new Mo({fileSystem:e,homeDirectory:this.configuration.directories.home,commandExecutor:this.getAsynchronousCommandExecutor()});default:return null}}))}getCliConfigurationProvider(){return this.share(this.getCliConfigurationProvider,()=>{let e=this.getFileSystem();return new qo({fileSystem:e,configurationProvider:new Vo({fileSystem:e,validator:new $o,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 re: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(`
|
|
1843
1843
|
`);return new d(`${e.message}
|
|
1844
1844
|
|
|
1845
1845
|
\u25B6\uFE0F **Trace**
|
|
1846
|
-
${t}`,e.help)}break;case e instanceof at: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 cs={version:"0.3.
|
|
1846
|
+
${t}`,e.help)}break;case e instanceof at: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 cs={version:"0.3.5"};function _c(o){let e=new gs().name("croct").description("Manage your Croct projects").enablePositionalOptions().option("--cwd <path>","The working directory.",y=>{try{return realpathSync(y)}catch{throw new We("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 We("The API key is malformed.")}})).option("--registry <url>","The template registry.",y=>{if(!URL.canParse(y))throw new We("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(cs.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,E)=>{await o.cli?.addSlot({slots:y,example:E.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 u=e.command("create").description("Create a resource in your project.");u.command("template").description("Create a template from your project.").addArgument(new fs("<path>","The path to the file.").argOptional()).option("-e, --empty","Create an empty template.").action(async(y,E)=>{await o.cli?.createTemplate({file:y,empty:E.empty});});let f=new se("--permissions <permissions...>","The permissions of the API key.").argParser(y=>y.split(",").map(E=>{try{return Ee.fromValue(E)}catch{throw new We(`Unknown permission "${E}".`)}})),h=new se("--env <environment>","The environment of the API key.").choices(["prod","dev"]).argParser(y=>y==="prod"?"PRODUCTION":"DEVELOPMENT");u.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?h:h.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 w={},x=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,E)=>{await o.cli?.useTemplate({template:y,options:Object.fromEntries(Object.entries(E).map(([B,De])=>[w[B],De]))});});for(let[y,E]of Object.entries(o.template??{})){let B=`--${y}${E.type!=="boolean"?" <value>":""}`,De=new se(B,E.description).makeOptionMandatory(E.required===true);switch(E.type){case "string":E.choices!==void 0&&E.choices.length>0&&De.choices(E.choices);break;case "number":De.argParser(q=>{let de=Number.parseFloat(q);if(Number.isNaN(de))throw new We("The value must be a number.");return de});break;case "array":De.argParser(q=>{let de;try{de=JSON.parse(q);}catch{}if(de===void 0||!Array.isArray(de))throw new We("The value must be a JSON array.");return q.split(",")});break;case "object":De.argParser(q=>{let de;try{de=JSON.parse(q);}catch{throw new We("The JSON is malformed.")}if(typeof de!="object"||de===null)throw new We("The value must be a JSON object.")});break}w[De.attributeName()]=y,x.addOption(De);}return e.command("enable").description("Enable a feature.").command("deep-link").description("Enable deep link support.").action(async()=>{await o.cli?.deepLink({operation:"enable"});}),e.command("disable").description("Disable a feature.").command("deep-link").description("Disable deep link support.").action(async()=>{await o.cli?.deepLink({operation:"disable"});}),e}function fd(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}function yd(o){return o.length>=2&&["enable","disable"].includes(o[0])&&o[1]==="deep-link"}async function ls(o=process.argv,e=true){let t=_c({interactive:true}).parse(o),n=t.opts(),r=xa.fromDefaults({program:p=>ls(t.args.slice(0,2).concat(p)),version:cs.version,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=fd(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({skipDeepLinkCheck:yd(t.args)}),await s.parseAsync(o);}ls();
|