croct 0.4.0 → 0.4.1

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 +2 -2
  2. package/package.json +1 -1
package/index.js CHANGED
@@ -1839,8 +1839,8 @@ ${t.join(`
1839
1839
  ${this.getPreferences(e.protocol).join(`
1840
1840
  `)}`;await this.fileSystem.writeTextFile(n,s,{overwrite:true});let p=o.parseHandlers(a);p.schemes[e.protocol]={ask:true,action:2,handlers:[{name:e.name,path:this.configuration.appPath}]},await this.fileSystem.writeTextFile(r,JSON.stringify(p),{overwrite:true});}async unregister(e){if(!await this.isRegistered(e))return;let t=await this.getProfilePath();if(t===null)return;let n=this.getUserPreferencesFilePath(t),r=this.getHandlersFilePath(t),[i,a]=await Promise.all([await this.fileSystem.readTextFile(n).catch(()=>""),this.fileSystem.readTextFile(r).catch(()=>"")]),s=i.split(`
1841
1841
  `).filter(c=>!this.getPreferences(e).includes(c)).join(`
1842
- `);await this.fileSystem.writeTextFile(n,s,{overwrite:true});let p=o.parseHandlers(a);p.schemes[e]!==void 0&&(delete p.schemes[e],await this.fileSystem.writeTextFile(r,JSON.stringify(p),{overwrite:true}));}getUserPreferencesFilePath(e){return this.fileSystem.joinPaths(e,"user.js")}getHandlersFilePath(e){return this.fileSystem.joinPaths(e,"handlers.json")}async getProfilePath(){let e=this.getPath("profiles.ini");if(!await this.fileSystem.exists(e))return null;let t=Object.values(parse$1(await this.fileSystem.readTextFile(e))),n=[],r=[];for(let a of t)a.Default!==void 0&&n.push(a.Default),a.Path!==void 0&&(a.Default==="1"?r.unshift(a.Path):r.push(a.Path));if(r.length===0)return null;let i=r[0];for(let a of r)if(n.includes(a)){i=a;break}return this.getPath(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 fa=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 ya=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 x of g.include){let M=new Minimatch(x,{partial:true,magicalBraces:true});if(!M.hasMagic()&&!x.includes(".")&&(M=new Minimatch(`${x.replace(/\/?$/,"")}/**/*`,{partial:true})),M.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.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 ha=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 De(`Unable to locate executable for command \`${e.name}\`.`);return this.commandExecutor.run({...e,name:n},t)}};function $c(o){let e=typeof o=="string"?ze(o,["jsx","typescript"]):o,t=false;return traverse(e,{enter:n=>{let{node:r}=n;if(dd(r))return t=true,n.stop()}}),t}function dd(o){return isTypeScript(o)||gd(o)}function gd(o){return (isImportSpecifier(o)||isImportDeclaration(o))&&(o.importKind==="type"||o.importKind==="typeof")}var Sa=class{async apply(e){if(!$c(e))return {modified:false,result:e};let t=createConfigItem([hd,{onlyRemoveTypeImports:true}]),n=createConfigItem([Sd,{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((M,H)=>H>g&&!["CommentLine","CommentBlock"].includes(M.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 ba=class{constructor({executableLocator:e,command:t}){this.executableLocator=e,this.command=t;}async test(){return await this.executableLocator.locate(this.command)!==null}};var Ia=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 va=class o{constructor(e){this.instances=new Map;this.configuration=e,this.skipPrompts=e.skipPrompts,this.initialDirectory=e.directories.current??e.process.getCurrentDirectory(),this.workingDirectory=new Go(this.initialDirectory);}static{this.READ_ONLY_COMMANDS=new Set([Nn,cn,ln,Dt,Mt,sn,pn,dn,tn]);}static fromDefaults(e){let t=Id("com.croct.cli"),n=new Xo;return new o({program:e.program??(()=>{throw new d("CLI is running in standalone mode.")}),process:e.process??n,quiet:e.quiet??false,debug:e.debug??false,interactive:e.interactive??!xd.isCI,version:e.version??"0.0.0",apiKey:e.apiKey,skipPrompts:e.skipPrompts??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){return this.execute(new Nn({version:this.configuration.version,configurationProvider:this.getCliConfigurationProvider(),deepLinkInstaller:t=>this.deepLink({operation:t?"optionally-update":"optionally-enable"})}),e)}deepLink(e){return this.execute(new fa({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 Mo({program:this.configuration.program,protocol:this.configuration.deepLinkProtocol,configurationProvider:this.getCliConfigurationProvider(),workingDirectory:new Ko(this.configuration.process),fileSystem:this.getFileSystem(),io:{input:this.getInput(),output:this.getOutput()}}),e)}init(e){return this.execute(new sr({sdkProvider:this.getSdkProvider(),platformProvider:this.getPlatformProvider(),configurationManager:this.getConfigurationManager(),skipConfirmation:new Ao(new Dn(new Co(new En({fileSystem:this.getFileSystem(),files:[".git"]})))),api:{user:this.getUserApi(),organization:this.getOrganizationApi(),workspace:this.getWorkspaceApi()},form:{organization:new mr({input:this.getFormInput(),output:this.getOutput(),userApi:this.getUserApi()}),workspace:new dr({input:this.getFormInput(),output:this.getOutput(),organizationApi:this.getOrganizationApi()}),application:new gr({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),slot:new Ze({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})},io:{input:this.getInput(),output:this.getOutput()}}),e)}install(e){return this.execute(new cn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),io:{input:this.getInput(),output:this.getOutput()}}),e)}upgrade(e){return this.execute(new ln({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),form:{slotForm:new Ze({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 Dt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new Ze({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}removeSlot(e){return this.execute(new sn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),slotForm:new Ze({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}addComponent(e){return this.execute(new Mt({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 pn({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 pr({authenticator:this.getAuthenticator()}),e)}logout(){return this.execute(new tn({authenticator:this.getAuthenticator(),output:this.getOutput()}),{})}admin(e){return this.execute(new br({output:this.getOutput(),pageForm:new Rr({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 dn({configurationManager:this.getConfigurationManager(),fileSystem:this.getFileSystem(),templateForm:new Gr({input:this.getFormInput(),form:{component:new tt({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),slot:new Ze({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),experience:new Kr({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 yn(this.getTemplateProvider()),validator:new vn}),fileSystem:this.getFileSystem(),action:this.getImportAction(),io:{input:this.getInput(),output:this.getOutput()}})}createApiKey(e){return this.execute(new qo({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 Tn(new Tr(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 Bn({input:this.configuration.process.getStandardInput(),output:this.configuration.process.getStandardOutput(),onAbort:()=>e.exit(),onInteractionStart:()=>e.suspend(),onInteractionEnd:()=>e.resume()});return this.skipPrompts?new Tn(t):t})}getNonInteractiveOutput(e=false){let{configuration:t}=this;return new en({output:t.process.getStandardOutput(),formatter:this.getLogFormatter(),interactive:false,quiet:e,onExit:()=>t.process.exit(),linkOpener:async n=>{await Lc(n,{wait:true});}})}getHierarchicalLogger(){return this.share(this.getHierarchicalLogger,()=>new sa(this.getLogger()))}getLogger(){return this.share(this.getLogger,()=>{let e=new pa(this.getOutput());return this.configuration.debug?e:new FilteredLogger(e,LogLevel.WARNING)})}getOutput(){return this.share(this.getOutput,()=>{let{configuration:e}=this;return new en({output:e.process.getStandardOutput(),formatter:this.getLogFormatter(),interactive:this.configuration.interactive,quiet:this.configuration.quiet,onExit:()=>e.process.exit(),linkOpener:async t=>{await Lc(t);}})})}getLogFormatter(){return this.share(this.getLogFormatter,()=>new Bo)}getTemplateProvider(){return this.share(this.getTemplateProvider,()=>{let e=n=>new We({providers:["template.json5","template.json"].map(r=>new yt({dataProvider:n,registryProvider:new Vt([{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 We({providers:[new yt({dataProvider:this.traceProvider({label:"ResourceProvider",provider:e(new ht(new We({providers:[this.traceProvider({provider:this.createGitHubProvider(t)}),this.traceProvider({provider:new gn(t)})]})))}),registryProvider:this.traceProvider({label:"NpmRegistryProvider",provider:new na(new _t({provider:ra.json(this.traceProvider({provider:this.getHttpProvider()})),validator:new ia}))})}),e(new ht(this.getFileProvider()))]})})})})}getFileProvider(){return this.share(this.getFileProvider,()=>{let e=this.traceProvider({provider:this.getHttpProvider()}),t=this.traceProvider({provider:new li(this.getFileSystem(),this.getScanFilter())}),n=new We({providers:[t,this.traceProvider({provider:this.createGitHubProvider(e)}),this.traceProvider({provider:new gn(e)})]});return this.traceProvider({label:"FileProvider",provider:new We({providers:[t,this.traceProvider({provider:new yt({baseUrl:new URL("./",this.configuration.templateRegistryUrl),dataProvider:this.traceProvider({label:"ResourceProvider",provider:n}),registryProvider:new Ui({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 yn(new ht(n)),validator:new fi})})})})})})]})})})}createGitHubProvider(e){return new ui({cache:new AutoSaveCache(new InMemoryCache),provider:new We({providers:[new We({providers:[new yt({dataProvider:e,registryProvider:new Vt([{pattern:/^https:\/\/raw\.github\.com\/croct-tech\/templates\/(HEAD|master)\/templates\/(.+)$/i,destination:"https://cdn.croct.io/templates/$2"},{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"}])}),e]}),e]})})}traceProvider({provider:e,label:t}){return new aa({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 F({action:new nt(new Te(()=>new Yi(r))),validator:new Xi}),try:new F({action:new nt(new Te(()=>new ni(r.run))),validator:new Ii}),test:new F({action:new nt(new Te(()=>new Ni(r.run))),validator:new zi}),repeat:new F({action:new nt(new Te(()=>new Eo(r.run))),validator:new Ro}),print:new F({action:new Li,validator:new Fi}),fail:new F({action:new ji,validator:new Wi}),define:new F({action:new ro,validator:new no}),prompt:new F({action:new Zi,validator:new Ji}),"change-directory":new F({action:new po({fileSystem:e,rootDirectory:this.initialDirectory,currentDirectory:this.workingDirectory}),validator:new so}),"open-link":new F({action:new eo,validator:new to}),"start-server":new F({action:new Qi({serverProvider:this.getServerProvider(),serverFactory:this.getServerFactory(),packageManager:this.getPackageManager(),serverMap:n}),validator:new Bi}),"stop-server":new F({action:new Ia({serverMap:n}),validator:new io}),"execute-package":new F({action:new co({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 lo}),"check-dependency":new F({action:new ci({packageManager:this.getPackageManager()}),validator:new xi}),download:new F({action:new Qr({fileSystem:e,provider:this.getFileProvider(),codemod:new Ln({codemods:{"**/*.{js,jsx,ts,tsx}":new _n(new ca({fileSystem:e,rootPath:this.workingDirectory,filter:(i,a)=>a<=10&&t(i,a),importResolver:this.getNodeImportResolver(),importCodemod:new Fe({fileSystem:e,codemod:new _e({languages:["typescript","jsx"],codemod:new ua})}),exportMatcher:{test:(i,{names:a})=>a.length===0?true:Dc(i).some(s=>a.includes(s))}}),new Ln({codemods:{"**/*.{js,jsx}":new _n(new Fe({fileSystem:e,codemod:new _e({codemod:new Sa,languages:["typescript","jsx"]})}))}}),new Ke(this.getJavaScriptFormatter()))}})}),validator:new vi}),"add-dependency":new F({action:new Br({packageManager:this.getPackageManager()}),validator:new Pi}),"locate-file":new F({action:new Yr({projectDirectory:this.workingDirectory,fileSystem:e,scanFilter:this.getScanFilter()}),validator:new Ci}),"replace-file-content":new F({action:new Xr({fileSystem:e}),validator:new ki}),initialize:new F({action:new ea({callback:async()=>{if(!await this.getConfigurationManager().isInitialized())return this.init({})}}),validator:new ta}),"add-slot":new F({action:new ei({installer:(i,a)=>{let s=this.getNonInteractiveOutput(true);return this.execute(new Dt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new Ze({input:this.getNonInteractiveInput(),output:s,workspaceApi:this.getWorkspaceApi()}),io:{output:s}}),{slots:i,example:a})}}),validator:new Ei}),"add-component":new F({action:new ti({installer:i=>{let a=this.getNonInteractiveOutput(true);return this.execute(new Mt({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 F({action:new oi({configurationManager:this.getConfigurationManager(),matcher:new si({workspaceApi:this.getWorkspaceApi()}),api:{user:this.getUserApi(),workspace:this.getWorkspaceApi(),organization:this.getOrganizationApi()},mappingForm:new ai({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 Oi}),"format-code":new F({action:new Di({formatter:this.getCodeFormatter()}),validator:new Mi}),import:new F({action:new nt(new Te(()=>new hi({runner:r.run,templateProvider:new bi({evaluator:new yi({functions:as}),validator:new vn,templateProvider:this.getTemplateProvider(),fileProvider:new ht(this.getFileProvider())}),variables:this.getActionVariables()}))),validator:new Ti})};return r.import})}getActionVariables(){let e=t=>new URL(t,this.configuration.adminUrl).toString();return {project:{features:ce.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{features:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),quotas:ce.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{quotas:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),organization:ce.transient(async()=>{let{organization:t}=await this.getConfigurationManager().load();return {slug:t,url:e(`organizations/${t}`)}}),workspace:ce.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load();return {slug:n,url:e(`organizations/${t}/workspaces/${n}`)}}),application:ce.transient(async()=>{let{organization:t,workspace:n,applications:r}=await this.getConfigurationManager().load(),i=`organizations/${t}/workspaces/${n}/applications/`;return {development:{slug:r.development,url:e(i+r.development)},production:{slug:r.production,url:e(i+r.production)}}}),path:ce.transient(async()=>{let t=this.getSdk(),n=await this.getConfigurationManager().load();return t.getPaths(n)}),platform:ce.transient(async()=>await this.getPlatformProvider().get()??"unknown"),server:ce.transient(async()=>{let n=await this.getServerProvider().get();if(n===null)return null;try{let r=await n.getStatus();if(r.running)return {running:!0,url:r.url.toString()}}catch{}return {running:false}})}}}getHttpProvider(){return this.share(this.getHttpProvider,()=>new pi({retry:{maxAttempts:3,delay:1e3}}))}getAuthenticator(){return this.share(this.getAuthenticator,()=>{if(this.configuration.apiKey!==void 0)return new Ho({apiKey:this.configuration.apiKey,clock:this.getClock(),tokenDuration:this.configuration.apiKeyTokenDuration});let e=this.getFormInput(),t=new yr({input:e,output:this.getOutput(),userApi:this.getUserApi(true),form:{signIn:new hr({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 Sr({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 Zo({cacheKey:"token",cacheProvider:new Jo({clock:this.getClock(),clockSkewTolerance:5,tokenFreshPeriod:this.configuration.cliTokenFreshPeriod,tokenIssuer:()=>n.issueToken({duration:this.configuration.cliTokenDuration}),cacheProvider:new hn({fileSystem:this.getFileSystem(),directory:this.configuration.directories.config,useKeyAsFileName:true})}),authenticator:new Dr({default:this.configuration.interactive?t:new Or({authenticator:t,instruction:{message:"Authentication required.",suggestions:["Run `login` to authenticate"],reason:"precondition"}}),credentials:t})});return this.configuration.interactive?new Wo({authenticator:r,invitationForm:new jo({output:this.getOutput(),input:e,userApi:this.getUserApi(true)})}):r})}getSdk(){return this.share(this.getSdk,()=>{let e=new Ht(this.getSdkProvider(),new Te(()=>{throw new U("No suitable SDK detected.",{reason:"not_supported",suggestions:["Make sure you are running the command in the project root directory."]})}));return new Po(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 Ut({discriminator:async()=>await this.getPlatformProvider().get()??i,mapping:{javascript:()=>new nr({...r,bundlers:["vite","parcel","tsup","rollup"]}),react:()=>new rr({...r,importResolver:n,codemod:{provider:new Ke(e,new Fe({fileSystem:this.getFileSystem(),codemod:new _e({languages:["typescript","jsx"],codemod:new ut({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 ar({...r,userApi:this.getUserApi(),applicationApi:this.getApplicationApi(),importResolver:n,codemod:{middleware:new Ke(e,new Fe({fileSystem:this.getFileSystem(),codemod:new _e({languages:["typescript","jsx"],codemod:new Pr({import:{module:"@croct/plug-next/middleware",middlewareName:"middleware",middlewareFactoryName:"withCroct",configName:"config",matcherName:"matcher",matcherLocalName:"croctMatcher"}})})})),appRouterProvider:new Ke(e,new Fe({fileSystem:this.getFileSystem(),codemod:new _e({languages:["typescript","jsx"],codemod:new ut({fallbackToNamedExports:false,fallbackCodemod:new Cr({provider:{component:"CroctProvider",module:"@croct/plug-next/CroctProvider"}}),wrapper:{module:"@croct/plug-next/CroctProvider",component:"CroctProvider"},targets:{variable:"children"}})})})),pageRouterProvider:new Ke(e,new Fe({fileSystem:this.getFileSystem(),codemod:new _e({languages:["typescript","jsx"],codemod:new ut({fallbackToNamedExports:false,fallbackCodemod:new an({provider:{component:"CroctProvider",module:"@croct/plug-next/CroctProvider"}}),wrapper:{module:"@croct/plug-next/CroctProvider",component:"CroctProvider"},targets:{component:"Component"}})})})),fallbackProvider:new Ke(e,new Fe({fileSystem:this.getFileSystem(),codemod:new _e({languages:["typescript","jsx"],codemod:new ut({fallbackToNamedExports:false,fallbackCodemod:new an({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 wo(new Ut({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 So(new Map(Object.entries(this.getPackageManagers()))))}getPackageManagers(){return this.getNodePackageManagers()}getPackageManager(){return this.share(this.getPackageManager,()=>new An(new Ht(this.getNodePackageManagerProvider(),new Te(()=>{throw new U("No package manager detected.",{reason:"not_supported",suggestions:["Make sure you are running the command in the project root directory.","Initialize your project and retry the command."]})}))))}getNodePackageManager(){return this.share(this.getNodePackageManager,()=>{let e=this.getNodePackageManagers();return new An(new Ht(this.getNodePackageManagerProvider(),new Vt(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 On(new Fo(new bt({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new _o({process:this.configuration.process,variable:"npm_config_user_agent",value:new RegExp(`^${r}`)})}))}),new bt({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new Dn(new Lo({packageManager:r,fileSystem:t,projectDirectory:this.workingDirectory}),new En({fileSystem:t,files:n[r]}))}))}),new bt({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new ba({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 fn,r={fileSystem:e,projectDirectory:this.workingDirectory,packageValidator:n};return {npm:new rt({...r,agent:new uo(t)}),yarn:new rt({...r,agent:new mo(t)}),bun:new rt({...r,agent:new go(t)}),pnpm:new rt({...r,agent:new fo(t)})}})}getServerProvider(){return this.share(this.getServerProvider,()=>{let e=Symbol("unknown");return new Ut({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 Vi({packageManager:this.getNodePackageManager(),factory:this.getServerFactory(),parsers:[new qi,new Hi,new Gi,new Ki]}))}getServerFactory(){return this.share(this.getServerFactory,()=>new ao({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 Ar({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 yo({fileSystem:this.getFileSystem(),tsConfigLoader:this.getTsConfigLoader(),projectDirectory:this.workingDirectory}))}getTsConfigLoader(){return this.share(this.getTsConfigLoader,()=>new ya({fileSystem:this.getFileSystem(),tsconfigValidator:new ho}))}getAsynchronousCommandExecutor(){return this.share(this.getAsynchronousCommandExecutor,()=>new ha({executableLocator:this.getExecutableLocator(),commandExecutor:this.getCommandExecutor()}))}getSynchronousCommandExecutor(){return this.getCommandExecutor()}getCommandExecutor(){return this.share(this.getCommandExecutor,()=>new vo({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 fn,fileSystem:this.getFileSystem(),agent:new bo});return new On(new bt({candidates:[{value:"nextjs",condition:new Rn({packageManager:e,dependencies:["next"]})},{value:"react",condition:new Rn({packageManager:e,dependencies:["react"]})},{value:"javascript",condition:new Io({packageManager:e})}]}),this.workingDirectory)})}getConfigurationManager(){return this.share(this.getConfigurationManager,()=>{let e=this.getOutput(),t=new cr({fileSystem:this.getFileSystem(),validator:new di,projectDirectory:this.workingDirectory});return new $o({workingDirectory:this.workingDirectory,configurationProvider:this.getCliConfigurationProvider(),manager:new ri(this.configuration.interactive&&!this.isReadOnlyMode()?new Er({manager:t,initializer:{initialize:async()=>{await this.init({}),e.break();}}}):t)})})}getScanFilter(){return this.share(this.getScanFilter,()=>{let e=new ko({fileSystem:this.getFileSystem(),workingDirectory:this.workingDirectory});return async t=>!await e.test(t)})}getUserApi(e=false){return e?new on(this.getGraphqlClient(true)):this.share(this.getUserApi,()=>new on(this.getGraphqlClient()))}getOrganizationApi(){return this.share(this.getOrganizationApi,()=>new lr(this.getGraphqlClient(),this.getHierarchyResolver()))}getWorkspaceApi(){return this.share(this.getWorkspaceApi,()=>new ur(this.getGraphqlClient(),this.getHierarchyResolver()))}getApplicationApi(){return this.share(this.getApplicationApi,()=>new fr(this.getGraphqlClient(),this.getHierarchyResolver()))}getHierarchyResolver(){return this.share(this.getHierarchyResolver,()=>{let e=this.getFileSystem();return new ma(this.getGraphqlClient(),AdaptedCache.transformValues(new hn({fileSystem:e,directory:e.joinPaths(this.configuration.directories.cache,"hierarchy")}),AdaptedCache.jsonSerializer(),AdaptedCache.jsonDeserializer()))})}getGraphqlClient(e=false){return e?new nn({endpoint:this.configuration.adminGraphqlEndpoint,tokenProvider:{getToken:()=>this.getAuthenticator().getToken()}}):this.share(this.getGraphqlClient,()=>{let t=this.getAuthenticator();return new nn({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 zr({platform:e.process.getPlatform(),commandExecutor:this.getSynchronousCommandExecutor(),timeout:2e3,listener:new Qo({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 Lr({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 _c.SystemClock.UTC}getProtocolRegistryProvider(){return this.share(this.getProtocolRegistryProvider,()=>new Te(()=>{let e=this.getFileSystem(),{process:t}=this.configuration;switch(t.getPlatform()){case "darwin":{let n=e.joinPaths(this.configuration.directories.data,"apps");return new da({output:this.getOutput(),macOsRegistry:new Oo({fileSystem:e,appDirectory:n,commandExecutor:this.getAsynchronousCommandExecutor()}),firefoxRegistry:ga.macOs({fileSystem:e,homeDirectory:this.configuration.directories.home,appPath:e.joinPaths(n,`${this.configuration.deepLinkProtocol}.app`)})})}case "win32":return new To({commandExecutor:this.getAsynchronousCommandExecutor()});case "linux":return new Do({fileSystem:e,homeDirectory:this.configuration.directories.home,commandExecutor:this.getAsynchronousCommandExecutor()});default:return null}}))}getCliConfigurationProvider(){return this.share(this.getCliConfigurationProvider,()=>{let e=this.getFileSystem();return new Vo({fileSystem:e,configurationProvider:new Uo({fileSystem:e,validator:new No,filePath:e.joinPaths(this.configuration.directories.config,"config.json")})})})}async execute(e,t){if(this.isReadOnlyMode()&&!o.READ_ONLY_COMMANDS.has(e.constructor))return this.reportError(new d("This command does not support API key authentication.",{reason:"precondition",suggestions:["Run the command without specifying an API key."]}));try{await e.execute(t);}catch(n){let r=o.handleError(n);return n instanceof Error&&r instanceof Error&&(r.stack=n.stack),this.reportError(r)}}isReadOnlyMode(){return this.configuration.apiKey!==void 0}reportError(e){let t=this.getOutput();return t.report(o.handleError(e)),t.exit()}static handleError(e){switch(true){case e instanceof z:return new d(e.message,{...e.help,details:[`URL: ${e.url}`,...e.help.details??[]]});case e instanceof ie: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 v:if(e.tracing.length>0){let t=e.tracing.map(({name:n,source:r},i)=>{let a=r!==void 0?` at ${o.getSourceLocation(r)}`:"";return `${" ".repeat(i+1)}\u21B3 \`${n}\`${a}`}).join(`
1842
+ `);await this.fileSystem.writeTextFile(n,s,{overwrite:true});let p=o.parseHandlers(a);p.schemes[e]!==void 0&&(delete p.schemes[e],await this.fileSystem.writeTextFile(r,JSON.stringify(p),{overwrite:true}));}getUserPreferencesFilePath(e){return this.fileSystem.joinPaths(e,"user.js")}getHandlersFilePath(e){return this.fileSystem.joinPaths(e,"handlers.json")}async getProfilePath(){let e=this.getPath("profiles.ini");if(!await this.fileSystem.exists(e))return null;let t=Object.values(parse$1(await this.fileSystem.readTextFile(e))),n=[],r=[];for(let a of t)a.Default!==void 0&&n.push(a.Default),a.Path!==void 0&&(a.Default==="1"?r.unshift(a.Path):r.push(a.Path));if(r.length===0)return null;let i=r[0];for(let a of r)if(n.includes(a)){i=a;break}return this.getPath(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 fa=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 ya=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 x of g.include){let M=new Minimatch(x,{partial:true,magicalBraces:true});if(!M.hasMagic()&&!x.includes(".")&&(M=new Minimatch(`${x.replace(/\/?$/,"")}/**/*`,{partial:true})),M.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.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 ha=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 De(`Unable to locate executable for command \`${e.name}\`.`);return this.commandExecutor.run({...e,name:n},t)}};function $c(o){let e=typeof o=="string"?ze(o,["jsx","typescript"]):o,t=false;return traverse(e,{enter:n=>{let{node:r}=n;if(dd(r))return t=true,n.stop()}}),t}function dd(o){return isTypeScript(o)||gd(o)}function gd(o){return (isImportSpecifier(o)||isImportDeclaration(o))&&(o.importKind==="type"||o.importKind==="typeof")}var Sa=class{async apply(e){if(!$c(e))return {modified:false,result:e};let t=createConfigItem([hd,{onlyRemoveTypeImports:true}]),n=createConfigItem([Sd,{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((M,H)=>H>g&&!["CommentLine","CommentBlock"].includes(M.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 ba=class{constructor({executableLocator:e,command:t}){this.executableLocator=e,this.command=t;}async test(){return await this.executableLocator.locate(this.command)!==null}};var Ia=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 va=class o{constructor(e){this.instances=new Map;this.configuration=e,this.skipPrompts=e.skipPrompts,this.initialDirectory=e.directories.current??e.process.getCurrentDirectory(),this.workingDirectory=new Go(this.initialDirectory);}static{this.READ_ONLY_COMMANDS=new Set([Nn,cn,ln,Dt,Mt,sn,pn,dn,tn]);}static fromDefaults(e){let t=Id("com.croct.cli"),n=new Xo;return new o({program:e.program??(()=>{throw new d("CLI is running in standalone mode.")}),process:e.process??n,quiet:e.quiet??false,debug:e.debug??false,interactive:e.interactive??!xd.isCI,version:e.version??"0.0.0",apiKey:e.apiKey,skipPrompts:e.skipPrompts??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){return this.execute(new Nn({version:this.configuration.version,configurationProvider:this.getCliConfigurationProvider(),deepLinkInstaller:t=>this.deepLink({operation:t?"optionally-update":"optionally-enable"})}),e)}deepLink(e){return this.execute(new fa({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 Mo({program:this.configuration.program,protocol:this.configuration.deepLinkProtocol,configurationProvider:this.getCliConfigurationProvider(),workingDirectory:new Ko(this.configuration.process),fileSystem:this.getFileSystem(),io:{input:this.getInput(),output:this.getOutput()}}),e)}init(e){return this.execute(new sr({sdkProvider:this.getSdkProvider(),platformProvider:this.getPlatformProvider(),configurationManager:this.getConfigurationManager(),skipConfirmation:new Ao(new Dn(new Co(new En({fileSystem:this.getFileSystem(),files:[".git"]})))),api:{user:this.getUserApi(),organization:this.getOrganizationApi(),workspace:this.getWorkspaceApi()},form:{organization:new mr({input:this.getFormInput(),output:this.getOutput(),userApi:this.getUserApi()}),workspace:new dr({input:this.getFormInput(),output:this.getOutput(),organizationApi:this.getOrganizationApi()}),application:new gr({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),slot:new Ze({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})},io:{input:this.getInput(),output:this.getOutput()}}),e)}install(e){return this.execute(new cn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),io:{input:this.getInput(),output:this.getOutput()}}),e)}upgrade(e){return this.execute(new ln({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),form:{slotForm:new Ze({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 Dt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new Ze({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}removeSlot(e){return this.execute(new sn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),slotForm:new Ze({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}addComponent(e){return this.execute(new Mt({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 pn({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 pr({authenticator:this.getAuthenticator()}),e)}logout(){return this.execute(new tn({authenticator:this.getAuthenticator(),output:this.getOutput()}),{})}admin(e){return this.execute(new br({output:this.getOutput(),pageForm:new Rr({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 dn({configurationManager:this.getConfigurationManager(),fileSystem:this.getFileSystem(),templateForm:new Gr({input:this.getFormInput(),form:{component:new tt({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),slot:new Ze({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),experience:new Kr({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 yn(this.getTemplateProvider()),validator:new vn}),fileSystem:this.getFileSystem(),action:this.getImportAction(),io:{input:this.getInput(),output:this.getOutput()}})}createApiKey(e){return this.execute(new qo({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 Tn(new Tr(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 Bn({input:this.configuration.process.getStandardInput(),output:this.configuration.process.getStandardOutput(),onAbort:()=>e.exit(),onInteractionStart:()=>e.suspend(),onInteractionEnd:()=>e.resume()});return this.skipPrompts?new Tn(t):t})}getNonInteractiveOutput(e=false){let{configuration:t}=this;return new en({output:t.process.getStandardOutput(),formatter:this.getLogFormatter(),interactive:false,quiet:e,onExit:()=>t.process.exit(),linkOpener:async n=>{await Lc(n,{wait:true});}})}getHierarchicalLogger(){return this.share(this.getHierarchicalLogger,()=>new sa(this.getLogger()))}getLogger(){return this.share(this.getLogger,()=>{let e=new pa(this.getOutput());return this.configuration.debug?e:new FilteredLogger(e,LogLevel.WARNING)})}getOutput(){return this.share(this.getOutput,()=>{let{configuration:e}=this;return new en({output:e.process.getStandardOutput(),formatter:this.getLogFormatter(),interactive:this.configuration.interactive,quiet:this.configuration.quiet,onExit:()=>e.process.exit(),linkOpener:async t=>{await Lc(t);}})})}getLogFormatter(){return this.share(this.getLogFormatter,()=>new Bo)}getTemplateProvider(){return this.share(this.getTemplateProvider,()=>{let e=n=>new We({providers:["template.json5","template.json"].map(r=>new yt({dataProvider:n,registryProvider:new Vt([{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 We({providers:[new yt({dataProvider:this.traceProvider({label:"ResourceProvider",provider:e(new ht(new We({providers:[this.traceProvider({provider:this.createGitHubProvider(t)}),this.traceProvider({provider:new gn(t)})]})))}),registryProvider:this.traceProvider({label:"NpmRegistryProvider",provider:new na(new _t({provider:ra.json(this.traceProvider({provider:this.getHttpProvider()})),validator:new ia}))})}),e(new ht(this.getFileProvider()))]})})})})}getFileProvider(){return this.share(this.getFileProvider,()=>{let e=this.traceProvider({provider:this.getHttpProvider()}),t=this.traceProvider({provider:new li(this.getFileSystem(),this.getScanFilter())}),n=new We({providers:[t,this.traceProvider({provider:this.createGitHubProvider(e)}),this.traceProvider({provider:new gn(e)})]});return this.traceProvider({label:"FileProvider",provider:new We({providers:[t,this.traceProvider({provider:new yt({baseUrl:new URL("./",this.configuration.templateRegistryUrl),dataProvider:this.traceProvider({label:"ResourceProvider",provider:n}),registryProvider:new Ui({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 yn(new ht(n)),validator:new fi})})})})})})]})})})}createGitHubProvider(e){let t=Date.now();return new ui({cache:new AutoSaveCache(new InMemoryCache),provider:new We({providers:[new We({providers:[new yt({dataProvider:e,registryProvider:new Vt([{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 aa({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 F({action:new nt(new Te(()=>new Yi(r))),validator:new Xi}),try:new F({action:new nt(new Te(()=>new ni(r.run))),validator:new Ii}),test:new F({action:new nt(new Te(()=>new Ni(r.run))),validator:new zi}),repeat:new F({action:new nt(new Te(()=>new Eo(r.run))),validator:new Ro}),print:new F({action:new Li,validator:new Fi}),fail:new F({action:new ji,validator:new Wi}),define:new F({action:new ro,validator:new no}),prompt:new F({action:new Zi,validator:new Ji}),"change-directory":new F({action:new po({fileSystem:e,rootDirectory:this.initialDirectory,currentDirectory:this.workingDirectory}),validator:new so}),"open-link":new F({action:new eo,validator:new to}),"start-server":new F({action:new Qi({serverProvider:this.getServerProvider(),serverFactory:this.getServerFactory(),packageManager:this.getPackageManager(),serverMap:n}),validator:new Bi}),"stop-server":new F({action:new Ia({serverMap:n}),validator:new io}),"execute-package":new F({action:new co({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 lo}),"check-dependency":new F({action:new ci({packageManager:this.getPackageManager()}),validator:new xi}),download:new F({action:new Qr({fileSystem:e,provider:this.getFileProvider(),codemod:new Ln({codemods:{"**/*.{js,jsx,ts,tsx}":new _n(new ca({fileSystem:e,rootPath:this.workingDirectory,filter:(i,a)=>a<=10&&t(i,a),importResolver:this.getNodeImportResolver(),importCodemod:new Fe({fileSystem:e,codemod:new _e({languages:["typescript","jsx"],codemod:new ua})}),exportMatcher:{test:(i,{names:a})=>a.length===0?true:Dc(i).some(s=>a.includes(s))}}),new Ln({codemods:{"**/*.{js,jsx}":new _n(new Fe({fileSystem:e,codemod:new _e({codemod:new Sa,languages:["typescript","jsx"]})}))}}),new Ke(this.getJavaScriptFormatter()))}})}),validator:new vi}),"add-dependency":new F({action:new Br({packageManager:this.getPackageManager()}),validator:new Pi}),"locate-file":new F({action:new Yr({projectDirectory:this.workingDirectory,fileSystem:e,scanFilter:this.getScanFilter()}),validator:new Ci}),"replace-file-content":new F({action:new Xr({fileSystem:e}),validator:new ki}),initialize:new F({action:new ea({callback:async()=>{if(!await this.getConfigurationManager().isInitialized())return this.init({})}}),validator:new ta}),"add-slot":new F({action:new ei({installer:(i,a)=>{let s=this.getNonInteractiveOutput(true);return this.execute(new Dt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new Ze({input:this.getNonInteractiveInput(),output:s,workspaceApi:this.getWorkspaceApi()}),io:{output:s}}),{slots:i,example:a})}}),validator:new Ei}),"add-component":new F({action:new ti({installer:i=>{let a=this.getNonInteractiveOutput(true);return this.execute(new Mt({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 F({action:new oi({configurationManager:this.getConfigurationManager(),matcher:new si({workspaceApi:this.getWorkspaceApi()}),api:{user:this.getUserApi(),workspace:this.getWorkspaceApi(),organization:this.getOrganizationApi()},mappingForm:new ai({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 Oi}),"format-code":new F({action:new Di({formatter:this.getCodeFormatter()}),validator:new Mi}),import:new F({action:new nt(new Te(()=>new hi({runner:r.run,templateProvider:new bi({evaluator:new yi({functions:as}),validator:new vn,templateProvider:this.getTemplateProvider(),fileProvider:new ht(this.getFileProvider())}),variables:this.getActionVariables()}))),validator:new Ti})};return r.import})}getActionVariables(){let e=t=>new URL(t,this.configuration.adminUrl).toString();return {project:{features:ce.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{features:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),quotas:ce.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{quotas:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),organization:ce.transient(async()=>{let{organization:t}=await this.getConfigurationManager().load();return {slug:t,url:e(`organizations/${t}`)}}),workspace:ce.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load();return {slug:n,url:e(`organizations/${t}/workspaces/${n}`)}}),application:ce.transient(async()=>{let{organization:t,workspace:n,applications:r}=await this.getConfigurationManager().load(),i=`organizations/${t}/workspaces/${n}/applications/`;return {development:{slug:r.development,url:e(i+r.development)},production:{slug:r.production,url:e(i+r.production)}}}),path:ce.transient(async()=>{let t=this.getSdk(),n=await this.getConfigurationManager().load();return t.getPaths(n)}),platform:ce.transient(async()=>await this.getPlatformProvider().get()??"unknown"),server:ce.transient(async()=>{let n=await this.getServerProvider().get();if(n===null)return null;try{let r=await n.getStatus();if(r.running)return {running:!0,url:r.url.toString()}}catch{}return {running:false}})}}}getHttpProvider(){return this.share(this.getHttpProvider,()=>new pi({retry:{maxAttempts:3,delay:1e3}}))}getAuthenticator(){return this.share(this.getAuthenticator,()=>{if(this.configuration.apiKey!==void 0)return new Ho({apiKey:this.configuration.apiKey,clock:this.getClock(),tokenDuration:this.configuration.apiKeyTokenDuration});let e=this.getFormInput(),t=new yr({input:e,output:this.getOutput(),userApi:this.getUserApi(true),form:{signIn:new hr({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 Sr({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 Zo({cacheKey:"token",cacheProvider:new Jo({clock:this.getClock(),clockSkewTolerance:5,tokenFreshPeriod:this.configuration.cliTokenFreshPeriod,tokenIssuer:()=>n.issueToken({duration:this.configuration.cliTokenDuration}),cacheProvider:new hn({fileSystem:this.getFileSystem(),directory:this.configuration.directories.config,useKeyAsFileName:true})}),authenticator:new Dr({default:this.configuration.interactive?t:new Or({authenticator:t,instruction:{message:"Authentication required.",suggestions:["Run `login` to authenticate"],reason:"precondition"}}),credentials:t})});return this.configuration.interactive?new Wo({authenticator:r,invitationForm:new jo({output:this.getOutput(),input:e,userApi:this.getUserApi(true)})}):r})}getSdk(){return this.share(this.getSdk,()=>{let e=new Ht(this.getSdkProvider(),new Te(()=>{throw new U("No suitable SDK detected.",{reason:"not_supported",suggestions:["Make sure you are running the command in the project root directory."]})}));return new Po(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 Ut({discriminator:async()=>await this.getPlatformProvider().get()??i,mapping:{javascript:()=>new nr({...r,bundlers:["vite","parcel","tsup","rollup"]}),react:()=>new rr({...r,importResolver:n,codemod:{provider:new Ke(e,new Fe({fileSystem:this.getFileSystem(),codemod:new _e({languages:["typescript","jsx"],codemod:new ut({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 ar({...r,userApi:this.getUserApi(),applicationApi:this.getApplicationApi(),importResolver:n,codemod:{middleware:new Ke(e,new Fe({fileSystem:this.getFileSystem(),codemod:new _e({languages:["typescript","jsx"],codemod:new Pr({import:{module:"@croct/plug-next/middleware",middlewareName:"middleware",middlewareFactoryName:"withCroct",configName:"config",matcherName:"matcher",matcherLocalName:"croctMatcher"}})})})),appRouterProvider:new Ke(e,new Fe({fileSystem:this.getFileSystem(),codemod:new _e({languages:["typescript","jsx"],codemod:new ut({fallbackToNamedExports:false,fallbackCodemod:new Cr({provider:{component:"CroctProvider",module:"@croct/plug-next/CroctProvider"}}),wrapper:{module:"@croct/plug-next/CroctProvider",component:"CroctProvider"},targets:{variable:"children"}})})})),pageRouterProvider:new Ke(e,new Fe({fileSystem:this.getFileSystem(),codemod:new _e({languages:["typescript","jsx"],codemod:new ut({fallbackToNamedExports:false,fallbackCodemod:new an({provider:{component:"CroctProvider",module:"@croct/plug-next/CroctProvider"}}),wrapper:{module:"@croct/plug-next/CroctProvider",component:"CroctProvider"},targets:{component:"Component"}})})})),fallbackProvider:new Ke(e,new Fe({fileSystem:this.getFileSystem(),codemod:new _e({languages:["typescript","jsx"],codemod:new ut({fallbackToNamedExports:false,fallbackCodemod:new an({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 wo(new Ut({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 So(new Map(Object.entries(this.getPackageManagers()))))}getPackageManagers(){return this.getNodePackageManagers()}getPackageManager(){return this.share(this.getPackageManager,()=>new An(new Ht(this.getNodePackageManagerProvider(),new Te(()=>{throw new U("No package manager detected.",{reason:"not_supported",suggestions:["Make sure you are running the command in the project root directory.","Initialize your project and retry the command."]})}))))}getNodePackageManager(){return this.share(this.getNodePackageManager,()=>{let e=this.getNodePackageManagers();return new An(new Ht(this.getNodePackageManagerProvider(),new Vt(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 On(new Fo(new bt({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new _o({process:this.configuration.process,variable:"npm_config_user_agent",value:new RegExp(`^${r}`)})}))}),new bt({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new Dn(new Lo({packageManager:r,fileSystem:t,projectDirectory:this.workingDirectory}),new En({fileSystem:t,files:n[r]}))}))}),new bt({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new ba({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 fn,r={fileSystem:e,projectDirectory:this.workingDirectory,packageValidator:n};return {npm:new rt({...r,agent:new uo(t)}),yarn:new rt({...r,agent:new mo(t)}),bun:new rt({...r,agent:new go(t)}),pnpm:new rt({...r,agent:new fo(t)})}})}getServerProvider(){return this.share(this.getServerProvider,()=>{let e=Symbol("unknown");return new Ut({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 Vi({packageManager:this.getNodePackageManager(),factory:this.getServerFactory(),parsers:[new qi,new Hi,new Gi,new Ki]}))}getServerFactory(){return this.share(this.getServerFactory,()=>new ao({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 Ar({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 yo({fileSystem:this.getFileSystem(),tsConfigLoader:this.getTsConfigLoader(),projectDirectory:this.workingDirectory}))}getTsConfigLoader(){return this.share(this.getTsConfigLoader,()=>new ya({fileSystem:this.getFileSystem(),tsconfigValidator:new ho}))}getAsynchronousCommandExecutor(){return this.share(this.getAsynchronousCommandExecutor,()=>new ha({executableLocator:this.getExecutableLocator(),commandExecutor:this.getCommandExecutor()}))}getSynchronousCommandExecutor(){return this.getCommandExecutor()}getCommandExecutor(){return this.share(this.getCommandExecutor,()=>new vo({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 fn,fileSystem:this.getFileSystem(),agent:new bo});return new On(new bt({candidates:[{value:"nextjs",condition:new Rn({packageManager:e,dependencies:["next"]})},{value:"react",condition:new Rn({packageManager:e,dependencies:["react"]})},{value:"javascript",condition:new Io({packageManager:e})}]}),this.workingDirectory)})}getConfigurationManager(){return this.share(this.getConfigurationManager,()=>{let e=this.getOutput(),t=new cr({fileSystem:this.getFileSystem(),validator:new di,projectDirectory:this.workingDirectory});return new $o({workingDirectory:this.workingDirectory,configurationProvider:this.getCliConfigurationProvider(),manager:new ri(this.configuration.interactive&&!this.isReadOnlyMode()?new Er({manager:t,initializer:{initialize:async()=>{await this.init({}),e.break();}}}):t)})})}getScanFilter(){return this.share(this.getScanFilter,()=>{let e=new ko({fileSystem:this.getFileSystem(),workingDirectory:this.workingDirectory});return async t=>!await e.test(t)})}getUserApi(e=false){return e?new on(this.getGraphqlClient(true)):this.share(this.getUserApi,()=>new on(this.getGraphqlClient()))}getOrganizationApi(){return this.share(this.getOrganizationApi,()=>new lr(this.getGraphqlClient(),this.getHierarchyResolver()))}getWorkspaceApi(){return this.share(this.getWorkspaceApi,()=>new ur(this.getGraphqlClient(),this.getHierarchyResolver()))}getApplicationApi(){return this.share(this.getApplicationApi,()=>new fr(this.getGraphqlClient(),this.getHierarchyResolver()))}getHierarchyResolver(){return this.share(this.getHierarchyResolver,()=>{let e=this.getFileSystem();return new ma(this.getGraphqlClient(),AdaptedCache.transformValues(new hn({fileSystem:e,directory:e.joinPaths(this.configuration.directories.cache,"hierarchy")}),AdaptedCache.jsonSerializer(),AdaptedCache.jsonDeserializer()))})}getGraphqlClient(e=false){return e?new nn({endpoint:this.configuration.adminGraphqlEndpoint,tokenProvider:{getToken:()=>this.getAuthenticator().getToken()}}):this.share(this.getGraphqlClient,()=>{let t=this.getAuthenticator();return new nn({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 zr({platform:e.process.getPlatform(),commandExecutor:this.getSynchronousCommandExecutor(),timeout:2e3,listener:new Qo({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 Lr({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 _c.SystemClock.UTC}getProtocolRegistryProvider(){return this.share(this.getProtocolRegistryProvider,()=>new Te(()=>{let e=this.getFileSystem(),{process:t}=this.configuration;switch(t.getPlatform()){case "darwin":{let n=e.joinPaths(this.configuration.directories.data,"apps");return new da({output:this.getOutput(),macOsRegistry:new Oo({fileSystem:e,appDirectory:n,commandExecutor:this.getAsynchronousCommandExecutor()}),firefoxRegistry:ga.macOs({fileSystem:e,homeDirectory:this.configuration.directories.home,appPath:e.joinPaths(n,`${this.configuration.deepLinkProtocol}.app`)})})}case "win32":return new To({commandExecutor:this.getAsynchronousCommandExecutor()});case "linux":return new Do({fileSystem:e,homeDirectory:this.configuration.directories.home,commandExecutor:this.getAsynchronousCommandExecutor()});default:return null}}))}getCliConfigurationProvider(){return this.share(this.getCliConfigurationProvider,()=>{let e=this.getFileSystem();return new Vo({fileSystem:e,configurationProvider:new Uo({fileSystem:e,validator:new No,filePath:e.joinPaths(this.configuration.directories.config,"config.json")})})})}async execute(e,t){if(this.isReadOnlyMode()&&!o.READ_ONLY_COMMANDS.has(e.constructor))return this.reportError(new d("This command does not support API key authentication.",{reason:"precondition",suggestions:["Run the command without specifying an API key."]}));try{await e.execute(t);}catch(n){let r=o.handleError(n);return n instanceof Error&&r instanceof Error&&(r.stack=n.stack),this.reportError(r)}}isReadOnlyMode(){return this.configuration.apiKey!==void 0}reportError(e){let t=this.getOutput();return t.report(o.handleError(e)),t.exit()}static handleError(e){switch(true){case e instanceof z:return new d(e.message,{...e.help,details:[`URL: ${e.url}`,...e.help.details??[]]});case e instanceof ie: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 v:if(e.tracing.length>0){let t=e.tracing.map(({name:n,source:r},i)=>{let a=r!==void 0?` at ${o.getSourceLocation(r)}`:"";return `${" ".repeat(i+1)}\u21B3 \`${n}\`${a}`}).join(`
1843
1843
  `);return new d(`${e.message}
1844
1844
 
1845
1845
  \u25B6\uFE0F **Trace**
1846
- ${t}`,e.help)}break;case e instanceof st:return new d(e.message,{...e.help,suggestions:["Run `init` to create a new configuration."]})}return e}static getSourceLocation(e){return e.url.protocol==="file:"?`${e.url}:${e.start.line}:${e.start.column}`:e.url.hostname==="github.com"?`${e.url}#L${e.start.line}-L${e.end.line}`:`${e.url}#${e.start.line}:${e.start.column}-${e.end.line}:${e.end.column}`}};var cs={version:"0.4.0"};function Fc(o){let e=new gs().name("croct").description("Manage your Croct projects").enablePositionalOptions().option("--cwd <path>","The working directory.",h=>{try{return realpathSync(h)}catch{throw new He("The path does not exist.")}}).addOption(new se("--api-key <key>","The API key to use for authentication.").env("CROCT_API_KEY").argParser(h=>{try{return ApiKey.parse(h)}catch{throw new He("The API key is malformed.")}})).option("--registry <url>","The template registry.",h=>{if(!URL.canParse(h))throw new He("Malformed URL.");return h}).option("--no-interaction","Disable interaction mode.").addOption(new se("-s, --skip-prompts","Skip prompts with default options.").default(false)).addOption(new se("-q, --quiet","Disable output messages.").default(false).implies({interaction:false})).option("--debug","Enable debug mode.").version(cs.version,"-v, --version","Display the version number.").helpOption("-h, --help","Display help for a command.").helpCommand("help [command]","Display help for a command.");e.command("open <url>").description("Open a deep link.").action(async h=>{await o.cli?.open({url:h});});let t=e.command("login").description("Authenticate your user."),n=new se("-u, --username <username>","The email."),r=new se("-p, --password <password>","The password.");t.command("credentials",{isDefault:true}).description("Authenticate using credentials.").addOption(o.interactive?n:n.makeOptionMandatory()).addOption(o.interactive?r:r.makeOptionMandatory()).action(async 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 se("--wor <workspace-slug>","The workspace slug."),a=new se("--org <organization-slug>","The organization slug."),s=new se("--dev-app <application-slug>","The development application slug."),p=new se("--prod-app <application-slug>","The production application slug.");e.command("init").description("Configure the project.").option("-o, --override","Override any existing configuration.").addOption(new se("-n, --new <resource>","The resources to create.").choices(["organization","org","workspace","wor","application","app"])).addOption(new se("-s, --sdk <platform>","The SDK to use.").choices(["javascript","react","next"])).addOption(o.interactive?a:a.makeOptionMandatory()).addOption(o.interactive?i:i.makeOptionMandatory()).addOption(o.interactive?s:s.makeOptionMandatory()).addOption(p).action(async 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});}),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,A)=>{await o.cli?.addSlot({slots:h,example:A.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 fs("<path>","The path to the file.").argOptional()).option("-e, --empty","Create an empty template.").action(async(h,A)=>{await o.cli?.createTemplate({file:h,empty:A.empty});});let g=new se("--permissions <permissions...>","The permissions of the API key.").argParser(h=>h.split(",").map(A=>{try{return Ee.fromValue(A)}catch{throw new He(`Unknown permission "${A}".`)}})),y=new se("--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={},x=e.command("use").description("Use a template.").argument("template","The path to the template.").passThroughOptions(o.cli===void 0).allowUnknownOption(o.cli===void 0||o.template===null).action(async(h,A)=>{await o.cli?.useTemplate({template:h,options:Object.fromEntries(Object.entries(A).map(([B,Me])=>[I[B],Me]))});});for(let[h,A]of Object.entries(o.template??{})){let B=`--${h}${A.type!=="boolean"?" <value>":""}`,Me=new se(B,A.description).makeOptionMandatory(A.required===true);switch(A.type){case "string":A.choices!==void 0&&A.choices.length>0&&Me.choices(A.choices);break;case "number":Me.argParser(q=>{let de=Number.parseFloat(q);if(Number.isNaN(de))throw new He("The value must be a number.");return de});break;case "array":Me.argParser(q=>{let de;try{de=JSON.parse(q);}catch{}if(de===void 0||!Array.isArray(de))throw new He("The value must be a JSON array.");return q.split(",")});break;case "object":Me.argParser(q=>{let de;try{de=JSON.parse(q);}catch{throw new He("The JSON is malformed.")}if(typeof de!="object"||de===null)throw new He("The value must be a JSON object.")});break}I[Me.attributeName()]=h,x.addOption(Me);}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 Ad(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 Ed(o){return o.length>=2&&["enable","disable"].includes(o[0])&&o[1]==="deep-link"}async function ls(o=process.argv,e=true){let t=Fc({interactive:true}).parse(o),n=t.opts(),r=va.fromDefaults({program:p=>ls(t.args.slice(0,2).concat(p)),version:cs.version,quiet:n.quiet,debug:n.debug,interactive:n.interaction?void 0:false,apiKey:n.apiKey,skipPrompts:n.skipPrompts===true,templateRegistryUrl:n.registry===void 0?void 0:new URL(n.registry)}),i=Ad(t.args),a=i!==null?await r.getTemplateOptions(i).catch(()=>null):void 0,s=Fc({cli:r,interactive:n.interaction,template:a});e&&await r.welcome({skipDeepLinkCheck:Ed(t.args)}),await s.parseAsync(o);}ls();
1846
+ ${t}`,e.help)}break;case e instanceof st:return new d(e.message,{...e.help,suggestions:["Run `init` to create a new configuration."]})}return e}static getSourceLocation(e){return e.url.protocol==="file:"?`${e.url}:${e.start.line}:${e.start.column}`:e.url.hostname==="github.com"?`${e.url}#L${e.start.line}-L${e.end.line}`:`${e.url}#${e.start.line}:${e.start.column}-${e.end.line}:${e.end.column}`}};var cs={version:"0.4.1"};function Fc(o){let e=new gs().name("croct").description("Manage your Croct projects").enablePositionalOptions().option("--cwd <path>","The working directory.",h=>{try{return realpathSync(h)}catch{throw new He("The path does not exist.")}}).addOption(new se("--api-key <key>","The API key to use for authentication.").env("CROCT_API_KEY").argParser(h=>{try{return ApiKey.parse(h)}catch{throw new He("The API key is malformed.")}})).option("--registry <url>","The template registry.",h=>{if(!URL.canParse(h))throw new He("Malformed URL.");return h}).option("--no-interaction","Disable interaction mode.").addOption(new se("-s, --skip-prompts","Skip prompts with default options.").default(false)).addOption(new se("-q, --quiet","Disable output messages.").default(false).implies({interaction:false})).option("--debug","Enable debug mode.").version(cs.version,"-v, --version","Display the version number.").helpOption("-h, --help","Display help for a command.").helpCommand("help [command]","Display help for a command.");e.command("open <url>").description("Open a deep link.").action(async h=>{await o.cli?.open({url:h});});let t=e.command("login").description("Authenticate your user."),n=new se("-u, --username <username>","The email."),r=new se("-p, --password <password>","The password.");t.command("credentials",{isDefault:true}).description("Authenticate using credentials.").addOption(o.interactive?n:n.makeOptionMandatory()).addOption(o.interactive?r:r.makeOptionMandatory()).action(async 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 se("--wor <workspace-slug>","The workspace slug."),a=new se("--org <organization-slug>","The organization slug."),s=new se("--dev-app <application-slug>","The development application slug."),p=new se("--prod-app <application-slug>","The production application slug.");e.command("init").description("Configure the project.").option("-o, --override","Override any existing configuration.").addOption(new se("-n, --new <resource>","The resources to create.").choices(["organization","org","workspace","wor","application","app"])).addOption(new se("-s, --sdk <platform>","The SDK to use.").choices(["javascript","react","next"])).addOption(o.interactive?a:a.makeOptionMandatory()).addOption(o.interactive?i:i.makeOptionMandatory()).addOption(o.interactive?s:s.makeOptionMandatory()).addOption(p).action(async 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});}),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,A)=>{await o.cli?.addSlot({slots:h,example:A.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 fs("<path>","The path to the file.").argOptional()).option("-e, --empty","Create an empty template.").action(async(h,A)=>{await o.cli?.createTemplate({file:h,empty:A.empty});});let g=new se("--permissions <permissions...>","The permissions of the API key.").argParser(h=>h.split(",").map(A=>{try{return Ee.fromValue(A)}catch{throw new He(`Unknown permission "${A}".`)}})),y=new se("--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={},x=e.command("use").description("Use a template.").argument("template","The path to the template.").passThroughOptions(o.cli===void 0).allowUnknownOption(o.cli===void 0||o.template===null).action(async(h,A)=>{await o.cli?.useTemplate({template:h,options:Object.fromEntries(Object.entries(A).map(([B,Me])=>[I[B],Me]))});});for(let[h,A]of Object.entries(o.template??{})){let B=`--${h}${A.type!=="boolean"?" <value>":""}`,Me=new se(B,A.description).makeOptionMandatory(A.required===true);switch(A.type){case "string":A.choices!==void 0&&A.choices.length>0&&Me.choices(A.choices);break;case "number":Me.argParser(q=>{let de=Number.parseFloat(q);if(Number.isNaN(de))throw new He("The value must be a number.");return de});break;case "array":Me.argParser(q=>{let de;try{de=JSON.parse(q);}catch{}if(de===void 0||!Array.isArray(de))throw new He("The value must be a JSON array.");return q.split(",")});break;case "object":Me.argParser(q=>{let de;try{de=JSON.parse(q);}catch{throw new He("The JSON is malformed.")}if(typeof de!="object"||de===null)throw new He("The value must be a JSON object.")});break}I[Me.attributeName()]=h,x.addOption(Me);}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 Ad(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 Ed(o){return o.length>=2&&["enable","disable"].includes(o[0])&&o[1]==="deep-link"}async function ls(o=process.argv,e=true){let t=Fc({interactive:true}).parse(o),n=t.opts(),r=va.fromDefaults({program:p=>ls(t.args.slice(0,2).concat(p)),version:cs.version,quiet:n.quiet,debug:n.debug,interactive:n.interaction?void 0:false,apiKey:n.apiKey,skipPrompts:n.skipPrompts===true,templateRegistryUrl:n.registry===void 0?void 0:new URL(n.registry)}),i=Ad(t.args),a=i!==null?await r.getTemplateOptions(i).catch(()=>null):void 0,s=Fc({cli:r,interactive:n.interaction,template:a});e&&await r.welcome({skipDeepLinkCheck:Ed(t.args)}),await s.parseAsync(o);}ls();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "croct",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
4
4
  "description": "A command-line interface (CLI) for managing projects using Croct.",
5
5
  "author": {
6
6
  "name": "Croct",