croct 0.4.3 → 0.4.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +4 -4
- package/package.json +2 -2
package/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {createRequire}from'module';import {createReadStream,realpathSync}from'fs';import {ApiKey}from'@croct/sdk/apiKey';import {NoopCache,InMemoryCache,AutoSaveCache,AdaptedCache}from'@croct/cache';import Lc from'open';import {homedir}from'os';import wd from'xdg-app-paths';import Pd from'ci-info';import {FilteredLogger,LogLevel}from'@croct/logging';import gl from'prompts';import {Readable,PassThrough}from'stream';import Ma from'cli-cursor';import ot from'chalk';import Na from'node:readline';import {WriteStream}from'tty';import Pl from'strip-ansi';import fl from'is-unicode-supported';import {render}from'@croct/md-lite/rendering.js';import hl from'terminal-link';import {unescape}from'@croct/md-lite/parsing.js';import {strip}from'node-emoji';import {JsonParser as JsonParser$1,JsonObjectNode as JsonObjectNode$1,JsonArrayNode as JsonArrayNode$1}from'@croct/json5-parser/index.js';import {JsonObjectNode,JsonParser,JsonArrayNode,JsonPrimitiveNode,JsonIdentifierNode,JsonTokenNode,JsonTokenType,isIdentifier}from'@croct/json5-parser';import*as f from'@babel/types';import {traverseFast,noop,isTypeScript,isImportSpecifier,isImportDeclaration}from'@babel/types';import {traverse,createConfigItem,transformFromAstAsync}from'@babel/core';import {parse as parse$2}from'@babel/parser';import {createHash,randomUUID as randomUUID$1}from'crypto';import*as vr from'recast';import {parse}from'recast/parsers/babel-ts.js';import {stringSimilarity}from'string-similarity-js';import {realpath,lstat,readdir,symlink,link,mkdir,writeFile,rm as rm$1,readFile,mkdtemp,cp as cp$1}from'fs/promises';import {tmpdir}from'node:os';import {sep,basename,dirname,relative,isAbsolute,join,delimiter}from'path';import {Minimatch,minimatch}from'minimatch';import {deepEqual}from'fast-equals';import {z as z$1,ZodPromise,ZodOptional,ZodTuple,ZodArray,ZodRecord,ZodObject,ZodEffects,ZodAny,ZodPipeline,ZodUnion,ZodDiscriminatedUnion}from'zod';import Ue from'jsep';import du from'@jsep-plugin/object';import gu from'@jsep-plugin/spread';import fu from'@jsep-plugin/regex';import uc from'is-plain-obj';import {randomUUID}from'node:crypto';import
|
|
2
|
+
import {createRequire}from'module';import {createReadStream,realpathSync}from'fs';import {ApiKey}from'@croct/sdk/apiKey';import {NoopCache,InMemoryCache,AutoSaveCache,AdaptedCache}from'@croct/cache';import Lc from'open';import {homedir}from'os';import wd from'xdg-app-paths';import Pd from'ci-info';import {FilteredLogger,LogLevel}from'@croct/logging';import gl from'prompts';import {Readable,PassThrough}from'stream';import Ma from'cli-cursor';import ot from'chalk';import Na from'node:readline';import {WriteStream}from'tty';import Pl from'strip-ansi';import fl from'is-unicode-supported';import {render}from'@croct/md-lite/rendering.js';import hl from'terminal-link';import {unescape}from'@croct/md-lite/parsing.js';import {strip}from'node-emoji';import {JsonParser as JsonParser$1,JsonObjectNode as JsonObjectNode$1,JsonArrayNode as JsonArrayNode$1}from'@croct/json5-parser/index.js';import {JsonObjectNode,JsonParser,JsonArrayNode,JsonPrimitiveNode,JsonIdentifierNode,JsonTokenNode,JsonTokenType,JsonParseError,isIdentifier}from'@croct/json5-parser';import*as f from'@babel/types';import {traverseFast,noop,isTypeScript,isImportSpecifier,isImportDeclaration}from'@babel/types';import {traverse,createConfigItem,transformFromAstAsync}from'@babel/core';import {parse as parse$2}from'@babel/parser';import {createHash,randomUUID as randomUUID$1}from'crypto';import*as vr from'recast';import {parse as parse$1}from'recast/parsers/babel-ts.js';import {stringSimilarity}from'string-similarity-js';import {realpath,lstat,readdir,symlink,link,mkdir,writeFile,rm as rm$1,readFile,mkdtemp,cp as cp$1}from'fs/promises';import {tmpdir}from'node:os';import {sep,basename,dirname,relative,isAbsolute,join,delimiter}from'path';import {Minimatch,minimatch}from'minimatch';import {deepEqual}from'fast-equals';import {z as z$1,ZodPromise,ZodOptional,ZodTuple,ZodArray,ZodRecord,ZodObject,ZodEffects,ZodAny,ZodPipeline,ZodUnion,ZodDiscriminatedUnion}from'zod';import Ue from'jsep';import du from'@jsep-plugin/object';import gu from'@jsep-plugin/spread';import fu from'@jsep-plugin/regex';import uc from'is-plain-obj';import {randomUUID}from'node:crypto';import Fm from'semver';import {spawn,spawnSync}from'child_process';import Qm from'clipboardy';import {Token}from'@croct/sdk/token';import Tc from'boxen';import He from'node:process';import {AsyncLocalStorage}from'node:async_hooks';import {parse}from'ini';import Id from'@babel/plugin-transform-typescript';import xd from'@babel/plugin-syntax-decorators';const require = createRequire(import.meta.url);
|
|
3
3
|
var Wc=Object.create;var Ca=Object.defineProperty;var Uc=Object.getOwnPropertyDescriptor;var Vc=Object.getOwnPropertyNames;var qc=Object.getPrototypeOf,Hc=Object.prototype.hasOwnProperty;var Gc=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var xe=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),Kc=(o,e)=>{for(var t in e)Ca(o,t,{get:e[t],enumerable:true});},Zc=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Vc(e))!Hc.call(o,r)&&r!==t&&Ca(o,r,{get:()=>e[r],enumerable:!(n=Uc(e,r))||n.enumerable});return o};var xt=(o,e,t)=>(t=o!=null?Wc(qc(o)):{},Zc(Ca(t,"default",{value:o,enumerable:true}),o));var ds=xe((fe,ms)=>{var Ae=Gc("commander");fe=ms.exports={};fe.program=new Ae.Command;fe.Argument=Ae.Argument;fe.Command=Ae.Command;fe.CommanderError=Ae.CommanderError;fe.Help=Ae.Help;fe.InvalidArgumentError=Ae.InvalidArgumentError;fe.InvalidOptionArgumentError=Ae.InvalidArgumentError;fe.Option=Ae.Option;fe.createCommand=o=>new Ae.Command(o);fe.createOption=(o,e)=>new Ae.Option(o,e);fe.createArgument=(o,e)=>new Ae.Argument(o,e);});var ka=xe(Fn=>{Object.defineProperty(Fn,"__esModule",{value:true});Fn.TimeZone=void 0;var Zt=class o{constructor(e){this.id=e;}static getTimesZoneIds(){return o.SUPPORTED_TIMEZONE_IDS===void 0&&(o.SUPPORTED_TIMEZONE_IDS=new Set(["UTC","CET","CST6CDT","EET","EST","EST5EDT","Etc/GMT+1","Etc/GMT+10","Etc/GMT+11","Etc/GMT+12","Etc/GMT+2","Etc/GMT+3","Etc/GMT+4","Etc/GMT+5","Etc/GMT+6","Etc/GMT+7","Etc/GMT+8","Etc/GMT+9","Etc/GMT-1","Etc/GMT-10","Etc/GMT-11","Etc/GMT-12","Etc/GMT-13","Etc/GMT-14","Etc/GMT-2","Etc/GMT-3","Etc/GMT-4","Etc/GMT-5","Etc/GMT-6","Etc/GMT-7","Etc/GMT-8","Etc/GMT-9","HST","MET","MST","MST7MDT","PST8PDT","WET",...Intl.supportedValuesOf("timeZone")])),o.SUPPORTED_TIMEZONE_IDS}static of(e){if(!o.getTimesZoneIds().has(e))throw new Error(`The timezone ${e} is not supported.`);return new o(e)}getId(){return this.id}toString(){return this.id}equals(e){return this.id===e.id}toJSON(){return this.toString()}};Fn.TimeZone=Zt;Zt.UTC=new Zt("UTC");});var Ea=xe(jn=>{var Aa;Object.defineProperty(jn,"__esModule",{value:true});jn.SystemClock=void 0;var Jc=Qt(),Qc=ka(),Jt=class{constructor(e){this.zone=e;}static of(e){return new this(e)}getZone(){return this.zone}getInstant(){return Jc.Instant.ofEpochMilli(Date.now())}equals(e){return e===this||e instanceof Aa&&e.zone.equals(this.zone)}};jn.SystemClock=Jt;Aa=Jt;Jt.UTC=new Aa(Qc.TimeZone.UTC);});var Ra=xe(Wn=>{Object.defineProperty(Wn,"__esModule",{value:true});Wn.DefaultClockProvider=void 0;var Bc=Ea(),hs;(function(o){let e=null;function t(){return e===null&&(e=Bc.SystemClock.UTC),e}o.getClock=t;function n(r){e=r;}o.setClock=n;})(hs||(Wn.DefaultClockProvider=hs={}));});var Bt=xe(ue=>{Object.defineProperty(ue,"__esModule",{value:true});ue.intDiv=ue.multiplyExact=ue.subtractExact=ue.addExact=ue.floorMod=ue.floorDiv=void 0;function Ss(o,e){let t=Math.trunc(o/e);return Math.sign(o)!==Math.sign(e)&&t*e!==o&&t--,t}ue.floorDiv=Ss;function Yc(o,e){return o-Ss(o,e)*e}ue.floorMod=Yc;function Xc(o,e){let t=o+e;if(!Number.isSafeInteger(t))throw new Error("The result overflows the range of safe integers.");return t}ue.addExact=Xc;function el(o,e){let t=o-e;if(!Number.isSafeInteger(t))throw new Error("The result overflows the range of safe integers.");return t}ue.subtractExact=el;function tl(o,e){let t=o*e;if(!Number.isSafeInteger(t))throw new Error("The result overflows the range of safe integers.");return t}ue.multiplyExact=tl;function nl(o,e){let t=Math.trunc(o/e);if(!Number.isSafeInteger(t))throw new Error("The result overflows the range of safe integers.");return t}ue.intDiv=nl;});var Vn=xe(Un=>{Object.defineProperty(Un,"__esModule",{value:true});Un.LocalDate=void 0;var W=Bt(),me=class o{constructor(e,t,n){this.year=e,this.month=t,this.day=n;}static of(e,t,n){if(!Number.isSafeInteger(e)||e<o.MIN_YEAR||e>o.MAX_YEAR)throw new Error(`Year must be a safe integer between ${o.MIN_YEAR} and ${o.MAX_YEAR}.`);if(!Number.isInteger(t)||t<1||t>12)throw new Error("Month must be an integer between 1 and 12.");let r=o.getMonthLength(t,o.isLeapYear(e));if(!Number.isInteger(n)||n<1||n>r)throw new Error(`Day must be an integer between 1 and ${r}.`);return new o(e,t,n)}static ofEpochDay(e){if(e<o.MIN_EPOCH_DAY||e>o.MAX_EPOCH_DAY)throw new Error(`The day ${e} is out of the range [${o.MIN_EPOCH_DAY} - ${o.MAX_EPOCH_DAY}].`);let t=(0, W.addExact)(e,719468),n=(0, W.floorDiv)(t,146097),r=(0, W.floorMod)(t,146097),i=(0, W.intDiv)(r,1460);i-=(0, W.intDiv)(r,36524),i+=(0, W.intDiv)(r,146096);let a=(0, W.intDiv)(r-i,365),s=a+n*400,p=365*a+(0, W.intDiv)(a,4)-(0, W.intDiv)(a,100),c=r-p,l=(0, W.intDiv)(c*5+2,153);s+=(0, W.intDiv)(l,10);let u=c-(0, W.intDiv)(l*306+5,10)+1;return l=(l+2)%12+1,o.of(s,l,u)}static fromNative(e){return o.of(e.getFullYear(),e.getMonth()+1,e.getDate())}static parse(e){let{groups:t}=e.match(o.PATTERN)??{};if(t===void 0)throw new Error(`Invalid ISO-8601 date string: ${e}`);let n=Number.parseInt(t.year,10),r=Number.parseInt(t.month,10),i=Number.parseInt(t.day,10);return o.of(n,r,i)}getYear(){return this.year}getMonth(){return this.month}getDay(){return this.day}equals(e){return this===e?true:this.year===e.year&&this.month===e.month&&this.day===e.day}plusYears(e){if(e===0)return this;let t=(0, W.addExact)(this.year,e);return o.resolvePreviousValid(t,this.month,this.day)}minusYears(e){return this.plusYears(-e)}plusMonths(e){if(e===0)return this;let t=this.year+(0, W.intDiv)(e,12),n=this.month+e%12,r=t+(0, W.floorDiv)(n-1,12),i=(0, W.floorMod)(n-1,12)+1;return o.resolvePreviousValid(r,i,this.day)}minusMonths(e){return this.plusMonths(-e)}plusWeeks(e){return e===0?this:this.plusDays((0, W.multiplyExact)(e,7))}minusWeeks(e){return this.plusWeeks(-e)}plusDays(e){if(e===0)return this;let t=this.day+e;if(t>0){if(t<=28)return o.of(this.year,this.month,t);if(t<=59){let n=o.getMonthLength(this.month,o.isLeapYear(this.year));return t<=n?o.of(this.year,this.month,t):this.month<12?o.of(this.year,this.month+1,t-n):o.of(this.year+1,1,t-n)}}return o.ofEpochDay((0, W.addExact)(this.toEpochDay(),e))}minusDays(e){return this.plusDays(-e)}isAfter(e){return this.compare(e)>0}isAfterOrEqual(e){return this.compare(e)>=0}isBefore(e){return this.compare(e)<0}isBeforeOrEqual(e){return this.compare(e)<=0}static isValid(e){try{o.parse(e);}catch{return false}return true}compare(e){return this.year!==e.year?this.year-e.year:this.month!==e.month?this.month-e.month:this.day-e.day}toEpochDay(){let{year:e}=this;this.month<=2&&e--;let t=(0, W.floorDiv)(e,400),n=(this.month+9)%12,r=(0, W.intDiv)(153*n+2,5)+this.day-1,i=e-t*400;return 365*i+(0, W.intDiv)(i,4)-(0, W.intDiv)(i,100)+r+t*146097-719468}toString(){let e=`${this.month}`.padStart(2,"0"),t=`${this.day}`.padStart(2,"0");return `${this.year}-${e}-${t}`}static resolvePreviousValid(e,t,n){let r=o.getMonthLength(t,o.isLeapYear(e));return o.of(e,t,Math.min(n,r))}static isLeapYear(e){return e%4===0&&(e%100!==0||e%400===0)}static getMonthLength(e,t){switch(e){case 2:return t?29:28;case 4:case 6:case 9:case 11:return 30;default:return 31}}toJSON(){return this.toString()}};Un.LocalDate=me;me.PATTERN=/^(?<year>[+-]?\d{4,19})-(?<month>\d{2})-(?<day>\d{2})$/;me.MIN_EPOCH_DAY=-365961662;me.MAX_EPOCH_DAY=364522971;me.MIN_YEAR=-999999;me.MAX_YEAR=999999;me.MIN=new me(me.MIN_YEAR,1,1);me.MAX=new me(me.MAX_YEAR,12,31);});var Hn=xe(qn=>{Object.defineProperty(qn,"__esModule",{value:true});qn.LocalTime=void 0;var Ne=Bt(),G=class o{constructor(e,t,n,r){this.hour=e,this.minute=t,this.second=n,this.nanos=r;}static of(e,t=0,n=0,r=0){if(!Number.isInteger(e)||e<0||e>23)throw new Error("Hour must be an integer between 0 and 23.");if(!Number.isInteger(t)||t<0||t>59)throw new Error("Minute must be an integer between 0 and 59.");if(!Number.isInteger(n)||n<0||n>59)throw new Error("Second must be an integer between 0 and 59.");if(!Number.isInteger(r)||r<0||r>999999999)throw new Error("Nanosecond of second must be an integer between 0 and 999999999.");return new o(e,t,n,r)}static ofSecondOfDay(e,t=0){if(e<0||e>o.SECONDS_PER_DAY-1)throw new Error(`The second value ${e} is out of the range [0 - ${o.SECONDS_PER_DAY-1}] of local time.`);if(t<0||t>o.NANOS_PER_SECOND-1)throw new Error(`The nanosecond value ${t} is out of the range [0 - ${o.NANOS_PER_SECOND-1}] of local time.`);let n=e,r=(0, Ne.intDiv)(n,o.SECONDS_PER_HOUR);n-=r*o.SECONDS_PER_HOUR;let i=(0, Ne.intDiv)(n,o.SECONDS_PER_MINUTE);return n-=i*o.SECONDS_PER_MINUTE,o.of(r,i,n,t)}static fromNative(e){return new o(e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()*o.NANOS_PER_MILLI)}static startOfDay(){return new o(0,0,0,0)}static endOfDay(){return new o(23,59,59,999999999)}static parse(e){let{groups:t}=e.match(o.PATTERN)??{};if(t===void 0)throw new Error(`Invalid ISO-8601 time string: ${e}`);let n=Number.parseInt(t.hour,10),r=Number.parseInt(t.minute,10),i=Number.parseInt(t.second??"0",10),a=Number.parseInt(t.fraction?.padEnd(9,"0")??"0",10);return o.of(n,r,i,a)}getHour(){return this.hour}getMinute(){return this.minute}getSecond(){return this.second}getNano(){return this.nanos}toMinuteOfDay(){return this.hour*o.MINUTES_PER_HOUR+this.minute}toSecondOfDay(){return this.toMinuteOfDay()*o.SECONDS_PER_MINUTE+this.second}toMilliOfDay(){return (0, Ne.intDiv)(this.toNanoOfDay(),o.NANOS_PER_MILLI)}toMicroOfDay(){return (0, Ne.intDiv)(this.toNanoOfDay(),o.NANOS_PER_MICRO)}toNanoOfDay(){return this.toSecondOfDay()*o.NANOS_PER_SECOND+this.nanos}plusHours(e){if(e===0)return this;let n=(e%o.HOURS_PER_DAY+this.hour+o.HOURS_PER_DAY)%o.HOURS_PER_DAY;return new o(n,this.minute,this.second,this.nanos)}minusHours(e){return this.plusHours(-e)}plusMinutes(e){if(e===0)return this;let t=e%o.MINUTES_PER_DAY,n=this.toMinuteOfDay(),r=(t+n+o.MINUTES_PER_DAY)%o.MINUTES_PER_DAY;if(n===r)return this;let i=(0, Ne.intDiv)(r,o.MINUTES_PER_HOUR),a=r%o.MINUTES_PER_HOUR;return new o(i,a,this.second,this.nanos)}minusMinutes(e){return this.plusMinutes(-e)}plusSeconds(e){if(e===0)return this;let t=e%o.SECONDS_PER_DAY,n=this.toSecondOfDay(),r=(t+n+o.SECONDS_PER_DAY)%o.SECONDS_PER_DAY;if(n===r)return this;let i=(0, Ne.intDiv)(r,o.SECONDS_PER_HOUR),a=(0, Ne.intDiv)(r,o.SECONDS_PER_MINUTE)%o.MINUTES_PER_HOUR,s=r%o.SECONDS_PER_MINUTE;return o.of(i,a,s,this.nanos)}minusSeconds(e){return this.plusSeconds(-e)}plusMillis(e){return e===0?this:this.plusNanos(e%o.MILLIS_PER_DAY*o.NANOS_PER_MILLI)}minusMillis(e){return this.plusMillis(-e)}plusMicros(e){return e===0?this:this.plusNanos(e%o.MICROS_PER_DAY*o.NANOS_PER_MICRO)}minusMicros(e){return this.plusMicros(-e)}plusNanos(e){if(e===0)return this;let t=e%o.NANOS_PER_DAY,n=this.toNanoOfDay(),r=(t+n+o.NANOS_PER_DAY)%o.NANOS_PER_DAY;if(n===r)return this;let i=(0, Ne.intDiv)(r,o.NANOS_PER_HOUR),a=(0, Ne.intDiv)(r,o.NANOS_PER_MINUTE)%o.MINUTES_PER_HOUR,s=(0, Ne.intDiv)(r,o.NANOS_PER_SECOND)%o.SECONDS_PER_MINUTE,p=r%o.NANOS_PER_SECOND;return o.of(i,a,s,p)}minusNanos(e){return this.plusNanos(-e)}equals(e){return this===e?true:this.hour===e.hour&&this.minute===e.minute&&this.second===e.second&&this.nanos===e.nanos}isAfter(e){return this.compare(e)>0}isAfterOrEqual(e){return this.compare(e)>=0}isBefore(e){return this.compare(e)<0}isBeforeOrEqual(e){return this.compare(e)<=0}static isValid(e){try{o.parse(e);}catch{return false}return true}compare(e){return this.hour!==e.hour?this.hour-e.hour:this.minute!==e.minute?this.minute-e.minute:this.second!==e.second?this.second-e.second:this.nanos-e.nanos}toString(){let e=`${this.hour}`.padStart(2,"0"),t=`${this.minute}`.padStart(2,"0"),n=`${e}:${t}`;if(this.second===0&&this.nanos===0)return n;let r=`${this.second}`.padStart(2,"0");if(n+=`:${r}`,this.nanos>0){let i=`${this.nanos}`.padStart(9,"0").replace(/0+$/,""),a=Math.floor((i.length+2)/3)*3;n+=`.${i.padEnd(a,"0")}`;}return n}toJSON(){return this.toString()}};qn.LocalTime=G;G.PATTERN=/^(?<hour>\d{2}):(?<minute>\d{2})(?::(?<second>\d{2})(?:.(?<fraction>\d{1,9}))?)?$/;G.HOURS_PER_DAY=24;G.MINUTES_PER_DAY=1440;G.MINUTES_PER_HOUR=60;G.SECONDS_PER_DAY=86400;G.SECONDS_PER_HOUR=3600;G.SECONDS_PER_MINUTE=60;G.MICROS_PER_DAY=864e8;G.MICROS_PER_SECOND=1e6;G.MILLIS_PER_DAY=864e5;G.MILLIS_PER_SECOND=1e3;G.NANOS_PER_DAY=864e11;G.NANOS_PER_HOUR=36e11;G.NANOS_PER_MINUTE=6e10;G.NANOS_PER_SECOND=1e9;G.NANOS_PER_MILLI=1e6;G.NANOS_PER_MICRO=1e3;});var Ta=xe(Kn=>{Object.defineProperty(Kn,"__esModule",{value:true});Kn.LocalDateTime=void 0;var bs=Ra(),rl=Qt(),Gn=Vn(),E=Hn(),K=Bt(),Oa=class o{constructor(e,t){this.date=e,this.time=t;}static nowIn(e,t=bs.DefaultClockProvider.getClock()){return o.ofInstant(t.getInstant(),e)}static now(e=bs.DefaultClockProvider.getClock()){return o.ofInstant(e.getInstant(),e.getZone())}static ofInstant(e,t){return o.fromZonedDate(e.toDate(),t)}static fromZonedDate(e,t){let i=e.toLocaleString("sv-SE",{timeZone:t.getId(),calendar:e.getUTCFullYear()<200?"gregory":"iso8601",hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3}).match(/(?<year>\d{1,4})-(?<month>\d{2})-(?<day>\d{2}) (?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2}),(?<fraction>\d{3})/)?.groups;return o.of(Gn.LocalDate.of(Number.parseInt(i.year,10),Number.parseInt(i.month,10),Number.parseInt(i.day,10)),E.LocalTime.of(Number.parseInt(i.hour,10),Number.parseInt(i.minute,10),Number.parseInt(i.second,10),Number.parseInt(i.fraction.padEnd(9,"0"),10)))}static ofEpochSecond(e,t=0){if(!Number.isSafeInteger(e)||!Number.isSafeInteger(t))throw new Error("The timestamp must be a safe integer.");let n=(0, K.floorDiv)(e,E.LocalTime.SECONDS_PER_DAY),r=(0, K.floorMod)(e,E.LocalTime.SECONDS_PER_DAY),i=Gn.LocalDate.ofEpochDay(n),a=E.LocalTime.ofSecondOfDay(r,t);return o.of(i,a)}static fromNative(e){return o.of(Gn.LocalDate.fromNative(e),E.LocalTime.fromNative(e))}static of(e,t){return new o(e,t??E.LocalTime.startOfDay())}static parse(e){let t=e.split("T");if(t.length!==2)throw new Error(`Malformed local date-time "${e}".`);return o.of(Gn.LocalDate.parse(t[0]),E.LocalTime.parse(t[1]))}getLocalDate(){return this.date}getLocalTime(){return this.time}getDay(){return this.date.getDay()}getMonth(){return this.date.getMonth()}getYear(){return this.date.getYear()}getHour(){return this.time.getHour()}getMinute(){return this.time.getMinute()}getSecond(){return this.time.getSecond()}getNano(){return this.time.getNano()}plusYears(e){return o.of(this.date.plusYears(e),this.time)}minusYears(e){return this.plusYears(-e)}plusMonths(e){return o.of(this.date.plusMonths(e),this.time)}minusMonths(e){return this.plusMonths(-e)}plusWeeks(e){return o.of(this.date.plusWeeks(e),this.time)}minusWeeks(e){return this.plusWeeks(-e)}plusDays(e){return o.of(this.date.plusDays(e),this.time)}minusDays(e){return this.plusDays(-e)}plusHours(e){if(e===0)return this;let t=(0, K.intDiv)(e,E.LocalTime.HOURS_PER_DAY),n=e%E.LocalTime.HOURS_PER_DAY,r=n*E.LocalTime.NANOS_PER_HOUR+this.time.toNanoOfDay(),i=t+(0, K.floorDiv)(r,E.LocalTime.NANOS_PER_DAY);return o.of(this.date.plusDays(i),this.time.plusHours(n))}minusHours(e){return this.plusHours(-e)}plusMinutes(e){if(e===0)return this;let t=(0, K.intDiv)(e,E.LocalTime.MINUTES_PER_DAY),n=e%E.LocalTime.MINUTES_PER_DAY,r=n*E.LocalTime.NANOS_PER_MINUTE+this.time.toNanoOfDay(),i=t+(0, K.floorDiv)(r,E.LocalTime.NANOS_PER_DAY);return o.of(this.date.plusDays(i),this.time.plusMinutes(n))}minusMinutes(e){return this.plusMinutes(-e)}plusSeconds(e){if(e===0)return this;let t=(0, K.intDiv)(e,E.LocalTime.SECONDS_PER_DAY),n=e%E.LocalTime.SECONDS_PER_DAY,r=n*E.LocalTime.NANOS_PER_SECOND+this.time.toNanoOfDay(),i=t+(0, K.floorDiv)(r,E.LocalTime.NANOS_PER_DAY);return o.of(this.date.plusDays(i),this.time.plusSeconds(n))}minusSeconds(e){return this.plusSeconds(-e)}plusMillis(e){if(e===0)return this;let t=(0, K.intDiv)(e,E.LocalTime.MILLIS_PER_DAY),n=e%E.LocalTime.MILLIS_PER_DAY,r=n*E.LocalTime.NANOS_PER_MILLI+this.time.toNanoOfDay(),i=t+(0, K.floorDiv)(r,E.LocalTime.NANOS_PER_DAY);return o.of(this.date.plusDays(i),this.time.plusMillis(n))}minusMillis(e){return this.plusMillis(-e)}plusMicros(e){if(e===0)return this;let t=(0, K.intDiv)(e,E.LocalTime.MICROS_PER_DAY),n=e%E.LocalTime.MICROS_PER_DAY,r=n*E.LocalTime.NANOS_PER_MICRO+this.time.toNanoOfDay(),i=t+(0, K.floorDiv)(r,E.LocalTime.NANOS_PER_DAY);return o.of(this.date.plusDays(i),this.time.plusMicros(n))}minusMicros(e){return this.plusMicros(-e)}plusNanos(e){if(e===0)return this;let t=(0, K.intDiv)(e,E.LocalTime.NANOS_PER_DAY),n=e%E.LocalTime.NANOS_PER_DAY,r=n+this.time.toNanoOfDay(),i=t+(0, K.floorDiv)(r,E.LocalTime.NANOS_PER_DAY);return o.of(this.date.plusDays(i),this.time.plusNanos(n))}minusNanos(e){return this.plusNanos(-e)}equals(e){return this===e?true:this.date.equals(e.date)&&this.time.equals(e.time)}isAfter(e){return this.compare(e)>0}isAfterOrEqual(e){return this.compare(e)>=0}isBefore(e){return this.compare(e)<0}isBeforeOrEqual(e){return this.compare(e)<=0}static isValid(e){try{o.parse(e);}catch{return false}return true}compare(e){let t=this.date.compare(e.date);return t!==0?t:this.time.compare(e.time)}toInstant(e){let t=this.date.toEpochDay(),n=(0, K.multiplyExact)(t,E.LocalTime.SECONDS_PER_DAY),r=(0, K.subtractExact)((0, K.addExact)(n,this.time.toSecondOfDay()),14*E.LocalTime.SECONDS_PER_HOUR),i=(0, K.addExact)(r,26*E.LocalTime.SECONDS_PER_HOUR),a=o.of(this.date,E.LocalTime.of(this.time.getHour(),this.time.getMinute(),this.time.getSecond())),s=new Date(r*E.LocalTime.MILLIS_PER_SECOND),p=o.fromZonedDate(s,e),c=Math.min(o.getTimeZoneMultiple(s,e.getId()),o.getTimeZoneMultiple(new Date(i*E.LocalTime.MILLIS_PER_SECOND),e.getId()));for(;!p.equals(a)&&(s.setTime((0, K.addExact)(s.getTime(),c*E.LocalTime.MILLIS_PER_SECOND)),p=o.fromZonedDate(s,e),!p.isAfter(a)););let l=(0, K.intDiv)(s.getTime(),E.LocalTime.MILLIS_PER_SECOND),u=this.time.getNano();return rl.Instant.ofEpochSecond(l,u)}static getTimeZoneMultiple(e,t){let n=Math.abs(o.getTimeZoneOffset(e,t));return n%E.LocalTime.SECONDS_PER_HOUR===0?E.LocalTime.SECONDS_PER_HOUR:n%(E.LocalTime.SECONDS_PER_HOUR/2)===0?E.LocalTime.SECONDS_PER_HOUR/2:E.LocalTime.SECONDS_PER_HOUR/4}static getTimeZoneOffset(e,t){let r=new Intl.DateTimeFormat("sv-SE",{timeZone:t,calendar:"iso8601",timeZoneName:"short"}).format(e).match(/GMT([+-]\d+)(?::(\d+))?/),i=Number.parseInt(r?.[1]??"0",10),a=Number.parseInt(r?.[2]??"0",10);return i*E.LocalTime.SECONDS_PER_HOUR+a*E.LocalTime.SECONDS_PER_MINUTE}toString(){return `${this.date.toString()}T${this.time.toString()}`}toJSON(){return this.toString()}};Kn.LocalDateTime=Oa;});var Qt=xe(Zn=>{Object.defineProperty(Zn,"__esModule",{value:true});Zn.Instant=void 0;var il=Ra(),ol=Vn(),al=Ta(),j=Hn(),L=Bt(),de=class o{constructor(e,t){this.nanos=0,this.seconds=e,this.nanos=t;}static now(e=il.DefaultClockProvider.getClock()){return e.getInstant()}static fromDate(e){return o.ofEpochMilli(e.getTime())}static ofEpochMilli(e){if(!Number.isSafeInteger(e))throw new Error("The timestamp must be a safe integer.");let t=(0, L.floorDiv)(e,j.LocalTime.MILLIS_PER_SECOND),r=(0, L.floorMod)(e,j.LocalTime.MILLIS_PER_SECOND)*j.LocalTime.NANOS_PER_MILLI;return o.ofEpochSecond(t,r)}static ofEpochSecond(e,t=0){if(!Number.isSafeInteger(e)||!Number.isSafeInteger(t))throw new Error("The timestamp must be a safe integer.");if(e===0&&t===0)return o.EPOCH;if(e<o.MIN_SECOND||e>o.MAX_SECOND)throw new Error(`The value ${e} is out of the range [${o.MIN_SECOND} - ${o.MAX_SECOND}] of instant.`);let n=e,r=t;return t!==0&&(n=(0, L.addExact)(n,(0, L.floorDiv)(t,j.LocalTime.NANOS_PER_SECOND)),r=(0, L.floorMod)(t,j.LocalTime.NANOS_PER_SECOND)),new o(n,r)}static parse(e){let n=e.match(o.PATTERN)?.groups;if(n==null)throw new Error(`Unrecognized UTC ISO-8601 date-time string "${e}".`);let r=ol.LocalDate.of(Number.parseInt(n.year,10),Number.parseInt(n.month,10),Number.parseInt(n.day,10)).toEpochDay(),i=j.LocalTime.of(Number.parseInt(n.hour,10),Number.parseInt(n.minute??"0",10),Number.parseInt(n.second??"0",10),Number.parseInt(n.fraction?.padEnd(9,"0")??"0",10)).toNanoOfDay();return o.ofEpochSecond((0, L.multiplyExact)(r,j.LocalTime.SECONDS_PER_DAY),i)}static compareAscending(e,t){return e.compare(t)}static compareDescending(e,t){return t.compare(e)}getSeconds(){return this.seconds}getNano(){return this.nanos}toEpochMillis(){if(this.seconds<0&&this.nanos>0){let n=(0, L.multiplyExact)(this.seconds+1,j.LocalTime.MILLIS_PER_SECOND),r=(0, L.intDiv)(this.nanos,j.LocalTime.NANOS_PER_MILLI)-j.LocalTime.MILLIS_PER_SECOND;return (0, L.addExact)(n,r)}let e=(0, L.multiplyExact)(this.seconds,j.LocalTime.MILLIS_PER_SECOND),t=(0, L.intDiv)(this.nanos,j.LocalTime.NANOS_PER_MILLI);return (0, L.addExact)(e,t)}toDate(){return new Date(this.toEpochMillis())}toString(){let e=this.seconds%12622780800,t=al.LocalDateTime.ofEpochSecond(e,this.nanos),n=t.getYear()+(0, L.intDiv)(this.seconds,146097*86400)*400,r="";n<0?r="-":n>9999&&(r="+");let a=r+Math.abs(n).toString().padStart(4,"0")+t.toString().slice(4);return t.getSecond()===0&&t.getNano()===0&&(a+=":00"),a+="Z",a}toJSON(){return this.toString()}equals(e){return this.seconds===e.seconds&&this.nanos===e.nanos}plusDays(e){if(e===0)return this;let t=(0, L.multiplyExact)(e,j.LocalTime.SECONDS_PER_DAY);return this.plusSeconds(t)}minusDays(e){if(e===0)return this;let t=(0, L.multiplyExact)(e,j.LocalTime.SECONDS_PER_DAY);return this.minusSeconds(t)}plusHours(e){if(e===0)return this;let t=(0, L.multiplyExact)(e,j.LocalTime.SECONDS_PER_HOUR);return this.plusSeconds(t)}minusHours(e){if(e===0)return this;let t=(0, L.multiplyExact)(e,j.LocalTime.SECONDS_PER_HOUR);return this.minusSeconds(t)}plusMinutes(e){if(e===0)return this;let t=(0, L.multiplyExact)(e,j.LocalTime.SECONDS_PER_MINUTE);return this.plusSeconds(t)}minusMinutes(e){if(e===0)return this;let t=(0, L.multiplyExact)(e,j.LocalTime.SECONDS_PER_MINUTE);return this.minusSeconds(t)}plusSeconds(e){return e===0?this:o.ofEpochSecond((0, L.addExact)(this.seconds,e),this.nanos)}minusSeconds(e){return e===0?this:o.ofEpochSecond((0, L.subtractExact)(this.seconds,e),this.nanos)}plusMillis(e){if(e===0)return this;let t=(0, L.intDiv)(e,j.LocalTime.MILLIS_PER_SECOND),n=(0, L.addExact)(this.seconds,t),r=e%j.LocalTime.MILLIS_PER_SECOND,i=this.nanos+r*j.LocalTime.NANOS_PER_MILLI;return o.ofEpochSecond(n,i)}minusMillis(e){return this.plusMillis(-e)}plusMicros(e){if(e===0)return this;let t=(0, L.intDiv)(e,j.LocalTime.MICROS_PER_SECOND),n=(0, L.addExact)(this.seconds,t),r=e%j.LocalTime.MICROS_PER_SECOND,i=this.nanos+r*j.LocalTime.NANOS_PER_MICRO;return o.ofEpochSecond(n,i)}minusMicros(e){return this.plusMicros(-e)}plusNanos(e){if(e===0)return this;let t=(0, L.intDiv)(e,j.LocalTime.NANOS_PER_SECOND),n=(0, L.addExact)(this.seconds,t),r=e%j.LocalTime.NANOS_PER_SECOND,i=this.nanos+r;return o.ofEpochSecond(n,i)}minusNanos(e){return this.plusNanos(-e)}isAfter(e){return this.compare(e)>0}isAfterOrEqual(e){return this.compare(e)>=0}isBefore(e){return this.compare(e)<0}static isValid(e){try{o.parse(e);}catch{return false}return true}isBeforeOrEqual(e){return this.compare(e)<=0}compare(e){return this.seconds!==e.seconds?this.seconds-e.seconds:this.nanos-e.nanos}};Zn.Instant=de;de.EPOCH=new de(0,0);de.MIN_SECOND=-31619087596800;de.MIN=new de(de.MIN_SECOND,0);de.MAX_SECOND=31494784780799;de.MAX=new de(de.MAX_SECOND,999999999);de.PATTERN=/^(?<year>[+-]?\d{4,19})-(?<month>\d{2})-(?<day>\d{2})T(?<hour>\d{2})(?::(?<minute>\d{2})(:(?<second>\d{2})(?:.(?<fraction>\d{1,9}))?)?)?Z$/;});var xs=xe(Jn=>{Object.defineProperty(Jn,"__esModule",{value:true});Jn.Weekday=void 0;var Is;(function(o){o.SUNDAY="SUNDAY",o.MONDAY="MONDAY",o.TUESDAY="TUESDAY",o.WEDNESDAY="WEDNESDAY",o.THURSDAY="THURSDAY",o.FRIDAY="FRIDAY",o.SATURDAY="SATURDAY";})(Is||(Jn.Weekday=Is={}));});var vs=xe(Qn=>{Object.defineProperty(Qn,"__esModule",{value:true});Qn.TimeInterval=void 0;var vt=Qt(),Da=class o{constructor(e,t){this.start=e,this.end=t;}static all(){return new o(vt.Instant.MIN,vt.Instant.MAX)}static between(e,t){if(t.isBefore(e))throw new Error("The end instant must be equal or after start instant.");return new o(e,t)}static parse(e){let t=e.split("/");if(t.length!==2||t[0]===""||t[1]==="")throw new Error(`Malformed time interval "${e}".`);return o.between(vt.Instant.parse(t[0]),vt.Instant.parse(t[1]))}static startingAt(e){return o.all().withStart(e)}static endingAt(e){return o.all().withEnd(e)}withStart(e){return o.between(e,this.end)}withEnd(e){return o.between(this.start,e)}getStart(){return this.start}getEnd(){return this.end}isEmpty(){return this.start.equals(this.end)}isUnboundedStart(){return this.start.equals(vt.Instant.MIN)}isUnboundedEnd(){return this.end.equals(vt.Instant.MAX)}encloses(e){return this.start.isBeforeOrEqual(e.start)&&this.end.isAfterOrEqual(e.end)}abuts(e){return this.start.equals(e.end)||this.end.equals(e.start)}isConnected(e){return this.equals(e)||this.start.isBeforeOrEqual(e.end)&&this.end.isAfterOrEqual(e.start)}overlaps(e){return this.equals(e)||this.start.isBefore(e.end)&&this.end.isAfter(e.start)}intersection(e){if(!this.isConnected(e))throw new Error("The intervals are not connected.");return this.start.isAfterOrEqual(e.start)&&this.end.isBefore(e.end)?this:e.start.isAfterOrEqual(this.start)&&e.end.isBeforeOrEqual(this.end)?e:o.between(this.start.isAfterOrEqual(e.start)?this.start:e.start,this.end.isBeforeOrEqual(e.end)?this.end:e.end)}union(e){if(!this.isConnected(e))throw new Error("The intervals are not connected.");return this.start.isAfterOrEqual(e.start)&&this.end.isBefore(e.end)?e:e.start.isAfterOrEqual(this.start)&&e.end.isBeforeOrEqual(this.end)?this:o.between(this.start.isAfterOrEqual(e.start)?e.start:this.start,this.end.isBeforeOrEqual(e.end)?e.end:this.end)}span(e){return o.between(this.start.isAfterOrEqual(e.start)?e.start:this.start,this.end.isBeforeOrEqual(e.end)?e.end:this.end)}isAfter(e){return this.start.isAfterOrEqual(e.end)&&!this.equals(e)}isBefore(e){return this.end.isBeforeOrEqual(e.start)&&!this.equals(e)}static isValid(e){try{o.parse(e);}catch{return false}return true}startsBefore(e){return this.start.isBefore(e)}startsAtOrBefore(e){return this.start.isBeforeOrEqual(e)}startsAfter(e){return this.start.isAfter(e)}startsAtOrAfter(e){return this.start.isAfterOrEqual(e)}endsBefore(e){return this.end.isBefore(e)}endsAtOrBefore(e){return this.end.isBeforeOrEqual(e)}endsAfter(e){return this.end.isAfter(e)}endsAtOrAfter(e){return this.end.isAfterOrEqual(e)}contains(e){return this.start.isBeforeOrEqual(e)&&this.end.isAfter(e)}equals(e){return e instanceof o&&this.start.equals(e.start)&&this.end.equals(e.end)}toString(){return `${this.start.toString()}/${this.end.toString()}`}toJSON(){return this.toString()}};Qn.TimeInterval=Da;});var Yt=xe(ee=>{Object.defineProperty(ee,"__esModule",{value:true});ee.TimeInterval=ee.TimeZone=ee.LocalDateTime=ee.LocalTime=ee.LocalDate=ee.Weekday=ee.Instant=void 0;var sl=Qt();Object.defineProperty(ee,"Instant",{enumerable:true,get:function(){return sl.Instant}});var pl=xs();Object.defineProperty(ee,"Weekday",{enumerable:true,get:function(){return pl.Weekday}});var cl=Vn();Object.defineProperty(ee,"LocalDate",{enumerable:true,get:function(){return cl.LocalDate}});var ll=Hn();Object.defineProperty(ee,"LocalTime",{enumerable:true,get:function(){return ll.LocalTime}});var ul=Ta();Object.defineProperty(ee,"LocalDateTime",{enumerable:true,get:function(){return ul.LocalDateTime}});var ml=ka();Object.defineProperty(ee,"TimeZone",{enumerable:true,get:function(){return ml.TimeZone}});var dl=vs();Object.defineProperty(ee,"TimeInterval",{enumerable:true,get:function(){return dl.TimeInterval}});});var gs=xt(ds()),{program:Md,createCommand:Nd,createArgument:$d,createOption:zd,CommanderError:Ld,InvalidArgumentError:Ge,InvalidOptionArgumentError:_d,Command:fs,Argument:ys,Option:pe,Help:Fd}=gs.default;var It=xt(Yt()),_c=xt(Ea());var Bn=class{constructor(e){this.configuration=e;}prompt(e){return this.interact({type:e.type==="password"?"invisible":"text",message:e.message,initial:e.default,validate:e.validate})}select(e){let t=e.default!==void 0?e.options.findIndex(n=>n.value===e.default):-1;return this.interact({type:e.options.length>10?"autocomplete":"select",instructions:false,message:e.message,choices:e.options.map((n,r)=>({title:n.label,value:`${r}`,disabled:n.disabled})),initial:t===-1?void 0:t}).then(n=>e.options[Number.parseInt(n,10)].value)}selectMultiple(e){return this.interact({type:e.options.length>10?"autocompleteMultiselect":"multiselect",hint:"<space> to select. <a> to toggle all. <enter> to submit.",message:e.message,instructions:false,min:e.min,max:e.max,choices:e.options.map((t,n)=>({title:t.label,value:`${n}`,disabled:t.disabled,selected:t.selected}))}).then(t=>t.map(n=>e.options[Number.parseInt(n,10)].value))}confirm(e){return this.interact({type:"confirm",message:e.message,initial:e.default??false})}wait(e){let t={enter:"[enter]",space:"[space]"},n={[t.enter]:"",[t.space]:" "},r=`Press <${e.key}> to continue`,i=e.key!==void 0?n[e.key]??e.key:void 0,a=false;return this.interact({type:"invisible",message:e.message,validate:s=>i===void 0||s===i?true:r,onState:function(p){if(!a){if(p.value===""){this.error&&e.key!==t.enter&&this.bell();return}i===void 0||p.value===i?(a=true,this.submit()):(this.bell(),this.reset(),i!==void 0&&(this.error=true,this.errorMsg=r));}}})}async interact(e,t){this.configuration.onInteractionStart?.();let{output:n,onAbort:r}=this.configuration,i={name:"value",...e,stdin:this.configuration.input,stdout:this.configuration.output,onState:function(s){e.onState?.apply(this,[s]),s.aborted&&(n.write("\x1B[?25h"),n.write(`
|
|
4
4
|
`),r());}};try{return await gl(i,t).then(a=>a.value)}finally{this.configuration.onInteractionEnd?.();}}};var it=fl(),Xt={neutral:"cyan",info:"blue",error:"red",warning:"yellow",success:"green"},Il={neutral:it?"\u279C":">",info:it?"\u2139":"i",error:it?"\u2718":"\xD7",warning:it?"\u26A0":"\u203C",success:it?"\u2714":"\u221A"};function te(o,e={}){let t=e.basic===true?o:xl(o);if(it||(t=strip(t)),e.text!==void 0&&(t=ot[Xt[e.text]](t)),e.icon!==void 0){let{semantics:n,symbol:r}=e.icon;t=r!==void 0?`${ot[Xt[n]](r[it?"unicode":"ascii"])} ${t}`:`${ot[Xt[n]](Il[n])} ${t}`;}return t}function xl(o){return render(o,{fragment:e=>e.children.join(""),text:e=>e.content,bold:e=>ot.bold(e.children),italic:e=>ot.italic(e.children),strike:e=>ot.strikethrough(e.children),code:e=>ot.cyan(e.content),link:e=>hl(e.children,e.href,{fallback:(t,n)=>`${t} (${n})`}),image:e=>unescape(e.source),paragraph:e=>`${e.children.join("")}
|
|
5
5
|
|
|
@@ -1734,7 +1734,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1734
1734
|
`),this.wrapElement(c,t,r),f.jsxText(`
|
|
1735
1735
|
`)]:[...p.slice(0,s),this.wrapElement(c,t,r),...p.slice(s)],{result:0,node:e}}return f.isJSXText(e)||f.isJSXExpressionContainer(e)||f.isJSXSpreadChild(e)||f.isJSXElement(e)||f.isJSXFragment(e)?{result:0,node:this.wrapElement(e,t,r)}:{result:1,node:e}}wrapElement(e,t,n){return e.extra?.parenthesized===true&&(e.extra.parenthesized=false),f.jsxElement(f.jsxOpeningElement(f.jsxIdentifier(t??this.configuration.wrapper.component),this.getProviderProps(n)),f.jsxClosingElement(f.jsxIdentifier(t??this.configuration.wrapper.component)),[f.jsxText(`
|
|
1736
1736
|
`),e,f.jsxText(`
|
|
1737
|
-
`)])}getProviderProps(e){return xr({...this.configuration.wrapper.props,...e?.props})}containsElement(e,t){let n=false;return traverseFast(e,r=>{!n&&f.isJSXOpeningElement(r)&&f.isJSXIdentifier(r.name)&&r.name.name===t&&(n=true);}),n}findComponentDeclaration(e,t){let n=null;return traverse(e,{VariableDeclaration:r=>{if(!f.isProgram(r.parent))return r.skip();for(let i of r.node.declarations)if(f.isVariableDeclarator(i)&&f.isIdentifier(i.id)&&i.id.name===t)return n=i,r.stop();return r.skip()},FunctionDeclaration:r=>{if(!f.isProgram(r.parent))return r.skip();let{id:i}=r.node;return f.isIdentifier(i)&&i.name===t?(n=r.node,r.stop()):r.skip()}}),n}findTargetChildren(e,t){let n=null,{configuration:r}=this;return r.targets?.variable===void 0&&r.targets?.component===void 0?null:(traverse(e,{enter:function(a){let{node:s}=a;if(s===t)return a.traverse({JSXExpressionContainer:p=>{let{expression:c}=p.node;if(r.targets?.variable!==void 0&&f.isIdentifier(c)&&c.name===r.targets.variable){let l=p.parent;return n={parent:l,index:l.children.indexOf(p.node)},p.stop()}},JSXElement:p=>{let{openingElement:c}=p.node;if(r.targets?.component!==void 0&&f.isJSXOpeningElement(c)&&f.isJSXIdentifier(c.name)&&c.name.name===r.targets.component&&p.parent!==null){let l=p.parent;n={parent:l,index:l.children.indexOf(p.node)};}}}),a.stop()}}),n)}static findReturnStatement(e){let t=null;return traverseFast(e,n=>{t===null&&f.isReturnStatement(n)&&(t=n);}),t}};var _e=class{constructor(e){this.codemod=e.codemod;}async apply(e,t){let n=vr.parse(e,{parser:{parse:parse}}),r=await this.codemod.apply(n,t);return r.modified?{modified:true,result:vr.print(r.result,{reuseWhitespace:false}).code}:{modified:false,result:e}}};function Ha(o,e){let t=typeof o=="string"?ze(o,["jsx","typescript"]):o,n=false;return traverse(t,{ExportAllDeclaration:r=>{let{node:i}=r;return !f.isStringLiteral(i.source)||!qa(i.source,e.moduleName)||(n=true),r.skip()},ExportNamedDeclaration:r=>{let{node:i}=r;if(!f.isStringLiteral(i.source)||!qa(i.source,e.moduleName))return r.skip();if(e.importName===void 0)return n=true,r.skip();for(let a of i.specifiers)if(f.isExportSpecifier(a)&&qa(a.local,e.importName))return n=true,r.skip();return r.skip()}}),n}function qa(o,e){let t=f.isIdentifier(o)?o.name:o.value;return typeof e=="string"?t===e:e.test(t)}function wr(o,e){let t=[],n=false,r=false;if(traverse(o,{ExportAllDeclaration:s=>{let{node:p}=s;if(p.source.value!==e.moduleName)return s.skip();let c=p.exportKind??"value";if(e.exportName===void 0&&e.importName===void 0){if(c==="value"||c==="type"&&e.type==="type")return n=true,s.stop();if(c==="type"&&e.type==="value")return p.exportKind="value",n=true,r=true,s.stop()}else if((e.exportName===void 0||e.exportName===e.importName)&&(c==="value"||c==="type"&&e.type==="type"))return n=true,s.stop();return s.skip()},ExportNamedDeclaration:s=>{let{node:p}=s,c=p.source??null;if(c===null||c.value!==e.moduleName)return s.skip();t.push({declaration:p});let l=p.exportKind??"value";for(let u of p.specifiers){if(f.isExportNamespaceSpecifier(u)&&e.importName===void 0&&u.exported.name===e.exportName)return n=true,e.type==="value"&&l==="type"&&(p.exportKind="value",r=true),s.stop();if(e.importName===void 0||!f.isExportSpecifier(u)||Ga(u.local)!==e.importName||e.exportName!==void 0&&Ga(u.exported)!==e.exportName)continue;let g=u.exportKind??"value";if(l===e.type||l==="value"&&(g==="value"||u.exportKind===e.type))return n=true,s.stop();t.unshift({declaration:p,specifier:u});}return s.skip()}}),n)return r;let{body:i}=o.program;if(e.importName===void 0){if(e.exportName===void 0)for(let p of t){let{declaration:c}=p,l=c.exportKind??"value",u=c.specifiers.filter(g=>!f.isExportSpecifier(g)||g.local.name!==Ga(g.exported)||e.type==="type"&&l!=="type"&&g.exportKind!=="type");u.length===0?i.splice(i.indexOf(c),1):c.specifiers=u;}let s=e.exportName===void 0?f.exportAllDeclaration(f.stringLiteral(e.moduleName)):f.exportNamedDeclaration(null,[f.exportNamespaceSpecifier(f.identifier(e.exportName))],f.stringLiteral(e.moduleName));return e.type==="type"&&(s.exportKind="type"),i.push(s),true}for(let s of t){let{declaration:p}=s;if(p.exportKind==="type"&&e.type==="value"){p.exportKind="value";for(let c of p.specifiers)f.isExportSpecifier(c)&&c!==s.specifier&&(c.exportKind="type");return s.specifier===void 0&&p.specifiers.push(f.exportSpecifier(f.identifier(e.importName),f.identifier(e.exportName??e.importName))),true}}for(let{declaration:s}of t){let p=s.exportKind??"value";if(p==="value"||p===e.type){let c=f.exportSpecifier(f.identifier(e.importName),f.identifier(e.exportName??e.importName));return p!==e.type&&(c.exportKind="type"),s.specifiers.push(c),true}}let a=f.exportNamedDeclaration(null,[f.exportSpecifier(f.identifier(e.importName),f.identifier(e.exportName??e.importName))],f.stringLiteral(e.moduleName));return e.type==="type"&&(a.exportKind="type"),i.push(a),true}function Ga(o){return f.isIdentifier(o)?o.name:o.value}var Pr=class o{constructor(e){this.configuration=e;}apply(e){let{body:t}=e.program,n=Ha(e,{moduleName:this.configuration.import.module,importName:this.configuration.import.configName}),r=Ha(e,{moduleName:this.configuration.import.module,importName:this.configuration.import.middlewareName}),i=n?null:o.findConfig(e);if(r){if(n||i!==null)return Promise.resolve({modified:false,result:e});let u=wr(e,{type:"value",moduleName:this.configuration.import.module,importName:this.configuration.import.configName});return Promise.resolve({modified:u,result:e})}let a=Tt(e,{moduleName:this.configuration.import.module,importName:this.configuration.import.middlewareFactoryName}),s=Tt(e,{moduleName:this.configuration.import.module,importName:this.configuration.import.middlewareName}),p=[];if(a!==null&&p.push(a),s!==null&&p.push(s),p.length>0&&o.isCalled(e,p))return Promise.resolve({modified:false,result:e});let c=i===null?null:Tt(e,{moduleName:this.configuration.import.module,importName:this.configuration.import.matcherName}),l=o.refactorMiddleware(e,a??this.configuration.import.middlewareFactoryName,i!==null&&i.matcher?i.name:void 0);if(l===null){if(i===null){let u=wr(e,{type:"value",moduleName:this.configuration.import.module,importName:this.configuration.import.middlewareName}),g=wr(e,{type:"value",moduleName:this.configuration.import.module,importName:this.configuration.import.configName});return Promise.resolve({modified:u||g,result:e})}l=f.exportDefaultDeclaration(f.callExpression(f.identifier(a??this.configuration.import.middlewareFactoryName),[f.objectExpression([f.objectProperty(f.identifier("matcher"),f.memberExpression(f.identifier(i.name),f.identifier(c??this.configuration.import.matcherName)))])])),t.push(l);}if(i!==null){this.configureMatcher(i.object,c??this.configuration.import.matcherLocalName);let u=t.indexOf(i.root),g=t.indexOf(l);if(u>g){t.splice(g,0,...t.splice(u,1));for(let y of o.findReferencesFrom(i.root,e.program)){let x=t.indexOf(y);x>g&&t.splice(g,0,...t.splice(x,1));}}}return a===null&&he(e,{type:"value",moduleName:this.configuration.import.module,importName:this.configuration.import.middlewareFactoryName}),i?.matcher===true&&c===null&&he(e,{type:"value",moduleName:this.configuration.import.module,importName:this.configuration.import.matcherName,localName:this.configuration.import.matcherLocalName}),Promise.resolve({modified:true,result:e})}configureMatcher(e,t){let n=false;for(let r of e.properties)if(f.isObjectProperty(r)&&f.isIdentifier(r.key)&&r.key.name==="matcher"){if(f.isStringLiteral(r.value)){r.value=f.arrayExpression([r.value,f.identifier(t)]),n=true;break}if(f.isArrayExpression(r.value)){let{elements:i}=r.value;i.some(a=>f.isIdentifier(a)&&a.name===t)||(i.push(f.identifier(t)),n=true);break}if(f.isIdentifier(r.value)){if(r.value.name===t)break;r.value=f.arrayExpression([f.spreadElement(f.conditionalExpression(f.callExpression(f.memberExpression(f.identifier("Array"),f.identifier("isArray")),[r.value]),r.value,f.arrayExpression([r.value]))),f.identifier(t)]),n=true;}}return n}static refactorMiddleware(e,t,n){let r=null;return traverse(e,{ExportNamedDeclaration:i=>{let{node:a}=i,{declaration:s,specifiers:p=[]}=a;if(f.isFunctionDeclaration(s))return f.isFunctionDeclaration(a.declaration)&&f.isIdentifier(a.declaration.id)&&a.declaration.id.name==="middleware"?(i.replaceWith(f.exportNamedDeclaration(f.variableDeclaration("const",[f.variableDeclarator(f.identifier("middleware"),o.wrapMiddleware(f.isFunctionDeclaration(a.declaration)?o.createFunctionExpression(a.declaration):a.declaration,t,n))]),[])),r=o.getRootNode(i),i.stop()):i.skip();if(f.isVariableDeclaration(s)){for(let c of s.declarations)if(f.isVariableDeclarator(c)&&f.isIdentifier(c.id)&&c.id.name==="middleware"){let l=c.init??null;if(l!==null)return c.init=o.wrapMiddleware(l,t,n),r=o.getRootNode(i),i.stop()}}for(let c of p)if(f.isExportSpecifier(c)&&f.isIdentifier(c.exported)&&f.isIdentifier(c.local)&&["middleware","default"].includes(c.exported.name))return r=o.replaceMiddlewareDeclaration(e,c.local.name,t,n),i.stop();return i.skip()},ExportDefaultDeclaration:i=>{let{node:a}=i,{declaration:s}=a;return f.isArrowFunctionExpression(s)?(i.replaceWith(f.exportDefaultDeclaration(o.wrapMiddleware(s,t,n))),r=o.getRootNode(i),i.stop()):f.isFunctionDeclaration(s)?(i.replaceWith(f.exportDefaultDeclaration(o.wrapMiddleware(o.createFunctionExpression(s,true),t,n))),r=o.getRootNode(i),i.stop()):f.isIdentifier(s)?(r=o.replaceMiddlewareDeclaration(e,s.name,t,n),i.stop()):i.skip()}}),r}static replaceMiddlewareDeclaration(e,t,n,r){let i=null;return traverse(e,{VariableDeclarator:a=>{let{node:s}=a;if(f.isIdentifier(s.id)&&s.id.name===t){let p=s.init??null;return p!==null&&(s.init=o.wrapMiddleware(p,n,r),i=o.getRootNode(a)),a.stop()}return a.skip()},FunctionDeclaration:a=>{let{node:s}=a;return f.isIdentifier(s.id)&&s.id.name===t?(a.replaceWith(o.wrapFunctionDeclaration(s,n,r,f.isIdentifier(s.id)?s.id.name:void 0)),i=o.getRootNode(a),a.stop()):a.skip()}}),i}static isCalled(e,t){let n=false;return traverse(e,{CallExpression:r=>{let{node:i}=r;return f.isIdentifier(i.callee)&&t.includes(i.callee.name)?(n=true,r.stop()):r.skip()}}),n}static findConfig(e){let t=null;return traverse(e,{ExportNamedDeclaration:n=>{let{declaration:r,specifiers:i=[]}=n.node;if(f.isVariableDeclaration(r)){for(let a of r.declarations)if(f.isVariableDeclarator(a)&&f.isIdentifier(a.id)&&a.id.name==="config"){let s=f.isIdentifier(a.init)?o.findVariableDeclarator(e,a.init.name):{name:"config",root:o.getRootNode(n),declaration:a};if(s===null||s.declaration.init===null)return n.stop();if(f.isObjectExpression(s.declaration.init))return t={name:s.name,root:s.root,object:s.declaration.init,matcher:o.hasMatcherProperty(s.declaration.init)},n.stop()}}for(let a of i)if(f.isExportSpecifier(a)&&f.isIdentifier(a.exported)&&f.isIdentifier(a.local)&&a.exported.name==="config"){let s=o.findVariableDeclarator(e,a.local.name);return s!==null&&f.isObjectExpression(s.declaration.init)&&(t={name:s.name,root:s.root,object:s.declaration.init,matcher:o.hasMatcherProperty(s.declaration.init)}),n.stop()}return n.skip()}}),t}static hasMatcherProperty(e){for(let t of e.properties)if(f.isObjectProperty(t)&&f.isIdentifier(t.key)&&t.key.name==="matcher")return true;return false}static findVariableDeclarator(e,t){let n=null;return traverse(e,{VariableDeclarator:r=>{if(!f.isProgram(r.parentPath.parent))return r.skip();let{node:i}=r;return f.isVariableDeclarator(i)&&f.isIdentifier(i.id)&&i.id.name===t?(f.isIdentifier(i.init)?n=o.findVariableDeclarator(e,i.init.name):n={name:t,root:o.getRootNode(r),declaration:i},r.stop()):r.skip()}}),n}static wrapMiddleware(e,t,n){return f.callExpression(f.identifier(t),[n!==void 0?f.objectExpression([f.objectProperty(f.identifier("matcher"),f.memberExpression(f.identifier(n),f.identifier("matcher"))),f.objectProperty(f.identifier("next"),e)]):e])}static wrapFunctionDeclaration(e,t,n,r="middleware"){return f.variableDeclaration("const",[f.variableDeclarator(f.identifier(r),o.wrapMiddleware(o.createFunctionExpression(e),t,n))])}static findReferencesFrom(e,t){let n=new Set;traverse(t,{enter:i=>{let{node:a}=i;if(a===e)return i.traverse({Identifier:function(p){let c=p.node;return o.isVariableReference(p.parent,c)&&n.add(c.name),p.skip()}}),i.stop()}});let r=[];return traverse(t,{VariableDeclarator:i=>{if(!f.isProgram(i.parentPath.parent))return i.skip();let{node:a}=i;return f.isIdentifier(a.id)&&n.has(a.id.name)&&r.push(o.getRootNode(i)),i.skip()},FunctionDeclaration:i=>{if(!f.isProgram(i.parent))return;let{node:a}=i;return f.isIdentifier(a.id)&&n.has(a.id.name)&&r.push(o.getRootNode(i)),i.skip()},ClassDeclaration:i=>{if(!f.isProgram(i.parent))return;let{node:a}=i;return f.isIdentifier(a.id)&&n.has(a.id.name)&&r.push(o.getRootNode(i)),i.skip()}}),[...new Set(r.flatMap(i=>[i,...o.findReferencesFrom(i,t)]))]}static isVariableReference(e,t){return f.isVariableDeclarator(e)?e.init===t:f.isClassProperty(e)||f.isObjectProperty(e)||f.isProperty(e)?e.value===t:f.isMemberExpression(e)?e.object===t:f.isCallExpression(e)||f.isNewExpression(e)?e.callee===t:f.isExpression(e)}static createFunctionExpression(e,t=false){return f.functionExpression(t?e.id:null,e.params,e.body,e.generator,e.async)}static getRootNode(e){let t=e;for(;t.parentPath!==null&&!f.isProgram(t.parent);)t=t.parentPath;return t.node}};var Ze=class{constructor(e,t){this.codemod=t,this.formatter=e;}async apply(e,t){if(this.codemod===void 0)return await this.formatter.format([e]),{modified:true,result:e};let n=await this.codemod.apply(e,t);return n.modified&&await this.formatter.format([e]),n}};var Fe=class{constructor({fileSystem:e,codemod:t}){this.fileSystem=e,this.codemod=t;}async apply(e,t){let n="";if(await this.fileSystem.exists(e))try{n=await this.fileSystem.readTextFile(e);}catch(i){throw new Ye("Failed to read file.",{cause:i,details:[`File: file://${e.replace(/\\/g,"/")}`]})}let r=await this.codemod.apply(n,t);if(r.modified)try{await this.fileSystem.writeTextFile(e,r.result,{overwrite:!0});}catch(i){throw new Ye("Failed to write file",{cause:i,details:[`File: file://${e.replace(/\\/g,"/")}`]})}return {modified:r.modified,result:e}}};var Cr=class{constructor(e){this.configuration=e;}apply(e,t={}){let n=t.typescript??false,{body:r}=e.program,i=he(e,{type:"value",moduleName:this.configuration.provider.module,importName:this.configuration.provider.component}),a=n?he(e,{type:"type",moduleName:"react",importName:"PropsWithChildren"}):null,s=n?he(e,{type:"type",moduleName:"react",importName:"ReactNode"}):null,p=f.objectPattern([f.objectProperty(f.identifier("children"),f.identifier("children"))]);a!==null&&(p.typeAnnotation=f.tsTypeAnnotation(f.tsTypeReference(f.identifier(a.localName))));let c=f.functionDeclaration(f.identifier("RootLayout"),[p],f.blockStatement([f.returnStatement(f.parenthesizedExpression(f.jsxElement(f.jsxOpeningElement(f.jsxIdentifier("html"),[f.jsxAttribute(f.jsxIdentifier("lang"),f.stringLiteral("en"))]),f.jsxClosingElement(f.jsxIdentifier("html")),[f.jsxText(`
|
|
1737
|
+
`)])}getProviderProps(e){return xr({...this.configuration.wrapper.props,...e?.props})}containsElement(e,t){let n=false;return traverseFast(e,r=>{!n&&f.isJSXOpeningElement(r)&&f.isJSXIdentifier(r.name)&&r.name.name===t&&(n=true);}),n}findComponentDeclaration(e,t){let n=null;return traverse(e,{VariableDeclaration:r=>{if(!f.isProgram(r.parent))return r.skip();for(let i of r.node.declarations)if(f.isVariableDeclarator(i)&&f.isIdentifier(i.id)&&i.id.name===t)return n=i,r.stop();return r.skip()},FunctionDeclaration:r=>{if(!f.isProgram(r.parent))return r.skip();let{id:i}=r.node;return f.isIdentifier(i)&&i.name===t?(n=r.node,r.stop()):r.skip()}}),n}findTargetChildren(e,t){let n=null,{configuration:r}=this;return r.targets?.variable===void 0&&r.targets?.component===void 0?null:(traverse(e,{enter:function(a){let{node:s}=a;if(s===t)return a.traverse({JSXExpressionContainer:p=>{let{expression:c}=p.node;if(r.targets?.variable!==void 0&&f.isIdentifier(c)&&c.name===r.targets.variable){let l=p.parent;return n={parent:l,index:l.children.indexOf(p.node)},p.stop()}},JSXElement:p=>{let{openingElement:c}=p.node;if(r.targets?.component!==void 0&&f.isJSXOpeningElement(c)&&f.isJSXIdentifier(c.name)&&c.name.name===r.targets.component&&p.parent!==null){let l=p.parent;n={parent:l,index:l.children.indexOf(p.node)};}}}),a.stop()}}),n)}static findReturnStatement(e){let t=null;return traverseFast(e,n=>{t===null&&f.isReturnStatement(n)&&(t=n);}),t}};var _e=class{constructor(e){this.codemod=e.codemod;}async apply(e,t){let n=vr.parse(e,{parser:{parse:parse$1}}),r=await this.codemod.apply(n,t);return r.modified?{modified:true,result:vr.print(r.result,{reuseWhitespace:false}).code}:{modified:false,result:e}}};function Ha(o,e){let t=typeof o=="string"?ze(o,["jsx","typescript"]):o,n=false;return traverse(t,{ExportAllDeclaration:r=>{let{node:i}=r;return !f.isStringLiteral(i.source)||!qa(i.source,e.moduleName)||(n=true),r.skip()},ExportNamedDeclaration:r=>{let{node:i}=r;if(!f.isStringLiteral(i.source)||!qa(i.source,e.moduleName))return r.skip();if(e.importName===void 0)return n=true,r.skip();for(let a of i.specifiers)if(f.isExportSpecifier(a)&&qa(a.local,e.importName))return n=true,r.skip();return r.skip()}}),n}function qa(o,e){let t=f.isIdentifier(o)?o.name:o.value;return typeof e=="string"?t===e:e.test(t)}function wr(o,e){let t=[],n=false,r=false;if(traverse(o,{ExportAllDeclaration:s=>{let{node:p}=s;if(p.source.value!==e.moduleName)return s.skip();let c=p.exportKind??"value";if(e.exportName===void 0&&e.importName===void 0){if(c==="value"||c==="type"&&e.type==="type")return n=true,s.stop();if(c==="type"&&e.type==="value")return p.exportKind="value",n=true,r=true,s.stop()}else if((e.exportName===void 0||e.exportName===e.importName)&&(c==="value"||c==="type"&&e.type==="type"))return n=true,s.stop();return s.skip()},ExportNamedDeclaration:s=>{let{node:p}=s,c=p.source??null;if(c===null||c.value!==e.moduleName)return s.skip();t.push({declaration:p});let l=p.exportKind??"value";for(let u of p.specifiers){if(f.isExportNamespaceSpecifier(u)&&e.importName===void 0&&u.exported.name===e.exportName)return n=true,e.type==="value"&&l==="type"&&(p.exportKind="value",r=true),s.stop();if(e.importName===void 0||!f.isExportSpecifier(u)||Ga(u.local)!==e.importName||e.exportName!==void 0&&Ga(u.exported)!==e.exportName)continue;let g=u.exportKind??"value";if(l===e.type||l==="value"&&(g==="value"||u.exportKind===e.type))return n=true,s.stop();t.unshift({declaration:p,specifier:u});}return s.skip()}}),n)return r;let{body:i}=o.program;if(e.importName===void 0){if(e.exportName===void 0)for(let p of t){let{declaration:c}=p,l=c.exportKind??"value",u=c.specifiers.filter(g=>!f.isExportSpecifier(g)||g.local.name!==Ga(g.exported)||e.type==="type"&&l!=="type"&&g.exportKind!=="type");u.length===0?i.splice(i.indexOf(c),1):c.specifiers=u;}let s=e.exportName===void 0?f.exportAllDeclaration(f.stringLiteral(e.moduleName)):f.exportNamedDeclaration(null,[f.exportNamespaceSpecifier(f.identifier(e.exportName))],f.stringLiteral(e.moduleName));return e.type==="type"&&(s.exportKind="type"),i.push(s),true}for(let s of t){let{declaration:p}=s;if(p.exportKind==="type"&&e.type==="value"){p.exportKind="value";for(let c of p.specifiers)f.isExportSpecifier(c)&&c!==s.specifier&&(c.exportKind="type");return s.specifier===void 0&&p.specifiers.push(f.exportSpecifier(f.identifier(e.importName),f.identifier(e.exportName??e.importName))),true}}for(let{declaration:s}of t){let p=s.exportKind??"value";if(p==="value"||p===e.type){let c=f.exportSpecifier(f.identifier(e.importName),f.identifier(e.exportName??e.importName));return p!==e.type&&(c.exportKind="type"),s.specifiers.push(c),true}}let a=f.exportNamedDeclaration(null,[f.exportSpecifier(f.identifier(e.importName),f.identifier(e.exportName??e.importName))],f.stringLiteral(e.moduleName));return e.type==="type"&&(a.exportKind="type"),i.push(a),true}function Ga(o){return f.isIdentifier(o)?o.name:o.value}var Pr=class o{constructor(e){this.configuration=e;}apply(e){let{body:t}=e.program,n=Ha(e,{moduleName:this.configuration.import.module,importName:this.configuration.import.configName}),r=Ha(e,{moduleName:this.configuration.import.module,importName:this.configuration.import.middlewareName}),i=n?null:o.findConfig(e);if(r){if(n||i!==null)return Promise.resolve({modified:false,result:e});let u=wr(e,{type:"value",moduleName:this.configuration.import.module,importName:this.configuration.import.configName});return Promise.resolve({modified:u,result:e})}let a=Tt(e,{moduleName:this.configuration.import.module,importName:this.configuration.import.middlewareFactoryName}),s=Tt(e,{moduleName:this.configuration.import.module,importName:this.configuration.import.middlewareName}),p=[];if(a!==null&&p.push(a),s!==null&&p.push(s),p.length>0&&o.isCalled(e,p))return Promise.resolve({modified:false,result:e});let c=i===null?null:Tt(e,{moduleName:this.configuration.import.module,importName:this.configuration.import.matcherName}),l=o.refactorMiddleware(e,a??this.configuration.import.middlewareFactoryName,i!==null&&i.matcher?i.name:void 0);if(l===null){if(i===null){let u=wr(e,{type:"value",moduleName:this.configuration.import.module,importName:this.configuration.import.middlewareName}),g=wr(e,{type:"value",moduleName:this.configuration.import.module,importName:this.configuration.import.configName});return Promise.resolve({modified:u||g,result:e})}l=f.exportDefaultDeclaration(f.callExpression(f.identifier(a??this.configuration.import.middlewareFactoryName),[f.objectExpression([f.objectProperty(f.identifier("matcher"),f.memberExpression(f.identifier(i.name),f.identifier(c??this.configuration.import.matcherName)))])])),t.push(l);}if(i!==null){this.configureMatcher(i.object,c??this.configuration.import.matcherLocalName);let u=t.indexOf(i.root),g=t.indexOf(l);if(u>g){t.splice(g,0,...t.splice(u,1));for(let y of o.findReferencesFrom(i.root,e.program)){let x=t.indexOf(y);x>g&&t.splice(g,0,...t.splice(x,1));}}}return a===null&&he(e,{type:"value",moduleName:this.configuration.import.module,importName:this.configuration.import.middlewareFactoryName}),i?.matcher===true&&c===null&&he(e,{type:"value",moduleName:this.configuration.import.module,importName:this.configuration.import.matcherName,localName:this.configuration.import.matcherLocalName}),Promise.resolve({modified:true,result:e})}configureMatcher(e,t){let n=false;for(let r of e.properties)if(f.isObjectProperty(r)&&f.isIdentifier(r.key)&&r.key.name==="matcher"){if(f.isStringLiteral(r.value)){r.value=f.arrayExpression([r.value,f.identifier(t)]),n=true;break}if(f.isArrayExpression(r.value)){let{elements:i}=r.value;i.some(a=>f.isIdentifier(a)&&a.name===t)||(i.push(f.identifier(t)),n=true);break}if(f.isIdentifier(r.value)){if(r.value.name===t)break;r.value=f.arrayExpression([f.spreadElement(f.conditionalExpression(f.callExpression(f.memberExpression(f.identifier("Array"),f.identifier("isArray")),[r.value]),r.value,f.arrayExpression([r.value]))),f.identifier(t)]),n=true;}}return n}static refactorMiddleware(e,t,n){let r=null;return traverse(e,{ExportNamedDeclaration:i=>{let{node:a}=i,{declaration:s,specifiers:p=[]}=a;if(f.isFunctionDeclaration(s))return f.isFunctionDeclaration(a.declaration)&&f.isIdentifier(a.declaration.id)&&a.declaration.id.name==="middleware"?(i.replaceWith(f.exportNamedDeclaration(f.variableDeclaration("const",[f.variableDeclarator(f.identifier("middleware"),o.wrapMiddleware(f.isFunctionDeclaration(a.declaration)?o.createFunctionExpression(a.declaration):a.declaration,t,n))]),[])),r=o.getRootNode(i),i.stop()):i.skip();if(f.isVariableDeclaration(s)){for(let c of s.declarations)if(f.isVariableDeclarator(c)&&f.isIdentifier(c.id)&&c.id.name==="middleware"){let l=c.init??null;if(l!==null)return c.init=o.wrapMiddleware(l,t,n),r=o.getRootNode(i),i.stop()}}for(let c of p)if(f.isExportSpecifier(c)&&f.isIdentifier(c.exported)&&f.isIdentifier(c.local)&&["middleware","default"].includes(c.exported.name))return r=o.replaceMiddlewareDeclaration(e,c.local.name,t,n),i.stop();return i.skip()},ExportDefaultDeclaration:i=>{let{node:a}=i,{declaration:s}=a;return f.isArrowFunctionExpression(s)?(i.replaceWith(f.exportDefaultDeclaration(o.wrapMiddleware(s,t,n))),r=o.getRootNode(i),i.stop()):f.isFunctionDeclaration(s)?(i.replaceWith(f.exportDefaultDeclaration(o.wrapMiddleware(o.createFunctionExpression(s,true),t,n))),r=o.getRootNode(i),i.stop()):f.isIdentifier(s)?(r=o.replaceMiddlewareDeclaration(e,s.name,t,n),i.stop()):i.skip()}}),r}static replaceMiddlewareDeclaration(e,t,n,r){let i=null;return traverse(e,{VariableDeclarator:a=>{let{node:s}=a;if(f.isIdentifier(s.id)&&s.id.name===t){let p=s.init??null;return p!==null&&(s.init=o.wrapMiddleware(p,n,r),i=o.getRootNode(a)),a.stop()}return a.skip()},FunctionDeclaration:a=>{let{node:s}=a;return f.isIdentifier(s.id)&&s.id.name===t?(a.replaceWith(o.wrapFunctionDeclaration(s,n,r,f.isIdentifier(s.id)?s.id.name:void 0)),i=o.getRootNode(a),a.stop()):a.skip()}}),i}static isCalled(e,t){let n=false;return traverse(e,{CallExpression:r=>{let{node:i}=r;return f.isIdentifier(i.callee)&&t.includes(i.callee.name)?(n=true,r.stop()):r.skip()}}),n}static findConfig(e){let t=null;return traverse(e,{ExportNamedDeclaration:n=>{let{declaration:r,specifiers:i=[]}=n.node;if(f.isVariableDeclaration(r)){for(let a of r.declarations)if(f.isVariableDeclarator(a)&&f.isIdentifier(a.id)&&a.id.name==="config"){let s=f.isIdentifier(a.init)?o.findVariableDeclarator(e,a.init.name):{name:"config",root:o.getRootNode(n),declaration:a};if(s===null||s.declaration.init===null)return n.stop();if(f.isObjectExpression(s.declaration.init))return t={name:s.name,root:s.root,object:s.declaration.init,matcher:o.hasMatcherProperty(s.declaration.init)},n.stop()}}for(let a of i)if(f.isExportSpecifier(a)&&f.isIdentifier(a.exported)&&f.isIdentifier(a.local)&&a.exported.name==="config"){let s=o.findVariableDeclarator(e,a.local.name);return s!==null&&f.isObjectExpression(s.declaration.init)&&(t={name:s.name,root:s.root,object:s.declaration.init,matcher:o.hasMatcherProperty(s.declaration.init)}),n.stop()}return n.skip()}}),t}static hasMatcherProperty(e){for(let t of e.properties)if(f.isObjectProperty(t)&&f.isIdentifier(t.key)&&t.key.name==="matcher")return true;return false}static findVariableDeclarator(e,t){let n=null;return traverse(e,{VariableDeclarator:r=>{if(!f.isProgram(r.parentPath.parent))return r.skip();let{node:i}=r;return f.isVariableDeclarator(i)&&f.isIdentifier(i.id)&&i.id.name===t?(f.isIdentifier(i.init)?n=o.findVariableDeclarator(e,i.init.name):n={name:t,root:o.getRootNode(r),declaration:i},r.stop()):r.skip()}}),n}static wrapMiddleware(e,t,n){return f.callExpression(f.identifier(t),[n!==void 0?f.objectExpression([f.objectProperty(f.identifier("matcher"),f.memberExpression(f.identifier(n),f.identifier("matcher"))),f.objectProperty(f.identifier("next"),e)]):e])}static wrapFunctionDeclaration(e,t,n,r="middleware"){return f.variableDeclaration("const",[f.variableDeclarator(f.identifier(r),o.wrapMiddleware(o.createFunctionExpression(e),t,n))])}static findReferencesFrom(e,t){let n=new Set;traverse(t,{enter:i=>{let{node:a}=i;if(a===e)return i.traverse({Identifier:function(p){let c=p.node;return o.isVariableReference(p.parent,c)&&n.add(c.name),p.skip()}}),i.stop()}});let r=[];return traverse(t,{VariableDeclarator:i=>{if(!f.isProgram(i.parentPath.parent))return i.skip();let{node:a}=i;return f.isIdentifier(a.id)&&n.has(a.id.name)&&r.push(o.getRootNode(i)),i.skip()},FunctionDeclaration:i=>{if(!f.isProgram(i.parent))return;let{node:a}=i;return f.isIdentifier(a.id)&&n.has(a.id.name)&&r.push(o.getRootNode(i)),i.skip()},ClassDeclaration:i=>{if(!f.isProgram(i.parent))return;let{node:a}=i;return f.isIdentifier(a.id)&&n.has(a.id.name)&&r.push(o.getRootNode(i)),i.skip()}}),[...new Set(r.flatMap(i=>[i,...o.findReferencesFrom(i,t)]))]}static isVariableReference(e,t){return f.isVariableDeclarator(e)?e.init===t:f.isClassProperty(e)||f.isObjectProperty(e)||f.isProperty(e)?e.value===t:f.isMemberExpression(e)?e.object===t:f.isCallExpression(e)||f.isNewExpression(e)?e.callee===t:f.isExpression(e)}static createFunctionExpression(e,t=false){return f.functionExpression(t?e.id:null,e.params,e.body,e.generator,e.async)}static getRootNode(e){let t=e;for(;t.parentPath!==null&&!f.isProgram(t.parent);)t=t.parentPath;return t.node}};var Ze=class{constructor(e,t){this.codemod=t,this.formatter=e;}async apply(e,t){if(this.codemod===void 0)return await this.formatter.format([e]),{modified:true,result:e};let n=await this.codemod.apply(e,t);return n.modified&&await this.formatter.format([e]),n}};var Fe=class{constructor({fileSystem:e,codemod:t}){this.fileSystem=e,this.codemod=t;}async apply(e,t){let n="";if(await this.fileSystem.exists(e))try{n=await this.fileSystem.readTextFile(e);}catch(i){throw new Ye("Failed to read file.",{cause:i,details:[`File: file://${e.replace(/\\/g,"/")}`]})}let r=await this.codemod.apply(n,t);if(r.modified)try{await this.fileSystem.writeTextFile(e,r.result,{overwrite:!0});}catch(i){throw new Ye("Failed to write file",{cause:i,details:[`File: file://${e.replace(/\\/g,"/")}`]})}return {modified:r.modified,result:e}}};var Cr=class{constructor(e){this.configuration=e;}apply(e,t={}){let n=t.typescript??false,{body:r}=e.program,i=he(e,{type:"value",moduleName:this.configuration.provider.module,importName:this.configuration.provider.component}),a=n?he(e,{type:"type",moduleName:"react",importName:"PropsWithChildren"}):null,s=n?he(e,{type:"type",moduleName:"react",importName:"ReactNode"}):null,p=f.objectPattern([f.objectProperty(f.identifier("children"),f.identifier("children"))]);a!==null&&(p.typeAnnotation=f.tsTypeAnnotation(f.tsTypeReference(f.identifier(a.localName))));let c=f.functionDeclaration(f.identifier("RootLayout"),[p],f.blockStatement([f.returnStatement(f.parenthesizedExpression(f.jsxElement(f.jsxOpeningElement(f.jsxIdentifier("html"),[f.jsxAttribute(f.jsxIdentifier("lang"),f.stringLiteral("en"))]),f.jsxClosingElement(f.jsxIdentifier("html")),[f.jsxText(`
|
|
1738
1738
|
`),f.jsxElement(f.jsxOpeningElement(f.jsxIdentifier("body"),[]),f.jsxClosingElement(f.jsxIdentifier("body")),[f.jsxText(`
|
|
1739
1739
|
`),f.jsxElement(f.jsxOpeningElement(f.jsxIdentifier(i.localName),[]),f.jsxClosingElement(f.jsxIdentifier(i.localName)),[f.jsxText(`
|
|
1740
1740
|
`),f.jsxExpressionContainer(f.identifier("children")),f.jsxText(`
|
|
@@ -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 x=this.fileSystem.joinPaths("./",this.fileSystem.getRelativePath(this.fileSystem.getDirectoryName(u),y));for(let v of g.include){let M=new Minimatch(v,{partial:true,magicalBraces:true});if(!M.hasMagic()&&!v.includes(".")&&(M=new Minimatch(`${v.replace(/\/?$/,"")}/**/*`,{partial:true})),M.match(x))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(yd(r))return t=true,n.stop()}}),t}function yd(o){return isTypeScript(o)||hd(o)}function hd(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([Id,{onlyRemoveTypeImports:true}]),n=createConfigItem([xd,{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],x=u.find((M,q)=>q>g&&!["CommentLine","CommentBlock"].includes(M.type));if(x===void 0)continue;x.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=wd("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??!Pd.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 Je({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 Je({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),componentForm:new tt({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})},io:{input:this.getInput(),output:this.getOutput()}}),e)}addSlot(e){return this.execute(new Dt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new Je({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}removeSlot(e){return this.execute(new sn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),slotForm:new Je({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}addComponent(e){return this.execute(new 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 Je({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 Ze(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 Je({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:ss}),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 {packageManager:oe.transient(()=>({name:this.getPackageManager().getName()})),project:{features:oe.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{features:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),quotas:oe.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{quotas:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),organization:oe.transient(async()=>{let{organization:t}=await this.getConfigurationManager().load();return {slug:t,url:e(`organizations/${t}`)}}),workspace:oe.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load();return {slug:n,url:e(`organizations/${t}/workspaces/${n}`)}}),application:oe.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:oe.transient(async()=>{let t=this.getSdk(),n=await this.getConfigurationManager().load();return t.getPaths(n)}),platform:oe.transient(async()=>await this.getPlatformProvider().get()??"unknown"),server:oe.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 Ze(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 Ze(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 Ze(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 Ze(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 Ze(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 I:if(e.tracing.length>0){let t=e.tracing.map(({name:n,source:r},i)=>{let a=r!==void 0?` at ${o.getSourceLocation(r)}`:"";return `${" ".repeat(i+1)}\u21B3 \`${n}\`${a}`}).join(`
|
|
1842
|
+
`);await this.fileSystem.writeTextFile(n,s,{overwrite:true});let p=o.parseHandlers(a);p.schemes[e]!==void 0&&(delete p.schemes[e],await this.fileSystem.writeTextFile(r,JSON.stringify(p),{overwrite:true}));}getUserPreferencesFilePath(e){return this.fileSystem.joinPaths(e,"user.js")}getHandlersFilePath(e){return this.fileSystem.joinPaths(e,"handlers.json")}async getProfilePath(){let e=this.getPath("profiles.ini");if(!await this.fileSystem.exists(e))return null;let t=Object.values(parse(await this.fileSystem.readTextFile(e))),n=[],r=[];for(let a of t)a.Default!==void 0&&n.push(a.Default),a.Path!==void 0&&(a.Default==="1"?r.unshift(a.Path):r.push(a.Path));if(r.length===0)return null;let i=r[0];for(let a of r)if(n.includes(a)){i=a;break}return this.getPath(i)}getPath(e){return this.fileSystem.joinPaths(this.profileDirectory,e)}getPreferences(e){return o.PREFERENCES.map(t=>t.replace(/%protocol%/g,e))}static parseHandlers(e){let t;try{t=JSON.parse(e);}catch{return {schemes:{}}}return typeof t!="object"||t===null?{schemes:{}}:!("schemes"in t)||typeof t.schemes!="object"||t.schemes===null?{...t,schemes:{}}:t}};var 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 x=this.fileSystem.joinPaths("./",this.fileSystem.getRelativePath(this.fileSystem.getDirectoryName(u),y));for(let v of g.include){let M=new Minimatch(v,{partial:true,magicalBraces:true});if(!M.hasMagic()&&!v.includes(".")&&(M=new Minimatch(`${v.replace(/\/?$/,"")}/**/*`,{partial:true})),M.match(x))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(yd(r))return t=true,n.stop()}}),t}function yd(o){return isTypeScript(o)||hd(o)}function hd(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([Id,{onlyRemoveTypeImports:true}]),n=createConfigItem([xd,{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],x=u.find((M,q)=>q>g&&!["CommentLine","CommentBlock"].includes(M.type));if(x===void 0)continue;x.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=wd("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??!Pd.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 Je({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 Je({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),componentForm:new tt({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})},io:{input:this.getInput(),output:this.getOutput()}}),e)}addSlot(e){return this.execute(new Dt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new Je({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}removeSlot(e){return this.execute(new sn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),slotForm:new Je({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}addComponent(e){return this.execute(new 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 Je({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 Ze(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 Je({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:ss}),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 {packageManager:oe.transient(()=>({name:this.getPackageManager().getName()})),project:{features:oe.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{features:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),quotas:oe.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{quotas:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),organization:oe.transient(async()=>{let{organization:t}=await this.getConfigurationManager().load();return {slug:t,url:e(`organizations/${t}`)}}),workspace:oe.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load();return {slug:n,url:e(`organizations/${t}/workspaces/${n}`)}}),application:oe.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:oe.transient(async()=>{let t=this.getSdk(),n=await this.getConfigurationManager().load();return t.getPaths(n)}),platform:oe.transient(async()=>await this.getPlatformProvider().get()??"unknown"),server:oe.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 Ze(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 Ze(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 Ze(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 Ze(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 Ze(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 I:if(e.tracing.length>0){let t=e.tracing.map(({name:n,source:r},i)=>{let a=r!==void 0?` at ${o.getSourceLocation(r)}`:"";return `${" ".repeat(i+1)}\u21B3 \`${n}\`${a}`}).join(`
|
|
1843
1843
|
`);return new d(`${e.message}
|
|
1844
1844
|
|
|
1845
1845
|
\u25B6\uFE0F **Trace**
|
|
1846
|
-
${t}`,e.help)}break;case e instanceof 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 ls={version:"0.4.
|
|
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 ls={version:"0.4.4"};function Fc(o){let e=new fs().name("croct").description("Manage your Croct projects").enablePositionalOptions().option("--cwd <path>","The working directory.",h=>{try{return realpathSync(h)}catch{throw new Ge("The path does not exist.")}}).addOption(new pe("--api-key <key>","The API key to use for authentication.").env("CROCT_API_KEY").argParser(h=>{try{return ApiKey.parse(h)}catch{throw new Ge("The API key is malformed.")}})).option("--registry <url>","The template registry.",h=>{if(!URL.canParse(h))throw new Ge("Malformed URL.");return h}).option("--no-interaction","Disable interaction mode.").addOption(new pe("-s, --skip-prompts","Skip prompts with default options.").default(false)).addOption(new pe("-q, --quiet","Disable output messages.").default(false).implies({interaction:false})).option("--debug","Enable debug mode.").version(ls.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 pe("-u, --username <username>","The email."),r=new pe("-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 pe("--wor <workspace-slug>","The workspace slug."),a=new pe("--org <organization-slug>","The organization slug."),s=new pe("--dev-app <application-slug>","The development application slug."),p=new pe("--prod-app <application-slug>","The production application slug.");e.command("init").description("Configure the project.").option("-o, --override","Override any existing configuration.").addOption(new pe("-n, --new <resource>","The resources to create.").choices(["organization","org","workspace","wor","application","app"])).addOption(new pe("-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 ys("<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 pe("--permissions <permissions...>","The permissions of the API key.").argParser(h=>h.split(",").map(A=>{try{return Ee.fromValue(A)}catch{throw new Ge(`Unknown permission "${A}".`)}})),y=new pe("--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 x={},v=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])=>[x[B],Me]))});});for(let[h,A]of Object.entries(o.template??{})){let B=`--${h}${A.type!=="boolean"?" <value>":""}`,Me=new pe(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(H=>{let le=Number.parseFloat(H);if(Number.isNaN(le))throw new Ge("The value must be a number.");return le});break;case "array":Me.argParser(H=>{let le;try{le=JSON.parse(H);}catch{}if(le===void 0||!Array.isArray(le))throw new Ge("The value must be a JSON array.");return le});break;case "object":Me.argParser(H=>{let le;try{le=JSON.parse(H);}catch{throw new Ge("The JSON is malformed.")}if(typeof le!="object"||le===null)throw new Ge("The value must be a JSON object.")});break}x[Me.attributeName()]=h,v.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 Od(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 Td(o){return o.length>=2&&["enable","disable"].includes(o[0])&&o[1]==="deep-link"}async function us(o=process.argv,e=true){let t=Fc({interactive:true}).parse(o),n=t.opts(),r=va.fromDefaults({program:p=>us(t.args.slice(0,2).concat(p)),version:ls.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=Od(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:Td(t.args)}),await s.parseAsync(o);}us();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "croct",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.4",
|
|
4
4
|
"description": "A command-line interface (CLI) for managing projects using Croct.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Croct",
|
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
"@croct/content": "^1.0.0",
|
|
44
44
|
"@croct/content-model": "^0.19.4",
|
|
45
45
|
"@croct/json": "^2.1.0",
|
|
46
|
-
"@croct/json5-parser": "^0.1.
|
|
46
|
+
"@croct/json5-parser": "^0.1.1",
|
|
47
47
|
"@croct/logging": "^0.2.3",
|
|
48
48
|
"@croct/md-lite": "^0.3.1",
|
|
49
49
|
"@croct/sdk": "^0.18.0",
|