croct 0.6.1 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/index.js +3 -3
  2. package/package.json +1 -1
package/index.js CHANGED
@@ -1842,9 +1842,9 @@ ${t.join(`
1842
1842
  ${this.getPreferences(e.protocol).join(`
1843
1843
  `)}`;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(`
1844
1844
  `).filter(c=>!this.getPreferences(e).includes(c)).join(`
1845
- `);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 ya=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 ha=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 g=await this.resolveConfig({...e,configPath:u});if(g?.include!==void 0)for(let y of i){let I=this.fileSystem.joinPaths("./",this.fileSystem.getRelativePath(this.fileSystem.getDirectoryName(u),y));for(let w of g.include){let D=new Minimatch(w,{partial:true,magicalBraces:true});if(!D.hasMagic()&&!w.includes(".")&&(D=new Minimatch(`${w.replace(/\/?$/,"")}/**/*`,{partial:true})),D.match(I))return o.mergeConfig({...g,rootConfigPath:a.rootConfigPath},p)}}}}return a}async locateParentConfig(e,t,n){let r=n;r.endsWith(".json")||(r+=".json");let i=this.fileSystem.joinPaths(t,r);if(await this.fileSystem.exists(i))return i;let a=this.fileSystem.joinPaths(e,"node_modules",r);return await this.fileSystem.exists(a)?a:null}async parseConfig(e){let t;try{t=JsonParser$1.parse(await this.fileSystem.readTextFile(e)).toJSON();}catch{return null}let n=await this.tsConfigValidator.validate(t);return n.valid?{rootConfigPath:e,matchedConfigPath:e,...n.data}:null}static mergeConfig(e,t){return {...t,...e,compilerOptions:{...t.compilerOptions,...e.compilerOptions}}}};var Sa=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 Me(`Unable to locate executable for command \`${e.name}\`.`);return this.commandExecutor.run({...e,name:n},t)}};function tl(o){let e=typeof o=="string"?ze(o,["jsx","typescript"]):o,t=false;return traverse(e,{enter:n=>{let{node:r}=n;if(Fd(r))return t=true,n.stop()}}),t}function Fd(o){return isTypeScript(o)||jd(o)}function jd(o){return (isImportSpecifier(o)||isImportDeclaration(o))&&(o.importKind==="type"||o.importKind==="typeof")}var ba=class{async apply(e){if(!tl(e))return {modified:false,result:e};let t=createConfigItem([Vd,{onlyRemoveTypeImports:true}]),n=createConfigItem([qd,{legacy:true}]),r={enter:function(s){let p=s.node.leadingComments??s.node.innerComments??null;if(p===null)return;let c=[];for(let l of p){let u=l.loc?.tokens??[],g=u.findIndex(y=>y.loc?.start===l.loc?.start&&y.loc?.end===l.loc?.end);if(g>=0&&g<u.length-1){let y=u[g],I=u.find((D,q)=>q>g&&!["CommentLine","CommentBlock"].includes(D.type));if(I===void 0)continue;I.loc.start.line-y.loc.end.line>1&&c.push(l);}}if(c.length>0){let l=noop();l.comments=c,s.insertBefore(l);}}},i=await transformFromAstAsync(e,void 0,{plugins:[{name:"comment-remover",visitor:{Program:r,TSTypeAliasDeclaration:r,TSInterfaceDeclaration:r,TSDeclareFunction:r,TSDeclareMethod:r,TSImportType:r,TSModuleDeclaration:r}},t,n],ast:true,configFile:false});return {result:i?.ast??e,modified:(i?.ast??null)!==null}}};var Ia=class{constructor({executableLocator:e,command:t}){this.executableLocator=e,this.command=t;}async test(){return await this.executableLocator.locate(this.command)!==null}};var va=class{constructor({serverMap:e}){this.serverMap=e;}async execute({id:e},t){let{output:n}=t,r=this.serverMap.get(e);if(r===void 0)throw new d(`No server with id "${e}" found.`);let i=n.notify("Stopping server");try{await r.stop();}finally{i.stop();}this.serverMap.delete(e);}};var xa=class{constructor({token:e}){this.token=e;}getToken(){return Promise.resolve(this.token.toString())}login(){this.reportUnsupportedOperation("login");}logout(){this.reportUnsupportedOperation("logout");}reportUnsupportedOperation(e){throw new d(`${e==="login"?"Login":"Logout"} is not supported when using an externally provided token.`,{title:"Unsupported operation",reason:"precondition",suggestions:["Do not specify the `--token` option or the `CROCT_TOKEN` environment variable."]})}};var Fn=class{constructor(e){this.factory=e;}open(e){return this.instance===void 0&&(this.instance=this.factory()),this.instance.open(e)}};var jn=class{constructor(e){this.output=e;}open(e){let t=e.replace(/([\\`*_{}[\]()#+\-.!])/g,"\\$1");return this.output.log(`[${t}](${t})`),Promise.resolve()}};var wa=class{constructor(e){this.fallbackOpener=e;}async open(e){try{await Hd(e);}catch{return this.fallbackOpener.open(e)}}};var Pa=class{constructor({packageManager:e}){this.packageManager=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Installing dependencies");try{await this.packageManager.installDependencies();}catch(i){throw S.fromCause(i)}finally{r?.stop();}}};var Gd=z$1.strictObject({}),Ca=class extends x{constructor(){super(Gd);}};var ka=class{constructor({fileSystem:e}){this.fileSystem=e;}async execute({path:e,destination:t,overwrite:n=false}){if(!await this.fileSystem.exists(e))throw new S("Cannot move path because source does not exist.",{reason:"invalid_input",details:[`Source: ${e}`]});if(await this.fileSystem.exists(t)&&!n)throw new S("Cannot move path because destination already exists.",{reason:"precondition",details:[`Destination: ${t}`]});if(this.fileSystem.isSubPath(e,t))throw new S("Cannot move path to a subdirectory of itself.",{reason:"invalid_input",details:[`Source: ${e}`,`Destination: ${t}`]});try{await this.fileSystem.move(e,t,{overwrite:n});}catch(r){throw S.fromCause(r)}}};var Aa=class{constructor({fileSystem:e}){this.fileSystem=e;}async execute(e,t){t.set(e.result,await this.readFile(e));}async readFile({path:e,optional:t=false}){if(!await this.fileSystem.exists(e)){if(!t)throw new S("Cannot read file because it does not exist.",{reason:"precondition",details:[`Path: ${e}`]});return null}if(await this.fileSystem.isDirectory(e)){if(!t)throw new S("Cannot read file because the specified path is a directory.",{reason:"precondition",details:[`Path: ${e}`]});return null}try{return this.fileSystem.readTextFile(e)}catch(n){throw S.fromCause(n)}}};var Zd=z$1.strictObject({path:z$1.string().min(1),destination:z$1.string().min(1),overwrite:z$1.boolean().optional()}),Oa=class extends x{constructor(){super(Zd);}};var Jd=z$1.strictObject({path:z$1.string().min(1),optional:z$1.boolean().optional(),result:z$1.string().min(1)}),Ta=class extends x{constructor(){super(Jd);}};var Da=class{constructor({fileSystem:e}){this.fileSystem=e;}async execute({path:e}){if(await this.fileSystem.exists(e)&&!await this.fileSystem.isDirectory(e))throw new S("Cannot create directory because a file with the same name exists.",{reason:"precondition",details:[`Path: ${e}`]});try{await this.fileSystem.createDirectory(e,{recursive:!0});}catch(t){throw S.fromCause(t)}}};var Qd=z$1.strictObject({path:z$1.string().min(1)}),Ma=class extends x{constructor(){super(Qd);}};var Na=class{constructor({fileSystem:e,input:t}){this.fileSystem=e,this.input=t;}async execute({path:e,content:t,...n}){let r=n.overwrite===true;if(!r&&await this.fileSystem.exists(e)&&(r=this.input===void 0?false:await this.input.confirm({message:`Path \`${e}\` already exists. Do you want to overwrite it?`,default:false}),!r))throw new S("Failed to write file because the specified path already exists.",{reason:"precondition",details:[`File: ${e}`]});r&&await this.fileSystem.isDirectory(e)&&await this.fileSystem.delete(e,{recursive:true});try{await this.fileSystem.writeTextFile(e,t,{overwrite:r});}catch(i){throw S.fromCause(i)}}};var Bd=z$1.strictObject({path:z$1.string().min(1),content:z$1.string(),overwrite:z$1.boolean().optional()}),La=class extends x{constructor(){super(Bd);}};var za=class{constructor(e){this.currentVersion=e.currentVersion,this.packageManager=e.packageManager,this.configurationProvider=e.configurationProvider,this.input=e.input,this.output=e.output,this.checkTimeout=e.checkTimeout,this.checkFrequency=e.checkFrequency;}async checkForUpdates(){let e=await this.configurationProvider.get();if(!this.isCheckEnabled(e))return;let t=await this.getLatestVersion();if(!(t===null||(await this.configurationProvider.save({...e,lastUpdateCheck:Date.now()}),ad.gte(this.currentVersion,t))||(this.output.announce({semantics:"info",title:"New version",message:`Update your CLI from ${this.currentVersion} \u2192 \`${t}\``}),!(await this.input?.confirm({message:"Would you like to update now?",default:true})??false)))){try{await this.packageManager.updatePackage("croct",il);}catch{let i=await this.packageManager.getPackageUpdateCommand("croct",il),a=`${i.name} ${i.arguments?.join(" ")}`;this.output.alert("Failed to update the Croct CLI automatically"),this.output.log(`Please run the command:
1846
- \`${a}\``);return}this.output.confirm("CLI updated successfully!"),this.output.inform("The new version will take effect the next time you run a command");}}isCheckEnabled(e){return e.lastUpdateCheck===void 0||Date.now()-e.lastUpdateCheck>this.checkFrequency}getLatestVersion(){let e=new AbortController;return setTimeout(()=>e.abort(),this.checkTimeout),fetch("https://registry.npmjs.org/croct/latest",{signal:e.signal}).then(t=>t.json()).then(t=>t.version).catch(()=>null)}};var Fa=class o{constructor(e){this.instances=new Map;this.configuration=e,this.initialDirectory=e.directories.current??e.process.getCurrentDirectory(),this.workingDirectory=new Go(this.initialDirectory);}static{this.READ_ONLY_COMMANDS=new Set([Nn,ln,un,Mt,Nt,pn,cn,gn,nn]);}static fromDefaults(e){let t=eg("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,stateless:e.stateless??false,interactive:e.interactive??!tg.isCI,version:e.version??"0.0.0",apiKey:e.apiKey,token:e.token,dnd:e.dnd??false,adminTokenDuration:e.adminTokenDuration??7*it.LocalTime.SECONDS_PER_DAY,apiKeyTokenDuration:e.apiKeyTokenDuration??30*it.LocalTime.SECONDS_PER_MINUTE,cliTokenDuration:e.cliTokenDuration??90*it.LocalTime.SECONDS_PER_DAY,cliTokenFreshPeriod:e.cliTokenFreshPeriod??15*it.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){let t=!this.configuration.interactive||this.configuration.dnd;return this.execute(new Nn({cliVersion:this.configuration.version,autoUpdater:new za({currentVersion:this.configuration.version,input:this.getInput(),configurationProvider:this.getCliConfigurationProvider(),packageManager:this.getNodePackageManager(),output:this.getOutput(),checkFrequency:it.LocalTime.MILLIS_PER_DAY/2,checkTimeout:500}),configurationProvider:this.getCliConfigurationProvider(),deepLinkInstaller:n=>this.deepLink({operation:n?"optionally-update":"optionally-enable"})}),{skipDeepLinkCheck:t||e.skipDeepLinkCheck===true,skipUpdateCheck:t||e.skipUpdateCheck===true})}deepLink(e){return this.execute(new ya({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){let{process:t}=this.configuration;return this.execute(new cr({sdkProvider:this.getSdkProvider(),platformProvider:this.getPlatformProvider(),configurationManager:this.getConfigurationManager(),skipConfirmation:new Eo(new Mn(new ko(new On({fileSystem:this.getFileSystem(),files:[".git"]})))),api:{user:this.getUserApi(),organization:this.getOrganizationApi(),workspace:this.getWorkspaceApi()},form:{organization:new gr({input:this.getFormInput(),output:this.getOutput(),userApi:this.getUserApi()}),workspace:new fr({input:this.getFormInput(),output:this.getOutput(),organizationApi:this.getOrganizationApi()}),application:new yr({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),slot:new Je({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})},io:{input:this.getInput(),output:this.getOutput()}}),{...e,organization:e.organization??t.getEnvValue("CROCT_ORGANIZATION")??void 0,workspace:e.workspace??t.getEnvValue("CROCT_WORKSPACE")??void 0,devApplication:e.devApplication??t.getEnvValue("CROCT_DEV_APPLICATION")??void 0,prodApplication:e.prodApplication??t.getEnvValue("CROCT_PROD_APPLICATION")??void 0,skipApiKeySetup:e.skipApiKeySetup??t.getEnvValue("CROCT_SKIP_API_KEY_SETUP")!==null})}install(e){return this.execute(new ln({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),io:{input:this.getInput(),output:this.getOutput()}}),e)}upgrade(e){return this.execute(new un({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),form:{slotForm:new Je({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),componentForm:new tt({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})},io:{input:this.getInput(),output:this.getOutput()}}),e)}addSlot(e){return this.execute(new Mt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new Je({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}removeSlot(e){return this.execute(new pn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),slotForm:new Je({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}addComponent(e){return this.execute(new Nt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new tt({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}removeComponent(e){return this.execute(new cn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new tt({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}login(e){return this.execute(new lr({authenticator:this.getAuthenticator()}),e)}logout(){return this.execute(new nn({authenticator:this.getAuthenticator(),output:this.getOutput()}),{})}admin(e){return this.execute(new vr({output:this.getOutput(),pageForm:new Tr({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 gn({configurationManager:this.getConfigurationManager(),fileSystem:this.getFileSystem(),templateForm:new Kr({input:this.getFormInput(),form:{component:new tt({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),slot:new Je({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),experience:new Gr({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),audience:new Zr({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 Jr({templateProvider:new _t({provider:new hn(this.getTemplateProvider()),validator:new xn}),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 Dn(new Mr(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 Xn({input:this.configuration.process.getStandardInput(),output:this.configuration.process.getStandardOutput(),onAbort:()=>e.exit(),onInteractionStart:()=>e.suspend(),onInteractionEnd:()=>e.resume()});return this.configuration.dnd?new Dn(t):t})}getNonInteractiveOutput(e=false){let{configuration:t}=this,n=new tn({output:t.process.getStandardOutput(),formatter:this.getLogFormatter(),interactive:false,quiet:e,onExit:()=>t.process.exit(),linkOpener:new Fn(()=>new jn(n))});return n}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,t=new tn({output:e.process.getStandardOutput(),formatter:this.getLogFormatter(),interactive:this.configuration.interactive,quiet:this.configuration.quiet,onExit:()=>e.process.exit(),linkOpener:new Fn(()=>{let n=new jn(t);return this.configuration.dnd?n:new wa(n)})});return t})}getLogFormatter(){return this.share(this.getLogFormatter,()=>new Yo)}getTemplateProvider(){return this.share(this.getTemplateProvider,()=>{let e=n=>new Ue({providers:["template.json5","template.json"].map(r=>new ht({dataProvider:n,registryProvider:new qt([{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 Sn({resourceCache:new AutoSaveCache(new InMemoryCache),errorCache:new InMemoryCache,provider:new Ue({providers:[new ht({dataProvider:this.traceProvider({label:"ResourceProvider",provider:e(new St(new Ue({providers:[this.traceProvider({provider:this.createGitHubProvider(t)}),this.traceProvider({provider:new fn(t)})]})))}),registryProvider:this.traceProvider({label:"NpmRegistryProvider",provider:new ra(new _t({provider:ia.json(this.traceProvider({provider:this.getHttpProvider()})),validator:new oa}))})}),e(new St(this.getFileProvider()))]})})})})}getFileProvider(){return this.share(this.getFileProvider,()=>{let e=this.traceProvider({provider:this.getHttpProvider()}),t=this.traceProvider({provider:new ui(this.getFileSystem(),this.getScanFilter())}),n=new Ue({providers:[t,this.traceProvider({provider:this.createGitHubProvider(e)}),this.traceProvider({provider:new fn(e)})]});return this.traceProvider({label:"FileProvider",provider:new Ue({providers:[t,this.traceProvider({provider:new ht({baseUrl:new URL("./",this.configuration.templateRegistryUrl),dataProvider:this.traceProvider({label:"ResourceProvider",provider:n}),registryProvider:new Vi({url:this.configuration.templateRegistryUrl,provider:this.traceProvider({label:"GlobalRegistryProvider",provider:new Sn({errorCache:new InMemoryCache,resourceCache:new AutoSaveCache(new InMemoryCache),provider:new _t({provider:new hn(new St(n)),validator:new yi})})})})})})]})})})}createGitHubProvider(e){let t=Date.now();return new mi({cache:new AutoSaveCache(new InMemoryCache),provider:new Ue({providers:[new Ue({providers:[new ht({dataProvider:e,registryProvider:new qt([{pattern:/^https:\/\/raw\.github\.com\/croct-tech\/templates\/(HEAD|master)\/templates\/(.+)$/i,destination:`https://cdn.croct.io/templates/$2?c=${t}`},{pattern:/^https:\/\/api\.github\.com\/repos\/croct-tech\/templates\/git\/trees\/(HEAD|master)\?recursive=true/i,destination:`https://cdn.croct.io/templates/git-tree.json?c=${t}`}])}),e]}),e]})})}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=this.getScanFilter(),n=new Map,r={run:new N({action:new nt(new De(()=>new Xi(r))),validator:new eo}),try:new N({action:new nt(new De(()=>new ri(r.run))),validator:new vi}),test:new N({action:new nt(new De(()=>new $i(r.run))),validator:new zi}),repeat:new N({action:new nt(new De(()=>new Oo(r.run))),validator:new Ro}),print:new N({action:new _i,validator:new ji}),fail:new N({action:new Wi,validator:new Ui}),define:new N({action:new io,validator:new ro}),prompt:new N({action:new Ji,validator:new Qi}),"change-directory":new N({action:new co({fileSystem:e,rootDirectory:this.initialDirectory,currentDirectory:this.workingDirectory}),validator:new po}),"open-link":new N({action:new to,validator:new no}),"start-server":new N({action:new Bi({serverProvider:this.getServerProvider(),serverFactory:this.getServerFactory(),packageManager:this.getPackageManager(),serverMap:n}),validator:new Yi}),"stop-server":new N({action:new va({serverMap:n}),validator:new oo}),"check-dependency":new N({action:new li({packageManager:this.getPackageManager()}),validator:new xi}),download:new N({action:new Qr({fileSystem:e,provider:this.getFileProvider(),codemod:new zn({codemods:{"**/*.{js,jsx,ts,tsx}":new _n(new la({fileSystem:e,rootPath:this.workingDirectory,filter:(i,a)=>a<=10&&t(i,a),importResolver:this.getNodeImportResolver(),importCodemod:new je({fileSystem:e,codemod:new Fe({languages:["typescript","jsx"],codemod:new ma})}),exportMatcher:{test:(i,{names:a})=>a.length===0?true:Yc(i).some(s=>a.includes(s))}}),new zn({codemods:{"**/*.{js,jsx}":new _n(new je({fileSystem:e,codemod:new Fe({codemod:new ba,languages:["typescript","jsx"]})}))}}),new Ze(this.getJavaScriptFormatter()))}})}),validator:new wi}),install:new N({action:new Pa({packageManager:this.getPackageManager()}),validator:new Ca}),"add-dependency":new N({action:new Br({packageManager:this.getPackageManager()}),validator:new Ci}),"execute-package":new N({action:new lo({packageManager:this.getPackageManager(),packageManagerProvider:this.getPackageManagerRegistry(),workingDirectory:this.workingDirectory,commandExecutor:this.getAsynchronousCommandExecutor(),commandTimeout:3*60*1e3,sourceChecker:{test:i=>i.protocol==="file:"||`${i}`.startsWith("https://github.com/croct-tech")}}),validator:new uo}),"locate-path":new N({action:new Xr({projectDirectory:this.workingDirectory,fileSystem:e,scanFilter:this.getScanFilter()}),validator:new ki}),"move-path":new N({action:new ka({fileSystem:e}),validator:new Oa}),"read-file":new N({action:new Aa({fileSystem:e}),validator:new Ta}),"write-file":new N({action:new Na({fileSystem:e,input:this.getInput()}),validator:new La}),"replace-file-content":new N({action:new ei({fileSystem:e}),validator:new Ai}),"create-directory":new N({action:new Da({fileSystem:e}),validator:new Ma}),"integrate-croct":new N({action:new ta({callback:async()=>{if(!await this.getConfigurationManager().isInitialized())return this.init({})}}),validator:new na}),"add-slot":new N({action:new ti({installer:(i,a)=>{let s=this.getNonInteractiveOutput(true);return this.execute(new Mt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new Je({input:this.getNonInteractiveInput(),output:s,workspaceApi:this.getWorkspaceApi()}),io:{output:s}}),{slots:i,example:a})}}),validator:new Oi}),"add-component":new N({action:new ni({installer:i=>{let a=this.getNonInteractiveOutput(true);return this.execute(new Nt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new tt({input:this.getNonInteractiveInput(),output:a,workspaceApi:this.getWorkspaceApi()}),io:{output:a}}),{components:i})}}),validator:new Ri}),"create-resource":new N({action:new ai({configurationManager:this.getConfigurationManager(),matcher:new pi({workspaceApi:this.getWorkspaceApi()}),api:{user:this.getUserApi(),workspace:this.getWorkspaceApi(),organization:this.getOrganizationApi()},mappingForm:new si({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 Ti}),"format-code":new N({action:new Mi({formatter:this.getCodeFormatter()}),validator:new Ni}),import:new N({action:new nt(new De(()=>new Si({runner:r.run,templateProvider:new Ii({evaluator:new hi({functions:Es}),validator:new xn,templateProvider:this.getTemplateProvider(),fileProvider:new St(this.getFileProvider())}),variables:this.getActionVariables()}))),validator:new Di})};return r.import})}getActionVariables(){let e=t=>new URL(t,this.configuration.adminUrl).toString();return {packageManager:ae.transient(()=>({name:this.getPackageManager().getName()})),project:{features:ae.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{features:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),quotas:ae.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{quotas:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),organization:ae.transient(async()=>{let{organization:t}=await this.getConfigurationManager().load();return {slug:t,url:e(`organizations/${t}`)}}),workspace:ae.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load();return {slug:n,url:e(`organizations/${t}/workspaces/${n}`)}}),application:ae.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:ae.transient(async()=>{let t=this.getSdk(),n=await this.getConfigurationManager().load();return t.getPaths(n)}),platform:ae.transient(async()=>await this.getPlatformProvider().get()??"unknown"),server:ae.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 ci({retry:{maxAttempts:3,delay:1e3}}))}getAuthenticator(){return this.share(this.getAuthenticator,()=>{if(this.configuration.apiKey!==void 0)return new Ko({apiKey:this.configuration.apiKey,clock:this.getClock(),tokenDuration:this.configuration.apiKeyTokenDuration});if(this.configuration.token!==void 0)return new xa({token:this.configuration.token});let e=this.getFormInput(),t=new Sr({input:e,output:this.getOutput(),userApi:this.getUserApi(true),form:{signIn:new br({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 Ir({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:this.selectCacheProvider(()=>new Ft({fileSystem:this.getFileSystem(),directory:this.configuration.directories.config,useKeyAsFileName:true}))}),authenticator:new Nr({default:this.configuration.interactive?t:new Dr({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 Kt(this.getSdkProvider(),new De(()=>{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 Co(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 Vt({discriminator:async()=>await this.getPlatformProvider().get()??i,mapping:{javascript:()=>new ir({...r,bundlers:["vite","parcel","tsup","rollup"]}),react:()=>new or({...r,importResolver:n,codemod:{provider:new Ze(e,new je({fileSystem:this.getFileSystem(),codemod:new Fe({languages:["typescript","jsx"],codemod:new mt({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 pr({...r,userApi:this.getUserApi(),applicationApi:this.getApplicationApi(),importResolver:n,codemod:{middleware:new Ze(e,new je({fileSystem:this.getFileSystem(),codemod:new Fe({languages:["typescript","jsx"],codemod:new kr({import:{module:"@croct/plug-next/middleware",middlewareName:"middleware",middlewareFactoryName:"withCroct",configName:"config",matcherName:"matcher",matcherLocalName:"croctMatcher"}})})})),appRouterProvider:new Ze(e,new je({fileSystem:this.getFileSystem(),codemod:new Fe({languages:["typescript","jsx"],codemod:new mt({fallbackToNamedExports:false,fallbackCodemod:new Ar({provider:{component:"CroctProvider",module:"@croct/plug-next/CroctProvider"}}),wrapper:{module:"@croct/plug-next/CroctProvider",component:"CroctProvider"},targets:{variable:"children"}})})})),pageRouterProvider:new Ze(e,new je({fileSystem:this.getFileSystem(),codemod:new Fe({languages:["typescript","jsx"],codemod:new mt({fallbackToNamedExports:false,fallbackCodemod:new sn({provider:{component:"CroctProvider",module:"@croct/plug-next/CroctProvider"}}),wrapper:{module:"@croct/plug-next/CroctProvider",component:"CroctProvider"},targets:{component:"Component"}})})})),fallbackProvider:new Ze(e,new je({fileSystem:this.getFileSystem(),codemod:new Fe({languages:["typescript","jsx"],codemod:new mt({fallbackToNamedExports:false,fallbackCodemod:new sn({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 Po(new Vt({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 bo(new Map(Object.entries(this.getPackageManagers()))))}getPackageManagers(){return this.getNodePackageManagers()}getPackageManager(){return this.share(this.getPackageManager,()=>new En(new Kt(this.getNodePackageManagerProvider(),new De(()=>{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 En(new Kt(this.getNodePackageManagerProvider(),new qt(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 Tn(new jo(new It({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 It({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new Mn(new _o({packageManager:r,fileSystem:t,projectDirectory:this.workingDirectory}),new On({fileSystem:t,files:n[r]}))}))}),new It({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new Ia({executableLocator:this.getExecutableLocator(),command: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 yn,r={fileSystem:e,projectDirectory:this.workingDirectory,packageValidator:n};return {npm:new rt({...r,agent:new mo(t)}),yarn:new rt({...r,agent:new go(t)}),bun:new rt({...r,agent:new fo(t)}),pnpm:new rt({...r,agent:new yo(t)})}})}getServerProvider(){return this.share(this.getServerProvider,()=>{let e=Symbol("unknown");return new Vt({discriminator:async()=>await this.getPlatformProvider().get()??e,mapping:{javascript:()=>this.getNodeServerProvider().get(),react:()=>this.getNodeServerProvider().get(),nextjs:()=>this.getNodeServerProvider().get(),[e]:()=>null}})})}getNodeServerProvider(){return this.share(this.getNodeServerProvider,()=>new qi({packageManager:this.getNodePackageManager(),factory:this.getServerFactory(),parsers:[new Hi,new Ki,new Gi,new Zi]}))}getServerFactory(){return this.share(this.getServerFactory,()=>new so({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 Or({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 ho({fileSystem:this.getFileSystem(),tsConfigLoader:this.getTsConfigLoader(),projectDirectory:this.workingDirectory}))}getTsConfigLoader(){return this.share(this.getTsConfigLoader,()=>new ha({fileSystem:this.getFileSystem(),tsconfigValidator:new So}))}getAsynchronousCommandExecutor(){return this.share(this.getAsynchronousCommandExecutor,()=>new Sa({executableLocator:this.getExecutableLocator(),commandExecutor:this.getCommandExecutor()}))}getSynchronousCommandExecutor(){return this.getCommandExecutor()}getCommandExecutor(){return this.share(this.getCommandExecutor,()=>new wo({currentDirectory:this.workingDirectory,windows:this.configuration.process.getPlatform()==="win32"}))}getExecutableLocator(){return this.share(this.getExecutableLocator,()=>{let{process:e}=this.configuration;return new zo({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 rt({projectDirectory:this.workingDirectory,packageValidator:new yn,fileSystem:this.getFileSystem(),agent:new Io});return new Tn(new It({candidates:[{value:"nextjs",condition:new Rn({packageManager:e,dependencies:["next"]})},{value:"react",condition:new Rn({packageManager:e,dependencies:["react"]})},{value:"javascript",condition:new vo({packageManager:e})}]}),this.workingDirectory)})}getConfigurationManager(){return this.share(this.getConfigurationManager,()=>{let e=this.getOutput(),t=new ur({fileSystem:this.getFileSystem(),validator:new gi,projectDirectory:this.workingDirectory});return new Lo({workingDirectory:this.workingDirectory,configurationProvider:this.getCliConfigurationProvider(),manager:new ii(this.configuration.interactive&&!this.isReadOnlyMode()?new Rr({manager:t,initializer:{initialize:async()=>{await this.init({}),e.break();}}}):t)})})}getScanFilter(){return this.share(this.getScanFilter,()=>{let e=new Ao({fileSystem:this.getFileSystem(),workingDirectory:this.workingDirectory});return async t=>!await e.test(t)})}getUserApi(e=false){return e?new an(this.getGraphqlClient(true)):this.share(this.getUserApi,()=>new an(this.getGraphqlClient()))}getOrganizationApi(){return this.share(this.getOrganizationApi,()=>new mr(this.getGraphqlClient(),this.getHierarchyResolver()))}getWorkspaceApi(){return this.share(this.getWorkspaceApi,()=>new dr(this.getGraphqlClient(),this.getHierarchyResolver()))}getApplicationApi(){return this.share(this.getApplicationApi,()=>new hr(this.getGraphqlClient(),this.getHierarchyResolver()))}getHierarchyResolver(){return this.share(this.getHierarchyResolver,()=>{let e=this.getFileSystem();return new da(this.getGraphqlClient(),AdaptedCache.transformValues(this.selectCacheProvider(()=>new Ft({fileSystem:e,directory:e.joinPaths(this.configuration.directories.cache,"hierarchy")})),AdaptedCache.jsonSerializer(),AdaptedCache.jsonDeserializer()))})}getGraphqlClient(e=false){return e?new rn({endpoint:this.configuration.adminGraphqlEndpoint,tokenProvider:{getToken:()=>this.getAuthenticator().getToken()}}):this.share(this.getGraphqlClient,()=>{let t=this.getAuthenticator();return new rn({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 Lr({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 $r({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:it.Instant.now(n).getSeconds()})}getEmailLinkGenerator(){return this.share(this.getEmailLinkGenerator,()=>new zr({detector:new _r(new Fr,new jr),templates:{google:new Wr,icloud:new Ur,microsoft:new Vr,proton:new qr,yahoo:new Hr}}))}getClock(){return ol.SystemClock.UTC}getProtocolRegistryProvider(){return this.share(this.getProtocolRegistryProvider,()=>new De(()=>{let e=this.getFileSystem(),{process:t}=this.configuration;switch(t.getPlatform()){case "darwin":{let n=e.joinPaths(this.configuration.directories.data,"apps");return new ga({output:this.getOutput(),macOsRegistry:new To({fileSystem:e,appDirectory:n,commandExecutor:this.getAsynchronousCommandExecutor()}),firefoxRegistry:fa.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}}))}selectCacheProvider(e){return this.configuration.stateless?new InMemoryCache:e()}getCliConfigurationProvider(){return this.share(this.getCliConfigurationProvider,()=>{let e=this.getFileSystem();return new qo({fileSystem:e,configurationProvider:new Vo({cacheKey:"config.json",cache:this.selectCacheProvider(()=>new Ft({fileSystem:e,directory:this.configuration.directories.config,useKeyAsFileName:true})),validator:new $o})})})}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 z:return new d(e.message,{...e.help,details:[`URL: ${e.url}`,...e.help.details??[]]});case e instanceof oe: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 S:if(e.tracing.length>0){let t=e.tracing.map(({name:n,source:r},i)=>{let a=r!==void 0?` at ${o.getSourceLocation(r)}`:"";return `${" ".repeat(i+1)}\u21B3 \`${n}\`${a}`}).join(`
1845
+ `);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 ya=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 ha=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 g=await this.resolveConfig({...e,configPath:u});if(g?.include!==void 0)for(let y of i){let I=this.fileSystem.joinPaths("./",this.fileSystem.getRelativePath(this.fileSystem.getDirectoryName(u),y));for(let w of g.include){let D=new Minimatch(w,{partial:true,magicalBraces:true});if(!D.hasMagic()&&!w.includes(".")&&(D=new Minimatch(`${w.replace(/\/?$/,"")}/**/*`,{partial:true})),D.match(I))return o.mergeConfig({...g,rootConfigPath:a.rootConfigPath},p)}}}}return a}async locateParentConfig(e,t,n){let r=n;r.endsWith(".json")||(r+=".json");let i=this.fileSystem.joinPaths(t,r);if(await this.fileSystem.exists(i))return i;let a=this.fileSystem.joinPaths(e,"node_modules",r);return await this.fileSystem.exists(a)?a:null}async parseConfig(e){let t;try{t=JsonParser$1.parse(await this.fileSystem.readTextFile(e)).toJSON();}catch{return null}let n=await this.tsConfigValidator.validate(t);return n.valid?{rootConfigPath:e,matchedConfigPath:e,...n.data}:null}static mergeConfig(e,t){return {...t,...e,compilerOptions:{...t.compilerOptions,...e.compilerOptions}}}};var Sa=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 Me(`Unable to locate executable for command \`${e.name}\`.`);return this.commandExecutor.run({...e,name:n},t)}};function tl(o){let e=typeof o=="string"?ze(o,["jsx","typescript"]):o,t=false;return traverse(e,{enter:n=>{let{node:r}=n;if(Fd(r))return t=true,n.stop()}}),t}function Fd(o){return isTypeScript(o)||jd(o)}function jd(o){return (isImportSpecifier(o)||isImportDeclaration(o))&&(o.importKind==="type"||o.importKind==="typeof")}var ba=class{async apply(e){if(!tl(e))return {modified:false,result:e};let t=createConfigItem([Vd,{onlyRemoveTypeImports:true}]),n=createConfigItem([qd,{legacy:true}]),r={enter:function(s){let p=s.node.leadingComments??s.node.innerComments??null;if(p===null)return;let c=[];for(let l of p){let u=l.loc?.tokens??[],g=u.findIndex(y=>y.loc?.start===l.loc?.start&&y.loc?.end===l.loc?.end);if(g>=0&&g<u.length-1){let y=u[g],I=u.find((D,q)=>q>g&&!["CommentLine","CommentBlock"].includes(D.type));if(I===void 0)continue;I.loc.start.line-y.loc.end.line>1&&c.push(l);}}if(c.length>0){let l=noop();l.comments=c,s.insertBefore(l);}}},i=await transformFromAstAsync(e,void 0,{plugins:[{name:"comment-remover",visitor:{Program:r,TSTypeAliasDeclaration:r,TSInterfaceDeclaration:r,TSDeclareFunction:r,TSDeclareMethod:r,TSImportType:r,TSModuleDeclaration:r}},t,n],ast:true,configFile:false});return {result:i?.ast??e,modified:(i?.ast??null)!==null}}};var Ia=class{constructor({executableLocator:e,command:t}){this.executableLocator=e,this.command=t;}async test(){return await this.executableLocator.locate(this.command)!==null}};var va=class{constructor({serverMap:e}){this.serverMap=e;}async execute({id:e},t){let{output:n}=t,r=this.serverMap.get(e);if(r===void 0)throw new d(`No server with id "${e}" found.`);let i=n.notify("Stopping server");try{await r.stop();}finally{i.stop();}this.serverMap.delete(e);}};var xa=class{constructor({token:e}){this.token=e;}getToken(){return Promise.resolve(this.token.toString())}login(){this.reportUnsupportedOperation("login");}logout(){this.reportUnsupportedOperation("logout");}reportUnsupportedOperation(e){throw new d(`${e==="login"?"Login":"Logout"} is not supported when using an externally provided token.`,{title:"Unsupported operation",reason:"precondition",suggestions:["Do not specify the `--token` option or the `CROCT_TOKEN` environment variable."]})}};var Fn=class{constructor(e){this.factory=e;}open(e){return this.instance===void 0&&(this.instance=this.factory()),this.instance.open(e)}};var jn=class{constructor(e){this.output=e;}open(e){let t=e.replace(/([\\`*_{}[\]()#+\-.!])/g,"\\$1");return this.output.log(`[${t}](${t})`),Promise.resolve()}};var wa=class{constructor(e){this.fallbackOpener=e;}async open(e){try{await Hd(e);}catch{return this.fallbackOpener.open(e)}}};var Pa=class{constructor({packageManager:e}){this.packageManager=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Installing dependencies");try{await this.packageManager.installDependencies();}catch(i){throw S.fromCause(i)}finally{r?.stop();}}};var Gd=z$1.strictObject({}),Ca=class extends x{constructor(){super(Gd);}};var ka=class{constructor({fileSystem:e}){this.fileSystem=e;}async execute({path:e,destination:t,overwrite:n=false}){if(!await this.fileSystem.exists(e))throw new S("Cannot move path because source does not exist.",{reason:"invalid_input",details:[`Source: ${e}`]});if(await this.fileSystem.exists(t)&&!n)throw new S("Cannot move path because destination already exists.",{reason:"precondition",details:[`Destination: ${t}`]});if(this.fileSystem.isSubPath(e,t))throw new S("Cannot move path to a subdirectory of itself.",{reason:"invalid_input",details:[`Source: ${e}`,`Destination: ${t}`]});try{await this.fileSystem.move(e,t,{overwrite:n});}catch(r){throw S.fromCause(r)}}};var Aa=class{constructor({fileSystem:e}){this.fileSystem=e;}async execute(e,t){t.set(e.result,await this.readFile(e));}async readFile({path:e,optional:t=false}){if(!await this.fileSystem.exists(e)){if(!t)throw new S("Cannot read file because it does not exist.",{reason:"precondition",details:[`Path: ${e}`]});return null}if(await this.fileSystem.isDirectory(e)){if(!t)throw new S("Cannot read file because the specified path is a directory.",{reason:"precondition",details:[`Path: ${e}`]});return null}try{return this.fileSystem.readTextFile(e)}catch(n){throw S.fromCause(n)}}};var Zd=z$1.strictObject({path:z$1.string().min(1),destination:z$1.string().min(1),overwrite:z$1.boolean().optional()}),Oa=class extends x{constructor(){super(Zd);}};var Jd=z$1.strictObject({path:z$1.string().min(1),optional:z$1.boolean().optional(),result:z$1.string().min(1)}),Ta=class extends x{constructor(){super(Jd);}};var Da=class{constructor({fileSystem:e}){this.fileSystem=e;}async execute({path:e}){if(await this.fileSystem.exists(e)&&!await this.fileSystem.isDirectory(e))throw new S("Cannot create directory because a file with the same name exists.",{reason:"precondition",details:[`Path: ${e}`]});try{await this.fileSystem.createDirectory(e,{recursive:!0});}catch(t){throw S.fromCause(t)}}};var Qd=z$1.strictObject({path:z$1.string().min(1)}),Ma=class extends x{constructor(){super(Qd);}};var Na=class{constructor({fileSystem:e,input:t}){this.fileSystem=e,this.input=t;}async execute({path:e,content:t,...n}){let r=n.overwrite===true;if(!r&&await this.fileSystem.exists(e)&&(r=this.input===void 0?false:await this.input.confirm({message:`Path \`${e}\` already exists. Do you want to overwrite it?`,default:false}),!r))throw new S("Failed to write file because the specified path already exists.",{reason:"precondition",details:[`File: ${e}`]});r&&await this.fileSystem.isDirectory(e)&&await this.fileSystem.delete(e,{recursive:true});try{await this.fileSystem.writeTextFile(e,t,{overwrite:r});}catch(i){throw S.fromCause(i)}}};var Bd=z$1.strictObject({path:z$1.string().min(1),content:z$1.string(),overwrite:z$1.boolean().optional()}),La=class extends x{constructor(){super(Bd);}};var za=class{constructor(e){this.currentVersion=e.currentVersion,this.packageManager=e.packageManager,this.configurationProvider=e.configurationProvider,this.input=e.input,this.output=e.output,this.checkTimeout=e.checkTimeout,this.checkFrequency=e.checkFrequency;}async checkForUpdates(){let e=await this.configurationProvider.get();if(!this.isCheckEnabled(e))return;let t=await this.getLatestVersion();if(t===null||(await this.configurationProvider.save({...e,lastUpdateCheck:Date.now()}),ad.gte(this.currentVersion,t))||(this.output.announce({semantics:"info",title:"New version",message:`Update your CLI from ${this.currentVersion} \u2192 \`${t}\``}),!(await this.input?.confirm({message:"Would you like to update now?",default:true})??false)))return;let r=this.output.notify("Updating the CLI");try{await this.packageManager.updatePackage("croct",il);}catch{let a=await this.packageManager.getPackageUpdateCommand("croct",il),s=`${a.name} ${a.arguments?.join(" ")}`;r.alert("Failed to update the CLI automatically"),this.output.log(`Please run the command:
1846
+ \`${s}\``);return}r.confirm("CLI updated successfully!"),this.output.inform("The new version will take effect the next time you run a command");}isCheckEnabled(e){return e.lastUpdateCheck===void 0||Date.now()-e.lastUpdateCheck>this.checkFrequency}getLatestVersion(){let e=new AbortController;return setTimeout(()=>e.abort(),this.checkTimeout),fetch("https://registry.npmjs.org/croct/latest",{signal:e.signal}).then(t=>t.json()).then(t=>t.version).catch(()=>null)}};var Fa=class o{constructor(e){this.instances=new Map;this.configuration=e,this.initialDirectory=e.directories.current??e.process.getCurrentDirectory(),this.workingDirectory=new Go(this.initialDirectory);}static{this.READ_ONLY_COMMANDS=new Set([Nn,ln,un,Mt,Nt,pn,cn,gn,nn]);}static fromDefaults(e){let t=eg("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,stateless:e.stateless??false,interactive:e.interactive??!tg.isCI,version:e.version??"0.0.0",apiKey:e.apiKey,token:e.token,dnd:e.dnd??false,adminTokenDuration:e.adminTokenDuration??7*it.LocalTime.SECONDS_PER_DAY,apiKeyTokenDuration:e.apiKeyTokenDuration??30*it.LocalTime.SECONDS_PER_MINUTE,cliTokenDuration:e.cliTokenDuration??90*it.LocalTime.SECONDS_PER_DAY,cliTokenFreshPeriod:e.cliTokenFreshPeriod??15*it.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){let t=!this.configuration.interactive||this.configuration.dnd;return this.execute(new Nn({cliVersion:this.configuration.version,autoUpdater:new za({currentVersion:this.configuration.version,input:this.getInput(),configurationProvider:this.getCliConfigurationProvider(),packageManager:this.getNodePackageManager(),output:this.getOutput(),checkFrequency:it.LocalTime.MILLIS_PER_DAY/2,checkTimeout:500}),configurationProvider:this.getCliConfigurationProvider(),deepLinkInstaller:n=>this.deepLink({operation:n?"optionally-update":"optionally-enable"})}),{skipDeepLinkCheck:t||e.skipDeepLinkCheck===true,skipUpdateCheck:t||e.skipUpdateCheck===true})}deepLink(e){return this.execute(new ya({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){let{process:t}=this.configuration;return this.execute(new cr({sdkProvider:this.getSdkProvider(),platformProvider:this.getPlatformProvider(),configurationManager:this.getConfigurationManager(),skipConfirmation:new Eo(new Mn(new ko(new On({fileSystem:this.getFileSystem(),files:[".git"]})))),api:{user:this.getUserApi(),organization:this.getOrganizationApi(),workspace:this.getWorkspaceApi()},form:{organization:new gr({input:this.getFormInput(),output:this.getOutput(),userApi:this.getUserApi()}),workspace:new fr({input:this.getFormInput(),output:this.getOutput(),organizationApi:this.getOrganizationApi()}),application:new yr({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),slot:new Je({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})},io:{input:this.getInput(),output:this.getOutput()}}),{...e,organization:e.organization??t.getEnvValue("CROCT_ORGANIZATION")??void 0,workspace:e.workspace??t.getEnvValue("CROCT_WORKSPACE")??void 0,devApplication:e.devApplication??t.getEnvValue("CROCT_DEV_APPLICATION")??void 0,prodApplication:e.prodApplication??t.getEnvValue("CROCT_PROD_APPLICATION")??void 0,skipApiKeySetup:e.skipApiKeySetup??t.getEnvValue("CROCT_SKIP_API_KEY_SETUP")!==null})}install(e){return this.execute(new ln({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),io:{input:this.getInput(),output:this.getOutput()}}),e)}upgrade(e){return this.execute(new un({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),form:{slotForm:new Je({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),componentForm:new tt({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})},io:{input:this.getInput(),output:this.getOutput()}}),e)}addSlot(e){return this.execute(new Mt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new Je({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}removeSlot(e){return this.execute(new pn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),slotForm:new Je({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}addComponent(e){return this.execute(new Nt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new tt({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}removeComponent(e){return this.execute(new cn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new tt({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}login(e){return this.execute(new lr({authenticator:this.getAuthenticator()}),e)}logout(){return this.execute(new nn({authenticator:this.getAuthenticator(),output:this.getOutput()}),{})}admin(e){return this.execute(new vr({output:this.getOutput(),pageForm:new Tr({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 gn({configurationManager:this.getConfigurationManager(),fileSystem:this.getFileSystem(),templateForm:new Kr({input:this.getFormInput(),form:{component:new tt({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),slot:new Je({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),experience:new Gr({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),audience:new Zr({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 Jr({templateProvider:new _t({provider:new hn(this.getTemplateProvider()),validator:new xn}),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 Dn(new Mr(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 Xn({input:this.configuration.process.getStandardInput(),output:this.configuration.process.getStandardOutput(),onAbort:()=>e.exit(),onInteractionStart:()=>e.suspend(),onInteractionEnd:()=>e.resume()});return this.configuration.dnd?new Dn(t):t})}getNonInteractiveOutput(e=false){let{configuration:t}=this,n=new tn({output:t.process.getStandardOutput(),formatter:this.getLogFormatter(),interactive:false,quiet:e,onExit:()=>t.process.exit(),linkOpener:new Fn(()=>new jn(n))});return n}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,t=new tn({output:e.process.getStandardOutput(),formatter:this.getLogFormatter(),interactive:this.configuration.interactive,quiet:this.configuration.quiet,onExit:()=>e.process.exit(),linkOpener:new Fn(()=>{let n=new jn(t);return this.configuration.dnd?n:new wa(n)})});return t})}getLogFormatter(){return this.share(this.getLogFormatter,()=>new Yo)}getTemplateProvider(){return this.share(this.getTemplateProvider,()=>{let e=n=>new Ue({providers:["template.json5","template.json"].map(r=>new ht({dataProvider:n,registryProvider:new qt([{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 Sn({resourceCache:new AutoSaveCache(new InMemoryCache),errorCache:new InMemoryCache,provider:new Ue({providers:[new ht({dataProvider:this.traceProvider({label:"ResourceProvider",provider:e(new St(new Ue({providers:[this.traceProvider({provider:this.createGitHubProvider(t)}),this.traceProvider({provider:new fn(t)})]})))}),registryProvider:this.traceProvider({label:"NpmRegistryProvider",provider:new ra(new _t({provider:ia.json(this.traceProvider({provider:this.getHttpProvider()})),validator:new oa}))})}),e(new St(this.getFileProvider()))]})})})})}getFileProvider(){return this.share(this.getFileProvider,()=>{let e=this.traceProvider({provider:this.getHttpProvider()}),t=this.traceProvider({provider:new ui(this.getFileSystem(),this.getScanFilter())}),n=new Ue({providers:[t,this.traceProvider({provider:this.createGitHubProvider(e)}),this.traceProvider({provider:new fn(e)})]});return this.traceProvider({label:"FileProvider",provider:new Ue({providers:[t,this.traceProvider({provider:new ht({baseUrl:new URL("./",this.configuration.templateRegistryUrl),dataProvider:this.traceProvider({label:"ResourceProvider",provider:n}),registryProvider:new Vi({url:this.configuration.templateRegistryUrl,provider:this.traceProvider({label:"GlobalRegistryProvider",provider:new Sn({errorCache:new InMemoryCache,resourceCache:new AutoSaveCache(new InMemoryCache),provider:new _t({provider:new hn(new St(n)),validator:new yi})})})})})})]})})})}createGitHubProvider(e){let t=Date.now();return new mi({cache:new AutoSaveCache(new InMemoryCache),provider:new Ue({providers:[new Ue({providers:[new ht({dataProvider:e,registryProvider:new qt([{pattern:/^https:\/\/raw\.github\.com\/croct-tech\/templates\/(HEAD|master)\/templates\/(.+)$/i,destination:`https://cdn.croct.io/templates/$2?c=${t}`},{pattern:/^https:\/\/api\.github\.com\/repos\/croct-tech\/templates\/git\/trees\/(HEAD|master)\?recursive=true/i,destination:`https://cdn.croct.io/templates/git-tree.json?c=${t}`}])}),e]}),e]})})}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=this.getScanFilter(),n=new Map,r={run:new N({action:new nt(new De(()=>new Xi(r))),validator:new eo}),try:new N({action:new nt(new De(()=>new ri(r.run))),validator:new vi}),test:new N({action:new nt(new De(()=>new $i(r.run))),validator:new zi}),repeat:new N({action:new nt(new De(()=>new Oo(r.run))),validator:new Ro}),print:new N({action:new _i,validator:new ji}),fail:new N({action:new Wi,validator:new Ui}),define:new N({action:new io,validator:new ro}),prompt:new N({action:new Ji,validator:new Qi}),"change-directory":new N({action:new co({fileSystem:e,rootDirectory:this.initialDirectory,currentDirectory:this.workingDirectory}),validator:new po}),"open-link":new N({action:new to,validator:new no}),"start-server":new N({action:new Bi({serverProvider:this.getServerProvider(),serverFactory:this.getServerFactory(),packageManager:this.getPackageManager(),serverMap:n}),validator:new Yi}),"stop-server":new N({action:new va({serverMap:n}),validator:new oo}),"check-dependency":new N({action:new li({packageManager:this.getPackageManager()}),validator:new xi}),download:new N({action:new Qr({fileSystem:e,provider:this.getFileProvider(),codemod:new zn({codemods:{"**/*.{js,jsx,ts,tsx}":new _n(new la({fileSystem:e,rootPath:this.workingDirectory,filter:(i,a)=>a<=10&&t(i,a),importResolver:this.getNodeImportResolver(),importCodemod:new je({fileSystem:e,codemod:new Fe({languages:["typescript","jsx"],codemod:new ma})}),exportMatcher:{test:(i,{names:a})=>a.length===0?true:Yc(i).some(s=>a.includes(s))}}),new zn({codemods:{"**/*.{js,jsx}":new _n(new je({fileSystem:e,codemod:new Fe({codemod:new ba,languages:["typescript","jsx"]})}))}}),new Ze(this.getJavaScriptFormatter()))}})}),validator:new wi}),install:new N({action:new Pa({packageManager:this.getPackageManager()}),validator:new Ca}),"add-dependency":new N({action:new Br({packageManager:this.getPackageManager()}),validator:new Ci}),"execute-package":new N({action:new lo({packageManager:this.getPackageManager(),packageManagerProvider:this.getPackageManagerRegistry(),workingDirectory:this.workingDirectory,commandExecutor:this.getAsynchronousCommandExecutor(),commandTimeout:3*60*1e3,sourceChecker:{test:i=>i.protocol==="file:"||`${i}`.startsWith("https://github.com/croct-tech")}}),validator:new uo}),"locate-path":new N({action:new Xr({projectDirectory:this.workingDirectory,fileSystem:e,scanFilter:this.getScanFilter()}),validator:new ki}),"move-path":new N({action:new ka({fileSystem:e}),validator:new Oa}),"read-file":new N({action:new Aa({fileSystem:e}),validator:new Ta}),"write-file":new N({action:new Na({fileSystem:e,input:this.getInput()}),validator:new La}),"replace-file-content":new N({action:new ei({fileSystem:e}),validator:new Ai}),"create-directory":new N({action:new Da({fileSystem:e}),validator:new Ma}),"integrate-croct":new N({action:new ta({callback:async()=>{if(!await this.getConfigurationManager().isInitialized())return this.init({})}}),validator:new na}),"add-slot":new N({action:new ti({installer:(i,a)=>{let s=this.getNonInteractiveOutput(true);return this.execute(new Mt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new Je({input:this.getNonInteractiveInput(),output:s,workspaceApi:this.getWorkspaceApi()}),io:{output:s}}),{slots:i,example:a})}}),validator:new Oi}),"add-component":new N({action:new ni({installer:i=>{let a=this.getNonInteractiveOutput(true);return this.execute(new Nt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new tt({input:this.getNonInteractiveInput(),output:a,workspaceApi:this.getWorkspaceApi()}),io:{output:a}}),{components:i})}}),validator:new Ri}),"create-resource":new N({action:new ai({configurationManager:this.getConfigurationManager(),matcher:new pi({workspaceApi:this.getWorkspaceApi()}),api:{user:this.getUserApi(),workspace:this.getWorkspaceApi(),organization:this.getOrganizationApi()},mappingForm:new si({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 Ti}),"format-code":new N({action:new Mi({formatter:this.getCodeFormatter()}),validator:new Ni}),import:new N({action:new nt(new De(()=>new Si({runner:r.run,templateProvider:new Ii({evaluator:new hi({functions:Es}),validator:new xn,templateProvider:this.getTemplateProvider(),fileProvider:new St(this.getFileProvider())}),variables:this.getActionVariables()}))),validator:new Di})};return r.import})}getActionVariables(){let e=t=>new URL(t,this.configuration.adminUrl).toString();return {packageManager:ae.transient(()=>({name:this.getPackageManager().getName()})),project:{features:ae.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{features:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),quotas:ae.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{quotas:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),organization:ae.transient(async()=>{let{organization:t}=await this.getConfigurationManager().load();return {slug:t,url:e(`organizations/${t}`)}}),workspace:ae.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load();return {slug:n,url:e(`organizations/${t}/workspaces/${n}`)}}),application:ae.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:ae.transient(async()=>{let t=this.getSdk(),n=await this.getConfigurationManager().load();return t.getPaths(n)}),platform:ae.transient(async()=>await this.getPlatformProvider().get()??"unknown"),server:ae.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 ci({retry:{maxAttempts:3,delay:1e3}}))}getAuthenticator(){return this.share(this.getAuthenticator,()=>{if(this.configuration.apiKey!==void 0)return new Ko({apiKey:this.configuration.apiKey,clock:this.getClock(),tokenDuration:this.configuration.apiKeyTokenDuration});if(this.configuration.token!==void 0)return new xa({token:this.configuration.token});let e=this.getFormInput(),t=new Sr({input:e,output:this.getOutput(),userApi:this.getUserApi(true),form:{signIn:new br({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 Ir({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:this.selectCacheProvider(()=>new Ft({fileSystem:this.getFileSystem(),directory:this.configuration.directories.config,useKeyAsFileName:true}))}),authenticator:new Nr({default:this.configuration.interactive?t:new Dr({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 Kt(this.getSdkProvider(),new De(()=>{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 Co(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 Vt({discriminator:async()=>await this.getPlatformProvider().get()??i,mapping:{javascript:()=>new ir({...r,bundlers:["vite","parcel","tsup","rollup"]}),react:()=>new or({...r,importResolver:n,codemod:{provider:new Ze(e,new je({fileSystem:this.getFileSystem(),codemod:new Fe({languages:["typescript","jsx"],codemod:new mt({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 pr({...r,userApi:this.getUserApi(),applicationApi:this.getApplicationApi(),importResolver:n,codemod:{middleware:new Ze(e,new je({fileSystem:this.getFileSystem(),codemod:new Fe({languages:["typescript","jsx"],codemod:new kr({import:{module:"@croct/plug-next/middleware",middlewareName:"middleware",middlewareFactoryName:"withCroct",configName:"config",matcherName:"matcher",matcherLocalName:"croctMatcher"}})})})),appRouterProvider:new Ze(e,new je({fileSystem:this.getFileSystem(),codemod:new Fe({languages:["typescript","jsx"],codemod:new mt({fallbackToNamedExports:false,fallbackCodemod:new Ar({provider:{component:"CroctProvider",module:"@croct/plug-next/CroctProvider"}}),wrapper:{module:"@croct/plug-next/CroctProvider",component:"CroctProvider"},targets:{variable:"children"}})})})),pageRouterProvider:new Ze(e,new je({fileSystem:this.getFileSystem(),codemod:new Fe({languages:["typescript","jsx"],codemod:new mt({fallbackToNamedExports:false,fallbackCodemod:new sn({provider:{component:"CroctProvider",module:"@croct/plug-next/CroctProvider"}}),wrapper:{module:"@croct/plug-next/CroctProvider",component:"CroctProvider"},targets:{component:"Component"}})})})),fallbackProvider:new Ze(e,new je({fileSystem:this.getFileSystem(),codemod:new Fe({languages:["typescript","jsx"],codemod:new mt({fallbackToNamedExports:false,fallbackCodemod:new sn({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 Po(new Vt({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 bo(new Map(Object.entries(this.getPackageManagers()))))}getPackageManagers(){return this.getNodePackageManagers()}getPackageManager(){return this.share(this.getPackageManager,()=>new En(new Kt(this.getNodePackageManagerProvider(),new De(()=>{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 En(new Kt(this.getNodePackageManagerProvider(),new qt(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 Tn(new jo(new It({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 It({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new Mn(new _o({packageManager:r,fileSystem:t,projectDirectory:this.workingDirectory}),new On({fileSystem:t,files:n[r]}))}))}),new It({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new Ia({executableLocator:this.getExecutableLocator(),command: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 yn,r={fileSystem:e,projectDirectory:this.workingDirectory,packageValidator:n};return {npm:new rt({...r,agent:new mo(t)}),yarn:new rt({...r,agent:new go(t)}),bun:new rt({...r,agent:new fo(t)}),pnpm:new rt({...r,agent:new yo(t)})}})}getServerProvider(){return this.share(this.getServerProvider,()=>{let e=Symbol("unknown");return new Vt({discriminator:async()=>await this.getPlatformProvider().get()??e,mapping:{javascript:()=>this.getNodeServerProvider().get(),react:()=>this.getNodeServerProvider().get(),nextjs:()=>this.getNodeServerProvider().get(),[e]:()=>null}})})}getNodeServerProvider(){return this.share(this.getNodeServerProvider,()=>new qi({packageManager:this.getNodePackageManager(),factory:this.getServerFactory(),parsers:[new Hi,new Ki,new Gi,new Zi]}))}getServerFactory(){return this.share(this.getServerFactory,()=>new so({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 Or({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 ho({fileSystem:this.getFileSystem(),tsConfigLoader:this.getTsConfigLoader(),projectDirectory:this.workingDirectory}))}getTsConfigLoader(){return this.share(this.getTsConfigLoader,()=>new ha({fileSystem:this.getFileSystem(),tsconfigValidator:new So}))}getAsynchronousCommandExecutor(){return this.share(this.getAsynchronousCommandExecutor,()=>new Sa({executableLocator:this.getExecutableLocator(),commandExecutor:this.getCommandExecutor()}))}getSynchronousCommandExecutor(){return this.getCommandExecutor()}getCommandExecutor(){return this.share(this.getCommandExecutor,()=>new wo({currentDirectory:this.workingDirectory,windows:this.configuration.process.getPlatform()==="win32"}))}getExecutableLocator(){return this.share(this.getExecutableLocator,()=>{let{process:e}=this.configuration;return new zo({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 rt({projectDirectory:this.workingDirectory,packageValidator:new yn,fileSystem:this.getFileSystem(),agent:new Io});return new Tn(new It({candidates:[{value:"nextjs",condition:new Rn({packageManager:e,dependencies:["next"]})},{value:"react",condition:new Rn({packageManager:e,dependencies:["react"]})},{value:"javascript",condition:new vo({packageManager:e})}]}),this.workingDirectory)})}getConfigurationManager(){return this.share(this.getConfigurationManager,()=>{let e=this.getOutput(),t=new ur({fileSystem:this.getFileSystem(),validator:new gi,projectDirectory:this.workingDirectory});return new Lo({workingDirectory:this.workingDirectory,configurationProvider:this.getCliConfigurationProvider(),manager:new ii(this.configuration.interactive&&!this.isReadOnlyMode()?new Rr({manager:t,initializer:{initialize:async()=>{await this.init({}),e.break();}}}):t)})})}getScanFilter(){return this.share(this.getScanFilter,()=>{let e=new Ao({fileSystem:this.getFileSystem(),workingDirectory:this.workingDirectory});return async t=>!await e.test(t)})}getUserApi(e=false){return e?new an(this.getGraphqlClient(true)):this.share(this.getUserApi,()=>new an(this.getGraphqlClient()))}getOrganizationApi(){return this.share(this.getOrganizationApi,()=>new mr(this.getGraphqlClient(),this.getHierarchyResolver()))}getWorkspaceApi(){return this.share(this.getWorkspaceApi,()=>new dr(this.getGraphqlClient(),this.getHierarchyResolver()))}getApplicationApi(){return this.share(this.getApplicationApi,()=>new hr(this.getGraphqlClient(),this.getHierarchyResolver()))}getHierarchyResolver(){return this.share(this.getHierarchyResolver,()=>{let e=this.getFileSystem();return new da(this.getGraphqlClient(),AdaptedCache.transformValues(this.selectCacheProvider(()=>new Ft({fileSystem:e,directory:e.joinPaths(this.configuration.directories.cache,"hierarchy")})),AdaptedCache.jsonSerializer(),AdaptedCache.jsonDeserializer()))})}getGraphqlClient(e=false){return e?new rn({endpoint:this.configuration.adminGraphqlEndpoint,tokenProvider:{getToken:()=>this.getAuthenticator().getToken()}}):this.share(this.getGraphqlClient,()=>{let t=this.getAuthenticator();return new rn({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 Lr({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 $r({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:it.Instant.now(n).getSeconds()})}getEmailLinkGenerator(){return this.share(this.getEmailLinkGenerator,()=>new zr({detector:new _r(new Fr,new jr),templates:{google:new Wr,icloud:new Ur,microsoft:new Vr,proton:new qr,yahoo:new Hr}}))}getClock(){return ol.SystemClock.UTC}getProtocolRegistryProvider(){return this.share(this.getProtocolRegistryProvider,()=>new De(()=>{let e=this.getFileSystem(),{process:t}=this.configuration;switch(t.getPlatform()){case "darwin":{let n=e.joinPaths(this.configuration.directories.data,"apps");return new ga({output:this.getOutput(),macOsRegistry:new To({fileSystem:e,appDirectory:n,commandExecutor:this.getAsynchronousCommandExecutor()}),firefoxRegistry:fa.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}}))}selectCacheProvider(e){return this.configuration.stateless?new InMemoryCache:e()}getCliConfigurationProvider(){return this.share(this.getCliConfigurationProvider,()=>{let e=this.getFileSystem();return new qo({fileSystem:e,configurationProvider:new Vo({cacheKey:"config.json",cache:this.selectCacheProvider(()=>new Ft({fileSystem:e,directory:this.configuration.directories.config,useKeyAsFileName:true})),validator:new $o})})})}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 z:return new d(e.message,{...e.help,details:[`URL: ${e.url}`,...e.help.details??[]]});case e instanceof oe: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 S: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(`
1847
1847
  `);return new d(`${e.message}
1848
1848
 
1849
1849
  \u25B6\uFE0F **Trace**
1850
- ${t}`,e.help)}break;case e instanceof pt: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 Ts={version:"0.6.1"};function al(o){let e=new Ls().name("croct").description("Manage your Croct projects").enablePositionalOptions().option("--cwd <path>","The working directory.",h=>{try{return realpathSync(h)}catch{throw new Ee("The path does not exist.")}}).addOption(new X("--api-key <key>","The API key to use for authentication.").env("CROCT_API_KEY").argParser(h=>{try{return ApiKey.parse(h)}catch{throw new Ee("The API key is malformed.")}}).conflicts("token")).addOption(new X("--token <token>","The JWT-formatted token to use for authentication.").env("CROCT_TOKEN").argParser(h=>{let k;try{k=Token.parse(h);}catch{throw new Ee("The token is malformed.")}if(!k.isValidNow())throw new Ee("The token is expired.");return k})).option("--registry <url>","The template registry.",h=>{if(!URL.canParse(h))throw new Ee("Malformed URL.");return h}).option("--no-interaction","Run the CLI in non-interactive mode.").addOption(new X("--stateless","Run the CLI without saving any state locally.").env("CROCT_STATELESS").default(false)).addOption(new X("--dnd","Run the CLI with minimal interaction and interruption.").env("CROCT_DND").default(false)).addOption(new X("-q, --quiet","Disable output messages.").default(false).implies({interaction:false})).option("--debug","Enable debug mode.").version(Ts.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 h=>{await o.cli?.open({url:h});});let t=e.command("login").description("Authenticate your user."),n=new X("-u, --username <username>","The email."),r=new X("-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 h=>{await o.cli?.login({method:"credentials",username:h.username,password:h.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 h=>{await o.cli?.admin({page:h!==void 0?h.join(" "):o.interactive?void 0:"/"});});let i=new X("--wor <workspace-slug>","The workspace slug."),a=new X("--org <organization-slug>","The organization slug."),s=new X("--dev-app <application-slug>","The development application slug."),p=new X("--prod-app <application-slug>","The production application slug.");e.command("init").description("Configure the project.").option("-o, --override","Override any existing configuration.").addOption(new X("-n, --new <resource>","The resources to create.").choices(["organization","org","workspace","wor","application","app"])).addOption(new X("-s, --sdk <platform>","The SDK to use.").choices(["javascript","react","next"])).addOption(new X("--skip-api-key-setup","Opt-out of API key setup.").default(false).env("CROCT_SKIP_API_KEY_SETUP")).addOption(o.interactive?a:a.makeOptionMandatory()).addOption(o.interactive?i:i.makeOptionMandatory()).addOption(o.interactive?s:s.makeOptionMandatory()).addOption(p).action(async h=>{await o.cli?.init({override:h.override,new:(()=>{switch(h.new){case "organization":case "org":return "organization";case "workspace":case "wor":return "workspace";case "application":case "app":return "application";default:return}})(),sdk:h.sdk,organization:h.org,workspace:h.wor,devApplication:h.devApp,prodApplication:h.prodApp,skipApiKeySetup:h.skipApiKeySetup});}),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 h=>{await o.cli?.upgrade({slots:h.slots??(h.components!==void 0?[]:void 0),components:h.components??(h.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(h,k)=>{await o.cli?.addSlot({slots:h,example:k.example});}),c.command("component").description("Add a component to your project.").argument(o.interactive?"[components...]":"<components...>").action(async h=>{await o.cli?.addComponent({components:h});});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 h=>{await o.cli?.removeSlot({slots:h});}),l.command("component").description("Remove a component from your project.").argument(o.interactive?"[components...]":"<components...>").action(async h=>{await o.cli?.removeComponent({components:h});});let u=e.command("create").description("Create a resource in your project.");u.command("template").description("Create a template from your project.").addArgument(new zs("<path>","The path to the file.").argOptional()).option("-e, --empty","Create an empty template.").action(async(h,k)=>{await o.cli?.createTemplate({file:h,empty:k.empty});});let g=new X("--permissions <permissions...>","The permissions of the API key.").argParser(h=>h.split(",").map(k=>{try{return Oe.fromValue(k)}catch{throw new Ee(`Unknown permission "${k}".`)}})),y=new X("--env <environment>","The environment of the API key.").choices(["prod","dev"]).argParser(h=>h==="prod"?"PRODUCTION":"DEVELOPMENT");u.command("api-key").description("Create an API key.").option("--name <name>","The name of the API key.").addOption(o.interactive?g:g.makeOptionMandatory()).addOption(o.interactive?y:y.makeOptionMandatory()).option("-c, --copy","Copy the API key to the clipboard.").action(async h=>{await o.cli?.createApiKey({name:h.name,permissions:h.permissions,environment:h.env,copy:h.copy});});let I={},w=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(h,k)=>{await o.cli?.useTemplate({template:h,options:Object.fromEntries(Object.entries(k).map(([Y,Ne])=>[I[Y],Ne]))});});for(let[h,k]of Object.entries(o.template??{})){let Y=`--${h}${k.type!=="boolean"?" <value>":""}`,Ne=new X(Y,k.description).makeOptionMandatory(k.required===true);switch(k.type){case "string":k.choices!==void 0&&k.choices.length>0&&Ne.choices(k.choices);break;case "number":Ne.argParser(H=>{let le=Number.parseFloat(H);if(Number.isNaN(le))throw new Ee("The value must be a number.");return le});break;case "array":Ne.argParser(H=>{let le;try{le=JSON.parse(H);}catch{}if(le===void 0||!Array.isArray(le))throw new Ee("The value must be a JSON array.");return le});break;case "object":Ne.argParser(H=>{let le;try{le=JSON.parse(H);}catch{throw new Ee("The JSON is malformed.")}if(typeof le!="object"||le===null)throw new Ee("The value must be a JSON object.")});break}I[Ne.attributeName()]=h,w.addOption(Ne);}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 pg(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 cg(o){return o.length>=2&&["enable","disable"].includes(o[0])&&o[1]==="deep-link"}async function Ds(o=process.argv,e=true){let t=al({interactive:true}).parse(o),n=t.opts(),r=Fa.fromDefaults({program:p=>Ds(t.args.slice(0,2).concat(p)),version:Ts.version,quiet:n.quiet,debug:n.debug,interactive:n.interaction?void 0:false,stateless:n.stateless,apiKey:n.apiKey,token:n.token,dnd:n.dnd,templateRegistryUrl:n.registry===void 0?void 0:new URL(n.registry)}),i=pg(t.args),a=i!==null?await r.getTemplateOptions(i).catch(()=>null):void 0,s=al({cli:r,interactive:n.interaction,template:a});e&&await r.welcome({skipDeepLinkCheck:cg(t.args)}),await s.parseAsync(o);}Ds();
1850
+ ${t}`,e.help)}break;case e instanceof pt: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 Ts={version:"0.6.2"};function al(o){let e=new Ls().name("croct").description("Manage your Croct projects").enablePositionalOptions().option("--cwd <path>","The working directory.",h=>{try{return realpathSync(h)}catch{throw new Ee("The path does not exist.")}}).addOption(new X("--api-key <key>","The API key to use for authentication.").env("CROCT_API_KEY").argParser(h=>{try{return ApiKey.parse(h)}catch{throw new Ee("The API key is malformed.")}}).conflicts("token")).addOption(new X("--token <token>","The JWT-formatted token to use for authentication.").env("CROCT_TOKEN").argParser(h=>{let k;try{k=Token.parse(h);}catch{throw new Ee("The token is malformed.")}if(!k.isValidNow())throw new Ee("The token is expired.");return k})).option("--registry <url>","The template registry.",h=>{if(!URL.canParse(h))throw new Ee("Malformed URL.");return h}).option("--no-interaction","Run the CLI in non-interactive mode.").addOption(new X("--stateless","Run the CLI without saving any state locally.").env("CROCT_STATELESS").default(false)).addOption(new X("--dnd","Run the CLI with minimal interaction and interruption.").env("CROCT_DND").default(false)).addOption(new X("-q, --quiet","Disable output messages.").default(false).implies({interaction:false})).option("--debug","Enable debug mode.").version(Ts.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 h=>{await o.cli?.open({url:h});});let t=e.command("login").description("Authenticate your user."),n=new X("-u, --username <username>","The email."),r=new X("-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 h=>{await o.cli?.login({method:"credentials",username:h.username,password:h.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 h=>{await o.cli?.admin({page:h!==void 0?h.join(" "):o.interactive?void 0:"/"});});let i=new X("--wor <workspace-slug>","The workspace slug."),a=new X("--org <organization-slug>","The organization slug."),s=new X("--dev-app <application-slug>","The development application slug."),p=new X("--prod-app <application-slug>","The production application slug.");e.command("init").description("Configure the project.").option("-o, --override","Override any existing configuration.").addOption(new X("-n, --new <resource>","The resources to create.").choices(["organization","org","workspace","wor","application","app"])).addOption(new X("-s, --sdk <platform>","The SDK to use.").choices(["javascript","react","next"])).addOption(new X("--skip-api-key-setup","Opt-out of API key setup.").default(false).env("CROCT_SKIP_API_KEY_SETUP")).addOption(o.interactive?a:a.makeOptionMandatory()).addOption(o.interactive?i:i.makeOptionMandatory()).addOption(o.interactive?s:s.makeOptionMandatory()).addOption(p).action(async h=>{await o.cli?.init({override:h.override,new:(()=>{switch(h.new){case "organization":case "org":return "organization";case "workspace":case "wor":return "workspace";case "application":case "app":return "application";default:return}})(),sdk:h.sdk,organization:h.org,workspace:h.wor,devApplication:h.devApp,prodApplication:h.prodApp,skipApiKeySetup:h.skipApiKeySetup});}),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 h=>{await o.cli?.upgrade({slots:h.slots??(h.components!==void 0?[]:void 0),components:h.components??(h.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(h,k)=>{await o.cli?.addSlot({slots:h,example:k.example});}),c.command("component").description("Add a component to your project.").argument(o.interactive?"[components...]":"<components...>").action(async h=>{await o.cli?.addComponent({components:h});});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 h=>{await o.cli?.removeSlot({slots:h});}),l.command("component").description("Remove a component from your project.").argument(o.interactive?"[components...]":"<components...>").action(async h=>{await o.cli?.removeComponent({components:h});});let u=e.command("create").description("Create a resource in your project.");u.command("template").description("Create a template from your project.").addArgument(new zs("<path>","The path to the file.").argOptional()).option("-e, --empty","Create an empty template.").action(async(h,k)=>{await o.cli?.createTemplate({file:h,empty:k.empty});});let g=new X("--permissions <permissions...>","The permissions of the API key.").argParser(h=>h.split(",").map(k=>{try{return Oe.fromValue(k)}catch{throw new Ee(`Unknown permission "${k}".`)}})),y=new X("--env <environment>","The environment of the API key.").choices(["prod","dev"]).argParser(h=>h==="prod"?"PRODUCTION":"DEVELOPMENT");u.command("api-key").description("Create an API key.").option("--name <name>","The name of the API key.").addOption(o.interactive?g:g.makeOptionMandatory()).addOption(o.interactive?y:y.makeOptionMandatory()).option("-c, --copy","Copy the API key to the clipboard.").action(async h=>{await o.cli?.createApiKey({name:h.name,permissions:h.permissions,environment:h.env,copy:h.copy});});let I={},w=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(h,k)=>{await o.cli?.useTemplate({template:h,options:Object.fromEntries(Object.entries(k).map(([Y,Ne])=>[I[Y],Ne]))});});for(let[h,k]of Object.entries(o.template??{})){let Y=`--${h}${k.type!=="boolean"?" <value>":""}`,Ne=new X(Y,k.description).makeOptionMandatory(k.required===true);switch(k.type){case "string":k.choices!==void 0&&k.choices.length>0&&Ne.choices(k.choices);break;case "number":Ne.argParser(H=>{let le=Number.parseFloat(H);if(Number.isNaN(le))throw new Ee("The value must be a number.");return le});break;case "array":Ne.argParser(H=>{let le;try{le=JSON.parse(H);}catch{}if(le===void 0||!Array.isArray(le))throw new Ee("The value must be a JSON array.");return le});break;case "object":Ne.argParser(H=>{let le;try{le=JSON.parse(H);}catch{throw new Ee("The JSON is malformed.")}if(typeof le!="object"||le===null)throw new Ee("The value must be a JSON object.")});break}I[Ne.attributeName()]=h,w.addOption(Ne);}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 pg(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 cg(o){return o.length>=2&&["enable","disable"].includes(o[0])&&o[1]==="deep-link"}async function Ds(o=process.argv,e=true){let t=al({interactive:true}).parse(o),n=t.opts(),r=Fa.fromDefaults({program:p=>Ds(t.args.slice(0,2).concat(p)),version:Ts.version,quiet:n.quiet,debug:n.debug,interactive:n.interaction?void 0:false,stateless:n.stateless,apiKey:n.apiKey,token:n.token,dnd:n.dnd,templateRegistryUrl:n.registry===void 0?void 0:new URL(n.registry)}),i=pg(t.args),a=i!==null?await r.getTemplateOptions(i).catch(()=>null):void 0,s=al({cli:r,interactive:n.interaction,template:a});e&&await r.welcome({skipDeepLinkCheck:cg(t.args)}),await s.parseAsync(o);}Ds();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "croct",
3
- "version": "0.6.1",
3
+ "version": "0.6.2",
4
4
  "description": "A command-line interface (CLI) for managing projects using Croct.",
5
5
  "author": {
6
6
  "name": "Croct",