croct 0.8.1 → 0.8.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +133 -189
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -1,81 +1,25 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
import { createReadStream, realpathSync } from 'fs';
|
|
4
|
-
|
|
5
|
-
import { Token } from '@croct/sdk/token';
|
|
6
|
-
import { NoopCache, InMemoryCache, AutoSaveCache } from '@croct/cache';
|
|
7
|
-
import { homedir } from 'os';
|
|
8
|
-
import dg from 'xdg-app-paths';
|
|
9
|
-
import gg from 'ci-info';
|
|
10
|
-
import { LogLevel, FilteredLogger } from '@croct/logging';
|
|
11
|
-
import Vl from 'prompts';
|
|
12
|
-
import { Readable, PassThrough } from 'stream';
|
|
13
|
-
import ts from 'cli-cursor';
|
|
14
|
-
import ct from 'chalk';
|
|
15
|
-
import ns from 'node:readline';
|
|
16
|
-
import { WriteStream } from 'tty';
|
|
17
|
-
import Xl from 'strip-ansi';
|
|
18
|
-
import ql from 'is-unicode-supported';
|
|
19
|
-
import { render } from '@croct/md-lite/rendering.js';
|
|
20
|
-
import Kl from 'terminal-link';
|
|
21
|
-
import { unescape } from '@croct/md-lite/parsing.js';
|
|
22
|
-
import { strip } from 'node-emoji';
|
|
23
|
-
import { JsonParser, JsonObjectNode, JsonArrayNode } from '@croct/json5-parser/index.js';
|
|
24
|
-
import { JsonParser as JsonParser$1, JsonObjectNode as JsonObjectNode$1, JsonArrayNode as JsonArrayNode$1, JsonPrimitiveNode, JsonIdentifierNode, JsonTokenNode, JsonTokenType, JsonParseError, isIdentifier } from '@croct/json5-parser';
|
|
25
|
-
import * as f from '@babel/types';
|
|
26
|
-
import { traverseFast, noop, isTypeScript, isImportSpecifier, isImportDeclaration } from '@babel/types';
|
|
27
|
-
import { createConfigItem, transformFromAstAsync, traverse } from '@babel/core';
|
|
28
|
-
import { parse as parse$2 } from '@babel/parser';
|
|
29
|
-
import { createHash, randomUUID as randomUUID$1 } from 'crypto';
|
|
30
|
-
import * as kr from 'recast';
|
|
31
|
-
import { parse as parse$1 } from 'recast/parsers/babel-ts.js';
|
|
32
|
-
import { stringSimilarity } from 'string-similarity-js';
|
|
33
|
-
import { realpath, lstat, readdir, symlink, link, mkdir, writeFile, rm, rename, readFile, mkdtemp, cp as cp$1 } from 'fs/promises';
|
|
34
|
-
import { tmpdir } from 'node:os';
|
|
35
|
-
import { sep, basename, dirname, relative, isAbsolute, join, delimiter } from 'path';
|
|
36
|
-
import { Minimatch, minimatch } from 'minimatch';
|
|
37
|
-
import { deepEqual } from 'fast-equals';
|
|
38
|
-
import { z as z$1, ZodPromise, ZodOptional, ZodTuple, ZodArray, ZodRecord, ZodObject, ZodEffects, ZodAny, ZodPipeline, ZodUnion, ZodDiscriminatedUnion } from 'zod';
|
|
39
|
-
import Ge from 'jsep';
|
|
40
|
-
import Wu from '@jsep-plugin/object';
|
|
41
|
-
import Vu from '@jsep-plugin/spread';
|
|
42
|
-
import qu from '@jsep-plugin/regex';
|
|
43
|
-
import Lc from 'is-plain-obj';
|
|
44
|
-
import { randomUUID } from 'node:crypto';
|
|
45
|
-
import fd from 'semver';
|
|
46
|
-
import { spawn, spawnSync } from 'child_process';
|
|
47
|
-
import Id from 'ignore';
|
|
48
|
-
import Od from 'clipboardy';
|
|
49
|
-
import il from 'boxen';
|
|
50
|
-
import ze from 'node:process';
|
|
51
|
-
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
52
|
-
import { parse } from 'ini';
|
|
53
|
-
import eg from '@babel/plugin-transform-typescript';
|
|
54
|
-
import tg from '@babel/plugin-syntax-decorators';
|
|
55
|
-
import ng from 'open';
|
|
56
|
-
import ul from 'is-installed-globally';
|
|
2
|
+
import {createRequire}from'module';import {createReadStream,realpathSync}from'fs';import {ApiKey}from'@croct/sdk/apiKey';import {Token}from'@croct/sdk/token';import {NoopCache,InMemoryCache,AutoSaveCache}from'@croct/cache';import {homedir}from'os';import hg from'xdg-app-paths';import Sg from'ci-info';import {LogLevel,FilteredLogger}from'@croct/logging';import Kl from'prompts';import {Readable,PassThrough}from'stream';import is from'cli-cursor';import ct from'chalk';import os from'node:readline';import {WriteStream}from'tty';import nu from'strip-ansi';import Gl from'is-unicode-supported';import {render}from'@croct/md-lite/rendering.js';import Jl 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 {createConfigItem,transformFromAstAsync,traverse}from'@babel/core';import {parse as parse$2}from'@babel/parser';import {createHash,randomUUID as randomUUID$1}from'crypto';import*as Ar 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,rename,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 Ge from'jsep';import Hu from'@jsep-plugin/object';import Ku from'@jsep-plugin/spread';import Gu from'@jsep-plugin/regex';import Fc from'is-plain-obj';import {randomUUID}from'node:crypto';import Sd from'semver';import {spawn,spawnSync}from'child_process';import wd from'ignore';import Dd from'clipboardy';import sl from'boxen';import ze from'node:process';import {AsyncLocalStorage}from'node:async_hooks';import {parse}from'ini';import rg from'@babel/plugin-transform-typescript';import ig from'@babel/plugin-syntax-decorators';import og from'open';import gl from'is-installed-globally';const require = createRequire(import.meta.url);
|
|
3
|
+
var bl=Object.create;var Qa=Object.defineProperty;var Il=Object.getOwnPropertyDescriptor;var vl=Object.getOwnPropertyNames;var xl=Object.getPrototypeOf,wl=Object.prototype.hasOwnProperty;var Pl=(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 Pe=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),Cl=(o,e)=>{for(var t in e)Qa(o,t,{get:e[t],enumerable:true});},kl=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of vl(e))!wl.call(o,r)&&r!==t&&Qa(o,r,{get:()=>e[r],enumerable:!(n=Il(e,r))||n.enumerable});return o};var Pt=(o,e,t)=>(t=o!=null?bl(xl(o)):{},kl(Qa(t,"default",{value:o,enumerable:true}),o));var Ws=Pe((be,Us)=>{var Te=Pl("commander");be=Us.exports={};be.program=new Te.Command;be.Argument=Te.Argument;be.Command=Te.Command;be.CommanderError=Te.CommanderError;be.Help=Te.Help;be.InvalidArgumentError=Te.InvalidArgumentError;be.InvalidOptionArgumentError=Te.InvalidArgumentError;be.Option=Te.Option;be.createCommand=o=>new Te.Command(o);be.createOption=(o,e)=>new Te.Option(o,e);be.createArgument=(o,e)=>new Te.Argument(o,e);});var Ba=Pe(qn=>{Object.defineProperty(qn,"__esModule",{value:true});qn.TimeZone=void 0;var Xt=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()}};qn.TimeZone=Xt;Xt.UTC=new Xt("UTC");});var Xa=Pe(Hn=>{var Ya;Object.defineProperty(Hn,"__esModule",{value:true});Hn.SystemClock=void 0;var Al=tn(),El=Ba(),en=class{constructor(e){this.zone=e;}static of(e){return new this(e)}getZone(){return this.zone}getInstant(){return Al.Instant.ofEpochMilli(Date.now())}equals(e){return e===this||e instanceof Ya&&e.zone.equals(this.zone)}};Hn.SystemClock=en;Ya=en;en.UTC=new Ya(El.TimeZone.UTC);});var es=Pe(Kn=>{Object.defineProperty(Kn,"__esModule",{value:true});Kn.DefaultClockProvider=void 0;var Ol=Xa(),Ks;(function(o){let e=null;function t(){return e===null&&(e=Ol.SystemClock.UTC),e}o.getClock=t;function n(r){e=r;}o.setClock=n;})(Ks||(Kn.DefaultClockProvider=Ks={}));});var nn=Pe(ue=>{Object.defineProperty(ue,"__esModule",{value:true});ue.intDiv=ue.multiplyExact=ue.subtractExact=ue.addExact=ue.floorMod=ue.floorDiv=void 0;function Gs(o,e){let t=Math.trunc(o/e);return Math.sign(o)!==Math.sign(e)&&t*e!==o&&t--,t}ue.floorDiv=Gs;function Rl(o,e){return o-Gs(o,e)*e}ue.floorMod=Rl;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.addExact=Tl;function Dl(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=Dl;function Ml(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=Ml;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 Zn=Pe(Gn=>{Object.defineProperty(Gn,"__esModule",{value:true});Gn.LocalDate=void 0;var W=nn(),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()}};Gn.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 Qn=Pe(Jn=>{Object.defineProperty(Jn,"__esModule",{value:true});Jn.LocalTime=void 0;var _e=nn(),K=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, _e.intDiv)(n,o.SECONDS_PER_HOUR);n-=r*o.SECONDS_PER_HOUR;let i=(0, _e.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, _e.intDiv)(this.toNanoOfDay(),o.NANOS_PER_MILLI)}toMicroOfDay(){return (0, _e.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, _e.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, _e.intDiv)(r,o.SECONDS_PER_HOUR),a=(0, _e.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, _e.intDiv)(r,o.NANOS_PER_HOUR),a=(0, _e.intDiv)(r,o.NANOS_PER_MINUTE)%o.MINUTES_PER_HOUR,s=(0, _e.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()}};Jn.LocalTime=K;K.PATTERN=/^(?<hour>\d{2}):(?<minute>\d{2})(?::(?<second>\d{2})(?:.(?<fraction>\d{1,9}))?)?$/;K.HOURS_PER_DAY=24;K.MINUTES_PER_DAY=1440;K.MINUTES_PER_HOUR=60;K.SECONDS_PER_DAY=86400;K.SECONDS_PER_HOUR=3600;K.SECONDS_PER_MINUTE=60;K.MICROS_PER_DAY=864e8;K.MICROS_PER_SECOND=1e6;K.MILLIS_PER_DAY=864e5;K.MILLIS_PER_SECOND=1e3;K.NANOS_PER_DAY=864e11;K.NANOS_PER_HOUR=36e11;K.NANOS_PER_MINUTE=6e10;K.NANOS_PER_SECOND=1e9;K.NANOS_PER_MILLI=1e6;K.NANOS_PER_MICRO=1e3;});var ns=Pe(Yn=>{Object.defineProperty(Yn,"__esModule",{value:true});Yn.LocalDateTime=void 0;var Zs=es(),$l=tn(),Bn=Zn(),E=Qn(),G=nn(),ts=class o{constructor(e,t){this.date=e,this.time=t;}static nowIn(e,t=Zs.DefaultClockProvider.getClock()){return o.ofInstant(t.getInstant(),e)}static now(e=Zs.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(Bn.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, G.floorDiv)(e,E.LocalTime.SECONDS_PER_DAY),r=(0, G.floorMod)(e,E.LocalTime.SECONDS_PER_DAY),i=Bn.LocalDate.ofEpochDay(n),a=E.LocalTime.ofSecondOfDay(r,t);return o.of(i,a)}static fromNative(e){return o.of(Bn.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(Bn.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, G.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, G.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, G.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, G.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, G.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, G.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, G.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, G.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, G.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, G.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, G.intDiv)(e,E.LocalTime.NANOS_PER_DAY),n=e%E.LocalTime.NANOS_PER_DAY,r=n+this.time.toNanoOfDay(),i=t+(0, G.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, G.multiplyExact)(t,E.LocalTime.SECONDS_PER_DAY),r=(0, G.subtractExact)((0, G.addExact)(n,this.time.toSecondOfDay()),14*E.LocalTime.SECONDS_PER_HOUR),i=(0, G.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, G.addExact)(s.getTime(),c*E.LocalTime.MILLIS_PER_SECOND)),p=o.fromZonedDate(s,e),!p.isAfter(a)););let l=(0, G.intDiv)(s.getTime(),E.LocalTime.MILLIS_PER_SECOND),u=this.time.getNano();return $l.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()}};Yn.LocalDateTime=ts;});var tn=Pe(Xn=>{Object.defineProperty(Xn,"__esModule",{value:true});Xn.Instant=void 0;var Ll=es(),zl=Zn(),_l=ns(),j=Qn(),_=nn(),de=class o{constructor(e,t){this.nanos=0,this.seconds=e,this.nanos=t;}static now(e=Ll.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, _.floorDiv)(e,j.LocalTime.MILLIS_PER_SECOND),r=(0, _.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, _.addExact)(n,(0, _.floorDiv)(t,j.LocalTime.NANOS_PER_SECOND)),r=(0, _.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=zl.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, _.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, _.multiplyExact)(this.seconds+1,j.LocalTime.MILLIS_PER_SECOND),r=(0, _.intDiv)(this.nanos,j.LocalTime.NANOS_PER_MILLI)-j.LocalTime.MILLIS_PER_SECOND;return (0, _.addExact)(n,r)}let e=(0, _.multiplyExact)(this.seconds,j.LocalTime.MILLIS_PER_SECOND),t=(0, _.intDiv)(this.nanos,j.LocalTime.NANOS_PER_MILLI);return (0, _.addExact)(e,t)}toDate(){return new Date(this.toEpochMillis())}toString(){let e=this.seconds%12622780800,t=_l.LocalDateTime.ofEpochSecond(e,this.nanos),n=t.getYear()+(0, _.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, _.multiplyExact)(e,j.LocalTime.SECONDS_PER_DAY);return this.plusSeconds(t)}minusDays(e){if(e===0)return this;let t=(0, _.multiplyExact)(e,j.LocalTime.SECONDS_PER_DAY);return this.minusSeconds(t)}plusHours(e){if(e===0)return this;let t=(0, _.multiplyExact)(e,j.LocalTime.SECONDS_PER_HOUR);return this.plusSeconds(t)}minusHours(e){if(e===0)return this;let t=(0, _.multiplyExact)(e,j.LocalTime.SECONDS_PER_HOUR);return this.minusSeconds(t)}plusMinutes(e){if(e===0)return this;let t=(0, _.multiplyExact)(e,j.LocalTime.SECONDS_PER_MINUTE);return this.plusSeconds(t)}minusMinutes(e){if(e===0)return this;let t=(0, _.multiplyExact)(e,j.LocalTime.SECONDS_PER_MINUTE);return this.minusSeconds(t)}plusSeconds(e){return e===0?this:o.ofEpochSecond((0, _.addExact)(this.seconds,e),this.nanos)}minusSeconds(e){return e===0?this:o.ofEpochSecond((0, _.subtractExact)(this.seconds,e),this.nanos)}plusMillis(e){if(e===0)return this;let t=(0, _.intDiv)(e,j.LocalTime.MILLIS_PER_SECOND),n=(0, _.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, _.intDiv)(e,j.LocalTime.MICROS_PER_SECOND),n=(0, _.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, _.intDiv)(e,j.LocalTime.NANOS_PER_SECOND),n=(0, _.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}};Xn.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 Qs=Pe(er=>{Object.defineProperty(er,"__esModule",{value:true});er.Weekday=void 0;var Js;(function(o){o.SUNDAY="SUNDAY",o.MONDAY="MONDAY",o.TUESDAY="TUESDAY",o.WEDNESDAY="WEDNESDAY",o.THURSDAY="THURSDAY",o.FRIDAY="FRIDAY",o.SATURDAY="SATURDAY";})(Js||(er.Weekday=Js={}));});var Bs=Pe(tr=>{Object.defineProperty(tr,"__esModule",{value:true});tr.TimeInterval=void 0;var Ct=tn(),rs=class o{constructor(e,t){this.start=e,this.end=t;}static all(){return new o(Ct.Instant.MIN,Ct.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(Ct.Instant.parse(t[0]),Ct.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(Ct.Instant.MIN)}isUnboundedEnd(){return this.end.equals(Ct.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()}};tr.TimeInterval=rs;});var rn=Pe(ne=>{Object.defineProperty(ne,"__esModule",{value:true});ne.TimeInterval=ne.TimeZone=ne.LocalDateTime=ne.LocalTime=ne.LocalDate=ne.Weekday=ne.Instant=void 0;var Fl=tn();Object.defineProperty(ne,"Instant",{enumerable:true,get:function(){return Fl.Instant}});var jl=Qs();Object.defineProperty(ne,"Weekday",{enumerable:true,get:function(){return jl.Weekday}});var Ul=Zn();Object.defineProperty(ne,"LocalDate",{enumerable:true,get:function(){return Ul.LocalDate}});var Wl=Qn();Object.defineProperty(ne,"LocalTime",{enumerable:true,get:function(){return Wl.LocalTime}});var Vl=ns();Object.defineProperty(ne,"LocalDateTime",{enumerable:true,get:function(){return Vl.LocalDateTime}});var ql=Ba();Object.defineProperty(ne,"TimeZone",{enumerable:true,get:function(){return ql.TimeZone}});var Hl=Bs();Object.defineProperty(ne,"TimeInterval",{enumerable:true,get:function(){return Hl.TimeInterval}});});var Vs=Pt(Ws()),{program:Eg,createCommand:Og,createArgument:Rg,createOption:Tg,CommanderError:Dg,InvalidArgumentError:Mg,InvalidOptionArgumentError:De,Command:qs,Argument:Hs,Option:X,Help:Ng}=Vs.default;var Xe=Pt(rn()),yl=Pt(Xa());var nr=class{constructor(e){this.configuration=e;}prompt(e){return this.interact({type:e.type==="password"?"invisible":"text",message:e.message,initial:e.default??e.initial,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,a={name:"value",...e,stdin:this.configuration.input,stdout:this.configuration.output,onState:function(p){e.onState?.apply(this,[p]),p.aborted&&(n.write("\x1B[?25h"),n.write(`
|
|
4
|
+
`),i=r());}};try{return await Kl(a,t).then(s=>s.value??i)}finally{this.configuration.onInteractionEnd?.();}}};var et=Gl(),on={neutral:"cyan",info:"blue",error:"red",warning:"yellow",success:"green",secondary:"grey"},Yl={neutral:et?"\u279C":">",info:et?"\u2139":"i",error:et?"\u2718":"\xD7",warning:et?"\u26A0":"\u203C",success:et?"\u2714":"\u221A",secondary:et?"\u21B3":"\u203A"};function re(o,e={}){let t=e.basic===true?o:Xl(o);if(et||(t=strip(t)),e.text!==void 0&&(t=ct[on[e.text]](t)),e.icon!==void 0){let{semantics:n,symbol:r}=e.icon;t=r!==void 0?`${ct[on[n]](r[et?"unicode":"ascii"])} ${t}`:`${ct[on[n]](Yl[n])} ${t}`;}return t}function Xl(o){return render(o,{fragment:e=>e.children.join(""),text:e=>e.content,bold:e=>ct.bold(e.children),italic:e=>ct.italic(e.children),strike:e=>ct.strikethrough(e.children),code:e=>ct.cyan(e.content),link:e=>Jl(e.children,e.href,{fallback:(t,n)=>t.includes(n)?t:`${t} (${n})`}),image:e=>unescape(e.source),paragraph:e=>`${e.children.join("")}
|
|
57
5
|
|
|
58
|
-
|
|
59
|
-
var yl=Object.create;var Ga=Object.defineProperty;var hl=Object.getOwnPropertyDescriptor;var Sl=Object.getOwnPropertyNames;var bl=Object.getPrototypeOf,Il=Object.prototype.hasOwnProperty;var vl=(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 we=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),xl=(o,e)=>{for(var t in e)Ga(o,t,{get:e[t],enumerable:true});},wl=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Sl(e))!Il.call(o,r)&&r!==t&&Ga(o,r,{get:()=>e[r],enumerable:!(n=hl(e,r))||n.enumerable});return o};var Pt=(o,e,t)=>(t=o!=null?yl(bl(o)):{},wl(Ga(t,"default",{value:o,enumerable:true}),o));var Fs=we((Se,_s)=>{var Re=vl("commander");Se=_s.exports={};Se.program=new Re.Command;Se.Argument=Re.Argument;Se.Command=Re.Command;Se.CommanderError=Re.CommanderError;Se.Help=Re.Help;Se.InvalidArgumentError=Re.InvalidArgumentError;Se.InvalidOptionArgumentError=Re.InvalidArgumentError;Se.Option=Re.Option;Se.createCommand=o=>new Re.Command(o);Se.createOption=(o,e)=>new Re.Option(o,e);Se.createArgument=(o,e)=>new Re.Argument(o,e);});var Za=we(Vn=>{Object.defineProperty(Vn,"__esModule",{value:true});Vn.TimeZone=void 0;var Yt=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()}};Vn.TimeZone=Yt;Yt.UTC=new Yt("UTC");});var Qa=we(qn=>{var Ja;Object.defineProperty(qn,"__esModule",{value:true});qn.SystemClock=void 0;var Pl=en(),Cl=Za(),Xt=class{constructor(e){this.zone=e;}static of(e){return new this(e)}getZone(){return this.zone}getInstant(){return Pl.Instant.ofEpochMilli(Date.now())}equals(e){return e===this||e instanceof Ja&&e.zone.equals(this.zone)}};qn.SystemClock=Xt;Ja=Xt;Xt.UTC=new Ja(Cl.TimeZone.UTC);});var Ba=we(Hn=>{Object.defineProperty(Hn,"__esModule",{value:true});Hn.DefaultClockProvider=void 0;var kl=Qa(),Vs;(function(o){let e=null;function t(){return e===null&&(e=kl.SystemClock.UTC),e}o.getClock=t;function n(r){e=r;}o.setClock=n;})(Vs||(Hn.DefaultClockProvider=Vs={}));});var tn=we(ue=>{Object.defineProperty(ue,"__esModule",{value:true});ue.intDiv=ue.multiplyExact=ue.subtractExact=ue.addExact=ue.floorMod=ue.floorDiv=void 0;function qs(o,e){let t=Math.trunc(o/e);return Math.sign(o)!==Math.sign(e)&&t*e!==o&&t--,t}ue.floorDiv=qs;function Al(o,e){return o-qs(o,e)*e}ue.floorMod=Al;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.addExact=El;function Ol(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=Ol;function Rl(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=Rl;function Tl(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=Tl;});var Gn=we(Kn=>{Object.defineProperty(Kn,"__esModule",{value:true});Kn.LocalDate=void 0;var W=tn(),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()}};Kn.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 Jn=we(Zn=>{Object.defineProperty(Zn,"__esModule",{value:true});Zn.LocalTime=void 0;var _e=tn(),K=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, _e.intDiv)(n,o.SECONDS_PER_HOUR);n-=r*o.SECONDS_PER_HOUR;let i=(0, _e.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, _e.intDiv)(this.toNanoOfDay(),o.NANOS_PER_MILLI)}toMicroOfDay(){return (0, _e.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, _e.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, _e.intDiv)(r,o.SECONDS_PER_HOUR),a=(0, _e.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, _e.intDiv)(r,o.NANOS_PER_HOUR),a=(0, _e.intDiv)(r,o.NANOS_PER_MINUTE)%o.MINUTES_PER_HOUR,s=(0, _e.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()}};Zn.LocalTime=K;K.PATTERN=/^(?<hour>\d{2}):(?<minute>\d{2})(?::(?<second>\d{2})(?:.(?<fraction>\d{1,9}))?)?$/;K.HOURS_PER_DAY=24;K.MINUTES_PER_DAY=1440;K.MINUTES_PER_HOUR=60;K.SECONDS_PER_DAY=86400;K.SECONDS_PER_HOUR=3600;K.SECONDS_PER_MINUTE=60;K.MICROS_PER_DAY=864e8;K.MICROS_PER_SECOND=1e6;K.MILLIS_PER_DAY=864e5;K.MILLIS_PER_SECOND=1e3;K.NANOS_PER_DAY=864e11;K.NANOS_PER_HOUR=36e11;K.NANOS_PER_MINUTE=6e10;K.NANOS_PER_SECOND=1e9;K.NANOS_PER_MILLI=1e6;K.NANOS_PER_MICRO=1e3;});var Xa=we(Bn=>{Object.defineProperty(Bn,"__esModule",{value:true});Bn.LocalDateTime=void 0;var Hs=Ba(),Dl=en(),Qn=Gn(),E=Jn(),G=tn(),Ya=class o{constructor(e,t){this.date=e,this.time=t;}static nowIn(e,t=Hs.DefaultClockProvider.getClock()){return o.ofInstant(t.getInstant(),e)}static now(e=Hs.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(Qn.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, G.floorDiv)(e,E.LocalTime.SECONDS_PER_DAY),r=(0, G.floorMod)(e,E.LocalTime.SECONDS_PER_DAY),i=Qn.LocalDate.ofEpochDay(n),a=E.LocalTime.ofSecondOfDay(r,t);return o.of(i,a)}static fromNative(e){return o.of(Qn.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(Qn.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, G.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, G.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, G.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, G.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, G.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, G.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, G.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, G.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, G.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, G.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, G.intDiv)(e,E.LocalTime.NANOS_PER_DAY),n=e%E.LocalTime.NANOS_PER_DAY,r=n+this.time.toNanoOfDay(),i=t+(0, G.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, G.multiplyExact)(t,E.LocalTime.SECONDS_PER_DAY),r=(0, G.subtractExact)((0, G.addExact)(n,this.time.toSecondOfDay()),14*E.LocalTime.SECONDS_PER_HOUR),i=(0, G.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, G.addExact)(s.getTime(),c*E.LocalTime.MILLIS_PER_SECOND)),p=o.fromZonedDate(s,e),!p.isAfter(a)););let l=(0, G.intDiv)(s.getTime(),E.LocalTime.MILLIS_PER_SECOND),u=this.time.getNano();return Dl.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()}};Bn.LocalDateTime=Ya;});var en=we(Yn=>{Object.defineProperty(Yn,"__esModule",{value:true});Yn.Instant=void 0;var Ml=Ba(),Nl=Gn(),$l=Xa(),j=Jn(),_=tn(),de=class o{constructor(e,t){this.nanos=0,this.seconds=e,this.nanos=t;}static now(e=Ml.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, _.floorDiv)(e,j.LocalTime.MILLIS_PER_SECOND),r=(0, _.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, _.addExact)(n,(0, _.floorDiv)(t,j.LocalTime.NANOS_PER_SECOND)),r=(0, _.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=Nl.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, _.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, _.multiplyExact)(this.seconds+1,j.LocalTime.MILLIS_PER_SECOND),r=(0, _.intDiv)(this.nanos,j.LocalTime.NANOS_PER_MILLI)-j.LocalTime.MILLIS_PER_SECOND;return (0, _.addExact)(n,r)}let e=(0, _.multiplyExact)(this.seconds,j.LocalTime.MILLIS_PER_SECOND),t=(0, _.intDiv)(this.nanos,j.LocalTime.NANOS_PER_MILLI);return (0, _.addExact)(e,t)}toDate(){return new Date(this.toEpochMillis())}toString(){let e=this.seconds%12622780800,t=$l.LocalDateTime.ofEpochSecond(e,this.nanos),n=t.getYear()+(0, _.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, _.multiplyExact)(e,j.LocalTime.SECONDS_PER_DAY);return this.plusSeconds(t)}minusDays(e){if(e===0)return this;let t=(0, _.multiplyExact)(e,j.LocalTime.SECONDS_PER_DAY);return this.minusSeconds(t)}plusHours(e){if(e===0)return this;let t=(0, _.multiplyExact)(e,j.LocalTime.SECONDS_PER_HOUR);return this.plusSeconds(t)}minusHours(e){if(e===0)return this;let t=(0, _.multiplyExact)(e,j.LocalTime.SECONDS_PER_HOUR);return this.minusSeconds(t)}plusMinutes(e){if(e===0)return this;let t=(0, _.multiplyExact)(e,j.LocalTime.SECONDS_PER_MINUTE);return this.plusSeconds(t)}minusMinutes(e){if(e===0)return this;let t=(0, _.multiplyExact)(e,j.LocalTime.SECONDS_PER_MINUTE);return this.minusSeconds(t)}plusSeconds(e){return e===0?this:o.ofEpochSecond((0, _.addExact)(this.seconds,e),this.nanos)}minusSeconds(e){return e===0?this:o.ofEpochSecond((0, _.subtractExact)(this.seconds,e),this.nanos)}plusMillis(e){if(e===0)return this;let t=(0, _.intDiv)(e,j.LocalTime.MILLIS_PER_SECOND),n=(0, _.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, _.intDiv)(e,j.LocalTime.MICROS_PER_SECOND),n=(0, _.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, _.intDiv)(e,j.LocalTime.NANOS_PER_SECOND),n=(0, _.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}};Yn.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 Gs=we(Xn=>{Object.defineProperty(Xn,"__esModule",{value:true});Xn.Weekday=void 0;var Ks;(function(o){o.SUNDAY="SUNDAY",o.MONDAY="MONDAY",o.TUESDAY="TUESDAY",o.WEDNESDAY="WEDNESDAY",o.THURSDAY="THURSDAY",o.FRIDAY="FRIDAY",o.SATURDAY="SATURDAY";})(Ks||(Xn.Weekday=Ks={}));});var Zs=we(er=>{Object.defineProperty(er,"__esModule",{value:true});er.TimeInterval=void 0;var Ct=en(),es=class o{constructor(e,t){this.start=e,this.end=t;}static all(){return new o(Ct.Instant.MIN,Ct.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(Ct.Instant.parse(t[0]),Ct.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(Ct.Instant.MIN)}isUnboundedEnd(){return this.end.equals(Ct.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()}};er.TimeInterval=es;});var nn=we(te=>{Object.defineProperty(te,"__esModule",{value:true});te.TimeInterval=te.TimeZone=te.LocalDateTime=te.LocalTime=te.LocalDate=te.Weekday=te.Instant=void 0;var Ll=en();Object.defineProperty(te,"Instant",{enumerable:true,get:function(){return Ll.Instant}});var zl=Gs();Object.defineProperty(te,"Weekday",{enumerable:true,get:function(){return zl.Weekday}});var _l=Gn();Object.defineProperty(te,"LocalDate",{enumerable:true,get:function(){return _l.LocalDate}});var Fl=Jn();Object.defineProperty(te,"LocalTime",{enumerable:true,get:function(){return Fl.LocalTime}});var jl=Xa();Object.defineProperty(te,"LocalDateTime",{enumerable:true,get:function(){return jl.LocalDateTime}});var Ul=Za();Object.defineProperty(te,"TimeZone",{enumerable:true,get:function(){return Ul.TimeZone}});var Wl=Zs();Object.defineProperty(te,"TimeInterval",{enumerable:true,get:function(){return Wl.TimeInterval}});});var js=Pt(Fs()),{program:Pg,createCommand:Cg,createArgument:kg,createOption:Ag,CommanderError:Eg,InvalidArgumentError:Og,InvalidOptionArgumentError:Te,Command:Us,Argument:Ws,Option:X,Help:Rg}=js.default;var Xe=Pt(nn()),dl=Pt(Qa());var tr=class{constructor(e){this.configuration=e;}prompt(e){return this.interact({type:e.type==="password"?"invisible":"text",message:e.message,initial:e.default??e.initial,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,a={name:"value",...e,stdin:this.configuration.input,stdout:this.configuration.output,onState:function(p){e.onState?.apply(this,[p]),p.aborted&&(n.write("\x1B[?25h"),n.write(`
|
|
60
|
-
`)
|
|
61
|
-
|
|
62
|
-
`
|
|
63
|
-
`).
|
|
64
|
-
`);}e&&this.lineCount>r?this.clear():ns.moveCursor(this.output,0,-this.lineCount);for(let i of n)this.output.write(i);this.lineCount=r;}formatTask(e){let t=o.getSemantics(e.status),n=e.status==="loading"?`${Js[this.frame%Js.length]} ${ne(e.title)}`:ne(e.title,{icon:{semantics:t,symbol:e.status==="pending"?{unicode:"\u25F7",ascii:"\u25A0"}:void 0}});return e.subtitle!==void 0&&(n+=`
|
|
65
|
-
${ne(e.subtitle,{text:"secondary",icon:{semantics:"secondary"}})}`),n}static getSemantics(e){return e==="loading"||e==="pending"?"neutral":e}},nr=class{constructor(e){this.watchers=[];this.output=e;}suspend(){for(let e of this.watchers)e.suspend();}stop(e){for(let t of this.watchers)t.stop(e);}resume(){this.watchers[this.watchers.length-1]?.start();}notify(e){let t=this.addWatcher({tasks:[{title:e,task:()=>Promise.resolve()}]},{manual:true,status:"loading"});return t.start(),{stop:(n=false)=>{t.stop(n);},update:(n,r)=>{t.setStatus(0,{status:"loading",title:n,subtitle:r});},confirm:(n,r)=>{t.setStatus(0,{status:"success",title:n,subtitle:r}),t.stop(true);},alert:(n,r)=>{t.setStatus(0,{status:"error",title:n,subtitle:r}),t.stop(true);},warn:(n,r)=>{t.setStatus(0,{status:"warning",title:n,subtitle:r}),t.stop(true);}}}monitor(e){let t=this.addWatcher(e),n=t.start();return {wait:()=>n,stop:()=>t.stop()}}addWatcher(e,t={}){for(let r of this.watchers)r.suspend();let n=new rs(e.tasks,this.output,{clear:e.clear,concurrent:e.concurrent,...t,onStop:r=>this.removeWatcher(r)});return this.watchers.push(n),n}removeWatcher(e){let t=this.watchers.indexOf(e),n=t===this.watchers.length-1;this.watchers.splice(t,1),n&&this.resume();}};var rr=class{constructor(e){this.notifiers=[];this.stopped=false;this.output=e;}suspend(){this.stop();}stop(){this.notifiers.forEach(e=>{e.stopped=true;});}resume(){this.notifiers.forEach(e=>{e.stopped=false;});}monitor(e){let t=e.tasks.map(r=>this.notify(r.title,e.clear)),n=e.concurrent===true?Promise.all(e.tasks.map((r,i)=>r.task(t[i]))):e.tasks.reduce((r,i,a)=>r.then(()=>i.task(t[a])),Promise.resolve());return {stop:()=>{t.forEach(r=>r.stop(false));},wait:()=>n.then(()=>{})}}notify(e,t=false){let n=(i,a,s,p=!t)=>{!this.stopped&&!r.stopped&&p&&this.log(i??r.lastStatus,a??r.latestDetails,s);let c=this.notifiers.indexOf(r);c!==-1&&this.notifiers.splice(c,1);},r={stopped:false,lastStatus:e,latestDetails:void 0,stop:(i=false)=>{n(r.lastStatus,r.latestDetails,"neutral",i);},update:(i,a)=>{r.lastStatus=i??r.lastStatus,r.latestDetails=a;},confirm:(i,a)=>{n(i,a,"success");},alert:(i,a)=>{n(i,a,"error");},warn:(i,a)=>{n(i,a,"warning");}};return this.notifiers.push(r),r}log(e,t,n){this.output.write(`${this.format(e,t,n)}
|
|
66
|
-
`);}format(e,t,n="neutral"){let r=ne(e,{icon:{semantics:n}});return t!==void 0&&(r+=`
|
|
67
|
-
${ne(t,{text:n,icon:{semantics:n,symbol:{unicode:"\u21B3",ascii:"\u203A"}}})}`),r}};var on=class{constructor(e){this.output=e.output,this.onExit=e.onExit,this.quiet=e.quiet??false,this.formatter=e.formatter,this.linkOpener=e.linkOpener,this.taskMonitor=(e.interactive??true)&&!this.quiet?new nr(this.output):new rr(this.quiet?new PassThrough:this.output);}suspend(){this.taskMonitor.suspend();}resume(){this.taskMonitor.resume();}stop(){this.taskMonitor.stop(false);}async open(e){await this.linkOpener.open(e);}break(){this.write(`
|
|
6
|
+
`}).trim()}var Ys=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"].map(o=>ct.cyan(o)),as=class o{constructor(e,t,n={}){this.tasks=[];this.interval=null;this.promise=null;this.active=false;this.frame=0;this.lineCount=0;this.output=t,this.options=n,this.tasks=e.map(r=>({title:r.title,subtitle:r.subtitle,status:n.status??"pending",task:r.task}));}suspend(){this.active&&(this.stopRendering(true),is.show());}stop(e){this.active&&(this.active=false,this.stopRendering(e!==void 0?!e:this.options.clear===true),is.show(),this.options.onStop?.(this));}start(){return this.promise!==null&&!this.active?this.promise:(this.promise===null&&(this.active=true,this.promise=this.execute()),this.active&&(is.hide(),this.resumeRendering()),this.promise)}async execute(){try{await(this.options.concurrent===!0?Promise.all(this.tasks.map(e=>this.startTask(e))):this.tasks.reduce((e,t)=>e.then(()=>this.startTask(t)),Promise.resolve())),this.options.manual!==!0&&this.stop();}catch(e){throw this.stop(),e}}startTask(e){return this.updateTask(e,{status:"loading"}),e.task({confirm:(t,n)=>this.updateTask(e,{status:"success",title:t,subtitle:n}),alert:(t,n)=>this.updateTask(e,{status:"error",title:t,subtitle:n}),warn:(t,n)=>this.updateTask(e,{status:"warning",title:t,subtitle:n}),update:(t,n)=>this.updateTask(e,{status:"loading",title:t,subtitle:n})})}setStatus(e,t){if(!this.active)throw new Error("Cannot update task status once the task is finished");this.updateTask(this.tasks[e],t);}updateTask(e,t){e.status=t.status,t.title!==void 0&&(e.title=t.title),e.subtitle=t.subtitle;}stopRendering(e){this.interval!==null&&(clearInterval(this.interval),this.interval=null,this.clear(),e||this.render());}resumeRendering(){this.render(),this.interval=setInterval(()=>{this.frame++,this.render(true);},80),this.interval.unref();}clear(){for(let e=0;e<this.lineCount;e++)os.moveCursor(this.output,0,-1),os.clearLine(this.output,0);this.lineCount=0;}render(e=false){let t=this.output instanceof WriteStream?this.output.columns:0,n=[],r=0;for(let i of this.tasks){let a=this.formatTask(i);r=a.split(`
|
|
7
|
+
`).map(p=>t===0?1:Math.ceil([...nu(p)].length/t)).reduce((p,c)=>p+c,r),n.push(`${a}${e?"\x1B[0K":""}
|
|
8
|
+
`);}e&&this.lineCount>r?this.clear():os.moveCursor(this.output,0,-this.lineCount);for(let i of n)this.output.write(i);this.lineCount=r;}formatTask(e){let t=o.getSemantics(e.status),n=e.status==="loading"?`${Ys[this.frame%Ys.length]} ${re(e.title)}`:re(e.title,{icon:{semantics:t,symbol:e.status==="pending"?{unicode:"\u25F7",ascii:"\u25A0"}:void 0}});return e.subtitle!==void 0&&(n+=`
|
|
9
|
+
${re(e.subtitle,{text:"secondary",icon:{semantics:"secondary"}})}`),n}static getSemantics(e){return e==="loading"||e==="pending"?"neutral":e}},rr=class{constructor(e){this.watchers=[];this.output=e;}suspend(){for(let e of this.watchers)e.suspend();}stop(e){for(let t of this.watchers)t.stop(e);}resume(){this.watchers[this.watchers.length-1]?.start();}notify(e){let t=this.addWatcher({tasks:[{title:e,task:()=>Promise.resolve()}]},{manual:true,status:"loading"});return t.start(),{stop:(n=false)=>{t.stop(n);},update:(n,r)=>{t.setStatus(0,{status:"loading",title:n,subtitle:r});},confirm:(n,r)=>{t.setStatus(0,{status:"success",title:n,subtitle:r}),t.stop(true);},alert:(n,r)=>{t.setStatus(0,{status:"error",title:n,subtitle:r}),t.stop(true);},warn:(n,r)=>{t.setStatus(0,{status:"warning",title:n,subtitle:r}),t.stop(true);}}}monitor(e){let t=this.addWatcher(e),n=t.start();return {wait:()=>n,stop:()=>t.stop()}}addWatcher(e,t={}){for(let r of this.watchers)r.suspend();let n=new as(e.tasks,this.output,{clear:e.clear,concurrent:e.concurrent,...t,onStop:r=>this.removeWatcher(r)});return this.watchers.push(n),n}removeWatcher(e){let t=this.watchers.indexOf(e),n=t===this.watchers.length-1;this.watchers.splice(t,1),n&&this.resume();}};var ir=class{constructor(e){this.notifiers=[];this.stopped=false;this.output=e;}suspend(){this.stop();}stop(){this.notifiers.forEach(e=>{e.stopped=true;});}resume(){this.notifiers.forEach(e=>{e.stopped=false;});}monitor(e){let t=e.tasks.map(r=>this.notify(r.title,e.clear)),n=e.concurrent===true?Promise.all(e.tasks.map((r,i)=>r.task(t[i]))):e.tasks.reduce((r,i,a)=>r.then(()=>i.task(t[a])),Promise.resolve());return {stop:()=>{t.forEach(r=>r.stop(false));},wait:()=>n.then(()=>{})}}notify(e,t=false){let n=(i,a,s,p=!t)=>{!this.stopped&&!r.stopped&&p&&this.log(i??r.lastStatus,a??r.latestDetails,s);let c=this.notifiers.indexOf(r);c!==-1&&this.notifiers.splice(c,1);},r={stopped:false,lastStatus:e,latestDetails:void 0,stop:(i=false)=>{n(r.lastStatus,r.latestDetails,"neutral",i);},update:(i,a)=>{r.lastStatus=i??r.lastStatus,r.latestDetails=a;},confirm:(i,a)=>{n(i,a,"success");},alert:(i,a)=>{n(i,a,"error");},warn:(i,a)=>{n(i,a,"warning");}};return this.notifiers.push(r),r}log(e,t,n){this.output.write(`${this.format(e,t,n)}
|
|
10
|
+
`);}format(e,t,n="neutral"){let r=re(e,{icon:{semantics:n}});return t!==void 0&&(r+=`
|
|
11
|
+
${re(t,{text:n,icon:{semantics:n,symbol:{unicode:"\u21B3",ascii:"\u203A"}}})}`),r}};var an=class{constructor(e){this.output=e.output,this.onExit=e.onExit,this.quiet=e.quiet??false,this.formatter=e.formatter,this.linkOpener=e.linkOpener,this.taskMonitor=(e.interactive??true)&&!this.quiet?new rr(this.output):new ir(this.quiet?new PassThrough:this.output);}suspend(){this.taskMonitor.suspend();}resume(){this.taskMonitor.resume();}stop(){this.taskMonitor.stop(false);}async open(e){await this.linkOpener.open(e);}break(){this.write(`
|
|
68
12
|
`);}announce(e){this.write(`${this.formatter.formatCallout(e)}
|
|
69
13
|
`);}log(e,t){this.writeLog(e,t??"neutral");}confirm(e){this.writeLog(e,"success");}inform(e){this.writeLog(e,"info");}warn(e){this.writeLog(e,"warning");}alert(e){this.writeLog(e,"error");}debug(e){this.writeLog(e,"neutral");}notify(e){return this.taskMonitor.notify(e)}monitor(e){return typeof e=="function"?new Promise((t,n)=>{let r=this.taskMonitor.monitor(e(t,i=>{r.stop(),n(i);}));}):this.taskMonitor.monitor(e).wait()}report(e){this.stop(),this.write(`${this.formatter.formatError(e)}
|
|
70
|
-
`,true);}exit(){return this.stop(),this.onExit()}writeLog(e,t){this.write(`${
|
|
71
|
-
`);}write(e,t=false){(!this.quiet||t)&&(this.suspend(),this.output.write(e),this.resume());}};var d=class o extends Error{constructor(e,t={}){super(e),this.help=t,this.reason=t.reason??"other",Object.setPrototypeOf(this,o.prototype);}static formatMessage(e){let t=o.extractMessage(e).trim();return t.length===0?t:t.charAt(0).toUpperCase()+t.slice(1)+(/^[^\n.]+$/.test(t)?".":"")}static formatCause(e){let t=o.formatMessage(e);return t.length===0?t:t.charAt(0).toLowerCase()+t.slice(1)}static extractMessage(e){return e instanceof Error?e.message:typeof e=="string"&&e!==""?e:"unknown error"}static describeType(e){switch(true){case e===null:return "null";case typeof e=="object":return e.constructor.name!=="Object"?e.constructor.name:"object";default:return typeof e}}};var
|
|
14
|
+
`,true);}exit(){return this.stop(),this.onExit()}writeLog(e,t){this.write(`${re(e,t==="neutral"?{}:{icon:{semantics:t}})}
|
|
15
|
+
`);}write(e,t=false){(!this.quiet||t)&&(this.suspend(),this.output.write(e),this.resume());}};var d=class o extends Error{constructor(e,t={}){super(e),this.help=t,this.reason=t.reason??"other",Object.setPrototypeOf(this,o.prototype);}static formatMessage(e){let t=o.extractMessage(e).trim();return t.length===0?t:t.charAt(0).toUpperCase()+t.slice(1)+(/^[^\n.]+$/.test(t)?".":"")}static formatCause(e){let t=o.formatMessage(e);return t.length===0?t:t.charAt(0).toLowerCase()+t.slice(1)}static extractMessage(e){return e instanceof Error?e.message:typeof e=="string"&&e!==""?e:"unknown error"}static describeType(e){switch(true){case e===null:return "null";case typeof e=="object":return e.constructor.name!=="Object"?e.constructor.name:"object";default:return typeof e}}};var ie=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var M=class o{constructor(e,t,n){this.min=t,this.max=n,this.versions=e??[];}static isValid(e){try{return o.parse(e),!0}catch{return false}}static between(e,t){if(e===t)return new o([e]);if(e>t)throw new Error(`Out of order range ${e}-${t}`);return new o(void 0,e,t)}static of(e){return new o([e])}static either(...e){if(e.length===0)throw new Error("No versions specified.");return new o([...new Set(e)].sort((t,n)=>t-n))}static parse(e){if(/^\d+$/.test(e))return new o([Number.parseInt(e,10)]);let{groups:t}=e.match(/^((?<range>(?<min>\d+)\s*-\s*(?<max>\d+))|(?<set>\d+(\s*,\s*\d+)+))$/)??{};if(t===void 0)throw new Error(`Invalid version pattern: ${e}`);return t.range!==void 0?o.between(Number.parseInt(t.min,10),Number.parseInt(t.max,10)):o.either(...t.set.split(",").map(n=>Number.parseInt(n,10)))}isRange(){return this.min!==void 0&&this.max!==void 0}isSet(){return this.versions.length>0}isExact(){return this.versions.length===1}getCardinality(){return this.min!==void 0&&this.max!==void 0?this.max-this.min+1:this.versions.length}getExactVersion(){if(!this.isExact())throw new Error("Not an exact version.");return this.versions[0]}getMinVersion(){return this.min??Math.min(...this.versions)}getMaxVersion(){return this.max??Math.max(...this.versions)}getVersions(){let{min:e,max:t}=this;if(e===void 0||t===void 0)return this.versions;let n=[];for(let r=e;r<=t;r++)n.push(r);return n}intersects(e){if(e.isRange())return e.intersects(this);if(this.isRange()){if(e.isRange())return this.getMinVersion()<=e.getMaxVersion()&&e.getMinVersion()<=this.getMaxVersion();if(e.isExact()){let a=e.getExactVersion();return this.getMinVersion()<=a&&a<=this.getMaxVersion()}let r=this.getMinVersion(),i=this.getMaxVersion();return e.getVersions().some(a=>r<=a&&a<=i)}let t=this.getVersions(),n=e.getVersions();return t.length===0||n.length===0?false:t.some(r=>n.includes(r))}contains(e){if(this.isExact()&&e.isExact())return this.getExactVersion()===e.getExactVersion();if(this.isRange()){if(e.isRange())return this.getMinVersion()<=e.getMinVersion()&&e.getMaxVersion()<=this.getMaxVersion();if(e.isExact()){let i=e.getExactVersion();return this.getMinVersion()<=i&&i<=this.getMaxVersion()}let n=this.getMinVersion(),r=this.getMaxVersion();return e.getVersions().every(i=>n<=i&&i<=r)}if(!e.isSet())return false;let t=this.getVersions();return e.getVersions().every(n=>t.includes(n))}without(e){if(!this.intersects(e))return this;if(e.contains(this))throw new Error("A version cannot be empty.");if(this.isRange()){if(e.isExact()){if(this.getMinVersion()===e.getExactVersion())return o.between(e.getExactVersion()+1,this.getMaxVersion());if(this.getMaxVersion()===e.getExactVersion())return o.between(this.getMinVersion(),e.getExactVersion()-1)}else if(e.isRange()){if(this.getMinVersion()===e.getMinVersion())return o.between(e.getMaxVersion()+1,this.getMaxVersion());if(this.getMaxVersion()===e.getMaxVersion())return o.between(this.getMinVersion(),e.getMinVersion()-1)}else if(e.isSet()&&e.getVersions().every((i,a)=>i===e.getMinVersion()+a)){if(this.getMinVersion()===e.getMinVersion())return o.between(e.getMaxVersion()+1,this.getMaxVersion());if(this.getMaxVersion()===e.getMaxVersion())return o.between(this.getMinVersion(),e.getMinVersion()-1)}}if(e.isRange()){let n=e.getMinVersion(),r=e.getMaxVersion();return o.either(...this.getVersions().filter(i=>i<n||i>r))}let t=e.getVersions();return o.either(...this.getVersions().filter(n=>!t.includes(n)))}with(e){if(this.contains(e))return this;if(e.isRange())return e.with(this);if(this.isRange()){if(e.isExact()){if(this.getMaxVersion()+1===e.getExactVersion())return o.between(this.getMinVersion(),e.getExactVersion());if(e.getExactVersion()+1===this.getMinVersion())return o.between(e.getExactVersion(),this.getMaxVersion())}else if(e.isRange()){if(this.getMaxVersion()+1===e.getMinVersion()||e.getMaxVersion()+1===this.getMinVersion())return o.between(Math.min(this.getMinVersion(),e.getMinVersion()),Math.max(this.getMaxVersion(),e.getMaxVersion()))}else if(e.isSet()&&this.contains(this))return this}return o.either(...this.getVersions(),...e.getVersions())}equals(e){if(e.min!==this.min||e.max!==this.max||e.versions.length!==this.versions.length)return false;for(let t=0;t<this.versions.length;t++)if(this.versions[t]!==e.versions[t])return false;return true}toString(){return this.isSet()?this.versions.join(", "):`${this.min} - ${this.max}`}toJSON(){return this.toString()}};function oe(o,...e){let t=[];for(let i=0;i<o.length;i++)t.push(o[i]),i<e.length&&t.push(e[i]);let n=t.join("").split(`
|
|
72
16
|
`);if(n.length<2)return t.join("");let r=n[1].search(/\S/);return n.map(i=>i.slice(r)).join(`
|
|
73
|
-
`).trim()}function kt(o){return o.normalize("NFD").replace(/(^[^a-z]+|[^a-z0-9_ -]+)/ig,"").split(/[^a-z0-9]+/i).map((e,t)=>t===0?e.toLowerCase():e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}var ge=class o{constructor({notifier:e,status:t}){this.notifier=e,this.status=t;}log(e){let t=o.extractLastLine(e.message);t!==""&&this.notifier.update(this.status,t);}static extractLastLine(e){let t=e.split(/\n+/);for(let n=t.length-1;n>=0;n--){let r=t[n].trim();if(r!=="")return r}return ""}};var tt=class o{static{this.CONTENT_PACKAGE="@croct/content";}constructor(e){this.projectDirectory=e.projectDirectory,this.packageManager=e.packageManager,this.workspaceApi=e.workspaceApi,this.formatter=e.formatter,this.fileSystem=e.fileSystem,this.importConfigLoader=e.tsConfigLoader;}async generateSlotExample(e,t){let n=this.projectDirectory.get(),r=[];for(let i of await this.generateSlotExampleFiles(e,t)){let a=this.fileSystem.joinPaths(n,this.fileSystem.getDirectoryName(i.path));await this.fileSystem.createDirectory(a,{recursive:true}).catch(()=>null);let s=this.fileSystem.joinPaths(n,i.path);await this.fileSystem.writeTextFile(s,i.code,{overwrite:true}),r.push(s);}await this.formatter.format(r);}async setup(e){let{input:t,output:n}=e,r=await this.getInstallationPlan(e),i={...r.configuration,paths:{content:".",...await this.getPaths(e.configuration),...r.configuration.paths}},a={...e,configuration:{...e.configuration,...i,applications:e.configuration.applications}},s=[];if(s.push({title:"Install dependencies",task:async p=>{p.update("Installing dependencies");let c=new ge({status:"Installing dependencies",notifier:p});try{await this.packageManager.addDependencies(["croct"],{dev:!0,logger:c}),await this.packageManager.addDependencies([...r.dependencies,o.CONTENT_PACKAGE],{logger:c}),p.confirm("Dependencies installed");}catch(l){p.alert("Failed to install dependencies",d.formatMessage(l));}}}),s.push(...r.tasks),Object.keys(i.slots).length>0&&s.push({title:"Download content",task:async p=>{p.update("Downloading content");try{await this.updateContent(a,{notifier:p,clean:!0});}catch(c){p.alert("Failed to download content",d.formatMessage(c));}}}),await this.isTypeScriptProject()&&s.push({title:"Generate types",task:async p=>{p.update("Generating types");try{await this.updateTypes(a,{notifier:p,clean:!0});}catch(c){p.alert("Failed to generate types",d.formatMessage(c));}try{await this.registerTypeFile(a,p);}catch(c){p.alert("Failed to register type file",d.formatMessage(c));}}}),s.push({title:"Register script",task:async p=>{p.update("Registering script");try{await this.packageManager.addScript("postinstall","croct install"),p.confirm("Script registered");}catch(c){p.alert("Failed to register script",d.formatMessage(c));}}}),s.length>0){if(t!==void 0){n.break(),n.inform("**Installation plan**");for(let{title:p}of s)n.log(` - ${p}`);if(n.break(),!await t.confirm({message:"Proceed?",default:true}))return n.exit()}await n.monitor({tasks:s});}return i}async getPaths(e){let t=await this.resolvePath(["src"],e.paths?.source,".");return {...e.paths,source:t,utilities:await this.resolvePath([this.fileSystem.joinPaths(t,"lib","utils"),this.fileSystem.joinPaths(t,"utils"),this.fileSystem.joinPaths(t,"lib")],e.paths?.utilities,this.fileSystem.joinPaths(t,"lib")),components:await this.resolvePath(["components","Components","component","Component"].flatMap(n=>this.fileSystem.joinPaths(t,n)),e.paths?.components,this.fileSystem.joinPaths(t,"components")),examples:await this.resolvePath(["examples","Examples","example","examples"].flatMap(n=>this.fileSystem.joinPaths(t,n)),e.paths?.examples,this.fileSystem.joinPaths(t,"examples"))}}async resolvePath(e,t,n){if(t!==void 0)return this.fileSystem.normalizeSeparators(t);let r=await this.locateFile(...e);return r!==null?r:n}async update(e,t={}){await this.updateContent(e,t),await this.isTypeScriptProject()&&(await this.updateTypes(e,t),t.clean===true&&await this.registerTypeFile(e));}async updateContent(e,t={}){let{output:n,configuration:r}=e,i=t.notifier??n.notify("Updating content");if(Object.entries(r.slots).length===0){i.confirm("No slots to update");return}let s=await this.mountContentPackageFolder();if(s===null){i.alert(`The package ${o.CONTENT_PACKAGE} is not installed`);return}let p=this.fileSystem.joinPaths(s.directory,"slot");for await(let U of this.fileSystem.list(p,(
|
|
17
|
+
`).trim()}function kt(o){return o.normalize("NFD").replace(/(^[^a-z]+|[^a-z0-9_ -]+)/ig,"").split(/[^a-z0-9]+/i).map((e,t)=>t===0?e.toLowerCase():e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}var ge=class o{constructor({notifier:e,status:t}){this.notifier=e,this.status=t;}log(e){let t=o.extractLastLine(e.message);t!==""&&this.notifier.update(this.status,t);}static extractLastLine(e){let t=e.split(/\n+/);for(let n=t.length-1;n>=0;n--){let r=t[n].trim();if(r!=="")return r}return ""}};var tt=class o{static{this.CONTENT_PACKAGE="@croct/content";}constructor(e){this.projectDirectory=e.projectDirectory,this.packageManager=e.packageManager,this.workspaceApi=e.workspaceApi,this.formatter=e.formatter,this.fileSystem=e.fileSystem,this.importConfigLoader=e.tsConfigLoader;}async generateSlotExample(e,t){let n=this.projectDirectory.get(),r=[];for(let i of await this.generateSlotExampleFiles(e,t)){let a=this.fileSystem.joinPaths(n,this.fileSystem.getDirectoryName(i.path));await this.fileSystem.createDirectory(a,{recursive:true}).catch(()=>null);let s=this.fileSystem.joinPaths(n,i.path);await this.fileSystem.writeTextFile(s,i.code,{overwrite:true}),r.push(s);}await this.formatter.format(r);}async setup(e){let{input:t,output:n}=e,r=await this.getInstallationPlan(e),i={...r.configuration,paths:{content:".",...await this.getPaths(e.configuration),...r.configuration.paths}},a={...e,configuration:{...e.configuration,...i,applications:e.configuration.applications}},s=[];if(s.push({title:"Install dependencies",task:async p=>{p.update("Installing dependencies");let c=new ge({status:"Installing dependencies",notifier:p});try{await this.packageManager.addDependencies(["croct"],{dev:!0,logger:c}),await this.packageManager.addDependencies([...r.dependencies,o.CONTENT_PACKAGE],{logger:c}),p.confirm("Dependencies installed");}catch(l){p.alert("Failed to install dependencies",d.formatMessage(l));}}}),s.push(...r.tasks),Object.keys(i.slots).length>0&&s.push({title:"Download content",task:async p=>{p.update("Downloading content");try{await this.updateContent(a,{notifier:p,clean:!0});}catch(c){p.alert("Failed to download content",d.formatMessage(c));}}}),await this.isTypeScriptProject()&&s.push({title:"Generate types",task:async p=>{p.update("Generating types");try{await this.updateTypes(a,{notifier:p,clean:!0});}catch(c){p.alert("Failed to generate types",d.formatMessage(c));}try{await this.registerTypeFile(a,p);}catch(c){p.alert("Failed to register type file",d.formatMessage(c));}}}),s.push({title:"Register script",task:async p=>{p.update("Registering script");try{await this.packageManager.addScript("postinstall","croct install"),p.confirm("Script registered");}catch(c){p.alert("Failed to register script",d.formatMessage(c));}}}),s.length>0){if(t!==void 0){n.break(),n.inform("**Installation plan**");for(let{title:p}of s)n.log(` - ${p}`);if(n.break(),!await t.confirm({message:"Proceed?",default:true}))return n.exit()}await n.monitor({tasks:s});}return i}async getPaths(e){let t=await this.resolvePath(["src"],e.paths?.source,".");return {...e.paths,source:t,utilities:await this.resolvePath([this.fileSystem.joinPaths(t,"lib","utils"),this.fileSystem.joinPaths(t,"utils"),this.fileSystem.joinPaths(t,"lib")],e.paths?.utilities,this.fileSystem.joinPaths(t,"lib")),components:await this.resolvePath(["components","Components","component","Component"].flatMap(n=>this.fileSystem.joinPaths(t,n)),e.paths?.components,this.fileSystem.joinPaths(t,"components")),examples:await this.resolvePath(["examples","Examples","example","examples"].flatMap(n=>this.fileSystem.joinPaths(t,n)),e.paths?.examples,this.fileSystem.joinPaths(t,"examples"))}}async resolvePath(e,t,n){if(t!==void 0)return this.fileSystem.normalizeSeparators(t);let r=await this.locateFile(...e);return r!==null?r:n}async update(e,t={}){await this.updateContent(e,t),await this.isTypeScriptProject()&&(await this.updateTypes(e,t),t.clean===true&&await this.registerTypeFile(e));}async updateContent(e,t={}){let{output:n,configuration:r}=e,i=t.notifier??n.notify("Updating content");if(Object.entries(r.slots).length===0){i.confirm("No slots to update");return}let s=await this.mountContentPackageFolder();if(s===null){i.alert(`The package ${o.CONTENT_PACKAGE} is not installed`);return}let p=this.fileSystem.joinPaths(s.directory,"slot");for await(let U of this.fileSystem.list(p,(S,P)=>P===0))U.type==="directory"&&await this.fileSystem.delete(this.fileSystem.joinPaths(p,U.name),{recursive:true});let c={},l={},u={};for(let[U,S]of Object.entries(await this.loadContent(e,t.clean))){let P=Math.max(...S.map(({version:B})=>B));for(let{version:B,content:Se}of S)for(let[H,le]of Object.entries(Se)){let Yt=`${U}@${B}`;c[H]===void 0&&(c[H]={});let Za=`${kt(`${U}-${H}`)}V${B}`,Ja=`./${H}/${Yt}`;u[H]===void 0&&(u[H]={}),c[H][Yt]=Ja,u[H][Yt]=`${Za}`,l[Za]=Ja,B===P&&(c[H][U]=Ja,u[H][U]=`${Za}`);let Sl=this.fileSystem.joinPaths(p,H);await this.fileSystem.isDirectory(Sl)||await this.fileSystem.createDirectory(this.fileSystem.joinPaths(p,H),{recursive:true}),await this.fileSystem.writeTextFile(this.fileSystem.joinPaths(p,H,`${Yt}.js`),`export default ${JSON.stringify(le,null,2)};`,{overwrite:true}),await this.fileSystem.writeTextFile(this.fileSystem.joinPaths(p,H,`${Yt}.cjs`),`module.exports = ${JSON.stringify(le,null,2)};`,{overwrite:true});}}let g=Object.entries(l).map(([U,S])=>`import ${U} from '${S}.js';`).join(`
|
|
74
18
|
`),y=`const contentMap = ${JSON.stringify(u,null,2).replace(/(?<=: )"(.*?)"/g,"$1")};
|
|
75
19
|
|
|
76
20
|
`;await this.fileSystem.writeTextFile(this.fileSystem.joinPaths(p,"getSlotContent.js"),`${g}
|
|
77
21
|
|
|
78
|
-
${y}`+
|
|
22
|
+
${y}`+oe`
|
|
79
23
|
const defaultLocale = ${JSON.stringify(r.defaultLocale)};
|
|
80
24
|
|
|
81
25
|
export function getSlotContent(slotId, language = defaultLocale) {
|
|
@@ -89,10 +33,10 @@ ${y}`+ie`
|
|
|
89
33
|
|
|
90
34
|
return null;
|
|
91
35
|
}
|
|
92
|
-
`,{overwrite:true});let C=Object.entries(l).map(([U,
|
|
36
|
+
`,{overwrite:true});let C=Object.entries(l).map(([U,S])=>`const ${U} = require('${S}.cjs');`).join(`
|
|
93
37
|
`);await this.fileSystem.writeTextFile(this.fileSystem.joinPaths(p,"getSlotContent.cjs"),`${C}
|
|
94
38
|
|
|
95
|
-
${y}`+
|
|
39
|
+
${y}`+oe`
|
|
96
40
|
const defaultLocale = ${JSON.stringify(r.defaultLocale)};
|
|
97
41
|
|
|
98
42
|
module.exports = {
|
|
@@ -110,7 +54,7 @@ ${y}`+ie`
|
|
|
110
54
|
};
|
|
111
55
|
`,{overwrite:true});let v=`const contentMap = ${JSON.stringify(c,null,2).replace(/"(\.\/.*?)"/g,'() => import("$1.js")')};
|
|
112
56
|
|
|
113
|
-
`;await this.fileSystem.writeTextFile(this.fileSystem.joinPaths(p,"loadSlotContent.js"),v+
|
|
57
|
+
`;await this.fileSystem.writeTextFile(this.fileSystem.joinPaths(p,"loadSlotContent.js"),v+oe`
|
|
114
58
|
const defaultLocale = ${JSON.stringify(r.defaultLocale)};
|
|
115
59
|
|
|
116
60
|
export function loadSlotContent(slotId, language = defaultLocale) {
|
|
@@ -126,7 +70,7 @@ ${y}`+ie`
|
|
|
126
70
|
}
|
|
127
71
|
`,{overwrite:true});let D=`const contentMap = ${JSON.stringify(c,null,2).replace(/"(\.\/.*?)"/g,'() => Promise.resolve(require("$1.cjs"))')};
|
|
128
72
|
|
|
129
|
-
`;await this.fileSystem.writeTextFile(this.fileSystem.joinPaths(p,"loadSlotContent.cjs"),D+
|
|
73
|
+
`;await this.fileSystem.writeTextFile(this.fileSystem.joinPaths(p,"loadSlotContent.cjs"),D+oe`
|
|
130
74
|
const defaultLocale = ${JSON.stringify(r.defaultLocale)};
|
|
131
75
|
|
|
132
76
|
module.exports = {
|
|
@@ -142,7 +86,7 @@ ${y}`+ie`
|
|
|
142
86
|
return Promise.resolve(null);
|
|
143
87
|
}
|
|
144
88
|
};
|
|
145
|
-
`,{overwrite:true}),i.confirm("Content updated");}async loadContent(e,t=false){let{configuration:n}=e;if(n.paths?.content===void 0)return this.loadRemoteContent(e);let r=this.fileSystem.joinPaths(n.paths.content,"slots.json");if(!t&&await this.fileSystem.exists(r))return this.loadLocalContent(r);let i=await this.loadRemoteContent(e);return await this.saveContent(i,r),i}async saveContent(e,t){let n=this.fileSystem.getDirectoryName(t);await this.fileSystem.createDirectory(n,{recursive:true}),await this.fileSystem.writeTextFile(t,JSON.stringify(e,null,2),{overwrite:true});}async loadLocalContent(e){let t;try{t=await this.fileSystem.readTextFile(e);}catch{return {}}try{return JSON.parse(t)}catch(n){throw new
|
|
89
|
+
`,{overwrite:true}),i.confirm("Content updated");}async loadContent(e,t=false){let{configuration:n}=e;if(n.paths?.content===void 0)return this.loadRemoteContent(e);let r=this.fileSystem.joinPaths(n.paths.content,"slots.json");if(!t&&await this.fileSystem.exists(r))return this.loadLocalContent(r);let i=await this.loadRemoteContent(e);return await this.saveContent(i,r),i}async saveContent(e,t){let n=this.fileSystem.getDirectoryName(t);await this.fileSystem.createDirectory(n,{recursive:true}),await this.fileSystem.writeTextFile(t,JSON.stringify(e,null,2),{overwrite:true});}async loadLocalContent(e){let t;try{t=await this.fileSystem.readTextFile(e);}catch{return {}}try{return JSON.parse(t)}catch(n){throw new ie("Failed to parse content file.",{reason:"invalid_input",cause:n,details:[`File: ${e}`]})}}async loadRemoteContent(e){let t=await this.resolveVersions(e.configuration),n=Object.entries(t.slots),r={};for(let[i,a]of n)r[i]=M.parse(a).getVersions();return Object.fromEntries(await Promise.all(n.map(async([i])=>[i,await Promise.all(r[i].map(a=>this.workspaceApi.getSlotStaticContent({organizationSlug:t.organization,workspaceSlug:t.workspace,slotSlug:i},a).then(s=>({version:a,content:Object.fromEntries(s.map(({locale:p,content:c})=>[p,c]))}))))])))}async updateTypes(e,t={}){let{output:n,configuration:r}=e,i=t.notifier??n.notify("Updating types"),a=this.getTypeFile(r.paths?.content??this.projectDirectory.get());if(t.clean===true||!await this.fileSystem.exists(a)){let s="";(Object.keys(r.slots).length>0||Object.keys(r.components).length>0)&&(s=`${await this.generateTypes(r)}`),s=oe`
|
|
146
90
|
/**
|
|
147
91
|
* Generated by the Croct CLI.
|
|
148
92
|
*
|
|
@@ -154,12 +98,12 @@ ${y}`+ie`
|
|
|
154
98
|
// module
|
|
155
99
|
|
|
156
100
|
export {};
|
|
157
|
-
`.replace("// module",s),await this.fileSystem.writeTextFile(a,s,{overwrite:true});}i.confirm("Types updated");}async generateTypes(e){let{organization:t,workspace:n,components:r,slots:i}=await this.resolveVersions(e);return this.workspaceApi.generateTypes({organizationSlug:t,workspaceSlug:n,target:"PLUG_JS",components:Object.entries(r).map(([a,s])=>({id:a,version:s})),slots:Object.entries(i).map(([a,s])=>({id:a,version:s}))})}async registerTypeFile(e,t){let n=await this.getPaths(e.configuration),r=await this.getTypeScriptConfigPath([n.components,n.examples]),i=t??e.output.notify("Registering type file");if(r===null)throw new
|
|
101
|
+
`.replace("// module",s),await this.fileSystem.writeTextFile(a,s,{overwrite:true});}i.confirm("Types updated");}async generateTypes(e){let{organization:t,workspace:n,components:r,slots:i}=await this.resolveVersions(e);return this.workspaceApi.generateTypes({organizationSlug:t,workspaceSlug:n,target:"PLUG_JS",components:Object.entries(r).map(([a,s])=>({id:a,version:s})),slots:Object.entries(i).map(([a,s])=>({id:a,version:s}))})}async registerTypeFile(e,t){let n=await this.getPaths(e.configuration),r=await this.getTypeScriptConfigPath([n.components,n.examples]),i=t??e.output.notify("Registering type file");if(r===null)throw new ie("TypeScript configuration not found");let a=this.projectDirectory.get();if(!this.fileSystem.isSubPath(a,r)){let l=this.fileSystem.getRelativePath(a,r);throw new ie(`TypeScript configuration is outside the project directory: \`${l}\``)}let s=e.configuration.paths?.content??this.projectDirectory.get(),p=this.fileSystem.getRelativePath(this.fileSystem.getDirectoryName(r),this.getTypeFile(s)).replace(/\\/g,"/"),c=JsonParser$1.parse(await this.fileSystem.readTextFile(r),JsonObjectNode$1);if(c.has("files")){let l=c.get("files",JsonArrayNode$1).toJSON();if(l.includes(p))return i.confirm("Type file already registered");let u=this.getTypeFile(".");for(let g=0;g<l.length;g++){let y=`${l[g]}`;y!==p&&y.endsWith(u)&&l.splice(g,1);}l.push(p),c.set("files",l);}else c.set("files",[p]);await this.fileSystem.writeTextFile(r,c.toString(),{overwrite:true}),i.confirm("Type file registered");}async resolveVersions(e){let t=Object.keys(e.components),n=Object.keys(e.slots);if(t.length===0&&n.length===0)return e;let[r,i]=await Promise.all([Promise.all(n.map(a=>this.workspaceApi.getSlot({organizationSlug:e.organization,workspaceSlug:e.workspace,slotSlug:a}))).then(a=>a.filter(s=>s!==null)),Promise.all(t.map(a=>this.workspaceApi.getComponent({organizationSlug:e.organization,workspaceSlug:e.workspace,componentSlug:a}))).then(a=>a.filter(s=>s!==null))]);return {...e,components:Object.fromEntries(Object.entries(e.components).flatMap(([a,s])=>{let p=M.parse(s).getVersions().filter(c=>i.some(l=>l.slug===a&&c<=l.version.major));return p.length===0?[]:[[a,M.either(...p).toString()]]})),slots:Object.fromEntries(Object.entries(e.slots).flatMap(([a,s])=>{let p=M.parse(s).getVersions().filter(c=>r.some(l=>l.slug===a&&c<=l.version.major));return p.length===0?[]:[[a,M.either(...p).toString()]]}))}}async mountContentPackageFolder(){let e=await this.packageManager.getDependency(o.CONTENT_PACKAGE);if(e===null)return null;if(await this.fileSystem.isSymbolicLink(e.directory)){let t=await this.fileSystem.getRealPath(e.directory);await this.fileSystem.delete(e.directory),await this.fileSystem.copy(t,e.directory);}return e}async locateFile(...e){let t=this.projectDirectory.get();for(let n of e){if(this.fileSystem.isAbsolutePath(n))throw new ie("The file path must be relative");let r=this.fileSystem.joinPaths(t,n);if(await this.fileSystem.exists(r))return n}return null}async readFile(...e){let t=await this.locateFile(...e);return t===null?null:this.fileSystem.readTextFile(this.fileSystem.joinPaths(this.projectDirectory.get(),t))}getTypeFile(e){return this.fileSystem.joinPaths(e,"slots.d.ts")}isTypeScriptProject(){return this.packageManager.hasDirectDependency("typescript")}async getTypeScriptConfigPath(e=[]){let t=this.projectDirectory.get(),n=await this.importConfigLoader.load(t,{fileNames:["tsconfig.json"],sourcePaths:e.length===0?[t]:e});return n===null?null:n.matchedConfigPath}};var Fe=class o{constructor(e=2){this.code="";this.indentationLevel=0;this.indentationSize=e;}indent(){return this.indentationLevel++,this}outdent(){return this.indentationLevel>0&&this.indentationLevel--,this}newLine(e=1){return this.code+=`
|
|
158
102
|
`.repeat(e),this}write(e,t=true){return this.code+=this.indentCode(`${e}`)+(t?`
|
|
159
103
|
`:""),this}appendString(e,t){return this.append(t+e.replace(new RegExp(t,"g"),`\\${t}`)+t)}appendIndentation(){return this.write("",false)}appendName(e,t=true){return this.code+=o.formatName(e,t),this}writeValue(e,t){return this.appendIndentation().appendValue(e,t)}append(e){return this.code+=this.indentCode(e,false),this}appendValue(e,t){let{delimiter:n,stringKeys:r=false}=t;switch(typeof e){case "string":{let i=e.replace(new RegExp(n,"g"),`\\${n}`);return this.append(`${n}${i}${n}`)}case "number":case "boolean":return this.append(`${e}`);case "object":{if(e===null)return this.append("null");if(Array.isArray(e)){if(e.length===0)return this.append("[]");this.append("[").newLine().indent();for(let a=0;a<e.length;a++)this.appendIndentation().appendValue(e[a],t),a<e.length-1&&this.append(", ").newLine();return this.outdent().newLine().write("]",false)}let i=Object.entries(e);if(i.length===0)return this.append("{}");this.append("{").newLine().indent();for(let a=0;a<i.length;a++){let[s,p]=i[a];this.appendIndentation(),r||!isIdentifier(s)?this.appendValue(s,t):this.append(s),this.append(": ").appendValue(p,t),a<i.length-1&&this.append(", ").newLine();}return this.outdent().newLine().write("}",false)}default:return this.append("undefined")}}indentCode(e,t=true){let n=" ".repeat(this.indentationLevel*this.indentationSize);return (t?n:"")+e.replace(/\n/g,`
|
|
160
|
-
${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/[^a-z0-9]/gi,"_");return e.includes("_")?t?n[0].toUpperCase()+n.slice(1):n:n.replace(/(^[a-z_])|_([a-z])/gi,(r,i,a,s)=>t||s>0?(i??a).toUpperCase():(i??a).toLowerCase())}};function
|
|
104
|
+
${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/[^a-z0-9]/gi,"_");return e.includes("_")?t?n[0].toUpperCase()+n.slice(1):n:n.replace(/(^[a-z_])|_([a-z])/gi,(r,i,a,s)=>t||s>0?(i??a).toUpperCase():(i??a).toLowerCase())}};function or(o){let e=o.split(/(?<![A-Z])(?=[A-Z])|_/),t=e[0];return [t[0].toUpperCase()+t.slice(1).toLowerCase(),...e.slice(1).map(i=>i.toLowerCase())].join(" ")}function Xs(o){return o.normalize("NFD").toLocaleLowerCase().replace(/(^[^a-z]+|[^a-z0-9_ &-]+)/ig,"").split(/[^a-z0-9]+/i).filter(e=>e!=="").join("-")}function At(o){return Object.entries(o).sort(([,e],[,t])=>{let n=e.position??Number.MAX_SAFE_INTEGER,r=t.position??Number.MAX_SAFE_INTEGER;return n-r})}var ar=class o{constructor({fileSystem:e,...t}){this.options=t,this.fileSystem=e;}generate(e){let t=this.generateSlotFile(e);return {files:[this.generatePageFile(e,t.path),t]}}generatePageFile(e,t){let n=this.createWriter();return this.writePageSnippet(n,e.definition.title??"Croct example",this.fileSystem.getRelativePath(this.fileSystem.getDirectoryName(this.options.pagePath),t).replace(/\\/g,"/")),{path:this.options.pagePath,language:"html",code:n.toString()}}writePageSnippet(e,t,n){e.write('<html lang="en">').write("<head>").indent().write('<meta charset="UTF-8">').write(`<title>${o.escapeEntities(t)}</title>`).write(`<script type="module" src="${n}"></script>`).outdent().write("</head>").write("<body>").indent().write(`<div id="${this.options.containerId}"></div>`).outdent().write("</body>").write("</html>",false);}generateSlotFile(e){let t=this.createWriter();return this.writeSlotSnippet(t,e),{path:this.options.slotPath,language:this.options.language,code:t.toString()}}writeSlotSnippet(e,t){e.write("import croct from '@croct/plug';"),e.newLine().write(`croct.plug({appId: '${this.options.appId}'});`).newLine(),this.renderListener(e,t);}renderListener(e,t){e.write("document.addEventListener('DOMContentLoaded', async () => {").indent(),e.write("const {content} = ",false).append(`await croct.fetch('${t.id}@${t.version}'`),this.options.fallbackContent!==void 0&&e.append(", {").indent().newLine().write("fallback: ",false).appendValue(this.options.fallbackContent,{delimiter:"'"}).newLine().outdent().write("}",false),e.append(");"),e.newLine(2).write(`document.querySelector('#${this.options.containerId}')`,false),this.options.language==="typescript"&&e.append("!"),e.append(".innerHTML = `").newLine().indent(),this.writeContentSnippet(e,t.definition,"content"),e.outdent().write("`;").outdent().write("});");}writeContentSnippet(e,t,n){switch(t.type){case "text":case "number":e.append(`\${${n}}`);break;case "boolean":t.label!==void 0?e.append(`\${${n} ? `).appendValue(t.label.true??"Yes",{delimiter:"'"}).append(" : ").appendValue(t.label.false??"No",{delimiter:"'"}).append("}"):e.append(`\${${n} ? 'Yes' : 'No'}`);break;case "list":{let r=t.itemLabel!==void 0?kt(t.itemLabel):"item";e.write("<ol>").indent().write(`\${${n}.map(${r} => \``).indent().write("<li>").indent();let i=o.isInline(t.items);i&&e.appendIndentation(),this.writeContentSnippet(e,t.items,r),i&&e.newLine(),e.outdent().write("</li>").outdent().write("`).join('')}").outdent().write("</ol>");break}case "structure":e.write("<ul>").indent();for(let[r,i]of At(t.attributes))i.private!==true&&(i.optional===true&&(e.write(`\${${n}.${r} && \``),e.indent()),this.writeAttributeSnippet(e,i,`${n}.${r}`),i.optional===true&&(e.outdent(),e.write("`}")));e.outdent().write("</ul>");break;case "union":for(let[r,i]of Object.entries(t.types))e.write(`\${${n}._type === '${r}' && \``).indent(),this.writeContentSnippet(e,i,n),e.outdent().write("`}");break}}writeAttributeSnippet(e,t,n){let r=t.type,i=t.label!==void 0?o.escapeEntities(t.label).replace(/`/g,"\\`"):or(n.split(".").pop());switch(r.type){case "boolean":case "text":case "number":{e.write("<li>",false).append(`<strong>${i}:</strong> `),this.writeContentSnippet(e,r,n),e.append("</li>").newLine();break}default:e.write("<li>").indent().write(`<strong>${i}</strong>`),this.writeContentSnippet(e,r,n),e.outdent().write("</li>");break}}static isInline(e){return ["number","text","boolean"].includes(e.type)}static escapeEntities(e){return e.replace(/([&<>])/g,t=>({"&":"&","<":"<",">":">"})[t]??t)}createWriter(){return new Fe(this.options.indentationSize)}};var sr=class o extends tt{constructor({bundlers:e,...t}){super(t),this.bundlers=e;}async generateSlotExampleFiles(e,t){let{configuration:n}=t,[r,i,a]=await Promise.all([this.isTypeScriptProject(),this.detectBundler(),this.workspaceApi.getApplication({organizationSlug:n.organization,workspaceSlug:n.workspace,applicationSlug:n.applications.development})]);if(a===null)throw new ie(`Development application ${n.applications.development} not found.`,{reason:"not_found"});let s=await this.getPaths(n),p=this.fileSystem.joinPaths(s.examples,e.slug),l=new ar({fileSystem:this.fileSystem,language:r?"typescript":"javascript",appId:a.publicId,fallbackContent:i===null?o.extractFallbackContent(e.content[t.configuration.defaultLocale],e.resolvedDefinition):void 0,containerId:"slot",slotPath:this.fileSystem.joinPaths(p,`slot.${r?"ts":"js"}`),pagePath:this.fileSystem.joinPaths(p,"index.html")}).generate({id:e.slug,version:e.version.major,definition:e.resolvedDefinition});return Promise.resolve(l.files)}static extractFallbackContent(e,t){switch(e.type){case "text":case "boolean":case "number":return e.value.type==="static"?e.value.value:e.value.default!==void 0?e.value.default:null;case "list":return e.items.map(n=>o.extractFallbackContent(n,t.items));case "structure":{let n=t,r={};for(let[i,a]of At(n.attributes)){if(a.private===true)continue;let s=o.extractFallbackContent(e.attributes[i],n.attributes[i].type);(a.optional!==true||s!==null)&&(r[i]=s);}return r}}}async detectBundler(){for(let e of this.bundlers)if(await this.packageManager.hasDirectDependency(e))return Promise.resolve(e);return Promise.resolve(null)}getInstallationPlan(e){return Promise.resolve({tasks:[],dependencies:["@croct/plug"],configuration:e.configuration})}};var Qe=class o{constructor(e,t){this.fileSystem=e,this.path=t;}getName(){return this.fileSystem.getBaseName(this.path)}exists(){return this.fileSystem.exists(this.path)}async hasVariable(e){let t=await this.read();if(t==="")return false;let n=o.escapeRegex(e);return new RegExp(`^${n}\\s*=`,"m").test(t)}async setVariables(e){let t=await this.read();try{for(let[n,r]of Object.entries(e))await this.setVariable(n,r);}catch(n){throw await this.write(t),n}}async setVariable(e,t){let n=await this.read(),r=o.escapeRegex(e);if(n==="")return this.write(`${e}=${t}`);let i=`${e}=${t}`,a=n.replace(new RegExp(`${r}\\s*=\\s*((?!['"\`]).*$|\`(?:\\.|[^\`])*\`|'(?:\\.|[^'])*'|"(?:\\.|[^"])*")`,"m"),i);return a!==n||a.includes(i)?this.write(a):this.write(`${n}${n.endsWith(`
|
|
161
105
|
`)?"":`
|
|
162
|
-
`}${e}=${t}`)}async write(e){await this.fileSystem.writeTextFile(this.path,e,{overwrite:true});}async read(){return await this.exists()?this.fileSystem.readTextFile(this.path):""}static escapeRegex(e){return e.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&")}};var Ot=class o{constructor({fileSystem:e,...t}){this.options=t,this.fileSystem=e;}generate(e){let t=o.replaceVariables(this.options.slotFilePath,e.id),n=o.replaceVariables(this.options.slotComponentName,e.id);return {files:[this.generatePageFile(e,{name:n,path:t,importPath:o.replaceVariables(this.options.slotImportPath,e.id),definition:e}),this.generateSlotFile(e,t,n)]}}generatePageFile(e,t){let n=this.createWriter(),r=o.replaceVariables(this.options.pageFilePath,e.id),i=o.replaceVariables(this.options.pageComponentName,e.id);return this.writePageSnippet(n,i,t),{path:r,language:this.options.language,code:n.toString()}}generateSlotFile(e,t,n){let r=this.createWriter();return this.writeSlotSnippet(r,e,n),{path:t,language:this.options.language,code:r.toString()}}writePageSnippet(e,t,n){this.writePageHeader(e,n),e.newLine(),this.writePageSignature(e,t),e.indent().write("return (").indent(),this.hasSuspenseBoundary()&&e.write('<Suspense fallback="\u2728 Personalizing...">').indent(),this.writeSlotRendering(e,n.name),this.hasSuspenseBoundary()&&e.outdent().write("</Suspense>"),e.outdent().write(");").outdent().write("}",false);}writeSlotRendering(e,t){e.write(`<${t} />`);}writePageSignature(e,t){e.write(this.options.language==="tsx"?`export default function ${t}(): ReactElement {`:`export default function ${t}() {`);}writePageHeader(e,t){switch(this.options.language){case "jsx":this.hasSuspenseBoundary()&&e.write("import {Suspense} from 'react';");break;case "tsx":e.write(this.hasSuspenseBoundary()?"import {type ReactElement, Suspense} from 'react';":"import type {ReactElement} from 'react';");break}e.write(`import ${t.name} from '${t.importPath}';`);}writeSlotSnippet(e,t,n){this.writeSlotHeader(e,t),this.writeSlotSignature(e,t,n),e.indent(),this.writeSlotFetch(e,t),e.write("return (").indent(),this.writeRenderingSnippet(e,t.definition,this.options.contentVariable),e.outdent().write(");").outdent().write("};");}writeSlotSignature(e,t,n){e.write(`export default ${this.isSlotFetchAsync()?"async ":""}function ${n}`,false),this.appendSlotParams(e,t),this.options.language==="tsx"&&e.append(`: ${this.isSlotFetchBlocking()?"Promise<ReactElement>":"ReactElement"}`),e.write(" {");}appendSlotParams(e,t){e.append("()");}writeRenderingSnippet(e,t,n){switch(t.type){case "number":case "text":e.append(`{${n}}`);break;case "boolean":t.label!==void 0?e.append(`{${n} ? `).appendValue(t.label.true??"Yes",{delimiter:"'"}).append(" : ").appendValue(t.label.false??"No",{delimiter:"'"}).append("}"):e.append(`{${n} ? 'Yes' : 'No'}`);break;case "list":{let r=t.itemLabel!==void 0?kt(t.itemLabel):"item";e.write("<ol>").indent().write(`{${n}.map((${r}, index) => (`).indent().write("<li key={index}>").indent();let i=o.isInline(t.items);i&&e.appendIndentation(),this.writeRenderingSnippet(e,t.items,r),i&&e.newLine(),e.outdent().write("</li>").outdent().write("))}").outdent().write("</ol>");break}case "structure":e.write("<ul>").indent();for(let[r,i]of At(t.attributes))i.private!==true&&(i.optional===true&&(e.write(`{${n}.${r} && (`),e.indent()),this.writeAttributeSnippet(e,{name:r,...i},n),i.optional===true&&(e.outdent(),e.write(")}")));e.outdent().write("</ul>");break;case "union":{let r=!n.includes(".");r&&e.write("<>").indent();for(let[i,a]of Object.entries(t.types))e.write(`{${n}._type === '${i}' && (`).indent(),this.writeRenderingSnippet(e,a,n),e.outdent().write(")}");r&&e.outdent().write("</>");break}}}writeAttributeSnippet(e,t,n){let r=t.type,i=o.escapeEntities(t.label??ir(t.name));switch(r.type){case "boolean":case "text":case "number":{e.write("<li>",false).append(`<strong>${i}:</strong> `),this.writeRenderingSnippet(e,r,`${n}.${t.name}`),e.append("</li>").newLine();break}default:e.write("<li>").indent().write(`<strong>${i}</strong>`),this.writeRenderingSnippet(e,r,`${n}.${t.name}`),e.outdent().write("</li>");break}}static escapeEntities(e){return e.replace(/([&"<>])/g,t=>({"&":"&",'"':""","<":"<",">":">"})[t]??t)}createWriter(){return new Fe(this.options.indentationSize)}static replaceVariables(e,t){return e.replace(/%name%/g,o.formatName(t,true)).replace(/%slug%/g,Qs(t))}static formatName(e,t=false){return Fe.formatName(e,t)}static isInline(e){return ["number","text","boolean"].includes(e.type)}};var Rt=class extends Ot{writeSlotHeader(e){switch(this.options.language){case "jsx":e.write("import {useContent} from '@croct/plug-react';");break;case "tsx":e.write("import type {ReactElement} from 'react';"),e.write("import {useContent} from '@croct/plug-react';");break}e.newLine();}writeSlotFetch(e,t){let n=this.options.contentVariable;e.write(`const ${n} = useContent('${t.id}@${t.version}');`).newLine();}isSlotFetchAsync(){return false}isSlotFetchBlocking(){return false}hasSuspenseBoundary(){return false}};var sr=class o extends tt{constructor(e){super(e),this.codemod=e.codemod,this.bundlers=e.bundlers,this.importResolver=e.importResolver;}async generateSlotExampleFiles(e,t){let n=await this.isTypeScriptProject(),r=await this.getPaths(t.configuration),i=this.fileSystem.joinPaths(r.components,`%slug%${n?".tsx":".jsx"}`),a=this.fileSystem.joinPaths(r.examples,`%slug%-example${n?".tsx":".jsx"}`);return new Rt({fileSystem:this.fileSystem,language:await this.isTypeScriptProject()?"tsx":"jsx",contentVariable:"content",slotImportPath:await this.importResolver.getImportPath(i,this.fileSystem.getDirectoryName(a)),slotFilePath:i,slotComponentName:"%name%",pageFilePath:a,pageComponentName:"%name%Example"}).generate({id:e.slug,version:e.version.major,definition:e.resolvedDefinition}).files}async getInstallationPlan(e){let{configuration:t}=e,n=await this.getProjectInfo();return {dependencies:["@croct/plug-react"],tasks:this.getInstallationTasks({...e,project:n}),configuration:t}}async getProjectInfo(){let e="src",t=await this.getEnvVarProperty(),n=this.projectDirectory.get();return {typescript:await this.isTypeScriptProject(),sourceDirectory:e,provider:{file:await this.locateFile(...["App","main","index"].flatMap(r=>["js","jsx","ts","tsx"].map(i=>`${r}.${i}`)).map(r=>this.fileSystem.joinPaths(e,r)))},env:t===null?void 0:{property:t,productionFile:new Qe(this.fileSystem,this.fileSystem.joinPaths(n,".env.production")),developmentFile:new Qe(this.fileSystem,this.fileSystem.joinPaths(n,".env.development"))}}}getInstallationTasks(e){let t=[],n=e.project.env,{configuration:r}=e,i=null,a=()=>(i===null&&(i=Promise.all([this.workspaceApi.getApplication({organizationSlug:r.organization,workspaceSlug:r.workspace,applicationSlug:r.applications.development}),r.applications.production===void 0?null:this.workspaceApi.getApplication({organizationSlug:r.organization,workspaceSlug:r.workspace,applicationSlug:r.applications.production})]).then(([s,p])=>s===null?Promise.reject(new re(`Development application ${r.applications.development} not found`,{reason:"not_found"})):{development:s.publicId,production:p?.publicId})),i);if(n!==void 0){let{developmentFile:s,productionFile:p,property:c}=n,l=c.split(".").pop();t.push({title:"Setup environment variables",task:async u=>{u.update("Setting up environment variables");try{let g=await a();await Promise.all([s.setVariable(l,g.development),g.production===void 0?Promise.resolve():p.setVariable(l,g.production)]),u.confirm("Environment variables updated");}catch(g){u.alert("Failed to update environment variables",d.formatMessage(g));}}});}return t.push({title:"Configure provider",task:async s=>{s.update("Configuring provider");let p=e.project.provider.file;try{p===null?s.alert("No root component found"):(s.update("Configuring provider"),await this.installProvider(p,{props:{appId:o.getAppIdProperty(await a(),n?.property)}}),s.confirm("Provider configured"));}catch(c){s.alert("Failed to install provider",d.formatMessage(c));}}}),t}async installProvider(e,t){await this.codemod.provider.apply(this.fileSystem.joinPaths(this.projectDirectory.get(),e),t);}async getEnvVarProperty(){for(let e of this.bundlers)if(await this.packageManager.hasDirectDependency(e.package))return `${e.prefix}CROCT_APP_ID`;return null}static getAppIdProperty(e,t){return t!==void 0?{type:"reference",path:t.split(".")}:e.production===void 0?{type:"literal",value:e.development}:{type:"ternary",condition:{operator:"===",left:{type:"reference",path:["process","env","NODE_ENV"]},right:{type:"literal",value:"production"}},consequent:{type:"literal",value:e.production},alternate:{type:"literal",value:e.development}}}};var nt=class o extends d{constructor(e,t={}){super(e,t),Object.setPrototypeOf(this,o.prototype);}},pr=class o extends nt{constructor(e){super(e),Object.setPrototypeOf(this,o.prototype);}};function je(o,e,t){try{return parse$2(o,{...t,sourceType:"module",plugins:[...e,...t?.plugins??[]]})}catch{throw new pr("The source code contains syntax errors.")}}function Bs(o){let e={locales:Array()},t;try{t=je(o,["jsx","typescript"]);}catch{return {i18n:e}}return traverse(t,{ObjectProperty:n=>{if(is(n.node.key)!=="i18n")return n.skip();let r=n.node.value;if(!f.isObjectExpression(r))return n.stop();for(let i of r.properties)if(f.isObjectProperty(i)&&is(i.key)==="locales"){let a=i.value;if(f.isArrayExpression(a))for(let s of a.elements)s!==null&&f.isStringLiteral(s)&&e.locales.push(s.value);}else if(f.isObjectProperty(i)&&is(i.key)==="defaultLocale"){let a=i.value;a!==null&&f.isStringLiteral(a)&&(e.defaultLocale=a.value);}return n.stop()}}),{i18n:e}}function is(o){return f.isIdentifier(o)?o.name:f.isStringLiteral(o)?o.value:null}var cr=class extends Ot{constructor({fileSystem:e,router:t,...n}){super({fileSystem:e,contentVariable:t==="app"?"content":"props",...n}),this.nextOptions={router:t};}writeSlotHeader(e,t){switch(this.options.language){case "jsx":this.nextOptions.router==="app"&&(e.write("import {fetchContent} from '@croct/plug-next/server';"),e.newLine());break;case "tsx":if(e.write("import type {ReactElement} from 'react';"),this.nextOptions.router==="app"&&e.write("import {fetchContent} from '@croct/plug-next/server';"),this.nextOptions.router==="page"){e.write("import type {SlotContent} from '@croct/plug-next';"),e.newLine();let n=Fe.formatName(t.id,true);e.write(`export type ${n}Props = SlotContent<'${t.id}@${t.version}'>;`);}e.newLine();break}}writeSlotFetch(e,t){if(this.nextOptions.router==="app"){let n=this.options.contentVariable;e.write(`const {${n}} = await fetchContent('${t.id}@${t.version}');`).newLine();}}writePageHeader(e,t){if(this.nextOptions.router==="app")return super.writePageHeader(e,t);let n=`${t.definition.id}@${t.definition.version}`;switch(this.options.language){case "jsx":e.write("import {fetchContent} from '@croct/plug-next/server';").write(`import ${t.name} from '${t.importPath}';`),e.newLine().write("export async function getServerSideProps(context) {").indent().write("return {").indent().write(`props: await fetchContent('${n}', {`).indent().write("route: context,").outdent().write("}),").outdent().write("}").outdent().write("}");break;case "tsx":e.write("import type {ReactElement} from 'react';"),e.write("import type {GetServerSideProps} from 'next';"),e.write("import {fetchContent} from '@croct/plug-next/server';"),e.write(`import ${t.name}, {type ${t.name}Props} from '${t.importPath}';`),e.newLine().write("type PageProps = {").indent().write(`content: ${t.name}Props,`).outdent().write("};").newLine().write("export const getServerSideProps: ",false).write("GetServerSideProps<PageProps> = async context => ({").indent().write(`props: await fetchContent('${n}', {`).indent().write("route: context,").outdent().write("}),").outdent().write("});");break}}writePageSignature(e,t){switch(this.nextOptions.router){case "app":super.writePageSignature(e,t);break;case "page":{e.write(this.options.language==="tsx"?"export default function Page({content}: PageProps): ReactElement {":"export default function Page({content}) {");break}}}appendSlotParams(e,t){if(this.nextOptions.router!=="page")return super.appendSlotParams(e,t);let n=Fe.formatName(t.id,true),r=this.options.contentVariable;if(this.options.language==="jsx"){e.append(`(${r})`);return}e.append(`(${r}: ${n}Props)`);}writeSlotRendering(e,t){switch(this.nextOptions.router){case "app":super.writeSlotRendering(e,t);break;case "page":{e.write(`<${t} {...content} />`);break}}}isSlotFetchAsync(){return this.nextOptions.router==="app"}isSlotFetchBlocking(){return this.nextOptions.router==="app"}hasSuspenseBoundary(){return false}};var oe=class o extends d{constructor(e,t=[],n={}){super(e,{...n,details:n.details??t.map(r=>r.detail??r.title)}),Object.setPrototypeOf(this,o.prototype),this.problems=t;}isErrorType(e){return this.problems.some(t=>t.type===e)}isAccessDenied(e){return this.problems.some(t=>t.type==="https://croct.help/api/admin#access-denied"&&(e===void 0||t.reason===e))}};var Pe=(t=>(t.DEVELOPMENT="DEVELOPMENT",t.PRODUCTION="PRODUCTION",t))(Pe||{});(n=>{function o(r){switch(r){case "DEVELOPMENT":return "Development";case "PRODUCTION":return "Production"}}n.getLabel=o;function e(){return Object.values(n).filter(r=>typeof r=="string")}n.all=e;function t(r){let i=r.toUpperCase();if(!n.all().includes(i))throw new Error(`Invalid environment value "${r}".`);return i}n.fromValue=t;})(Pe||={});var De=(n=>(n.READ_RESOURCES="RESOURCE_READ_ACCESS",n.ISSUE_TOKEN="TOKEN_ISSUE",n.EXPORT_DATA="DATA_EXPORT",n))(De||{});(n=>{function o(r){switch(r){case "RESOURCE_READ_ACCESS":return "Read resources";case "TOKEN_ISSUE":return "Issue tokens";case "DATA_EXPORT":return "Export data"}}n.getLabel=o;function e(){return Object.values(n).filter(r=>typeof r=="string")}n.all=e;function t(r){let i=r.toUpperCase();if(!n.all().includes(i))throw new Error(`Invalid permission value "${r}".`);return i}n.fromValue=t;})(De||={});var lr=class extends tt{constructor(e){super(e),this.codemod=e.codemod,this.importResolver=e.importResolver,this.userApi=e.userApi,this.applicationApi=e.applicationApi;}async generateSlotExampleFiles(e,t){let[n,r,i]=await Promise.all([this.detectRouter(),this.isTypeScriptProject(),this.isFallbackMode()]),a=await this.isTypeScriptProject(),s=await this.getPaths(t.configuration),p=this.fileSystem.joinPaths(s.components,`%slug%${a?".tsx":".jsx"}`),c=this.fileSystem.joinPaths(s.examples,"%slug%"),l=await this.importResolver.getImportPath(p,c),u=r?"tsx":"jsx";return (i?new Rt({fileSystem:this.fileSystem,language:u,contentVariable:"content",slotImportPath:l,slotFilePath:p,slotComponentName:"%name%",pageFilePath:this.fileSystem.joinPaths(c,`index${a?".tsx":".jsx"}`),pageComponentName:"Page"}):new cr({fileSystem:this.fileSystem,router:n==="page"?"page":"app",language:u,slotImportPath:l,slotFilePath:p,slotComponentName:"%name%",pageFilePath:this.fileSystem.joinPaths(c,`${n==="page"?"index":"page"}${r?".tsx":".jsx"}`),pageComponentName:"Page"})).generate({id:e.slug,version:e.version.major,definition:e.resolvedDefinition}).files}async getInstallationPlan(e){let{configuration:t,output:n}=e,[{i18n:r},i]=await Promise.all([this.getConfig(),this.getProjectInfo()]);i.fallbackMode&&n.announce({semantics:"warning",title:"Fallback mode",message:"Next.js SDK requires version 13 or newer, so React SDK will be installed instead."});let a=t.locales.filter(c=>r.locales.includes(c)||c===t.defaultLocale),s=a.length>0?a:r.locales,p=r.defaultLocale!==void 0&&s.includes(r.defaultLocale)?r.defaultLocale:t.defaultLocale;return {dependencies:[i.fallbackMode?"@croct/plug-react":"@croct/plug-next"],tasks:this.getInstallationTasks({...e,project:i}),configuration:{...t,locales:s,defaultLocale:p,paths:{...t.paths,examples:i.pageDirectory}}}}async getProjectInfo(){let[e,t,n]=await Promise.all([this.isTypeScriptProject(),this.getPageDirectory(),this.isFallbackMode()]),r={typescript:e,router:await this.detectRouter(t),sourceDirectory:t.startsWith("src")?"src":".",pageDirectory:t},[i,a]=await Promise.all([this.locateFile(...["middleware.js","middleware.ts"].map(c=>this.fileSystem.joinPaths(r.sourceDirectory,c))),this.locateFile(...(r.router==="app"?[this.fileSystem.joinPaths("app","layout"),this.fileSystem.joinPaths("app","layout")]:[this.fileSystem.joinPaths("pages","_app"),this.fileSystem.joinPaths("pages","_app")]).flatMap(c=>["js","jsx","ts","tsx"].map(l=>this.fileSystem.joinPaths(r.sourceDirectory,`${c}.${l}`))))]),s=r.typescript?"ts":"js",p=this.projectDirectory.get();return {...r,fallbackMode:n,env:{localFile:new Qe(this.fileSystem,this.fileSystem.joinPaths(p,".env.local")),developmentFile:new Qe(this.fileSystem,this.fileSystem.joinPaths(p,".env.development")),productionFile:new Qe(this.fileSystem,this.fileSystem.joinPaths(p,".env.production"))},middleware:{file:i??this.fileSystem.joinPaths(r.sourceDirectory,`middleware.${s}`)},provider:{file:a??(r.router==="app"?this.fileSystem.joinPaths(r.sourceDirectory,"app",`layout.${s}x`):this.fileSystem.joinPaths(r.sourceDirectory,"pages",`_app.${s}x`))}}}getInstallationTasks(e){let t=[];return e.project.fallbackMode||t.push({title:"Configure middleware",task:async n=>{n.update("Configuring middleware");try{await this.updateCode(this.codemod.middleware,e.project.middleware.file),n.confirm("Middleware configured");}catch(r){n.alert("Failed to install middleware",d.formatMessage(r));}}}),t.push({title:"Configure provider",task:async n=>{n.update("Configuring provider");try{await this.installProvider({...e,notifier:n}),n.confirm("Provider configured");}catch(r){n.alert("Failed to install provider",d.formatMessage(r));}}}),t.push({title:"Setup environment variables",task:async n=>{n.update("Setting up environment variables");try{await this.updateEnvVariables({...e,notifier:n}),n.confirm("Environment variables updated");}catch(r){n.alert("Failed to update .env.local",d.formatMessage(r));}}}),t}installProvider(e){return this.updateCode(this.getProviderCodemod(e),e.project.provider.file,{typescript:e.project.typescript})}getProviderCodemod(e){return e.project.fallbackMode?this.codemod.fallbackProvider:e.project.router==="app"?this.codemod.appRouterProvider:this.codemod.pageRouterProvider}async updateCode(e,t,n){await e.apply(this.fileSystem.joinPaths(this.projectDirectory.get(),t),n);}async updateEnvVariables(e){let{project:{env:t},configuration:n,notifier:r}=e;r.update("Loading information");let[i,a]=await Promise.all([this.workspaceApi.getApplication({organizationSlug:n.organization,workspaceSlug:n.workspace,applicationSlug:n.applications.development}),n.applications.production===void 0?null:this.workspaceApi.getApplication({organizationSlug:n.organization,workspaceSlug:n.workspace,applicationSlug:n.applications.production})]);if(i===null)throw new re(`Development application \`${n.applications.development}\` not found.`,{reason:"not_found"});if(!await t.localFile.hasVariable("CROCT_API_KEY")&&e.skipApiKeySetup!==true){let s=await this.userApi.getUser();r.update("Creating API key");let p;try{p=await this.applicationApi.createApiKey({organizationSlug:n.organization,workspaceSlug:n.workspace,applicationSlug:i.slug,name:`${s.username} CLI`,permissions:["TOKEN_ISSUE"]});}catch(c){throw c instanceof d?new re(c instanceof oe&&c.isAccessDenied()?"Your user does not have permission to create an API key":c.message,c.help):c}await t.localFile.setVariables({CROCT_API_KEY:p.secret});}await Promise.all([t.developmentFile.setVariables({NEXT_PUBLIC_CROCT_APP_ID:i.publicId}),a===null?Promise.resolve():t.productionFile.setVariables({NEXT_PUBLIC_CROCT_APP_ID:a.publicId})]);}async detectRouter(e){return (e??await this.getPageDirectory()).endsWith("pages")?"page":"app"}async getPageDirectory(){return await this.locateFile("app",this.fileSystem.joinPaths("src","app"),"pages",this.fileSystem.joinPaths("src","pages"))??"app"}async getConfig(){let e=["js","mjs","ts","mts"].map(n=>`next.config.${n}`),t=await this.readFile(...e).catch(()=>null);return t===null?{i18n:{locales:[],defaultLocale:""}}:Bs(t)}isFallbackMode(){return this.packageManager.hasDirectDependency("next","<=13")}};var lt=(n=>(n.NEXTJS="nextjs",n.REACT="react",n.JAVASCRIPT="javascript",n))(lt||{});(e=>{function o(t){switch(t){case "nextjs":return "Next.js";case "react":return "React";case "javascript":return "JavaScript"}}e.getName=o;})(lt||={});var ur=class o{constructor(e){this.config=e;}async execute(e){let{configurationManager:t,platformProvider:n,sdkProvider:r,io:{output:i}}=this.config;if(e.override!==true&&await t.isInitialized())throw new d("Configuration file already exists, specify `override` to reconfigure.",{reason:"precondition"});let a=await n.get(),s=a!==null?`${lt.getName(a)} project`:"project";i.break(),i.announce({semantics:"neutral",title:"\u{1F44B} Welcome to Croct",alignment:"center",message:`Let's configure your ${s} to get started!`}),i.break();let p=await this.getOrganization({new:e.new==="organization"},e.organization);if(p===null)throw new d(`Organization not found: ${e.organization}`,{reason:"invalid_input"});let c=await this.getWorkspace({organization:p,new:e.new==="workspace"},e.workspace),l={organization:p,workspace:c,platform:a??"javascript",new:e.new==="application"},u=await this.getApplication({...l,environment:"DEVELOPMENT"},e.devApplication),g={organization:p.slug,workspace:c.slug,applications:{development:u.slug},defaultLocale:c.defaultLocale,locales:c.locales,slots:{},components:{}},y=c.website??p.website??void 0;if(y!==void 0&&new URL(y).hostname!=="localhost"){let v=await this.getApplication({...l,environment:"PRODUCTION"},e.prodApplication);g.applications.production=v.slug;}let C=await r.get();if(C===null){await t.update(g),i.warn("No suitable SDK found, skipping project configuration");return}await t.update(await this.configure(C,g,e.skipApiKeySetup===true));}async getOrganization(e,t){let{form:n,api:r}=this.config,i=t===void 0?await n.organization.handle(e):await r.user.getOrganization(t).catch(a=>{if(a instanceof oe&&a.isAccessDenied())return null;throw a});if(i===null)throw new d(`No organization found with slug "${t}".`,{reason:"invalid_input"});return i}async getWorkspace(e,t){let{form:n,api:r}=this.config,i=t===void 0?await n.workspace.handle(e):await r.organization.getWorkspace({organizationSlug:e.organization.slug,workspaceSlug:t}).catch(a=>{if(a instanceof oe&&a.isAccessDenied())return null;throw a});if(i===null)throw new d(`No workspace found with slug "${t}".`,{reason:"invalid_input"});return i}async getApplication(e,t){let{form:n,api:r}=this.config,i=t===void 0?await n.application.handle(e):await r.workspace.getApplication({organizationSlug:e.organization.slug,workspaceSlug:e.workspace.slug,applicationSlug:t}).catch(a=>{if(a instanceof oe&&a.isAccessDenied())return null;throw a});if(i===null)throw new d(`No application found with slug "${t}".`,{reason:"invalid_input"});if(i.environment!==e.environment)throw new d(`No ${Pe.getLabel(e.environment).toUpperCase()} application found with slug "${t}".`,{reason:"invalid_input"});return i}async configure(e,t,n){let{skipConfirmation:r}=this.config,i=await e.setup({input:this.config.io.input===void 0||await r.get()?void 0:this.config.io.input,output:this.config.io.output,skipApiKeySetup:n,configuration:t});return o.canonicalizePaths(i)}static canonicalizePaths(e){return e.paths===void 0?e:{...e,paths:Object.fromEntries(Object.entries(e.paths).map(([t,n])=>[t,o.canonicalizePath(n)]))}}static canonicalizePath(e){return e.replace(/\\/g,"/")}};var mr=class{constructor(e){this.authenticator=e.authenticator;}async execute(e){await this.authenticator.logout(),await this.authenticator.login(e);}};var an=class{constructor({output:e,authenticator:t}){this.authenticator=t,this.output=e;}async execute(){await this.authenticator.logout(),this.output.confirm("Logged out");}};var ut=class o extends d{constructor(e,t={}){super(e,{...t,reason:t.reason??"invalid_configuration"}),Object.setPrototypeOf(this,o.prototype);}};var dr=class o{static{this.CONFIGURATION_SCHEMA="https://schema.croct.com/json/v1/project.json";}constructor({fileSystem:e,projectDirectory:t,validator:n}){this.fileSystem=e,this.projectDirectory=t,this.validator=n;}isInitialized(){return this.fileSystem.exists(this.getConfigurationFilePath())}async load(){let e=await this.loadConfigurationFile();if(e.configuration===null)throw new ut("Project configuration not found.",{reason:"not_found",suggestions:["Run `init` command to initialize the project"]});return e.configuration}async update(e){return this.updateConfigurationFile(await this.validateConfiguration(e))}async updateConfigurationFile(e){let t=await this.loadConfigurationFile(),r=this.applyConfigurationChanges(t,e).toString({indentationCharacter:"space",object:{indentationSize:2,leadingIndentation:true,trailingIndentation:true,entryIndentation:true,colonSpacing:true,commaSpacing:true},array:{indentationSize:2,entryIndentation:true,leadingIndentation:true,trailingIndentation:true,colonSpacing:true,commaSpacing:true}});try{await this.fileSystem.writeTextFile(t.path,r,{overwrite:!0});}catch{throw new Error(`Unable to write configuration file ${t.path}.`)}return e}applyConfigurationChanges(e,t){if(e.configuration===null||e.source===null)return JsonObjectNode$1.of({$schema:o.CONFIGURATION_SCHEMA,...t});let n=JsonParser$1.parse(e.source,JsonObjectNode$1);return n.update({$schema:n.has("$schema")?n.get("$schema").toJSON():void 0,...t}).cast(JsonObjectNode$1)}async loadConfigurationFile(){let e={path:this.getConfigurationFilePath(),source:null,configuration:null},t;try{e.source=await this.fileSystem.readTextFile(e.path),t=JsonParser$1.parse(e.source).toJSON();}catch{return e}return t!==null&&(e.configuration=await this.validateConfiguration(t,e),e.configuration?.$schema!==void 0&&delete e.configuration?.$schema),e}getConfigurationFilePath(){return this.fileSystem.joinPaths(this.projectDirectory.get(),"croct.json")}async validateConfiguration(e,t){let n=await this.validator.validate(e);if(!n.valid){let r=n.violations[0];throw new ut(r.message,{details:[...t!==void 0?[`File: file://${t.path.replace(/\\/g,"/")}`]:[],`Violation path: ${r.path}`]})}return n.data}};var sn=class{constructor(e){this.configuration=e;}async execute(e,...[t]){let{tokenProvider:n,endpoint:r}=this.configuration,i=n!==void 0?await n.getToken():null,a=await fetch(r,{method:"POST",headers:{accept:"application/json","content-type":"application/json",...i!==null?{Authorization:`Bearer ${i}`}:{}},body:JSON.stringify({query:e,variables:t})});return a.json().then(s=>{let{data:p,errors:c}=s;if(c!==void 0)throw new oe(c[0].message.replace(/"/g,"`"),c.map(({extensions:l})=>({...l,detail:l.detail?.replace(/"/g,"`")})));return {data:p,headers:a.headers}})}};function as(o,e){return o.slice(0,o.indexOf("-",e-1)===e-1?e-1:e)}function*pn({baseName:o,alwaysSuffixed:e=false}){let t=o.normalize("NFD").toLowerCase().replace(/[^a-z ]/g,"").trim().split(/\s+/);t.length===0&&t.push(String.fromCharCode(97+Math.floor(Math.random()*26))+Math.random().toString(36).substring(2,14));let n=t.slice(0,2).join("-");for(e||(yield as(n,30),n.length<29&&t.length>2&&(yield as(t.join("-"),30)));;){let r=Math.floor(Math.random()*1e4).toString();yield `${as(n,30-r.length-1)}-${r}`;}}function mt(o){let{baseName:e,query:t,client:n,alwaysSuffixed:r}=o;return pu({baseName:e,alwaysSuffixed:r},async i=>{let a=[i.next().value,i.next().value,i.next().value],{data:{checkAvailability:s}}=await n.execute(t,{...o.variables??{},slugFirstOption:a[0],slugSecondOption:a[1],slugThirdOption:a[2]}),p=[s.slugFirstOption,s.slugSecondOption,s.slugThirdOption];return a.find((c,l)=>p[l])??null})}async function pu(o,e){let t=pn(o),n;do n=await e(t);while(n===null);return n}var O=class extends String{constructor(e,t){super(e),this.value=e,this.__meta__=t;}toString(){return this.value}},Xs=new O(`
|
|
106
|
+
`}${e}=${t}`)}async write(e){await this.fileSystem.writeTextFile(this.path,e,{overwrite:true});}async read(){return await this.exists()?this.fileSystem.readTextFile(this.path):""}static escapeRegex(e){return e.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&")}};var Ot=class o{constructor({fileSystem:e,...t}){this.options=t,this.fileSystem=e;}generate(e){let t=o.replaceVariables(this.options.slotFilePath,e.id),n=o.replaceVariables(this.options.slotComponentName,e.id);return {files:[this.generatePageFile(e,{name:n,path:t,importPath:o.replaceVariables(this.options.slotImportPath,e.id),definition:e}),this.generateSlotFile(e,t,n)]}}generatePageFile(e,t){let n=this.createWriter(),r=o.replaceVariables(this.options.pageFilePath,e.id),i=o.replaceVariables(this.options.pageComponentName,e.id);return this.writePageSnippet(n,i,t),{path:r,language:this.options.language,code:n.toString()}}generateSlotFile(e,t,n){let r=this.createWriter();return this.writeSlotSnippet(r,e,n),{path:t,language:this.options.language,code:r.toString()}}writePageSnippet(e,t,n){this.writePageHeader(e,n),e.newLine(),this.writePageSignature(e,t),e.indent().write("return (").indent(),this.hasSuspenseBoundary()&&e.write('<Suspense fallback="\u2728 Personalizing...">').indent(),this.writeSlotRendering(e,n.name),this.hasSuspenseBoundary()&&e.outdent().write("</Suspense>"),e.outdent().write(");").outdent().write("}",false);}writeSlotRendering(e,t){e.write(`<${t} />`);}writePageSignature(e,t){e.write(this.options.language==="tsx"?`export default function ${t}(): ReactElement {`:`export default function ${t}() {`);}writePageHeader(e,t){switch(this.options.language){case "jsx":this.hasSuspenseBoundary()&&e.write("import {Suspense} from 'react';");break;case "tsx":e.write(this.hasSuspenseBoundary()?"import {type ReactElement, Suspense} from 'react';":"import type {ReactElement} from 'react';");break}e.write(`import ${t.name} from '${t.importPath}';`);}writeSlotSnippet(e,t,n){this.writeSlotHeader(e,t),this.writeSlotSignature(e,t,n),e.indent(),this.writeSlotFetch(e,t),e.write("return (").indent(),this.writeRenderingSnippet(e,t.definition,this.options.contentVariable),e.outdent().write(");").outdent().write("};");}writeSlotSignature(e,t,n){e.write(`export default ${this.isSlotFetchAsync()?"async ":""}function ${n}`,false),this.appendSlotParams(e,t),this.options.language==="tsx"&&e.append(`: ${this.isSlotFetchBlocking()?"Promise<ReactElement>":"ReactElement"}`),e.write(" {");}appendSlotParams(e,t){e.append("()");}writeRenderingSnippet(e,t,n){switch(t.type){case "number":case "text":e.append(`{${n}}`);break;case "boolean":t.label!==void 0?e.append(`{${n} ? `).appendValue(t.label.true??"Yes",{delimiter:"'"}).append(" : ").appendValue(t.label.false??"No",{delimiter:"'"}).append("}"):e.append(`{${n} ? 'Yes' : 'No'}`);break;case "list":{let r=t.itemLabel!==void 0?kt(t.itemLabel):"item";e.write("<ol>").indent().write(`{${n}.map((${r}, index) => (`).indent().write("<li key={index}>").indent();let i=o.isInline(t.items);i&&e.appendIndentation(),this.writeRenderingSnippet(e,t.items,r),i&&e.newLine(),e.outdent().write("</li>").outdent().write("))}").outdent().write("</ol>");break}case "structure":e.write("<ul>").indent();for(let[r,i]of At(t.attributes))i.private!==true&&(i.optional===true&&(e.write(`{${n}.${r} && (`),e.indent()),this.writeAttributeSnippet(e,{name:r,...i},n),i.optional===true&&(e.outdent(),e.write(")}")));e.outdent().write("</ul>");break;case "union":{let r=!n.includes(".");r&&e.write("<>").indent();for(let[i,a]of Object.entries(t.types))e.write(`{${n}._type === '${i}' && (`).indent(),this.writeRenderingSnippet(e,a,n),e.outdent().write(")}");r&&e.outdent().write("</>");break}}}writeAttributeSnippet(e,t,n){let r=t.type,i=o.escapeEntities(t.label??or(t.name));switch(r.type){case "boolean":case "text":case "number":{e.write("<li>",false).append(`<strong>${i}:</strong> `),this.writeRenderingSnippet(e,r,`${n}.${t.name}`),e.append("</li>").newLine();break}default:e.write("<li>").indent().write(`<strong>${i}</strong>`),this.writeRenderingSnippet(e,r,`${n}.${t.name}`),e.outdent().write("</li>");break}}static escapeEntities(e){return e.replace(/([&"<>])/g,t=>({"&":"&",'"':""","<":"<",">":">"})[t]??t)}createWriter(){return new Fe(this.options.indentationSize)}static replaceVariables(e,t){return e.replace(/%name%/g,o.formatName(t,true)).replace(/%slug%/g,Xs(t))}static formatName(e,t=false){return Fe.formatName(e,t)}static isInline(e){return ["number","text","boolean"].includes(e.type)}};var Rt=class extends Ot{writeSlotHeader(e){switch(this.options.language){case "jsx":e.write("import {useContent} from '@croct/plug-react';");break;case "tsx":e.write("import type {ReactElement} from 'react';"),e.write("import {useContent} from '@croct/plug-react';");break}e.newLine();}writeSlotFetch(e,t){let n=this.options.contentVariable;e.write(`const ${n} = useContent('${t.id}@${t.version}');`).newLine();}isSlotFetchAsync(){return false}isSlotFetchBlocking(){return false}hasSuspenseBoundary(){return false}};var pr=class o extends tt{constructor(e){super(e),this.codemod=e.codemod,this.bundlers=e.bundlers,this.importResolver=e.importResolver;}async generateSlotExampleFiles(e,t){let n=await this.isTypeScriptProject(),r=await this.getPaths(t.configuration),i=this.fileSystem.joinPaths(r.components,`%slug%${n?".tsx":".jsx"}`),a=this.fileSystem.joinPaths(r.examples,`%slug%-example${n?".tsx":".jsx"}`);return new Rt({fileSystem:this.fileSystem,language:await this.isTypeScriptProject()?"tsx":"jsx",contentVariable:"content",slotImportPath:await this.importResolver.getImportPath(i,this.fileSystem.getDirectoryName(a)),slotFilePath:i,slotComponentName:"%name%",pageFilePath:a,pageComponentName:"%name%Example"}).generate({id:e.slug,version:e.version.major,definition:e.resolvedDefinition}).files}async getInstallationPlan(e){let{configuration:t}=e,n=await this.getProjectInfo();return {dependencies:["@croct/plug-react"],tasks:this.getInstallationTasks({...e,project:n}),configuration:t}}async getProjectInfo(){let e="src",t=await this.getEnvVarProperty(),n=this.projectDirectory.get();return {typescript:await this.isTypeScriptProject(),sourceDirectory:e,provider:{file:await this.locateFile(...["App","main","index"].flatMap(r=>["js","jsx","ts","tsx"].map(i=>`${r}.${i}`)).map(r=>this.fileSystem.joinPaths(e,r)))},env:t===null?void 0:{property:t,productionFile:new Qe(this.fileSystem,this.fileSystem.joinPaths(n,".env.production")),developmentFile:new Qe(this.fileSystem,this.fileSystem.joinPaths(n,".env.development"))}}}getInstallationTasks(e){let t=[],n=e.project.env,{configuration:r}=e,i=null,a=()=>(i===null&&(i=Promise.all([this.workspaceApi.getApplication({organizationSlug:r.organization,workspaceSlug:r.workspace,applicationSlug:r.applications.development}),r.applications.production===void 0?null:this.workspaceApi.getApplication({organizationSlug:r.organization,workspaceSlug:r.workspace,applicationSlug:r.applications.production})]).then(([s,p])=>s===null?Promise.reject(new ie(`Development application ${r.applications.development} not found`,{reason:"not_found"})):{development:s.publicId,production:p?.publicId})),i);if(n!==void 0){let{developmentFile:s,productionFile:p,property:c}=n,l=c.split(".").pop();t.push({title:"Setup environment variables",task:async u=>{u.update("Setting up environment variables");try{let g=await a();await Promise.all([s.setVariable(l,g.development),g.production===void 0?Promise.resolve():p.setVariable(l,g.production)]),u.confirm("Environment variables updated");}catch(g){u.alert("Failed to update environment variables",d.formatMessage(g));}}});}return t.push({title:"Configure provider",task:async s=>{s.update("Configuring provider");let p=e.project.provider.file;try{p===null?s.alert("No root component found"):(s.update("Configuring provider"),await this.installProvider(p,{props:{appId:o.getAppIdProperty(await a(),n?.property)}}),s.confirm("Provider configured"));}catch(c){s.alert("Failed to install provider",d.formatMessage(c));}}}),t}async installProvider(e,t){await this.codemod.provider.apply(this.fileSystem.joinPaths(this.projectDirectory.get(),e),t);}async getEnvVarProperty(){for(let e of this.bundlers)if(await this.packageManager.hasDirectDependency(e.package))return `${e.prefix}CROCT_APP_ID`;return null}static getAppIdProperty(e,t){return t!==void 0?{type:"reference",path:t.split(".")}:e.production===void 0?{type:"literal",value:e.development}:{type:"ternary",condition:{operator:"===",left:{type:"reference",path:["process","env","NODE_ENV"]},right:{type:"literal",value:"production"}},consequent:{type:"literal",value:e.production},alternate:{type:"literal",value:e.development}}}};var nt=class o extends d{constructor(e,t={}){super(e,t),Object.setPrototypeOf(this,o.prototype);}},cr=class o extends nt{constructor(e){super(e),Object.setPrototypeOf(this,o.prototype);}};function je(o,e,t){try{return parse$2(o,{...t,sourceType:"module",plugins:[...e,...t?.plugins??[]]})}catch{throw new cr("The source code contains syntax errors.")}}function ep(o){let e={locales:Array()},t;try{t=je(o,["jsx","typescript"]);}catch{return {i18n:e}}return traverse(t,{ObjectProperty:n=>{if(ss(n.node.key)!=="i18n")return n.skip();let r=n.node.value;if(!f.isObjectExpression(r))return n.stop();for(let i of r.properties)if(f.isObjectProperty(i)&&ss(i.key)==="locales"){let a=i.value;if(f.isArrayExpression(a))for(let s of a.elements)s!==null&&f.isStringLiteral(s)&&e.locales.push(s.value);}else if(f.isObjectProperty(i)&&ss(i.key)==="defaultLocale"){let a=i.value;a!==null&&f.isStringLiteral(a)&&(e.defaultLocale=a.value);}return n.stop()}}),{i18n:e}}function ss(o){return f.isIdentifier(o)?o.name:f.isStringLiteral(o)?o.value:null}var lr=class extends Ot{constructor({fileSystem:e,router:t,...n}){super({fileSystem:e,contentVariable:t==="app"?"content":"props",...n}),this.nextOptions={router:t};}writeSlotHeader(e,t){switch(this.options.language){case "jsx":this.nextOptions.router==="app"&&(e.write("import {fetchContent} from '@croct/plug-next/server';"),e.newLine());break;case "tsx":if(e.write("import type {ReactElement} from 'react';"),this.nextOptions.router==="app"&&e.write("import {fetchContent} from '@croct/plug-next/server';"),this.nextOptions.router==="page"){e.write("import type {SlotContent} from '@croct/plug-next';"),e.newLine();let n=Fe.formatName(t.id,true);e.write(`export type ${n}Props = SlotContent<'${t.id}@${t.version}'>;`);}e.newLine();break}}writeSlotFetch(e,t){if(this.nextOptions.router==="app"){let n=this.options.contentVariable;e.write(`const {${n}} = await fetchContent('${t.id}@${t.version}');`).newLine();}}writePageHeader(e,t){if(this.nextOptions.router==="app")return super.writePageHeader(e,t);let n=`${t.definition.id}@${t.definition.version}`;switch(this.options.language){case "jsx":e.write("import {fetchContent} from '@croct/plug-next/server';").write(`import ${t.name} from '${t.importPath}';`),e.newLine().write("export async function getServerSideProps(context) {").indent().write("return {").indent().write(`props: await fetchContent('${n}', {`).indent().write("route: context,").outdent().write("}),").outdent().write("}").outdent().write("}");break;case "tsx":e.write("import type {ReactElement} from 'react';"),e.write("import type {GetServerSideProps} from 'next';"),e.write("import {fetchContent} from '@croct/plug-next/server';"),e.write(`import ${t.name}, {type ${t.name}Props} from '${t.importPath}';`),e.newLine().write("type PageProps = {").indent().write(`content: ${t.name}Props,`).outdent().write("};").newLine().write("export const getServerSideProps: ",false).write("GetServerSideProps<PageProps> = async context => ({").indent().write(`props: await fetchContent('${n}', {`).indent().write("route: context,").outdent().write("}),").outdent().write("});");break}}writePageSignature(e,t){switch(this.nextOptions.router){case "app":super.writePageSignature(e,t);break;case "page":{e.write(this.options.language==="tsx"?"export default function Page({content}: PageProps): ReactElement {":"export default function Page({content}) {");break}}}appendSlotParams(e,t){if(this.nextOptions.router!=="page")return super.appendSlotParams(e,t);let n=Fe.formatName(t.id,true),r=this.options.contentVariable;if(this.options.language==="jsx"){e.append(`(${r})`);return}e.append(`(${r}: ${n}Props)`);}writeSlotRendering(e,t){switch(this.nextOptions.router){case "app":super.writeSlotRendering(e,t);break;case "page":{e.write(`<${t} {...content} />`);break}}}isSlotFetchAsync(){return this.nextOptions.router==="app"}isSlotFetchBlocking(){return this.nextOptions.router==="app"}hasSuspenseBoundary(){return false}};var ae=class o extends d{constructor(e,t=[],n={}){super(e,{...n,details:n.details??t.map(r=>r.detail??r.title)}),Object.setPrototypeOf(this,o.prototype),this.problems=t;}isErrorType(e){return this.problems.some(t=>t.type===e)}isAccessDenied(e){return this.problems.some(t=>t.type==="https://croct.help/api/admin#access-denied"&&(e===void 0||t.reason===e))}};var Ce=(t=>(t.DEVELOPMENT="DEVELOPMENT",t.PRODUCTION="PRODUCTION",t))(Ce||{});(n=>{function o(r){switch(r){case "DEVELOPMENT":return "Development";case "PRODUCTION":return "Production"}}n.getLabel=o;function e(){return Object.values(n).filter(r=>typeof r=="string")}n.all=e;function t(r){let i=r.toUpperCase();if(!n.all().includes(i))throw new Error(`Invalid environment value "${r}".`);return i}n.fromValue=t;})(Ce||={});var fe=(n=>(n.READ_RESOURCES="RESOURCE_READ_ACCESS",n.ISSUE_TOKEN="TOKEN_ISSUE",n.EXPORT_DATA="DATA_EXPORT",n))(fe||{});(n=>{function o(r){switch(r){case "RESOURCE_READ_ACCESS":return "Read resources";case "TOKEN_ISSUE":return "Issue tokens";case "DATA_EXPORT":return "Export data"}}n.getLabel=o;function e(){return Object.values(n).filter(r=>typeof r=="string")}n.all=e;function t(r){let i=r.toUpperCase();if(!n.all().includes(i))throw new Error(`Invalid permission value "${r}".`);return i}n.fromValue=t;})(fe||={});var ur=class extends tt{constructor(e){super(e),this.codemod=e.codemod,this.importResolver=e.importResolver,this.userApi=e.userApi,this.applicationApi=e.applicationApi;}async generateSlotExampleFiles(e,t){let[n,r,i]=await Promise.all([this.detectRouter(),this.isTypeScriptProject(),this.isFallbackMode()]),a=await this.isTypeScriptProject(),s=await this.getPaths(t.configuration),p=this.fileSystem.joinPaths(s.components,`%slug%${a?".tsx":".jsx"}`),c=this.fileSystem.joinPaths(s.examples,"%slug%"),l=await this.importResolver.getImportPath(p,c),u=r?"tsx":"jsx";return (i?new Rt({fileSystem:this.fileSystem,language:u,contentVariable:"content",slotImportPath:l,slotFilePath:p,slotComponentName:"%name%",pageFilePath:this.fileSystem.joinPaths(c,`index${a?".tsx":".jsx"}`),pageComponentName:"Page"}):new lr({fileSystem:this.fileSystem,router:n==="page"?"page":"app",language:u,slotImportPath:l,slotFilePath:p,slotComponentName:"%name%",pageFilePath:this.fileSystem.joinPaths(c,`${n==="page"?"index":"page"}${r?".tsx":".jsx"}`),pageComponentName:"Page"})).generate({id:e.slug,version:e.version.major,definition:e.resolvedDefinition}).files}async getInstallationPlan(e){let{configuration:t,output:n}=e,[{i18n:r},i]=await Promise.all([this.getConfig(),this.getProjectInfo()]);i.fallbackMode&&n.announce({semantics:"warning",title:"Fallback mode",message:"Next.js SDK requires version 13 or newer, so React SDK will be installed instead."});let a=t.locales.filter(c=>r.locales.includes(c)||c===t.defaultLocale),s=a.length>0?a:r.locales,p=r.defaultLocale!==void 0&&s.includes(r.defaultLocale)?r.defaultLocale:t.defaultLocale;return {dependencies:[i.fallbackMode?"@croct/plug-react":"@croct/plug-next"],tasks:this.getInstallationTasks({...e,project:i}),configuration:{...t,locales:s,defaultLocale:p,paths:{...t.paths,examples:i.pageDirectory}}}}async getProjectInfo(){let[e,t,n]=await Promise.all([this.isTypeScriptProject(),this.getPageDirectory(),this.isFallbackMode()]),r={typescript:e,router:await this.detectRouter(t),sourceDirectory:t.startsWith("src")?"src":".",pageDirectory:t},[i,a]=await Promise.all([this.locateFile(...["middleware.js","middleware.ts"].map(c=>this.fileSystem.joinPaths(r.sourceDirectory,c))),this.locateFile(...(r.router==="app"?[this.fileSystem.joinPaths("app","layout"),this.fileSystem.joinPaths("app","layout")]:[this.fileSystem.joinPaths("pages","_app"),this.fileSystem.joinPaths("pages","_app")]).flatMap(c=>["js","jsx","ts","tsx"].map(l=>this.fileSystem.joinPaths(r.sourceDirectory,`${c}.${l}`))))]),s=r.typescript?"ts":"js",p=this.projectDirectory.get();return {...r,fallbackMode:n,env:{localFile:new Qe(this.fileSystem,this.fileSystem.joinPaths(p,".env.local")),developmentFile:new Qe(this.fileSystem,this.fileSystem.joinPaths(p,".env.development")),productionFile:new Qe(this.fileSystem,this.fileSystem.joinPaths(p,".env.production"))},middleware:{file:i??this.fileSystem.joinPaths(r.sourceDirectory,`middleware.${s}`)},provider:{file:a??(r.router==="app"?this.fileSystem.joinPaths(r.sourceDirectory,"app",`layout.${s}x`):this.fileSystem.joinPaths(r.sourceDirectory,"pages",`_app.${s}x`))}}}getInstallationTasks(e){let t=[];return e.project.fallbackMode||t.push({title:"Configure middleware",task:async n=>{n.update("Configuring middleware");try{await this.updateCode(this.codemod.middleware,e.project.middleware.file),n.confirm("Middleware configured");}catch(r){n.alert("Failed to install middleware",d.formatMessage(r));}}}),t.push({title:"Configure provider",task:async n=>{n.update("Configuring provider");try{await this.installProvider({...e,notifier:n}),n.confirm("Provider configured");}catch(r){n.alert("Failed to install provider",d.formatMessage(r));}}}),t.push({title:"Setup environment variables",task:async n=>{n.update("Setting up environment variables");try{await this.updateEnvVariables({...e,notifier:n}),n.confirm("Environment variables updated");}catch(r){n.alert("Failed to update .env.local",d.formatMessage(r));}}}),t}installProvider(e){return this.updateCode(this.getProviderCodemod(e),e.project.provider.file,{typescript:e.project.typescript})}getProviderCodemod(e){return e.project.fallbackMode?this.codemod.fallbackProvider:e.project.router==="app"?this.codemod.appRouterProvider:this.codemod.pageRouterProvider}async updateCode(e,t,n){await e.apply(this.fileSystem.joinPaths(this.projectDirectory.get(),t),n);}async updateEnvVariables(e){let{project:{env:t},configuration:n,notifier:r}=e;r.update("Loading information");let[i,a]=await Promise.all([this.workspaceApi.getApplication({organizationSlug:n.organization,workspaceSlug:n.workspace,applicationSlug:n.applications.development}),n.applications.production===void 0?null:this.workspaceApi.getApplication({organizationSlug:n.organization,workspaceSlug:n.workspace,applicationSlug:n.applications.production})]);if(i===null)throw new ie(`Development application \`${n.applications.development}\` not found.`,{reason:"not_found"});if(!await t.localFile.hasVariable("CROCT_API_KEY")&&e.skipApiKeySetup!==true){let s=await this.userApi.getUser();r.update("Creating API key");let p;try{p=await this.applicationApi.createApiKey({organizationSlug:n.organization,workspaceSlug:n.workspace,applicationSlug:i.slug,name:`${s.username} CLI`,permissions:["TOKEN_ISSUE"]});}catch(c){throw c instanceof d?new ie(c instanceof ae&&c.isAccessDenied()?"Your user does not have permission to create an API key":c.message,c.help):c}await t.localFile.setVariables({CROCT_API_KEY:p.secret});}await Promise.all([t.developmentFile.setVariables({NEXT_PUBLIC_CROCT_APP_ID:i.publicId}),a===null?Promise.resolve():t.productionFile.setVariables({NEXT_PUBLIC_CROCT_APP_ID:a.publicId})]);}async detectRouter(e){return (e??await this.getPageDirectory()).endsWith("pages")?"page":"app"}async getPageDirectory(){return await this.locateFile("app",this.fileSystem.joinPaths("src","app"),"pages",this.fileSystem.joinPaths("src","pages"))??"app"}async getConfig(){let e=["js","mjs","ts","mts"].map(n=>`next.config.${n}`),t=await this.readFile(...e).catch(()=>null);return t===null?{i18n:{locales:[],defaultLocale:""}}:ep(t)}isFallbackMode(){return this.packageManager.hasDirectDependency("next","<=13")}};var lt=(n=>(n.NEXTJS="nextjs",n.REACT="react",n.JAVASCRIPT="javascript",n))(lt||{});(e=>{function o(t){switch(t){case "nextjs":return "Next.js";case "react":return "React";case "javascript":return "JavaScript"}}e.getName=o;})(lt||={});var mr=class o{constructor(e){this.config=e;}async execute(e){let{configurationManager:t,platformProvider:n,sdkProvider:r,io:{output:i}}=this.config;if(e.override!==true&&await t.isInitialized())throw new d("Configuration file already exists, specify `override` to reconfigure.",{reason:"precondition"});let a=await n.get(),s=a!==null?`${lt.getName(a)} project`:"project";i.break(),i.announce({semantics:"neutral",title:"\u{1F44B} Welcome to Croct",alignment:"center",message:`Let's configure your ${s} to get started!`}),i.break();let p=await this.getOrganization({new:e.new==="organization"},e.organization);if(p===null)throw new d(`Organization not found: ${e.organization}`,{reason:"invalid_input"});let c=await this.getWorkspace({organization:p,new:e.new==="workspace"},e.workspace),l={organization:p,workspace:c,platform:a??"javascript",new:e.new==="application"},u=await this.getApplication({...l,environment:"DEVELOPMENT"},e.devApplication),g={organization:p.slug,workspace:c.slug,applications:{development:u.slug},defaultLocale:c.defaultLocale,locales:c.locales,slots:{},components:{}},y=c.website??p.website??void 0;if(y!==void 0&&new URL(y).hostname!=="localhost"){let v=await this.getApplication({...l,environment:"PRODUCTION"},e.prodApplication);g.applications.production=v.slug;}let C=await r.get();if(C===null){await t.update(g),i.warn("No suitable SDK found, skipping project configuration");return}await t.update(await this.configure(C,g,e.skipApiKeySetup===true));}async getOrganization(e,t){let{form:n,api:r}=this.config,i=t===void 0?await n.organization.handle(e):await r.user.getOrganization(t).catch(a=>{if(a instanceof ae&&a.isAccessDenied())return null;throw a});if(i===null)throw new d(`No organization found with slug "${t}".`,{reason:"invalid_input"});return i}async getWorkspace(e,t){let{form:n,api:r}=this.config,i=t===void 0?await n.workspace.handle(e):await r.organization.getWorkspace({organizationSlug:e.organization.slug,workspaceSlug:t}).catch(a=>{if(a instanceof ae&&a.isAccessDenied())return null;throw a});if(i===null)throw new d(`No workspace found with slug "${t}".`,{reason:"invalid_input"});return i}async getApplication(e,t){let{form:n,api:r}=this.config,i=t===void 0?await n.application.handle(e):await r.workspace.getApplication({organizationSlug:e.organization.slug,workspaceSlug:e.workspace.slug,applicationSlug:t}).catch(a=>{if(a instanceof ae&&a.isAccessDenied())return null;throw a});if(i===null)throw new d(`No application found with slug "${t}".`,{reason:"invalid_input"});if(i.environment!==e.environment)throw new d(`No ${Ce.getLabel(e.environment).toUpperCase()} application found with slug "${t}".`,{reason:"invalid_input"});return i}async configure(e,t,n){let{skipConfirmation:r}=this.config,i=await e.setup({input:this.config.io.input===void 0||await r.get()?void 0:this.config.io.input,output:this.config.io.output,skipApiKeySetup:n,configuration:t});return o.canonicalizePaths(i)}static canonicalizePaths(e){return e.paths===void 0?e:{...e,paths:Object.fromEntries(Object.entries(e.paths).map(([t,n])=>[t,o.canonicalizePath(n)]))}}static canonicalizePath(e){return e.replace(/\\/g,"/")}};var dr=class{constructor(e){this.authenticator=e.authenticator;}async execute(e){await this.authenticator.logout(),await this.authenticator.login(e);}};var sn=class{constructor({output:e,authenticator:t}){this.authenticator=t,this.output=e;}async execute(){await this.authenticator.logout(),this.output.confirm("Logged out");}};var ut=class o extends d{constructor(e,t={}){super(e,{...t,reason:t.reason??"invalid_configuration"}),Object.setPrototypeOf(this,o.prototype);}};var gr=class o{static{this.CONFIGURATION_SCHEMA="https://schema.croct.com/json/v1/project.json";}constructor({fileSystem:e,projectDirectory:t,validator:n}){this.fileSystem=e,this.projectDirectory=t,this.validator=n;}isInitialized(){return this.fileSystem.exists(this.getConfigurationFilePath())}async load(){let e=await this.loadConfigurationFile();if(e.configuration===null)throw new ut("Project configuration not found.",{reason:"not_found",suggestions:["Run `init` command to initialize the project"]});return e.configuration}async update(e){return this.updateConfigurationFile(await this.validateConfiguration(e))}async updateConfigurationFile(e){let t=await this.loadConfigurationFile(),r=this.applyConfigurationChanges(t,e).toString({indentationCharacter:"space",object:{indentationSize:2,leadingIndentation:true,trailingIndentation:true,entryIndentation:true,colonSpacing:true,commaSpacing:true},array:{indentationSize:2,entryIndentation:true,leadingIndentation:true,trailingIndentation:true,colonSpacing:true,commaSpacing:true}});try{await this.fileSystem.writeTextFile(t.path,r,{overwrite:!0});}catch{throw new Error(`Unable to write configuration file ${t.path}.`)}return e}applyConfigurationChanges(e,t){if(e.configuration===null||e.source===null)return JsonObjectNode.of({$schema:o.CONFIGURATION_SCHEMA,...t});let n=JsonParser.parse(e.source,JsonObjectNode);return n.update({$schema:n.has("$schema")?n.get("$schema").toJSON():void 0,...t}).cast(JsonObjectNode)}async loadConfigurationFile(){let e={path:this.getConfigurationFilePath(),source:null,configuration:null},t;try{e.source=await this.fileSystem.readTextFile(e.path),t=JsonParser.parse(e.source).toJSON();}catch{return e}return t!==null&&(e.configuration=await this.validateConfiguration(t,e),e.configuration?.$schema!==void 0&&delete e.configuration?.$schema),e}getConfigurationFilePath(){return this.fileSystem.joinPaths(this.projectDirectory.get(),"croct.json")}async validateConfiguration(e,t){let n=await this.validator.validate(e);if(!n.valid){let r=n.violations[0];throw new ut(r.message,{details:[...t!==void 0?[`File: file://${t.path.replace(/\\/g,"/")}`]:[],`Violation path: ${r.path}`]})}return n.data}};var pn=class{constructor(e){this.configuration=e;}async execute(e,...[t]){let{tokenProvider:n,endpoint:r}=this.configuration,i=n!==void 0?await n.getToken():null,a=await fetch(r,{method:"POST",headers:{accept:"application/json","content-type":"application/json",...i!==null?{Authorization:`Bearer ${i}`}:{}},body:JSON.stringify({query:e,variables:t})});return a.json().then(s=>{let{data:p,errors:c}=s;if(c!==void 0)throw new ae(c[0].message.replace(/"/g,"`"),c.map(({extensions:l})=>({...l,detail:l.detail?.replace(/"/g,"`")})));return {data:p,headers:a.headers}})}};function cs(o,e){return o.slice(0,o.indexOf("-",e-1)===e-1?e-1:e)}function*cn({baseName:o,alwaysSuffixed:e=false}){let t=o.normalize("NFD").toLowerCase().replace(/[^a-z ]/g,"").trim().split(/\s+/);t.length===0&&t.push(String.fromCharCode(97+Math.floor(Math.random()*26))+Math.random().toString(36).substring(2,14));let n=t.slice(0,2).join("-");for(e||(yield cs(n,30),n.length<29&&t.length>2&&(yield cs(t.join("-"),30)));;){let r=Math.floor(Math.random()*1e4).toString();yield `${cs(n,30-r.length-1)}-${r}`;}}function mt(o){let{baseName:e,query:t,client:n,alwaysSuffixed:r}=o;return uu({baseName:e,alwaysSuffixed:r},async i=>{let a=[i.next().value,i.next().value,i.next().value],{data:{checkAvailability:s}}=await n.execute(t,{...o.variables??{},slugFirstOption:a[0],slugSecondOption:a[1],slugThirdOption:a[2]}),p=[s.slugFirstOption,s.slugSecondOption,s.slugThirdOption];return a.find((c,l)=>p[l])??null})}async function uu(o,e){let t=cn(o),n;do n=await e(t);while(n===null);return n}var O=class extends String{constructor(e,t){super(e),this.value=e,this.__meta__=t;}toString(){return this.value}},np=new O(`
|
|
163
107
|
query ApplicationSlugAvailability($workspaceId: WorkspaceId!, $slugFirstOption: ReadableId!, $slugSecondOption: ReadableId!, $slugThirdOption: ReadableId!) {
|
|
164
108
|
checkAvailability {
|
|
165
109
|
slugFirstOption: applicationSlug(
|
|
@@ -176,7 +120,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
176
120
|
)
|
|
177
121
|
}
|
|
178
122
|
}
|
|
179
|
-
`),
|
|
123
|
+
`),rp=new O(`
|
|
180
124
|
query Applications($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
|
|
181
125
|
organization(slug: $organizationSlug) {
|
|
182
126
|
workspace(slug: $workspaceSlug) {
|
|
@@ -201,7 +145,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
201
145
|
}
|
|
202
146
|
}
|
|
203
147
|
}
|
|
204
|
-
`),
|
|
148
|
+
`),ip=new O(`
|
|
205
149
|
query Application($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $applicationSlug: ReadableId!) {
|
|
206
150
|
organization(slug: $organizationSlug) {
|
|
207
151
|
workspace(slug: $workspaceSlug) {
|
|
@@ -222,7 +166,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
222
166
|
}
|
|
223
167
|
}
|
|
224
168
|
}
|
|
225
|
-
`),
|
|
169
|
+
`),op=new O(`
|
|
226
170
|
mutation CreateApplication($workspaceId: WorkspaceId!, $payload: CreateWebApplicationPayload!) {
|
|
227
171
|
createWebApplication(workspaceId: $workspaceId, payload: $payload) {
|
|
228
172
|
id
|
|
@@ -239,7 +183,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
239
183
|
}
|
|
240
184
|
}
|
|
241
185
|
}
|
|
242
|
-
`),
|
|
186
|
+
`),ap=new O(`
|
|
243
187
|
mutation CreateApiKey($applicationId: ApplicationId!, $payload: CreateApiKeyPayload!) {
|
|
244
188
|
createApiKey(applicationId: $applicationId, payload: $payload) {
|
|
245
189
|
apiKey {
|
|
@@ -250,7 +194,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
250
194
|
apiKeyValue
|
|
251
195
|
}
|
|
252
196
|
}
|
|
253
|
-
`),
|
|
197
|
+
`),sp=new O(`
|
|
254
198
|
query Audiences($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
|
|
255
199
|
organization(slug: $organizationSlug) {
|
|
256
200
|
workspace(slug: $workspaceSlug) {
|
|
@@ -267,7 +211,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
267
211
|
}
|
|
268
212
|
}
|
|
269
213
|
}
|
|
270
|
-
`),
|
|
214
|
+
`),pp=new O(`
|
|
271
215
|
query Audience($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $audienceSlug: ReadableId!) {
|
|
272
216
|
organization(slug: $organizationSlug) {
|
|
273
217
|
workspace(slug: $workspaceSlug) {
|
|
@@ -280,43 +224,43 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
280
224
|
}
|
|
281
225
|
}
|
|
282
226
|
}
|
|
283
|
-
`),
|
|
227
|
+
`),cp=new O(`
|
|
284
228
|
mutation SignIn($payload: SignInPayload!) {
|
|
285
229
|
signIn(payload: $payload) {
|
|
286
230
|
token
|
|
287
231
|
}
|
|
288
232
|
}
|
|
289
|
-
`),
|
|
233
|
+
`),lp=new O(`
|
|
290
234
|
mutation SignUp($payload: SignUpPayload!) {
|
|
291
235
|
signUp(payload: $payload) {
|
|
292
236
|
userId
|
|
293
237
|
}
|
|
294
238
|
}
|
|
295
|
-
`),
|
|
239
|
+
`),up=new O(`
|
|
296
240
|
mutation IssueToken($payload: IssueTokenPayload!) {
|
|
297
241
|
issueToken(payload: $payload)
|
|
298
242
|
}
|
|
299
|
-
`),
|
|
243
|
+
`),mp=new O(`
|
|
300
244
|
mutation ResetPassword($payload: ResetPasswordPayload!) {
|
|
301
245
|
resetPassword(payload: $payload) {
|
|
302
246
|
token
|
|
303
247
|
}
|
|
304
248
|
}
|
|
305
|
-
`),
|
|
249
|
+
`),dp=new O(`
|
|
306
250
|
mutation RequestPasswordReset($email: String!, $sessionId: UserSessionId) {
|
|
307
251
|
sendResetLink(email: $email, sessionId: $sessionId)
|
|
308
252
|
}
|
|
309
|
-
`),
|
|
253
|
+
`),gp=new O(`
|
|
310
254
|
mutation RetryActivation($email: String!, $sessionId: UserSessionId!) {
|
|
311
255
|
retry {
|
|
312
256
|
accountActivation(sessionId: $sessionId, email: $email)
|
|
313
257
|
}
|
|
314
258
|
}
|
|
315
|
-
`),
|
|
259
|
+
`),fp=new O(`
|
|
316
260
|
mutation CreateSession($redirectDestination: String) {
|
|
317
261
|
createSession(redirectDestination: $redirectDestination)
|
|
318
262
|
}
|
|
319
|
-
`),
|
|
263
|
+
`),yp=new O(`
|
|
320
264
|
mutation CloseSession($sessionId: UserSessionId!) {
|
|
321
265
|
closeSession(sessionId: $sessionId) {
|
|
322
266
|
__typename
|
|
@@ -328,7 +272,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
328
272
|
}
|
|
329
273
|
}
|
|
330
274
|
}
|
|
331
|
-
`),
|
|
275
|
+
`),hp=new O(`
|
|
332
276
|
query Components($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
|
|
333
277
|
organization(slug: $organizationSlug) {
|
|
334
278
|
workspace(slug: $workspaceSlug) {
|
|
@@ -360,7 +304,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
360
304
|
}
|
|
361
305
|
}
|
|
362
306
|
}
|
|
363
|
-
`),
|
|
307
|
+
`),Sp=new O(`
|
|
364
308
|
query Component($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $componentSlug: ReadableId!, $majorVersion: Int) {
|
|
365
309
|
organization(slug: $organizationSlug) {
|
|
366
310
|
workspace(slug: $workspaceSlug) {
|
|
@@ -388,7 +332,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
388
332
|
}
|
|
389
333
|
}
|
|
390
334
|
}
|
|
391
|
-
`),
|
|
335
|
+
`),bp=new O(`
|
|
392
336
|
query Experience($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $experienceId: ExperienceId!) {
|
|
393
337
|
organization(slug: $organizationSlug) {
|
|
394
338
|
workspace(slug: $workspaceSlug) {
|
|
@@ -542,7 +486,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
542
486
|
}
|
|
543
487
|
}
|
|
544
488
|
}
|
|
545
|
-
`),
|
|
489
|
+
`),Ip=new O(`
|
|
546
490
|
query Experiences($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $status: [ExperienceStatus!]) {
|
|
547
491
|
organization(slug: $organizationSlug) {
|
|
548
492
|
workspace(slug: $workspaceSlug) {
|
|
@@ -598,7 +542,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
598
542
|
}
|
|
599
543
|
}
|
|
600
544
|
}
|
|
601
|
-
`),
|
|
545
|
+
`),vp=new O(`
|
|
602
546
|
query ResourceIdQuery($organizationSlug: ReadableId!, $workspaceSlug: ReadableId, $applicationSlug: ReadableId) {
|
|
603
547
|
organization(slug: $organizationSlug) {
|
|
604
548
|
id
|
|
@@ -610,7 +554,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
610
554
|
}
|
|
611
555
|
}
|
|
612
556
|
}
|
|
613
|
-
`),
|
|
557
|
+
`),xp=new O(`
|
|
614
558
|
query Organization($slug: ReadableId!) {
|
|
615
559
|
organization(slug: $slug) {
|
|
616
560
|
id
|
|
@@ -622,7 +566,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
622
566
|
email
|
|
623
567
|
}
|
|
624
568
|
}
|
|
625
|
-
`),
|
|
569
|
+
`),wp=new O(`
|
|
626
570
|
query Organizations {
|
|
627
571
|
organizations(first: 300) {
|
|
628
572
|
edges {
|
|
@@ -638,7 +582,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
638
582
|
}
|
|
639
583
|
}
|
|
640
584
|
}
|
|
641
|
-
`),
|
|
585
|
+
`),Pp=new O(`
|
|
642
586
|
mutation SetupOrganization($payload: CreateConfiguredOrganizationPayload!) {
|
|
643
587
|
createConfiguredOrganization(payload: $payload) {
|
|
644
588
|
organization {
|
|
@@ -652,7 +596,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
652
596
|
}
|
|
653
597
|
}
|
|
654
598
|
}
|
|
655
|
-
`),
|
|
599
|
+
`),Cp=new O(`
|
|
656
600
|
query FindOrganizationSlug($slugFirstOption: ReadableId!, $slugSecondOption: ReadableId!, $slugThirdOption: ReadableId!) {
|
|
657
601
|
checkAvailability {
|
|
658
602
|
slugFirstOption: organizationSlug(slug: $slugFirstOption)
|
|
@@ -660,7 +604,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
660
604
|
slugThirdOption: organizationSlug(slug: $slugThirdOption)
|
|
661
605
|
}
|
|
662
606
|
}
|
|
663
|
-
`),
|
|
607
|
+
`),kp=new O(`
|
|
664
608
|
query OrganizationMetadata($url: String!) {
|
|
665
609
|
websiteMetadata(url: $url) {
|
|
666
610
|
url
|
|
@@ -678,7 +622,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
678
622
|
}
|
|
679
623
|
}
|
|
680
624
|
}
|
|
681
|
-
`),
|
|
625
|
+
`),Ap=new O(`
|
|
682
626
|
query Slots($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
|
|
683
627
|
organization(slug: $organizationSlug) {
|
|
684
628
|
workspace(slug: $workspaceSlug) {
|
|
@@ -724,7 +668,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
724
668
|
}
|
|
725
669
|
}
|
|
726
670
|
}
|
|
727
|
-
`),
|
|
671
|
+
`),Ep=new O(`
|
|
728
672
|
query Slot($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $slotSlug: ReadableId!, $majorVersion: Int) {
|
|
729
673
|
organization(slug: $organizationSlug) {
|
|
730
674
|
workspace(slug: $workspaceSlug) {
|
|
@@ -766,7 +710,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
766
710
|
}
|
|
767
711
|
}
|
|
768
712
|
}
|
|
769
|
-
`),
|
|
713
|
+
`),Op=new O(`
|
|
770
714
|
query SlotStaticContent($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $slotSlug: ReadableId!, $majorVersion: Int) {
|
|
771
715
|
organization(slug: $organizationSlug) {
|
|
772
716
|
workspace(slug: $workspaceSlug) {
|
|
@@ -779,11 +723,11 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
779
723
|
}
|
|
780
724
|
}
|
|
781
725
|
}
|
|
782
|
-
`),
|
|
726
|
+
`),Rp=new O(`
|
|
783
727
|
mutation GenerateTyping($workspaceId: WorkspaceId!, $payload: GenerateTypingPayload!) {
|
|
784
728
|
generateTyping(workspaceId: $workspaceId, payload: $payload)
|
|
785
729
|
}
|
|
786
|
-
`),
|
|
730
|
+
`),Tp=new O(`
|
|
787
731
|
query User {
|
|
788
732
|
userAccount {
|
|
789
733
|
id
|
|
@@ -798,7 +742,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
798
742
|
}
|
|
799
743
|
}
|
|
800
744
|
}
|
|
801
|
-
`),
|
|
745
|
+
`),Dp=new O(`
|
|
802
746
|
query Username($slugFirstOption: ReadableId!, $slugSecondOption: ReadableId!, $slugThirdOption: ReadableId!) {
|
|
803
747
|
checkAvailability {
|
|
804
748
|
slugFirstOption: username(username: $slugFirstOption)
|
|
@@ -806,19 +750,19 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
806
750
|
slugThirdOption: username(username: $slugThirdOption)
|
|
807
751
|
}
|
|
808
752
|
}
|
|
809
|
-
`),
|
|
753
|
+
`),Mp=new O(`
|
|
810
754
|
query UserEmail($email: String!) {
|
|
811
755
|
checkAvailability {
|
|
812
756
|
email(email: $email)
|
|
813
757
|
}
|
|
814
758
|
}
|
|
815
|
-
`),
|
|
759
|
+
`),Np=new O(`
|
|
816
760
|
mutation AcceptInvitation($invitationId: InvitationId!) {
|
|
817
761
|
acceptInvitation(invitationId: $invitationId) {
|
|
818
762
|
id
|
|
819
763
|
}
|
|
820
764
|
}
|
|
821
|
-
`)
|
|
765
|
+
`),$p=new O(`
|
|
822
766
|
query Invitations {
|
|
823
767
|
invitations(first: 100) {
|
|
824
768
|
edges {
|
|
@@ -838,7 +782,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
838
782
|
}
|
|
839
783
|
}
|
|
840
784
|
}
|
|
841
|
-
`),
|
|
785
|
+
`),Lp=new O(`
|
|
842
786
|
query Workspace($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
|
|
843
787
|
organization(slug: $organizationSlug) {
|
|
844
788
|
workspace(slug: $workspaceSlug) {
|
|
@@ -859,7 +803,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
859
803
|
}
|
|
860
804
|
}
|
|
861
805
|
}
|
|
862
|
-
`),
|
|
806
|
+
`),zp=new O(`
|
|
863
807
|
query Workspaces($organizationSlug: ReadableId!) {
|
|
864
808
|
organization(slug: $organizationSlug) {
|
|
865
809
|
workspaces(first: 100) {
|
|
@@ -884,7 +828,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
884
828
|
}
|
|
885
829
|
}
|
|
886
830
|
}
|
|
887
|
-
`)
|
|
831
|
+
`),_p=new O(`
|
|
888
832
|
mutation CreateWorkspace($organizationId: OrganizationId!, $payload: CreateWorkspacePayload!) {
|
|
889
833
|
createWorkspace(organizationId: $organizationId, payload: $payload) {
|
|
890
834
|
id
|
|
@@ -903,7 +847,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
903
847
|
}
|
|
904
848
|
}
|
|
905
849
|
}
|
|
906
|
-
`),
|
|
850
|
+
`),Fp=new O(`
|
|
907
851
|
query FindWorkspaceSlug($organizationId: OrganizationId!, $slugFirstOption: ReadableId!, $slugSecondOption: ReadableId!, $slugThirdOption: ReadableId!) {
|
|
908
852
|
checkAvailability {
|
|
909
853
|
slugFirstOption: workspaceSlug(
|
|
@@ -920,7 +864,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
920
864
|
)
|
|
921
865
|
}
|
|
922
866
|
}
|
|
923
|
-
`),
|
|
867
|
+
`),jp=new O(`
|
|
924
868
|
query WorkspaceFeatures($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
|
|
925
869
|
organization(slug: $organizationSlug) {
|
|
926
870
|
workspace(slug: $workspaceSlug) {
|
|
@@ -946,7 +890,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
946
890
|
}
|
|
947
891
|
}
|
|
948
892
|
}
|
|
949
|
-
`),
|
|
893
|
+
`),Up=new O(`
|
|
950
894
|
mutation CreateResources($workspaceId: WorkspaceId!, $payload: CreateWorkspaceResourcePayload!) {
|
|
951
895
|
createWorkspaceResources(workspaceId: $workspaceId, payload: $payload) {
|
|
952
896
|
slots
|
|
@@ -958,7 +902,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
958
902
|
}
|
|
959
903
|
}
|
|
960
904
|
}
|
|
961
|
-
`);var lu={"\n query ApplicationSlugAvailability(\n $workspaceId: WorkspaceId!\n $slugFirstOption: ReadableId!\n $slugSecondOption: ReadableId!\n $slugThirdOption: ReadableId!\n ) {\n checkAvailability {\n slugFirstOption: applicationSlug(workspaceId: $workspaceId, slug: $slugFirstOption)\n slugSecondOption: applicationSlug(workspaceId: $workspaceId, slug: $slugSecondOption)\n slugThirdOption: applicationSlug(workspaceId: $workspaceId, slug: $slugThirdOption)\n }\n }\n":Xs,"\n query Applications($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n applications(first: 100) {\n edges {\n node {\n id\n publicId\n name\n slug\n logo\n website\n environment\n platform\n applicationStatus\n settings {\n timeZone\n }\n }\n }\n }\n }\n }\n }\n":ep,"\n query Application($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $applicationSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n application(slug: $applicationSlug) {\n id\n publicId\n name\n slug\n logo\n website\n environment\n platform\n applicationStatus\n settings {\n timeZone\n }\n }\n }\n }\n }\n":tp,"\n mutation CreateApplication($workspaceId: WorkspaceId!, $payload: CreateWebApplicationPayload!) {\n createWebApplication(workspaceId: $workspaceId, payload: $payload) {\n id\n publicId\n name\n slug\n logo\n website\n environment\n platform\n applicationStatus\n settings {\n timeZone\n }\n }\n }\n":np,"\n mutation CreateApiKey($applicationId: ApplicationId!, $payload: CreateApiKeyPayload!) {\n createApiKey(applicationId: $applicationId, payload: $payload) {\n apiKey {\n id\n name\n permissions\n }\n apiKeyValue\n }\n }\n":rp,"\n query Audiences($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n audiences(first: 100) {\n edges {\n node {\n id\n customId\n name\n criteria\n }\n }\n }\n }\n }\n }\n":ip,"\n query Audience(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId!,\n $audienceSlug: ReadableId!\n ) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n audience(customId: $audienceSlug) {\n id\n customId\n name\n criteria\n }\n }\n }\n }\n":op,"\n mutation SignIn($payload: SignInPayload!) {\n signIn(payload: $payload) {\n token\n }\n }\n":ap,"\n mutation SignUp($payload: SignUpPayload!) {\n signUp(payload: $payload) {\n userId\n }\n }\n":sp,"\n mutation IssueToken($payload: IssueTokenPayload!) {\n issueToken(payload: $payload) \n }\n":pp,"\n mutation ResetPassword($payload: ResetPasswordPayload!) {\n resetPassword(payload: $payload) {\n token\n }\n }\n":cp,"\n mutation RequestPasswordReset($email: String!, $sessionId: UserSessionId) {\n sendResetLink(email: $email, sessionId: $sessionId)\n }\n":lp,"\n mutation RetryActivation($email: String!, $sessionId: UserSessionId!) {\n retry {\n accountActivation(sessionId: $sessionId, email: $email)\n }\n }\n":up,"\n mutation CreateSession($redirectDestination: String) {\n createSession(redirectDestination: $redirectDestination)\n }\n":mp,"\n mutation CloseSession($sessionId: UserSessionId!) {\n closeSession(sessionId: $sessionId) {\n __typename\n ... on CloseSessionRecoveryGrantedResult {\n recoveryToken\n }\n ... on CloseSessionAccessGrantedResult {\n accessToken\n }\n }\n }\n":dp,"\n query Components($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n components(first: 500) {\n edges {\n node {\n id\n customId\n name\n description\n definition {\n definition,\n version {\n major\n minor\n }\n metadata {\n directReferences\n indirectReferences\n referenceMetadata {\n referenceName\n componentId\n }\n }\n }\n }\n }\n }\n }\n }\n }\n":gp,"\n query Component(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId!,\n $componentSlug: ReadableId!,\n $majorVersion: Int\n ) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n component(customId: $componentSlug) {\n id\n customId\n name\n description\n definition(majorVersion: $majorVersion) {\n definition\n version {\n major\n minor\n }\n metadata {\n directReferences\n indirectReferences\n referenceMetadata {\n referenceName\n componentId\n }\n }\n }\n }\n }\n }\n }\n":fp,"\n query Experience(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId!,\n $experienceId: ExperienceId!\n ) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n experience(id: $experienceId) {\n id,\n name,\n priority,\n status,\n hasExperiments,\n currentExperiment {\n id,\n name,\n crossDevice,\n goalId,\n traffic,\n status,\n variants {\n variantId\n name\n allocation\n baseline\n content {\n default {\n contents {\n slotId,\n content,\n locale,\n }\n },\n segmented {\n groupId,\n contents {\n slotId,\n content,\n locale,\n },\n audiences {\n audienceId\n }\n }\n }\n }\n }\n draft {\n priority,\n audiences {\n id,\n customId,\n },\n slots {\n slot {\n id,\n customId,\n }\n version {\n minor,\n major\n }\n },\n timeZone,\n content {\n default {\n contents {\n slotId,\n content,\n locale,\n }\n },\n segmented {\n groupId,\n contents {\n slotId,\n content,\n locale,\n },\n audiences {\n audienceId\n }\n }\n },\n experiment {\n name,\n crossDevice,\n goalId,\n traffic,\n variants {\n variantId\n name\n allocation\n baseline\n content {\n default {\n contents {\n slotId,\n content,\n locale,\n }\n },\n segmented {\n groupId,\n contents {\n slotId,\n content,\n locale,\n },\n audiences {\n audienceId\n }\n }\n }\n }\n }\n }\n settings {\n content {\n default {\n contents {\n slotId\n content,\n locale,\n }\n },\n segmented {\n groupId,\n contents {\n slotId,\n content,\n locale,\n },\n audiences {\n audienceId\n }\n }\n }\n audiences {\n id,\n customId,\n }\n slots {\n slot {\n id,\n customId,\n }\n version {\n minor,\n major\n }\n }\n }\n }\n }\n }\n }\n":yp,"\n query Experiences($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $status: [ExperienceStatus!]) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n experiences(first: 100, status: $status) {\n edges {\n node {\n id,\n name,\n priority,\n status,\n currentExperiment {\n name,\n },\n draft {\n priority,\n audiences {\n id,\n customId,\n },\n slots {\n slot {\n id,\n customId,\n }\n version {\n minor,\n major\n }\n },\n experiment {\n name,\n }\n }\n settings {\n audiences {\n id,\n customId\n }\n slots {\n slot {\n id,\n customId\n }\n version {\n minor,\n major\n }\n }\n }\n }\n }\n }\n }\n }\n }\n":hp,"\n query ResourceIdQuery(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId,\n $applicationSlug: ReadableId\n ) {\n organization(slug: $organizationSlug) {\n id\n workspace(slug: $workspaceSlug) {\n id\n application(slug: $applicationSlug) {\n id\n }\n }\n }\n }\n":Sp,"\n query Organization($slug: ReadableId!) {\n organization(slug: $slug) {\n id\n name\n slug\n type\n website\n logo\n email\n }\n }\n":bp,"\n query Organizations {\n organizations(first: 300) {\n edges {\n node {\n id\n name\n slug\n type\n website\n logo\n email\n }\n }\n }\n }\n":Ip,"\n mutation SetupOrganization($payload: CreateConfiguredOrganizationPayload!) {\n createConfiguredOrganization(payload: $payload) {\n organization {\n id\n name\n slug\n type\n website\n logo\n email\n }\n }\n }\n":vp,"\n query FindOrganizationSlug(\n $slugFirstOption: ReadableId!\n $slugSecondOption: ReadableId!\n $slugThirdOption: ReadableId!\n ) {\n checkAvailability {\n slugFirstOption: organizationSlug(slug: $slugFirstOption)\n slugSecondOption: organizationSlug(slug: $slugSecondOption)\n slugThirdOption: organizationSlug(slug: $slugThirdOption)\n }\n }\n":xp,"\n query OrganizationMetadata($url: String!) {\n websiteMetadata(url: $url){\n url\n siteName\n domain\n languages\n platform\n technologies {\n name\n }\n logo {\n data\n height\n width\n }\n }\n }\n":wp,"\n query Slots($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n slots(first: 500) {\n edges {\n node {\n id\n customId\n name\n content {\n component {\n customId\n definition {\n version {\n major\n minor\n }\n metadata {\n directReferences\n indirectReferences\n referenceMetadata {\n referenceName\n componentId\n }\n }\n }\n }\n version {\n major\n minor\n }\n componentDefinition {\n resolvedDefinition\n }\n default {\n content\n locale\n }\n }\n }\n }\n }\n }\n }\n }\n":Pp,"\n query Slot(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId!,\n $slotSlug: ReadableId!,\n $majorVersion: Int\n ) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n slot(customId: $slotSlug) {\n id\n customId\n name\n content(majorVersion: $majorVersion) {\n component {\n customId\n definition {\n version {\n major\n minor\n }\n metadata {\n directReferences\n indirectReferences\n referenceMetadata {\n referenceName\n componentId\n }\n }\n }\n }\n version {\n major\n minor\n }\n componentDefinition {\n resolvedDefinition\n }\n default {\n content\n locale\n }\n }\n }\n }\n }\n }\n":Cp,"\n query SlotStaticContent(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId!,\n $slotSlug: ReadableId!\n $majorVersion: Int\n ) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n slot(customId: $slotSlug) {\n staticContent(majorVersion: $majorVersion) {\n locale\n content\n }\n }\n }\n }\n }\n":kp,"\n mutation GenerateTyping($workspaceId: WorkspaceId!, $payload: GenerateTypingPayload!) {\n generateTyping(workspaceId: $workspaceId, payload: $payload)\n }\n":Ap,"\n query User {\n userAccount {\n id\n user {\n username\n email\n profile {\n firstName\n lastName\n expertise\n }\n }\n }\n }\n":Ep,"\n query Username(\n $slugFirstOption: ReadableId!\n $slugSecondOption: ReadableId!\n $slugThirdOption: ReadableId!\n ) {\n checkAvailability {\n slugFirstOption: username(username: $slugFirstOption)\n slugSecondOption: username(username: $slugSecondOption)\n slugThirdOption: username(username: $slugThirdOption)\n }\n }\n":Op,"\n query UserEmail($email: String!) {\n checkAvailability {\n email(email: $email)\n }\n }\n":Rp,"\n mutation AcceptInvitation($invitationId: InvitationId!) {\n acceptInvitation(invitationId: $invitationId) {\n id\n }\n }\n":Tp,"\n query Invitations {\n invitations(first: 100) {\n edges {\n node {\n id\n invitationTime\n organization {\n id\n name\n slug\n type\n website\n logo\n email\n }\n }\n }\n }\n }\n":Dp,"\n query Workspace($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n id\n name\n slug\n logo\n website\n timeZone\n defaultLocale\n locales {\n edges {\n node {\n code\n }\n }\n }\n }\n }\n }\n":Mp,"\n query Workspaces($organizationSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspaces(first: 100) {\n edges {\n node {\n id\n name\n slug\n logo\n website\n timeZone\n defaultLocale\n locales {\n edges {\n node {\n code\n }\n }\n }\n }\n }\n }\n }\n }\n":Np,"\n mutation CreateWorkspace($organizationId: OrganizationId!, $payload: CreateWorkspacePayload!) {\n createWorkspace(organizationId: $organizationId, payload: $payload) {\n id\n name\n slug\n logo\n website\n timeZone\n defaultLocale\n locales {\n edges {\n node {\n code\n }\n }\n }\n }\n }\n":$p,"\n query FindWorkspaceSlug(\n $organizationId: OrganizationId!\n $slugFirstOption: ReadableId!\n $slugSecondOption: ReadableId!\n $slugThirdOption: ReadableId!\n ) {\n checkAvailability {\n slugFirstOption: workspaceSlug(organizationId: $organizationId, slug: $slugFirstOption)\n slugSecondOption: workspaceSlug(organizationId: $organizationId, slug: $slugSecondOption)\n slugThirdOption: workspaceSlug(organizationId: $organizationId, slug: $slugThirdOption)\n }\n }\n":Lp,"\n query WorkspaceFeatures($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n quotas {\n audience\n remainingAudiences\n component\n remainingComponents\n slot\n remainingSlots,\n experience\n remainingExperiences\n experiment\n remainingExperiments\n dynamicAttributesPerContent\n audiencesPerExperience\n }\n capabilities {\n features(requiredFeatures: [\n EXPERIMENT,\n CROSS_DEVICE_EXPERIMENT,\n API_DATA_EXPORT\n ])\n }\n } \n }\n }\n":zp,"\n mutation CreateResources($workspaceId: WorkspaceId!, $payload: CreateWorkspaceResourcePayload!) {\n createWorkspaceResources(workspaceId: $workspaceId, payload: $payload) {\n slots\n components\n audiences\n experiences {\n id,\n experimentId\n }\n }\n }\n":_p};function k(o){return lu[o]??{}}var Fp=k(`
|
|
905
|
+
`);var du={"\n query ApplicationSlugAvailability(\n $workspaceId: WorkspaceId!\n $slugFirstOption: ReadableId!\n $slugSecondOption: ReadableId!\n $slugThirdOption: ReadableId!\n ) {\n checkAvailability {\n slugFirstOption: applicationSlug(workspaceId: $workspaceId, slug: $slugFirstOption)\n slugSecondOption: applicationSlug(workspaceId: $workspaceId, slug: $slugSecondOption)\n slugThirdOption: applicationSlug(workspaceId: $workspaceId, slug: $slugThirdOption)\n }\n }\n":np,"\n query Applications($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n applications(first: 100) {\n edges {\n node {\n id\n publicId\n name\n slug\n logo\n website\n environment\n platform\n applicationStatus\n settings {\n timeZone\n }\n }\n }\n }\n }\n }\n }\n":rp,"\n query Application($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $applicationSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n application(slug: $applicationSlug) {\n id\n publicId\n name\n slug\n logo\n website\n environment\n platform\n applicationStatus\n settings {\n timeZone\n }\n }\n }\n }\n }\n":ip,"\n mutation CreateApplication($workspaceId: WorkspaceId!, $payload: CreateWebApplicationPayload!) {\n createWebApplication(workspaceId: $workspaceId, payload: $payload) {\n id\n publicId\n name\n slug\n logo\n website\n environment\n platform\n applicationStatus\n settings {\n timeZone\n }\n }\n }\n":op,"\n mutation CreateApiKey($applicationId: ApplicationId!, $payload: CreateApiKeyPayload!) {\n createApiKey(applicationId: $applicationId, payload: $payload) {\n apiKey {\n id\n name\n permissions\n }\n apiKeyValue\n }\n }\n":ap,"\n query Audiences($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n audiences(first: 100) {\n edges {\n node {\n id\n customId\n name\n criteria\n }\n }\n }\n }\n }\n }\n":sp,"\n query Audience(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId!,\n $audienceSlug: ReadableId!\n ) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n audience(customId: $audienceSlug) {\n id\n customId\n name\n criteria\n }\n }\n }\n }\n":pp,"\n mutation SignIn($payload: SignInPayload!) {\n signIn(payload: $payload) {\n token\n }\n }\n":cp,"\n mutation SignUp($payload: SignUpPayload!) {\n signUp(payload: $payload) {\n userId\n }\n }\n":lp,"\n mutation IssueToken($payload: IssueTokenPayload!) {\n issueToken(payload: $payload) \n }\n":up,"\n mutation ResetPassword($payload: ResetPasswordPayload!) {\n resetPassword(payload: $payload) {\n token\n }\n }\n":mp,"\n mutation RequestPasswordReset($email: String!, $sessionId: UserSessionId) {\n sendResetLink(email: $email, sessionId: $sessionId)\n }\n":dp,"\n mutation RetryActivation($email: String!, $sessionId: UserSessionId!) {\n retry {\n accountActivation(sessionId: $sessionId, email: $email)\n }\n }\n":gp,"\n mutation CreateSession($redirectDestination: String) {\n createSession(redirectDestination: $redirectDestination)\n }\n":fp,"\n mutation CloseSession($sessionId: UserSessionId!) {\n closeSession(sessionId: $sessionId) {\n __typename\n ... on CloseSessionRecoveryGrantedResult {\n recoveryToken\n }\n ... on CloseSessionAccessGrantedResult {\n accessToken\n }\n }\n }\n":yp,"\n query Components($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n components(first: 500) {\n edges {\n node {\n id\n customId\n name\n description\n definition {\n definition,\n version {\n major\n minor\n }\n metadata {\n directReferences\n indirectReferences\n referenceMetadata {\n referenceName\n componentId\n }\n }\n }\n }\n }\n }\n }\n }\n }\n":hp,"\n query Component(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId!,\n $componentSlug: ReadableId!,\n $majorVersion: Int\n ) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n component(customId: $componentSlug) {\n id\n customId\n name\n description\n definition(majorVersion: $majorVersion) {\n definition\n version {\n major\n minor\n }\n metadata {\n directReferences\n indirectReferences\n referenceMetadata {\n referenceName\n componentId\n }\n }\n }\n }\n }\n }\n }\n":Sp,"\n query Experience(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId!,\n $experienceId: ExperienceId!\n ) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n experience(id: $experienceId) {\n id,\n name,\n priority,\n status,\n hasExperiments,\n currentExperiment {\n id,\n name,\n crossDevice,\n goalId,\n traffic,\n status,\n variants {\n variantId\n name\n allocation\n baseline\n content {\n default {\n contents {\n slotId,\n content,\n locale,\n }\n },\n segmented {\n groupId,\n contents {\n slotId,\n content,\n locale,\n },\n audiences {\n audienceId\n }\n }\n }\n }\n }\n draft {\n priority,\n audiences {\n id,\n customId,\n },\n slots {\n slot {\n id,\n customId,\n }\n version {\n minor,\n major\n }\n },\n timeZone,\n content {\n default {\n contents {\n slotId,\n content,\n locale,\n }\n },\n segmented {\n groupId,\n contents {\n slotId,\n content,\n locale,\n },\n audiences {\n audienceId\n }\n }\n },\n experiment {\n name,\n crossDevice,\n goalId,\n traffic,\n variants {\n variantId\n name\n allocation\n baseline\n content {\n default {\n contents {\n slotId,\n content,\n locale,\n }\n },\n segmented {\n groupId,\n contents {\n slotId,\n content,\n locale,\n },\n audiences {\n audienceId\n }\n }\n }\n }\n }\n }\n settings {\n content {\n default {\n contents {\n slotId\n content,\n locale,\n }\n },\n segmented {\n groupId,\n contents {\n slotId,\n content,\n locale,\n },\n audiences {\n audienceId\n }\n }\n }\n audiences {\n id,\n customId,\n }\n slots {\n slot {\n id,\n customId,\n }\n version {\n minor,\n major\n }\n }\n }\n }\n }\n }\n }\n":bp,"\n query Experiences($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $status: [ExperienceStatus!]) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n experiences(first: 100, status: $status) {\n edges {\n node {\n id,\n name,\n priority,\n status,\n currentExperiment {\n name,\n },\n draft {\n priority,\n audiences {\n id,\n customId,\n },\n slots {\n slot {\n id,\n customId,\n }\n version {\n minor,\n major\n }\n },\n experiment {\n name,\n }\n }\n settings {\n audiences {\n id,\n customId\n }\n slots {\n slot {\n id,\n customId\n }\n version {\n minor,\n major\n }\n }\n }\n }\n }\n }\n }\n }\n }\n":Ip,"\n query ResourceIdQuery(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId,\n $applicationSlug: ReadableId\n ) {\n organization(slug: $organizationSlug) {\n id\n workspace(slug: $workspaceSlug) {\n id\n application(slug: $applicationSlug) {\n id\n }\n }\n }\n }\n":vp,"\n query Organization($slug: ReadableId!) {\n organization(slug: $slug) {\n id\n name\n slug\n type\n website\n logo\n email\n }\n }\n":xp,"\n query Organizations {\n organizations(first: 300) {\n edges {\n node {\n id\n name\n slug\n type\n website\n logo\n email\n }\n }\n }\n }\n":wp,"\n mutation SetupOrganization($payload: CreateConfiguredOrganizationPayload!) {\n createConfiguredOrganization(payload: $payload) {\n organization {\n id\n name\n slug\n type\n website\n logo\n email\n }\n }\n }\n":Pp,"\n query FindOrganizationSlug(\n $slugFirstOption: ReadableId!\n $slugSecondOption: ReadableId!\n $slugThirdOption: ReadableId!\n ) {\n checkAvailability {\n slugFirstOption: organizationSlug(slug: $slugFirstOption)\n slugSecondOption: organizationSlug(slug: $slugSecondOption)\n slugThirdOption: organizationSlug(slug: $slugThirdOption)\n }\n }\n":Cp,"\n query OrganizationMetadata($url: String!) {\n websiteMetadata(url: $url){\n url\n siteName\n domain\n languages\n platform\n technologies {\n name\n }\n logo {\n data\n height\n width\n }\n }\n }\n":kp,"\n query Slots($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n slots(first: 500) {\n edges {\n node {\n id\n customId\n name\n content {\n component {\n customId\n definition {\n version {\n major\n minor\n }\n metadata {\n directReferences\n indirectReferences\n referenceMetadata {\n referenceName\n componentId\n }\n }\n }\n }\n version {\n major\n minor\n }\n componentDefinition {\n resolvedDefinition\n }\n default {\n content\n locale\n }\n }\n }\n }\n }\n }\n }\n }\n":Ap,"\n query Slot(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId!,\n $slotSlug: ReadableId!,\n $majorVersion: Int\n ) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n slot(customId: $slotSlug) {\n id\n customId\n name\n content(majorVersion: $majorVersion) {\n component {\n customId\n definition {\n version {\n major\n minor\n }\n metadata {\n directReferences\n indirectReferences\n referenceMetadata {\n referenceName\n componentId\n }\n }\n }\n }\n version {\n major\n minor\n }\n componentDefinition {\n resolvedDefinition\n }\n default {\n content\n locale\n }\n }\n }\n }\n }\n }\n":Ep,"\n query SlotStaticContent(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId!,\n $slotSlug: ReadableId!\n $majorVersion: Int\n ) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n slot(customId: $slotSlug) {\n staticContent(majorVersion: $majorVersion) {\n locale\n content\n }\n }\n }\n }\n }\n":Op,"\n mutation GenerateTyping($workspaceId: WorkspaceId!, $payload: GenerateTypingPayload!) {\n generateTyping(workspaceId: $workspaceId, payload: $payload)\n }\n":Rp,"\n query User {\n userAccount {\n id\n user {\n username\n email\n profile {\n firstName\n lastName\n expertise\n }\n }\n }\n }\n":Tp,"\n query Username(\n $slugFirstOption: ReadableId!\n $slugSecondOption: ReadableId!\n $slugThirdOption: ReadableId!\n ) {\n checkAvailability {\n slugFirstOption: username(username: $slugFirstOption)\n slugSecondOption: username(username: $slugSecondOption)\n slugThirdOption: username(username: $slugThirdOption)\n }\n }\n":Dp,"\n query UserEmail($email: String!) {\n checkAvailability {\n email(email: $email)\n }\n }\n":Mp,"\n mutation AcceptInvitation($invitationId: InvitationId!) {\n acceptInvitation(invitationId: $invitationId) {\n id\n }\n }\n":Np,"\n query Invitations {\n invitations(first: 100) {\n edges {\n node {\n id\n invitationTime\n organization {\n id\n name\n slug\n type\n website\n logo\n email\n }\n }\n }\n }\n }\n":$p,"\n query Workspace($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n id\n name\n slug\n logo\n website\n timeZone\n defaultLocale\n locales {\n edges {\n node {\n code\n }\n }\n }\n }\n }\n }\n":Lp,"\n query Workspaces($organizationSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspaces(first: 100) {\n edges {\n node {\n id\n name\n slug\n logo\n website\n timeZone\n defaultLocale\n locales {\n edges {\n node {\n code\n }\n }\n }\n }\n }\n }\n }\n }\n":zp,"\n mutation CreateWorkspace($organizationId: OrganizationId!, $payload: CreateWorkspacePayload!) {\n createWorkspace(organizationId: $organizationId, payload: $payload) {\n id\n name\n slug\n logo\n website\n timeZone\n defaultLocale\n locales {\n edges {\n node {\n code\n }\n }\n }\n }\n }\n":_p,"\n query FindWorkspaceSlug(\n $organizationId: OrganizationId!\n $slugFirstOption: ReadableId!\n $slugSecondOption: ReadableId!\n $slugThirdOption: ReadableId!\n ) {\n checkAvailability {\n slugFirstOption: workspaceSlug(organizationId: $organizationId, slug: $slugFirstOption)\n slugSecondOption: workspaceSlug(organizationId: $organizationId, slug: $slugSecondOption)\n slugThirdOption: workspaceSlug(organizationId: $organizationId, slug: $slugThirdOption)\n }\n }\n":Fp,"\n query WorkspaceFeatures($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n quotas {\n audience\n remainingAudiences\n component\n remainingComponents\n slot\n remainingSlots,\n experience\n remainingExperiences\n experiment\n remainingExperiments\n dynamicAttributesPerContent\n audiencesPerExperience\n }\n capabilities {\n features(requiredFeatures: [\n EXPERIMENT,\n CROSS_DEVICE_EXPERIMENT,\n API_DATA_EXPORT\n ])\n }\n } \n }\n }\n":jp,"\n mutation CreateResources($workspaceId: WorkspaceId!, $payload: CreateWorkspaceResourcePayload!) {\n createWorkspaceResources(workspaceId: $workspaceId, payload: $payload) {\n slots\n components\n audiences\n experiences {\n id,\n experimentId\n }\n }\n }\n":Up};function k(o){return du[o]??{}}var Wp=k(`
|
|
962
906
|
query ResourceIdQuery(
|
|
963
907
|
$organizationSlug: ReadableId!,
|
|
964
908
|
$workspaceSlug: ReadableId,
|
|
@@ -974,7 +918,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
974
918
|
}
|
|
975
919
|
}
|
|
976
920
|
}
|
|
977
|
-
`),
|
|
921
|
+
`),Vp=k(`
|
|
978
922
|
query Organization($slug: ReadableId!) {
|
|
979
923
|
organization(slug: $slug) {
|
|
980
924
|
id
|
|
@@ -986,7 +930,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
986
930
|
email
|
|
987
931
|
}
|
|
988
932
|
}
|
|
989
|
-
`),
|
|
933
|
+
`),qp=k(`
|
|
990
934
|
query Organizations {
|
|
991
935
|
organizations(first: 300) {
|
|
992
936
|
edges {
|
|
@@ -1002,7 +946,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1002
946
|
}
|
|
1003
947
|
}
|
|
1004
948
|
}
|
|
1005
|
-
`),
|
|
949
|
+
`),Hp=k(`
|
|
1006
950
|
mutation SetupOrganization($payload: CreateConfiguredOrganizationPayload!) {
|
|
1007
951
|
createConfiguredOrganization(payload: $payload) {
|
|
1008
952
|
organization {
|
|
@@ -1016,7 +960,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1016
960
|
}
|
|
1017
961
|
}
|
|
1018
962
|
}
|
|
1019
|
-
`),
|
|
963
|
+
`),Kp=k(`
|
|
1020
964
|
query FindOrganizationSlug(
|
|
1021
965
|
$slugFirstOption: ReadableId!
|
|
1022
966
|
$slugSecondOption: ReadableId!
|
|
@@ -1028,7 +972,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1028
972
|
slugThirdOption: organizationSlug(slug: $slugThirdOption)
|
|
1029
973
|
}
|
|
1030
974
|
}
|
|
1031
|
-
`),
|
|
975
|
+
`),Gp=k(`
|
|
1032
976
|
query OrganizationMetadata($url: String!) {
|
|
1033
977
|
websiteMetadata(url: $url){
|
|
1034
978
|
url
|
|
@@ -1046,7 +990,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1046
990
|
}
|
|
1047
991
|
}
|
|
1048
992
|
}
|
|
1049
|
-
`);var
|
|
993
|
+
`);var Zp=k(`
|
|
1050
994
|
query User {
|
|
1051
995
|
userAccount {
|
|
1052
996
|
id
|
|
@@ -1061,7 +1005,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1061
1005
|
}
|
|
1062
1006
|
}
|
|
1063
1007
|
}
|
|
1064
|
-
`),
|
|
1008
|
+
`),Jp=k(`
|
|
1065
1009
|
query Username(
|
|
1066
1010
|
$slugFirstOption: ReadableId!
|
|
1067
1011
|
$slugSecondOption: ReadableId!
|
|
@@ -1073,19 +1017,19 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1073
1017
|
slugThirdOption: username(username: $slugThirdOption)
|
|
1074
1018
|
}
|
|
1075
1019
|
}
|
|
1076
|
-
`),
|
|
1020
|
+
`),Qp=k(`
|
|
1077
1021
|
query UserEmail($email: String!) {
|
|
1078
1022
|
checkAvailability {
|
|
1079
1023
|
email(email: $email)
|
|
1080
1024
|
}
|
|
1081
1025
|
}
|
|
1082
|
-
`),
|
|
1026
|
+
`),Bp=k(`
|
|
1083
1027
|
mutation AcceptInvitation($invitationId: InvitationId!) {
|
|
1084
1028
|
acceptInvitation(invitationId: $invitationId) {
|
|
1085
1029
|
id
|
|
1086
1030
|
}
|
|
1087
1031
|
}
|
|
1088
|
-
`),
|
|
1032
|
+
`),Yp=k(`
|
|
1089
1033
|
query Invitations {
|
|
1090
1034
|
invitations(first: 100) {
|
|
1091
1035
|
edges {
|
|
@@ -1105,43 +1049,43 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1105
1049
|
}
|
|
1106
1050
|
}
|
|
1107
1051
|
}
|
|
1108
|
-
`);var
|
|
1052
|
+
`);var Xp=k(`
|
|
1109
1053
|
mutation SignIn($payload: SignInPayload!) {
|
|
1110
1054
|
signIn(payload: $payload) {
|
|
1111
1055
|
token
|
|
1112
1056
|
}
|
|
1113
1057
|
}
|
|
1114
|
-
`),
|
|
1058
|
+
`),ec=k(`
|
|
1115
1059
|
mutation SignUp($payload: SignUpPayload!) {
|
|
1116
1060
|
signUp(payload: $payload) {
|
|
1117
1061
|
userId
|
|
1118
1062
|
}
|
|
1119
1063
|
}
|
|
1120
|
-
`),
|
|
1064
|
+
`),tc=k(`
|
|
1121
1065
|
mutation IssueToken($payload: IssueTokenPayload!) {
|
|
1122
1066
|
issueToken(payload: $payload)
|
|
1123
1067
|
}
|
|
1124
|
-
`),
|
|
1068
|
+
`),nc=k(`
|
|
1125
1069
|
mutation ResetPassword($payload: ResetPasswordPayload!) {
|
|
1126
1070
|
resetPassword(payload: $payload) {
|
|
1127
1071
|
token
|
|
1128
1072
|
}
|
|
1129
1073
|
}
|
|
1130
|
-
`),
|
|
1074
|
+
`),rc=k(`
|
|
1131
1075
|
mutation RequestPasswordReset($email: String!, $sessionId: UserSessionId) {
|
|
1132
1076
|
sendResetLink(email: $email, sessionId: $sessionId)
|
|
1133
1077
|
}
|
|
1134
|
-
`),
|
|
1078
|
+
`),ic=k(`
|
|
1135
1079
|
mutation RetryActivation($email: String!, $sessionId: UserSessionId!) {
|
|
1136
1080
|
retry {
|
|
1137
1081
|
accountActivation(sessionId: $sessionId, email: $email)
|
|
1138
1082
|
}
|
|
1139
1083
|
}
|
|
1140
|
-
`),
|
|
1084
|
+
`),oc=k(`
|
|
1141
1085
|
mutation CreateSession($redirectDestination: String) {
|
|
1142
1086
|
createSession(redirectDestination: $redirectDestination)
|
|
1143
1087
|
}
|
|
1144
|
-
`),
|
|
1088
|
+
`),ac=k(`
|
|
1145
1089
|
mutation CloseSession($sessionId: UserSessionId!) {
|
|
1146
1090
|
closeSession(sessionId: $sessionId) {
|
|
1147
1091
|
__typename
|
|
@@ -1153,7 +1097,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1153
1097
|
}
|
|
1154
1098
|
}
|
|
1155
1099
|
}
|
|
1156
|
-
`);var
|
|
1100
|
+
`);var ln=class o{constructor(e){this.client=e;}async getUser(){let{data:e}=await this.client.execute(Zp),{id:t,user:n}=e.userAccount,{profile:{lastName:r=null}}=n;return {id:t,username:n.profile.firstName,email:n.email,firstName:n.profile.firstName,expertise:n.profile.expertise,...r!==null?{lastName:r}:{}}}async isEmailRegistered(e){let{data:t}=await this.client.execute(Qp,{email:e});return !t.checkAvailability.email}async requestPasswordReset(e){await this.client.execute(rc,{email:e.email,sessionId:e.sessionId});}async resetPassword(e){let{data:t}=await this.client.execute(nc,{payload:{password:e.password,token:e.token}});return t.resetPassword.token}async retryActivation(e){await this.client.execute(ic,{email:e.email,sessionId:e.sessionId});}async registerUser(e){await this.client.execute(ec,{payload:{username:await this.generateUsername(`${e.firstName} ${e.lastName??""}`.trim()),email:e.email,password:e.password,firstName:e.firstName,lastName:e.lastName,expertise:e.expertise,sessionId:e.sessionId,bypassOnboarding:true}});}async createSession(e){let{data:t}=await this.client.execute(oc,{redirectDestination:e?.destination});return t.createSession}async closeSession(e){let{data:t}=await this.client.execute(ac,{sessionId:e});switch(t.closeSession.__typename){case "CloseSessionAccessGrantedResult":return {status:"access-granted",accessToken:t.closeSession.accessToken};case "CloseSessionRecoveryGrantedResult":return {status:"recovery-granted",recoveryToken:t.closeSession.recoveryToken};case "CloseSessionPendingResult":return {status:"pending"}}}async signIn(e){let{data:t}=await this.client.execute(Xp,{payload:{email:e.email,password:e.password,duration:e.duration,remember:false}});return t.signIn.token}async issueToken(e){let{data:t}=await this.client.execute(tc,{payload:{duration:e.duration}});return t.issueToken}async getOrganization(e){let{data:t}=await this.client.execute(Vp,{slug:e}),n=t.organization??null;return n===null?null:o.normalizeOrganization(n)}async getOrganizations(){let{data:e}=await this.client.execute(qp);return (e.organizations.edges??[]).flatMap(n=>{let r=n?.node??null;return r===null||r.slug==="demo"?[]:[o.normalizeOrganization(r)]})}async setupOrganization(e){let{data:t}=await this.client.execute(Hp,{payload:await this.getOrganizationSetupPayload(e)}),{organization:n}=t.createConfiguredOrganization,{logo:r=null,website:i=null}=n;return {id:n.id,name:n.name,slug:n.slug,type:n.type,email:n.email,...r!==null?{logo:r}:{},...i!==null?{website:i}:{}}}async getOrganizationSetupPayload(e){let t=new URL(e.website),n=await this.getUser(),r=`${n.firstName} ${n.lastName??""}`.trim();if(t.hostname.toLowerCase()==="localhost")return {locale:e.locale,timeZone:e.timeZone,acceptedTerms:true,organization:{website:t.origin,email:n.email,name:"Personal organization",slug:await this.generateOrganizationSlug(r,true),type:"PERSONAL"},workspace:{name:"Personal workspace",slug:cn({baseName:r,alwaysSuffixed:true}).next().value,website:t.origin},applications:[{environment:"DEVELOPMENT",name:"Website",slug:"website-dev",website:t.origin,platform:"JAVASCRIPT"}],audiences:[],components:[],experiences:[],slots:[],redirectUrl:e.redirectUrl};let i=await this.getOrganizationMetadata(t),a=`${t.protocol}//${i.domain}`,s=i.logo!==null&&i.logo!==void 0&&i.logo.width>=64&&i.logo.height>=64?i.logo.data:void 0;return {locale:i.languages[0]??e.locale,timeZone:e.timeZone,acceptedTerms:true,organization:{website:a,email:n.email,name:i.siteName,slug:await this.generateOrganizationSlug(i.siteName,false),type:"BUSINESS",logo:s},workspace:{name:i.siteName,slug:cn({baseName:i.siteName,alwaysSuffixed:false}).next().value,logo:s,website:a},applications:[{environment:"PRODUCTION",name:"Website",slug:"website-prod",website:t.origin,platform:i.platform},{environment:"DEVELOPMENT",name:"Website",slug:"website-dev",website:t.origin,platform:i.platform}],audiences:[],components:[],experiences:[],slots:[],redirectUrl:e.redirectUrl}}async getInvitations(){let{data:e}=await this.client.execute(Yp);return (e.invitations.edges??[]).flatMap(n=>{let r=n?.node??null;return r===null?[]:[{id:r.id,invitationTime:r.invitationTime,organization:o.normalizeOrganization(r.organization)}]})}async acceptInvitation(e){await this.client.execute(Bp,{invitationId:e});}static normalizeOrganization(e){let{logo:t=null,website:n=null}=e;return {id:e.id,name:e.name,slug:e.slug,type:e.type,email:e.email,...t!==null?{logo:t}:{},...n!==null?{website:n}:{}}}async getOrganizationMetadata(e){let{data:t}=await this.client.execute(Gp,{url:e.toString()});return t.websiteMetadata}generateOrganizationSlug(e,t=false){return mt({query:Kp,baseName:e,client:this.client,alwaysSuffixed:t})}generateUsername(e){return mt({query:Jp,baseName:e,client:this.client,alwaysSuffixed:false})}};var sc=k(`
|
|
1157
1101
|
query Workspace($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
|
|
1158
1102
|
organization(slug: $organizationSlug) {
|
|
1159
1103
|
workspace(slug: $workspaceSlug) {
|
|
@@ -1174,7 +1118,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1174
1118
|
}
|
|
1175
1119
|
}
|
|
1176
1120
|
}
|
|
1177
|
-
`),
|
|
1121
|
+
`),pc=k(`
|
|
1178
1122
|
query Workspaces($organizationSlug: ReadableId!) {
|
|
1179
1123
|
organization(slug: $organizationSlug) {
|
|
1180
1124
|
workspaces(first: 100) {
|
|
@@ -1199,7 +1143,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1199
1143
|
}
|
|
1200
1144
|
}
|
|
1201
1145
|
}
|
|
1202
|
-
`),
|
|
1146
|
+
`),cc=k(`
|
|
1203
1147
|
mutation CreateWorkspace($organizationId: OrganizationId!, $payload: CreateWorkspacePayload!) {
|
|
1204
1148
|
createWorkspace(organizationId: $organizationId, payload: $payload) {
|
|
1205
1149
|
id
|
|
@@ -1218,7 +1162,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1218
1162
|
}
|
|
1219
1163
|
}
|
|
1220
1164
|
}
|
|
1221
|
-
`),
|
|
1165
|
+
`),lc=k(`
|
|
1222
1166
|
query FindWorkspaceSlug(
|
|
1223
1167
|
$organizationId: OrganizationId!
|
|
1224
1168
|
$slugFirstOption: ReadableId!
|
|
@@ -1231,7 +1175,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1231
1175
|
slugThirdOption: workspaceSlug(organizationId: $organizationId, slug: $slugThirdOption)
|
|
1232
1176
|
}
|
|
1233
1177
|
}
|
|
1234
|
-
`),
|
|
1178
|
+
`),uc=k(`
|
|
1235
1179
|
query WorkspaceFeatures($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
|
|
1236
1180
|
organization(slug: $organizationSlug) {
|
|
1237
1181
|
workspace(slug: $workspaceSlug) {
|
|
@@ -1259,7 +1203,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1259
1203
|
}
|
|
1260
1204
|
}
|
|
1261
1205
|
}
|
|
1262
|
-
`),
|
|
1206
|
+
`),mc=k(`
|
|
1263
1207
|
mutation CreateResources($workspaceId: WorkspaceId!, $payload: CreateWorkspaceResourcePayload!) {
|
|
1264
1208
|
createWorkspaceResources(workspaceId: $workspaceId, payload: $payload) {
|
|
1265
1209
|
slots
|
|
@@ -1271,7 +1215,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1271
1215
|
}
|
|
1272
1216
|
}
|
|
1273
1217
|
}
|
|
1274
|
-
`);var
|
|
1218
|
+
`);var fr=class o{constructor(e,t){this.client=e,this.hierarchyResolver=t;}async getWorkspace(e){let{data:t}=await this.client.execute(sc,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),n=t.organization?.workspace??null;return n===null?null:o.normalizeWorkspace(n)}async getWorkspaces(e){let{data:t}=await this.client.execute(pc,{organizationSlug:e.organizationSlug});return (t.organization?.workspaces.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeWorkspace(i)]})}static normalizeWorkspace(e){let{logo:t=null,website:n=null,locales:{edges:r=[]}}=e;return {id:e.id,name:e.name,slug:e.slug,timeZone:e.timeZone,defaultLocale:e.defaultLocale,locales:r?.flatMap(i=>{let a=i?.node?.code??null;return a===null?[]:[a]})??[],...t!==null?{logo:t}:{},...n!==null?{website:n}:{}}}async createWorkspace(e){let t=await this.hierarchyResolver.getHierarchy({organizationSlug:e.organizationSlug}),{data:n}=await this.client.execute(cc,{organizationId:t.organizationId,payload:{name:e.name,slug:await this.generateWorkspaceSlug(t.organizationId,e.name),timeZone:e.timeZone,defaultLocale:e.defaultLocale,website:e.website}}),r=n.createWorkspace,{logo:i=null,website:a=null,locales:{edges:s=[]}}=r;return {id:r.id,name:r.name,slug:r.slug,timeZone:r.timeZone,defaultLocale:r.defaultLocale,locales:s?.flatMap(p=>{let c=p?.node?.code??null;return c===null?[]:[c]})??[],...i!==null?{logo:i}:{},...a!==null?{website:a}:{}}}generateWorkspaceSlug(e,t){return mt({query:lc,baseName:t,client:this.client,variables:{organizationId:e}})}};var dc=k(`
|
|
1275
1219
|
query Audiences($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
|
|
1276
1220
|
organization(slug: $organizationSlug) {
|
|
1277
1221
|
workspace(slug: $workspaceSlug) {
|
|
@@ -1288,7 +1232,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1288
1232
|
}
|
|
1289
1233
|
}
|
|
1290
1234
|
}
|
|
1291
|
-
`),
|
|
1235
|
+
`),gc=k(`
|
|
1292
1236
|
query Audience(
|
|
1293
1237
|
$organizationSlug: ReadableId!,
|
|
1294
1238
|
$workspaceSlug: ReadableId!,
|
|
@@ -1305,7 +1249,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1305
1249
|
}
|
|
1306
1250
|
}
|
|
1307
1251
|
}
|
|
1308
|
-
`);var
|
|
1252
|
+
`);var fc=k(`
|
|
1309
1253
|
query Slots($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
|
|
1310
1254
|
organization(slug: $organizationSlug) {
|
|
1311
1255
|
workspace(slug: $workspaceSlug) {
|
|
@@ -1351,7 +1295,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1351
1295
|
}
|
|
1352
1296
|
}
|
|
1353
1297
|
}
|
|
1354
|
-
`),
|
|
1298
|
+
`),yc=k(`
|
|
1355
1299
|
query Slot(
|
|
1356
1300
|
$organizationSlug: ReadableId!,
|
|
1357
1301
|
$workspaceSlug: ReadableId!,
|
|
@@ -1398,7 +1342,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1398
1342
|
}
|
|
1399
1343
|
}
|
|
1400
1344
|
}
|
|
1401
|
-
`),
|
|
1345
|
+
`),hc=k(`
|
|
1402
1346
|
query SlotStaticContent(
|
|
1403
1347
|
$organizationSlug: ReadableId!,
|
|
1404
1348
|
$workspaceSlug: ReadableId!,
|
|
@@ -1416,7 +1360,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1416
1360
|
}
|
|
1417
1361
|
}
|
|
1418
1362
|
}
|
|
1419
|
-
`);var
|
|
1363
|
+
`);var Sc=k(`
|
|
1420
1364
|
query ApplicationSlugAvailability(
|
|
1421
1365
|
$workspaceId: WorkspaceId!
|
|
1422
1366
|
$slugFirstOption: ReadableId!
|
|
@@ -1429,7 +1373,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1429
1373
|
slugThirdOption: applicationSlug(workspaceId: $workspaceId, slug: $slugThirdOption)
|
|
1430
1374
|
}
|
|
1431
1375
|
}
|
|
1432
|
-
`),
|
|
1376
|
+
`),bc=k(`
|
|
1433
1377
|
query Applications($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
|
|
1434
1378
|
organization(slug: $organizationSlug) {
|
|
1435
1379
|
workspace(slug: $workspaceSlug) {
|
|
@@ -1454,7 +1398,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1454
1398
|
}
|
|
1455
1399
|
}
|
|
1456
1400
|
}
|
|
1457
|
-
`),
|
|
1401
|
+
`),Ic=k(`
|
|
1458
1402
|
query Application($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $applicationSlug: ReadableId!) {
|
|
1459
1403
|
organization(slug: $organizationSlug) {
|
|
1460
1404
|
workspace(slug: $workspaceSlug) {
|
|
@@ -1475,7 +1419,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1475
1419
|
}
|
|
1476
1420
|
}
|
|
1477
1421
|
}
|
|
1478
|
-
`),
|
|
1422
|
+
`),vc=k(`
|
|
1479
1423
|
mutation CreateApplication($workspaceId: WorkspaceId!, $payload: CreateWebApplicationPayload!) {
|
|
1480
1424
|
createWebApplication(workspaceId: $workspaceId, payload: $payload) {
|
|
1481
1425
|
id
|
|
@@ -1492,7 +1436,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1492
1436
|
}
|
|
1493
1437
|
}
|
|
1494
1438
|
}
|
|
1495
|
-
`),
|
|
1439
|
+
`),xc=k(`
|
|
1496
1440
|
mutation CreateApiKey($applicationId: ApplicationId!, $payload: CreateApiKeyPayload!) {
|
|
1497
1441
|
createApiKey(applicationId: $applicationId, payload: $payload) {
|
|
1498
1442
|
apiKey {
|
|
@@ -1503,7 +1447,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1503
1447
|
apiKeyValue
|
|
1504
1448
|
}
|
|
1505
1449
|
}
|
|
1506
|
-
`);var
|
|
1450
|
+
`);var wc=k(`
|
|
1507
1451
|
query Components($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
|
|
1508
1452
|
organization(slug: $organizationSlug) {
|
|
1509
1453
|
workspace(slug: $workspaceSlug) {
|
|
@@ -1535,7 +1479,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1535
1479
|
}
|
|
1536
1480
|
}
|
|
1537
1481
|
}
|
|
1538
|
-
`),
|
|
1482
|
+
`),Pc=k(`
|
|
1539
1483
|
query Component(
|
|
1540
1484
|
$organizationSlug: ReadableId!,
|
|
1541
1485
|
$workspaceSlug: ReadableId!,
|
|
@@ -1568,7 +1512,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1568
1512
|
}
|
|
1569
1513
|
}
|
|
1570
1514
|
}
|
|
1571
|
-
`);var
|
|
1515
|
+
`);var Cc=k(`
|
|
1572
1516
|
query Experience(
|
|
1573
1517
|
$organizationSlug: ReadableId!,
|
|
1574
1518
|
$workspaceSlug: ReadableId!,
|
|
@@ -1726,7 +1670,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1726
1670
|
}
|
|
1727
1671
|
}
|
|
1728
1672
|
}
|
|
1729
|
-
`),
|
|
1673
|
+
`),kc=k(`
|
|
1730
1674
|
query Experiences($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $status: [ExperienceStatus!]) {
|
|
1731
1675
|
organization(slug: $organizationSlug) {
|
|
1732
1676
|
workspace(slug: $workspaceSlug) {
|
|
@@ -1782,23 +1726,23 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1782
1726
|
}
|
|
1783
1727
|
}
|
|
1784
1728
|
}
|
|
1785
|
-
`);var
|
|
1729
|
+
`);var Ac=k(`
|
|
1786
1730
|
mutation GenerateTyping($workspaceId: WorkspaceId!, $payload: GenerateTypingPayload!) {
|
|
1787
1731
|
generateTyping(workspaceId: $workspaceId, payload: $payload)
|
|
1788
1732
|
}
|
|
1789
|
-
`);function Tt(o){return {model:o,api:Object.fromEntries(Object.entries(o).map(([e,t])=>[t,e]))}}var ps=Tt({javascript:"JAVASCRIPT",react:"REACT",nextjs:"NEXT"}),cs=Tt({DEVELOPMENT:"DEVELOPMENT",PRODUCTION:"PRODUCTION"}),Cc=Tt({NEVER_RECEIVED_TRAFFIC:"NEVER_RECEIVED_TRAFFIC",NOT_RECEIVING_TRAFFIC:"NOT_RECEIVING_TRAFFIC",RECEIVING_TRAFFIC:"RECEIVING_TRAFFIC"}),du=Tt({PLUG_JS:"PLUG_JS"}),ls=Tt({DRAFT:"DRAFT",ACTIVE:"ACTIVE",SCHEDULED:"SCHEDULED",PAUSED:"PAUSED",ARCHIVED:"ARCHIVED"}),gu=Tt({DRAFT:"DRAFT",ACTIVE:"ACTIVE",SCHEDULED:"SCHEDULED",PAUSED:"PAUSED",FINISHED:"FINISHED",INDIRECTLY_PAUSED:"INDIRECTLY_PAUSED"}),fr=class o{constructor(e,t){this.client=e,this.hierarchyResolver=t;}async getFeatures(e){let{data:t}=await this.client.execute(pc,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),n=t.organization?.workspace??null;if(n===null)return null;let{quotas:r,capabilities:{features:i}}=n;return {quotas:{audiences:r.audience,remainingAudiences:r.remainingAudiences,components:r.component,remainingComponents:r.remainingComponents,slots:r.slot,remainingSlots:r.remainingSlots,experiences:r.experience,remainingExperiences:r.remainingExperiences,experiments:r.experiment,remainingExperiments:r.remainingExperiments,dynamicAttributesPerContent:r.dynamicAttributesPerContent,audiencesPerExperience:r.audiencesPerExperience},features:{crossDevice:i.includes("CROSS_DEVICE_EXPERIMENT"),dataExport:i.includes("API_DATA_EXPORT")}}}async getApplications(e){let{data:t}=await this.client.execute(yc,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.applications.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeApplication(i)]})}async getApplication(e){let{data:t}=await this.client.execute(hc,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,applicationSlug:e.applicationSlug}),n=t.organization?.workspace?.application??null;return n===null?null:o.normalizeApplication(n)}static normalizeApplication(e){let{logo:t=null}=e;return {id:e.id,name:e.name,slug:e.slug,timeZone:e.settings.timeZone,website:e.website,environment:cs.api[e.environment],platform:ps.api[e.platform??"JAVASCRIPT"],publicId:e.publicId,trafficStatus:Cc.api[e.applicationStatus],...t!==null?{logo:t}:{}}}async createApplication(e){let t=await this.hierarchyResolver.getHierarchy({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),{data:n}=await this.client.execute(Sc,{workspaceId:t.workspaceId,payload:{name:e.name,website:e.website,environment:cs.model[e.environment],platform:ps.model[e.platform],timeZone:e.timeZone,slug:await this.generateApplicationSlug(t.workspaceId,e.name,e.environment)}}),r=n.createWebApplication,{logo:i=null}=r;return {id:r.id,name:r.name,slug:r.slug,timeZone:r.settings.timeZone,website:r.website,environment:cs.api[r.environment],platform:ps.api[r.platform??"JAVASCRIPT"],publicId:r.publicId,trafficStatus:Cc.api[r.applicationStatus],...i!==null?{logo:i}:{}}}async getAudiences(e){let{data:t}=await this.client.execute(lc,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.audiences.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeAudience(i)]})}async getAudience(e){let{data:t}=await this.client.execute(uc,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,audienceSlug:e.audienceSlug}),n=t.organization?.workspace?.audience??null;return n===null?null:o.normalizeAudience(n)}static normalizeAudience(e){return {id:e.id,name:e.name,slug:e.customId,criteria:e.criteria}}async getComponents(e){let{data:t}=await this.client.execute(Ic,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.components.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeComponent(i)]})}async getComponent(e){let{data:t}=await this.client.execute(vc,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,componentSlug:e.componentSlug,majorVersion:e.majorVersion}),n=t.organization?.workspace?.component??null;return n===null?null:o.normalizeComponent(n)}static normalizeComponent(e){let{definition:t,metadata:{directReferences:n,indirectReferences:r,referenceMetadata:i}}=e.definition,a=e.description??null;return {id:e.id,name:e.name,slug:e.customId,...a!==null?{description:a}:{},definition:t,version:{major:e.definition.version.major,minor:e.definition.version.minor},metadata:{directReferences:n.map(s=>i.find(({componentId:p})=>p===s)?.referenceName??s),indirectReferences:r.map(s=>i.find(({componentId:p})=>p===s)?.referenceName??s)}}}async getSlots(e){let{data:t}=await this.client.execute(mc,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.slots.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeSlot(i)]})}async getSlot(e){let{data:t}=await this.client.execute(dc,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,slotSlug:e.slotSlug,majorVersion:e.majorVersion}),n=t.organization?.workspace?.slot??null;return n===null?null:o.normalizeSlot(n)}static normalizeSlot(e){let{component:t=null}=e.content,n=t?.definition.metadata??null;return {id:e.id,name:e.name,slug:e.customId,...t!==null&&n!==null?{component:{slug:t.customId,version:{major:t.definition.version.major,minor:t.definition.version.minor},metadata:{directReferences:n.directReferences.map(r=>n.referenceMetadata.find(({componentId:i})=>i===r)?.referenceName??r),indirectReferences:n.indirectReferences.map(r=>n.referenceMetadata.find(({componentId:i})=>i===r)?.referenceName??r)}}}:{},version:{major:e.content.version.major,minor:e.content.version.minor},resolvedDefinition:e.content.componentDefinition.resolvedDefinition,content:Object.fromEntries(e.content.default.map(({locale:r,content:i})=>[r,i]))}}async getSlotStaticContent(e,t){let{data:n}=await this.client.execute(gc,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,slotSlug:e.slotSlug,majorVersion:t});return (n.organization?.workspace?.slot?.staticContent??[]).map(i=>({locale:i.locale,content:i.content}))}async generateTypes(e){let t=await this.hierarchyResolver.getHierarchy({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),{data:n}=await this.client.execute(Pc,{workspaceId:t.workspaceId,payload:{target:du.model[e.target],components:e.components,slots:e.slots}});return n.generateTyping}async getExperiences(e){let{data:t}=await this.client.execute(wc,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,status:e.status===void 0?void 0:(Array.isArray(e.status)?e.status:[e.status]).map(r=>ls.model[r])});return (t.organization?.workspace?.experiences.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeExperience(i)]})}async getExperience(e){let{data:t}=await this.client.execute(xc,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,experienceId:e.experienceId}),n=t.organization?.workspace?.experience??null;return n===null?null:o.normalizeExperienceDetails(n)}static normalizeExperience(e){let t=e.settings?.audiences??e.draft?.audiences??[],n=e.settings?.slots??e.draft?.slots??[],r=e.currentExperiment?.name??e.draft?.experiment?.name??null;return {id:e.id,name:e.name,priority:e.priority??e.draft?.priority??0,status:ls.api[e.status],audiences:t.map(i=>i.customId),slots:n.flatMap(({slot:i=null})=>i===null?[]:[i.customId]),...r!==null?{experiment:{name:r}}:{}}}static normalizeExperienceDetails(e){let t=e.settings?.audiences??e.draft?.audiences??[],n=e.settings?.slots??e.draft?.slots??[],r=e.currentExperiment??e.draft?.experiment??null,{name:i=null,goalId:a=null,crossDevice:s=null,traffic:p=null}=r??{},c=Object.fromEntries(n.flatMap(({slot:l=null})=>l===null?[]:[[l.id,l.customId]]));return {id:e.id,name:e.name,priority:e.priority??e.draft?.priority??0,status:ls.api[e.status],hasExperiments:e.hasExperiments,audiences:t.map(l=>l.customId),slots:Object.values(c),...r!==null?{experiment:{...i!==null?{name:i}:{},...a!==null?{goalId:a}:{},...s!==null?{crossDevice:s}:{},...p!==null?{traffic:p}:{},..."status"in r?{status:gu.api[r.status]}:{},variants:(r.variants??[]).map(l=>{let u=l.variantId,g=l.name??null,y=l.allocation??null;return {...u!==null?{id:u}:{},...g!==null?{name:g}:{},...y!==null?{allocation:y}:{},baseline:l.baseline===true,content:{default:o.normalizeLocalizedContent(l.content?.default.contents??[],c),segmented:(l.content?.segmented??[]).map(C=>({id:C.groupId,audiences:C.audiences.map(v=>v.audienceId),content:o.normalizeLocalizedContent(C.contents,c)}))}}})}}:{},content:{default:o.normalizeLocalizedContent(e.settings?.content.default.contents??e.draft?.content?.default.contents??[],c),segmented:(e.settings?.content.segmented??e.draft?.content?.segmented??[]).map(l=>({id:l.groupId,audiences:l.audiences.map(({audienceId:u})=>t.find(({id:g})=>g===u)?.customId??u),content:o.normalizeLocalizedContent(l.contents,c)}))}}}static normalizeLocalizedContent(e,t){let n={};for(let r of e){let{locale:i,slotId:a}=r,s=t[a];s!==void 0&&(n[s]===void 0&&(n[s]={}),n[s][i]=r.content);}return n}async createResources(e){let t=await this.hierarchyResolver.getHierarchy({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),n={components:Object.entries(e.components??{}).map(([i,a])=>({customId:i,name:a.name,description:a.description,definition:a.schema})),slots:Object.entries(e.slots??{}).map(([i,a])=>({customId:i,name:a.name,component:a.component,defaultContent:Object.entries(a.content).map(([s,p])=>({locale:s,content:p}))})),audiences:Object.entries(e.audiences??{}).map(([i,a])=>({customId:i,name:a.name,criteria:a.criteria})),experiences:(e.experiences??[]).map(i=>{let a=i.experiment??null;return {name:i.name,audiences:i.audiences,slots:i.slots,experiment:a!==null?{name:a.name,goalId:a.goalId,traffic:a.traffic,crossDevice:a.crossDevice===true,variants:a.variants.map(s=>({id:randomUUID$1(),name:s.name??"",baseline:s.baseline===true,allocation:s.allocation??0,content:o.createContentVariantGroup(s.content)}))}:void 0,content:o.createContentVariantGroup(i.content),validate:true,publish:i.draft===false}})},{data:{createWorkspaceResources:r}}=await this.client.execute(cc,{workspaceId:t.workspaceId,payload:n});return {components:Object.fromEntries(n.components.map(({customId:i},a)=>[i,r.components[a]])),slots:Object.fromEntries(n.slots.map(({customId:i},a)=>[i,r.slots[a]])),audiences:Object.fromEntries(n.audiences.map(({customId:i},a)=>[i,r.audiences[a]])),experiences:r.experiences.map(i=>{let a=i.experimentId??null;return {experienceId:i.id,...a!==null?{experimentId:a}:{}}})}}static createContentVariantGroup(e){return {default:{id:randomUUID$1(),contents:o.createSlotContentMap(e.default??{})},segmented:(e.segmented??[]).map(t=>({id:randomUUID$1(),audiences:t.audiences,contents:o.createSlotContentMap(t.content)}))}}static createSlotContentMap(e){return Object.entries(e).flatMap(([t,n])=>Object.entries(n).map(([r,i])=>({slot:t,locale:r,content:i})))}generateApplicationSlug(e,t,n){return mt({query:fc,baseName:`${t} ${n.slice(0,3).toLowerCase()}`,client:this.client,variables:{workspaceId:e}})}};var dt;(t=>{function o(){return Intl.DateTimeFormat().resolvedOptions().locale.toLowerCase()}t.getLocale=o;function e(){return Intl.DateTimeFormat().resolvedOptions().timeZone}t.getTimeZone=e;})(dt||={});var Dt=class o{constructor(e){this.config=e;}static prompt(e){return new o(e).handle()}handle(){let{input:e,validate:t}=this.config;return e.prompt({message:this.config.label,default:this.config.default,initial:this.config.initial??"https://",validate:n=>URL.canParse(n)?t!==void 0?t(n):true:"Invalid URL"})}};var yr=class{constructor(e){this.config=e;}async handle(e={}){let{userApi:t,output:n,input:r}=this.config;if(e.new!==true){let c=n.notify("Loading organizations"),l=[];if(e.default!==void 0){let u=await t.getOrganization(e.default);u!==null&&l.push(u);}if(l.length===0&&l.push(...await t.getOrganizations()),l.length===1){let u=l[0];return c.confirm(`Organization: ${u.name}`),u}if(c.stop(),l.length>0)return r.select({message:"Select organization",options:l.map(u=>({value:u,label:u.name}))})}let i=dt.getTimeZone(),a=dt.getLocale();n.inform("Setting up a new organization"),n.inform("*By continuing, you agree to our [Terms of Service](https://croct.link/terms-of-service)*");let s=await Dt.prompt({input:r,label:"Organization website"}),p=this.notify("Setting up organization");try{let c=await t.setupOrganization({website:s,locale:a,timeZone:i});return p.confirm(`Organization: ${c.name}`),c}finally{p.stop();}}notify(e){let{output:t}=this.config,n=["Visiting website","Detecting tech stack","Configuring organization","Creating workspace","Configuring applications","Setting up organization"],r=t.notify(e),i=0,a=setInterval(()=>{i>=n.length?clearInterval(a):r.update(n[i++]);},3e3);return a.unref(),{confirm:(s,p)=>{clearInterval(a),r.confirm(s,p);},stop:s=>{clearInterval(a),r.stop(s);}}}};var Ue=class o{constructor(e){this.config=e;}static prompt(e){return new o(e).handle()}handle(){let{input:e,validator:t,minimumLength:n=2,maximumLength:r=30}=this.config;return e.prompt({message:this.config.label,default:this.config.default,initial:this.config.initial,validate:i=>/(^\s|\s$|\s{2,})/.test(i)?"No leading, trailing, or multiple spaces.":i.length<n?`Minimum of ${n} characters`:i.length>r?`Maximum of ${r} characters`:t?.(i)??true})}};var hr=class o{constructor(e){this.config=e;}async handle(e){let{organizationApi:t,output:n,input:r}=this.config,{organization:i}=e;if(e.new===false){let a=n.notify("Loading workspaces"),s=await t.getWorkspaces({organizationSlug:i.slug}),p=o.getDefaultWorkspace(s,e.default);if(p!==null)return a.confirm(`Workspace: ${p.name}`),p;if(a.stop(),s.length>0)return r.select({message:"Select workspace",options:s.map(c=>({value:c,label:c.name}))})}return this.setupWorkspace(i,e.new===true)}async setupWorkspace(e,t){let{organizationApi:n,input:r,output:i}=this.config,a=t?await Ue.prompt({input:r,label:"Workspace name",default:e.name}):e.name,s=dt.getLocale(),p=dt.getTimeZone(),c=i.notify("Creating workspace");try{let l=await n.createWorkspace({organizationSlug:e.slug,name:a,website:e.website,defaultLocale:s,timeZone:p});return c.confirm(`Workspace: ${l.name}`),l}finally{c.stop();}}static getDefaultWorkspace(e,t){return e.length===1?e[0]:t!==void 0?e.find(({slug:n})=>n===t)??null:null}};var Sr=class o{constructor(e){this.config=e;}async handle(e){let{workspaceApi:t,output:n,input:r}=this.config,{organization:i,workspace:a,environment:s}=e,p=n.notify("Loading applications"),c=await t.getApplications({workspaceSlug:a.slug,organizationSlug:i.slug}),l=c.filter(u=>u.environment===s&&(e.default??u.slug)===u.slug);if(p.stop(),l.length===0||e.new===true)return this.setupApplication(e,c);if(l.length===1){let u=l[0];return n.confirm(o.formatSelection(u)),u}return r.select({message:s==="DEVELOPMENT"?"Select development application":"Select production application",options:l.map(u=>({value:u,label:u.name}))})}async setupApplication(e,t){let{workspaceApi:n,output:r,input:i}=this.config,{organization:a,workspace:s,platform:p,environment:c}=e,l=e.new===true,u=l?await Ue.prompt({input:i,label:"Application name",default:"Website",validator:v=>t.every(D=>D.name.toLowerCase()!==v.toLowerCase()||D.environment!==c)||"Name already in use"}):"Website",g=s.website??a.website??void 0,y=l||!o.isValidUrl(g,c)?await Dt.prompt({input:i,label:"Application website",default:g,validate:v=>URL.canParse(v)?o.isValidUrl(v,c)?true:"Production URL must not be localhost":"Invalid URL"}):g,C=r.notify("Configuring application");try{let v=await n.createApplication({organizationSlug:a.slug,workspaceSlug:s.slug,name:u,website:y,environment:c,platform:p,timeZone:s.timeZone});return C.confirm(o.formatSelection(v)),v}finally{C.stop();}}static isValidUrl(e,t){return e===void 0||!URL.canParse(e)?false:t!=="PRODUCTION"||new URL(e).hostname!=="localhost"}static formatSelection(e){return e.environment==="DEVELOPMENT"?`Development application: ${e.name} (${e.slug})`:`Production application: ${e.name} (${e.slug})`}};var br=class{constructor(e,t){this.client=e,this.hierarchyResolver=t;}async createApiKey(e){let t=await this.hierarchyResolver.getHierarchy({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,applicationSlug:e.applicationSlug}),{data:n}=await this.client.execute(bc,{applicationId:t.applicationId,payload:{name:e.name,permissions:e.permissions}}),{apiKey:r}=n.createApiKey;return {id:r.id,name:r.name,permissions:r.permissions.map(De.fromValue),secret:n.createApiKey.apiKeyValue}}};var rt=class o{constructor(e){this.config=e;}static prompt(e){return new o(e).handle()}handle(){let{input:e}=this.config;return e.prompt({message:this.config.label,validate:t=>t.length>255?"The email must be less than 255 characters":/^([A-Z0-9_+-]+\.?)*[A-Z0-9_+-]@([A-Z0-9][A-Z0-9-]*\.)+[A-Z]{2,}$/i.test(t)?true:"Please enter a valid email"})}};var Ir=class{constructor(e){this.config=e;}getToken(){return Promise.resolve(null)}login(e={}){if(e.username===void 0||e.password===void 0)return this.loginInteractively(e);let{form:t}=this.config;return t.signIn.handle({email:e.username,password:e.password})}async loginInteractively(e){let{input:t,output:n,userApi:r,form:i}=this.config,a=e.username??await rt.prompt({input:t,label:"Enter your email"}),s=n.notify("Finding account"),p=await r.isEmailRegistered(a);return s.stop(),p?(e.password===void 0&&n.inform("Account found, please sign in"),i.signIn.handle({email:a,password:e.password,retry:true})):(n.inform("New account, please sign up"),i.signUp.handle({email:a}))}logout(){return Promise.resolve()}};var it=class o{constructor(e){this.config=e;}static prompt(e){return new o(e).handle()}handle(){let{input:e}=this.config;return e.prompt({message:this.config.label,type:"password",validate:this.config.validator??(t=>t.length>0?true:"Please enter your password")})}};var vr=class{constructor(e){this.config=e;}handle(e){return this.login(e.email,e.password,e.retry)}async login(e,t,n=false){let{input:r,output:i,userApi:a}=this.config,s=e??await rt.prompt({input:this.config.input,label:"Enter your email"}),p=t,c="retry-password";for(;c==="retry-password";){let l=p??await it.prompt({input:r,label:"Password"});p=void 0;let u=i.notify("Checking credentials");try{let g=await a.signIn({email:s,password:l,duration:this.config.tokenDuration});return u.confirm("Logged in"),g}catch(g){if(g instanceof oe){if(g.isAccessDenied("UNVERIFIED_USER")){if(!n)throw new d("Email not verified.",{reason:"access_denied",cause:g,suggestions:["Access your email and click on the activation link"]});u.warn("Email not verified"),c=await r.confirm({message:"Resend activation link?",default:true})?"retry-activation":"cancel";continue}if(g.isAccessDenied("BAD_CREDENTIALS")){if(!n)throw new d("Username or password is incorrect.",{reason:"access_denied",cause:g,suggestions:["Check your credentials or reset your password"]});u.alert("Wrong password"),c=await r.select({message:"What would you like to do?",default:"retry-password",options:[{label:"Try again",value:"retry-password"},{label:"Recover password",value:"reset-password"},...e===void 0?[{label:"Enter a different email",value:"change-email"}]:[],{label:"Cancel",value:"cancel"}]});continue}}throw u.stop(),g}}switch(c){case "change-email":return this.login();case "retry-activation":return this.retryActivation(s);case "reset-password":return this.resetPassword(s);case "cancel":default:return i.exit()}}async retryActivation(e){let{output:t,userApi:n,emailLinkGenerator:{verification:r}}=this.config,i=t.notify("Sending email"),a=await n.createSession({destination:this.config.verificationLinkDestination.accountActivation});await n.retryActivation({email:e,sessionId:a}),i.confirm(`Link sent to \`${e}\``);let s=await this.getInboxLink(r,e),p=this.waitToken(a);return s!==null&&await t.open(s),p}async resetPassword(e){let{output:t,userApi:n,emailLinkGenerator:{recovery:r}}=this.config,i=t.notify("Sending link to reset password"),a=await n.createSession({destination:this.config.verificationLinkDestination.passwordReset});await n.requestPasswordReset({email:e,sessionId:a}),i.confirm(`Link sent to \`${e}\``);let s=await this.getInboxLink(r,e),p=this.waitToken(a);return s!==null&&await t.open(s),n.resetPassword({token:await p,password:await this.createPassword()})}async createPassword(){let{input:e,output:t}=this.config,n=null;for(;n===null;){let r=await it.prompt({input:e,label:"Enter your new password"}),i=await it.prompt({input:e,label:"Confirm your new password"});if(r!==i){t.warn("Passwords do not match, please try again");continue}n=r;}return n}async getInboxLink(e,t){let{input:n}=this.config,r=await e(t);return r!==null&&await n.confirm({message:"Open your inbox?",default:true})?r.toString():null}async waitToken(e){let{output:t,listener:n}=this.config,r=t.notify("Waiting for confirmation"),i=await n.wait(e);return r.confirm("Login completed"),i}};var xr=class{constructor(e){this.config=e;}async handle(e){let{input:t,output:n,listener:r,userApi:i}=this.config;n.inform("*By continuing, you agree to our [Terms of Use](https://croct.link/terms-of-use) and [Privacy Policy](https://croct.link/privacy)*");let a=await Ue.prompt({input:t,minimumLength:2,maximumLength:30,label:"Name"}),[s,p]=a.replace(/\s+/g," ").trim().split(" "),c=e.email??await rt.prompt({input:t,label:"Email"}),l=await it.prompt({input:t,label:"Password",validator:D=>/[A-Z]/.test(D)?/[a-z]/.test(D)?/[^A-Za-z]/.test(D)?D.length<8?"Minimum of 8 characters":D.length>256?"Maximum of 256 characters":true:"Must contain a special character":"Must contain a lowercase letter":"Must contain an uppercase letter"}),u=i.createSession({destination:this.config.verificationLinkDestination}),g=n.notify("Creating account");await i.registerUser({sessionId:await u,email:c,password:l,firstName:s,lastName:p,expertise:e.expertise??"ENGINEERING"}),g.confirm(`Link to verify sent to \`${c}\``);let y=await this.config.emailLinkGenerator(c).then(async D=>D!==null&&await t.confirm({message:"Open your inbox?",default:true})?D.toString():null);g=n.notify("Waiting for account activation");let C=r.wait(await u);y!==null&&await n.open(y);let v=await C;return g.confirm("Account activated"),v}};var wr=class{constructor(e){this.config=e;}async execute(e){let{output:t,pageForm:n,userApi:r}=this.config,i=await this.config.configurationManager.load(),a=await n.handle({page:e.page,organizationSlug:i.organization,workspaceSlug:i.workspace,devApplicationSlug:i.applications.development,prodApplicationSlug:i.applications.production}),s=t.notify("Logging in..."),p=await r.issueToken({duration:this.config.adminTokenDuration});s.stop();let c=new URL(a.startsWith("/")?a.slice(1):a,this.config.adminUrl);c.searchParams.set(this.config.adminTokenParameter,p),await t.open(c.toString());}};function Ce(o,e){let t=[],n=null;if(traverse(o,{ImportDeclaration:i=>{let{node:a}=i;if(a.source.value!==e.moduleName)return i.skip();t.push({declaration:a});let s=a.importKind??"value";for(let p of a.specifiers)if(!(!f.isImportSpecifier(p)||yu(p.imported)!==e.importName)){if(s==="value"&&(p.importKind===null||p.importKind===e.type)||s==="type"&&e.type==="type")return n=p.local.name,i.stop();t.unshift({declaration:a,specifier:p,localName:p.local.name});}return i.skip()}}),n!==null)return {modified:false,localName:n};if(t.length>0){for(let i of t){let{declaration:a}=i;if(a.importKind==="type"&&e.type==="value"){a.importKind="value";for(let s of a.specifiers)f.isImportSpecifier(s)&&s!==i.specifier&&(s.importKind="type");if(i.localName===void 0){let s=f.importSpecifier(f.identifier(e.localName??e.importName),f.identifier(e.importName));s.importKind=e.type,a.specifiers.push(s);}return {modified:true,localName:i.localName??e.importName}}if(i.specifier!==void 0&&i.specifier.importKind==="type"&&e.type==="value")return i.specifier.importKind="value",{modified:true,localName:i.localName}}for(let{declaration:i}of t){let a=i.importKind??"value";if(a==="value"||a===e.type){let s=f.importSpecifier(f.identifier(e.localName??e.importName),f.identifier(e.importName));return a!==e.type&&(s.importKind="type"),i.specifiers.push(s),{modified:true,localName:e.localName??e.importName}}}}let r=f.importDeclaration([f.importSpecifier(f.identifier(e.localName??e.importName),f.identifier(e.importName))],f.stringLiteral(e.moduleName));return e.type==="type"&&(r.importKind="type"),o.program.body.unshift(r),{modified:true,localName:e.localName??e.importName}}function yu(o){return f.isIdentifier(o)?o.name:o.value}function ln(o,e){let t=typeof o=="string"?je(o,["jsx","typescript"]):o,n=null;return traverse(t,{ImportDeclaration:r=>{let{node:i}=r;if(!Pr(i.source.value,e.moduleName))return r.skip();for(let a of i.specifiers??[]){if(f.isImportDefaultSpecifier(a)){Pr("default",e.importName)&&(n=a.local.name);continue}if(f.isImportSpecifier(a)&&Pr(a.imported,e.importName))return n=a.local.name,r.skip()}return r.skip()}}),n}function Pr(o,e){return typeof o!="string"?Pr(f.isIdentifier(o)?o.name:o.value,e):typeof e=="string"?o===e:e.test(o)}function Cr(o){let e=[];for(let[t,n]of Object.entries(o))e.push(f.jsxAttribute(f.jsxIdentifier(t),f.jsxExpressionContainer(gt(n))));return e}function gt(o){switch(o.type){case "reference":return o.path.length<2?f.identifier(o.path[0]):o.path.slice(2).reduce((e,t)=>f.memberExpression(e,f.identifier(t)),f.memberExpression(f.identifier(o.path[0]),f.identifier(o.path[1])));case "literal":return typeof o.value=="string"?f.stringLiteral(o.value):typeof o.value=="number"?f.numericLiteral(o.value):typeof o.value=="boolean"?f.booleanLiteral(o.value):f.nullLiteral();case "comparison":return f.binaryExpression(o.operator,gt(o.left),gt(o.right));case "ternary":return f.conditionalExpression(f.binaryExpression(o.condition.operator,gt(o.condition.left),gt(o.condition.right)),gt(o.consequent),gt(o.alternate))}}var ft=class o{constructor(e){this.configuration=e;}apply(e,t){let n=ln(e,{importName:this.configuration.wrapper.component,moduleName:this.configuration.wrapper.module}),r=n??this.configuration.wrapper.component,i=[],a=1;if(traverse(e,{ExportDefaultDeclaration:p=>(a=this.wrapDeclaration(p.node.declaration,r,e,t),p.stop()),ExportNamedDeclaration:p=>(i.push(p.node),p.skip())}),a===1&&this.configuration?.fallbackToNamedExports===true)for(let p of i){if(f.isFunctionDeclaration(p.declaration)&&(a=this.wrapBlockStatement(p.declaration.body,r,e,t),a===0))break;if(f.isVariableDeclaration(p.declaration)){let{declarations:c}=p.declaration;if(c.some(u=>f.isIdentifier(u.init)||f.isArrowFunctionExpression(u.init)||f.isFunctionExpression(u.init)?this.wrapDeclaration(u.init,r,e,t)===0:false)){a=0;break}}for(let c of p.specifiers??[])if(f.isExportSpecifier(c)){let l=this.findComponentDeclaration(e,c.local.name);if(l!==null&&f.isVariableDeclarator(l)&&f.isExpression(l.init)&&(a=this.wrapDeclaration(l.init,r,e,t),a===0))break}if(a===0)break}if(a===0&&n===null){let{body:p}=e.program;f.isImportDeclaration(p[0])||p.unshift(f.emptyStatement()),Ce(e,{type:"value",moduleName:this.configuration.wrapper.module,importName:this.configuration.wrapper.component});}let s=this.configuration?.fallbackCodemod;return a===1&&s!==void 0?s.apply(e,t):Promise.resolve({modified:a===0,result:e})}wrapDeclaration(e,t,n,r){if(f.isArrowFunctionExpression(e)){if(f.isBlockStatement(e.body))return this.wrapBlockStatement(e.body,t,n,r);let i=this.insertWrapper(e.body,t,n,r);return i.result!==0?i.result:(e.body=i.node,0)}if(f.isFunctionExpression(e)||f.isFunctionDeclaration(e))return this.wrapBlockStatement(e.body,t,n,r);if(f.isIdentifier(e)){let i=this.findComponentDeclaration(n,e.name);if(i!==null)if(f.isVariableDeclarator(i)){let a=i.init??null;if(a!==null)return this.wrapDeclaration(a,t,n,r)}else return this.wrapBlockStatement(i.body,t,n,r)}return 1}wrapBlockStatement(e,t,n,r){let i=o.findReturnStatement(e),a=i?.argument??null;if(i!==null&&a!==null){let s=this.insertWrapper(a,t,n,r);return s.result!==0?s.result:(i.argument=f.parenthesizedExpression(s.node),0)}return 1}insertWrapper(e,t,n,r){if(this.containsElement(e,t))return {result:2,node:e};let i=this.findTargetChildren(n,e);if(i!==null){let{parent:a,index:s}=i,p=[...a.children??[]],c=p.splice(s,1)[0];return i.parent.children=p.length===0?[f.jsxText(`
|
|
1733
|
+
`);function Tt(o){return {model:o,api:Object.fromEntries(Object.entries(o).map(([e,t])=>[t,e]))}}var us=Tt({javascript:"JAVASCRIPT",react:"REACT",nextjs:"NEXT"}),ms=Tt({DEVELOPMENT:"DEVELOPMENT",PRODUCTION:"PRODUCTION"}),Ec=Tt({NEVER_RECEIVED_TRAFFIC:"NEVER_RECEIVED_TRAFFIC",NOT_RECEIVING_TRAFFIC:"NOT_RECEIVING_TRAFFIC",RECEIVING_TRAFFIC:"RECEIVING_TRAFFIC"}),yu=Tt({PLUG_JS:"PLUG_JS"}),ds=Tt({DRAFT:"DRAFT",ACTIVE:"ACTIVE",SCHEDULED:"SCHEDULED",PAUSED:"PAUSED",ARCHIVED:"ARCHIVED"}),hu=Tt({DRAFT:"DRAFT",ACTIVE:"ACTIVE",SCHEDULED:"SCHEDULED",PAUSED:"PAUSED",FINISHED:"FINISHED",INDIRECTLY_PAUSED:"INDIRECTLY_PAUSED"}),yr=class o{constructor(e,t){this.client=e,this.hierarchyResolver=t;}async getFeatures(e){let{data:t}=await this.client.execute(uc,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),n=t.organization?.workspace??null;if(n===null)return null;let{quotas:r,capabilities:{features:i}}=n;return {quotas:{audiences:r.audience,remainingAudiences:r.remainingAudiences,components:r.component,remainingComponents:r.remainingComponents,slots:r.slot,remainingSlots:r.remainingSlots,experiences:r.experience,remainingExperiences:r.remainingExperiences,experiments:r.experiment,remainingExperiments:r.remainingExperiments,dynamicAttributesPerContent:r.dynamicAttributesPerContent,audiencesPerExperience:r.audiencesPerExperience},features:{crossDevice:i.includes("CROSS_DEVICE_EXPERIMENT"),dataExport:i.includes("API_DATA_EXPORT")}}}async getApplications(e){let{data:t}=await this.client.execute(bc,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.applications.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeApplication(i)]})}async getApplication(e){let{data:t}=await this.client.execute(Ic,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,applicationSlug:e.applicationSlug}),n=t.organization?.workspace?.application??null;return n===null?null:o.normalizeApplication(n)}static normalizeApplication(e){let{logo:t=null}=e;return {id:e.id,name:e.name,slug:e.slug,timeZone:e.settings.timeZone,website:e.website,environment:ms.api[e.environment],platform:us.api[e.platform??"JAVASCRIPT"],publicId:e.publicId,trafficStatus:Ec.api[e.applicationStatus],...t!==null?{logo:t}:{}}}async createApplication(e){let t=await this.hierarchyResolver.getHierarchy({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),{data:n}=await this.client.execute(vc,{workspaceId:t.workspaceId,payload:{name:e.name,website:e.website,environment:ms.model[e.environment],platform:us.model[e.platform],timeZone:e.timeZone,slug:await this.generateApplicationSlug(t.workspaceId,e.name,e.environment)}}),r=n.createWebApplication,{logo:i=null}=r;return {id:r.id,name:r.name,slug:r.slug,timeZone:r.settings.timeZone,website:r.website,environment:ms.api[r.environment],platform:us.api[r.platform??"JAVASCRIPT"],publicId:r.publicId,trafficStatus:Ec.api[r.applicationStatus],...i!==null?{logo:i}:{}}}async getAudiences(e){let{data:t}=await this.client.execute(dc,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.audiences.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeAudience(i)]})}async getAudience(e){let{data:t}=await this.client.execute(gc,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,audienceSlug:e.audienceSlug}),n=t.organization?.workspace?.audience??null;return n===null?null:o.normalizeAudience(n)}static normalizeAudience(e){return {id:e.id,name:e.name,slug:e.customId,criteria:e.criteria}}async getComponents(e){let{data:t}=await this.client.execute(wc,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.components.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeComponent(i)]})}async getComponent(e){let{data:t}=await this.client.execute(Pc,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,componentSlug:e.componentSlug,majorVersion:e.majorVersion}),n=t.organization?.workspace?.component??null;return n===null?null:o.normalizeComponent(n)}static normalizeComponent(e){let{definition:t,metadata:{directReferences:n,indirectReferences:r,referenceMetadata:i}}=e.definition,a=e.description??null;return {id:e.id,name:e.name,slug:e.customId,...a!==null?{description:a}:{},definition:t,version:{major:e.definition.version.major,minor:e.definition.version.minor},metadata:{directReferences:n.map(s=>i.find(({componentId:p})=>p===s)?.referenceName??s),indirectReferences:r.map(s=>i.find(({componentId:p})=>p===s)?.referenceName??s)}}}async getSlots(e){let{data:t}=await this.client.execute(fc,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.slots.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeSlot(i)]})}async getSlot(e){let{data:t}=await this.client.execute(yc,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,slotSlug:e.slotSlug,majorVersion:e.majorVersion}),n=t.organization?.workspace?.slot??null;return n===null?null:o.normalizeSlot(n)}static normalizeSlot(e){let{component:t=null}=e.content,n=t?.definition.metadata??null;return {id:e.id,name:e.name,slug:e.customId,...t!==null&&n!==null?{component:{slug:t.customId,version:{major:t.definition.version.major,minor:t.definition.version.minor},metadata:{directReferences:n.directReferences.map(r=>n.referenceMetadata.find(({componentId:i})=>i===r)?.referenceName??r),indirectReferences:n.indirectReferences.map(r=>n.referenceMetadata.find(({componentId:i})=>i===r)?.referenceName??r)}}}:{},version:{major:e.content.version.major,minor:e.content.version.minor},resolvedDefinition:e.content.componentDefinition.resolvedDefinition,content:Object.fromEntries(e.content.default.map(({locale:r,content:i})=>[r,i]))}}async getSlotStaticContent(e,t){let{data:n}=await this.client.execute(hc,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,slotSlug:e.slotSlug,majorVersion:t});return (n.organization?.workspace?.slot?.staticContent??[]).map(i=>({locale:i.locale,content:i.content}))}async generateTypes(e){let t=await this.hierarchyResolver.getHierarchy({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),{data:n}=await this.client.execute(Ac,{workspaceId:t.workspaceId,payload:{target:yu.model[e.target],components:e.components,slots:e.slots}});return n.generateTyping}async getExperiences(e){let{data:t}=await this.client.execute(kc,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,status:e.status===void 0?void 0:(Array.isArray(e.status)?e.status:[e.status]).map(r=>ds.model[r])});return (t.organization?.workspace?.experiences.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeExperience(i)]})}async getExperience(e){let{data:t}=await this.client.execute(Cc,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,experienceId:e.experienceId}),n=t.organization?.workspace?.experience??null;return n===null?null:o.normalizeExperienceDetails(n)}static normalizeExperience(e){let t=e.settings?.audiences??e.draft?.audiences??[],n=e.settings?.slots??e.draft?.slots??[],r=e.currentExperiment?.name??e.draft?.experiment?.name??null;return {id:e.id,name:e.name,priority:e.priority??e.draft?.priority??0,status:ds.api[e.status],audiences:t.map(i=>i.customId),slots:n.flatMap(({slot:i=null})=>i===null?[]:[i.customId]),...r!==null?{experiment:{name:r}}:{}}}static normalizeExperienceDetails(e){let t=e.settings?.audiences??e.draft?.audiences??[],n=e.settings?.slots??e.draft?.slots??[],r=e.currentExperiment??e.draft?.experiment??null,{name:i=null,goalId:a=null,crossDevice:s=null,traffic:p=null}=r??{},c=Object.fromEntries(n.flatMap(({slot:l=null})=>l===null?[]:[[l.id,l.customId]]));return {id:e.id,name:e.name,priority:e.priority??e.draft?.priority??0,status:ds.api[e.status],hasExperiments:e.hasExperiments,audiences:t.map(l=>l.customId),slots:Object.values(c),...r!==null?{experiment:{...i!==null?{name:i}:{},...a!==null?{goalId:a}:{},...s!==null?{crossDevice:s}:{},...p!==null?{traffic:p}:{},..."status"in r?{status:hu.api[r.status]}:{},variants:(r.variants??[]).map(l=>{let u=l.variantId,g=l.name??null,y=l.allocation??null;return {...u!==null?{id:u}:{},...g!==null?{name:g}:{},...y!==null?{allocation:y}:{},baseline:l.baseline===true,content:{default:o.normalizeLocalizedContent(l.content?.default.contents??[],c),segmented:(l.content?.segmented??[]).map(C=>({id:C.groupId,audiences:C.audiences.map(v=>v.audienceId),content:o.normalizeLocalizedContent(C.contents,c)}))}}})}}:{},content:{default:o.normalizeLocalizedContent(e.settings?.content.default.contents??e.draft?.content?.default.contents??[],c),segmented:(e.settings?.content.segmented??e.draft?.content?.segmented??[]).map(l=>({id:l.groupId,audiences:l.audiences.map(({audienceId:u})=>t.find(({id:g})=>g===u)?.customId??u),content:o.normalizeLocalizedContent(l.contents,c)}))}}}static normalizeLocalizedContent(e,t){let n={};for(let r of e){let{locale:i,slotId:a}=r,s=t[a];s!==void 0&&(n[s]===void 0&&(n[s]={}),n[s][i]=r.content);}return n}async createResources(e){let t=await this.hierarchyResolver.getHierarchy({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),n={components:Object.entries(e.components??{}).map(([i,a])=>({customId:i,name:a.name,description:a.description,definition:a.schema})),slots:Object.entries(e.slots??{}).map(([i,a])=>({customId:i,name:a.name,component:a.component,defaultContent:Object.entries(a.content).map(([s,p])=>({locale:s,content:p}))})),audiences:Object.entries(e.audiences??{}).map(([i,a])=>({customId:i,name:a.name,criteria:a.criteria})),experiences:(e.experiences??[]).map(i=>{let a=i.experiment??null;return {name:i.name,audiences:i.audiences,slots:i.slots,experiment:a!==null?{name:a.name,goalId:a.goalId,traffic:a.traffic,crossDevice:a.crossDevice===true,variants:a.variants.map(s=>({id:randomUUID$1(),name:s.name??"",baseline:s.baseline===true,allocation:s.allocation??0,content:o.createContentVariantGroup(s.content)}))}:void 0,content:o.createContentVariantGroup(i.content),validate:true,publish:i.draft===false}})},{data:{createWorkspaceResources:r}}=await this.client.execute(mc,{workspaceId:t.workspaceId,payload:n});return {components:Object.fromEntries(n.components.map(({customId:i},a)=>[i,r.components[a]])),slots:Object.fromEntries(n.slots.map(({customId:i},a)=>[i,r.slots[a]])),audiences:Object.fromEntries(n.audiences.map(({customId:i},a)=>[i,r.audiences[a]])),experiences:r.experiences.map(i=>{let a=i.experimentId??null;return {experienceId:i.id,...a!==null?{experimentId:a}:{}}})}}static createContentVariantGroup(e){return {default:{id:randomUUID$1(),contents:o.createSlotContentMap(e.default??{})},segmented:(e.segmented??[]).map(t=>({id:randomUUID$1(),audiences:t.audiences,contents:o.createSlotContentMap(t.content)}))}}static createSlotContentMap(e){return Object.entries(e).flatMap(([t,n])=>Object.entries(n).map(([r,i])=>({slot:t,locale:r,content:i})))}generateApplicationSlug(e,t,n){return mt({query:Sc,baseName:`${t} ${n.slice(0,3).toLowerCase()}`,client:this.client,variables:{workspaceId:e}})}};var dt;(t=>{function o(){return Intl.DateTimeFormat().resolvedOptions().locale.toLowerCase()}t.getLocale=o;function e(){return Intl.DateTimeFormat().resolvedOptions().timeZone}t.getTimeZone=e;})(dt||={});var Dt=class o{constructor(e){this.config=e;}static prompt(e){return new o(e).handle()}handle(){let{input:e,validate:t}=this.config;return e.prompt({message:this.config.label,default:this.config.default,initial:this.config.initial??"https://",validate:n=>URL.canParse(n)?t!==void 0?t(n):true:"Invalid URL"})}};var hr=class{constructor(e){this.config=e;}async handle(e={}){let{userApi:t,output:n,input:r}=this.config;if(e.new!==true){let c=n.notify("Loading organizations"),l=[];if(e.default!==void 0){let u=await t.getOrganization(e.default);u!==null&&l.push(u);}if(l.length===0&&l.push(...await t.getOrganizations()),l.length===1){let u=l[0];return c.confirm(`Organization: ${u.name}`),u}if(c.stop(),l.length>0)return r.select({message:"Select organization",options:l.map(u=>({value:u,label:u.name}))})}let i=dt.getTimeZone(),a=dt.getLocale();n.inform("Setting up a new organization"),n.inform("*By continuing, you agree to our [Terms of Service](https://croct.link/terms-of-service)*");let s=await Dt.prompt({input:r,label:"Organization website"}),p=this.notify("Setting up organization");try{let c=await t.setupOrganization({website:s,locale:a,timeZone:i});return p.confirm(`Organization: ${c.name}`),c}finally{p.stop();}}notify(e){let{output:t}=this.config,n=["Visiting website","Detecting tech stack","Configuring organization","Creating workspace","Configuring applications","Setting up organization"],r=t.notify(e),i=0,a=setInterval(()=>{i>=n.length?clearInterval(a):r.update(n[i++]);},3e3);return a.unref(),{confirm:(s,p)=>{clearInterval(a),r.confirm(s,p);},stop:s=>{clearInterval(a),r.stop(s);}}}};var Ue=class o{constructor(e){this.config=e;}static prompt(e){return new o(e).handle()}handle(){let{input:e,validator:t,minimumLength:n=2,maximumLength:r=30}=this.config;return e.prompt({message:this.config.label,default:this.config.default,initial:this.config.initial,validate:i=>/(^\s|\s$|\s{2,})/.test(i)?"No leading, trailing, or multiple spaces.":i.length<n?`Minimum of ${n} characters`:i.length>r?`Maximum of ${r} characters`:t?.(i)??true})}};var Sr=class o{constructor(e){this.config=e;}async handle(e){let{organizationApi:t,output:n,input:r}=this.config,{organization:i}=e;if(e.new===false){let a=n.notify("Loading workspaces"),s=await t.getWorkspaces({organizationSlug:i.slug}),p=o.getDefaultWorkspace(s,e.default);if(p!==null)return a.confirm(`Workspace: ${p.name}`),p;if(a.stop(),s.length>0)return r.select({message:"Select workspace",options:s.map(c=>({value:c,label:c.name}))})}return this.setupWorkspace(i,e.new===true)}async setupWorkspace(e,t){let{organizationApi:n,input:r,output:i}=this.config,a=t?await Ue.prompt({input:r,label:"Workspace name",default:e.name}):e.name,s=dt.getLocale(),p=dt.getTimeZone(),c=i.notify("Creating workspace");try{let l=await n.createWorkspace({organizationSlug:e.slug,name:a,website:e.website,defaultLocale:s,timeZone:p});return c.confirm(`Workspace: ${l.name}`),l}finally{c.stop();}}static getDefaultWorkspace(e,t){return e.length===1?e[0]:t!==void 0?e.find(({slug:n})=>n===t)??null:null}};var br=class o{constructor(e){this.config=e;}async handle(e){let{workspaceApi:t,output:n,input:r}=this.config,{organization:i,workspace:a,environment:s}=e,p=n.notify("Loading applications"),c=await t.getApplications({workspaceSlug:a.slug,organizationSlug:i.slug}),l=c.filter(u=>u.environment===s&&(e.default??u.slug)===u.slug);if(p.stop(),l.length===0||e.new===true)return this.setupApplication(e,c);if(l.length===1){let u=l[0];return n.confirm(o.formatSelection(u)),u}return r.select({message:s==="DEVELOPMENT"?"Select development application":"Select production application",options:l.map(u=>({value:u,label:u.name}))})}async setupApplication(e,t){let{workspaceApi:n,output:r,input:i}=this.config,{organization:a,workspace:s,platform:p,environment:c}=e,l=e.new===true,u=l?await Ue.prompt({input:i,label:"Application name",default:"Website",validator:v=>t.every(D=>D.name.toLowerCase()!==v.toLowerCase()||D.environment!==c)||"Name already in use"}):"Website",g=s.website??a.website??void 0,y=l||!o.isValidUrl(g,c)?await Dt.prompt({input:i,label:"Application website",default:g,validate:v=>URL.canParse(v)?o.isValidUrl(v,c)?true:"Production URL must not be localhost":"Invalid URL"}):g,C=r.notify("Configuring application");try{let v=await n.createApplication({organizationSlug:a.slug,workspaceSlug:s.slug,name:u,website:y,environment:c,platform:p,timeZone:s.timeZone});return C.confirm(o.formatSelection(v)),v}finally{C.stop();}}static isValidUrl(e,t){return e===void 0||!URL.canParse(e)?false:t!=="PRODUCTION"||new URL(e).hostname!=="localhost"}static formatSelection(e){return e.environment==="DEVELOPMENT"?`Development application: ${e.name} (${e.slug})`:`Production application: ${e.name} (${e.slug})`}};var Ir=class{constructor(e,t){this.client=e,this.hierarchyResolver=t;}async createApiKey(e){let t=await this.hierarchyResolver.getHierarchy({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,applicationSlug:e.applicationSlug}),{data:n}=await this.client.execute(xc,{applicationId:t.applicationId,payload:{name:e.name,permissions:e.permissions}}),{apiKey:r}=n.createApiKey;return {id:r.id,name:r.name,permissions:r.permissions.map(fe.fromValue),secret:n.createApiKey.apiKeyValue}}};var rt=class o{constructor(e){this.config=e;}static prompt(e){return new o(e).handle()}handle(){let{input:e}=this.config;return e.prompt({message:this.config.label,validate:t=>t.length>255?"The email must be less than 255 characters":/^([A-Z0-9_+-]+\.?)*[A-Z0-9_+-]@([A-Z0-9][A-Z0-9-]*\.)+[A-Z]{2,}$/i.test(t)?true:"Please enter a valid email"})}};var vr=class{constructor(e){this.config=e;}getToken(){return Promise.resolve(null)}login(e={}){if(e.username===void 0||e.password===void 0)return this.loginInteractively(e);let{form:t}=this.config;return t.signIn.handle({email:e.username,password:e.password})}async loginInteractively(e){let{input:t,output:n,userApi:r,form:i}=this.config,a=e.username??await rt.prompt({input:t,label:"Enter your email"}),s=n.notify("Finding account"),p=await r.isEmailRegistered(a);return s.stop(),p?(e.password===void 0&&n.inform("Account found, please sign in"),i.signIn.handle({email:a,password:e.password,retry:true})):(n.inform("New account, please sign up"),i.signUp.handle({email:a}))}logout(){return Promise.resolve()}};var it=class o{constructor(e){this.config=e;}static prompt(e){return new o(e).handle()}handle(){let{input:e}=this.config;return e.prompt({message:this.config.label,type:"password",validate:this.config.validator??(t=>t.length>0?true:"Please enter your password")})}};var xr=class{constructor(e){this.config=e;}handle(e){return this.login(e.email,e.password,e.retry)}async login(e,t,n=false){let{input:r,output:i,userApi:a}=this.config,s=e??await rt.prompt({input:this.config.input,label:"Enter your email"}),p=t,c="retry-password";for(;c==="retry-password";){let l=p??await it.prompt({input:r,label:"Password"});p=void 0;let u=i.notify("Checking credentials");try{let g=await a.signIn({email:s,password:l,duration:this.config.tokenDuration});return u.confirm("Logged in"),g}catch(g){if(g instanceof ae){if(g.isAccessDenied("UNVERIFIED_USER")){if(!n)throw new d("Email not verified.",{reason:"access_denied",cause:g,suggestions:["Access your email and click on the activation link"]});u.warn("Email not verified"),c=await r.confirm({message:"Resend activation link?",default:true})?"retry-activation":"cancel";continue}if(g.isAccessDenied("BAD_CREDENTIALS")){if(!n)throw new d("Username or password is incorrect.",{reason:"access_denied",cause:g,suggestions:["Check your credentials or reset your password"]});u.alert("Wrong password"),c=await r.select({message:"What would you like to do?",default:"retry-password",options:[{label:"Try again",value:"retry-password"},{label:"Recover password",value:"reset-password"},...e===void 0?[{label:"Enter a different email",value:"change-email"}]:[],{label:"Cancel",value:"cancel"}]});continue}}throw u.stop(),g}}switch(c){case "change-email":return this.login();case "retry-activation":return this.retryActivation(s);case "reset-password":return this.resetPassword(s);case "cancel":default:return i.exit()}}async retryActivation(e){let{output:t,userApi:n,emailLinkGenerator:{verification:r}}=this.config,i=t.notify("Sending email"),a=await n.createSession({destination:this.config.verificationLinkDestination.accountActivation});await n.retryActivation({email:e,sessionId:a}),i.confirm(`Link sent to \`${e}\``);let s=await this.getInboxLink(r,e),p=this.waitToken(a);return s!==null&&await t.open(s),p}async resetPassword(e){let{output:t,userApi:n,emailLinkGenerator:{recovery:r}}=this.config,i=t.notify("Sending link to reset password"),a=await n.createSession({destination:this.config.verificationLinkDestination.passwordReset});await n.requestPasswordReset({email:e,sessionId:a}),i.confirm(`Link sent to \`${e}\``);let s=await this.getInboxLink(r,e),p=this.waitToken(a);return s!==null&&await t.open(s),n.resetPassword({token:await p,password:await this.createPassword()})}async createPassword(){let{input:e,output:t}=this.config,n=null;for(;n===null;){let r=await it.prompt({input:e,label:"Enter your new password"}),i=await it.prompt({input:e,label:"Confirm your new password"});if(r!==i){t.warn("Passwords do not match, please try again");continue}n=r;}return n}async getInboxLink(e,t){let{input:n}=this.config,r=await e(t);return r!==null&&await n.confirm({message:"Open your inbox?",default:true})?r.toString():null}async waitToken(e){let{output:t,listener:n}=this.config,r=t.notify("Waiting for confirmation"),i=await n.wait(e);return r.confirm("Login completed"),i}};var wr=class{constructor(e){this.config=e;}async handle(e){let{input:t,output:n,listener:r,userApi:i}=this.config;n.inform("*By continuing, you agree to our [Terms of Use](https://croct.link/terms-of-use) and [Privacy Policy](https://croct.link/privacy)*");let a=await Ue.prompt({input:t,minimumLength:2,maximumLength:30,label:"Name"}),[s,p]=a.replace(/\s+/g," ").trim().split(" "),c=e.email??await rt.prompt({input:t,label:"Email"}),l=await it.prompt({input:t,label:"Password",validator:D=>/[A-Z]/.test(D)?/[a-z]/.test(D)?/[^A-Za-z]/.test(D)?D.length<8?"Minimum of 8 characters":D.length>256?"Maximum of 256 characters":true:"Must contain a special character":"Must contain a lowercase letter":"Must contain an uppercase letter"}),u=i.createSession({destination:this.config.verificationLinkDestination}),g=n.notify("Creating account");await i.registerUser({sessionId:await u,email:c,password:l,firstName:s,lastName:p,expertise:e.expertise??"ENGINEERING"}),g.confirm(`Link to verify sent to \`${c}\``);let y=await this.config.emailLinkGenerator(c).then(async D=>D!==null&&await t.confirm({message:"Open your inbox?",default:true})?D.toString():null);g=n.notify("Waiting for account activation");let C=r.wait(await u);y!==null&&await n.open(y);let v=await C;return g.confirm("Account activated"),v}};var Pr=class{constructor(e){this.config=e;}async execute(e){let{output:t,pageForm:n,userApi:r}=this.config,i=await this.config.configurationManager.load(),a=await n.handle({page:e.page,organizationSlug:i.organization,workspaceSlug:i.workspace,devApplicationSlug:i.applications.development,prodApplicationSlug:i.applications.production}),s=t.notify("Logging in..."),p=await r.issueToken({duration:this.config.adminTokenDuration});s.stop();let c=new URL(a.startsWith("/")?a.slice(1):a,this.config.adminUrl);c.searchParams.set(this.config.adminTokenParameter,p),await t.open(c.toString());}};function ke(o,e){let t=[],n=null;if(traverse(o,{ImportDeclaration:i=>{let{node:a}=i;if(a.source.value!==e.moduleName)return i.skip();t.push({declaration:a});let s=a.importKind??"value";for(let p of a.specifiers)if(!(!f.isImportSpecifier(p)||bu(p.imported)!==e.importName)){if(s==="value"&&(p.importKind===null||p.importKind===e.type)||s==="type"&&e.type==="type")return n=p.local.name,i.stop();t.unshift({declaration:a,specifier:p,localName:p.local.name});}return i.skip()}}),n!==null)return {modified:false,localName:n};if(t.length>0){for(let i of t){let{declaration:a}=i;if(a.importKind==="type"&&e.type==="value"){a.importKind="value";for(let s of a.specifiers)f.isImportSpecifier(s)&&s!==i.specifier&&(s.importKind="type");if(i.localName===void 0){let s=f.importSpecifier(f.identifier(e.localName??e.importName),f.identifier(e.importName));s.importKind=e.type,a.specifiers.push(s);}return {modified:true,localName:i.localName??e.importName}}if(i.specifier!==void 0&&i.specifier.importKind==="type"&&e.type==="value")return i.specifier.importKind="value",{modified:true,localName:i.localName}}for(let{declaration:i}of t){let a=i.importKind??"value";if(a==="value"||a===e.type){let s=f.importSpecifier(f.identifier(e.localName??e.importName),f.identifier(e.importName));return a!==e.type&&(s.importKind="type"),i.specifiers.push(s),{modified:true,localName:e.localName??e.importName}}}}let r=f.importDeclaration([f.importSpecifier(f.identifier(e.localName??e.importName),f.identifier(e.importName))],f.stringLiteral(e.moduleName));return e.type==="type"&&(r.importKind="type"),o.program.body.unshift(r),{modified:true,localName:e.localName??e.importName}}function bu(o){return f.isIdentifier(o)?o.name:o.value}function un(o,e){let t=typeof o=="string"?je(o,["jsx","typescript"]):o,n=null;return traverse(t,{ImportDeclaration:r=>{let{node:i}=r;if(!Cr(i.source.value,e.moduleName))return r.skip();for(let a of i.specifiers??[]){if(f.isImportDefaultSpecifier(a)){Cr("default",e.importName)&&(n=a.local.name);continue}if(f.isImportSpecifier(a)&&Cr(a.imported,e.importName))return n=a.local.name,r.skip()}return r.skip()}}),n}function Cr(o,e){return typeof o!="string"?Cr(f.isIdentifier(o)?o.name:o.value,e):typeof e=="string"?o===e:e.test(o)}function kr(o){let e=[];for(let[t,n]of Object.entries(o))e.push(f.jsxAttribute(f.jsxIdentifier(t),f.jsxExpressionContainer(gt(n))));return e}function gt(o){switch(o.type){case "reference":return o.path.length<2?f.identifier(o.path[0]):o.path.slice(2).reduce((e,t)=>f.memberExpression(e,f.identifier(t)),f.memberExpression(f.identifier(o.path[0]),f.identifier(o.path[1])));case "literal":return typeof o.value=="string"?f.stringLiteral(o.value):typeof o.value=="number"?f.numericLiteral(o.value):typeof o.value=="boolean"?f.booleanLiteral(o.value):f.nullLiteral();case "comparison":return f.binaryExpression(o.operator,gt(o.left),gt(o.right));case "ternary":return f.conditionalExpression(f.binaryExpression(o.condition.operator,gt(o.condition.left),gt(o.condition.right)),gt(o.consequent),gt(o.alternate))}}var ft=class o{constructor(e){this.configuration=e;}apply(e,t){let n=un(e,{importName:this.configuration.wrapper.component,moduleName:this.configuration.wrapper.module}),r=n??this.configuration.wrapper.component,i=[],a=1;if(traverse(e,{ExportDefaultDeclaration:p=>(a=this.wrapDeclaration(p.node.declaration,r,e,t),p.stop()),ExportNamedDeclaration:p=>(i.push(p.node),p.skip())}),a===1&&this.configuration?.fallbackToNamedExports===true)for(let p of i){if(f.isFunctionDeclaration(p.declaration)&&(a=this.wrapBlockStatement(p.declaration.body,r,e,t),a===0))break;if(f.isVariableDeclaration(p.declaration)){let{declarations:c}=p.declaration;if(c.some(u=>f.isIdentifier(u.init)||f.isArrowFunctionExpression(u.init)||f.isFunctionExpression(u.init)?this.wrapDeclaration(u.init,r,e,t)===0:false)){a=0;break}}for(let c of p.specifiers??[])if(f.isExportSpecifier(c)){let l=this.findComponentDeclaration(e,c.local.name);if(l!==null&&f.isVariableDeclarator(l)&&f.isExpression(l.init)&&(a=this.wrapDeclaration(l.init,r,e,t),a===0))break}if(a===0)break}if(a===0&&n===null){let{body:p}=e.program;f.isImportDeclaration(p[0])||p.unshift(f.emptyStatement()),ke(e,{type:"value",moduleName:this.configuration.wrapper.module,importName:this.configuration.wrapper.component});}let s=this.configuration?.fallbackCodemod;return a===1&&s!==void 0?s.apply(e,t):Promise.resolve({modified:a===0,result:e})}wrapDeclaration(e,t,n,r){if(f.isArrowFunctionExpression(e)){if(f.isBlockStatement(e.body))return this.wrapBlockStatement(e.body,t,n,r);let i=this.insertWrapper(e.body,t,n,r);return i.result!==0?i.result:(e.body=i.node,0)}if(f.isFunctionExpression(e)||f.isFunctionDeclaration(e))return this.wrapBlockStatement(e.body,t,n,r);if(f.isIdentifier(e)){let i=this.findComponentDeclaration(n,e.name);if(i!==null)if(f.isVariableDeclarator(i)){let a=i.init??null;if(a!==null)return this.wrapDeclaration(a,t,n,r)}else return this.wrapBlockStatement(i.body,t,n,r)}return 1}wrapBlockStatement(e,t,n,r){let i=o.findReturnStatement(e),a=i?.argument??null;if(i!==null&&a!==null){let s=this.insertWrapper(a,t,n,r);return s.result!==0?s.result:(i.argument=f.parenthesizedExpression(s.node),0)}return 1}insertWrapper(e,t,n,r){if(this.containsElement(e,t))return {result:2,node:e};let i=this.findTargetChildren(n,e);if(i!==null){let{parent:a,index:s}=i,p=[...a.children??[]],c=p.splice(s,1)[0];return i.parent.children=p.length===0?[f.jsxText(`
|
|
1790
1734
|
`),this.wrapElement(c,t,r),f.jsxText(`
|
|
1791
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(`
|
|
1792
1736
|
`),e,f.jsxText(`
|
|
1793
|
-
`)])}getProviderProps(e){return Cr({...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 We=class{constructor(e){this.codemod=e.codemod;}async apply(e,t){let n=kr.parse(e,{parser:{parse:parse$1}}),r=await this.codemod.apply(n,t);return r.modified?{modified:true,result:kr.print(r.result,{reuseWhitespace:false}).code}:{modified:false,result:e}}};function ds(o,e){let t=typeof o=="string"?je(o,["jsx","typescript"]):o,n=false;return traverse(t,{ExportAllDeclaration:r=>{let{node:i}=r;return !f.isStringLiteral(i.source)||!ms(i.source,e.moduleName)||(n=true),r.skip()},ExportNamedDeclaration:r=>{let{node:i}=r;if(!f.isStringLiteral(i.source)||!ms(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)&&ms(a.local,e.importName))return n=true,r.skip();return r.skip()}}),n}function ms(o,e){let t=f.isIdentifier(o)?o.name:o.value;return typeof e=="string"?t===e:e.test(t)}function Ar(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)||gs(u.local)!==e.importName||e.exportName!==void 0&&gs(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!==gs(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 gs(o){return f.isIdentifier(o)?o.name:o.value}var Er=class o{constructor(e){this.configuration=e;}apply(e){let{body:t}=e.program,n=ds(e,{moduleName:this.configuration.import.module,importName:this.configuration.import.configName}),r=ds(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 l=Ar(e,{type:"value",moduleName:this.configuration.import.module,importName:this.configuration.import.configName});return Promise.resolve({modified:l,result:e})}let a=ln(e,{moduleName:this.configuration.import.module,importName:this.configuration.import.middlewareFactoryName}),s=ln(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=o.refactorMiddleware(e,a??this.configuration.import.middlewareFactoryName,i!==null&&i.matcher?i.name:void 0);if(c===null){if(i===null){let l=Ar(e,{type:"value",moduleName:this.configuration.import.module,importName:this.configuration.import.middlewareName}),u=Ar(e,{type:"value",moduleName:this.configuration.import.module,importName:this.configuration.import.configName});return Promise.resolve({modified:l||u,result:e})}c=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(this.configuration.import.matcherName)))])])),t.push(c);}if(i!==null){this.configureMatcher(i.object,this.configuration.matcherPattern);let l=t.indexOf(i.root),u=t.indexOf(c);if(l>u){t.splice(u,0,...t.splice(l,1));for(let g of o.findReferencesFrom(i.root,e.program)){let y=t.indexOf(g);y>u&&t.splice(u,0,...t.splice(y,1));}}}return a===null&&Ce(e,{type:"value",moduleName:this.configuration.import.module,importName:this.configuration.import.middlewareFactoryName}),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)){if(r.value.value===t)break;r.value=f.arrayExpression([r.value,f.stringLiteral(t)]),n=true;break}if(f.isArrayExpression(r.value)){let{elements:i}=r.value;i.some(a=>f.isStringLiteral(a)&&a.value===t)||(i.push(f.stringLiteral(t)),n=true);break}f.isIdentifier(r.value)&&(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.stringLiteral(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 Ve=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 qe=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 nt("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 nt("Failed to write file",{cause:i,details:[`File: file://${e.replace(/\\/g,"/")}`]})}return {modified:r.modified,result:e}}};var Or=class{constructor(e){this.configuration=e;}apply(e,t={}){let n=t.typescript??false,{body:r}=e.program,i=Ce(e,{type:"value",moduleName:this.configuration.provider.module,importName:this.configuration.provider.component}),a=n?Ce(e,{type:"type",moduleName:"react",importName:"PropsWithChildren"}):null,s=n?Ce(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 kr({...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 We=class{constructor(e){this.codemod=e.codemod;}async apply(e,t){let n=Ar.parse(e,{parser:{parse:parse$1}}),r=await this.codemod.apply(n,t);return r.modified?{modified:true,result:Ar.print(r.result,{reuseWhitespace:false}).code}:{modified:false,result:e}}};function ys(o,e){let t=typeof o=="string"?je(o,["jsx","typescript"]):o,n=false;return traverse(t,{ExportAllDeclaration:r=>{let{node:i}=r;return !f.isStringLiteral(i.source)||!fs(i.source,e.moduleName)||(n=true),r.skip()},ExportNamedDeclaration:r=>{let{node:i}=r;if(!f.isStringLiteral(i.source)||!fs(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)&&fs(a.local,e.importName))return n=true,r.skip();return r.skip()}}),n}function fs(o,e){let t=f.isIdentifier(o)?o.name:o.value;return typeof e=="string"?t===e:e.test(t)}function Er(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)||hs(u.local)!==e.importName||e.exportName!==void 0&&hs(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!==hs(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 hs(o){return f.isIdentifier(o)?o.name:o.value}var Or=class o{constructor(e){this.configuration=e;}apply(e){let{body:t}=e.program,n=ys(e,{moduleName:this.configuration.import.module,importName:this.configuration.import.configName}),r=ys(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 l=Er(e,{type:"value",moduleName:this.configuration.import.module,importName:this.configuration.import.configName});return Promise.resolve({modified:l,result:e})}let a=un(e,{moduleName:this.configuration.import.module,importName:this.configuration.import.middlewareFactoryName}),s=un(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=o.refactorMiddleware(e,a??this.configuration.import.middlewareFactoryName,i!==null&&i.matcher?i.name:void 0);if(c===null){if(i===null){let l=Er(e,{type:"value",moduleName:this.configuration.import.module,importName:this.configuration.import.middlewareName}),u=Er(e,{type:"value",moduleName:this.configuration.import.module,importName:this.configuration.import.configName});return Promise.resolve({modified:l||u,result:e})}c=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(this.configuration.import.matcherName)))])])),t.push(c);}if(i!==null){this.configureMatcher(i.object,this.configuration.matcherPattern);let l=t.indexOf(i.root),u=t.indexOf(c);if(l>u){t.splice(u,0,...t.splice(l,1));for(let g of o.findReferencesFrom(i.root,e.program)){let y=t.indexOf(g);y>u&&t.splice(u,0,...t.splice(y,1));}}}return a===null&&ke(e,{type:"value",moduleName:this.configuration.import.module,importName:this.configuration.import.middlewareFactoryName}),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)){if(r.value.value===t)break;r.value=f.arrayExpression([r.value,f.stringLiteral(t)]),n=true;break}if(f.isArrayExpression(r.value)){let{elements:i}=r.value;i.some(a=>f.isStringLiteral(a)&&a.value===t)||(i.push(f.stringLiteral(t)),n=true);break}f.isIdentifier(r.value)&&(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.stringLiteral(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 Ve=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 qe=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 nt("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 nt("Failed to write file",{cause:i,details:[`File: file://${e.replace(/\\/g,"/")}`]})}return {modified:r.modified,result:e}}};var Rr=class{constructor(e){this.configuration=e;}apply(e,t={}){let n=t.typescript??false,{body:r}=e.program,i=ke(e,{type:"value",moduleName:this.configuration.provider.module,importName:this.configuration.provider.component}),a=n?ke(e,{type:"type",moduleName:"react",importName:"PropsWithChildren"}):null,s=n?ke(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(`
|
|
1794
1738
|
`),f.jsxElement(f.jsxOpeningElement(f.jsxIdentifier("body"),[]),f.jsxClosingElement(f.jsxIdentifier("body")),[f.jsxText(`
|
|
1795
1739
|
`),f.jsxElement(f.jsxOpeningElement(f.jsxIdentifier(i.localName),[]),f.jsxClosingElement(f.jsxIdentifier(i.localName)),[f.jsxText(`
|
|
1796
1740
|
`),f.jsxExpressionContainer(f.identifier("children")),f.jsxText(`
|
|
1797
1741
|
`)]),f.jsxText(`
|
|
1798
1742
|
`)]),f.jsxText(`
|
|
1799
|
-
`)])))]));return s!==null&&(c.returnType=f.tsTypeAnnotation(f.tsTypeReference(f.identifier(s.localName)))),r.push(f.exportDefaultDeclaration(c)),Promise.resolve({modified:true,result:e})}};var
|
|
1743
|
+
`)])))]));return s!==null&&(c.returnType=f.tsTypeAnnotation(f.tsTypeReference(f.identifier(s.localName)))),r.push(f.exportDefaultDeclaration(c)),Promise.resolve({modified:true,result:e})}};var mn=class{constructor(e){this.configuration=e;}apply(e,t={}){let n=t.typescript??false,{body:r}=e.program,i=ke(e,{type:"value",moduleName:this.configuration.provider.module,importName:this.configuration.provider.component}),a=n?ke(e,{type:"type",moduleName:"next/app",importName:"AppProps"}):null,s=n?ke(e,{type:"type",moduleName:"react",importName:"ReactNode"}):null,p=f.objectPattern([f.objectProperty(f.identifier("Component"),f.identifier("Component")),f.objectProperty(f.identifier("pageProps"),f.identifier("pageProps"))]);a!==null&&(p.typeAnnotation=f.tsTypeAnnotation(f.tsTypeReference(f.identifier(a.localName))));let c=f.functionDeclaration(f.identifier("App"),[p],f.blockStatement([f.returnStatement(f.parenthesizedExpression(f.jsxElement(f.jsxOpeningElement(f.jsxIdentifier(i.localName),kr(this.configuration.provider.props??{})),f.jsxClosingElement(f.jsxIdentifier(i.localName)),[f.jsxText(`
|
|
1800
1744
|
`),f.jsxElement(f.jsxOpeningElement(f.jsxIdentifier("Component"),[f.jsxSpreadAttribute(f.identifier("pageProps"))]),f.jsxClosingElement(f.jsxIdentifier("Component")),[]),f.jsxText(`
|
|
1801
|
-
`)])))]));return s!==null&&(c.returnType=f.tsTypeAnnotation(f.tsTypeReference(f.identifier(s.localName)))),r.push(f.exportDefaultDeclaration(c)),Promise.resolve({modified:true,result:e})}};var Rr=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var Tr=class o{constructor(e){this.configuration=e;}async format(e){let t=await this.getCommand(e);if(t!==null)try{await this.run(t);}catch{}}async run(e){let{commandExecutor:t,workingDirectory:n,timeout:r}=this.configuration;if(await(await t.run(e,{workingDirectory:n.get(),timeout:r})).wait()!==0)throw new Rr("Failed to format code.")}async getCommand(e){let{tools:t,packageManager:n,fileSystem:r}=this.configuration;for(let i of t){if(!await n.hasDirectDependency(i.package))continue;let a=await n.getDependency(i.package);if(a===null)continue;let s=o.getBinPath(a,i.bin);if(s!==null)return {name:r.joinPaths(a.directory,r.normalizeSeparators(s)),arguments:i.args(e)}}return null}static getBinPath({metadata:e},t){return "bin"in e?typeof e.bin=="string"?e.bin:t!==void 0&&typeof e.bin=="object"&&e.bin!==null&&typeof e.bin[t]=="string"?e.bin[t]:null:null}};var Nt=class o{constructor(e){this.config=e;}async execute(e){let{sdk:t,configurationManager:n,io:r}=this.config,{output:i}=r,a=await n.load(),s=await this.getSlots(a,e);if(s.length===0){i.inform("No slots to add");return}let p={input:r.input,output:r.output,configuration:{...a,slots:{...a.slots,...Object.fromEntries(s.map(([c,l])=>[c.slug,l.toString()]))}}};if(await n.update(p.configuration),i.confirm("Configuration updated"),await t.update(p,{clean:true}),e.example===true){let c=i.notify("Generating example");try{await Promise.all(s.map(([l])=>t.generateSlotExample(l,p)));}catch(l){throw c.stop(),l}c.confirm("Example generated");}}async getSlots(e,t){let{slotForm:n,workspaceApi:r,io:{output:i}}=this.config,a=t.slots===void 0?void 0:o.getVersionMap(t.slots,e.slots),s=Object.keys(e.slots),p=await n.handle({organizationSlug:e.organization,workspaceSlug:e.workspace,preselected:a===void 0?void 0:Object.keys(a),selected:t.example===true?[]:s});if(s.length===p.length&&p.every(c=>s.includes(c.slug))&&i.inform("No new slots to add"),t.slots!==void 0&&t.slots.length>0&&p.length!==t.slots.length){let c=t.slots.filter(l=>!p.some(u=>u.slug===l));throw new d(`Non-existing slots: \`${c.join("`, `")}\``,{reason:"invalid_input",suggestions:["Run `slot add` without arguments to see available slots"]})}return Promise.all(p.map(async c=>{let l=a?.[c.slug];if(l===void 0||l.getMaxVersion()===c.version.major)return [c,l??M.of(c.version.major)];if(l.getMinVersion()>c.version.major)throw new d(`No matching version for slot \`${c.slug}\`.`,{reason:"invalid_input",details:[`Requested version: ${l.toString()}`,`Current version: ${c.version.major}`],suggestions:["Omit version specifier to use the latest version"]});return t.example!==true?[c,l]:[await r.getSlot({organizationSlug:e.organization,workspaceSlug:e.workspace,slotSlug:c.slug,majorVersion:Math.min(c.version.major,l.getMinVersion())})??c,l]}))}static getVersionMap(e,t){return Object.fromEntries(e.map(n=>{let[r,i]=n.split("@",2);if(i===void 0)return [r,void 0];if(!M.isValid(i))throw new d(`Invalid version specifier \`${i}\` for slot \`${r}\`.`,{reason:"invalid_input",suggestions:["Version must be exact (i.e. `1`), range (i.e. `1 - 2`), or set (i.e. `1 || 2`)."]});let a=M.parse(i);if(a.getCardinality()>5)throw new d(`The number of versions specified for slot \`${r}\` exceeds 5 major versions.`,{reason:"invalid_input",suggestions:["Narrow down the number of versions to 5 or less."]});if(t[r]!==void 0&&(a=M.parse(t[r]).with(a),a.getCardinality()>5))throw new d(`The cumulative number of versions for slot \`${r}\` cannot exceed 5 major versions.`,{reason:"invalid_input",suggestions:["Narrow down the number of versions to 5 or less."]});return [r,a]}))}};var Be=class{constructor(e){this.config=e;}async handle(e){let{output:t,input:n}=this.config,r=t.notify("Loading slots"),i=await this.getSlots(e,e.allowed);r.stop();let a=e.preselected??[];if(a.length>0)return i.filter(({slug:p})=>a.includes(p));let s=e.selected??[];return i.length===0||s.length>0&&i.every(({slug:p})=>s.includes(p))?i.filter(({slug:p})=>s.includes(p)):e.selectionConfirmation!==void 0&&!await n.confirm(e.selectionConfirmation)?i.filter(({slug:c})=>s.includes(c)):n.selectMultiple({message:"Select slots",options:i.map(p=>{let c=s.includes(p.slug);return {value:p,label:p.name,disabled:c,selected:c}})})}async getSlots(e,t){let{workspaceApi:n}=this.config,r=await n.getSlots({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return t===void 0?r:r.filter(({slug:i})=>t.includes(i))}};var $t=class o{constructor(e){this.config=e;}async execute(e){let{sdk:t,configurationManager:n,io:r}=this.config,{output:i}=r,a=await n.load(),s=await this.getComponents(a,e);if(s.length===0){i.inform("No components to add");return}let p={input:r.input,output:r.output,configuration:{...a,components:{...a.components,...Object.fromEntries(s.map(([c,l])=>[c.slug,l.toString()]))}}};await n.update(p.configuration),i.confirm("Configuration updated"),await t.update(p,{clean:true});}async getComponents(e,t){let{componentForm:n,io:{output:r}}=this.config,i=t.components===void 0?void 0:o.getVersionMap(t.components,e.components),a=Object.keys(e.components),s=await n.handle({organizationSlug:e.organization,workspaceSlug:e.workspace,preselected:i===void 0?void 0:Object.keys(i),selected:a});if(a.length===s.length&&s.every(p=>a.includes(p.slug))&&r.inform("No new component to add"),t.components!==void 0&&t.components.length>0&&s.length!==t.components.length){let p=t.components.filter(c=>!s.some(l=>l.slug===c));throw new d(`Non-existing components: \`${p.join("`, `")}\``,{reason:"invalid_input",suggestions:["Run `component add` without arguments to see available components"]})}return s.map(p=>{let c=i?.[p.slug];if(c===void 0||c.getMaxVersion()===p.version.major)return [p,c??M.of(p.version.major)];if(c.getMinVersion()>p.version.major)throw new d(`No matching version for component \`${p.slug}\`.`,{reason:"invalid_input",details:[`Requested version: ${c.toString()}`,`Current version: ${p.version.major}`],suggestions:["Omit version specifier to use the latest version"]});return [p,c]})}static getVersionMap(e,t){return Object.fromEntries(e.map(n=>{let[r,i]=n.split("@",2);if(i===void 0)return [r,void 0];if(!M.isValid(i))throw new d(`Invalid version specifier \`${i}\` for component \`${r}\`.`,{reason:"invalid_input",suggestions:["Version must be exact (i.e. `1`), range (i.e. `1 - 2`), or set (i.e. `1 || 2`)."]});let a=M.parse(i);if(a.getCardinality()>5)throw new d(`The number of versions specified for component \`${r}\` exceeds 5 major versions.`,{reason:"invalid_input",suggestions:["Narrow down the number of versions to 5 or less."]});if(t[r]!==void 0&&(a=M.parse(t[r]).with(a),a.getCardinality()>5))throw new d(`The cumulative number of versions for component \`${r}\` cannot exceed 5 major versions.`,{reason:"invalid_input",suggestions:["Narrow down the number of versions to 5 or less."]});return [r,a]}))}};var ot=class{constructor(e){this.config=e;}async handle(e){let{workspaceApi:t}=this.config,{allowed:n}=e,r=await t.getComponents({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),i=await this.selectComponents(e,n===void 0?r:r.filter(({slug:a})=>n.includes(a)));return e.includeDependencies===true&&i.push(...this.getReferencedComponents(r,i)),i}async selectComponents(e,t){let{output:n,input:r}=this.config;n.notify("Loading components").stop();let a=e.preselected??[];if(a.length>0)return t.filter(({slug:p})=>a.includes(p));let s=e.selected??[];return e.includeDependencies===true&&s.push(...this.getReferencedComponents(t,t.filter(({slug:p})=>s.includes(p))).map(p=>p.slug)),t.length===0||s.length>0&&t.every(({slug:p})=>s.includes(p))?t.filter(({slug:p})=>s.includes(p)):e.selectionConfirmation!==void 0&&!await r.confirm(e.selectionConfirmation)?t.filter(({slug:c})=>s.includes(c)):r.selectMultiple({message:"Select components",options:t.map(p=>{let c=s.includes(p.slug);return {value:p,label:p.name,disabled:c,selected:c}})})}getReferencedComponents(e,t){let n=new Map;for(let r of t){let i=new Set([...r.metadata.directReferences,...r.metadata.indirectReferences]);for(let a of i)if(!t.some(({slug:s})=>s===a)){let s=e.find(({slug:p})=>p===a);s!==void 0&&n.set(s.slug,s);}}return [...n.values()]}};var mn=class o{constructor(e){this.config=e;}async execute(e){let{sdk:t,configurationManager:n,slotForm:r,io:i}=this.config,{output:a}=i,s=await n.load(),p=e.slots===void 0?void 0:o.getVersionMap(e.slots,s.slots),c=await r.handle({organizationSlug:s.organization,workspaceSlug:s.workspace,allowed:Object.keys(s.slots),preselected:p===void 0?void 0:Object.keys(p)});if(c.length===0)return a.inform("No slots to remove.");let l={input:i.input,output:i.output,configuration:{...s,slots:Object.fromEntries(Object.entries(s.slots).flatMap(([u,g])=>p?.[u]!==void 0?p[u]===null?[]:[[u,p[u].toString()]]:c.some(y=>y.slug===u)?[]:[[u,g.toString()]]))}};await n.update(l.configuration),a.confirm("Configuration updated"),await t.update(l,{clean:true});}static getVersionMap(e,t){return Object.fromEntries(e.map(n=>{let[r,i]=n.split("@",2);if(t[r]===void 0||i===void 0)return [r,null];let a=M.parse(t[r]);if(!M.isValid(i))return [r,a];let s=M.parse(i);return a.intersects(s)?s.contains(a)?[r,null]:[r,a.without(s)]:[r,a]}))}};var dn=class o{constructor(e){this.config=e;}async execute(e){let{sdk:t,configurationManager:n,componentForm:r,io:i}=this.config,{output:a}=i,s=await n.load(),p=e.components===void 0?void 0:o.getVersionMap(e.components,s.components),c=await r.handle({organizationSlug:s.organization,workspaceSlug:s.workspace,allowed:Object.keys(s.components),preselected:p===void 0?void 0:Object.keys(p)});if(c.length===0)return a.alert("No components to remove.");let l={input:i.input,output:i.output,configuration:{...s,components:Object.fromEntries(Object.entries(s.components).flatMap(([u,g])=>p?.[u]!==void 0?p[u]===null?[]:[[u,p[u].toString()]]:c.some(y=>y.slug===u)?[]:[[u,g.toString()]]))}};a.confirm("Configuration updated"),await n.update(l.configuration),await t.update(l,{clean:true});}static getVersionMap(e,t){return Object.fromEntries(e.map(n=>{let[r,i]=n.split("@",2);if(t[r]===void 0||i===void 0)return [r,null];let a=M.parse(t[r]);if(!M.isValid(i))return [r,a];let s=M.parse(i);return a.intersects(s)?s.contains(a)?[r,null]:[r,a.without(s)]:[r,a]}))}};var Dr=class{constructor({manager:e,initializer:t}){this.manager=e,this.initializer=t;}isInitialized(){return this.manager.isInitialized()}async load(){return await this.isInitialized()||await this.initializer.initialize(),this.manager.load()}update(e){return this.manager.update(e)}};var gn=class{constructor(e){this.configuration=e;}async execute(e){let{sdk:t,configurationManager:n,io:r}=this.configuration,i={input:r.input,output:r.output,configuration:await n.load()};await t.update(i,{clean:e.clean});}};var Mr=class o{static{this.SITEMAP={Home:"/","Personal settings":"/settings",Organization:"/organizations/:organization","Organization settings":"/organizations/:organization/settings","Organization members":"/organizations/:organization/members",Workspace:"/organizations/:organization/workspaces/:workspace","Workspace settings":"/organizations/:organization/workspaces/:workspace/settings","Workspace members":"/organizations/:organization/workspaces/:workspace/members","Dev application":"/organizations/:organization/workspaces/:workspace/applications/:dev-application/dashboard","Prod application":"/organizations/:organization/workspaces/:workspace/applications/:prod-application/dashboard","Dev application settings":"/organizations/:organization/workspaces/:workspace/applications/:dev-application/settings","Prod application settings":"/organizations/:organization/workspaces/:workspace/applications/:prod-application/settings",Slots:"/organizations/:organization/workspaces/:workspace/slots",Components:"/organizations/:organization/workspaces/:workspace/components",Experiences:"/organizations/:organization/workspaces/:workspace/experiences"};}constructor(e){this.config=e;}async handle(e){return o.resolvePath(await this.getPage(e.page,e),e)}getPage(e,t){if(e!==void 0){let r=o.findMatch(e,t);if(r!==null)return Promise.resolve(r)}let{input:n}=this.config;return n.select({message:"Where do you want to go?",options:Object.entries(o.SITEMAP).map(([r,i])=>({value:i,label:r}))})}static findMatch(e,t){if(e.startsWith("/"))return e;let n=null,r=.5;for(let i of Object.keys(o.getSitemap(t))){let a=stringSimilarity(e,i);a>r&&(n=o.SITEMAP[i],r=a);}return n}static getSitemap(e){return e.prodApplicationSlug!==void 0?o.SITEMAP:Object.fromEntries(Object.entries(o.SITEMAP).filter(([,t])=>!t.includes(":prod-application")))}static resolvePath(e,t){return e.replace(/:(organization|workspace|(dev|prod)-application)/g,(n,r)=>{switch(r){case "organization":return t.organizationSlug;case "workspace":return t.workspaceSlug;case "dev-application":return t.devApplicationSlug;case "prod-application":return t.prodApplicationSlug??""}})}};var Nr=class{constructor({instruction:e,authenticator:t}){this.instruction=e,this.authenticator=t;}getToken(){return this.authenticator.getToken()}login(e){if(Object.keys(e).length===0){let{message:t,...n}=this.instruction;throw new d(t,n)}return this.authenticator.login(e)}logout(){return this.authenticator.logout()}};var $r=class{constructor(e){this.instruction=e;}prompt(){return this.report()}select(){return this.report()}selectMultiple(){return this.report()}confirm(){return this.report()}wait(){return this.report()}report(){let{message:e,...t}=this.instruction;throw new d(e,t)}};var Lr=class{constructor(e){this.authenticators=e;}async getToken(){for(let e of Object.values(this.authenticators)){let t=await e.getToken();if(t!==null)return t}return null}login(e){let t={...e};return delete t.method,this.authenticators[e.method].login(t)}async logout(){await Promise.all(Object.values(this.authenticators).map(e=>e.logout()));}};var fn=class o{constructor(e){this.config=e;}async execute(e){let{sdk:t,configurationManager:n,io:r}=this.config,i=await n.load(),a=await this.selectSlots(i,e.slots),s=await this.selectComponents(i,e.components),p={input:r.input,output:r.output,configuration:{...i,slots:{...i.slots,...Object.fromEntries(a.map(c=>[c.slug,o.resolveVersion(c.version.major,i.slots[c.slug])]))},components:{...i.components,...Object.fromEntries(s.map(c=>[c.slug,o.resolveVersion(c.version.major,i.components[c.slug])]))}}};await n.update(p.configuration),await t.update(p,{clean:true});}async selectComponents(e,t){let{form:{componentForm:n}}=this.config,r=t===void 0?Object.keys(e.components):t,i=r.length===0?[]:await n.handle({organizationSlug:e.organization,workspaceSlug:e.workspace,preselected:r});if(r.length>0&&i.length!==r.length){let a=r.filter(s=>!i.some(p=>p.slug===s));throw new d(`Components not found: \`${a.join("`, `")}\`.`,{reason:"precondition",suggestions:["Run `remove component` to remove a component from your configuration."]})}return i}async selectSlots(e,t){let{form:{slotForm:n}}=this.config,r=t===void 0?Object.keys(e.slots):t,i=r.length===0?[]:await n.handle({organizationSlug:e.organization,workspaceSlug:e.workspace,preselected:r});if(r.length>0&&i.length!==r.length){let a=r.filter(s=>!i.some(p=>p.slug===s));throw new d(`Slots not found: \`${a.join("`, `")}\`.`,{reason:"precondition",suggestions:["Run `remove slot` to remove a slot from your configuration."]})}return i}static resolveVersion(e,t){let n=M.of(e);if(t===void 0)return n.toString();let r=M.parse(t);return r.isExact()?n.toString():r.isRange()?r.getMaxVersion()>=n.getMaxVersion()?t:M.between(r.getMinVersion(),n.getMaxVersion()).toString():M.either(...r.getVersions(),...n.getVersions()).toString()}};var yn=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var zr=class o{static{this.ERRORS={ENOENT:"The file or directory does not exist.",EACCES:"Unable to access the file or directory.",EISDIR:"Expected a file, but the path is a directory.",ENOTDIR:"Expected a directory, but the path is a file.",EPERM:"Operation not permitted.",EEXIST:"The file or directory already exists.",ENOTEMPTY:"The directory is not empty."};}static{this.ERROR_REASONS={ENOENT:"not_found",EACCES:"access_denied",EISDIR:"invalid_input",ENOTDIR:"invalid_input",EPERM:"access_denied",EEXIST:"invalid_input",ENOTEMPTY:"invalid_input"};}constructor(e){this.config={...e,defaultEncoding:e.defaultEncoding??"utf8"};}getSeparator(){return sep}normalizeSeparators(e){return e.replace(/\//g,sep)}getBaseName(e){return basename(e)}getDirectoryName(e){return dirname(e)}getRealPath(e){return this.execute(()=>realpath(this.resolvePath(e)))}getRelativePath(e,t){return relative(this.resolvePath(e),this.resolvePath(t))}isAbsolutePath(e){return isAbsolute(e)}isSubPath(e,t){let n=this.resolvePath(e),r=this.resolvePath(t),i=relative(n,r);return !i.startsWith("..")&&!isAbsolute(i)}isSymbolicLink(e){return this.execute(async()=>{try{return (await lstat(this.resolvePath(e))).isSymbolicLink()}catch(t){if(o.isErrorCode(t,["ENOENT","ENOTDIR"]))return false;throw t}})}isDirectory(e){return this.execute(async()=>{try{return (await lstat(this.resolvePath(e))).isDirectory()}catch(t){if(o.isErrorCode(t,["ENOENT","ENOTDIR"]))return false;throw t}})}isEmptyDirectory(e){return this.execute(async()=>(await readdir(this.resolvePath(e))).length===0)}create(e){switch(e.type){case "file":return this.execute(()=>writeFile(this.resolvePath(e.name),e.content));case "directory":return this.execute(()=>mkdir(this.resolvePath(e.name)));case "link":return this.execute(()=>link(e.target,this.resolvePath(e.name)));case "symlink":return this.execute(()=>symlink(e.target,this.resolvePath(e.name)))}}list(e,t){let n=this.resolvePath(e);return this.listRelatively(n,n,0,t??(()=>true))}async*listRelatively(e,t,n,r){if(!await r(e,n))return;let i=await this.execute(()=>lstat(e)).catch(()=>null);if(i===null)return;if(!i.isDirectory())return yield*this.createEntry(e,dirname(t),i,n,r);let a=await this.execute(()=>readdir(e));for(let s of a){let p=join(e,s),c=await this.execute(()=>lstat(p));await r(p,n)&&(yield*this.createEntry(p,t,c,n,r));}}async*createEntry(e,t,n,r,i){let a=relative(t,e);if(n.isFile()){let s=()=>this.execute(()=>createReadStream(e));yield {type:"file",name:a,get content(){return s()}};}else n.isDirectory()?(yield {type:"directory",name:a},yield*this.listRelatively(e,t,r+1,i)):n.isSymbolicLink()?yield {type:"symlink",name:a,target:await this.execute(()=>realpath(e))}:yield {type:"link",name:a,target:await this.execute(()=>realpath(e))};}joinPaths(...e){return join(...e)}async exists(e){try{return await lstat(this.resolvePath(e)),!0}catch(t){if(o.isErrorCode(t,["ENOENT","ENOTDIR"]))return false;throw t}}delete(e,t){return rm(this.resolvePath(e),{recursive:t?.recursive??false,force:true})}move(e,t,n){return this.execute(async()=>{let r=this.resolvePath(e),i=this.resolvePath(t);n?.overwrite===true&&await rm(i,{force:true,recursive:true}),await mkdir(dirname(i),{recursive:true}),await rename(r,i);})}readTextFile(e){return this.execute(()=>readFile(this.resolvePath(e),this.config.defaultEncoding))}writeTextFile(e,t,n){return this.execute(()=>writeFile(this.resolvePath(e),t,{flag:n?.overwrite===true?"w":"wx",encoding:this.config.defaultEncoding}))}async createDirectory(e,t){await this.execute(()=>mkdir(this.resolvePath(e),{recursive:t?.recursive??false}));}createTemporaryDirectory(e){return this.execute(()=>mkdtemp(this.joinPaths(tmpdir(),e)))}copy(e,t,n){return this.execute(()=>cp$1(this.resolvePath(e),this.resolvePath(t),{recursive:true,force:n?.overwrite??false}))}resolvePath(e){return isAbsolute(e)?e:join(this.config.workingDirectory.get(),e)}execute(e){try{let t=e();return t instanceof Promise?t.catch(n=>o.reportError(n)):t}catch(t){o.reportError(t);}}static reportError(e){if(e instanceof Error){let t=Object.entries(o.ERRORS);for(let[n,r]of t)if(o.isErrorCode(e,[n]))throw new yn(r,{reason:o.ERROR_REASONS[n]??"other",cause:e,details:[`Code: ${n}`]})}throw new yn("An unexpected error occurred.",{cause:e})}static isErrorCode(e,t){return !(e instanceof Error)||!("code"in e)||typeof e.code!="string"?false:t.includes(e.code)}};var _r=class{constructor(e){this.configuration=e;}wait(e){let{listener:t}=this.configuration;return new Promise((n,r)=>{this.focus(()=>t.wait(e).then(n,r));})}focus(e){switch(this.configuration.platform){case "darwin":return this.darwinFocus(e);case "linux":return this.linuxFocus(e);case "win32":return this.win32Focus(e);default:return e()}}async darwinFocus(e){let t=this.runCommand({name:"osascript",arguments:["-e","bundle identifier of (info for (path to frontmost application))"]});await e(),t!==null&&this.runCommand({name:"open",arguments:["-b",t]});}async linuxFocus(e){let t=this.runCommand({name:"xdotool",arguments:["getactivewindow"]});await e(),t!==null&&this.runCommand({name:"xdotool",arguments:["windowactivate",t]});}async win32Focus(e){let t=ie`
|
|
1745
|
+
`)])))]));return s!==null&&(c.returnType=f.tsTypeAnnotation(f.tsTypeReference(f.identifier(s.localName)))),r.push(f.exportDefaultDeclaration(c)),Promise.resolve({modified:true,result:e})}};var Tr=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var Dr=class o{constructor(e){this.configuration=e;}async format(e){let t=await this.getCommand(e);if(t!==null)try{await this.run(t);}catch{}}async run(e){let{commandExecutor:t,workingDirectory:n,timeout:r}=this.configuration;if(await(await t.run(e,{workingDirectory:n.get(),timeout:r})).wait()!==0)throw new Tr("Failed to format code.")}async getCommand(e){let{tools:t,packageManager:n,fileSystem:r}=this.configuration;for(let i of t){if(!await n.hasDirectDependency(i.package))continue;let a=await n.getDependency(i.package);if(a===null)continue;let s=o.getBinPath(a,i.bin);if(s!==null)return {name:r.joinPaths(a.directory,r.normalizeSeparators(s)),arguments:i.args(e)}}return null}static getBinPath({metadata:e},t){return "bin"in e?typeof e.bin=="string"?e.bin:t!==void 0&&typeof e.bin=="object"&&e.bin!==null&&typeof e.bin[t]=="string"?e.bin[t]:null:null}};var Nt=class o{constructor(e){this.config=e;}async execute(e){let{sdk:t,configurationManager:n,io:r}=this.config,{output:i}=r,a=await n.load(),s=await this.getSlots(a,e);if(s.length===0){i.inform("No slots to add");return}let p={input:r.input,output:r.output,configuration:{...a,slots:{...a.slots,...Object.fromEntries(s.map(([u,g])=>[u.slug,g.toString()]))}}};await n.update(p.configuration),i.confirm("Configuration updated"),await t.update(p,{clean:true});let c=s.filter(([u])=>a.slots[u.slug]===void 0||!M.parse(a.slots[u.slug]).contains(M.of(u.version.major)));if(c.length>0&&(e.example??await r.input?.confirm({message:"Generate an example implementation?",default:true})??false)){let u=i.notify("Generating example");try{await Promise.all(c.map(([g])=>t.generateSlotExample(g,p)));}catch(g){throw u.stop(),g}u.confirm("Example generated");}}async getSlots(e,t){let{slotForm:n,workspaceApi:r,io:{output:i}}=this.config,a=t.slots===void 0?void 0:o.getVersionMap(t.slots,e.slots),s=Object.keys(e.slots),p=await n.handle({organizationSlug:e.organization,workspaceSlug:e.workspace,preselected:a===void 0?void 0:Object.keys(a),selected:t.example===true?[]:s});if(s.length===p.length&&p.every(c=>s.includes(c.slug))&&i.inform("No new slots to add"),t.slots!==void 0&&t.slots.length>0&&p.length!==t.slots.length){let c=t.slots.filter(l=>!p.some(u=>u.slug===l));throw new d(`Non-existing slots: \`${c.join("`, `")}\``,{reason:"invalid_input",suggestions:["Run `slot add` without arguments to see available slots"]})}return Promise.all(p.map(async c=>{let l=a?.[c.slug];if(l===void 0||l.getMaxVersion()===c.version.major)return [c,l??M.of(c.version.major)];if(l.getMinVersion()>c.version.major)throw new d(`No matching version for slot \`${c.slug}\`.`,{reason:"invalid_input",details:[`Requested version: ${l.toString()}`,`Current version: ${c.version.major}`],suggestions:["Omit version specifier to use the latest version"]});return t.example!==true?[c,l]:[await r.getSlot({organizationSlug:e.organization,workspaceSlug:e.workspace,slotSlug:c.slug,majorVersion:Math.min(c.version.major,l.getMinVersion())})??c,l]}))}static getVersionMap(e,t){return Object.fromEntries(e.map(n=>{let[r,i]=n.split("@",2);if(i===void 0)return [r,void 0];if(!M.isValid(i))throw new d(`Invalid version specifier \`${i}\` for slot \`${r}\`.`,{reason:"invalid_input",suggestions:["Version must be exact (i.e. `1`), range (i.e. `1 - 2`), or set (i.e. `1 || 2`)."]});let a=M.parse(i);if(a.getCardinality()>5)throw new d(`The number of versions specified for slot \`${r}\` exceeds 5 major versions.`,{reason:"invalid_input",suggestions:["Narrow down the number of versions to 5 or less."]});if(t[r]!==void 0&&(a=M.parse(t[r]).with(a),a.getCardinality()>5))throw new d(`The cumulative number of versions for slot \`${r}\` cannot exceed 5 major versions.`,{reason:"invalid_input",suggestions:["Narrow down the number of versions to 5 or less."]});return [r,a]}))}};var Be=class{constructor(e){this.config=e;}async handle(e){let{output:t,input:n}=this.config,r=t.notify("Loading slots"),i=await this.getSlots(e,e.allowed);r.stop();let a=e.preselected??[];if(a.length>0)return i.filter(({slug:p})=>a.includes(p));let s=e.selected??[];return i.length===0||s.length>0&&i.every(({slug:p})=>s.includes(p))?i.filter(({slug:p})=>s.includes(p)):e.selectionConfirmation!==void 0&&!await n.confirm(e.selectionConfirmation)?i.filter(({slug:c})=>s.includes(c)):n.selectMultiple({message:"Select slots",options:i.map(p=>{let c=s.includes(p.slug);return {value:p,label:p.name,disabled:c,selected:c}})})}async getSlots(e,t){let{workspaceApi:n}=this.config,r=await n.getSlots({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return t===void 0?r:r.filter(({slug:i})=>t.includes(i))}};var $t=class o{constructor(e){this.config=e;}async execute(e){let{sdk:t,configurationManager:n,io:r}=this.config,{output:i}=r,a=await n.load(),s=await this.getComponents(a,e);if(s.length===0){i.inform("No components to add");return}let p={input:r.input,output:r.output,configuration:{...a,components:{...a.components,...Object.fromEntries(s.map(([c,l])=>[c.slug,l.toString()]))}}};await n.update(p.configuration),i.confirm("Configuration updated"),await t.update(p,{clean:true});}async getComponents(e,t){let{componentForm:n,io:{output:r}}=this.config,i=t.components===void 0?void 0:o.getVersionMap(t.components,e.components),a=Object.keys(e.components),s=await n.handle({organizationSlug:e.organization,workspaceSlug:e.workspace,preselected:i===void 0?void 0:Object.keys(i),selected:a});if(a.length===s.length&&s.every(p=>a.includes(p.slug))&&r.inform("No new component to add"),t.components!==void 0&&t.components.length>0&&s.length!==t.components.length){let p=t.components.filter(c=>!s.some(l=>l.slug===c));throw new d(`Non-existing components: \`${p.join("`, `")}\``,{reason:"invalid_input",suggestions:["Run `component add` without arguments to see available components"]})}return s.map(p=>{let c=i?.[p.slug];if(c===void 0||c.getMaxVersion()===p.version.major)return [p,c??M.of(p.version.major)];if(c.getMinVersion()>p.version.major)throw new d(`No matching version for component \`${p.slug}\`.`,{reason:"invalid_input",details:[`Requested version: ${c.toString()}`,`Current version: ${p.version.major}`],suggestions:["Omit version specifier to use the latest version"]});return [p,c]})}static getVersionMap(e,t){return Object.fromEntries(e.map(n=>{let[r,i]=n.split("@",2);if(i===void 0)return [r,void 0];if(!M.isValid(i))throw new d(`Invalid version specifier \`${i}\` for component \`${r}\`.`,{reason:"invalid_input",suggestions:["Version must be exact (i.e. `1`), range (i.e. `1 - 2`), or set (i.e. `1 || 2`)."]});let a=M.parse(i);if(a.getCardinality()>5)throw new d(`The number of versions specified for component \`${r}\` exceeds 5 major versions.`,{reason:"invalid_input",suggestions:["Narrow down the number of versions to 5 or less."]});if(t[r]!==void 0&&(a=M.parse(t[r]).with(a),a.getCardinality()>5))throw new d(`The cumulative number of versions for component \`${r}\` cannot exceed 5 major versions.`,{reason:"invalid_input",suggestions:["Narrow down the number of versions to 5 or less."]});return [r,a]}))}};var ot=class{constructor(e){this.config=e;}async handle(e){let{workspaceApi:t}=this.config,{allowed:n}=e,r=await t.getComponents({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),i=await this.selectComponents(e,n===void 0?r:r.filter(({slug:a})=>n.includes(a)));return e.includeDependencies===true&&i.push(...this.getReferencedComponents(r,i)),i}async selectComponents(e,t){let{output:n,input:r}=this.config;n.notify("Loading components").stop();let a=e.preselected??[];if(a.length>0)return t.filter(({slug:p})=>a.includes(p));let s=e.selected??[];return e.includeDependencies===true&&s.push(...this.getReferencedComponents(t,t.filter(({slug:p})=>s.includes(p))).map(p=>p.slug)),t.length===0||s.length>0&&t.every(({slug:p})=>s.includes(p))?t.filter(({slug:p})=>s.includes(p)):e.selectionConfirmation!==void 0&&!await r.confirm(e.selectionConfirmation)?t.filter(({slug:c})=>s.includes(c)):r.selectMultiple({message:"Select components",options:t.map(p=>{let c=s.includes(p.slug);return {value:p,label:p.name,disabled:c,selected:c}})})}getReferencedComponents(e,t){let n=new Map;for(let r of t){let i=new Set([...r.metadata.directReferences,...r.metadata.indirectReferences]);for(let a of i)if(!t.some(({slug:s})=>s===a)){let s=e.find(({slug:p})=>p===a);s!==void 0&&n.set(s.slug,s);}}return [...n.values()]}};var dn=class o{constructor(e){this.config=e;}async execute(e){let{sdk:t,configurationManager:n,slotForm:r,io:i}=this.config,{output:a}=i,s=await n.load(),p=e.slots===void 0?void 0:o.getVersionMap(e.slots,s.slots),c=await r.handle({organizationSlug:s.organization,workspaceSlug:s.workspace,allowed:Object.keys(s.slots),preselected:p===void 0?void 0:Object.keys(p)});if(c.length===0)return a.inform("No slots to remove.");let l={input:i.input,output:i.output,configuration:{...s,slots:Object.fromEntries(Object.entries(s.slots).flatMap(([u,g])=>p?.[u]!==void 0?p[u]===null?[]:[[u,p[u].toString()]]:c.some(y=>y.slug===u)?[]:[[u,g.toString()]]))}};await n.update(l.configuration),a.confirm("Configuration updated"),await t.update(l,{clean:true});}static getVersionMap(e,t){return Object.fromEntries(e.map(n=>{let[r,i]=n.split("@",2);if(t[r]===void 0||i===void 0)return [r,null];let a=M.parse(t[r]);if(!M.isValid(i))return [r,a];let s=M.parse(i);return a.intersects(s)?s.contains(a)?[r,null]:[r,a.without(s)]:[r,a]}))}};var gn=class o{constructor(e){this.config=e;}async execute(e){let{sdk:t,configurationManager:n,componentForm:r,io:i}=this.config,{output:a}=i,s=await n.load(),p=e.components===void 0?void 0:o.getVersionMap(e.components,s.components),c=await r.handle({organizationSlug:s.organization,workspaceSlug:s.workspace,allowed:Object.keys(s.components),preselected:p===void 0?void 0:Object.keys(p)});if(c.length===0)return a.alert("No components to remove.");let l={input:i.input,output:i.output,configuration:{...s,components:Object.fromEntries(Object.entries(s.components).flatMap(([u,g])=>p?.[u]!==void 0?p[u]===null?[]:[[u,p[u].toString()]]:c.some(y=>y.slug===u)?[]:[[u,g.toString()]]))}};a.confirm("Configuration updated"),await n.update(l.configuration),await t.update(l,{clean:true});}static getVersionMap(e,t){return Object.fromEntries(e.map(n=>{let[r,i]=n.split("@",2);if(t[r]===void 0||i===void 0)return [r,null];let a=M.parse(t[r]);if(!M.isValid(i))return [r,a];let s=M.parse(i);return a.intersects(s)?s.contains(a)?[r,null]:[r,a.without(s)]:[r,a]}))}};var Mr=class{constructor({manager:e,initializer:t}){this.manager=e,this.initializer=t;}isInitialized(){return this.manager.isInitialized()}async load(){return await this.isInitialized()||await this.initializer.initialize(),this.manager.load()}update(e){return this.manager.update(e)}};var fn=class{constructor(e){this.configuration=e;}async execute(e){let{sdk:t,configurationManager:n,io:r}=this.configuration,i={input:r.input,output:r.output,configuration:await n.load()};await t.update(i,{clean:e.clean});}};var Nr=class o{static{this.SITEMAP={Home:"/","Personal settings":"/settings",Organization:"/organizations/:organization","Organization settings":"/organizations/:organization/settings","Organization members":"/organizations/:organization/members",Workspace:"/organizations/:organization/workspaces/:workspace","Workspace settings":"/organizations/:organization/workspaces/:workspace/settings","Workspace members":"/organizations/:organization/workspaces/:workspace/members","Dev application":"/organizations/:organization/workspaces/:workspace/applications/:dev-application/dashboard","Prod application":"/organizations/:organization/workspaces/:workspace/applications/:prod-application/dashboard","Dev application settings":"/organizations/:organization/workspaces/:workspace/applications/:dev-application/settings","Prod application settings":"/organizations/:organization/workspaces/:workspace/applications/:prod-application/settings",Slots:"/organizations/:organization/workspaces/:workspace/slots",Components:"/organizations/:organization/workspaces/:workspace/components",Experiences:"/organizations/:organization/workspaces/:workspace/experiences"};}constructor(e){this.config=e;}async handle(e){return o.resolvePath(await this.getPage(e.page,e),e)}getPage(e,t){if(e!==void 0){let r=o.findMatch(e,t);if(r!==null)return Promise.resolve(r)}let{input:n}=this.config;return n.select({message:"Where do you want to go?",options:Object.entries(o.SITEMAP).map(([r,i])=>({value:i,label:r}))})}static findMatch(e,t){if(e.startsWith("/"))return e;let n=null,r=.5;for(let i of Object.keys(o.getSitemap(t))){let a=stringSimilarity(e,i);a>r&&(n=o.SITEMAP[i],r=a);}return n}static getSitemap(e){return e.prodApplicationSlug!==void 0?o.SITEMAP:Object.fromEntries(Object.entries(o.SITEMAP).filter(([,t])=>!t.includes(":prod-application")))}static resolvePath(e,t){return e.replace(/:(organization|workspace|(dev|prod)-application)/g,(n,r)=>{switch(r){case "organization":return t.organizationSlug;case "workspace":return t.workspaceSlug;case "dev-application":return t.devApplicationSlug;case "prod-application":return t.prodApplicationSlug??""}})}};var $r=class{constructor({instruction:e,authenticator:t}){this.instruction=e,this.authenticator=t;}getToken(){return this.authenticator.getToken()}login(e){if(Object.keys(e).length===0){let{message:t,...n}=this.instruction;throw new d(t,n)}return this.authenticator.login(e)}logout(){return this.authenticator.logout()}};var Lr=class{constructor(e){this.instruction=e;}prompt(){return this.report()}select(){return this.report()}selectMultiple(){return this.report()}confirm(){return this.report()}wait(){return this.report()}report(){let{message:e,...t}=this.instruction;throw new d(e,t)}};var zr=class{constructor(e){this.authenticators=e;}async getToken(){for(let e of Object.values(this.authenticators)){let t=await e.getToken();if(t!==null)return t}return null}login(e){let t={...e};return delete t.method,this.authenticators[e.method].login(t)}async logout(){await Promise.all(Object.values(this.authenticators).map(e=>e.logout()));}};var yn=class o{constructor(e){this.config=e;}async execute(e){let{sdk:t,configurationManager:n,io:r}=this.config,i=await n.load(),a=await this.selectSlots(i,e.slots),s=await this.selectComponents(i,e.components),p={input:r.input,output:r.output,configuration:{...i,slots:{...i.slots,...Object.fromEntries(a.map(c=>[c.slug,o.resolveVersion(c.version.major,i.slots[c.slug])]))},components:{...i.components,...Object.fromEntries(s.map(c=>[c.slug,o.resolveVersion(c.version.major,i.components[c.slug])]))}}};await n.update(p.configuration),await t.update(p,{clean:true});}async selectComponents(e,t){let{form:{componentForm:n}}=this.config,r=t===void 0?Object.keys(e.components):t,i=r.length===0?[]:await n.handle({organizationSlug:e.organization,workspaceSlug:e.workspace,preselected:r});if(r.length>0&&i.length!==r.length){let a=r.filter(s=>!i.some(p=>p.slug===s));throw new d(`Components not found: \`${a.join("`, `")}\`.`,{reason:"precondition",suggestions:["Run `remove component` to remove a component from your configuration."]})}return i}async selectSlots(e,t){let{form:{slotForm:n}}=this.config,r=t===void 0?Object.keys(e.slots):t,i=r.length===0?[]:await n.handle({organizationSlug:e.organization,workspaceSlug:e.workspace,preselected:r});if(r.length>0&&i.length!==r.length){let a=r.filter(s=>!i.some(p=>p.slug===s));throw new d(`Slots not found: \`${a.join("`, `")}\`.`,{reason:"precondition",suggestions:["Run `remove slot` to remove a slot from your configuration."]})}return i}static resolveVersion(e,t){let n=M.of(e);if(t===void 0)return n.toString();let r=M.parse(t);return r.isExact()?n.toString():r.isRange()?r.getMaxVersion()>=n.getMaxVersion()?t:M.between(r.getMinVersion(),n.getMaxVersion()).toString():M.either(...r.getVersions(),...n.getVersions()).toString()}};var hn=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var _r=class o{static{this.ERRORS={ENOENT:"The file or directory does not exist.",EACCES:"Unable to access the file or directory.",EISDIR:"Expected a file, but the path is a directory.",ENOTDIR:"Expected a directory, but the path is a file.",EPERM:"Operation not permitted.",EEXIST:"The file or directory already exists.",ENOTEMPTY:"The directory is not empty."};}static{this.ERROR_REASONS={ENOENT:"not_found",EACCES:"access_denied",EISDIR:"invalid_input",ENOTDIR:"invalid_input",EPERM:"access_denied",EEXIST:"invalid_input",ENOTEMPTY:"invalid_input"};}constructor(e){this.config={...e,defaultEncoding:e.defaultEncoding??"utf8"};}getSeparator(){return sep}normalizeSeparators(e){return e.replace(/\//g,sep)}getBaseName(e){return basename(e)}getDirectoryName(e){return dirname(e)}getRealPath(e){return this.execute(()=>realpath(this.resolvePath(e)))}getRelativePath(e,t){return relative(this.resolvePath(e),this.resolvePath(t))}isAbsolutePath(e){return isAbsolute(e)}isSubPath(e,t){let n=this.resolvePath(e),r=this.resolvePath(t),i=relative(n,r);return !i.startsWith("..")&&!isAbsolute(i)}isSymbolicLink(e){return this.execute(async()=>{try{return (await lstat(this.resolvePath(e))).isSymbolicLink()}catch(t){if(o.isErrorCode(t,["ENOENT","ENOTDIR"]))return false;throw t}})}isDirectory(e){return this.execute(async()=>{try{return (await lstat(this.resolvePath(e))).isDirectory()}catch(t){if(o.isErrorCode(t,["ENOENT","ENOTDIR"]))return false;throw t}})}isEmptyDirectory(e){return this.execute(async()=>(await readdir(this.resolvePath(e))).length===0)}create(e){switch(e.type){case "file":return this.execute(()=>writeFile(this.resolvePath(e.name),e.content));case "directory":return this.execute(()=>mkdir(this.resolvePath(e.name)));case "link":return this.execute(()=>link(e.target,this.resolvePath(e.name)));case "symlink":return this.execute(()=>symlink(e.target,this.resolvePath(e.name)))}}list(e,t){let n=this.resolvePath(e);return this.listRelatively(n,n,0,t??(()=>true))}async*listRelatively(e,t,n,r){if(!await r(e,n))return;let i=await this.execute(()=>lstat(e)).catch(()=>null);if(i===null)return;if(!i.isDirectory())return yield*this.createEntry(e,dirname(t),i,n,r);let a=await this.execute(()=>readdir(e));for(let s of a){let p=join(e,s),c=await this.execute(()=>lstat(p));await r(p,n)&&(yield*this.createEntry(p,t,c,n,r));}}async*createEntry(e,t,n,r,i){let a=relative(t,e);if(n.isFile()){let s=()=>this.execute(()=>createReadStream(e));yield {type:"file",name:a,get content(){return s()}};}else n.isDirectory()?(yield {type:"directory",name:a},yield*this.listRelatively(e,t,r+1,i)):n.isSymbolicLink()?yield {type:"symlink",name:a,target:await this.execute(()=>realpath(e))}:yield {type:"link",name:a,target:await this.execute(()=>realpath(e))};}joinPaths(...e){return join(...e)}async exists(e){try{return await lstat(this.resolvePath(e)),!0}catch(t){if(o.isErrorCode(t,["ENOENT","ENOTDIR"]))return false;throw t}}delete(e,t){return rm(this.resolvePath(e),{recursive:t?.recursive??false,force:true})}move(e,t,n){return this.execute(async()=>{let r=this.resolvePath(e),i=this.resolvePath(t);n?.overwrite===true&&await rm(i,{force:true,recursive:true}),await mkdir(dirname(i),{recursive:true}),await rename(r,i);})}readTextFile(e){return this.execute(()=>readFile(this.resolvePath(e),this.config.defaultEncoding))}writeTextFile(e,t,n){return this.execute(()=>writeFile(this.resolvePath(e),t,{flag:n?.overwrite===true?"w":"wx",encoding:this.config.defaultEncoding}))}async createDirectory(e,t){await this.execute(()=>mkdir(this.resolvePath(e),{recursive:t?.recursive??false}));}createTemporaryDirectory(e){return this.execute(()=>mkdtemp(this.joinPaths(tmpdir(),e)))}copy(e,t,n){return this.execute(()=>cp$1(this.resolvePath(e),this.resolvePath(t),{recursive:true,force:n?.overwrite??false}))}resolvePath(e){return isAbsolute(e)?e:join(this.config.workingDirectory.get(),e)}execute(e){try{let t=e();return t instanceof Promise?t.catch(n=>o.reportError(n)):t}catch(t){o.reportError(t);}}static reportError(e){if(e instanceof Error){let t=Object.entries(o.ERRORS);for(let[n,r]of t)if(o.isErrorCode(e,[n]))throw new hn(r,{reason:o.ERROR_REASONS[n]??"other",cause:e,details:[`Code: ${n}`]})}throw new hn("An unexpected error occurred.",{cause:e})}static isErrorCode(e,t){return !(e instanceof Error)||!("code"in e)||typeof e.code!="string"?false:t.includes(e.code)}};var Fr=class{constructor(e){this.configuration=e;}wait(e){let{listener:t}=this.configuration;return new Promise((n,r)=>{this.focus(()=>t.wait(e).then(n,r));})}focus(e){switch(this.configuration.platform){case "darwin":return this.darwinFocus(e);case "linux":return this.linuxFocus(e);case "win32":return this.win32Focus(e);default:return e()}}async darwinFocus(e){let t=this.runCommand({name:"osascript",arguments:["-e","bundle identifier of (info for (path to frontmost application))"]});await e(),t!==null&&this.runCommand({name:"open",arguments:["-b",t]});}async linuxFocus(e){let t=this.runCommand({name:"xdotool",arguments:["getactivewindow"]});await e(),t!==null&&this.runCommand({name:"xdotool",arguments:["windowactivate",t]});}async win32Focus(e){let t=oe`
|
|
1802
1746
|
Add-Type @"
|
|
1803
1747
|
using System;
|
|
1804
1748
|
using System.Runtime.InteropServices;
|
|
@@ -1811,40 +1755,40 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1811
1755
|
public static extern bool SetForegroundWindow(IntPtr hWnd);
|
|
1812
1756
|
}
|
|
1813
1757
|
"@
|
|
1814
|
-
`,n=
|
|
1758
|
+
`,n=oe`
|
|
1815
1759
|
${t}
|
|
1816
1760
|
[Window]::GetForegroundWindow()
|
|
1817
|
-
`,r=this.runCommand({name:"powershell",arguments:["-Command",`& {${n}}`]});if(await e(),r!==null){let i=
|
|
1761
|
+
`,r=this.runCommand({name:"powershell",arguments:["-Command",`& {${n}}`]});if(await e(),r!==null){let i=oe`
|
|
1818
1762
|
${t}
|
|
1819
1763
|
[Window]::SetForegroundWindow(${r})
|
|
1820
1764
|
[Window]::ShowWindow(${r}, 9)
|
|
1821
|
-
`;this.runCommand({name:"powershell",arguments:["-Command",`& {${i}}`]});}}runCommand(e){let{commandExecutor:t,timeout:n}=this.configuration;try{let r=t.runSync(e,{timeout:n});return r.exitCode!==0?null:r.output.trim()}catch{return null}}};var Fr=class{constructor(e){this.detector=e.detector,this.templates=e.templates;}async generate(e){let t=await this.detector.detect(e.recipient);return t===null||this.templates[t]===void 0?null:this.templates[t].generate(e)}};var jr=class{constructor(...e){this.detectors=e;}async detect(e){for(let t of this.detectors){let n=await t.detect(e);if(n!==null)return n}return null}};var Ur=class o{static{this.DEFAULT_DOMAINS={google:["gmail.com","googlemail.com","google.com"],yahoo:[/yahoo\.com(?:\.\w+)?/,"yahoo.co.uk","yahoo.fr","yahoo.it","ymail.com","rocketmail.com"],microsoft:["outlook.com","live.com","hotmail.com","msn.com","passport.com","passport.net"],proton:["proton.me","protonmail.com"],icloud:["icloud.com"]};}constructor(e=o.DEFAULT_DOMAINS){this.domains=e;}detect(e){let t=e.toLowerCase().split("@")[1];for(let[n,r]of Object.entries(this.domains))if(r.some(a=>typeof a=="string"?a===t:a.test(t)))return Promise.resolve(n);return Promise.resolve(null)}};var Wr=class o{static{this.DEFAULT_DOMAINS={google:["google.com"],microsoft:["outlook.com"]};}constructor(e=o.DEFAULT_DOMAINS){this.domains=e;}async detect(e){let t=e.toLowerCase().split("@")[1],n=await this.lookup(t);for(let[r,i]of Object.entries(this.domains))for(let a of i)for(let s of n)if(s.endsWith(`.${a}.`))return r;return null}async lookup(e){let t=new URL("https://dns.google.com/resolve");t.searchParams.set("type","MX"),t.searchParams.set("name",e);let n;try{n=await fetch(t).then(r=>{if(!r.ok)throw new Error("Failed to lookup domain");return r.json()});}catch{return []}return n.Answer===void 0?[]:n.Answer.map(r=>r.data)}};var Lt=Pt(nn()),Vr=class o{generate(e){return new URL(`https://mail.google.com/mail${o.formatFilters(e)}`)}static formatFilters(e){let t=[`to:${e.recipient}`],n=`/u/${e.recipient}`;if(e.sender!==void 0&&t.push(`from:${e.sender}`),e.subject!==void 0&&t.push(`subject:${e.subject}`),e.timestamp!==void 0){let r=Lt.TimeZone.of(Intl.DateTimeFormat().resolvedOptions().timeZone),i=Lt.Instant.ofEpochSecond(e.timestamp),a=Lt.LocalDateTime.ofInstant(i,r).getLocalDate();t.push(`after:${a}`);}return t.push("in:anywhere"),n+=`/#search/${t.map(r=>encodeURIComponent(r)).join("+")}`,n}};var qr=class{generate(e){return new URL("https://www.icloud.com/mail")}};var Hr=class{generate(e){let t=new URL("https://outlook.live.com/mail");return e.recipient!==void 0&&t.searchParams.append("login_hint",e.recipient),t}};var Kr=class o{generate(e){return new URL(`https://mail.proton.me/u/0/all-mail${o.formatFilters(e)}`)}static formatFilters(e){let t=new URLSearchParams;return t.set("to",e.recipient),e.sender!==void 0&&t.set("from",e.sender),e.timestamp!==void 0&&t.set("begin",e.timestamp.toFixed(0)),e.subject!==void 0&&t.set("keyword",e.subject),`#${t.toString()}`}};var Gr=class o{generate(e){return new URL(`https://mail.yahoo.com/d/search${o.formatFilters(e)}`)}static formatFilters(e){let t=[`to:${e.recipient}`];return e.sender!==void 0&&t.push(`from:${e.sender}`),e.subject!==void 0&&t.push(`subject:${e.subject}`),e.timestamp!==void 0&&t.push(`after:"${new Date(e.timestamp*1e3).toISOString().split("T")[0]}"`),t.length===0?"":`/keyword=${t.join(" ")}`}};var Sn=class{constructor(e){this.config=e;}async execute(e){let{fileSystem:t,io:n}=this.config,r=await this.createTemplate(e.empty??false),i=e.file??t.joinPaths(".","template.json5");try{let a=!1;await t.exists(i)&&(a=await n.input?.confirm({message:`Overwrite existing file at \`${i}\`?`,default:!1})??!1),await t.writeTextFile(i,JSON.stringify(r,null,2),{overwrite:a});}catch(a){throw new d("Failed to write template file",{reason:"other",cause:a})}n.output.confirm(`Template created at \`${i}\``);}async createTemplate(e){return {$schema:"https://schema.croct.com/json/v1/template.json",title:"My template",description:"My template description",actions:e?[{name:"print",semantics:"info",title:"Empty template",message:"Edit this template to define your actions."}]:[{name:"create-resource",resources:await this.exportResources()}]}}async exportResources(){let{configurationManager:e,templateForm:t}=this.config,n=await e.load(),r=await t.handle({organizationSlug:n.organization,workspaceSlug:n.workspace}),i={audiences:Object.fromEntries(r.audiences.map(a=>[a.slug,{name:a.name,criteria:a.criteria}])),components:Object.fromEntries(r.components.map(a=>[a.slug,{name:a.name,description:a.description,schema:a.definition}])),slots:Object.fromEntries(r.slots.map(a=>[a.slug,{name:a.name,component:a.component?.slug??"",content:a.content}])),experiences:r.experiences.map(a=>{let{experiment:s}=a,p=s!==void 0?{name:s.name??"",goalId:s.goalId,crossDevice:s.crossDevice,traffic:s.traffic??1,variants:s.variants.map(c=>({name:c.name??"",content:c.content,baseline:c.baseline,allocation:c.allocation??1e3/s.variants.length}))}:void 0;return {name:a.name,draft:a.status==="DRAFT",audiences:a.audiences,slots:a.slots,content:a.content,...p!==void 0?{experiment:p}:{}}})};for(let[a,s]of Object.entries(i))typeof s=="object"&&s!==null&&(Array.isArray(s)&&s.length===0||Object.keys(s).length===0)&&delete i[a];return i}};var Zr=class{constructor(e){this.config=e;}async handle(e){let{input:t,form:n}=this.config,r={components:[],slots:[],audiences:[],experiences:[]},i=new Set,a=new Set,s=await n.experience.handle({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,confirmation:"Do you want to include experiences?"});if(s.length>0){for(let c of s.flatMap(l=>l.audiences))i.add(c);for(let c of s.flatMap(l=>l.slots))a.add(c);r.experiences=s,s.some(c=>c.experiment!==void 0)&&(await t.confirm({message:"Include experiments?",default:false})||(r.experiences=r.experiences.map(c=>{let{experiment:l,...u}=c;return u})));}r.slots=await n.slot.handle({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,selected:[...a],selectionConfirmation:{message:a.size>0?"Do you want to include other slots?":"Do you want to include slots?",default:false}});let p=new Set(r.slots.map(c=>c.component?.slug??""));return r.components=await n.component.handle({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,includeDependencies:true,selected:[...p],selectionConfirmation:{message:p.size>0?"Do you want to include other components?":"Do you want to include components?",default:false}}),r.audiences=await n.audience.handle({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,selected:[...i],selectionConfirmation:{message:i.size>0?"Do you want to include other audiences?":"Do you want to include audiences?",default:false}}),r}};var Jr=class{constructor(e){this.config=e;}async handle(e){let{output:t,input:n,workspaceApi:r}=this.config,i=t.notify("Loading experiences"),a=await r.getExperiences({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});i.stop();let{confirmation:s}=e;if(a.length===0||s!==void 0&&!await n.confirm({message:s}))return [];let p=await n.selectMultiple({message:"Select experiences",options:a.map(l=>({value:l,label:l.name}))});i=t.notify("Loading details");let c=await Promise.all(p.flatMap(async({id:l})=>{let u=await r.getExperience({experienceId:l,organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return u===null?[]:[u]}));return i.stop(),c.flat()}};var Qr=class{constructor(e){this.config=e;}async handle(e){let{output:t,input:n}=this.config,r=t.notify("Loading audiences"),i=await this.getAudiences(e,e.allowed);r.stop();let a=e.preselected??[];if(a.length>0)return i.filter(({slug:p})=>a.includes(p));let s=e.selected??[];return i.length===0||s.length>0&&i.every(({slug:p})=>s.includes(p))?i.filter(({slug:p})=>s.includes(p)):e.selectionConfirmation!==void 0&&!await n.confirm(e.selectionConfirmation)?i.filter(({slug:c})=>s.includes(c)):n.selectMultiple({message:"Select audiences",options:i.map(p=>{let c=s.includes(p.slug);return {value:p,label:p.name,disabled:c,selected:c}})})}async getAudiences(e,t){let{workspaceApi:n}=this.config,r=await n.getAudiences({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return t===void 0?r:r.filter(({slug:i})=>t.includes(i))}};var S=class o extends d{constructor(e,{tracing:t,...n}={}){super(e,n),this.tracing=t??[],Object.setPrototypeOf(this,o.prototype);}static fromCause(e,t={}){let{message:n,...r}=t;if(!(e instanceof Error))return new o(n??d.formatMessage(e),{...r,cause:e});let i=new o(n??e.message,{cause:e,...e instanceof d?e.help:{},...r,tracing:[...r.tracing??[],...e instanceof o?e.tracing:[]]});return i.stack=e.stack,i}};var zt=class{constructor(e){this.variables={};this.input=e.input,this.output=e.output,this.baseUrl=e.baseUrl;}getVariables(){return structuredClone(this.variables)}set(e,t){this.variables[e]=t;}};var Br=class{constructor(e){this.config=e;}async getOptions(e){let{templateProvider:t}=this.config;return (await t.get(await this.resolveUrl(e))).value.options??{}}async execute(e){let{action:t,io:n}=this.config,{template:r,options:i}=e,a=await this.resolveUrl(r);return t.execute({template:a.toString(),options:i},new zt({input:n.input,output:n.output,baseUrl:a}))}async resolveUrl(e){let{fileSystem:t}=this.config,n=e;if(URL.canParse(e)){let r=new URL(e.replace(/(?<=^[a-z]+:\/*)([^/.:]+)/i,i=>i.replace(/@/g,"%40")));if(r.protocol!=="file:")return r;n=t.normalizeSeparators(r.pathname);}try{return new URL(`file://${await t.getRealPath(n)}`)}catch(r){throw new S(`Template file not found at \`${n}\`.`,{reason:"invalid_input",cause:r,suggestions:["Check the file path and try again."]})}}};function St(o,e){if(URL.canParse(o))return new URL(o);let t=new URL(e.href.replace(/^(.*:)(?!\/)/,"$1/"));return new URL(o,t)}var Yr=class{constructor(e){this.config=e;}async execute(e,t){let{fileSystem:n}=this.config,{input:r}=t,i=St(e.source,t.baseUrl);if(i.protocol==="file:"&&t.baseUrl.protocol!=="file:")throw new S("File URL is not allowed from remote sources for security reasons.",{reason:"precondition",details:[`Source URL: ${i}`]});let a=n.normalizeSeparators(e.destination),{output:s}=t,p=s?.notify("Downloading sources");try{await this.download(i,{...e,destination:a},r);}finally{p?.stop();}e.result?.destination!==void 0&&t.set(e.result.destination,a);}async download(e,t,n){let{provider:r,fileSystem:i,codemod:a}=this.config,{destination:s,overwrite:p=false}=t,c=t.filter!==void 0?new Minimatch(t.filter):void 0,{value:l}=await r.get(e),u=[],g=Object.fromEntries(Object.entries(t.mapping??{}).map(([y,C])=>[i.normalizeSeparators(y),i.normalizeSeparators(C)]));for await(let y of l){let C=this.resolvePath(i.normalizeSeparators(y.name),g);if(i.isAbsolutePath(C))throw new S("Path to downloaded file cannot be absolute.",{reason:"precondition",details:[`Path: ${C}`],suggestions:["Use relative paths"]});if(!(c!==void 0&&!c.match(C))){if(y.name=i.joinPaths(s,C),y.type==="link"||y.type==="symlink"){let v=i.normalizeSeparators(y.target);if(i.isAbsolutePath(v)||!i.isSubPath(s,v))continue;y.target=v;}u.push(y);}}if(u.length===0)throw new S("No matching files found for download.",{reason:"unexpected_result",details:[`Source: ${e}`,`Filter: ${t.filter??"none"}`]});await this.createDirectory(u,s,p,n);for(let y of u)await i.createDirectory(i.getDirectoryName(y.name),{recursive:true}),await i.create(y);for(let y of u)y.type==="file"&&await a.apply(await i.getRealPath(y.name));}resolvePath(e,t){if(e in t)return t[e];let{fileSystem:n}=this.config,r="",i=e,a=n.getSeparator();for(let[s,p]of Object.entries(t)){let c=s.endsWith(a)?s:s+a;e.startsWith(c)&&c.length>r.length&&(r=c,i=n.joinPaths(p,e.slice(c.length)));}return i}async createDirectory(e,t,n,r){let{fileSystem:i}=this.config;if(!await i.exists(t))return i.createDirectory(t,{recursive:true});if(e.length===1&&e[0].type==="file"){if(!n&&await i.exists(e[0].name)&&await r?.confirm({message:`File ${e[0].name} already exists. Do you want to overwrite it?`,default:false})!==true)throw new S("Destination file already exists.",{reason:"precondition",details:[`File: ${e[0].name}`],suggestions:["Delete the file"]});return}if(await i.isDirectory(t)){if(!n&&!await i.isEmptyDirectory(t)&&await r?.confirm({message:`Directory ${t} is not empty. Do you want to clear it?`,default:false})!==true)throw new S("Destination directory is not empty.",{reason:"precondition",details:[`Directory: ${t}`],suggestions:["Clear the directory"]})}else if(await r?.confirm({message:`Destination ${t} is not a directory. Do you want to delete it?`,default:false})!==true)throw new S("Destination is not a directory.",{reason:"precondition",details:[`Path: ${t}`],suggestions:["Delete the file"]});await i.delete(t,{recursive:true}),await i.createDirectory(t,{recursive:true});}};var Xr=class{constructor({packageManager:e}){this.packageManager=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Installing dependencies");try{await this.packageManager.addDependencies(e.dependencies,{dev:e.development??!1,logger:new ge({status:"Installing dependencies",notifier:r})});}catch(i){throw S.fromCause(i)}finally{r?.stop();}}};var _t=class o{constructor(e){this.matcher=e;}static fromPattern(e){return new o(new Minimatch(e.replace(/^\.\//,"").replace(/\\/g,"/")))}test(e){return Promise.resolve(this.matcher.match(e))}};var ei=class{constructor({projectDirectory:e,fileSystem:t,scanFilter:n}){this.projectDirectory=e,this.fileSystem=t,this.scanFilter=n;}async execute(e,t){let{output:n}=t,r=n?.notify("Locating files");try{await this.findMatches(e,t);}finally{r?.stop();}}async findMatches(e,t){t.set(e.result,await this.findMatch(e.path,e));}async findMatch(e,t){let n=(a,s)=>t.depth!==void 0&&s>t.depth?false:this.scanFilter!==void 0?this.scanFilter(a,s):true,r=[],i=_t.fromPattern(e);for await(let a of this.fileSystem.list(this.projectDirectory.get(),n))if(await i.test(a.name)){if(t.matcher===void 0)r.push(a.name);else if(a.type==="file"){let s=await new Response(a.content).text();this.matches(s,t.matcher)&&r.push(a.name);}if(t.limit!==void 0&&r.length>=t.limit)break}return r}matches(e,t){if("pattern"in t)return new RegExp(t.pattern,t.caseSensitive===true?"i":void 0).test(e);switch(t.type){case "and":return t.matchers.every(n=>this.matches(e,n));case "or":return t.matchers.some(n=>this.matches(e,n))}}};var ti=class{constructor({fileSystem:e}){this.fileSystem=e;}async execute(e,t){let{output:n}=t,r=n.notify("Replacing file content");try{await this.replaceFiles(e);}finally{r.stop();}}async replaceFiles(e){let t=false;for(let{path:n,replacements:r}of e.files){let i=this.fileSystem.normalizeSeparators(n);if(await this.fileSystem.exists(i)){t=true;try{await this.fileSystem.writeTextFile(i,this.replaceContent(await this.fileSystem.readTextFile(i),r),{overwrite:!0});}catch(a){throw S.fromCause(a)}}}if(!t)throw new S("No files matched for content replacement.",{reason:"unexpected_result"})}replaceContent(e,t){let n=e;for(let{pattern:r,caseSensitive:i,value:a}of t){let s=i===true?"gi":"g";n=n.replace(new RegExp(r,s),`${a}`);}return n}};var ni=class{constructor({installer:e}){this.installer=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Installing slots");try{await this.installer(e.slots,e.example===!0);}catch(i){throw S.fromCause(i)}finally{r?.stop();}}};var ri=class{constructor({installer:e}){this.installer=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Installing components");try{await this.installer(e.components);}catch(i){throw S.fromCause(i)}finally{r?.stop();}}};var ii=class{constructor(e){this.runner=e;}async execute(e,t){try{await this.run(e.action,t);}catch(n){if(e.else===void 0)throw e.help===void 0?n:S.fromCause(n,{...e.help,reason:"precondition"});await this.run(e.else,t);}finally{e.finally!==void 0&&await this.run(e.finally,t);}}run(e,t){return this.runner.execute({actions:e},t)}};var V=class o extends d{constructor(e,t={}){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var at=class{constructor(e){this.provider=e;}get action(){return Promise.resolve(this.provider.get()).catch(e=>{throw e instanceof V?new S(e.message,e.help):e})}async execute(e,t){return (await this.action).execute(e,t)}};var oi=class{constructor(e){this.manager=e;}isInitialized(){return this.manager.isInitialized()}load(){return this.configuration===void 0&&(this.configuration=this.manager.load()),this.configuration}update(e){return this.configuration=this.manager.update(e),this.configuration}};var vs;(r=>{function o(i){let a=new Set(Object.values(i.slots??{}).map(u=>u.component)??[]),s=new Set(i.experiences?.flatMap(u=>u.slots)??[]),p=new Set(i.experiences?.flatMap(u=>u.audiences)??[]),c=(i.experiences??[]).map(u=>({name:u.name,maximumAudiencesPerExperience:u.audiences.length,crossDevice:u.experiment?.crossDevice===true,...e(u)})),l=new Set;for(let u of Object.values(i.slots??{}))for(let g of Object.keys(u.content))l.add(g);for(let u of c){for(let g of u.locales)l.add(g);for(let g of u.audiences)p.add(g);for(let g of u.slots)s.add(g);}return {components:a,slots:s,audiences:p,locales:l,experiences:c}}r.analyze=o;function e(i){let a=t(i.content);for(let s of i.experiment?.variants??[]){let p=t(s.content);p.audiences.forEach(c=>a.audiences.add(c)),p.slots.forEach(c=>a.slots.add(c));}return {...a}}function t(i){let a=new Set,s=new Set,p=0;for(let[u,g]of Object.entries(i.default??{})){a.add(u);for(let[y,C]of Object.entries(g))s.add(y),p=Math.max(p,n(C));}let c=new Set,l=0;for(let u of i.segmented??[]){for(let g of u.audiences)c.add(g);l=Math.max(l,u.audiences.length);for(let[g,y]of Object.entries(u.content)){a.add(g);for(let[C,v]of Object.entries(y))s.add(C),p=Math.max(p,n(v));}}return {slots:a,audiences:c,locales:s,audiencesPerExperience:l,dynamicContentPerContent:p}}function n(i){switch(i.type){case "boolean":case "text":case "number":return i.value.type==="dynamic"?1:0;case "structure":return Object.values(i.attributes).map(n).reduce((a,s)=>a+s,0);case "list":return i.items.map(n).reduce((a,s)=>a+s,0)}}})(vs||={});var ai=class{constructor(e){this.refactoring=e;}refactor(e){return {components:Object.fromEntries(Object.entries(e.components??{}).map(([t,n])=>[this.refactoring.componentMapping[t]??t,{...n,schema:this.refactorSchema(n.schema)}])),slots:Object.fromEntries(Object.entries(e.slots??{}).map(([t,n])=>[this.refactoring.slotMapping[t]??t,this.refactorSlotContent(n)])),audiences:Object.fromEntries(Object.entries(e.audiences??{}).map(([t,n])=>[this.refactoring.audienceMapping[t]??t,n])),experiences:e.experiences?.map(t=>this.refactorExperience(t))??[]}}refactorSchema(e){switch(e.type){case "boolean":case "text":case "number":return e;case "structure":return {...e,attributes:Object.fromEntries(Object.entries(e.attributes).map(([t,n])=>[t,{...n,type:this.refactorSchema(n.type)}]))};case "list":return {...e,items:this.refactorSchema(e.items)};case "union":return {...e,types:Object.fromEntries(Object.entries(e.types).map(([t,n])=>[t,this.refactorSchema(n)]))};case "reference":return {...e,id:this.refactoring.componentMapping[e.id]??e.id}}}refactorSlotContent(e){return {...e,component:this.refactoring.componentMapping[e.component]??e.component,content:this.refactorLocalizedContentMap(e.content)}}refactorExperience(e){let t=e.audiences.slice(0,this.refactoring.maximumAudiencePerExperience),{experiment:n}=e;return {...e,audiences:e.audiences.map(r=>this.refactoring.audienceMapping[r]??r),slots:e.slots.map(r=>this.refactoring.slotMapping[r]??r),experiment:n!==void 0?{...n,variants:n.variants.map(r=>({...r,content:this.refactorPersonalizedContent(r.content,t)})),crossDevice:(n.crossDevice??false)&&this.refactoring.isCrossDeviceFeatureEnabled}:void 0,content:this.refactorPersonalizedContent(e.content,t)}}refactorPersonalizedContent(e,t){return {default:this.refactorSlotContentMap(e.default??{}),segmented:(e.segmented??[]).flatMap(n=>{let r=n.audiences.filter(i=>t.includes(i));return r.length===0?[]:{audiences:r,content:this.refactorSlotContentMap(n.content)}})}}refactorSlotContentMap(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[this.refactoring.slotMapping[t]??t,this.refactorLocalizedContentMap(n)]))}refactorLocalizedContentMap(e){return Object.fromEntries(Object.entries(e).flatMap(([t,n])=>{let r=this.refactoring.localeMapping[t];return r===null||r!==void 0&&e[r]!==void 0?[]:[[r??t,this.refactorContent(n,{dynamicAttributesPerContent:this.refactoring.dynamicAttributesPerContent})]]}))}refactorContent(e,t){switch(e.type){case "boolean":case "text":case "number":return e.value.type==="dynamic"&&t.dynamicAttributesPerContent>0&&t.dynamicAttributesPerContent--,e.value.type==="static"||t.dynamicAttributesPerContent>0?e:{...e,value:{type:"static",value:e.value.default}};case "structure":return {...e,attributes:Object.fromEntries(Object.entries(e.attributes).map(([n,r])=>[n,this.refactorContent(r,t)]))};case "list":return {...e,items:e.items.map(n=>this.refactorContent(n,t))}}}};var si=class o{constructor(e){this.config=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Analyzing resources"),i=vs.analyze(e.resources),{configurationManager:a,api:{workspace:s}}=this.config,p=await a.load(),c=await this.getProjectInfo(p);await this.checkMissingResources({...i,locales:new Set},e.resources,c);let l=await this.createPlan(e.resources,i,c);r?.update("Creating resources");let u=await s.createResources({organizationSlug:p.organization,workspaceSlug:p.workspace,...l.resources});if(r?.stop(),n!==void 0){let g=o.getWarnings(i,c.workspace);if(g.length>0)for(let y of g)n.warn(`${y}`);}e.result!==void 0&&o.setVariables(e.result,l,u,t);}async createPlan(e,t,n){let{mappingForm:r,matcher:i}=this.config,a=await i.match({resources:e,workspaceSlug:n.configuration.workspace,organizationSlug:n.configuration.organization}),s=Object.entries(a.audiences).filter(v=>!("id"in v[1])),p=Object.entries(a.components).filter(v=>!("id"in v[1])),c=Object.entries(a.slots).filter(v=>!("id"in v[1])),l=a.experiences.filter(v=>!("id"in v)),u=l.flatMap(v=>v.experiment===void 0?[]:[v.experiment]);await this.checkRequiredQuota(n,{components:p.length,slots:c.length,audiences:s.length,experiences:l.length,experiments:u.length});let g=await r.handle({organizationSlug:n.configuration.organization,workspaceSlug:n.configuration.workspace,resources:{audiences:s.map(([v])=>v),components:p.map(([v])=>v),slots:c.map(([v])=>v)}}),y={},{workspace:C}=n;for(let v of t.locales)C.locales.includes(v)||(y[v]=C.defaultLocale);return {matches:a,mapping:g,resources:new ai({componentMapping:g.components,audienceMapping:g.audiences,slotMapping:g.slots,dynamicAttributesPerContent:C.quotas.dynamicAttributesPerContent,maximumAudiencePerExperience:C.quotas.audiencesPerExperience,isCrossDeviceFeatureEnabled:C.features.crossDevice,localeMapping:y}).refactor({components:Object.fromEntries(p),slots:Object.fromEntries(c),audiences:Object.fromEntries(s),experiences:l})}}async getProjectInfo(e){let{api:t}=this.config,[n,r]=await Promise.all([t.organization.getWorkspace({organizationSlug:e.organization,workspaceSlug:e.workspace}),t.workspace.getFeatures({organizationSlug:e.organization,workspaceSlug:e.workspace})]);if(n==null||r==null)throw new d("Workspace not found",{title:"Invalid configuration",reason:"invalid_configuration",details:["The workspace defined in the configuration does not exist"],suggestions:["Check the configuration file"]});return {configuration:e,workspace:{...n,...r}}}async checkRequiredQuota(e,t){let{api:{user:n}}=this.config;for(let[r,i]of Object.entries(t)){let a=o.getRemainingQuota(e.workspace,r);if(a<i){let s=await n.getUser().catch(()=>({email:void 0})),p=new URL("https://croct.com/contact/support");throw p.searchParams.set("subject","limit-increase"),p.searchParams.set("organization",e.configuration.organization),p.searchParams.set("message",`I need more quota for ${r}`),s.email!==void 0&&p.searchParams.set("email",s.email),new d(`Not enough ${r} quota available in your workspace.`,{title:"Insufficient quota",reason:"precondition",links:[{label:"Request more quota",url:p.toString()}],details:[`Available: ${a}`,`Required: ${i}`],suggestions:[`Free up quota by removing unused ${r}`,"Request additional quota from support"]})}}}async checkMissingResources(e,t,n){let r=await this.findMissingResources(e,t,n);for(let[i,a]of Object.entries(r))if(a.size>0)throw new d(`Some ${i} referenced in the template are missing`,{title:"Invalid template",reason:"invalid_input",details:[`Missing ${i}: ${Array.from(a).join(", ")}`],suggestions:["Report this issue to the template author"]})}async findMissingResources(e,t,n){let r=new Set(e.components),i=new Set(e.slots),a=new Set(e.audiences),s=new Set(e.locales);for(let c of Object.keys(t.components??{}))r.delete(c);for(let c of Object.keys(t.slots??{}))i.delete(c);for(let c of Object.keys(t.audiences??{}))a.delete(c);let{api:p}=this.config;return await Promise.all([...[...r].map(async c=>{await p.workspace.getComponent({organizationSlug:n.configuration.organization,workspaceSlug:n.configuration.workspace,componentSlug:c})!==null&&r.delete(c);}),...[...i].map(async c=>{await p.workspace.getSlot({organizationSlug:n.configuration.organization,workspaceSlug:n.configuration.workspace,slotSlug:c})!==null&&i.delete(c);}),...[...a].map(async c=>{await p.workspace.getAudience({organizationSlug:n.configuration.organization,workspaceSlug:n.configuration.workspace,audienceSlug:c})!==null&&a.delete(c);}),(async()=>{if(s.size===0)return;let c=await p.organization.getWorkspace({organizationSlug:n.configuration.organization,workspaceSlug:n.configuration.workspace});for(let l of c?.locales??[])s.delete(l);})()]),{components:r,slots:i,audiences:a,locales:s}}static getRemainingQuota(e,t){let n=t.charAt(0).toUpperCase()+t.slice(1);return e.quotas[`remaining${n}`]}static getWarnings(e,t){let n=[];return Math.max(...e.experiences.map(s=>s.dynamicContentPerContent))>t.quotas.dynamicAttributesPerContent&&n.push("Some dynamic values have been removed from the content to fit the workspace quota"),Math.max(...e.experiences.map(s=>s.audiencesPerExperience))>t.quotas.audiencesPerExperience&&n.push("Some audiences have been removed from the experiences to fit the workspace quota"),Array.from(e.locales).filter(s=>!t.locales.includes(s)).length>0&&n.push("Content in unsupported locales have been mapped to default or dropped"),!t.features.crossDevice&&e.experiences.some(s=>s.crossDevice)&&n.push("Cross-device experiments have been disabled "),n}static setVariables(e,t,n,r){if(e.audiences!==void 0)for(let[s]of Object.entries(t.matches.audiences??{}))e.audiences[s]!==void 0&&r.set(e.audiences[s],t.mapping.audiences[s]??s);if(e.components!==void 0)for(let[s]of Object.entries(t.matches.components??{})){let p=e.components[s];if(p!==void 0){let c=t.mapping.components[s]??s,l=t.matches.components[s]??{};p.id!==void 0&&r.set(p.id,c),p.version!==void 0&&r.set(p.version,"version"in l?l.version.major:1);}}if(e.slots!==void 0)for(let[s]of Object.entries(t.matches.slots??{})){let p=e.slots[s];if(p!==void 0){let c=t.mapping.slots[s]??s,l=t.matches.slots[s]??{};p.id!==void 0&&r.set(p.id,c),p.version!==void 0&&r.set(p.version,"version"in l?l.version.major:1);}}let{experiences:i}=t.matches,a=0;for(let[s,p]of i.entries()){if(e.experiences?.[s]!==void 0&&r.set(e.experiences[s],"id"in p&&p.id!==void 0?p.id:n.experiences[a].experienceId),e.experiments?.[s]!==void 0){let{experiment:c}=p,l=c!==void 0&&"id"in c&&c.id!==void 0?c.id:n.experiences[a].experimentId;l!==void 0&&r.set(e.experiments[s],l);}(!("id"in p)||p.id===void 0)&&a++;}}};var Ft=class o{constructor(e){this.config=e;}static prompt(e){return new o(e).handle()}handle(){let{input:e,unavailableSlugs:t=[]}=this.config;return e.prompt({message:this.config.label,default:this.config.default,initial:this.config.initial,validate:n=>/^[a-z]+(-?[a-z0-9]+)*$/i.test(n)?t.includes(n)?"The entered slug is already in use.":true:"The slug must start with a letter and contain only letters, numbers, and hyphens."})}};var pi=class{constructor(e){this.config=e;}async handle(e){let{input:t,workspaceApi:n}=this.config,{resources:r,...i}=e,a=r.slots??[],s=r.components??[],p=r.audiences??[],[c,l,u]=await Promise.all([a.length>0?n.getSlots(i):new Array,s.length>0?n.getComponents(i):new Array,p.length>0?n.getAudiences(i):new Array]),g=s.filter(h=>l.some(w=>w.slug===h)),y={};if(g.length>0){let h=l.map(w=>w.slug);for(let w of g){let B=await Ft.prompt({input:t,initial:w,unavailableSlugs:h,label:`Component \`${w}\` already exists, enter a new component ID:`});h.push(B),y[w]=B;}}let C=a.filter(h=>c.some(w=>w.slug===h)),v={};if(C.length>0){let h=c.map(w=>w.slug);for(let w of C){let B=await Ft.prompt({input:t,initial:w,unavailableSlugs:h,label:`Slot \`${w}\` already exists, enter a new slot ID:`});h.push(B),v[w]=B;}}let D=p.filter(h=>u.some(w=>w.slug===h)),U={};if(D.length>0){let h=u.map(w=>w.slug);for(let w of D){let B=await Ft.prompt({input:t,initial:w,unavailableSlugs:h,label:`Audience \`${w}\` already exists, enter a new audience ID:`});h.push(B),U[w]=B;}}return {components:y,slots:v,audiences:U}}};var ci=class o{constructor(e){this.config=e;}async match(e){let{resources:t,...n}=e,[r,i,a,s]=await Promise.all([this.mapComponents(t.components??{},n),this.mapSlots(t.slots??{},n),this.mapAudiences(t.audiences??{},n),this.mapExperiences(t.experiences??[],n)]);return {components:r,slots:i,audiences:a,experiences:s}}async mapAudiences(e,t){let{workspaceApi:n}=this.config,r=await Promise.all(Object.keys(e).map(async a=>[a,await n.getAudience({...t,audienceSlug:a})])),i={};for(let[a,s]of r)i[a]=s===null||!o.isSimilarAudience(e[a],s)?e[a]:s;return i}async mapComponents(e,t){let{workspaceApi:n}=this.config,r=await Promise.all(Object.keys(e).map(async a=>[a,await n.getComponent({...t,componentSlug:a})])),i={};for(let[a,s]of r)i[a]=s===null||!o.isSimilarComponent(e[a],s)?e[a]:s;return i}async mapSlots(e,t){let{workspaceApi:n}=this.config,r=await Promise.all(Object.keys(e).map(async a=>[a,await n.getSlot({...t,slotSlug:a})])),i={};for(let[a,s]of r)i[a]=s===null||!o.isSimilarSlot(e[a],s)?e[a]:s;return i}async mapExperiences(e,t){let{workspaceApi:n}=this.config,i=(await n.getExperiences({...t,status:["ACTIVE","PAUSED","DRAFT"]})).map(a=>{let s=null;function p(){return s===null&&(s=n.getExperience({...t,experienceId:a.id})),s}return {...a,details:{get content(){return p().then(c=>c?.content??null)},get experiment(){return p().then(c=>c?.experiment??null)}}}});return Promise.all(e.map(async a=>{for(let s of i)if(await this.matchesExperience(a,s)){let{details:p,...c}=s;return c}return a}))}async matchesExperience(e,t){if((e.draft===true?"DRAFT":"ACTIVE")!==t.status||!deepEqual(e.audiences,t.audiences)||!deepEqual(e.slots,t.slots)||e.experiment!==void 0&&t.experiment===void 0)return false;let[r,i=null]=await Promise.all([t.details.content,t.details.experiment]);return e.experiment!==void 0&&(i===null||e.experiment.goalId!==i.goalId||e.experiment.traffic!==i.traffic||e.experiment.crossDevice!==i.crossDevice||!o.isSimilarExperimentContent(e.experiment.variants,i.variants))?false:o.isSimilarPersonalizedContent(e.content,r??{default:{},segmented:[]})}static isSimilarAudience(e,t){return e.criteria===t.criteria}static isSimilarComponent(e,t){return deepEqual(e.schema,t.definition)}static isSimilarSlot(e,t){return e.component===t.component?.slug&&Object.values(e.content).some(n=>Object.values(t.content).some(r=>deepEqual(n,r)))}static isSimilarExperimentContent(e,t){return e.length!==t.length?false:e.some((n,r)=>deepEqual(n,t[r]))}static isSimilarPersonalizedContent(e,t){if(o.isSimilarSlotContent(e.default??{},t.default??{}))return true;for(let n of e.segmented??[])for(let r of t.segmented??[])if(deepEqual(n.audiences,r.audiences)&&o.isSimilarSlotContent(n.content,r.content))return true;return false}static isSimilarSlotContent(e,t){for(let[n,r]of Object.entries(e)){let i=t[n];if(i!==void 0){for(let a of Object.values(r))if(Object.values(i).some(s=>deepEqual(a,s)))return true}}return false}};var z=class o extends V{constructor(e,{url:t,...n}){super(e,n),Object.setPrototypeOf(this,o.prototype),this.url=t;}},He=class o extends z{constructor(e,t){super(e,{...t,reason:t.reason??"not_found"}),Object.setPrototypeOf(this,o.prototype);}};var li=class o{constructor(e={}){this.configuration=e;}async get(e){if(!["http:","https:"].includes(e.protocol))throw new z("Unsupported protocol.",{reason:"not_supported",url:e});return {url:e,value:await this.fetch(e)}}async fetch(e,t=0){let n=await fetch(e);if(n.status===404)throw new He("Resource not found.",{url:e});let{maxAttempts:r=0,delay:i=1e3}=this.configuration.retry??{};if(o.isSuccessful(n))return n;if(o.isRetryableCode(n.status)&&t<r)return await new Promise(a=>{setTimeout(a,i);}),this.fetch(e,t+1);throw new z(n.statusText,{url:e})}static isSuccessful(e){return e.ok&&e.body!==null}static isRetryableCode(e){return e>=500||[429,408].includes(e)}};var ui=class{constructor({packageManager:e}){this.packageManager=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Checking dependencies"),i;try{i=await Promise.all(e.dependencies.map(s=>this.checkRequirement(s)));}finally{r?.stop();}let a=[];for(let s of i){if(e?.result?.[s.dependency]!==void 0){t.set(e.result[s.dependency],s.satisfied);continue}s.issue!==void 0&&a.push(s);}if(a.length>0){let{message:s,...p}=e.help??{};throw new S(s??"Missing required dependencies.",{...p,details:a.map(({dependency:c,issue:l})=>`\`${c}\`: ${l}`)})}}async checkRequirement(e){let{name:t,version:n,optional:r=false}=e;if(n===void 0){let a=await this.packageManager.hasDirectDependency(t);if(a||r)return {dependency:t,satisfied:a}}else {let a=await this.packageManager.hasDirectDependency(t,n);if(a||r)return {dependency:t,satisfied:a}}let i=await this.packageManager.getDependency(t);return {dependency:t,satisfied:false,issue:i===null?"not installed":`${n!==void 0?`version \`${n}\` is required`:""}found \`${i.version??"unknown"}\``}}};var It=class{constructor({dataProvider:e,registryProvider:t,baseUrl:n}){this.dataProvider=e,this.registryProvider=t,this.baseUrl=n;}async get(e){return this.dataProvider.get(await this.resolveUrl(e))}async resolveUrl(e){for(let{pattern:t,destination:n}of await this.loadMappings(e)){let r=e.href.match(typeof t=="string"?new RegExp(t):t);if(r!==null)return n instanceof URL?n:new URL(n.replace(/\$([0-9]+)/g,(i,a)=>r[Number.parseInt(a,10)]),this.baseUrl)}return e}async loadMappings(e){let t=await this.registryProvider.get(e);return Array.isArray(t)?t:t.value}};var Ke=class o{static{this.DEFAULT_EXPECTED_ERRORS=["not_supported","not_found","other"];}constructor({providers:e,expectedErrors:t}){this.providers=e,this.expectedErrors=t??o.DEFAULT_EXPECTED_ERRORS;}async get(e){for(let t of this.providers)try{return await t.get(e)}catch(n){if(!this.isExpectedError(n))throw n}throw new He("Resource not found.",{url:e})}isExpectedError(e){return e instanceof z&&this.expectedErrors.includes(e.reason)}};var mi=class o{constructor(e,t){this.fileSystem=e,this.filter=t;}get(e){if(!o.supportsUrl(e))throw new z(`Unsupported protocol "${e.protocol}".`,{reason:"not_supported",url:e});return Promise.resolve({url:e,value:this.fileSystem.list(this.fileSystem.normalizeSeparators(e.pathname),this.filter)})}static supportsUrl(e){return e.protocol==="file:"}};var di=class o{static{this.MAX_DOWNLOAD_FILES=50;}static{this.PROTOCOL="github:";}static{this.API_HOST="api.github.com";}static{this.RAW_HOST="raw.github.com";}static{this.MAIN_HOST="github.com";}constructor({cache:e,provider:t}){this.provider=t,this.cache=e??new NoopCache;}async get(e){let t=this.parseUrl(e);if(t===null)throw new z("Unsupported GitHub URL.",{reason:"not_supported",url:e});let n=await this.resolveFiles(t),r=await Promise.all(n.map(async i=>({url:i,response:(await this.provider.get(i)).value})));return {url:t.canonicalUrl,value:this.yieldFiles(r,t.path??"")}}async*yieldFiles(e,t){let n=new Set;for(let{url:r,response:i}of e){let a=r.pathname.split("/"),s=a.slice(4),p=s.join("/")===t&&e.length===1?a.slice(-1):s.slice(t.split("/").length);if(p.length>1){let c=p.slice(0,-1);for(let l=0;l<c.length;l++){let u=c.slice(0,l+1).join("/");n.has(u)||(n.add(u),yield {type:"directory",name:u});}}yield {type:"file",name:p.join("/"),content:Readable.fromWeb(i.body)};}}async resolveFiles(e){let{username:t,repository:n,path:r}=e,i=p=>{let c=new URL(`https://${o.RAW_HOST}`);return c.pathname=`/${t}/${n}/${e.ref??"HEAD"}/${p}`,c},a=await this.loadGitTree(e),s=[];if(r===null)s.push(...a.map(p=>i(p.path)));else {let p=a.find(c=>c.path===r);if(p===void 0)throw new z("File not found.",{reason:"not_found",url:e.canonicalUrl});p.type==="tree"?s.push(...a.filter(c=>c.path.startsWith(r)&&c.type==="blob").map(c=>i(c.path))):s.push(i(r));}if(s.length>o.MAX_DOWNLOAD_FILES)throw new z(`The number of files to download exceeds the limit of ${o.MAX_DOWNLOAD_FILES}.`,{reason:"precondition",url:e.canonicalUrl});return s}parseUrl(e){if(!o.isUrlSupported(e))return null;let t,n,r=null,i,a=((e.protocol===o.PROTOCOL?e.hostname:"")+e.pathname).replace(/^\/+/,"").split("/"),s=null;return e.hostname===o.MAIN_HOST?(s=e,[t=null,n=null,,r=null,...i]=a):[t=null,n=null,...i]=a,t===null||n===null?null:(s===null&&(s=new URL(`https://${o.MAIN_HOST}`),s.pathname=`/${t}/${n}/blob/master/${i.join("/")}`),{canonicalUrl:s,username:t,repository:n,ref:r,path:i!==void 0&&i.length>0?i.join("/"):null})}loadGitTree({username:e,repository:t,ref:n}){let r=new URL(`https://${o.API_HOST}`);return r.pathname=`repos/${e}/${t}/git/trees/${n??"HEAD"}`,r.searchParams.set("recursive","true"),this.cache.get(r.toString(),()=>this.provider.get(r).then(i=>i.value.json()).then(({tree:i})=>i))}static isUrlSupported(e){return e.protocol==="https:"?e.hostname===o.MAIN_HOST:e.protocol===o.PROTOCOL}};var bn=class o{constructor(e){this.provider=e;}async get(e){if(!o.supportsUrl(e))throw new z("Unsupported URL.",{reason:"not_supported",url:e});let{value:t,...n}=await this.provider.get(e);return {...n,value:this.yield(t,e)}}static supportsUrl(e){return e.pathname!=="/"}async*yield(e,t){yield {type:"file",name:t.pathname.split("/").pop(),content:Readable.fromWeb(e.body)};}};var ee=class{constructor(e){this.schema=e;}async validate(e){let t=await this.schema.safeParseAsync(e);if(t.success)return {valid:true,data:t.data};let{error:n}=t;return {valid:false,violations:n.issues.map(r=>({path:r.path.reduce((i,a)=>typeof a=="string"?i===""?a:`${i}.${a}`:`${i}[${a}]`,""),message:r.message}))}}};var Lu=z$1.object({name:z$1.string(),version:z$1.string().optional(),dependencies:z$1.record(z$1.string()).optional(),devDependencies:z$1.record(z$1.string()).optional(),bin:z$1.record(z$1.string()).optional(),scripts:z$1.record(z$1.string()).optional(),packageManager:z$1.string().optional()}),In=class extends ee{constructor(){super(Lu);}};var gi=z$1.string().regex(/^[a-z]+(-?[a-z0-9]+)*$/i,"An identifier must start with a letter and contain only letters, numbers, and hyphens."),Dc=z$1.string().regex(/^[a-z]{2,3}([-_][a-z]{2,3})?$/i,"Locale must be in the form of en, en_US, or en-US."),Mc=z$1.string().refine(M.isValid,"Version must be exact (1), range (1 - 2), or set (1, 2).").refine(o=>{try{return M.parse(o).getCardinality()<=5}catch{return false}},"Version range must not exceed 5 major versions."),zu=z$1.strictObject({$schema:z$1.string().optional(),organization:gi,workspace:gi,applications:z$1.strictObject({development:gi,production:gi.optional()}),locales:z$1.array(Dc).min(1),defaultLocale:Dc,slots:z$1.record(Mc).default({}),components:z$1.record(Mc).default({}),paths:z$1.strictObject({source:z$1.string().optional(),utilities:z$1.string().optional(),components:z$1.string().optional(),examples:z$1.string().optional(),content:z$1.string().optional()}).optional()}).refine(o=>o.locales.includes(o.defaultLocale),{message:"The default locale is not included in the list of locales.",path:["defaultLocale"]}),fi=class extends ee{constructor(){super(zu);}};var jt=class{constructor({provider:e,validator:t}){this.provider=e,this.validator=t;}async get(e){let{value:t,...n}=await this.provider.get(e),r=await this.validator.validate(t);if(!r.valid){let i=r.violations.map(a=>` \u2022 **${a.path}**: ${a.message}`).join(`
|
|
1765
|
+
`;this.runCommand({name:"powershell",arguments:["-Command",`& {${i}}`]});}}runCommand(e){let{commandExecutor:t,timeout:n}=this.configuration;try{let r=t.runSync(e,{timeout:n});return r.exitCode!==0?null:r.output.trim()}catch{return null}}};var jr=class{constructor(e){this.detector=e.detector,this.templates=e.templates;}async generate(e){let t=await this.detector.detect(e.recipient);return t===null||this.templates[t]===void 0?null:this.templates[t].generate(e)}};var Ur=class{constructor(...e){this.detectors=e;}async detect(e){for(let t of this.detectors){let n=await t.detect(e);if(n!==null)return n}return null}};var Wr=class o{static{this.DEFAULT_DOMAINS={google:["gmail.com","googlemail.com","google.com"],yahoo:[/yahoo\.com(?:\.\w+)?/,"yahoo.co.uk","yahoo.fr","yahoo.it","ymail.com","rocketmail.com"],microsoft:["outlook.com","live.com","hotmail.com","msn.com","passport.com","passport.net"],proton:["proton.me","protonmail.com"],icloud:["icloud.com"]};}constructor(e=o.DEFAULT_DOMAINS){this.domains=e;}detect(e){let t=e.toLowerCase().split("@")[1];for(let[n,r]of Object.entries(this.domains))if(r.some(a=>typeof a=="string"?a===t:a.test(t)))return Promise.resolve(n);return Promise.resolve(null)}};var Vr=class o{static{this.DEFAULT_DOMAINS={google:["google.com"],microsoft:["outlook.com"]};}constructor(e=o.DEFAULT_DOMAINS){this.domains=e;}async detect(e){let t=e.toLowerCase().split("@")[1],n=await this.lookup(t);for(let[r,i]of Object.entries(this.domains))for(let a of i)for(let s of n)if(s.endsWith(`.${a}.`))return r;return null}async lookup(e){let t=new URL("https://dns.google.com/resolve");t.searchParams.set("type","MX"),t.searchParams.set("name",e);let n;try{n=await fetch(t).then(r=>{if(!r.ok)throw new Error("Failed to lookup domain");return r.json()});}catch{return []}return n.Answer===void 0?[]:n.Answer.map(r=>r.data)}};var Lt=Pt(rn()),qr=class o{generate(e){return new URL(`https://mail.google.com/mail${o.formatFilters(e)}`)}static formatFilters(e){let t=[`to:${e.recipient}`],n=`/u/${e.recipient}`;if(e.sender!==void 0&&t.push(`from:${e.sender}`),e.subject!==void 0&&t.push(`subject:${e.subject}`),e.timestamp!==void 0){let r=Lt.TimeZone.of(Intl.DateTimeFormat().resolvedOptions().timeZone),i=Lt.Instant.ofEpochSecond(e.timestamp),a=Lt.LocalDateTime.ofInstant(i,r).getLocalDate();t.push(`after:${a}`);}return t.push("in:anywhere"),n+=`/#search/${t.map(r=>encodeURIComponent(r)).join("+")}`,n}};var Hr=class{generate(e){return new URL("https://www.icloud.com/mail")}};var Kr=class{generate(e){let t=new URL("https://outlook.live.com/mail");return e.recipient!==void 0&&t.searchParams.append("login_hint",e.recipient),t}};var Gr=class o{generate(e){return new URL(`https://mail.proton.me/u/0/all-mail${o.formatFilters(e)}`)}static formatFilters(e){let t=new URLSearchParams;return t.set("to",e.recipient),e.sender!==void 0&&t.set("from",e.sender),e.timestamp!==void 0&&t.set("begin",e.timestamp.toFixed(0)),e.subject!==void 0&&t.set("keyword",e.subject),`#${t.toString()}`}};var Zr=class o{generate(e){return new URL(`https://mail.yahoo.com/d/search${o.formatFilters(e)}`)}static formatFilters(e){let t=[`to:${e.recipient}`];return e.sender!==void 0&&t.push(`from:${e.sender}`),e.subject!==void 0&&t.push(`subject:${e.subject}`),e.timestamp!==void 0&&t.push(`after:"${new Date(e.timestamp*1e3).toISOString().split("T")[0]}"`),t.length===0?"":`/keyword=${t.join(" ")}`}};var bn=class{constructor(e){this.config=e;}async execute(e){let{fileSystem:t,io:n}=this.config,r=await this.createTemplate(e.empty??false),i=e.file??t.joinPaths(".","template.json5");try{let a=!1;await t.exists(i)&&(a=await n.input?.confirm({message:`Overwrite existing file at \`${i}\`?`,default:!1})??!1),await t.writeTextFile(i,JSON.stringify(r,null,2),{overwrite:a});}catch(a){throw new d("Failed to write template file",{reason:"other",cause:a})}n.output.confirm(`Template created at \`${i}\``);}async createTemplate(e){return {$schema:"https://schema.croct.com/json/v1/template.json",title:"My template",description:"My template description",actions:e?[{name:"print",semantics:"info",title:"Empty template",message:"Edit this template to define your actions."}]:[{name:"create-resource",resources:await this.exportResources()}]}}async exportResources(){let{configurationManager:e,templateForm:t}=this.config,n=await e.load(),r=await t.handle({organizationSlug:n.organization,workspaceSlug:n.workspace}),i={audiences:Object.fromEntries(r.audiences.map(a=>[a.slug,{name:a.name,criteria:a.criteria}])),components:Object.fromEntries(r.components.map(a=>[a.slug,{name:a.name,description:a.description,schema:a.definition}])),slots:Object.fromEntries(r.slots.map(a=>[a.slug,{name:a.name,component:a.component?.slug??"",content:a.content}])),experiences:r.experiences.map(a=>{let{experiment:s}=a,p=s!==void 0?{name:s.name??"",goalId:s.goalId,crossDevice:s.crossDevice,traffic:s.traffic??1,variants:s.variants.map(c=>({name:c.name??"",content:c.content,baseline:c.baseline,allocation:c.allocation??1e3/s.variants.length}))}:void 0;return {name:a.name,draft:a.status==="DRAFT",audiences:a.audiences,slots:a.slots,content:a.content,...p!==void 0?{experiment:p}:{}}})};for(let[a,s]of Object.entries(i))typeof s=="object"&&s!==null&&(Array.isArray(s)&&s.length===0||Object.keys(s).length===0)&&delete i[a];return i}};var Jr=class{constructor(e){this.config=e;}async handle(e){let{input:t,form:n}=this.config,r={components:[],slots:[],audiences:[],experiences:[]},i=new Set,a=new Set,s=await n.experience.handle({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,confirmation:"Do you want to include experiences?"});if(s.length>0){for(let c of s.flatMap(l=>l.audiences))i.add(c);for(let c of s.flatMap(l=>l.slots))a.add(c);r.experiences=s,s.some(c=>c.experiment!==void 0)&&(await t.confirm({message:"Include experiments?",default:false})||(r.experiences=r.experiences.map(c=>{let{experiment:l,...u}=c;return u})));}r.slots=await n.slot.handle({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,selected:[...a],selectionConfirmation:{message:a.size>0?"Do you want to include other slots?":"Do you want to include slots?",default:false}});let p=new Set(r.slots.map(c=>c.component?.slug??""));return r.components=await n.component.handle({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,includeDependencies:true,selected:[...p],selectionConfirmation:{message:p.size>0?"Do you want to include other components?":"Do you want to include components?",default:false}}),r.audiences=await n.audience.handle({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,selected:[...i],selectionConfirmation:{message:i.size>0?"Do you want to include other audiences?":"Do you want to include audiences?",default:false}}),r}};var Qr=class{constructor(e){this.config=e;}async handle(e){let{output:t,input:n,workspaceApi:r}=this.config,i=t.notify("Loading experiences"),a=await r.getExperiences({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});i.stop();let{confirmation:s}=e;if(a.length===0||s!==void 0&&!await n.confirm({message:s}))return [];let p=await n.selectMultiple({message:"Select experiences",options:a.map(l=>({value:l,label:l.name}))});i=t.notify("Loading details");let c=await Promise.all(p.flatMap(async({id:l})=>{let u=await r.getExperience({experienceId:l,organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return u===null?[]:[u]}));return i.stop(),c.flat()}};var Br=class{constructor(e){this.config=e;}async handle(e){let{output:t,input:n}=this.config,r=t.notify("Loading audiences"),i=await this.getAudiences(e,e.allowed);r.stop();let a=e.preselected??[];if(a.length>0)return i.filter(({slug:p})=>a.includes(p));let s=e.selected??[];return i.length===0||s.length>0&&i.every(({slug:p})=>s.includes(p))?i.filter(({slug:p})=>s.includes(p)):e.selectionConfirmation!==void 0&&!await n.confirm(e.selectionConfirmation)?i.filter(({slug:c})=>s.includes(c)):n.selectMultiple({message:"Select audiences",options:i.map(p=>{let c=s.includes(p.slug);return {value:p,label:p.name,disabled:c,selected:c}})})}async getAudiences(e,t){let{workspaceApi:n}=this.config,r=await n.getAudiences({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return t===void 0?r:r.filter(({slug:i})=>t.includes(i))}};var h=class o extends d{constructor(e,{tracing:t,...n}={}){super(e,n),this.tracing=t??[],Object.setPrototypeOf(this,o.prototype);}static fromCause(e,t={}){let{message:n,...r}=t;if(!(e instanceof Error))return new o(n??d.formatMessage(e),{...r,cause:e});let i=new o(n??e.message,{cause:e,...e instanceof d?e.help:{},...r,tracing:[...r.tracing??[],...e instanceof o?e.tracing:[]]});return i.stack=e.stack,i}};var zt=class{constructor(e){this.variables={};this.input=e.input,this.output=e.output,this.baseUrl=e.baseUrl;}getVariables(){return structuredClone(this.variables)}set(e,t){this.variables[e]=t;}};var Yr=class{constructor(e){this.config=e;}async getOptions(e){let{templateProvider:t}=this.config;return (await t.get(await this.resolveUrl(e))).value.options??{}}async execute(e){let{action:t,io:n}=this.config,{template:r,options:i}=e,a=await this.resolveUrl(r);return t.execute({template:a.toString(),options:i},new zt({input:n.input,output:n.output,baseUrl:a}))}async resolveUrl(e){let{fileSystem:t}=this.config,n=e;if(URL.canParse(e)){let r=new URL(e.replace(/(?<=^[a-z]+:\/*)([^/.:]+)/i,i=>i.replace(/@/g,"%40")));if(r.protocol!=="file:")return r;n=t.normalizeSeparators(r.pathname);}try{return new URL(`file://${await t.getRealPath(n)}`)}catch(r){throw new h(`Template file not found at \`${n}\`.`,{reason:"invalid_input",cause:r,suggestions:["Check the file path and try again."]})}}};function St(o,e){if(URL.canParse(o))return new URL(o);let t=new URL(e.href.replace(/^(.*:)(?!\/)/,"$1/"));return new URL(o,t)}var Xr=class{constructor(e){this.config=e;}async execute(e,t){let{fileSystem:n}=this.config,{input:r}=t,i=St(e.source,t.baseUrl);if(i.protocol==="file:"&&t.baseUrl.protocol!=="file:")throw new h("File URL is not allowed from remote sources for security reasons.",{reason:"precondition",details:[`Source URL: ${i}`]});let a=n.normalizeSeparators(e.destination),{output:s}=t,p=s?.notify("Downloading sources");try{await this.download(i,{...e,destination:a},r);}finally{p?.stop();}e.result?.destination!==void 0&&t.set(e.result.destination,a);}async download(e,t,n){let{provider:r,fileSystem:i,codemod:a}=this.config,{destination:s,overwrite:p=false}=t,c=t.filter!==void 0?new Minimatch(t.filter):void 0,{value:l}=await r.get(e),u=[],g=Object.fromEntries(Object.entries(t.mapping??{}).map(([y,C])=>[i.normalizeSeparators(y),i.normalizeSeparators(C)]));for await(let y of l){let C=this.resolvePath(i.normalizeSeparators(y.name),g);if(i.isAbsolutePath(C))throw new h("Path to downloaded file cannot be absolute.",{reason:"precondition",details:[`Path: ${C}`],suggestions:["Use relative paths"]});if(!(c!==void 0&&!c.match(C))){if(y.name=i.joinPaths(s,C),y.type==="link"||y.type==="symlink"){let v=i.normalizeSeparators(y.target);if(i.isAbsolutePath(v)||!i.isSubPath(s,v))continue;y.target=v;}u.push(y);}}if(u.length===0)throw new h("No matching files found for download.",{reason:"unexpected_result",details:[`Source: ${e}`,`Filter: ${t.filter??"none"}`]});await this.createDirectory(u,s,p,n);for(let y of u)await i.createDirectory(i.getDirectoryName(y.name),{recursive:true}),await i.create(y);for(let y of u)y.type==="file"&&await a.apply(await i.getRealPath(y.name));}resolvePath(e,t){if(e in t)return t[e];let{fileSystem:n}=this.config,r="",i=e,a=n.getSeparator();for(let[s,p]of Object.entries(t)){let c=s.endsWith(a)?s:s+a;e.startsWith(c)&&c.length>r.length&&(r=c,i=n.joinPaths(p,e.slice(c.length)));}return i}async createDirectory(e,t,n,r){let{fileSystem:i}=this.config;if(!await i.exists(t))return i.createDirectory(t,{recursive:true});if(e.length===1&&e[0].type==="file"){if(!n&&await i.exists(e[0].name)&&await r?.confirm({message:`File ${e[0].name} already exists. Do you want to overwrite it?`,default:false})!==true)throw new h("Destination file already exists.",{reason:"precondition",details:[`File: ${e[0].name}`],suggestions:["Delete the file"]});return}if(await i.isDirectory(t)){if(!n&&!await i.isEmptyDirectory(t)&&await r?.confirm({message:`Directory ${t} is not empty. Do you want to clear it?`,default:false})!==true)throw new h("Destination directory is not empty.",{reason:"precondition",details:[`Directory: ${t}`],suggestions:["Clear the directory"]})}else if(await r?.confirm({message:`Destination ${t} is not a directory. Do you want to delete it?`,default:false})!==true)throw new h("Destination is not a directory.",{reason:"precondition",details:[`Path: ${t}`],suggestions:["Delete the file"]});await i.delete(t,{recursive:true}),await i.createDirectory(t,{recursive:true});}};var ei=class{constructor({packageManager:e}){this.packageManager=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Installing dependencies");try{await this.packageManager.addDependencies(e.dependencies,{dev:e.development??!1,logger:new ge({status:"Installing dependencies",notifier:r})});}catch(i){throw h.fromCause(i)}finally{r?.stop();}}};var _t=class o{constructor(e){this.matcher=e;}static fromPattern(e){return new o(new Minimatch(e.replace(/^\.\//,"").replace(/\\/g,"/")))}test(e){return Promise.resolve(this.matcher.match(e))}};var ti=class{constructor({projectDirectory:e,fileSystem:t,scanFilter:n}){this.projectDirectory=e,this.fileSystem=t,this.scanFilter=n;}async execute(e,t){let{output:n}=t,r=n?.notify("Locating files");try{await this.findMatches(e,t);}finally{r?.stop();}}async findMatches(e,t){t.set(e.result,await this.findMatch(e.path,e));}async findMatch(e,t){let n=(a,s)=>t.depth!==void 0&&s>t.depth?false:this.scanFilter!==void 0?this.scanFilter(a,s):true,r=[],i=_t.fromPattern(e);for await(let a of this.fileSystem.list(this.projectDirectory.get(),n))if(await i.test(a.name)){if(t.matcher===void 0)r.push(a.name);else if(a.type==="file"){let s=await new Response(a.content).text();this.matches(s,t.matcher)&&r.push(a.name);}if(t.limit!==void 0&&r.length>=t.limit)break}return r}matches(e,t){if("pattern"in t)return new RegExp(t.pattern,t.caseSensitive===true?"i":void 0).test(e);switch(t.type){case "and":return t.matchers.every(n=>this.matches(e,n));case "or":return t.matchers.some(n=>this.matches(e,n))}}};var ni=class{constructor({fileSystem:e}){this.fileSystem=e;}async execute(e,t){let{output:n}=t,r=n.notify("Replacing file content");try{await this.replaceFiles(e);}finally{r.stop();}}async replaceFiles(e){let t=false;for(let{path:n,replacements:r}of e.files){let i=this.fileSystem.normalizeSeparators(n);if(await this.fileSystem.exists(i)){t=true;try{await this.fileSystem.writeTextFile(i,this.replaceContent(await this.fileSystem.readTextFile(i),r),{overwrite:!0});}catch(a){throw h.fromCause(a)}}}if(!t)throw new h("No files matched for content replacement.",{reason:"unexpected_result"})}replaceContent(e,t){let n=e;for(let{pattern:r,caseSensitive:i,value:a}of t){let s=i===true?"gi":"g";n=n.replace(new RegExp(r,s),`${a}`);}return n}};var ri=class{constructor({installer:e}){this.installer=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Installing slots");try{await this.installer(e.slots,e.example===!0);}catch(i){throw h.fromCause(i)}finally{r?.stop();}}};var ii=class{constructor({installer:e}){this.installer=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Installing components");try{await this.installer(e.components);}catch(i){throw h.fromCause(i)}finally{r?.stop();}}};var oi=class{constructor(e){this.runner=e;}async execute(e,t){try{await this.run(e.action,t);}catch(n){if(e.else===void 0)throw e.help===void 0?n:h.fromCause(n,{...e.help,reason:"precondition"});await this.run(e.else,t);}finally{e.finally!==void 0&&await this.run(e.finally,t);}}run(e,t){return this.runner.execute({actions:e},t)}};var V=class o extends d{constructor(e,t={}){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var at=class{constructor(e){this.provider=e;}get action(){return Promise.resolve(this.provider.get()).catch(e=>{throw e instanceof V?new h(e.message,e.help):e})}async execute(e,t){return (await this.action).execute(e,t)}};var ai=class{constructor(e){this.manager=e;}isInitialized(){return this.manager.isInitialized()}load(){return this.configuration===void 0&&(this.configuration=this.manager.load()),this.configuration}update(e){return this.configuration=this.manager.update(e),this.configuration}};var Ps;(r=>{function o(i){let a=new Set(Object.values(i.slots??{}).map(u=>u.component)??[]),s=new Set(i.experiences?.flatMap(u=>u.slots)??[]),p=new Set(i.experiences?.flatMap(u=>u.audiences)??[]),c=(i.experiences??[]).map(u=>({name:u.name,maximumAudiencesPerExperience:u.audiences.length,crossDevice:u.experiment?.crossDevice===true,...e(u)})),l=new Set;for(let u of Object.values(i.slots??{}))for(let g of Object.keys(u.content))l.add(g);for(let u of c){for(let g of u.locales)l.add(g);for(let g of u.audiences)p.add(g);for(let g of u.slots)s.add(g);}return {components:a,slots:s,audiences:p,locales:l,experiences:c}}r.analyze=o;function e(i){let a=t(i.content);for(let s of i.experiment?.variants??[]){let p=t(s.content);p.audiences.forEach(c=>a.audiences.add(c)),p.slots.forEach(c=>a.slots.add(c));}return {...a}}function t(i){let a=new Set,s=new Set,p=0;for(let[u,g]of Object.entries(i.default??{})){a.add(u);for(let[y,C]of Object.entries(g))s.add(y),p=Math.max(p,n(C));}let c=new Set,l=0;for(let u of i.segmented??[]){for(let g of u.audiences)c.add(g);l=Math.max(l,u.audiences.length);for(let[g,y]of Object.entries(u.content)){a.add(g);for(let[C,v]of Object.entries(y))s.add(C),p=Math.max(p,n(v));}}return {slots:a,audiences:c,locales:s,audiencesPerExperience:l,dynamicContentPerContent:p}}function n(i){switch(i.type){case "boolean":case "text":case "number":return i.value.type==="dynamic"?1:0;case "structure":return Object.values(i.attributes).map(n).reduce((a,s)=>a+s,0);case "list":return i.items.map(n).reduce((a,s)=>a+s,0)}}})(Ps||={});var si=class{constructor(e){this.refactoring=e;}refactor(e){return {components:Object.fromEntries(Object.entries(e.components??{}).map(([t,n])=>[this.refactoring.componentMapping[t]??t,{...n,schema:this.refactorSchema(n.schema)}])),slots:Object.fromEntries(Object.entries(e.slots??{}).map(([t,n])=>[this.refactoring.slotMapping[t]??t,this.refactorSlotContent(n)])),audiences:Object.fromEntries(Object.entries(e.audiences??{}).map(([t,n])=>[this.refactoring.audienceMapping[t]??t,n])),experiences:e.experiences?.map(t=>this.refactorExperience(t))??[]}}refactorSchema(e){switch(e.type){case "boolean":case "text":case "number":return e;case "structure":return {...e,attributes:Object.fromEntries(Object.entries(e.attributes).map(([t,n])=>[t,{...n,type:this.refactorSchema(n.type)}]))};case "list":return {...e,items:this.refactorSchema(e.items)};case "union":return {...e,types:Object.fromEntries(Object.entries(e.types).map(([t,n])=>[t,this.refactorSchema(n)]))};case "reference":return {...e,id:this.refactoring.componentMapping[e.id]??e.id}}}refactorSlotContent(e){return {...e,component:this.refactoring.componentMapping[e.component]??e.component,content:this.refactorLocalizedContentMap(e.content)}}refactorExperience(e){let t=e.audiences.slice(0,this.refactoring.maximumAudiencePerExperience),{experiment:n}=e;return {...e,audiences:e.audiences.map(r=>this.refactoring.audienceMapping[r]??r),slots:e.slots.map(r=>this.refactoring.slotMapping[r]??r),experiment:n!==void 0?{...n,variants:n.variants.map(r=>({...r,content:this.refactorPersonalizedContent(r.content,t)})),crossDevice:(n.crossDevice??false)&&this.refactoring.isCrossDeviceFeatureEnabled}:void 0,content:this.refactorPersonalizedContent(e.content,t)}}refactorPersonalizedContent(e,t){return {default:this.refactorSlotContentMap(e.default??{}),segmented:(e.segmented??[]).flatMap(n=>{let r=n.audiences.filter(i=>t.includes(i));return r.length===0?[]:{audiences:r,content:this.refactorSlotContentMap(n.content)}})}}refactorSlotContentMap(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[this.refactoring.slotMapping[t]??t,this.refactorLocalizedContentMap(n)]))}refactorLocalizedContentMap(e){return Object.fromEntries(Object.entries(e).flatMap(([t,n])=>{let r=this.refactoring.localeMapping[t];return r===null||r!==void 0&&e[r]!==void 0?[]:[[r??t,this.refactorContent(n,{dynamicAttributesPerContent:this.refactoring.dynamicAttributesPerContent})]]}))}refactorContent(e,t){switch(e.type){case "boolean":case "text":case "number":return e.value.type==="dynamic"&&t.dynamicAttributesPerContent>0&&t.dynamicAttributesPerContent--,e.value.type==="static"||t.dynamicAttributesPerContent>0?e:{...e,value:{type:"static",value:e.value.default}};case "structure":return {...e,attributes:Object.fromEntries(Object.entries(e.attributes).map(([n,r])=>[n,this.refactorContent(r,t)]))};case "list":return {...e,items:e.items.map(n=>this.refactorContent(n,t))}}}};var pi=class o{constructor(e){this.config=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Analyzing resources"),i=Ps.analyze(e.resources),{configurationManager:a,api:{workspace:s}}=this.config,p=await a.load(),c=await this.getProjectInfo(p);await this.checkMissingResources({...i,locales:new Set},e.resources,c);let l=await this.createPlan(e.resources,i,c);r?.update("Creating resources");let u=await s.createResources({organizationSlug:p.organization,workspaceSlug:p.workspace,...l.resources});if(r?.stop(),n!==void 0){let g=o.getWarnings(i,c.workspace);if(g.length>0)for(let y of g)n.warn(`${y}`);}e.result!==void 0&&o.setVariables(e.result,l,u,t);}async createPlan(e,t,n){let{mappingForm:r,matcher:i}=this.config,a=await i.match({resources:e,workspaceSlug:n.configuration.workspace,organizationSlug:n.configuration.organization}),s=Object.entries(a.audiences).filter(v=>!("id"in v[1])),p=Object.entries(a.components).filter(v=>!("id"in v[1])),c=Object.entries(a.slots).filter(v=>!("id"in v[1])),l=a.experiences.filter(v=>!("id"in v)),u=l.flatMap(v=>v.experiment===void 0?[]:[v.experiment]);await this.checkRequiredQuota(n,{components:p.length,slots:c.length,audiences:s.length,experiences:l.length,experiments:u.length});let g=await r.handle({organizationSlug:n.configuration.organization,workspaceSlug:n.configuration.workspace,resources:{audiences:s.map(([v])=>v),components:p.map(([v])=>v),slots:c.map(([v])=>v)}}),y={},{workspace:C}=n;for(let v of t.locales)C.locales.includes(v)||(y[v]=C.defaultLocale);return {matches:a,mapping:g,resources:new si({componentMapping:g.components,audienceMapping:g.audiences,slotMapping:g.slots,dynamicAttributesPerContent:C.quotas.dynamicAttributesPerContent,maximumAudiencePerExperience:C.quotas.audiencesPerExperience,isCrossDeviceFeatureEnabled:C.features.crossDevice,localeMapping:y}).refactor({components:Object.fromEntries(p),slots:Object.fromEntries(c),audiences:Object.fromEntries(s),experiences:l})}}async getProjectInfo(e){let{api:t}=this.config,[n,r]=await Promise.all([t.organization.getWorkspace({organizationSlug:e.organization,workspaceSlug:e.workspace}),t.workspace.getFeatures({organizationSlug:e.organization,workspaceSlug:e.workspace})]);if(n==null||r==null)throw new d("Workspace not found",{title:"Invalid configuration",reason:"invalid_configuration",details:["The workspace defined in the configuration does not exist"],suggestions:["Check the configuration file"]});return {configuration:e,workspace:{...n,...r}}}async checkRequiredQuota(e,t){let{api:{user:n}}=this.config;for(let[r,i]of Object.entries(t)){let a=o.getRemainingQuota(e.workspace,r);if(a<i){let s=await n.getUser().catch(()=>({email:void 0})),p=new URL("https://croct.com/contact/support");throw p.searchParams.set("subject","limit-increase"),p.searchParams.set("organization",e.configuration.organization),p.searchParams.set("message",`I need more quota for ${r}`),s.email!==void 0&&p.searchParams.set("email",s.email),new d(`Not enough ${r} quota available in your workspace.`,{title:"Insufficient quota",reason:"precondition",links:[{label:"Request more quota",url:p.toString()}],details:[`Available: ${a}`,`Required: ${i}`],suggestions:[`Free up quota by removing unused ${r}`,"Request additional quota from support"]})}}}async checkMissingResources(e,t,n){let r=await this.findMissingResources(e,t,n);for(let[i,a]of Object.entries(r))if(a.size>0)throw new d(`Some ${i} referenced in the template are missing`,{title:"Invalid template",reason:"invalid_input",details:[`Missing ${i}: ${Array.from(a).join(", ")}`],suggestions:["Report this issue to the template author"]})}async findMissingResources(e,t,n){let r=new Set(e.components),i=new Set(e.slots),a=new Set(e.audiences),s=new Set(e.locales);for(let c of Object.keys(t.components??{}))r.delete(c);for(let c of Object.keys(t.slots??{}))i.delete(c);for(let c of Object.keys(t.audiences??{}))a.delete(c);let{api:p}=this.config;return await Promise.all([...[...r].map(async c=>{await p.workspace.getComponent({organizationSlug:n.configuration.organization,workspaceSlug:n.configuration.workspace,componentSlug:c})!==null&&r.delete(c);}),...[...i].map(async c=>{await p.workspace.getSlot({organizationSlug:n.configuration.organization,workspaceSlug:n.configuration.workspace,slotSlug:c})!==null&&i.delete(c);}),...[...a].map(async c=>{await p.workspace.getAudience({organizationSlug:n.configuration.organization,workspaceSlug:n.configuration.workspace,audienceSlug:c})!==null&&a.delete(c);}),(async()=>{if(s.size===0)return;let c=await p.organization.getWorkspace({organizationSlug:n.configuration.organization,workspaceSlug:n.configuration.workspace});for(let l of c?.locales??[])s.delete(l);})()]),{components:r,slots:i,audiences:a,locales:s}}static getRemainingQuota(e,t){let n=t.charAt(0).toUpperCase()+t.slice(1);return e.quotas[`remaining${n}`]}static getWarnings(e,t){let n=[];return Math.max(...e.experiences.map(s=>s.dynamicContentPerContent))>t.quotas.dynamicAttributesPerContent&&n.push("Some dynamic values have been removed from the content to fit the workspace quota"),Math.max(...e.experiences.map(s=>s.audiencesPerExperience))>t.quotas.audiencesPerExperience&&n.push("Some audiences have been removed from the experiences to fit the workspace quota"),Array.from(e.locales).filter(s=>!t.locales.includes(s)).length>0&&n.push("Content in unsupported locales have been mapped to default or dropped"),!t.features.crossDevice&&e.experiences.some(s=>s.crossDevice)&&n.push("Cross-device experiments have been disabled "),n}static setVariables(e,t,n,r){if(e.audiences!==void 0)for(let[s]of Object.entries(t.matches.audiences??{}))e.audiences[s]!==void 0&&r.set(e.audiences[s],t.mapping.audiences[s]??s);if(e.components!==void 0)for(let[s]of Object.entries(t.matches.components??{})){let p=e.components[s];if(p!==void 0){let c=t.mapping.components[s]??s,l=t.matches.components[s]??{};p.id!==void 0&&r.set(p.id,c),p.version!==void 0&&r.set(p.version,"version"in l?l.version.major:1);}}if(e.slots!==void 0)for(let[s]of Object.entries(t.matches.slots??{})){let p=e.slots[s];if(p!==void 0){let c=t.mapping.slots[s]??s,l=t.matches.slots[s]??{};p.id!==void 0&&r.set(p.id,c),p.version!==void 0&&r.set(p.version,"version"in l?l.version.major:1);}}let{experiences:i}=t.matches,a=0;for(let[s,p]of i.entries()){if(e.experiences?.[s]!==void 0&&r.set(e.experiences[s],"id"in p&&p.id!==void 0?p.id:n.experiences[a].experienceId),e.experiments?.[s]!==void 0){let{experiment:c}=p,l=c!==void 0&&"id"in c&&c.id!==void 0?c.id:n.experiences[a].experimentId;l!==void 0&&r.set(e.experiments[s],l);}(!("id"in p)||p.id===void 0)&&a++;}}};var Ft=class o{constructor(e){this.config=e;}static prompt(e){return new o(e).handle()}handle(){let{input:e,unavailableSlugs:t=[]}=this.config;return e.prompt({message:this.config.label,default:this.config.default,initial:this.config.initial,validate:n=>/^[a-z]+(-?[a-z0-9]+)*$/i.test(n)?t.includes(n)?"The entered slug is already in use.":true:"The slug must start with a letter and contain only letters, numbers, and hyphens."})}};var ci=class{constructor(e){this.config=e;}async handle(e){let{input:t,workspaceApi:n}=this.config,{resources:r,...i}=e,a=r.slots??[],s=r.components??[],p=r.audiences??[],[c,l,u]=await Promise.all([a.length>0?n.getSlots(i):new Array,s.length>0?n.getComponents(i):new Array,p.length>0?n.getAudiences(i):new Array]),g=s.filter(S=>l.some(P=>P.slug===S)),y={};if(g.length>0){let S=l.map(P=>P.slug);for(let P of g){let B=await Ft.prompt({input:t,initial:P,unavailableSlugs:S,label:`Component \`${P}\` already exists, enter a new component ID:`});S.push(B),y[P]=B;}}let C=a.filter(S=>c.some(P=>P.slug===S)),v={};if(C.length>0){let S=c.map(P=>P.slug);for(let P of C){let B=await Ft.prompt({input:t,initial:P,unavailableSlugs:S,label:`Slot \`${P}\` already exists, enter a new slot ID:`});S.push(B),v[P]=B;}}let D=p.filter(S=>u.some(P=>P.slug===S)),U={};if(D.length>0){let S=u.map(P=>P.slug);for(let P of D){let B=await Ft.prompt({input:t,initial:P,unavailableSlugs:S,label:`Audience \`${P}\` already exists, enter a new audience ID:`});S.push(B),U[P]=B;}}return {components:y,slots:v,audiences:U}}};var li=class o{constructor(e){this.config=e;}async match(e){let{resources:t,...n}=e,[r,i,a,s]=await Promise.all([this.mapComponents(t.components??{},n),this.mapSlots(t.slots??{},n),this.mapAudiences(t.audiences??{},n),this.mapExperiences(t.experiences??[],n)]);return {components:r,slots:i,audiences:a,experiences:s}}async mapAudiences(e,t){let{workspaceApi:n}=this.config,r=await Promise.all(Object.keys(e).map(async a=>[a,await n.getAudience({...t,audienceSlug:a})])),i={};for(let[a,s]of r)i[a]=s===null||!o.isSimilarAudience(e[a],s)?e[a]:s;return i}async mapComponents(e,t){let{workspaceApi:n}=this.config,r=await Promise.all(Object.keys(e).map(async a=>[a,await n.getComponent({...t,componentSlug:a})])),i={};for(let[a,s]of r)i[a]=s===null||!o.isSimilarComponent(e[a],s)?e[a]:s;return i}async mapSlots(e,t){let{workspaceApi:n}=this.config,r=await Promise.all(Object.keys(e).map(async a=>[a,await n.getSlot({...t,slotSlug:a})])),i={};for(let[a,s]of r)i[a]=s===null||!o.isSimilarSlot(e[a],s)?e[a]:s;return i}async mapExperiences(e,t){let{workspaceApi:n}=this.config,i=(await n.getExperiences({...t,status:["ACTIVE","PAUSED","DRAFT"]})).map(a=>{let s=null;function p(){return s===null&&(s=n.getExperience({...t,experienceId:a.id})),s}return {...a,details:{get content(){return p().then(c=>c?.content??null)},get experiment(){return p().then(c=>c?.experiment??null)}}}});return Promise.all(e.map(async a=>{for(let s of i)if(await this.matchesExperience(a,s)){let{details:p,...c}=s;return c}return a}))}async matchesExperience(e,t){if((e.draft===true?"DRAFT":"ACTIVE")!==t.status||!deepEqual(e.audiences,t.audiences)||!deepEqual(e.slots,t.slots)||e.experiment!==void 0&&t.experiment===void 0)return false;let[r,i=null]=await Promise.all([t.details.content,t.details.experiment]);return e.experiment!==void 0&&(i===null||e.experiment.goalId!==i.goalId||e.experiment.traffic!==i.traffic||e.experiment.crossDevice!==i.crossDevice||!o.isSimilarExperimentContent(e.experiment.variants,i.variants))?false:o.isSimilarPersonalizedContent(e.content,r??{default:{},segmented:[]})}static isSimilarAudience(e,t){return e.criteria===t.criteria}static isSimilarComponent(e,t){return deepEqual(e.schema,t.definition)}static isSimilarSlot(e,t){return e.component===t.component?.slug&&Object.values(e.content).some(n=>Object.values(t.content).some(r=>deepEqual(n,r)))}static isSimilarExperimentContent(e,t){return e.length!==t.length?false:e.some((n,r)=>deepEqual(n,t[r]))}static isSimilarPersonalizedContent(e,t){if(o.isSimilarSlotContent(e.default??{},t.default??{}))return true;for(let n of e.segmented??[])for(let r of t.segmented??[])if(deepEqual(n.audiences,r.audiences)&&o.isSimilarSlotContent(n.content,r.content))return true;return false}static isSimilarSlotContent(e,t){for(let[n,r]of Object.entries(e)){let i=t[n];if(i!==void 0){for(let a of Object.values(r))if(Object.values(i).some(s=>deepEqual(a,s)))return true}}return false}};var z=class o extends V{constructor(e,{url:t,...n}){super(e,n),Object.setPrototypeOf(this,o.prototype),this.url=t;}},He=class o extends z{constructor(e,t){super(e,{...t,reason:t.reason??"not_found"}),Object.setPrototypeOf(this,o.prototype);}};var ui=class o{constructor(e={}){this.configuration=e;}async get(e){if(!["http:","https:"].includes(e.protocol))throw new z("Unsupported protocol.",{reason:"not_supported",url:e});return {url:e,value:await this.fetch(e)}}async fetch(e,t=0){let n=await fetch(e);if(n.status===404)throw new He("Resource not found.",{url:e});let{maxAttempts:r=0,delay:i=1e3}=this.configuration.retry??{};if(o.isSuccessful(n))return n;if(o.isRetryableCode(n.status)&&t<r)return await new Promise(a=>{setTimeout(a,i);}),this.fetch(e,t+1);throw new z(n.statusText,{url:e})}static isSuccessful(e){return e.ok&&e.body!==null}static isRetryableCode(e){return e>=500||[429,408].includes(e)}};var mi=class{constructor({packageManager:e}){this.packageManager=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Checking dependencies"),i;try{i=await Promise.all(e.dependencies.map(s=>this.checkRequirement(s)));}finally{r?.stop();}let a=[];for(let s of i){if(e?.result?.[s.dependency]!==void 0){t.set(e.result[s.dependency],s.satisfied);continue}s.issue!==void 0&&a.push(s);}if(a.length>0){let{message:s,...p}=e.help??{};throw new h(s??"Missing required dependencies.",{...p,details:a.map(({dependency:c,issue:l})=>`\`${c}\`: ${l}`)})}}async checkRequirement(e){let{name:t,version:n,optional:r=false}=e;if(n===void 0){let a=await this.packageManager.hasDirectDependency(t);if(a||r)return {dependency:t,satisfied:a}}else {let a=await this.packageManager.hasDirectDependency(t,n);if(a||r)return {dependency:t,satisfied:a}}let i=await this.packageManager.getDependency(t);return {dependency:t,satisfied:false,issue:i===null?"not installed":`${n!==void 0?`version \`${n}\` is required`:""}found \`${i.version??"unknown"}\``}}};var It=class{constructor({dataProvider:e,registryProvider:t,baseUrl:n}){this.dataProvider=e,this.registryProvider=t,this.baseUrl=n;}async get(e){return this.dataProvider.get(await this.resolveUrl(e))}async resolveUrl(e){for(let{pattern:t,destination:n}of await this.loadMappings(e)){let r=e.href.match(typeof t=="string"?new RegExp(t):t);if(r!==null)return n instanceof URL?n:new URL(n.replace(/\$([0-9]+)/g,(i,a)=>r[Number.parseInt(a,10)]),this.baseUrl)}return e}async loadMappings(e){let t=await this.registryProvider.get(e);return Array.isArray(t)?t:t.value}};var Ke=class o{static{this.DEFAULT_EXPECTED_ERRORS=["not_supported","not_found","other"];}constructor({providers:e,expectedErrors:t}){this.providers=e,this.expectedErrors=t??o.DEFAULT_EXPECTED_ERRORS;}async get(e){for(let t of this.providers)try{return await t.get(e)}catch(n){if(!this.isExpectedError(n))throw n}throw new He("Resource not found.",{url:e})}isExpectedError(e){return e instanceof z&&this.expectedErrors.includes(e.reason)}};var di=class o{constructor(e,t){this.fileSystem=e,this.filter=t;}get(e){if(!o.supportsUrl(e))throw new z(`Unsupported protocol "${e.protocol}".`,{reason:"not_supported",url:e});return Promise.resolve({url:e,value:this.fileSystem.list(this.fileSystem.normalizeSeparators(e.pathname),this.filter)})}static supportsUrl(e){return e.protocol==="file:"}};var gi=class o{static{this.MAX_DOWNLOAD_FILES=50;}static{this.PROTOCOL="github:";}static{this.API_HOST="api.github.com";}static{this.RAW_HOST="raw.github.com";}static{this.MAIN_HOST="github.com";}constructor({cache:e,provider:t}){this.provider=t,this.cache=e??new NoopCache;}async get(e){let t=this.parseUrl(e);if(t===null)throw new z("Unsupported GitHub URL.",{reason:"not_supported",url:e});let n=await this.resolveFiles(t),r=await Promise.all(n.map(async i=>({url:i,response:(await this.provider.get(i)).value})));return {url:t.canonicalUrl,value:this.yieldFiles(r,t.path??"")}}async*yieldFiles(e,t){let n=new Set;for(let{url:r,response:i}of e){let a=r.pathname.split("/"),s=a.slice(4),p=s.join("/")===t&&e.length===1?a.slice(-1):s.slice(t.split("/").length);if(p.length>1){let c=p.slice(0,-1);for(let l=0;l<c.length;l++){let u=c.slice(0,l+1).join("/");n.has(u)||(n.add(u),yield {type:"directory",name:u});}}yield {type:"file",name:p.join("/"),content:Readable.fromWeb(i.body)};}}async resolveFiles(e){let{username:t,repository:n,path:r}=e,i=p=>{let c=new URL(`https://${o.RAW_HOST}`);return c.pathname=`/${t}/${n}/${e.ref??"HEAD"}/${p}`,c},a=await this.loadGitTree(e),s=[];if(r===null)s.push(...a.map(p=>i(p.path)));else {let p=a.find(c=>c.path===r);if(p===void 0)throw new z("File not found.",{reason:"not_found",url:e.canonicalUrl});p.type==="tree"?s.push(...a.filter(c=>c.path.startsWith(r)&&c.type==="blob").map(c=>i(c.path))):s.push(i(r));}if(s.length>o.MAX_DOWNLOAD_FILES)throw new z(`The number of files to download exceeds the limit of ${o.MAX_DOWNLOAD_FILES}.`,{reason:"precondition",url:e.canonicalUrl});return s}parseUrl(e){if(!o.isUrlSupported(e))return null;let t,n,r=null,i,a=((e.protocol===o.PROTOCOL?e.hostname:"")+e.pathname).replace(/^\/+/,"").split("/"),s=null;return e.hostname===o.MAIN_HOST?(s=e,[t=null,n=null,,r=null,...i]=a):[t=null,n=null,...i]=a,t===null||n===null?null:(s===null&&(s=new URL(`https://${o.MAIN_HOST}`),s.pathname=`/${t}/${n}/blob/master/${i.join("/")}`),{canonicalUrl:s,username:t,repository:n,ref:r,path:i!==void 0&&i.length>0?i.join("/"):null})}loadGitTree({username:e,repository:t,ref:n}){let r=new URL(`https://${o.API_HOST}`);return r.pathname=`repos/${e}/${t}/git/trees/${n??"HEAD"}`,r.searchParams.set("recursive","true"),this.cache.get(r.toString(),()=>this.provider.get(r).then(i=>i.value.json()).then(({tree:i})=>i))}static isUrlSupported(e){return e.protocol==="https:"?e.hostname===o.MAIN_HOST:e.protocol===o.PROTOCOL}};var In=class o{constructor(e){this.provider=e;}async get(e){if(!o.supportsUrl(e))throw new z("Unsupported URL.",{reason:"not_supported",url:e});let{value:t,...n}=await this.provider.get(e);return {...n,value:this.yield(t,e)}}static supportsUrl(e){return e.pathname!=="/"}async*yield(e,t){yield {type:"file",name:t.pathname.split("/").pop(),content:Readable.fromWeb(e.body)};}};var ee=class{constructor(e){this.schema=e;}async validate(e){let t=await this.schema.safeParseAsync(e);if(t.success)return {valid:true,data:t.data};let{error:n}=t;return {valid:false,violations:n.issues.map(r=>({path:r.path.reduce((i,a)=>typeof a=="string"?i===""?a:`${i}.${a}`:`${i}[${a}]`,""),message:r.message}))}}};var Fu=z$1.object({name:z$1.string(),version:z$1.string().optional(),dependencies:z$1.record(z$1.string()).optional(),devDependencies:z$1.record(z$1.string()).optional(),bin:z$1.record(z$1.string()).optional(),scripts:z$1.record(z$1.string()).optional(),packageManager:z$1.string().optional()}),vn=class extends ee{constructor(){super(Fu);}};var fi=z$1.string().regex(/^[a-z]+(-?[a-z0-9]+)*$/i,"An identifier must start with a letter and contain only letters, numbers, and hyphens."),$c=z$1.string().regex(/^[a-z]{2,3}([-_][a-z]{2,3})?$/i,"Locale must be in the form of en, en_US, or en-US."),Lc=z$1.string().refine(M.isValid,"Version must be exact (1), range (1 - 2), or set (1, 2).").refine(o=>{try{return M.parse(o).getCardinality()<=5}catch{return false}},"Version range must not exceed 5 major versions."),ju=z$1.strictObject({$schema:z$1.string().optional(),organization:fi,workspace:fi,applications:z$1.strictObject({development:fi,production:fi.optional()}),locales:z$1.array($c).min(1),defaultLocale:$c,slots:z$1.record(Lc).default({}),components:z$1.record(Lc).default({}),paths:z$1.strictObject({source:z$1.string().optional(),utilities:z$1.string().optional(),components:z$1.string().optional(),examples:z$1.string().optional(),content:z$1.string().optional()}).optional()}).refine(o=>o.locales.includes(o.defaultLocale),{message:"The default locale is not included in the list of locales.",path:["defaultLocale"]}),yi=class extends ee{constructor(){super(ju);}};var jt=class{constructor({provider:e,validator:t}){this.provider=e,this.validator=t;}async get(e){let{value:t,...n}=await this.provider.get(e),r=await this.validator.validate(t);if(!r.valid){let i=r.violations.map(a=>` \u2022 **${a.path}**: ${a.message}`).join(`
|
|
1822
1766
|
|
|
1823
1767
|
`);throw new z(`The response data is invalid:
|
|
1824
1768
|
|
|
1825
|
-
${i}`,{reason:"invalid_input",url:e})}return {...n,value:r.data}}};var vt=class{constructor(e){this.provider=e;}async get(e){let{value:t,...n}=await this.provider.get(e),r=await t.next();if(r.done===true||r.value.type!=="file")throw new He("File not found.",{url:e});return {...n,value:await new Response(r.value.content).text()}}};var vn=class{constructor(e){this.provider=e;}async get(e){let{value:t,...n}=await this.provider.get(e);try{return {...n,value:JsonParser$1.parse(t).toJSON()}}catch(r){throw new z("Malformed JSON.",{reason:"precondition",url:e,cause:r})}}};var Fu=z$1.strictObject({pattern:z$1.string().refine(o=>{try{return new RegExp(o),!0}catch{return {message:"Invalid regular expression."}}}),destination:z$1.string()}),ju=z$1.array(Fu),hi=class extends ee{constructor(){super(ju);}};var xn=class{constructor({fileSystem:e,directory:t,useKeyAsFileName:n}){this.fileSystem=e,this.directory=t,this.useKeyAsFileName=n??false;}async delete(e){await this.fileSystem.delete(this.getCacheFile(e));}async get(e,t){try{return await this.fileSystem.readTextFile(this.getCacheFile(e))}catch{return t(e)}}async set(e,t){return await this.fileSystem.exists(this.directory)||await this.fileSystem.createDirectory(this.directory,{recursive:true}),this.fileSystem.writeTextFile(this.getCacheFile(e),t,{overwrite:true})}getCacheFile(e){return this.fileSystem.joinPaths(this.directory,this.useKeyAsFileName?e:createHash("md5").update(e).digest("hex"))}};var wn=class{constructor({provider:e,resourceCache:t,errorCache:n}){this.provider=e,this.resourceCache=t,this.errorCache=n;}async get(e){let t=await this.errorCache?.get(e.toString(),()=>Promise.resolve());return t!==void 0?Promise.reject(t):this.resourceCache.get(e.toString(),async()=>{try{return await this.provider.get(e)}catch(n){throw this.errorCache?.set(e.toString(),n),n}})}};var Ut;(e=>{function o(...t){return t.reduce((n,r)=>Object.defineProperties(n,Object.getOwnPropertyDescriptors(r)),{})}e.merge=o;})(Ut||={});var L=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var Cn=class o extends L{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}},xs=Symbol("regex"),Si=class o{constructor(e={}){this.cache=new Map;this.configuration=e;}static{this.ALLOWED_ARRAY_PROPERTIES=["length"];}static{this.ALLOWED_ARRAY_METHODS=["slice","join","includes","indexOf"];}static{this.ALLOWED_STRING_PROPERTIES=["length"];}static{this.ALLOWED_STRING_METHODS=["slice","indexOf","match","matchAll","replace","replaceAll","includes","startsWith","endsWith","toLowerCase","toUpperCase","repeat","split"];}static{this.ALLOWED_REGEX_PROPERTIES=["source"];}static{this.ALLOWED_REGEX_METHODS=["test"];}static{this.LITERALS={true:true,false:false,null:null};}static{this.UNARY_OPERATORS={"!":{evaluate:async e=>!await Pn(e)},"-":{evaluate:async e=>-await J(e)},"+":{evaluate:async e=>+await J(e)}};}static{this.BINARY_OPERATORS={"||":{precedence:1,evaluate:async(e,t)=>await Pn(e)||Pn(t)},"??":{precedence:1,evaluate:async(e,t)=>{let n=null;try{n=await e();}catch(r){if(!(r instanceof Cn))throw r}return n??t()}},"&&":{precedence:2,evaluate:async(e,t)=>await Pn(e)&&Pn(t)},"==":{precedence:6,evaluate:async(e,t)=>await e()==await t()},"===":{precedence:6,evaluate:async(e,t)=>await e()===await t()},"!=":{precedence:6,evaluate:async(e,t)=>await e()!=await t()},"!==":{precedence:6,evaluate:async(e,t)=>await e()!==await t()},"<":{precedence:7,evaluate:async(e,t)=>await J(e)<await J(t)},">":{precedence:7,evaluate:async(e,t)=>await J(e)>await J(t)},"<=":{precedence:7,evaluate:async(e,t)=>await J(e)<=await J(t)},">=":{precedence:7,evaluate:async(e,t)=>await J(e)>=await J(t)},"+":{precedence:9,evaluate:async(e,t)=>{let[n,r]=await Promise.all([e(),t()]);if(typeof n=="string"||typeof r=="string")return `${n}${r}`;if(typeof n!="number"||typeof r!="number")throw new L(`Operands must be numbers or strings, got ${d.describeType(n)} and ${d.describeType(r)}.`);return n+r}},"-":{precedence:9,evaluate:async(e,t)=>await J(e)-await J(t)},"*":{precedence:10,evaluate:async(e,t)=>await J(e)*await J(t)},"/":{precedence:10,evaluate:async(e,t)=>await J(e)/await J(t)},"%":{precedence:10,evaluate:async(e,t)=>await J(e)%await J(t)},"**":{precedence:11,evaluate:async(e,t)=>(await J(e))**await J(t)}};}evaluate(e,t){return this.evaluateExpression(this.parse(e),t)}parse(e){let t=this.cache.get(e);if(t!==void 0)return t;Ge.plugins.register(Wu),Ge.plugins.register(Vu),Ge.plugins.register(qu),Ge.removeAllUnaryOps();for(let r of Object.keys(o.UNARY_OPERATORS))Ge.addUnaryOp(r);Ge.removeAllBinaryOps();for(let[r,{precedence:i}]of Object.entries(o.BINARY_OPERATORS))Ge.addBinaryOp(r,i);Ge.removeAllLiterals();for(let[r,i]of Object.entries(o.LITERALS))Ge.addLiteral(r,i);let n;try{n=Ge(e);}catch(r){throw new L("Malformed expression.",{cause:r,details:[`Expression: ${e}`]})}return this.cache.set(e,n),n}async evaluateExpression(e,t){switch(true){case Y(e,"Literal"):if(e.raw.startsWith("/")){let n=e.raw.lastIndexOf("/"),r=e.raw.slice(n+1),i=e.raw.slice(1,n),a=new String(e.raw);return Object.assign(a,{[xs]:new RegExp(i,r)}),a}return e.value;case Y(e,"ThisExpression"):case Y(e,"Identifier"):{let n=e.type==="ThisExpression"?"this":e.name,r=t?.variables?.[n];if(r===void 0)throw new L(`Variable \`${n}\` is unknown.`);return r}case Y(e,"ArrayExpression"):return (await Promise.all(e.elements.map(async r=>{if(r===null)return [];if(Y(r,"SpreadElement")){let i=await this.evaluateExpression(r.argument,t);if(!Array.isArray(i))throw new L(`Spread expression must evaluate to an array, got ${d.describeType(i)}.`);return i}return [await this.evaluateExpression(r,t)]}))).flat();case Y(e,"ObjectExpression"):{let n=await Promise.all(e.properties.map(async r=>{if(Y(r,"SpreadElement")){let a=await this.evaluateExpression(r.argument,t);if(typeof a!="object"||a===null)throw new L(`Spread expression must evaluate to an object, got ${d.describeType(a)}.`);return Object.entries(a)}return r.value===void 0&&Y(r.key,"Identifier")?[[r.key.name,await this.evaluateExpression(r.key,t)]]:[[Y(r.key,"Identifier")?r.key.name:await this.evaluateExpression(r.key,t).then(a=>{if(typeof a!="string"&&typeof a!="number")throw new L(`Property name must be a string or a number, got ${d.describeType(a)}.`);return a}),await this.evaluateExpression(r.value,t)]]}));return Object.fromEntries(n.flat())}case Y(e,"UnaryExpression"):return o.UNARY_OPERATORS[e.operator].evaluate(()=>this.evaluateExpression(e.argument,t));case Y(e,"BinaryExpression"):return o.BINARY_OPERATORS[e.operator].evaluate(()=>this.evaluateExpression(e.left,t),()=>this.evaluateExpression(e.right,t));case Y(e,"MemberExpression"):{let n=await this.evaluateExpression(e.object,t).then(o.unbox);if(typeof n!="object"||n===null)throw new L("Cannot access property of a non-object.");let r=Y(e.property,"Identifier")?e.property.name:await this.evaluateExpression(e.property,t);if(typeof r=="number"){if(!Array.isArray(n))throw new L("Cannot access array index of a non-array.");if(r<0||r>=n.length)throw new Cn("Array index is out of bounds.");return n[r]}if(typeof r!="string")throw new L(`Property name must be a string, got ${d.describeType(r)}.`);if(!o.isPropertyAllowed(n,r))throw new Cn(`Property \`${r}\` does not exist or is not accessible.`);return n[r]}case Y(e,"CallExpression"):{let[n,r]=await Promise.all([this.getCallee(e.callee,t),Promise.all(e.arguments.map(i=>this.resolve(this.evaluateExpression(i,t))))]);return n(...e.arguments.flatMap((i,a)=>{let s=r[a];if(Y(i,"SpreadElement")){if(!Array.isArray(s))throw new L(`Spread argument must evaluate to an array, got ${d.describeType(s)}.`);return s}return [s]}))}case Y(e,"ConditionalExpression"):return await this.evaluateExpression(e.test,t)?this.evaluateExpression(e.consequent,t):this.evaluateExpression(e.alternate,t);default:throw new L(`Unexpected expression type \`${e.type}\`.`)}}async getCallee(e,t){if(Y(e,"Identifier")){let n=t?.functions?.[e.name]??this.configuration.functions?.[e.name];if(n===void 0)throw new L(`Function \`${e.name}\` does not exist.`);return n}if(Y(e,"MemberExpression")){let n=await this.resolve(this.evaluateExpression(e.object,t)).then(o.unbox),r=Y(e.property,"Identifier")?e.property.name:await this.evaluateExpression(e.property,t);if(typeof r!="string")throw new L(`Method name must be a string, got ${d.describeType(r)}.`);if(!o.isMethodAllowed(n,r))throw new L(`Method \`${r}\` does not exist or is not accessible.`);let i=n[r].bind(n);return (...a)=>i(...a.map(o.unbox))}throw new L("Callee is not callable.")}static isMethodAllowed(e,t){return typeof e=="string"?o.ALLOWED_STRING_METHODS.includes(t):Array.isArray(e)?o.ALLOWED_ARRAY_METHODS.includes(t):e instanceof RegExp?o.ALLOWED_REGEX_METHODS.includes(t):false}static isPropertyAllowed(e,t){return typeof e=="string"?o.ALLOWED_STRING_PROPERTIES.includes(t):Array.isArray(e)?o.ALLOWED_ARRAY_PROPERTIES.includes(t):e instanceof RegExp?o.ALLOWED_REGEX_PROPERTIES.includes(t):typeof e=="object"&&e!==null&&Object.hasOwn(e,t)&&e[t]!==void 0}async resolve(e){if(!(e instanceof Promise)&&(o.isBoxed(e)||typeof e!="object"||e===null))return e;let t=await e;if(o.isBoxed(t))return t;if(Array.isArray(t))return Promise.all(t.map(n=>this.resolve(n)));if(typeof t=="object"&&t!==null){let n=Object.fromEntries(await Promise.all(Object.entries(t).flatMap(([r,i])=>i===void 0?[]:[[r,this.resolve(i)]])));return Object.isFrozen(t)?Object.freeze(n):Object.isSealed(t)&&Object.seal(n),n}return t}static unbox(e){return e instanceof String&&xs in e?e[xs]:e}static isBoxed(e){return e instanceof String||e instanceof Number||e instanceof Boolean}};function Y(o,e){return o.type===e}async function J(o){let e=await o();if(typeof e!="number")throw new L(`Number expected, got ${d.describeType(e)}.`);return e}async function Pn(o){let e=await o();if(typeof e!="boolean")throw new L(`Boolean expected, got ${d.describeType(e)}.`);return e}var Wt=z$1.strictObject({description:z$1.string(),required:z$1.boolean().optional()}),Hu=z$1.union([z$1.string(),z$1.number(),z$1.boolean(),z$1.null()]),kn=z$1.lazy(()=>z$1.union([Hu,z$1.array(kn),z$1.record(kn)])),Ku=z$1.discriminatedUnion("type",[Wt.extend({type:z$1.literal("reference"),default:z$1.string().optional()}),Wt.extend({type:z$1.literal("string"),choices:z$1.array(z$1.string()).optional(),default:z$1.string().optional()}),Wt.extend({type:z$1.literal("number"),default:z$1.number().optional()}),Wt.extend({type:z$1.literal("boolean"),default:z$1.boolean().optional()}),Wt.extend({type:z$1.literal("array"),default:z$1.array(kn).optional()}),Wt.extend({type:z$1.literal("object"),default:z$1.record(z$1.string(),kn).optional()})]),Gu=z$1.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/).min(1),Zu=z$1.strictObject({$schema:z$1.string().optional(),title:z$1.string().min(1),description:z$1.string().min(1),metadata:z$1.record(z$1.string(),kn).optional(),options:z$1.record(Gu,Ku).optional(),actions:z$1.array(z$1.any())}),An=class extends ee{constructor(){super(Zu);}};var bi=class o{constructor(e){this.resolving=[];this.config=e;}async execute(e,t){await this.importTemplate(e,t);}async importTemplate(e,t){let{url:n,value:r}=await this.loadTemplate(e.template,t.baseUrl,t.output),i=await this.getInputValues(r,e.options);if(this.resolving.includes(n.href)){let s=[...this.resolving,n.href].map((p,c)=>` ${c+1}. ${p}`).join(`
|
|
1826
|
-
`);throw new
|
|
1769
|
+
${i}`,{reason:"invalid_input",url:e})}return {...n,value:r.data}}};var vt=class{constructor(e){this.provider=e;}async get(e){let{value:t,...n}=await this.provider.get(e),r=await t.next();if(r.done===true||r.value.type!=="file")throw new He("File not found.",{url:e});return {...n,value:await new Response(r.value.content).text()}}};var xn=class{constructor(e){this.provider=e;}async get(e){let{value:t,...n}=await this.provider.get(e);try{return {...n,value:JsonParser.parse(t).toJSON()}}catch(r){throw new z("Malformed JSON.",{reason:"precondition",url:e,cause:r})}}};var Wu=z$1.strictObject({pattern:z$1.string().refine(o=>{try{return new RegExp(o),!0}catch{return {message:"Invalid regular expression."}}}),destination:z$1.string()}),Vu=z$1.array(Wu),Si=class extends ee{constructor(){super(Vu);}};var wn=class{constructor({fileSystem:e,directory:t,useKeyAsFileName:n}){this.fileSystem=e,this.directory=t,this.useKeyAsFileName=n??false;}async delete(e){await this.fileSystem.delete(this.getCacheFile(e));}async get(e,t){try{return await this.fileSystem.readTextFile(this.getCacheFile(e))}catch{return t(e)}}async set(e,t){return await this.fileSystem.exists(this.directory)||await this.fileSystem.createDirectory(this.directory,{recursive:true}),this.fileSystem.writeTextFile(this.getCacheFile(e),t,{overwrite:true})}getCacheFile(e){return this.fileSystem.joinPaths(this.directory,this.useKeyAsFileName?e:createHash("md5").update(e).digest("hex"))}};var Pn=class{constructor({provider:e,resourceCache:t,errorCache:n}){this.provider=e,this.resourceCache=t,this.errorCache=n;}async get(e){let t=await this.errorCache?.get(e.toString(),()=>Promise.resolve());return t!==void 0?Promise.reject(t):this.resourceCache.get(e.toString(),async()=>{try{return await this.provider.get(e)}catch(n){throw this.errorCache?.set(e.toString(),n),n}})}};var Ut;(e=>{function o(...t){return t.reduce((n,r)=>Object.defineProperties(n,Object.getOwnPropertyDescriptors(r)),{})}e.merge=o;})(Ut||={});var $=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var kn=class o extends ${constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}},Cs=Symbol("regex"),bi=class o{constructor(e={}){this.cache=new Map;this.configuration=e;}static{this.ALLOWED_ARRAY_PROPERTIES=["length"];}static{this.ALLOWED_ARRAY_METHODS=["slice","join","includes","indexOf"];}static{this.ALLOWED_STRING_PROPERTIES=["length"];}static{this.ALLOWED_STRING_METHODS=["slice","indexOf","match","matchAll","replace","replaceAll","includes","startsWith","endsWith","toLowerCase","toUpperCase","repeat","split"];}static{this.ALLOWED_REGEX_PROPERTIES=["source"];}static{this.ALLOWED_REGEX_METHODS=["test"];}static{this.LITERALS={true:true,false:false,null:null};}static{this.UNARY_OPERATORS={"!":{evaluate:async e=>!await Cn(e)},"-":{evaluate:async e=>-await J(e)},"+":{evaluate:async e=>+await J(e)}};}static{this.BINARY_OPERATORS={"||":{precedence:1,evaluate:async(e,t)=>await Cn(e)||Cn(t)},"??":{precedence:1,evaluate:async(e,t)=>{let n=null;try{n=await e();}catch(r){if(!(r instanceof kn))throw r}return n??t()}},"&&":{precedence:2,evaluate:async(e,t)=>await Cn(e)&&Cn(t)},"==":{precedence:6,evaluate:async(e,t)=>await e()==await t()},"===":{precedence:6,evaluate:async(e,t)=>await e()===await t()},"!=":{precedence:6,evaluate:async(e,t)=>await e()!=await t()},"!==":{precedence:6,evaluate:async(e,t)=>await e()!==await t()},"<":{precedence:7,evaluate:async(e,t)=>await J(e)<await J(t)},">":{precedence:7,evaluate:async(e,t)=>await J(e)>await J(t)},"<=":{precedence:7,evaluate:async(e,t)=>await J(e)<=await J(t)},">=":{precedence:7,evaluate:async(e,t)=>await J(e)>=await J(t)},"+":{precedence:9,evaluate:async(e,t)=>{let[n,r]=await Promise.all([e(),t()]);if(typeof n=="string"||typeof r=="string")return `${n}${r}`;if(typeof n!="number"||typeof r!="number")throw new $(`Operands must be numbers or strings, got ${d.describeType(n)} and ${d.describeType(r)}.`);return n+r}},"-":{precedence:9,evaluate:async(e,t)=>await J(e)-await J(t)},"*":{precedence:10,evaluate:async(e,t)=>await J(e)*await J(t)},"/":{precedence:10,evaluate:async(e,t)=>await J(e)/await J(t)},"%":{precedence:10,evaluate:async(e,t)=>await J(e)%await J(t)},"**":{precedence:11,evaluate:async(e,t)=>(await J(e))**await J(t)}};}evaluate(e,t){return this.evaluateExpression(this.parse(e),t)}parse(e){let t=this.cache.get(e);if(t!==void 0)return t;Ge.plugins.register(Hu),Ge.plugins.register(Ku),Ge.plugins.register(Gu),Ge.removeAllUnaryOps();for(let r of Object.keys(o.UNARY_OPERATORS))Ge.addUnaryOp(r);Ge.removeAllBinaryOps();for(let[r,{precedence:i}]of Object.entries(o.BINARY_OPERATORS))Ge.addBinaryOp(r,i);Ge.removeAllLiterals();for(let[r,i]of Object.entries(o.LITERALS))Ge.addLiteral(r,i);let n;try{n=Ge(e);}catch(r){throw new $("Malformed expression.",{cause:r,details:[`Expression: ${e}`]})}return this.cache.set(e,n),n}async evaluateExpression(e,t){switch(true){case Y(e,"Literal"):if(e.raw.startsWith("/")){let n=e.raw.lastIndexOf("/"),r=e.raw.slice(n+1),i=e.raw.slice(1,n),a=new String(e.raw);return Object.assign(a,{[Cs]:new RegExp(i,r)}),a}return e.value;case Y(e,"ThisExpression"):case Y(e,"Identifier"):{let n=e.type==="ThisExpression"?"this":e.name,r=t?.variables?.[n];if(r===void 0)throw new $(`Variable \`${n}\` is unknown.`);return r}case Y(e,"ArrayExpression"):return (await Promise.all(e.elements.map(async r=>{if(r===null)return [];if(Y(r,"SpreadElement")){let i=await this.evaluateExpression(r.argument,t);if(!Array.isArray(i))throw new $(`Spread expression must evaluate to an array, got ${d.describeType(i)}.`);return i}return [await this.evaluateExpression(r,t)]}))).flat();case Y(e,"ObjectExpression"):{let n=await Promise.all(e.properties.map(async r=>{if(Y(r,"SpreadElement")){let a=await this.evaluateExpression(r.argument,t);if(typeof a!="object"||a===null)throw new $(`Spread expression must evaluate to an object, got ${d.describeType(a)}.`);return Object.entries(a)}return r.value===void 0&&Y(r.key,"Identifier")?[[r.key.name,await this.evaluateExpression(r.key,t)]]:[[Y(r.key,"Identifier")?r.key.name:await this.evaluateExpression(r.key,t).then(a=>{if(typeof a!="string"&&typeof a!="number")throw new $(`Property name must be a string or a number, got ${d.describeType(a)}.`);return a}),await this.evaluateExpression(r.value,t)]]}));return Object.fromEntries(n.flat())}case Y(e,"UnaryExpression"):return o.UNARY_OPERATORS[e.operator].evaluate(()=>this.evaluateExpression(e.argument,t));case Y(e,"BinaryExpression"):return o.BINARY_OPERATORS[e.operator].evaluate(()=>this.evaluateExpression(e.left,t),()=>this.evaluateExpression(e.right,t));case Y(e,"MemberExpression"):{let n=await this.evaluateExpression(e.object,t).then(o.unbox);if(typeof n!="object"||n===null)throw new $("Cannot access property of a non-object.");let r=Y(e.property,"Identifier")?e.property.name:await this.evaluateExpression(e.property,t);if(typeof r=="number"){if(!Array.isArray(n))throw new $("Cannot access array index of a non-array.");if(r<0||r>=n.length)throw new kn("Array index is out of bounds.");return n[r]}if(typeof r!="string")throw new $(`Property name must be a string, got ${d.describeType(r)}.`);if(!o.isPropertyAllowed(n,r))throw new kn(`Property \`${r}\` does not exist or is not accessible.`);return n[r]}case Y(e,"CallExpression"):{let[n,r]=await Promise.all([this.getCallee(e.callee,t),Promise.all(e.arguments.map(i=>this.resolve(this.evaluateExpression(i,t))))]);return n(...e.arguments.flatMap((i,a)=>{let s=r[a];if(Y(i,"SpreadElement")){if(!Array.isArray(s))throw new $(`Spread argument must evaluate to an array, got ${d.describeType(s)}.`);return s}return [s]}))}case Y(e,"ConditionalExpression"):return await this.evaluateExpression(e.test,t)?this.evaluateExpression(e.consequent,t):this.evaluateExpression(e.alternate,t);default:throw new $(`Unexpected expression type \`${e.type}\`.`)}}async getCallee(e,t){if(Y(e,"Identifier")){let n=t?.functions?.[e.name]??this.configuration.functions?.[e.name];if(n===void 0)throw new $(`Function \`${e.name}\` does not exist.`);return n}if(Y(e,"MemberExpression")){let n=await this.resolve(this.evaluateExpression(e.object,t)).then(o.unbox),r=Y(e.property,"Identifier")?e.property.name:await this.evaluateExpression(e.property,t);if(typeof r!="string")throw new $(`Method name must be a string, got ${d.describeType(r)}.`);if(!o.isMethodAllowed(n,r))throw new $(`Method \`${r}\` does not exist or is not accessible.`);let i=n[r].bind(n);return (...a)=>i(...a.map(o.unbox))}throw new $("Callee is not callable.")}static isMethodAllowed(e,t){return typeof e=="string"?o.ALLOWED_STRING_METHODS.includes(t):Array.isArray(e)?o.ALLOWED_ARRAY_METHODS.includes(t):e instanceof RegExp?o.ALLOWED_REGEX_METHODS.includes(t):false}static isPropertyAllowed(e,t){return typeof e=="string"?o.ALLOWED_STRING_PROPERTIES.includes(t):Array.isArray(e)?o.ALLOWED_ARRAY_PROPERTIES.includes(t):e instanceof RegExp?o.ALLOWED_REGEX_PROPERTIES.includes(t):typeof e=="object"&&e!==null&&Object.hasOwn(e,t)&&e[t]!==void 0}async resolve(e){if(!(e instanceof Promise)&&(o.isBoxed(e)||typeof e!="object"||e===null))return e;let t=await e;if(o.isBoxed(t))return t;if(Array.isArray(t))return Promise.all(t.map(n=>this.resolve(n)));if(typeof t=="object"&&t!==null){let n=Object.fromEntries(await Promise.all(Object.entries(t).flatMap(([r,i])=>i===void 0?[]:[[r,this.resolve(i)]])));return Object.isFrozen(t)?Object.freeze(n):Object.isSealed(t)&&Object.seal(n),n}return t}static unbox(e){return e instanceof String&&Cs in e?e[Cs]:e}static isBoxed(e){return e instanceof String||e instanceof Number||e instanceof Boolean}};function Y(o,e){return o.type===e}async function J(o){let e=await o();if(typeof e!="number")throw new $(`Number expected, got ${d.describeType(e)}.`);return e}async function Cn(o){let e=await o();if(typeof e!="boolean")throw new $(`Boolean expected, got ${d.describeType(e)}.`);return e}var Wt=z$1.strictObject({description:z$1.string(),required:z$1.boolean().optional()}),Zu=z$1.union([z$1.string(),z$1.number(),z$1.boolean(),z$1.null()]),An=z$1.lazy(()=>z$1.union([Zu,z$1.array(An),z$1.record(An)])),Ju=z$1.discriminatedUnion("type",[Wt.extend({type:z$1.literal("reference"),default:z$1.string().optional()}),Wt.extend({type:z$1.literal("string"),choices:z$1.array(z$1.string()).optional(),default:z$1.string().optional()}),Wt.extend({type:z$1.literal("number"),default:z$1.number().optional()}),Wt.extend({type:z$1.literal("boolean"),default:z$1.boolean().optional()}),Wt.extend({type:z$1.literal("array"),default:z$1.array(An).optional()}),Wt.extend({type:z$1.literal("object"),default:z$1.record(z$1.string(),An).optional()})]),Qu=z$1.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/).min(1),Bu=z$1.strictObject({$schema:z$1.string().optional(),title:z$1.string().min(1),description:z$1.string().min(1),metadata:z$1.record(z$1.string(),An).optional(),options:z$1.record(Qu,Ju).optional(),actions:z$1.array(z$1.any())}),En=class extends ee{constructor(){super(Bu);}};var Ii=class o{constructor(e){this.resolving=[];this.config=e;}async execute(e,t){await this.importTemplate(e,t);}async importTemplate(e,t){let{url:n,value:r}=await this.loadTemplate(e.template,t.baseUrl,t.output),i=await this.getInputValues(r,e.options);if(this.resolving.includes(n.href)){let s=[...this.resolving,n.href].map((p,c)=>` ${c+1}. ${p}`).join(`
|
|
1770
|
+
`);throw new h(`Circular dependency detected while loading templates:
|
|
1827
1771
|
|
|
1828
|
-
${s}`,{reason:"invalid_input"})}this.resolving.push(n.toString());let a=new zt({input:t.input,output:t.output,baseUrl:n});o.shareVariables(i.references,t,a);try{await this.run(r,i.values,a);}finally{this.resolving.pop();}o.shareVariables(i.references,a,t);}async getInputValues(e,t={}){let n={},r=[];for(let[i,a]of Object.entries(e.options??{})){let s=t[i];if(s===void 0&&a.required===true)throw new
|
|
1829
|
-
`?(this.line++,this.column=1):this.column++,i+=a,t>0||n>0)a==="\\"?(i+=this.chars[this.cursor],this.cursor++,this.index++,this.column++):t>0&&a==="'"?t--:n>0&&a==='"'&&n--;else if(r>0){if(a==="'"?t++:a==='"'?n++:a==="{"?r++:a==="}"&&r--,r===0)return this.createExpressionFragment(i,e)}else s&&(i+=this.chars[this.cursor],r++,this.cursor++,this.index++,this.column++);}if(t>0||n>0)throw new d("Unbalanced quotes in template string.",{details:[`Location: line ${e.line}, column ${e.column}`]});if(r>0)throw new d("Unbalanced braces in template string.",{details:[`Location: line ${e.line}, column ${e.column}`]});return this.createLiteralFragment(i,e)}createLiteralFragment(e,t){return {type:"literal",source:e,location:{start:t,end:this.position}}}createExpressionFragment(e,t){return {type:"expression",source:e,expression:e.slice(2,-1).trim(),location:{start:t,end:this.position}}}};var
|
|
1772
|
+
${s}`,{reason:"invalid_input"})}this.resolving.push(n.toString());let a=new zt({input:t.input,output:t.output,baseUrl:n});o.shareVariables(i.references,t,a);try{await this.run(r,i.values,a);}finally{this.resolving.pop();}o.shareVariables(i.references,a,t);}async getInputValues(e,t={}){let n={},r=[];for(let[i,a]of Object.entries(e.options??{})){let s=t[i];if(s===void 0&&a.required===true)throw new h(`Missing required option \`${i}\`.`,{reason:"invalid_input"});let p=await(s??a.resolveDefault?.(this.config.variables));p===void 0?n[i]=null:(a.type==="reference"?(o.checkOptionValue(i,p,{...a,type:"string"}),r.push(p)):o.checkOptionValue(i,p,a),n[i]=p);}return {values:n,references:r}}async run(e,t,n){let{runner:r,variables:i}=this.config,{output:a}=n;for(let{resolve:s}of e.actions){let p=a.notify("Resolving options"),c;try{c=await s(Ut.merge(i,{options:t,get this(){return n.getVariables()}}));}catch(l){throw h.fromCause(l,{message:"Unable to resolve action definition."})}finally{p.stop();}await r.execute({actions:[c]},n);}}async loadTemplate(e,t,n){let r=this.config.templateProvider,i=St(e,t),a=n.notify("Loading template");try{return await r.get(i)}catch(s){throw s instanceof He?new d(`No template found at \`${decodeURIComponent(i.toString())}\`.`,{cause:s,reason:"invalid_input",suggestions:["Check if the template path or URL is correct and try again."]}):s}finally{a.stop();}}static checkOptionValue(e,t,n){switch(n.type){case "number":case "string":case "boolean":{if(typeof t!==n.type)throw new h(`Expected value of type ${n.type} for option \`${e}\`, but got ${d.describeType(t)}.`,{reason:"invalid_input"});if(n.type==="string"&&n.choices!==void 0&&!n.choices.includes(t))throw new h(`Invalid value for option \`${e}\`.`,{reason:"invalid_input",details:[`Allowed values: \`${n.choices.join("`, `")}\`.`]});break}case "array":{if(!Array.isArray(t))throw new h(`Expected value of type ${n.type} for option \`${e}\`,but got ${d.describeType(t)}.`,{reason:"invalid_input"});break}case "object":{if(typeof t!="object"||t===null)throw new h(`Expected value of type ${n.type} for option \`${e}\`,but got ${d.describeType(t)}.`,{reason:"invalid_input"});break}}}static shareVariables(e,t,n){let r=t.getVariables();for(let i of e)r[i]!==void 0&&n.set(i,r[i]);}};var N=class{constructor(e){this.configuration=e;}async execute(e,t){let{action:n,validator:r}=this.configuration,i=await r.validate(e);if(!i.valid){let a=i.violations.map(s=>(s.path===""?s.message:`**${s.path}**: ${s.message}`).replace(/'/g,"`"));throw new h("Invalid action options.",{reason:"invalid_input",details:a})}await n.execute(i.data,t);}};var On;(n=>{let o=Symbol("source");function e(r){return r[o]??null}n.get=e;function t(r,i){r[o]=i;}n.set=t;})(On||={});var vi=class o{constructor(e,t){this.cursor=0;this.chars=[...e],this.index=t.index,this.line=t.line,this.column=t.column;}static parse(e,t){return [...o.from(e,t)]}static from(e,t){return new o(o.getExpression(e),t??(e instanceof JsonPrimitiveNode?e.location.start:{index:0,line:1,column:1}))}static getExpression(e){return typeof e=="string"?e:e instanceof JsonPrimitiveNode?e.value:e.token.value}get position(){return {index:this.index,line:this.line,column:this.column}}done(){return this.cursor>=this.chars.length}[Symbol.iterator](){return this}next(){return {done:this.done(),value:this.consume()}}consume(){if(this.done())return this.createLiteralFragment("",this.position);let e=this.position,t=0,n=0,r=0,i="";for(;this.cursor<this.chars.length;){let a=this.chars[this.cursor],s=a==="$"&&this.chars[this.cursor+1]==="{";if(!(r+t+n>0)&&s&&i.length>0)return this.createLiteralFragment(i,e);if(this.cursor++,this.index++,a===`
|
|
1773
|
+
`?(this.line++,this.column=1):this.column++,i+=a,t>0||n>0)a==="\\"?(i+=this.chars[this.cursor],this.cursor++,this.index++,this.column++):t>0&&a==="'"?t--:n>0&&a==='"'&&n--;else if(r>0){if(a==="'"?t++:a==='"'?n++:a==="{"?r++:a==="}"&&r--,r===0)return this.createExpressionFragment(i,e)}else s&&(i+=this.chars[this.cursor],r++,this.cursor++,this.index++,this.column++);}if(t>0||n>0)throw new d("Unbalanced quotes in template string.",{details:[`Location: line ${e.line}, column ${e.column}`]});if(r>0)throw new d("Unbalanced braces in template string.",{details:[`Location: line ${e.line}, column ${e.column}`]});return this.createLiteralFragment(i,e)}createLiteralFragment(e,t){return {type:"literal",source:e,location:{start:t,end:this.position}}}createExpressionFragment(e,t){return {type:"expression",source:e,expression:e.slice(2,-1).trim(),location:{start:t,end:this.position}}}};var te=class o extends Promise{#t;#n;#e;constructor(e,t=false){super(()=>{}),this.#t=e,this.#n=t;}static from(e){return new o(e)}static transient(e){return new o(e,true)}get promise(){if(this.#e!==void 0)return this.#e;let e=new Promise(t=>{t(this.#t());});return this.#n||(this.#e=e),e}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e)}};var ye=class o extends z{constructor(e,{violations:t,...n}){super(e,n),this.violations=t,Object.setPrototypeOf(this,o.prototype);}},xi=class o{constructor({evaluator:e,validator:t,templateProvider:n,fileProvider:r}){this.loading=[];this.evaluator=e,this.validator=t,this.templateProvider=n,this.fileProvider=r;}async get(e){let{url:t,value:n}=await this.templateProvider.get(e),r;try{r=o.cleanJson(JsonParser.parse(n,JsonObjectNode));}catch(g){throw new ye("Failed to parse the JSON template.",{reason:"invalid_input",url:t,cause:g,violations:[{path:"",message:d.formatMessage(g)}]})}let i=r.toJSON(),a=await this.validator.validate(i);if(!a.valid){let g=a.violations.map(y=>` \u2022 **${y.path}**: ${y.message}`).join(`
|
|
1830
1774
|
|
|
1831
|
-
`);throw new
|
|
1775
|
+
`);throw new ye(`The template contains errors:
|
|
1832
1776
|
|
|
1833
|
-
${g}`,{reason:"invalid_input",url:t,violations:a.violations})}let{options:s,actions:p,...c}=a.data,l=r.get("actions",JsonArrayNode
|
|
1834
|
-
`);throw new
|
|
1777
|
+
${g}`,{reason:"invalid_input",url:t,violations:a.violations})}let{options:s,actions:p,...c}=a.data,l=r.get("actions",JsonArrayNode),u=this.parseOptions(r,s,t);return {url:t,value:{...c,...u!==void 0?{options:u}:{},actions:l.elements.map(g=>({resolve:y=>this.resolve(g,y,t)}))}}}parseOptions(e,t,n){if(t===void 0)return;let r=e.get("options",JsonObjectNode);return Object.fromEntries(Object.entries(t).map(([i,a])=>{if(a.default===void 0)return [i,a];let s=r.get(i,JsonObjectNode).get("default");return [i,{...a,resolveDefault:p=>this.resolve(s,p,n)}]}))}resolve(e,t,n,r=""){return e instanceof JsonArrayNode?e.elements.map((i,a)=>this.resolve(i,t,n,`${r}[${a}]`)):e instanceof JsonObjectNode?te.transient(async()=>{let i=Object.fromEntries(await Promise.all(e.properties.map(async a=>{let s=await this.interpolate(a.key,t,n,r);if(typeof s!="string"&&typeof s!="number"){let c=a.key.location.start;throw new ye("Unexpected object key type.",{url:n,reason:"invalid_input",violations:[{path:r,message:`Expected object key to resolve to string or number at line ${c.line}, column ${c.column} but got ${d.describeType(s)}.`}]})}let p=r===""?`${s}`:`${r}.${s}`;return [s,te.transient(()=>this.resolve(a.value,t,n,p))]})));return On.set(i,{url:n,start:e.location.start,end:e.location.end}),i}):e instanceof JsonPrimitiveNode&&typeof e.value=="string"?te.transient(()=>this.interpolate(e,t,n,r)):e.toJSON()}interpolate(e,t,n,r){let i=vi.parse(e);if(i.length===1){let a=i[0];return a.type==="literal"?a.source:this.evaluate(o.createExpressionNode(a),t,n,r)}return Promise.all(i.map(async a=>{if(a.type==="literal")return a.source;let s=o.createExpressionNode(a),p=await this.evaluate(s,t,n,r);if(p!==null&&!["string","number","boolean"].includes(typeof p)){let c=e.location.start;throw new ye("Unexpected expression result.",{reason:"invalid_input",url:n,violations:[{path:r,message:`Expected expression \`${a.expression}\` to resolve to null, string, number, or boolean value at line ${c.line}, column ${c.column}, but got ${d.describeType(p)}.`}]})}return `${p??""}`})).then(a=>a.join(""))}async evaluate(e,t,n,r){let i=(e instanceof JsonIdentifierNode?e.token.value:e.value).trim();try{return await this.evaluator.evaluate(i,{variables:t,functions:{url:(a="")=>{if(typeof a!="string"){let s=e.location.start;throw new $("Invalid argument for function `url`.",{reason:"invalid_input",details:[`The \`url\` argument of the \`url\` function must be a string, but got ${d.describeType(a)} at line ${s.line}, column ${s.column}.`]})}return St(a,n).toString()},import:(a,s)=>{if(typeof a!="string"){let p=e.location.start;throw new $("Invalid argument for function `import`.",{reason:"invalid_input",details:[`The \`url\` argument of the \`import\` function must be a string, but got ${d.describeType(a)} at line ${p.line}, column ${p.column}.`]})}if(s!==void 0&&(typeof s!="object"||s===null||Array.isArray(s))){let p=e.location.start;throw new $("Invalid argument for function `import`.",{reason:"invalid_input",details:[`The \`properties\` argument of the \`import\` function must be an object, but got ${d.describeType(a)} at line ${p.line}, column ${p.column}.`]})}return this.import(St(a,n),s===void 0?t:Ut.merge(t,{this:Promise.resolve(t.this).then(p=>typeof p=="object"&&p!==null&&!Array.isArray(p)?Ut.merge(p,s):s)}),n,r)}}})}catch(a){let s=e.location.start;throw new ye("Failed to evaluate expression.",{reason:"invalid_input",url:n,cause:a,violations:[{path:r,message:`Evaluation of \`${i}\` at line ${s.line}, column ${s.column} failed because ${d.formatCause(a)}`}]})}}async import(e,t,n,r){if(e.protocol==="file:"&&n.protocol!=="file:")throw new ye("Unsafe import URL.",{reason:"precondition",url:e,violations:[{path:r,message:"File URL is not allowed from remote sources for security reasons."}]});if(this.loading.includes(e.toString())){let p=[...this.loading,e.href].map((c,l)=>` ${l+1}. ${c}`).join(`
|
|
1778
|
+
`);throw new ye(`Circular dependency detected while loading templates:
|
|
1835
1779
|
|
|
1836
|
-
${p}`,{reason:"invalid_input",url:e,violations:[{path:r,message:"Imported template creates a circular dependency."}]})}let{url:i,value:a}=await this.fileProvider.get(e),s;try{s=o.cleanJson(JsonParser$1.parse(a));}catch(p){throw new fe("Failed to parse referenced JSON.",{reason:"invalid_input",cause:p,url:i,violations:[{path:r,message:d.formatMessage(p)}]})}this.loading.push(i.toString());try{return this.resolve(s,t,i,r)}finally{this.loading.pop();}}static createExpressionNode(e){return new JsonPrimitiveNode({value:e.expression,location:e.location,token:new JsonTokenNode({type:JsonTokenType.STRING,value:e.source,location:e.location})})}static cleanJson(e){if(e instanceof JsonPrimitiveNode)return e;if(e instanceof JsonArrayNode$1){for(let t of e.elements)this.cleanJson(t);return e}if(e instanceof JsonObjectNode$1)for(let t of e.properties){let n=t.key.toJSON();n==="$schema"?e.delete(n):this.cleanJson(t.value);}return e}};var Cs=Symbol("any-property"),zc=Symbol("any-index"),Rn=Symbol("passthrough"),Vt=Symbol("resolve"),I=class o extends ee{async validate(e){let t=this.findPassthroughPaths(this.schema),n;try{n=await this.resolveOptions(e,t);}catch(r){if(r instanceof fe)return {valid:false,violations:r.violations};throw r}return super.validate(n).then(r=>(r.valid&&o.restoreSymbols(n,r.data),r))}async resolveOptions(e,t,n=[]){if(typeof e!="object"||e===null||o.isPassthroughPath(n,t))return e;if(e instanceof Promise)return this.resolveOptions(await e,t,n);if(Array.isArray(e)){let r=new Array(e.length),i=new Array(e.length);for(let[a,s]of e.entries()){let p=[...n,a];o.isPassthroughPath(p,t)?i[a]=s:r[a]=this.resolveOptions(await s,t,p);}for(let[a,s]of (await Promise.all(r)).entries())s!==void 0&&(i[a]=s);return i}return {...e,...Object.fromEntries(await Promise.all(Object.entries(e).map(async([r,i])=>{let a=[...n,r];return o.isPassthroughPath(a,t)?[r,i]:[r,await this.resolveOptions(await i,t,a)]})))}}static isPassthroughPath(e,t){for(let n of t)if(n.length===e.length+1)for(let[r,i]of n.entries()){let a=typeof e[r]=="number"?zc:Cs;if(r<e.length?i!==e[r]&&i!==a:i!==Vt&&i!==Rn)break;if(r===n.length-1)return i===Rn}return false}findPassthroughPaths(e,t=[]){if(e instanceof ZodPromise)return [[...t,Rn]];if(e instanceof ZodOptional)return this.findPassthroughPaths(e.unwrap(),t);if(e instanceof ZodTuple)return [[...t,Vt],...e.items.flatMap((n,r)=>this.findPassthroughPaths(n,[...t,r]))];if(e instanceof ZodArray)return [[...t,Vt],...this.findPassthroughPaths(e.element,[...t,zc])];if(e instanceof ZodRecord)return [[...t,Vt],...this.findPassthroughPaths(e.valueSchema,[...t,Cs])];if(e instanceof ZodObject){let n=[[...t,Vt],...Object.entries(e.shape).flatMap(([r,i])=>this.findPassthroughPaths(i,[...t,r]))];return e._def.unknownKeys==="passthrough"&&n.push([...t,Cs,Rn]),n}if(e instanceof ZodEffects){let n=e.innerType();return n instanceof ZodAny?[[...t,Rn]]:this.findPassthroughPaths(n,t)}return e instanceof ZodPipeline?this.findPassthroughPaths(e._def.out,t):e instanceof ZodUnion||e instanceof ZodDiscriminatedUnion?e.options.flatMap(n=>this.findPassthroughPaths(n,t)):[[...t,Vt]]}static restoreSymbols(e,t){if(Array.isArray(e)&&Array.isArray(t)){for(let[n,r]of e.entries())n<t.length&&o.restoreSymbols(r,t[n]);return}if(!(!Lc(e)||!Lc(t))){for(let n of Object.getOwnPropertySymbols(e))Object.assign(t,{[n]:e[n]});for(let[n,r]of Object.entries(e))n in t&&o.restoreSymbols(r,t[n]);}}};var cm=z$1.strictObject({action:z$1.instanceof(Promise),else:z$1.instanceof(Promise).optional(),finally:z$1.instanceof(Promise).optional(),help:z$1.strictObject({message:z$1.string().min(1).optional(),links:z$1.array(z$1.strictObject({url:z$1.string().url(),label:z$1.string().min(1)})).optional(),suggestions:z$1.array(z$1.string().min(1)).optional()}).optional()}),xi=class extends I{constructor(){super(cm);}};var lm=z$1.strictObject({name:z$1.string().min(1),version:z$1.string().min(1).optional(),optional:z$1.boolean().optional()}),um=z$1.strictObject({dependencies:z$1.array(lm),help:z$1.strictObject({message:z$1.string().min(1).optional(),links:z$1.array(z$1.strictObject({url:z$1.string().url(),label:z$1.string().min(1)})).optional(),suggestions:z$1.array(z$1.string().min(1)).optional()}).optional(),result:z$1.record(z$1.string().min(1)).optional()}),wi=class extends I{constructor(){super(um);}};var mm=z$1.strictObject({source:z$1.string().min(1),filter:z$1.string().min(1).optional(),destination:z$1.string().min(1),mapping:z$1.record(z$1.string().min(1),z$1.string().min(1)).optional(),overwrite:z$1.boolean().optional(),result:z$1.strictObject({destination:z$1.string().min(1).optional()}).optional()}),Pi=class extends I{constructor(){super(mm);}};var dm=z$1.strictObject({dependencies:z$1.array(z$1.string().min(1)).min(1),development:z$1.boolean().optional()}),ki=class extends I{constructor(){super(dm);}};var gm=z$1.strictObject({pattern:z$1.string().min(1),caseSensitive:z$1.boolean().optional()}),_c=z$1.union([gm,z$1.strictObject({type:z$1.enum(["and","or"]),matchers:z$1.array(z$1.lazy(()=>_c)).min(1)})]),fm=z$1.strictObject({path:z$1.string().min(1),matcher:_c.optional(),limit:z$1.number().int().positive().optional(),depth:z$1.number().int().nonnegative().optional(),result:z$1.string()}),Ai=class extends I{constructor(){super(fm);}};var ym=z$1.strictObject({files:z$1.array(z$1.strictObject({path:z$1.string(),replacements:z$1.array(z$1.strictObject({pattern:z$1.string().refine(o=>{try{return new RegExp(o),!0}catch{return {message:"Invalid regular expression pattern"}}}),caseSensitive:z$1.boolean().optional(),value:z$1.union([z$1.string(),z$1.number()])})).min(1)})).min(1)}),Ei=class extends I{constructor(){super(ym);}};var hm=z$1.strictObject({slots:z$1.array(z$1.string().min(1)).min(1),example:z$1.boolean().optional()}),Ri=class extends I{constructor(){super(hm);}};var Sm=z$1.strictObject({components:z$1.array(z$1.string().min(1)).min(1)}),Ti=class extends I{constructor(){super(Sm);}};var bm=z$1.strictObject({name:z$1.string().min(1),criteria:z$1.string().min(1)}),xt=z$1.strictObject({title:z$1.string().optional(),description:z$1.string().optional()}),Im=xt.extend({type:z$1.literal("boolean"),label:z$1.strictObject({true:z$1.string(),false:z$1.string()}).optional(),default:z$1.boolean().optional()}),vm=z$1.strictObject({label:z$1.string().optional(),description:z$1.string().optional(),default:z$1.boolean().optional(),position:z$1.number().optional()}),xm=xt.extend({type:z$1.literal("text"),minimumLength:z$1.number().optional(),maximumLength:z$1.number().optional(),format:z$1.string().optional(),pattern:z$1.string().optional(),choices:z$1.record(vm).optional()}),wm=xt.extend({type:z$1.literal("number"),integer:z$1.boolean().optional(),minimum:z$1.number().optional(),maximum:z$1.number().optional()}),Pm=z$1.lazy(()=>z$1.strictObject({type:z$1.lazy(()=>Vc),label:z$1.string().optional(),description:z$1.string().optional(),optional:z$1.boolean().optional(),private:z$1.boolean().optional(),position:z$1.number().optional()})),Es=xt.extend({type:z$1.literal("structure"),attributes:z$1.record(z$1.string(),Pm)}),Cm=xt.extend({type:z$1.literal("list"),items:z$1.lazy(()=>Vc),itemLabel:z$1.string().optional(),minimumLength:z$1.number().optional(),maximumLength:z$1.number().optional()}),km=z$1.union([z$1.string(),z$1.number(),z$1.boolean(),z$1.null()]),As=z$1.lazy(()=>z$1.union([km,z$1.array(As),z$1.record(As)])),Uc=xt.extend({type:z$1.literal("reference"),id:z$1.string(),properties:z$1.record(z$1.string(),As).optional()}),Wc=xt.extend({type:z$1.literal("union"),types:z$1.record(z$1.string(),z$1.discriminatedUnion("type",[Es,Uc]))}),Vc=z$1.discriminatedUnion("type",[Im,xm,wm,Es,Cm,Wc,Uc]),Am=z$1.discriminatedUnion("type",[Es,Wc]),Em=z$1.strictObject({name:z$1.string().min(1),description:z$1.string().min(1).optional(),schema:Am}),Om=z$1.union([z$1.strictObject({type:z$1.literal("static"),value:z$1.string()}),z$1.strictObject({type:z$1.literal("dynamic"),expression:z$1.string(),nullable:z$1.literal(false),default:z$1.string()}),z$1.strictObject({type:z$1.literal("dynamic"),expression:z$1.string(),nullable:z$1.literal(true),default:z$1.string().optional()})]),Rm=z$1.union([z$1.strictObject({type:z$1.literal("static"),value:z$1.number()}),z$1.strictObject({type:z$1.literal("dynamic"),nullable:z$1.literal(false),default:z$1.number(),expression:z$1.string()}),z$1.strictObject({type:z$1.literal("dynamic"),nullable:z$1.literal(true),default:z$1.number().optional(),expression:z$1.string()})]),Tm=z$1.union([z$1.strictObject({type:z$1.literal("static"),value:z$1.boolean()}),z$1.strictObject({type:z$1.literal("dynamic"),nullable:z$1.literal(false),default:z$1.boolean(),expression:z$1.string()}),z$1.strictObject({type:z$1.literal("dynamic"),nullable:z$1.literal(true),default:z$1.boolean().optional(),expression:z$1.string()})]),Dm=z$1.strictObject({type:z$1.literal("text"),value:Om}),Mm=z$1.strictObject({type:z$1.literal("number"),value:Rm}),Nm=z$1.strictObject({type:z$1.literal("boolean"),value:Tm}),qc=z$1.strictObject({type:z$1.literal("structure"),name:z$1.string().optional(),attributes:z$1.record(z$1.string(),z$1.lazy(()=>Hc))}),$m=z$1.strictObject({type:z$1.literal("list"),items:z$1.array(z$1.lazy(()=>Hc))}),Hc=z$1.discriminatedUnion("type",[Dm,Mm,Nm,qc,$m]),Kc=z$1.record(z$1.string(),qc),Lm=z$1.strictObject({name:z$1.string().min(1),component:z$1.string().min(1),content:Kc}),Gc=z$1.record(z$1.string(),Kc),zm=z$1.strictObject({audiences:z$1.array(z$1.string()),content:Gc}),Zc=z$1.strictObject({default:Gc.optional(),segmented:z$1.array(zm).optional()}),_m=z$1.strictObject({name:z$1.string(),content:Zc,baseline:z$1.boolean().optional(),allocation:z$1.number().min(0)}),Fm=z$1.strictObject({name:z$1.string(),draft:z$1.boolean().optional(),audiences:z$1.array(z$1.string()),slots:z$1.array(z$1.string()),experiment:z$1.strictObject({name:z$1.string(),goalId:z$1.string().optional(),crossDevice:z$1.boolean().optional(),traffic:z$1.number().min(0).max(1),variants:z$1.array(_m)}).optional(),content:Zc}),jm=z$1.record(z$1.string().min(1),z$1.string().min(1)),Fc=z$1.record(z$1.union([z$1.string().min(1).regex(/^\d+$/),z$1.number().nonnegative()]),z$1.string().min(1)),jc=z$1.record(z$1.string().min(1),z$1.strictObject({id:z$1.string().min(1).optional(),version:z$1.string().min(1).optional()})),Um=z$1.strictObject({resources:z$1.strictObject({audiences:z$1.record(z$1.string().min(1),bm).optional(),components:z$1.record(z$1.string().min(1),Em).optional(),slots:z$1.record(z$1.string().min(1),Lm).optional(),experiences:z$1.array(Fm).optional()}),result:z$1.strictObject({audiences:jm.optional(),components:jc.optional(),slots:jc.optional(),experiences:Fc.optional(),experiments:Fc.optional()}).optional()}),Di=class extends I{constructor(){super(Um);}};var Wm=z$1.union([z$1.string(),z$1.number(),z$1.boolean(),z$1.null()]),Os=z$1.lazy(()=>z$1.union([Wm,z$1.array(Os),z$1.record(Os)])),Vm=z$1.strictObject({template:z$1.string().min(1),options:z$1.record(z$1.string().min(1),Os).optional()}),Mi=class extends I{constructor(){super(Vm);}};var Ni=class{constructor({formatter:e}){this.formatter=e;}async execute(e,t){let{output:n}=t,r=n.notify("Formatting code");try{await this.formatter.format(e.files);}catch(i){throw S.fromCause(i)}finally{r.stop();}}};var qm=z$1.strictObject({files:z$1.array(z$1.string().min(1)).min(1)}),$i=class extends I{constructor(){super(qm);}};var qt=class{constructor(e){this.discriminator=e.discriminator,this.mapping=e.mapping;}async get(){let e=await this.discriminator(),t=this.mapping[e];if(t===void 0)throw new V(`No value found for discriminator "${String(e)}".`,{reason:"not_supported"});return t instanceof Function?t():t.get()}};var Li=class{constructor(e){this.runner=e;}execute(e,t){return e.condition?this.run(e.then,t):e.else!==void 0?this.run(e.else,t):Promise.resolve()}run(e,t){return this.runner.execute({actions:e},t)}};var Hm=z$1.strictObject({condition:z$1.boolean(),then:z$1.instanceof(Promise),else:z$1.instanceof(Promise).optional()}),_i=class extends I{constructor(){super(Hm);}};var Fi=class{execute(e,t){let n=t.output,r=e.semantics??"neutral";return e.title===void 0?n.log(e.message,r):n.announce({alignment:"left",semantics:r,title:e.title,message:e.message}),Promise.resolve()}};var Km=z$1.strictObject({semantics:z$1.enum(["neutral","info","error","warning","success"]).optional(),title:z$1.string().optional(),message:z$1.string()}),Ui=class extends I{constructor(){super(Km);}};var Wi=class{execute(e){let{message:t,...n}=e;throw new S(t,{...n,reason:"precondition"})}};var Gm=z$1.strictObject({title:z$1.string().min(1).optional(),message:z$1.string().min(1),links:z$1.array(z$1.strictObject({label:z$1.string().min(1),url:z$1.string().url()})).optional(),suggestions:z$1.array(z$1.string().min(1)).optional(),details:z$1.array(z$1.string().min(1)).optional()}),Vi=class extends I{constructor(){super(Gm);}};var qi=class{constructor({url:e,provider:t}){this.url=e,this.provider=t;}get(){return this.provider.get(this.url)}};var Ht=class{constructor(e){this.data=e;}get(){return Promise.resolve(this.data)}};var Hi=class{constructor({packageManager:e,parsers:t,factory:n}){this.packageManager=e,this.parsers=t,this.factory=n;}async get(){let e=await this.packageManager.getScripts();for(let[t,n]of Object.entries(e))for(let r of this.parsers){let i=r.parse(n);if(i!==null)return this.factory.create({...i,command:await this.packageManager.getScriptCommand(t)})}throw new V("No server found.")}};var Ki=class{parse(e){if(!e.includes("next dev"))return null;let t=e.match(/(?:-p|--port)\s*(\d+)/),n=e.match(/(?:-H|--hostname)\s*(\S+)/),r=t!==null?Number.parseInt(t[1],10):null,i=n!==null?n[1]:"localhost";return {protocol:e.includes("-https")?"https":"http",host:i,...r!==null?{port:r}:{},defaultPort:3e3}}};var Gi=class{parse(e){if(!e.includes("vite"))return null;let t=e.match(/--port\s*(\d+)/),n=e.match(/--host\s*(\S+)/),r=t!==null?Number.parseInt(t[1],10):null;return {protocol:"http",host:n!==null?n[1]:"localhost",...r!==null?{port:r}:{},defaultPort:5173}}};var Zi=class{parse(e){if(!e.includes("parcel"))return null;let t=e.match(/(?:-p|--port)\s*(\d+)/),n=e.match(/--host\s*(\S+)/),r=t!==null?Number.parseInt(t[1],10):null,i=n!==null?n[1]:"localhost";return {protocol:e.includes("--https")?"https":"http",host:i,...r!==null?{port:r}:{},defaultPort:1234}}};var Ji=class{parse(e){if(!e.includes("react-scripts start"))return null;let t=e.match(/PORT=(\d+)/),n=e.match(/HOST=(\S+)/),r=e.match(/HTTPS=(\S+)/),i=t!==null?Number.parseInt(t[1],10):null,a=n!==null?n[1]:"localhost";return {protocol:r!==null&&r[1]==="true"?"https":"http",host:a,...i!==null?{port:i}:{},defaultPort:5173}}};var Qi=class{async execute(e,t){let{input:n}=t,r=n===void 0?this.getDefaultValue(e):await this.prompt(e,n);if(r===void 0)throw new S("Action requires user input.",{reason:"precondition",suggestions:["Retry in interactive mode"]});e.result!==void 0&&t.set(e.result,r);}getDefaultValue(e){switch(e.type){case "confirmation":return e.default;case "choice":return e.default;case "multi-choice":{let t=e.options.flatMap(n=>n.selected===true?[n.value]:[]);return t.length===0?void 0:t}case "text":return e.default;default:return}}prompt(e,t){switch(e.type){case "confirmation":return t.confirm(e);case "choice":return t.select(e);case "multi-choice":return t.selectMultiple(e);case "text":{let{required:n=false,...r}=e;return t.prompt({...r,validate:i=>n&&i===""?"This value is required.":true})}case "keypress":return t.wait(e)}}};var Zm=z$1.strictObject({type:z$1.literal("confirmation"),message:z$1.string(),default:z$1.boolean().optional(),result:z$1.string()}),Ts=z$1.string(),Jm=z$1.preprocess(o=>typeof o=="string"?{value:o,label:o}:o,z$1.strictObject({value:Ts,label:z$1.string().min(1).optional(),disabled:z$1.boolean().optional()})).transform(o=>({...o,label:o.label??o.value.toString()})),Qm=z$1.strictObject({type:z$1.literal("choice"),message:z$1.string(),options:z$1.array(Jm),default:Ts.optional(),result:z$1.string()}),Bm=z$1.preprocess(o=>typeof o=="string"?{value:o,label:o}:o,z$1.strictObject({value:Ts,label:z$1.string().min(1).optional(),selected:z$1.boolean().optional(),disabled:z$1.boolean().optional()})).transform(o=>({...o,label:o.label??o.value.toString()})),Ym=z$1.strictObject({type:z$1.literal("multi-choice"),message:z$1.string(),min:z$1.number().optional(),max:z$1.number().optional(),options:z$1.array(Bm),result:z$1.string()}),Xm=z$1.strictObject({type:z$1.literal("text"),message:z$1.string(),default:z$1.string().optional(),required:z$1.boolean().optional(),result:z$1.string()}),ed=z$1.strictObject({type:z$1.literal("keypress"),message:z$1.string(),key:z$1.union([z$1.literal("enter"),z$1.literal("space"),z$1.string().length(1)]).optional(),result:z$1.string().optional()}),td=z$1.discriminatedUnion("type",[Zm,Qm,Ym,Xm,ed]),Bi=class extends I{constructor(){super(td);}};var Yi=class{constructor({serverFactory:e,serverProvider:t,packageManager:n,serverMap:r}){this.factory=e,this.provider=t,this.packageManager=n,this.serverMap=r;}async execute(e,t){let{output:n}=t,r=n.notify("Checking server"),i;try{i=await this.startServer(r,e.server);}finally{r.stop();}e.result?.url!==void 0&&t.set(e.result.url,i.url.toString()),e.result?.id!==void 0&&t.set(e.result.id,i.id??null);}async startServer(e,t){let n=await this.getServer(t),r=await n.getStatus();if(r.running)return {url:r.url,owned:false};e.update("Starting server");let i=randomUUID();return this.serverMap.set(i,n),{id:i,url:await n.start({logger:new ge({status:"Starting server",notifier:e})}),owned:true}}async getServer(e){if(e===void 0){let i=await this.provider.get();if(i===null)throw new d("No server detected.");return i}let t=new URL(e.url),n=t.protocol==="https:",r=n?443:80;return this.factory.create({host:t.hostname,protocol:n?"https":"http",defaultPort:t.port===""?r:Number.parseInt(t.port,10),command:await this.packageManager.getScriptCommand(e.script,e.arguments)})}};var rd=z$1.strictObject({server:z$1.strictObject({script:z$1.string(),arguments:z$1.array(z$1.string()).optional(),url:z$1.string()}).optional(),result:z$1.strictObject({id:z$1.string().optional(),url:z$1.string().optional()}).optional()}),Xi=class extends I{constructor(){super(rd);}};var eo=class{constructor(e){this.actions=e;}async execute(e,t){for(let n of Array.isArray(e.actions)?e.actions:[e.actions])try{await this.run(n,t);}catch(r){if(r instanceof fe&&r.help.cause instanceof JsonParseError){let{location:i}=r.help.cause;throw S.fromCause(r,{tracing:[{name:n.name,source:{url:r.url,start:i.start,end:i.end}}]})}throw S.fromCause(r,{tracing:[{name:n.name,source:En.get(n)??void 0}]})}}run({name:e,...t},n){let r=this.actions[e];if(r===void 0)throw new S(`Unsupported action \`${e}\`.`,{reason:"invalid_input"});return r.execute(t,n)}};var Jc=z$1.object({name:z$1.string().min(1)}).passthrough(),od=z$1.strictObject({actions:z$1.union([Jc,z$1.array(Jc)])}),to=class extends I{constructor(){super(od);}};var no=class{async execute(e,t){let{output:n}=t;await n.open(e.url);}};var ad=z$1.strictObject({url:z$1.string().url()}),ro=class extends I{constructor(){super(ad);}};var sd=z$1.union([z$1.string(),z$1.number(),z$1.boolean(),z$1.null()]),Ds=z$1.lazy(()=>z$1.union([sd,z$1.array(Ds),z$1.record(Ds)])),pd=z$1.strictObject({variables:z$1.record(z$1.string(),Ds)}),io=class extends I{constructor(){super(pd);}};var oo=class{execute(e,t){for(let[n,r]of Object.entries(e.variables))t.set(n,r);return Promise.resolve()}};var cd=z$1.strictObject({id:z$1.string()}),ao=class extends I{constructor(){super(cd);}};var Kt=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var ye=class{constructor(){this.lines=[[]];this.cursor={row:0,column:0};this.snapshot=[[]];this.ansiSequence="";this.lines=[[]];}write(e){for(let t=0;t<e.length;t++){let n=e[t];if(n==="\x1B"){this.ansiSequence="\x1B";continue}if(this.ansiSequence.length>0){this.ansiSequence+=n,/[A-Za-z]/.test(n)&&(this.processAnsiSequence(this.ansiSequence),this.ansiSequence="");continue}if(n==="\r"){let r=this.lines[this.cursor.row];for(let i=this.cursor.column;i<r.length;i++)r[i]=" ";this.cursor.column=0;continue}if(n===`
|
|
1780
|
+
${p}`,{reason:"invalid_input",url:e,violations:[{path:r,message:"Imported template creates a circular dependency."}]})}let{url:i,value:a}=await this.fileProvider.get(e),s;try{s=o.cleanJson(JsonParser.parse(a));}catch(p){throw new ye("Failed to parse referenced JSON.",{reason:"invalid_input",cause:p,url:i,violations:[{path:r,message:d.formatMessage(p)}]})}this.loading.push(i.toString());try{return this.resolve(s,t,i,r)}finally{this.loading.pop();}}static createExpressionNode(e){return new JsonPrimitiveNode({value:e.expression,location:e.location,token:new JsonTokenNode({type:JsonTokenType.STRING,value:e.source,location:e.location})})}static cleanJson(e){if(e instanceof JsonPrimitiveNode)return e;if(e instanceof JsonArrayNode){for(let t of e.elements)this.cleanJson(t);return e}if(e instanceof JsonObjectNode)for(let t of e.properties){let n=t.key.toJSON();n==="$schema"?e.delete(n):this.cleanJson(t.value);}return e}};var Es=Symbol("any-property"),jc=Symbol("any-index"),Tn=Symbol("passthrough"),Vt=Symbol("resolve"),I=class o extends ee{async validate(e){let t=this.findPassthroughPaths(this.schema),n;try{n=await this.resolveOptions(e,t);}catch(r){if(r instanceof ye)return {valid:false,violations:r.violations};throw r}return super.validate(n).then(r=>(r.valid&&o.restoreSymbols(n,r.data),r))}async resolveOptions(e,t,n=[]){if(typeof e!="object"||e===null||o.isPassthroughPath(n,t))return e;if(e instanceof Promise)return this.resolveOptions(await e,t,n);if(Array.isArray(e)){let r=new Array(e.length),i=new Array(e.length);for(let[a,s]of e.entries()){let p=[...n,a];o.isPassthroughPath(p,t)?i[a]=s:r[a]=this.resolveOptions(await s,t,p);}for(let[a,s]of (await Promise.all(r)).entries())s!==void 0&&(i[a]=s);return i}return {...e,...Object.fromEntries(await Promise.all(Object.entries(e).map(async([r,i])=>{let a=[...n,r];return o.isPassthroughPath(a,t)?[r,i]:[r,await this.resolveOptions(await i,t,a)]})))}}static isPassthroughPath(e,t){for(let n of t)if(n.length===e.length+1)for(let[r,i]of n.entries()){let a=typeof e[r]=="number"?jc:Es;if(r<e.length?i!==e[r]&&i!==a:i!==Vt&&i!==Tn)break;if(r===n.length-1)return i===Tn}return false}findPassthroughPaths(e,t=[]){if(e instanceof ZodPromise)return [[...t,Tn]];if(e instanceof ZodOptional)return this.findPassthroughPaths(e.unwrap(),t);if(e instanceof ZodTuple)return [[...t,Vt],...e.items.flatMap((n,r)=>this.findPassthroughPaths(n,[...t,r]))];if(e instanceof ZodArray)return [[...t,Vt],...this.findPassthroughPaths(e.element,[...t,jc])];if(e instanceof ZodRecord)return [[...t,Vt],...this.findPassthroughPaths(e.valueSchema,[...t,Es])];if(e instanceof ZodObject){let n=[[...t,Vt],...Object.entries(e.shape).flatMap(([r,i])=>this.findPassthroughPaths(i,[...t,r]))];return e._def.unknownKeys==="passthrough"&&n.push([...t,Es,Tn]),n}if(e instanceof ZodEffects){let n=e.innerType();return n instanceof ZodAny?[[...t,Tn]]:this.findPassthroughPaths(n,t)}return e instanceof ZodPipeline?this.findPassthroughPaths(e._def.out,t):e instanceof ZodUnion||e instanceof ZodDiscriminatedUnion?e.options.flatMap(n=>this.findPassthroughPaths(n,t)):[[...t,Vt]]}static restoreSymbols(e,t){if(Array.isArray(e)&&Array.isArray(t)){for(let[n,r]of e.entries())n<t.length&&o.restoreSymbols(r,t[n]);return}if(!(!Fc(e)||!Fc(t))){for(let n of Object.getOwnPropertySymbols(e))Object.assign(t,{[n]:e[n]});for(let[n,r]of Object.entries(e))n in t&&o.restoreSymbols(r,t[n]);}}};var mm=z$1.strictObject({action:z$1.instanceof(Promise),else:z$1.instanceof(Promise).optional(),finally:z$1.instanceof(Promise).optional(),help:z$1.strictObject({message:z$1.string().min(1).optional(),links:z$1.array(z$1.strictObject({url:z$1.string().url(),label:z$1.string().min(1)})).optional(),suggestions:z$1.array(z$1.string().min(1)).optional()}).optional()}),wi=class extends I{constructor(){super(mm);}};var dm=z$1.strictObject({name:z$1.string().min(1),version:z$1.string().min(1).optional(),optional:z$1.boolean().optional()}),gm=z$1.strictObject({dependencies:z$1.array(dm),help:z$1.strictObject({message:z$1.string().min(1).optional(),links:z$1.array(z$1.strictObject({url:z$1.string().url(),label:z$1.string().min(1)})).optional(),suggestions:z$1.array(z$1.string().min(1)).optional()}).optional(),result:z$1.record(z$1.string().min(1)).optional()}),Pi=class extends I{constructor(){super(gm);}};var fm=z$1.strictObject({source:z$1.string().min(1),filter:z$1.string().min(1).optional(),destination:z$1.string().min(1),mapping:z$1.record(z$1.string().min(1),z$1.string().min(1)).optional(),overwrite:z$1.boolean().optional(),result:z$1.strictObject({destination:z$1.string().min(1).optional()}).optional()}),Ci=class extends I{constructor(){super(fm);}};var ym=z$1.strictObject({dependencies:z$1.array(z$1.string().min(1)).min(1),development:z$1.boolean().optional()}),Ai=class extends I{constructor(){super(ym);}};var hm=z$1.strictObject({pattern:z$1.string().min(1),caseSensitive:z$1.boolean().optional()}),Uc=z$1.union([hm,z$1.strictObject({type:z$1.enum(["and","or"]),matchers:z$1.array(z$1.lazy(()=>Uc)).min(1)})]),Sm=z$1.strictObject({path:z$1.string().min(1),matcher:Uc.optional(),limit:z$1.number().int().positive().optional(),depth:z$1.number().int().nonnegative().optional(),result:z$1.string()}),Ei=class extends I{constructor(){super(Sm);}};var bm=z$1.strictObject({files:z$1.array(z$1.strictObject({path:z$1.string(),replacements:z$1.array(z$1.strictObject({pattern:z$1.string().refine(o=>{try{return new RegExp(o),!0}catch{return {message:"Invalid regular expression pattern"}}}),caseSensitive:z$1.boolean().optional(),value:z$1.union([z$1.string(),z$1.number()])})).min(1)})).min(1)}),Oi=class extends I{constructor(){super(bm);}};var Im=z$1.strictObject({slots:z$1.array(z$1.string().min(1)).min(1),example:z$1.boolean().optional()}),Ti=class extends I{constructor(){super(Im);}};var vm=z$1.strictObject({components:z$1.array(z$1.string().min(1)).min(1)}),Di=class extends I{constructor(){super(vm);}};var xm=z$1.strictObject({name:z$1.string().min(1),criteria:z$1.string().min(1)}),xt=z$1.strictObject({title:z$1.string().optional(),description:z$1.string().optional()}),wm=xt.extend({type:z$1.literal("boolean"),label:z$1.strictObject({true:z$1.string(),false:z$1.string()}).optional(),default:z$1.boolean().optional()}),Pm=z$1.strictObject({label:z$1.string().optional(),description:z$1.string().optional(),default:z$1.boolean().optional(),position:z$1.number().optional()}),Cm=xt.extend({type:z$1.literal("text"),minimumLength:z$1.number().optional(),maximumLength:z$1.number().optional(),format:z$1.string().optional(),pattern:z$1.string().optional(),choices:z$1.record(Pm).optional()}),km=xt.extend({type:z$1.literal("number"),integer:z$1.boolean().optional(),minimum:z$1.number().optional(),maximum:z$1.number().optional()}),Am=z$1.lazy(()=>z$1.strictObject({type:z$1.lazy(()=>Kc),label:z$1.string().optional(),description:z$1.string().optional(),optional:z$1.boolean().optional(),private:z$1.boolean().optional(),position:z$1.number().optional()})),Ts=xt.extend({type:z$1.literal("structure"),attributes:z$1.record(z$1.string(),Am)}),Em=xt.extend({type:z$1.literal("list"),items:z$1.lazy(()=>Kc),itemLabel:z$1.string().optional(),minimumLength:z$1.number().optional(),maximumLength:z$1.number().optional()}),Om=z$1.union([z$1.string(),z$1.number(),z$1.boolean(),z$1.null()]),Rs=z$1.lazy(()=>z$1.union([Om,z$1.array(Rs),z$1.record(Rs)])),qc=xt.extend({type:z$1.literal("reference"),id:z$1.string(),properties:z$1.record(z$1.string(),Rs).optional()}),Hc=xt.extend({type:z$1.literal("union"),types:z$1.record(z$1.string(),z$1.discriminatedUnion("type",[Ts,qc]))}),Kc=z$1.discriminatedUnion("type",[wm,Cm,km,Ts,Em,Hc,qc]),Rm=z$1.discriminatedUnion("type",[Ts,Hc]),Tm=z$1.strictObject({name:z$1.string().min(1),description:z$1.string().min(1).optional(),schema:Rm}),Dm=z$1.union([z$1.strictObject({type:z$1.literal("static"),value:z$1.string()}),z$1.strictObject({type:z$1.literal("dynamic"),expression:z$1.string(),nullable:z$1.literal(false),default:z$1.string()}),z$1.strictObject({type:z$1.literal("dynamic"),expression:z$1.string(),nullable:z$1.literal(true),default:z$1.string().optional()})]),Mm=z$1.union([z$1.strictObject({type:z$1.literal("static"),value:z$1.number()}),z$1.strictObject({type:z$1.literal("dynamic"),nullable:z$1.literal(false),default:z$1.number(),expression:z$1.string()}),z$1.strictObject({type:z$1.literal("dynamic"),nullable:z$1.literal(true),default:z$1.number().optional(),expression:z$1.string()})]),Nm=z$1.union([z$1.strictObject({type:z$1.literal("static"),value:z$1.boolean()}),z$1.strictObject({type:z$1.literal("dynamic"),nullable:z$1.literal(false),default:z$1.boolean(),expression:z$1.string()}),z$1.strictObject({type:z$1.literal("dynamic"),nullable:z$1.literal(true),default:z$1.boolean().optional(),expression:z$1.string()})]),$m=z$1.strictObject({type:z$1.literal("text"),value:Dm}),Lm=z$1.strictObject({type:z$1.literal("number"),value:Mm}),zm=z$1.strictObject({type:z$1.literal("boolean"),value:Nm}),Gc=z$1.strictObject({type:z$1.literal("structure"),name:z$1.string().optional(),attributes:z$1.record(z$1.string(),z$1.lazy(()=>Zc))}),_m=z$1.strictObject({type:z$1.literal("list"),items:z$1.array(z$1.lazy(()=>Zc))}),Zc=z$1.discriminatedUnion("type",[$m,Lm,zm,Gc,_m]),Jc=z$1.record(z$1.string(),Gc),Fm=z$1.strictObject({name:z$1.string().min(1),component:z$1.string().min(1),content:Jc}),Qc=z$1.record(z$1.string(),Jc),jm=z$1.strictObject({audiences:z$1.array(z$1.string()),content:Qc}),Bc=z$1.strictObject({default:Qc.optional(),segmented:z$1.array(jm).optional()}),Um=z$1.strictObject({name:z$1.string(),content:Bc,baseline:z$1.boolean().optional(),allocation:z$1.number().min(0)}),Wm=z$1.strictObject({name:z$1.string(),draft:z$1.boolean().optional(),audiences:z$1.array(z$1.string()),slots:z$1.array(z$1.string()),experiment:z$1.strictObject({name:z$1.string(),goalId:z$1.string().optional(),crossDevice:z$1.boolean().optional(),traffic:z$1.number().min(0).max(1),variants:z$1.array(Um)}).optional(),content:Bc}),Vm=z$1.record(z$1.string().min(1),z$1.string().min(1)),Wc=z$1.record(z$1.union([z$1.string().min(1).regex(/^\d+$/),z$1.number().nonnegative()]),z$1.string().min(1)),Vc=z$1.record(z$1.string().min(1),z$1.strictObject({id:z$1.string().min(1).optional(),version:z$1.string().min(1).optional()})),qm=z$1.strictObject({resources:z$1.strictObject({audiences:z$1.record(z$1.string().min(1),xm).optional(),components:z$1.record(z$1.string().min(1),Tm).optional(),slots:z$1.record(z$1.string().min(1),Fm).optional(),experiences:z$1.array(Wm).optional()}),result:z$1.strictObject({audiences:Vm.optional(),components:Vc.optional(),slots:Vc.optional(),experiences:Wc.optional(),experiments:Wc.optional()}).optional()}),Mi=class extends I{constructor(){super(qm);}};var Hm=z$1.union([z$1.string(),z$1.number(),z$1.boolean(),z$1.null()]),Ds=z$1.lazy(()=>z$1.union([Hm,z$1.array(Ds),z$1.record(Ds)])),Km=z$1.strictObject({template:z$1.string().min(1),options:z$1.record(z$1.string().min(1),Ds).optional()}),Ni=class extends I{constructor(){super(Km);}};var $i=class{constructor({formatter:e}){this.formatter=e;}async execute(e,t){let{output:n}=t,r=n.notify("Formatting code");try{await this.formatter.format(e.files);}catch(i){throw h.fromCause(i)}finally{r.stop();}}};var Gm=z$1.strictObject({files:z$1.array(z$1.string().min(1)).min(1)}),Li=class extends I{constructor(){super(Gm);}};var qt=class{constructor(e){this.discriminator=e.discriminator,this.mapping=e.mapping;}async get(){let e=await this.discriminator(),t=this.mapping[e];if(t===void 0)throw new V(`No value found for discriminator "${String(e)}".`,{reason:"not_supported"});return t instanceof Function?t():t.get()}};var zi=class{constructor(e){this.runner=e;}execute(e,t){return e.condition?this.run(e.then,t):e.else!==void 0?this.run(e.else,t):Promise.resolve()}run(e,t){return this.runner.execute({actions:e},t)}};var Zm=z$1.strictObject({condition:z$1.boolean(),then:z$1.instanceof(Promise),else:z$1.instanceof(Promise).optional()}),Fi=class extends I{constructor(){super(Zm);}};var ji=class{execute(e,t){let n=t.output,r=e.semantics??"neutral";return e.title===void 0?n.log(e.message,r):n.announce({alignment:"left",semantics:r,title:e.title,message:e.message}),Promise.resolve()}};var Jm=z$1.strictObject({semantics:z$1.enum(["neutral","info","error","warning","success"]).optional(),title:z$1.string().optional(),message:z$1.string()}),Wi=class extends I{constructor(){super(Jm);}};var Vi=class{execute(e){let{message:t,...n}=e;throw new h(t,{...n,reason:"precondition"})}};var Qm=z$1.strictObject({title:z$1.string().min(1).optional(),message:z$1.string().min(1),links:z$1.array(z$1.strictObject({label:z$1.string().min(1),url:z$1.string().url()})).optional(),suggestions:z$1.array(z$1.string().min(1)).optional(),details:z$1.array(z$1.string().min(1)).optional()}),qi=class extends I{constructor(){super(Qm);}};var Hi=class{constructor({url:e,provider:t}){this.url=e,this.provider=t;}get(){return this.provider.get(this.url)}};var Ht=class{constructor(e){this.data=e;}get(){return Promise.resolve(this.data)}};var Ki=class{constructor({packageManager:e,parsers:t,factory:n}){this.packageManager=e,this.parsers=t,this.factory=n;}async get(){let e=await this.packageManager.getScripts();for(let[t,n]of Object.entries(e))for(let r of this.parsers){let i=r.parse(n);if(i!==null)return this.factory.create({...i,command:await this.packageManager.getScriptCommand(t)})}throw new V("No server found.")}};var Gi=class{parse(e){if(!e.includes("next dev"))return null;let t=e.match(/(?:-p|--port)\s*(\d+)/),n=e.match(/(?:-H|--hostname)\s*(\S+)/),r=t!==null?Number.parseInt(t[1],10):null,i=n!==null?n[1]:"localhost";return {protocol:e.includes("-https")?"https":"http",host:i,...r!==null?{port:r}:{},defaultPort:3e3}}};var Zi=class{parse(e){if(!e.includes("vite"))return null;let t=e.match(/--port\s*(\d+)/),n=e.match(/--host\s*(\S+)/),r=t!==null?Number.parseInt(t[1],10):null;return {protocol:"http",host:n!==null?n[1]:"localhost",...r!==null?{port:r}:{},defaultPort:5173}}};var Ji=class{parse(e){if(!e.includes("parcel"))return null;let t=e.match(/(?:-p|--port)\s*(\d+)/),n=e.match(/--host\s*(\S+)/),r=t!==null?Number.parseInt(t[1],10):null,i=n!==null?n[1]:"localhost";return {protocol:e.includes("--https")?"https":"http",host:i,...r!==null?{port:r}:{},defaultPort:1234}}};var Qi=class{parse(e){if(!e.includes("react-scripts start"))return null;let t=e.match(/PORT=(\d+)/),n=e.match(/HOST=(\S+)/),r=e.match(/HTTPS=(\S+)/),i=t!==null?Number.parseInt(t[1],10):null,a=n!==null?n[1]:"localhost";return {protocol:r!==null&&r[1]==="true"?"https":"http",host:a,...i!==null?{port:i}:{},defaultPort:5173}}};var Bi=class{async execute(e,t){let{input:n}=t,r=n===void 0?this.getDefaultValue(e):await this.prompt(e,n);if(r===void 0)throw new h("Action requires user input.",{reason:"precondition",suggestions:["Retry in interactive mode"]});e.result!==void 0&&t.set(e.result,r);}getDefaultValue(e){switch(e.type){case "confirmation":return e.default;case "choice":return e.default;case "multi-choice":{let t=e.options.flatMap(n=>n.selected===true?[n.value]:[]);return t.length===0?void 0:t}case "text":return e.default;default:return}}prompt(e,t){switch(e.type){case "confirmation":return t.confirm(e);case "choice":return t.select(e);case "multi-choice":return t.selectMultiple(e);case "text":{let{required:n=false,...r}=e;return t.prompt({...r,validate:i=>n&&i===""?"This value is required.":true})}case "keypress":return t.wait(e)}}};var Bm=z$1.strictObject({type:z$1.literal("confirmation"),message:z$1.string(),default:z$1.boolean().optional(),result:z$1.string()}),Ns=z$1.string(),Ym=z$1.preprocess(o=>typeof o=="string"?{value:o,label:o}:o,z$1.strictObject({value:Ns,label:z$1.string().min(1).optional(),disabled:z$1.boolean().optional()})).transform(o=>({...o,label:o.label??o.value.toString()})),Xm=z$1.strictObject({type:z$1.literal("choice"),message:z$1.string(),options:z$1.array(Ym),default:Ns.optional(),result:z$1.string()}),ed=z$1.preprocess(o=>typeof o=="string"?{value:o,label:o}:o,z$1.strictObject({value:Ns,label:z$1.string().min(1).optional(),selected:z$1.boolean().optional(),disabled:z$1.boolean().optional()})).transform(o=>({...o,label:o.label??o.value.toString()})),td=z$1.strictObject({type:z$1.literal("multi-choice"),message:z$1.string(),min:z$1.number().optional(),max:z$1.number().optional(),options:z$1.array(ed),result:z$1.string()}),nd=z$1.strictObject({type:z$1.literal("text"),message:z$1.string(),default:z$1.string().optional(),required:z$1.boolean().optional(),result:z$1.string()}),rd=z$1.strictObject({type:z$1.literal("keypress"),message:z$1.string(),key:z$1.union([z$1.literal("enter"),z$1.literal("space"),z$1.string().length(1)]).optional(),result:z$1.string().optional()}),id=z$1.discriminatedUnion("type",[Bm,Xm,td,nd,rd]),Yi=class extends I{constructor(){super(id);}};var Xi=class{constructor({serverFactory:e,serverProvider:t,packageManager:n,serverMap:r}){this.factory=e,this.provider=t,this.packageManager=n,this.serverMap=r;}async execute(e,t){let{output:n}=t,r=n.notify("Checking server"),i;try{i=await this.startServer(r,e.server);}finally{r.stop();}e.result?.url!==void 0&&t.set(e.result.url,i.url.toString()),e.result?.id!==void 0&&t.set(e.result.id,i.id??null);}async startServer(e,t){let n=await this.getServer(t),r=await n.getStatus();if(r.running)return {url:r.url,owned:false};e.update("Starting server");let i=randomUUID();return this.serverMap.set(i,n),{id:i,url:await n.start({logger:new ge({status:"Starting server",notifier:e})}),owned:true}}async getServer(e){if(e===void 0){let i=await this.provider.get();if(i===null)throw new d("No server detected.");return i}let t=new URL(e.url),n=t.protocol==="https:",r=n?443:80;return this.factory.create({host:t.hostname,protocol:n?"https":"http",defaultPort:t.port===""?r:Number.parseInt(t.port,10),command:await this.packageManager.getScriptCommand(e.script,e.arguments)})}};var ad=z$1.strictObject({server:z$1.strictObject({script:z$1.string(),arguments:z$1.array(z$1.string()).optional(),url:z$1.string()}).optional(),result:z$1.strictObject({id:z$1.string().optional(),url:z$1.string().optional()}).optional()}),eo=class extends I{constructor(){super(ad);}};var to=class{constructor(e){this.actions=e;}async execute(e,t){for(let n of Array.isArray(e.actions)?e.actions:[e.actions])try{await this.run(n,t);}catch(r){if(r instanceof ye&&r.help.cause instanceof JsonParseError){let{location:i}=r.help.cause;throw h.fromCause(r,{tracing:[{name:n.name,source:{url:r.url,start:i.start,end:i.end}}]})}throw h.fromCause(r,{tracing:[{name:n.name,source:On.get(n)??void 0}]})}}run({name:e,...t},n){let r=this.actions[e];if(r===void 0)throw new h(`Unsupported action \`${e}\`.`,{reason:"invalid_input"});return r.execute(t,n)}};var Yc=z$1.object({name:z$1.string().min(1)}).passthrough(),pd=z$1.strictObject({actions:z$1.union([Yc,z$1.array(Yc)])}),no=class extends I{constructor(){super(pd);}};var ro=class{async execute(e,t){let{output:n}=t;await n.open(e.url);}};var cd=z$1.strictObject({url:z$1.string().url()}),io=class extends I{constructor(){super(cd);}};var ld=z$1.union([z$1.string(),z$1.number(),z$1.boolean(),z$1.null()]),$s=z$1.lazy(()=>z$1.union([ld,z$1.array($s),z$1.record($s)])),ud=z$1.strictObject({variables:z$1.record(z$1.string(),$s)}),oo=class extends I{constructor(){super(ud);}};var ao=class{execute(e,t){for(let[n,r]of Object.entries(e.variables))t.set(n,r);return Promise.resolve()}};var md=z$1.strictObject({id:z$1.string()}),so=class extends I{constructor(){super(md);}};var Kt=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var he=class{constructor(){this.lines=[[]];this.cursor={row:0,column:0};this.snapshot=[[]];this.ansiSequence="";this.lines=[[]];}write(e){for(let t=0;t<e.length;t++){let n=e[t];if(n==="\x1B"){this.ansiSequence="\x1B";continue}if(this.ansiSequence.length>0){this.ansiSequence+=n,/[A-Za-z]/.test(n)&&(this.processAnsiSequence(this.ansiSequence),this.ansiSequence="");continue}if(n==="\r"){let r=this.lines[this.cursor.row];for(let i=this.cursor.column;i<r.length;i++)r[i]=" ";this.cursor.column=0;continue}if(n===`
|
|
1837
1781
|
`){this.cursor.row++,this.cursor.column=0,this.resize(this.cursor.row);continue}for(this.resize(this.cursor.row);this.lines[this.cursor.row].length<this.cursor.column;)this.lines[this.cursor.row].push(" ");this.lines[this.cursor.row][this.cursor.column]=n,this.cursor.column++;}}processAnsiSequence(e){let t=e.match(/\x1b\[(\d*(?:;\d+)*)?([A-Za-z])/);if(t===null){this.lines[this.cursor.row].push(e);return}let[,n,r]=t,i=n?.split(";").map(a=>a===""?0:Number.parseInt(a,10))??[];switch(r){case "A":{let a=i[0]??1;this.cursor.row=Math.max(0,this.cursor.row-a);break}case "B":{let a=i[0]??1;this.cursor.row+=a,this.resize(this.cursor.row);break}case "C":{let a=i[0]??1;this.cursor.column+=a;break}case "D":{let a=i[0]??1;this.cursor.column=Math.max(0,this.cursor.column-a);break}case "E":{let a=i[0]??1;this.cursor.row+=a,this.resize(this.cursor.row),this.cursor.column=0;break}case "F":{let a=i[0]??1;this.cursor.row=Math.max(0,this.cursor.row-a),this.cursor.column=0;break}case "G":{let a=(i[0]??1)-1;this.cursor.column=Math.max(0,a);break}case "H":case "f":{let a=(i[0]??1)-1,s=(i[1]??1)-1;this.cursor.row=Math.max(0,a),this.resize(this.cursor.row),this.cursor.column=Math.max(0,s);break}case "K":{let a=i[0]??0,s=this.lines[this.cursor.row];switch(a){case 0:s.length=this.cursor.column;break;case 1:for(let p=0;p<=this.cursor.column;p++)s[p]=" ";break;case 2:for(let p=0;p<s.length;p++)s[p]=" ";break}break}case "J":{switch(i[0]??0){case 0:{this.lines[this.cursor.row].length=this.cursor.column,this.lines.length=this.cursor.row+1;break}case 1:{this.lines=this.lines.slice(this.cursor.row);for(let s=0;s<=this.cursor.column;s++)this.lines[0][s]=" ";break}case 2:{this.lines=[[]],this.cursor={row:0,column:0};break}}break}default:this.resize(this.cursor.row),this.lines[this.cursor.row].push(e);break}}resize(e){for(;this.lines.length<=e;)this.lines.push([]);}getSnapshot(){return this.lines.map(e=>e.join("")).join(`
|
|
1838
1782
|
`)}saveSnapshot(){this.snapshot=this.lines.map(e=>[...e]);}getSnapshotDiff(){let e=[];for(let t=0;t<this.lines.length;t++){let n=this.lines[t];if(this.snapshot[t]===void 0){e.push(n.join(""));continue}for(let r=0;r<n.length;r++)if(n[r]!==this.snapshot[t][r]){e.push(n.join(""));break}}return e.join(`
|
|
1839
|
-
`)}static getRawString(e){return
|
|
1783
|
+
`)}static getRawString(e){return nu(e)}};var po=class{constructor(e){this.configuration=e;}async getStatus(){let e=await this.findAddress();return e===null?{running:false}:{running:true,url:e}}async start({logger:e}={}){let{commandExecutor:t,command:n,workingDirectory:r,processObserver:i}=this.configuration;try{this.execution=await t.run(n,{workingDirectory:r.get()});}catch(g){throw new Kt("Failed to start server.",{cause:g})}let a=new AbortController,s=()=>(a.abort(),this.stop());if(this.execution.onExit(()=>{this.execution=void 0,i.off("exit",s);}),!this.execution.running)throw new Kt("Failed to start server.");i.on("exit",s);let{output:p}=this.execution,c=new he,l=(async()=>{for await(let g of p){if(a.signal.aborted)return;c.write(g),e?.log({level:LogLevel.DEBUG,message:g});}})(),u=await this.waitStart(a);if(a.abort(),await l,u===null){e?.log({level:LogLevel.ERROR,message:"Unable to reach the server after it was started."});let g=he.getRawString(c.getSnapshot()).trim();throw new Kt(`Server is unreachable${g===""?".":`:
|
|
1840
1784
|
|
|
1841
|
-
${g}`}`)}return u}async stop(){await this.execution?.kill("SIGINT"),this.execution=void 0;}async waitStart(e){let{startupCheckDelay:t,startupTimeout:n}=this.configuration,r=setTimeout(()=>e.abort(),n);r.unref(),e.signal.addEventListener("abort",()=>{clearTimeout(r);});let i=()=>new Promise(a=>{let s=()=>{a(),e.signal.removeEventListener("abort",s);};setTimeout(a,t),e.signal.addEventListener("abort",s);});do{let a=await this.findAddress(e);if(a!==null)return a;await i();}while(!e.signal.aborted);return null}async findAddress(e){let{lookupTimeout:t,lookupMaxPorts:n,server:{protocol:r,host:i,port:a,defaultPort:s}}=this.configuration,p=a??s,c=a??s+n-1,l=new AbortController;e!==void 0&&e.signal.addEventListener("abort",()=>l.abort()),setTimeout(()=>l.abort(),t).unref();let g=new URL(`${r}://${i}`);for(let y=p;y<=c;y++){try{return g.port=y.toString(),await fetch(g,{method:"HEAD",signal:l.signal}),g}catch{}if(l.signal.aborted)break}return null}};var
|
|
1842
|
-
`,"[down]":"\x1B[A","[up]":"\x1B[B","[left]":"\x1B[C","[right]":"\x1B[D","[backspace]":"\b"};}constructor(e){this.configuration=e;}async execute(e,t){let{input:n,output:r}=t,{sourceChecker:i}=this.configuration;if(e.interactions===true&&e.output!==void 0)throw new
|
|
1785
|
+
${g}`}`)}return u}async stop(){await this.execution?.kill("SIGINT"),this.execution=void 0;}async waitStart(e){let{startupCheckDelay:t,startupTimeout:n}=this.configuration,r=setTimeout(()=>e.abort(),n);r.unref(),e.signal.addEventListener("abort",()=>{clearTimeout(r);});let i=()=>new Promise(a=>{let s=()=>{a(),e.signal.removeEventListener("abort",s);};setTimeout(a,t),e.signal.addEventListener("abort",s);});do{let a=await this.findAddress(e);if(a!==null)return a;await i();}while(!e.signal.aborted);return null}async findAddress(e){let{lookupTimeout:t,lookupMaxPorts:n,server:{protocol:r,host:i,port:a,defaultPort:s}}=this.configuration,p=a??s,c=a??s+n-1,l=new AbortController;e!==void 0&&e.signal.addEventListener("abort",()=>l.abort()),setTimeout(()=>l.abort(),t).unref();let g=new URL(`${r}://${i}`);for(let y=p;y<=c;y++){try{return g.port=y.toString(),await fetch(g,{method:"HEAD",signal:l.signal}),g}catch{}if(l.signal.aborted)break}return null}};var co=class{constructor(e){this.configuration=e;}create(e){return Promise.resolve(new po({...this.configuration,command:e.command,server:{protocol:e.protocol,host:e.host,defaultPort:e.defaultPort,port:e.port}}))}};var gd=z$1.strictObject({path:z$1.string()}),lo=class extends I{constructor(){super(gd);}};var uo=class{constructor({fileSystem:e,rootDirectory:t,currentDirectory:n}){this.fileSystem=e,this.rootDirectory=t,this.currentDirectory=n;}async execute(e){let t=this.fileSystem.normalizeSeparators(e.path),n=this.fileSystem.isAbsolutePath(t)?t:this.fileSystem.joinPaths(this.currentDirectory.get(),t);if(!await this.fileSystem.isDirectory(n))throw new h(`Target path \`${t}\` is not a directory.`,{reason:"invalid_input",details:[`Target path: ${t}`]});if(!this.fileSystem.isSubPath(this.rootDirectory,n))throw new h("Cannot change to a directory outside the current working directory.",{reason:"precondition",details:[`Working directory: ${this.rootDirectory}`,`Target directory: ${n}`]});return this.currentDirectory.setCurrentDirectory(n),Promise.resolve()}};var mo=class o{static{this.INPUT_MAP={"[space]":" ","[enter]":`
|
|
1786
|
+
`,"[down]":"\x1B[A","[up]":"\x1B[B","[left]":"\x1B[C","[right]":"\x1B[D","[backspace]":"\b"};}constructor(e){this.configuration=e;}async execute(e,t){let{input:n,output:r}=t,{sourceChecker:i}=this.configuration;if(e.interactions===true&&e.output!==void 0)throw new h("Cannot capture output when interactions are enabled.",{reason:"not_supported",details:["Either use `interactions` or `output`, but not both."]});let a=await this.resolveCommand(e),s=o.formatCommand(a);if(e.script!==true&&!await i.test(t.baseUrl)){if(n===void 0)throw new h("Action requires explicit user confirmation.",{reason:"precondition",details:["Retry in interactive mode."]});if(r.warn(`This template will run the command \`${s}\``),!await n.confirm({message:"Continue?",default:true}))throw new h("Permission to run command denied.",{reason:"precondition"})}let p=r.notify(`Running \`${s}\``),c;try{c=await this.executeCommand(a,p,e.interactions??!1);}catch(l){throw h.fromCause(l)}finally{p?.stop();}e.output!==void 0&&t.set(e.output,c);}async resolveCommand(e){let t=await this.getPackageManager(e.runner);return e.script===true?t.getScriptCommand(e.command,e.arguments):t.getPackageCommand(e.command,e.arguments)}getPackageManager(e){return e===void 0?this.configuration.packageManager:this.configuration.packageManagerProvider.get(e)}async executeCommand(e,t,n){let{processObserver:r,workingDirectory:i,commandExecutor:a,commandTimeout:s}=this.configuration,p=await a.run(e,{workingDirectory:i.get(),timeout:s,inheritIo:n===true}),c=()=>{p.kill();};r.on("exit",c),p.onExit(()=>r.off("exit",c));let l=o.formatCommand(e);n===true&&t.stop(true);let u=new he,g=new ge({status:`Running \`${l}\``,notifier:t});if(n!==true){let v=Array.isArray(n)?[...n]:[];v.length===0&&await p.endWriting();for await(let D of p.output){u.write(D),g.log({level:LogLevel.DEBUG,message:he.getRawString(D)});let U=u.getSnapshotDiff();for(let[S,P]of v.entries())if(P.pattern===true?new RegExp(P.when).test(U):U.includes(P.when)){u.saveSnapshot(),P.always!==true&&v.splice(S,1);for(let Se of P.then??[])await p.write(o.INPUT_MAP[Se]??Se);P.final===true&&(await p.endWriting(),v.length=0);break}}}let y=-1;try{y=await p.wait();}catch(v){throw new h("Command execution failed.",{reason:"unexpected_result",cause:v})}let C=he.getRawString(u.getSnapshot()).trim();if(y!==0)throw new h(`Command execution failed${C===""?".":`:
|
|
1843
1787
|
|
|
1844
|
-
${C}`}`,{reason:"unexpected_result"});return C}static formatCommand(e){return [e.name.split(/[\\/]/).pop(),...(e.arguments??[]).map(t=>!t.startsWith("-")&&t.includes(" ")?JSON.stringify(t):t)].join(" ")}};var
|
|
1788
|
+
${C}`}`,{reason:"unexpected_result"});return C}static formatCommand(e){return [e.name.split(/[\\/]/).pop(),...(e.arguments??[]).map(t=>!t.startsWith("-")&&t.includes(" ")?JSON.stringify(t):t)].join(" ")}};var yd=z$1.array(z$1.object({when:z$1.string(),pattern:z$1.boolean().optional(),always:z$1.boolean().optional(),then:z$1.array(z$1.string()).min(1).optional(),final:z$1.boolean().optional()}).superRefine((o,e)=>{if(o.then===void 0&&o.final===void 0&&e.addIssue({code:z$1.ZodIssueCode.custom,message:"Either `then` or `final` must be defined"}),o.final===true&&o.always===true&&e.addIssue({code:z$1.ZodIssueCode.custom,path:["always"],message:"Final interactions must have `always` set to `false`"}),o.pattern===true)try{new RegExp(o.when);}catch{e.addIssue({code:z$1.ZodIssueCode.custom,path:["pattern"],message:"The `when` field must be a valid regular expression"});}})).min(1).optional().refine(o=>o===void 0||o.some(e=>e.final===true),{message:"At least one interaction must have `final` set to `true`"}),hd=z$1.strictObject({command:z$1.string(),script:z$1.boolean().optional(),arguments:z$1.array(z$1.string()).optional(),runner:z$1.string().optional(),interactions:z$1.union([z$1.boolean(),yd]),output:z$1.string().optional()}),go=class extends I{constructor(){super(hd);}};var we=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var st=class{constructor(e){this.manifestPath=new Map;this.projectDirectory=e.projectDirectory,this.fileSystem=e.fileSystem,this.agent=e.agent,this.packageValidator=e.packageValidator;}getName(){return this.agent.getName()}isInstalled(){return this.agent.isInstalled()}isProject(){return this.fileSystem.exists(this.getProjectManifestPath())}addDependencies(e,t){return this.agent.addDependencies(e,t)}installDependencies(e){return this.agent.installDependencies(e)}updatePackage(e,t){return this.agent.updatePackage(e,t)}getPackageCommand(e,t=[]){return this.agent.getPackageCommand(e,t)}getScriptCommand(e,t=[]){return this.agent.getScriptCommand(e,t)}getPackageUpdateCommand(e,t){return this.agent.getPackageUpdateCommand(e,t)}async hasDirectDependency(e,t){let n=await this.readManifest(this.getProjectManifestPath());return n?.dependencies?.[e]===void 0&&n?.devDependencies?.[e]===void 0?false:t===void 0?true:this.hasDependency(e,t)}async hasDependency(e,t){let n=await this.getDependency(e);return n===null?false:t===void 0||n.version===null?t===void 0:t===void 0||n.version!==null&&Sd.satisfies(n.version,t)}async getDependency(e){let t=await this.findPackageManifestPath(e);if(t===null)return null;let n=await this.readManifest(t);return n===null?null:{name:n.name,version:n.version??null,directory:this.fileSystem.getDirectoryName(t),metadata:n}}async getScripts(){let e=await this.readManifest(this.getProjectManifestPath());return e===null?{}:e.scripts??{}}async addScript(e,t){let n=this.getProjectManifestPath();if(!await this.fileSystem.exists(n))throw new we("Package file not found in the project.",{reason:"precondition",details:[`File: ${n}`]});let r=await this.fileSystem.readTextFile(n),i=JsonParser.parse(r,JsonObjectNode);if(i.has("scripts")){let a=i.get("scripts",JsonObjectNode),s=t;if(a.has(e)){let c=a.get(e).toJSON();if(typeof c=="string"&&c.includes(t))return;s=`${c} && ${t}`;}a.set(e,s);}else i.set("scripts",{[e]:t});await this.fileSystem.writeTextFile(n,i.toString(),{overwrite:true});}async findPackageManifestPath(e,t){let n=t??this.projectDirectory.get(),r=this.fileSystem.joinPaths(n,"node_modules",e,"package.json"),i=this.manifestPath.get(r);if(i!==void 0)return i;let a=r;if(!await this.fileSystem.exists(r)){let s=this.fileSystem.getDirectoryName(n);a=s!==n?await this.findPackageManifestPath(e,s):null;}return this.manifestPath.set(r,a),a}getProjectManifestPath(){return this.fileSystem.joinPaths(this.projectDirectory.get(),"package.json")}async readManifest(e){if(!await this.fileSystem.exists(e))return null;let t;try{t=JSON.parse(await this.fileSystem.readTextFile(e));}catch{return null}let n=await this.packageValidator.validate(t);return n.valid?n.data:null}};var Je=class{constructor(e){this.projectDirectory=e.projectDirectory,this.commandRunner=e.commandExecutor,this.executableLocator=e.executableLocator;}isInstalled(){return this.installed===void 0&&(this.installed=this.getExecutable(this.getCommandName()).then(e=>e!==null)),this.installed}getName(){return Promise.resolve(this.getCommandName())}async addDependencies(e,t){return this.run(await this.createAddDependencyCommand(e,t?.dev??false),{logger:t?.logger})}async installDependencies(e){return this.run(await this.createInstallDependenciesCommand(),{logger:e?.logger})}async updatePackage(e,t){return this.run(await this.createPackageUpdateCommand(e,t?.global??false),{logger:t?.logger})}getPackageCommand(e,t){return this.createPackageCommand(e,t)}getPackageUpdateCommand(e,t={}){return this.createPackageUpdateCommand(e,t.global??false)}getScriptCommand(e,t){return this.createScriptCommand(e,t)}async run(e,{logger:t,...n}={}){if(!await this.isInstalled())throw new we(`Package manager \`${this.getCommandName()}\` is not installed.`);let r=await this.commandRunner.run(e,{...n,workingDirectory:this.projectDirectory.get()}),i=new he;for await(let a of r.output)i.write(a),t?.log({level:LogLevel.DEBUG,message:he.getRawString(a).trim(),details:{output:he.getRawString(i.getSnapshot()).trim()}});if(await r.wait()!==0){let a=he.getRawString(i.getSnapshot()).trim();throw t?.log({level:LogLevel.ERROR,message:`Failed to run \`${e.name}\` command.`,details:{command:e.name,arguments:e.arguments??[],output:a}}),new we(`Failed to run \`${e.name}\` command${a===""?".":`:
|
|
1845
1789
|
|
|
1846
|
-
${a}`}`)}}getExecutable(e){return this.executableLocator.locate(e)}};var
|
|
1847
|
-
${s}`),{exitCode:i.status??1,output:a}}prepareCommand(e){return this.isWindowShell(e.name)?{name:o.escapeCommand(e.name),arguments:(e.arguments??[]).map(o.escapeArgument),shell:true}:{...e,shell:false}}isWindowShell(e){return this.isWindows&&(e.endsWith(".bat")||e.endsWith(".cmd"))}static escapeCommand(e){return `"${e}"`}static escapeArgument(e){return `"${e.replace("\\","\\\\").replace('"','\\"')}"`}};var
|
|
1790
|
+
${a}`}`)}}getExecutable(e){return this.executableLocator.locate(e)}};var fo=class extends Je{getCommandName(){return "npm"}createPackageCommand(e,t=[]){return Promise.resolve(this.getCommand("npx",["--yes",e,...t]))}createScriptCommand(e,t=[]){return Promise.resolve(this.getCommand(this.getCommandName(),["run",e,...t.length>0?["--",...t]:[]]))}createAddDependencyCommand(e,t){return Promise.resolve(this.getCommand(this.getCommandName(),["install",...t?["--save-dev"]:[],...e]))}createInstallDependenciesCommand(){return Promise.resolve(this.getCommand(this.getCommandName(),["install"]))}createPackageUpdateCommand(e,t=false){return Promise.resolve(this.getCommand(this.getCommandName(),["update",...t?["--global"]:[],e]))}getCommand(e,t=[]){return {name:e,arguments:t}}};var yo=class extends Je{getCommandName(){return "yarn"}createPackageCommand(e,t=[]){return Promise.resolve(this.getCommand("npx",["--yes",e,...t]))}createScriptCommand(e,t=[]){return Promise.resolve(this.getCommand(this.getCommandName(),["run",e,...t]))}createAddDependencyCommand(e,t){return Promise.resolve(this.getCommand(this.getCommandName(),["add",...t?["--dev"]:[],...e]))}createInstallDependenciesCommand(){return Promise.resolve(this.getCommand(this.getCommandName(),["install"]))}createPackageUpdateCommand(e,t=false){return Promise.resolve(this.getCommand(this.getCommandName(),t?["global","add",`${e}@latest`]:["upgrade",e]))}getCommand(e,t=[]){return {name:e,arguments:t}}};var ho=class extends Je{getCommandName(){return "bun"}createPackageCommand(e,t=[]){return Promise.resolve(this.getCommand(["x",e,...t]))}createScriptCommand(e,t=[]){return Promise.resolve(this.getCommand(["run",e,...t]))}createAddDependencyCommand(e,t){return Promise.resolve(this.getCommand(["install",...t?["--dev"]:[],...e]))}createInstallDependenciesCommand(){return Promise.resolve(this.getCommand(["install"]))}createPackageUpdateCommand(e,t=false){return Promise.resolve(this.getCommand(["update",...t?["--global"]:[],e]))}getCommand(e=[]){return {name:this.getCommandName(),arguments:e}}};var So=class extends Je{getCommandName(){return "pnpm"}createPackageCommand(e,t=[]){return Promise.resolve(this.getCommand(["dlx",e,...t]))}createScriptCommand(e,t=[]){return Promise.resolve(this.getCommand(["run",e,...t]))}createAddDependencyCommand(e,t){return Promise.resolve(this.getCommand(["install",...t?["--save-dev"]:[],...e]))}createInstallDependenciesCommand(){return Promise.resolve(this.getCommand(["install"]))}createPackageUpdateCommand(e,t=false){return Promise.resolve(this.getCommand(["update",...t?["--global"]:[],e]))}getCommand(e=[]){return {name:this.getCommandName(),arguments:e}}};var bo=class{constructor({projectDirectory:e,fileSystem:t,tsConfigLoader:n}){this.projectDirectory=e,this.fileSystem=t,this.tsConfigLoader=n;}async getImportPath(e,t){let n=this.projectDirectory.get(),r=this.fileSystem.isAbsolutePath(t)?t:this.fileSystem.joinPaths(n,t),i=this.fileSystem.isAbsolutePath(e)?e:this.fileSystem.joinPaths(n,e),a=await this.tsConfigLoader.load(n,{sourcePaths:[r]}),s=/\.m(?:js|ts)?$/.test(i)?i:i.replace(/\.(ts|js)x?$/,"");if(a!==null&&this.fileSystem.isSubPath(n,s)){let c=this.fileSystem.getRelativePath(n,s),l=0,u=null;for(let[g,y]of Object.entries(a.paths)){let C=this.fileSystem.normalizeSeparators(g.replace(/\*$/,""));for(let v of y){let D=v.replace(/\*$/,""),U=this.fileSystem.getRelativePath(n,this.fileSystem.joinPaths(a.baseUrl,D));if(c.startsWith(U)){let S=D.length;if(S>l){l=S;let P=c.slice(U.length).replace(/^[\\/]+/,"");u=C+P;}}}}if(u!==null)return Promise.resolve(u.replace(/\\+/g,"/"))}let p=this.fileSystem.getRelativePath(this.fileSystem.joinPaths(r,".."),s).replace(/\\/g,"/");return Promise.resolve(/^\.\.?\/ ?/.test(p)?p:`./${p}`)}};var Id=z$1.object({extends:z$1.string().optional(),references:z$1.array(z$1.object({path:z$1.string()})).optional(),include:z$1.array(z$1.string()).optional(),compilerOptions:z$1.object({baseUrl:z$1.string().optional(),paths:z$1.record(z$1.array(z$1.string())).optional()}).optional()}),Io=class extends ee{constructor(){super(Id);}};var Mn=class{constructor(e){this.provider=e;}get manager(){return Promise.resolve(this.provider.get()).catch(e=>{throw e instanceof V?new we(e.message,e.help):e})}async getName(){return (await this.manager).getName()}async isInstalled(){return (await this.manager).isInstalled()}async isProject(){return (await this.manager).isProject()}async hasDependency(e,t){return (await this.manager).hasDependency(e,t)}async hasDirectDependency(e,t){return (await this.manager).hasDirectDependency(e,t)}async getDependency(e){return (await this.manager).getDependency(e)}async addDependencies(e,t){return (await this.manager).addDependencies(e,t)}async updatePackage(e,t){return (await this.manager).updatePackage(e,t)}async installDependencies(e){return (await this.manager).installDependencies(e)}async getScripts(){return (await this.manager).getScripts()}async addScript(e,t){return (await this.manager).addScript(e,t)}async getScriptCommand(e,t){return (await this.manager).getScriptCommand(e,t)}async getPackageCommand(e,t){return (await this.manager).getPackageCommand(e,t)}async getPackageUpdateCommand(e,t){return (await this.manager).getPackageUpdateCommand(e,t)}};var vo=class{constructor(e){this.map=e;}supports(e){return this.map.has(e)}get(e){let t=this.map.get(e);if(t===void 0)throw new V(`No value found for key \`${e}\`.`,{reason:"not_found"});return Promise.resolve(t)}};var xo=class{getName(){return Promise.resolve("noop")}isInstalled(){return Promise.resolve(false)}addDependencies(){return this.fail()}installDependencies(){return this.fail()}updatePackage(){return this.fail()}getPackageCommand(){return this.fail()}getScriptCommand(){return this.fail()}getPackageUpdateCommand(){return this.fail()}fail(){throw new we("The package manager is not installed")}};var Gt=class{constructor(e,t){this.provider=e,this.fallback=t;}async get(...e){let t=await this.provider.get(...e)??null;return t!==null?t:this.fallback.get(...e)}};var $e=class{constructor(e){this.callback=e;}get(...e){return this.callback(...e)}};var wt=class{constructor(e){this.candidates=e.candidates;}async get(...e){for(let{condition:t,value:n}of this.candidates)try{if(await t.test(...e))return typeof n=="object"&&n!==null&&"get"in n?n.get(...e):n}catch{}return null}};var Nn=class{constructor({fileSystem:e,files:t}){this.fileSystem=e,this.files=t;}async test(){return (await Promise.all(this.files.map(t=>this.fileSystem.exists(t)))).some(t=>t)}};var $n=class{constructor({packageManager:e,dependencies:t}){this.packageManager=e,this.dependencies=t;}async test(){return (await Promise.all(this.dependencies.map(t=>this.packageManager.hasDirectDependency(t)))).some(t=>t)}};var wo=class{constructor({packageManager:e}){this.packageManager=e;}test(){return this.packageManager.isProject()}};var Le=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var Po=class{constructor(){this.open=true;this.queue=[];}async*[Symbol.asyncIterator](){let e=await this.next();for(;e.done!==true;)yield e.value,e=await this.next();}next(){return this.queue.length>0?Promise.resolve({done:false,value:this.queue.shift()}):this.open?new Promise(e=>{this.resolve=()=>{this.resolve=void 0,this.queue.length===0?e({done:true,value:void 0}):e({done:false,value:this.queue.shift()});};}):Promise.resolve({done:true,value:void 0})}push(e){this.queue.push(e),this.resolve?.();}close(){this.open=false,this.resolve?.();}};var Co=class o{constructor({currentDirectory:e,windows:t=false}){this.currentDirectory=e,this.isWindows=t;}run(e,t={}){let n=t.timeout!==void 0?AbortSignal.timeout(t.timeout):void 0,r=this.prepareCommand(e),i=spawn(r.name,r.arguments??[],{stdio:t.inheritIo===true?"inherit":"pipe",shell:r.shell,cwd:t?.workingDirectory??this.currentDirectory?.get(),signal:n}),a=new Po,s=[],p=null;i.on("error",u=>{a.close(),p=n?.aborted===true?new Le("Command timed out.",{reason:"precondition",cause:u}):new Le(`Failed to run command: ${d.formatCause(u)}`,{cause:u});for(let g of s)g(p);});let c=u=>{a.push(u.toString());};i.stdout?.on("data",c),i.stderr?.on("data",c);let l=[];return i.on("exit",u=>{a.close();for(let g of l)g(u??1);}),Promise.resolve({output:a,get running(){return i.exitCode===null},onExit:u=>(l.push(u),()=>{let g=l.indexOf(u);g!==-1&&l.splice(g,1);}),write:u=>new Promise((g,y)=>{if(i.stdin===null){y(new Le("Subprocess is not writable."));return}i.stdin.write(u,C=>{C===null?g():y(C);});}),endWriting:()=>new Promise(u=>{if(i.stdin===null||i.exitCode!==null){u();return}i.stdin.end(u);}),read:async()=>{let u="";for await(let g of a)u+=g;return u},wait:()=>new Promise((u,g)=>{if(p!==null){g(p);return}if(i.exitCode!==null){u(i.exitCode);return}s.push(g),i.on("exit",y=>{u(y??1);});}),kill:u=>new Promise((g,y)=>{if(i.exitCode!==null){g();return}i.stdout?.destroy(),i.stderr?.destroy(),i.stdin?.destroy(),i.kill(u)?g():y(new Le("Failed to kill the subprocess."));})})}runSync(e,t={}){let n=t.timeout!==void 0?AbortSignal.timeout(t.timeout):void 0,r=this.prepareCommand(e),i=spawnSync(r.name,r.arguments,{stdio:[t.inheritIo===true?"inherit":"ignore","pipe","pipe"],cwd:t?.workingDirectory??this.currentDirectory?.get(),shell:r.shell,signal:n});if(i.error!==void 0){let{error:p}=i;throw n?.aborted===true?new Le("Command timed out.",{reason:"precondition",cause:p}):new Le(`Failed to run command: ${d.formatCause(p)}`,{cause:p})}let a=i.stdout.toString(),s=i.stderr.toString();return a!==""&&s!==""&&(a=`${a}
|
|
1791
|
+
${s}`),{exitCode:i.status??1,output:a}}prepareCommand(e){return this.isWindowShell(e.name)?{name:o.escapeCommand(e.name),arguments:(e.arguments??[]).map(o.escapeArgument),shell:true}:{...e,shell:false}}isWindowShell(e){return this.isWindows&&(e.endsWith(".bat")||e.endsWith(".cmd"))}static escapeCommand(e){return `"${e}"`}static escapeArgument(e){return `"${e.replace("\\","\\\\").replace('"','\\"')}"`}};var ko=class{constructor(e){this.provider=e;}async format(e){return (await this.formatter).format(e)}get formatter(){return Promise.resolve(this.provider.get()).catch(e=>{throw e instanceof V?new we(e.message,e.help):e})}};var Ao=class{constructor(e){this.provider=e;}get sdk(){return Promise.resolve(this.provider.get()).catch(e=>{throw e instanceof V?new ie(e.message,e.help):e})}async setup(e){return (await this.sdk).setup(e)}async getPaths(e){return (await this.sdk).getPaths(e)}async update(e,t){return (await this.sdk).update(e,t)}async generateSlotExample(e,t){return (await this.sdk).generateSlotExample(e,t)}};var Ln=class{constructor(e,t){this.valueProvider=e,this.keyProvider=t;}async get(...e){if(this.keyProvider!==void 0){let t=this.key;if(this.key=await this.keyProvider.get(...e),t===this.key&&this.value!==void 0)return this.value}else if(this.value!==void 0)return this.value;return this.value=Promise.resolve(this.valueProvider.get(...e)),this.value}};var Eo=class{constructor(e){this.predicate=e;}async test(...e){return !await this.predicate.test(...e)}};var Oo=class{constructor({fileSystem:e,workingDirectory:t}){this.cache=new Map;this.fileSystem=e,this.workingDirectory=t;}async test(e){return (await this.getPredicate()).test(e)}async getPredicate(){let e=this.workingDirectory.get(),t=this.fileSystem.joinPaths(e,".gitignore");if(this.cache.has(t))return this.cache.get(t);let n={test:()=>Promise.resolve(false)};if(await this.fileSystem.exists(t)){let r=wd();r.add(await this.fileSystem.readTextFile(t)),n={test:i=>{if(!this.fileSystem.isSubPath(e,i))return Promise.resolve(false);let a=this.fileSystem.getRelativePath(e,i);return a===""?Promise.resolve(false):Promise.resolve(r.ignores(a))}};}return this.cache.set(t,n),n}};var Ro=class{constructor(e){this.predicate=e;}get(...e){return this.predicate.test(...e)}};var zn=class{constructor(e){this.input=e;}confirm(e){return e.default!==void 0?Promise.resolve(e.default):this.input.confirm(e)}prompt(e){return e.default!==void 0?Promise.resolve(e.default):this.input.prompt(e)}select(e){return e.default!==void 0?Promise.resolve(e.default):this.input.select(e)}selectMultiple(e){let t=e.options.filter(n=>n.selected===true);return t.length>0&&(e.min===void 0||t.length>=e.min)?Promise.resolve(t.map(n=>n.value)):this.input.selectMultiple(e)}wait(e){return this.input.wait(e)}};var _n=class{constructor(...e){this.predicates=e;}async test(...e){for(let t of this.predicates)if(await t.test(...e))return true;return false}};var Ls={};Cl(Ls,{basename:()=>kd,dirname:()=>Ad,ext:()=>Cd,uuid:()=>Ed});var Cd=o=>{if(typeof o!="string")throw new $(`The \`path\` argument of the \`ext\` function must be a string, but got ${d.describeType(o)}.`);return o.split(".").pop()??""},kd=(o,e=false)=>{if(typeof o!="string")throw new $(`The \`path\` argument of the \`basename\` function must be a string, but got ${d.describeType(o)}.`);if(typeof e!="boolean")throw new $(`The \`omitExtension\` argument of the \`basename\` function must be a boolean, but got ${d.describeType(e)}.`);let t=o.split(/[\\/]/).pop()??"";return e?t.replace(/\.[^/.]+$/,""):t},Ad=o=>{if(typeof o!="string")throw new $(`The \`path\` argument of the \`dirname\` function must be a string, but got ${d.describeType(o)}.`);return o.replace(/[\\/][^\\/]*$/,"")},Ed=()=>randomUUID();var To=class{constructor(e){this.runner=e;}async execute(e,t){for(;await e.condition;)await this.run(e.actions,t);}run(e,t){return this.runner.execute({actions:e},t)}};var Od=z$1.strictObject({condition:z$1.instanceof(Promise),actions:z$1.instanceof(Promise)}),Do=class extends I{constructor(){super(Od);}};var q=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var Mo=class o{constructor({fileSystem:e,commandExecutor:t,appDirectory:n}){this.fileSystem=e,this.commandExecutor=t,this.appDirectory=n;}async isRegistered(e){return await this.findLauncher(e)!==null}async register(e){if(!await this.isRegistered(e.protocol))try{await this.install(e);}catch(t){throw new q("Failed to register protocol handler.",{cause:t})}}async unregister(e){let t=await this.findLauncher(e);if(t===null)return;let n=this.getLauncherAppPath(e);if(t!==n)throw new q(`Application registered for protocol \`${e}\` is externally managed.`,{reason:"precondition"});try{await this.fileSystem.delete(n,{recursive:!0}),await this.fileSystem.delete(this.getHandlerAppPath(e),{recursive:!0});}catch(r){throw new q("Failed to unregister protocol handler.",{cause:r})}}async install(e){let t=this.getLauncherAppPath(e.protocol),n=this.getHandlerAppPath(e.protocol),r=this.createLauncherApp(e,n),i=this.createHandlerApp(e),a=await this.fileSystem.createTemporaryDirectory("protocol"),s=this.fileSystem.joinPaths(a,"launcher.scpt"),p=this.fileSystem.joinPaths(a,"handler.scpt");await this.fileSystem.writeTextFile(s,r),await this.fileSystem.writeTextFile(p,i),await this.fileSystem.createDirectory(this.appDirectory,{recursive:true}),await this.execute({name:"osacompile",arguments:["-o",t,s]}),await this.execute({name:"osacompile",arguments:["-o",n,p]}),await this.execute({name:"plutil",arguments:["-insert","CFBundleURLTypes","-json",JSON.stringify([{CFBundleURLName:o.formatId(e.id),CFBundleURLSchemes:[e.protocol]}]),`${t}/Contents/Info.plist`]}),await this.execute({name:"open",arguments:["-g",t]});}async findLauncher(e){let n=(await this.execute({name:"osascript",arguments:["-e",oe`
|
|
1848
1792
|
use AppleScript version "2.4"
|
|
1849
1793
|
use framework "Foundation"
|
|
1850
1794
|
use framework "AppKit"
|
|
@@ -1859,18 +1803,18 @@ ${s}`),{exitCode:i.status??1,output:a}}prepareCommand(e){return this.isWindowShe
|
|
|
1859
1803
|
end if
|
|
1860
1804
|
|
|
1861
1805
|
return appUrl's path as text
|
|
1862
|
-
`]})).trim();return n===""?null:n}async execute(e){let t=await this.commandExecutor.run(e);if(await t.wait()!==0)throw new d(`Failed to execute command \`${e.name}\`.`);return t.read()}createLauncherApp(e,t){let n=o.formatId(e.id);return
|
|
1806
|
+
`]})).trim();return n===""?null:n}async execute(e){let t=await this.commandExecutor.run(e);if(await t.wait()!==0)throw new d(`Failed to execute command \`${e.name}\`.`);return t.read()}createLauncherApp(e,t){let n=o.formatId(e.id);return oe`
|
|
1863
1807
|
on open location this_URL
|
|
1864
1808
|
do shell script "defaults write ${n} current_url " & quoted form of this_URL
|
|
1865
1809
|
tell application "${t}" to activate
|
|
1866
1810
|
end open location
|
|
1867
|
-
`}createHandlerApp(e){let t=o.formatId(e.id),n=e.command.replace(/\$url/,'" & quoted form of this_URL & "');return
|
|
1811
|
+
`}createHandlerApp(e){let t=o.formatId(e.id),n=e.command.replace(/\$url/,'" & quoted form of this_URL & "');return oe`
|
|
1868
1812
|
set this_URL to do shell script "defaults read ${t} current_url"
|
|
1869
1813
|
tell application "Terminal"
|
|
1870
1814
|
do script "${n}"
|
|
1871
1815
|
activate
|
|
1872
1816
|
end tell
|
|
1873
|
-
`}getLauncherAppPath(e){return this.getAppPath(`${e}`)}getHandlerAppPath(e){return this.getAppPath(`${e}-handler`)}getAppPath(e){return this.fileSystem.joinPaths(this.appDirectory,`${e}.app`)}static formatId(e){return e.split(/[^a-zA-Z0-9]+/g).join(".")}};var
|
|
1817
|
+
`}getLauncherAppPath(e){return this.getAppPath(`${e}`)}getHandlerAppPath(e){return this.getAppPath(`${e}-handler`)}getAppPath(e){return this.fileSystem.joinPaths(this.appDirectory,`${e}.app`)}static formatId(e){return e.split(/[^a-zA-Z0-9]+/g).join(".")}};var No=class o{constructor({commandExecutor:e}){this.commandExecutor=e;}async isRegistered(e){return await this.findCommand(e)!==null}async register(e){if(!await this.isRegistered(e.protocol))try{await this.install(e);}catch(t){throw new q("Failed to register protocol handler",{cause:t})}}async install(e){let t=o.getRegistryPath(e.protocol),n=o.getCommandRegistryPath(e.protocol),r=o.getCommand(e.command);await this.execute({name:"REG",arguments:["add",t,"/f"]}),await this.execute({name:"REG",arguments:["add",t,"/v","URL Protocol","/t","REG_SZ","/d","","/f"]}),await this.execute({name:"REG",arguments:["add",t,"/ve","/t","REG_SZ","/d",`URL:${e.protocol}`,"/f"]}),await this.execute({name:"REG",arguments:["add",n,"/ve","/t","REG_SZ","/d",r,"/f"]});}async unregister(e){let t=await this.findCommand(e);if(t!==null){if(!t.startsWith(o.getCommand("")))throw new q(`Application registered for protocol \`${e}\` is externally managed.`,{reason:"precondition"});try{await this.execute({name:"REG",arguments:["DELETE",`${o.getRegistryPath(e)}`,"/f"]});}catch(n){throw new q("Failed to unregister protocol handler",{cause:n})}}}async execute(e){let t=await this.commandExecutor.run(e);if(await t.wait()!==0)throw new d(`Failed to execute command \`${e.name}\`.`);return t.read()}async findCommand(e){let t=await this.execute({name:"REG",arguments:["query",`${o.getCommandRegistryPath(e)}`,"/ve"]}).catch(()=>null);if(t===null)return null;let n=/REG_SZ\s+(.*)/g.exec(t);return n===null?null:n[1].trim()}static getCommand(e){return `PowerShell -NoExit -Command ${e.replace(/\$url/,'"%1"')}`}static getCommandRegistryPath(e){return o.getRegistryPath(e,"shell\\open\\command")}static getRegistryPath(e,t){return `HKCU\\Software\\Classes\\${e}${t!==void 0?`\\${t}`:""}`}};var $o=class o{static{this.COMMAND="gnome-terminal -- bash --login -ic ";}constructor({fileSystem:e,commandExecutor:t,homeDirectory:n}){this.fileSystem=e,this.commandExecutor=t,this.homeDirectory=n;}async isRegistered(e){return await this.findDesktopEntry(e)!==null}async register(e){if(!await this.isRegistered(e.protocol))try{await this.fileSystem.writeTextFile(this.getDesktopEntryPath(e.protocol),o.createDesktopEntry(e)),await this.updateDesktopDatabase();}catch(t){throw new q("Failed to register protocol handler.",{cause:t})}}async unregister(e){let t=await this.findDesktopEntry(e);if(t===null)return;let n=await this.getCommand(t),r=this.getDesktopEntryPath(e);if(t!==r||n?.startsWith(o.COMMAND)!==true)throw new q(`Application registered for protocol \`${e}\` is externally managed.`,{reason:"precondition"});try{await this.fileSystem.delete(t),await this.updateDesktopDatabase();}catch(i){throw new q("Failed to unregister protocol handler.",{cause:i})}}async updateDesktopDatabase(){await this.execute({name:"update-desktop-database",arguments:[this.getApplicationPath()]});}async getCommand(e){if(!await this.fileSystem.exists(e))return null;let t=await this.fileSystem.readTextFile(e);if(!/^MimeType=x-scheme-handler\//im.test(t))return null;let n=t.match(/^Exec=(.*)$/im);return n===null?null:n[1].trim()}async findDesktopEntry(e){let t=null;try{t=await this.execute({name:"xdg-mime",arguments:["query","default",`x-scheme-handler/${e}`]});}catch{return null}let n=t.trim();return n===""?null:this.fileSystem.joinPaths(this.getApplicationPath(),n)}async execute(e){let t=await this.commandExecutor.run(e);if(await t.wait()!==0)throw new d(`Failed to execute command \`${e.name}\`.`);return t.read()}static createDesktopEntry(e){let t=e.command.replace(/\$url/,"'%u'");return oe`
|
|
1874
1818
|
[Desktop Entry]
|
|
1875
1819
|
Type=Application
|
|
1876
1820
|
Name=${e.name}
|
|
@@ -1878,13 +1822,13 @@ ${s}`),{exitCode:i.status??1,output:a}}prepareCommand(e){return this.isWindowShe
|
|
|
1878
1822
|
StartupNotify=false
|
|
1879
1823
|
Terminal=true
|
|
1880
1824
|
MimeType=x-scheme-handler/${e.protocol}
|
|
1881
|
-
`}getDesktopEntryPath(e){return this.fileSystem.joinPaths(this.getApplicationPath(),`${e}.desktop`)}getApplicationPath(){return this.fileSystem.joinPaths(this.homeDirectory,".local","share","applications")}};var $o=class{constructor(e){this.config=e;}async execute({url:e}){if(!URL.canParse(e))throw new d("The URL is not valid.",{reason:"invalid_input"});let t=new URL(e);if(!this.isValidUrl(t))throw new d("The URL is not supported.",{reason:"invalid_input"});let{input:n,output:r}=this.config.io;if(n===void 0)throw new d("Deep links requires explicit user interaction.",{reason:"precondition",details:["Retry in interactive mode."]});let i=this.parseArguments(t);r.announce({semantics:"neutral",title:"\u{1F517} Croct link",message:"You just opened a link to a `Croct CLI` command.",alignment:"center"});let a=i.join(" ");r.inform(`The command is \`${a}\``),await n.confirm({message:"Continue?",default:true})&&(await this.selectDirectory(n),await this.config.program(i));}async selectDirectory(e){let{workingDirectory:t,configurationProvider:n,fileSystem:r,io:{output:i}}=this.config,a=t.get(),{projectPaths:s}=await n.get(),p="";if(s.length>0){let c=r.getDirectoryName(s[0]);p=await e.select({message:"Where should this command run?",options:[{label:`${a} (current)`,value:""},{label:c,value:c},...s.map(l=>({value:l,label:l}))]});}else i.inform(`You are currently in \`${a}\``),await e.confirm({message:"Run the command from the current directory?",default:true})||await e.prompt({message:"Where do you want to run the command from?",default:a,validate:async c=>await r.isDirectory(c)?true:"Enter a valid directory path."});p!==""&&t.setCurrentDirectory(p);}parseArguments(e){let t=[];for(let r of (e.hostname+e.pathname).split("/"))r!==""&&t.push(r);let n=[];for(let[r,i]of e.searchParams){if(r==="arg"){n.push(i);continue}if(i===""){t.push(`-${r.length===1?"":"-"}${r}`);continue}t.push(`--${r}`),t.push(i);}return t.push(...n),t}isValidUrl(e){return e.protocol===`${this.config.protocol}:`&&e.username===""&&e.password===""&&e.port===""&&e.hash===""}};var Ad=z$1.strictObject({version:z$1.string().optional(),projectPaths:z$1.array(z$1.string().min(1)),isDeepLinkingEnabled:z$1.boolean().optional(),lastUpdateCheck:z$1.number().optional()}),Lo=class extends ee{constructor(){super(Ad);}};var zo=class{constructor({manager:e,workingDirectory:t,configurationProvider:n}){this.manager=e,this.workingDirectory=t,this.configurationProvider=n;}isInitialized(){return this.manager.isInitialized()}async load(){let e=await this.manager.load();return await this.updateIndex(),e}update(e){return Promise.all([this.manager.update(e),this.updateIndex()]).then(([t])=>t)}async updateIndex(){let e=await this.configurationProvider.get();await this.configurationProvider.save({...e,projectPaths:[this.workingDirectory.get(),...e.projectPaths]});}};var _o=class{constructor(e){this.fileSystem=e.fileSystem,this.executablePaths=e.executablePaths,this.executableExtensions=e.executableExtensions??[],this.executableCache=e.cache??new NoopCache;}locate(e){return this.executableCache.get(e,t=>this.findPath(t))}async findPath(e){for(let t of this.executablePaths)for(let n of [...this.executableExtensions,""]){let r=this.fileSystem.joinPaths(t,e+n.toLowerCase());if(r!==null&&await this.fileSystem.exists(r))return r}return null}};var Fo=class{constructor(e){this.projectDirectory=e.projectDirectory,this.fileSystem=e.fileSystem,this.packageManager=e.packageManager;}async test(){return (await this.getPreferredPackageManager())?.includes(this.packageManager)===true}async getPreferredPackageManager(){let e=this.fileSystem.joinPaths(this.projectDirectory.get(),"package.json");if(!await this.fileSystem.exists(e))return null;let t;try{t=JSON.parse(await this.fileSystem.readTextFile(e));}catch{return null}return typeof t=="object"&&t!==null&&"packageManager"in t&&typeof t.packageManager=="string"?t.packageManager:null}};var _n=class{constructor(e){this.cliVersion=e.cliVersion,this.autoUpdater=e.autoUpdater,this.deepLinkInstaller=e.deepLinkInstaller,this.configurationProvider=e.configurationProvider;}async execute(e){let t=await this.configurationProvider.get(),n=t.version;n!==this.cliVersion&&await this.configurationProvider.save({...t,version:this.cliVersion}),e.skipUpdateCheck!==true&&await this.autoUpdater.checkForUpdates(),e.skipDeepLinkCheck!==true&&await this.deepLinkInstaller(n!==this.cliVersion);}};var jo=class{constructor(e){this.process=e.process,this.variable=e.variable,this.value=e.value;}test(){let e=this.process.getEnvValue(this.variable);return e===null?false:this.value?.test(e)===true}};var Uo=class{constructor(...e){this.providers=e;}async get(...e){for(let t of this.providers){let n=await t.get(...e)??null;if(n!==null)return n}return null}};var Wo=class{constructor(e){this.config=e;}async handle(){let{input:e,output:t,userApi:n}=this.config,r=await n.getInvitations();if(r.length!==0){if(r.length===1){let{id:i,organization:a}=r[0];await e.confirm({message:`${a.name} has invited you to join. Accept?`,default:true})&&await n.acceptInvitation(i);return}r.length>1&&t.inform(`You have ${r.length} pending invitations:`);for(let{id:i,organization:a}of r)await e.confirm({message:`Accept invitation to join ${a.name}?`,default:true})&&await n.acceptInvitation(i);}}};var Vo=class{constructor(e){this.authenticator=e.authenticator,this.invitationForm=e.invitationForm;}getToken(){return this.authenticator.getToken()}async login(e){let t=await this.authenticator.login(e);return await this.invitationForm.handle({}),t}logout(){return this.authenticator.logout()}};var qo=class o{static{this.EMPTY_SETTINGS={projectPaths:[]};}constructor({validator:e,cache:t,cacheKey:n}){this.cache=t,this.cacheKey=n,this.validator=e;}async get(){let e=await this.cache.get(this.cacheKey,()=>Promise.resolve(""));if(e==="")return o.EMPTY_SETTINGS;let t;try{t=JSON.parse(e);}catch{return o.EMPTY_SETTINGS}let n=await this.validator.validate(t);return n.valid?n.data:o.EMPTY_SETTINGS}async save(e){await this.cache.set(this.cacheKey,JSON.stringify(e));}};var Ho=class{constructor({fileSystem:e,configurationProvider:t}){this.fileSystem=e,this.configurationProvider=t;}async get(){return this.normalizeSettings(await this.configurationProvider.get())}async save(e){return this.configurationProvider.save(await this.normalizeSettings(e))}async normalizeSettings(e){return {...e,projectPaths:(await Promise.all([...new Set(e.projectPaths)].map(async t=>await this.fileSystem.exists(t)?[t]:[]))).flat()}}};var Ko=class{constructor(e){this.config=e;}async execute(e){let{configurationManager:t,api:n,fileSystem:r,io:i}=this.config,a=await t.load(),s=e.environment??await i.input.select({message:"Which environment?",options:Pe.all().map(D=>({label:Pe.getLabel(D),value:D}))}),p=s==="PRODUCTION"?a.applications.production:a.applications.development;if(p===void 0)throw new d(`No ${Pe.getLabel(s).toLowerCase()} application found in the project configuration.`,{reason:"invalid_input"});let c=i.output.notify("Loading information"),l=e.name??`${(await n.user.getUser()).username} (CLI)`,u=await n.workspace.getFeatures({organizationSlug:a.organization,workspaceSlug:a.workspace});if(c.stop(),e.permissions?.includes("DATA_EXPORT")===true&&u?.features.dataExport!==true)throw new d("The workspace does not have the data export feature enabled.",{reason:"invalid_input"});let g=e.name??await Ue.prompt({input:i.input,label:"API key name",default:l}),y=e.permissions??await i.input.selectMultiple({message:"Select permissions",min:1,options:De.all().map(D=>({label:De.getLabel(D),value:D,disabled:D==="DATA_EXPORT"&&u?.features.dataExport!==true}))}),C=await n.application.createApiKey({organizationSlug:a.organization,workspaceSlug:a.workspace,applicationSlug:p,name:g,permissions:y});if(e.copy===true||await i.input.confirm({message:"Copy to clipboard?",default:false})){await Od.write(C.secret),i.output.confirm("API key copied to clipboard");return}let v=`api-key-${C.id}.txt`;await r.writeTextFile(v,C.secret),i.output.confirm(`API key saved to \`${v}\``);}};var nl=Pt(nn());var Go=class{constructor({apiKey:e,clock:t,tokenDuration:n}){this.apiKey=e,this.clock=t,this.tokenDuration=n;}getToken(){return Promise.resolve(this.token?.toString()??null)}async login(){return this.token=await this.issueToken(),this.token.toString()}logout(){return this.token=void 0,Promise.resolve()}async issueToken(){let e=nl.Instant.now(this.clock).getSeconds();return Token.of({kid:await this.apiKey.getIdentifierHash(),alg:"ES256",typ:"JWT"},{iat:e,nbf:e,exp:e+this.tokenDuration,iss:"cli.croct.com",aud:"app.croct.com",scope:["ADMIN"]}).signedWith(this.apiKey)}};var Zo=class{constructor(e){this.currentDirectory=e;}get(){return this.currentDirectory}setCurrentDirectory(e){this.currentDirectory=e;}toString(){return this.get()}};var Jo=class{constructor(e){this.process=e;}get(){return this.process.getCurrentDirectory()}setCurrentDirectory(e){this.process.changeDirectory(e);}toString(){return this.get()}};var Qo=class{constructor({authenticator:e,cacheKey:t,cacheProvider:n}){this.inFlightCache=new Map;this.authenticator=e,this.cacheKey=t,this.tokenCache=n;}getToken(){return this.tokenCache.get(this.cacheKey,()=>this.authenticator.getToken())}login(e){for(let[n,r]of this.inFlightCache.entries())if(deepEqual(e,n))return r;let t=this.issueToken(e).finally(()=>{this.inFlightCache.delete(e);});return this.inFlightCache.set(e,t),t}async issueToken(e){let t=await this.authenticator.login(e);return await this.tokenCache.set(this.cacheKey,t),t}async logout(){await this.authenticator.logout(),await this.tokenCache.delete(this.cacheKey);}};var rl=Pt(nn());var Bo=class{constructor(e){this.revalidating=new Map;this.clock=e.clock,this.clockSkewTolerance=e.clockSkewTolerance,this.cacheProvider=e.cacheProvider,this.tokenFreshPeriod=e.tokenFreshPeriod,this.tokenIssuer=e.tokenIssuer;}async get(e,t){let n=await this.cacheProvider.get(e,async()=>await t(e)??"");if(n==="")return null;let r=this.parseToken(n);if(r!==null){let i=this.clockSkewTolerance,a=this.clock.getInstant().getSeconds();if(!r.isValidNow(a-i)&&!r.isValidNow(a+i))return null;this.revalidateToken(e,r).catch(()=>{});}return n}set(e,t){return this.cacheProvider.set(e,t)}delete(e){return this.cacheProvider.delete(e)}async revalidateToken(e,t){let n=this.clock.getInstant();if(this.revalidating.has(e))return;let r=t.getIssueTime(),i=rl.Instant.ofEpochSecond(r+this.tokenFreshPeriod);n.isAfter(i)&&await this.renewToken(e,t);}async renewToken(e,t){let n=this.tokenIssuer(t);this.revalidating.set(e,true);try{await this.cacheProvider.set(e,await n);}finally{this.revalidating.delete(e);}}parseToken(e){let t;try{t=Token.parse(e);}catch{return null}return t}};var Yo=class{constructor(e){this.api=e.api,this.pollingInterval=e.pollingInterval;}async wait(e){let t=await this.api.closeSession(e);for(;t.status==="pending";)await this.delay(),t=await this.api.closeSession(e);switch(t.status){case "access-granted":return t.accessToken;case "recovery-granted":return t.recoveryToken}}delay(){return new Promise(e=>{setTimeout(e,this.pollingInterval);})}};var Xo=class o{constructor(e){this.boxenStyle=e??{titleAlignment:"center",borderStyle:"round",padding:{top:1,bottom:1,right:2,left:2}};}formatCallout(e){return il(ne(e.message),{...this.boxenStyle,title:ne(e.title,{basic:true}),textAlignment:e.alignment??"left",borderColor:rn[e.semantics]})}formatError(e){return il(o.formatErrorBody(e),{...this.boxenStyle,title:o.formatErrorTitle(e),borderColor:"red"})}static formatErrorTitle(e){return e instanceof d?{access_denied:"Access denied",invalid_configuration:"Invalid configuration",invalid_input:"Invalid input",not_found:"Not found",not_supported:"Not supported",precondition:"Precondition failed",unexpected_result:"Unexpected result",other:"Error"}[e.reason]:"Unexpected error"}static formatErrorBody(e){let t=ne(d.formatMessage(e));if(e instanceof d){t+=o.formatErrorDetails(e);let{cause:n}=e.help;n!==void 0&&!o.isCauseReported(e.message,n)&&(t+=`
|
|
1825
|
+
`}getDesktopEntryPath(e){return this.fileSystem.joinPaths(this.getApplicationPath(),`${e}.desktop`)}getApplicationPath(){return this.fileSystem.joinPaths(this.homeDirectory,".local","share","applications")}};var Lo=class{constructor(e){this.config=e;}async execute({url:e}){if(!URL.canParse(e))throw new d("The URL is not valid.",{reason:"invalid_input"});let t=new URL(e);if(!this.isValidUrl(t))throw new d("The URL is not supported.",{reason:"invalid_input"});let{input:n,output:r}=this.config.io;if(n===void 0)throw new d("Deep links requires explicit user interaction.",{reason:"precondition",details:["Retry in interactive mode."]});let i=this.parseArguments(t);r.announce({semantics:"neutral",title:"\u{1F517} Croct link",message:"You just opened a link to a `Croct CLI` command.",alignment:"center"});let a=i.join(" ");r.inform(`The command is \`${a}\``),await n.confirm({message:"Continue?",default:true})&&(await this.selectDirectory(n),await this.config.program(i));}async selectDirectory(e){let{workingDirectory:t,configurationProvider:n,fileSystem:r,io:{output:i}}=this.config,a=t.get(),{projectPaths:s}=await n.get(),p="";if(s.length>0){let c=r.getDirectoryName(s[0]);p=await e.select({message:"Where should this command run?",options:[{label:`${a} (current)`,value:""},{label:c,value:c},...s.map(l=>({value:l,label:l}))]});}else i.inform(`You are currently in \`${a}\``),await e.confirm({message:"Run the command from the current directory?",default:true})||await e.prompt({message:"Where do you want to run the command from?",default:a,validate:async c=>await r.isDirectory(c)?true:"Enter a valid directory path."});p!==""&&t.setCurrentDirectory(p);}parseArguments(e){let t=[];for(let r of (e.hostname+e.pathname).split("/"))r!==""&&t.push(r);let n=[];for(let[r,i]of e.searchParams){if(r==="arg"){n.push(i);continue}if(i===""){t.push(`-${r.length===1?"":"-"}${r}`);continue}t.push(`--${r}`),t.push(i);}return t.push(...n),t}isValidUrl(e){return e.protocol===`${this.config.protocol}:`&&e.username===""&&e.password===""&&e.port===""&&e.hash===""}};var Rd=z$1.strictObject({version:z$1.string().optional(),projectPaths:z$1.array(z$1.string().min(1)),isDeepLinkingEnabled:z$1.boolean().optional(),lastUpdateCheck:z$1.number().optional()}),zo=class extends ee{constructor(){super(Rd);}};var _o=class{constructor({manager:e,workingDirectory:t,configurationProvider:n}){this.manager=e,this.workingDirectory=t,this.configurationProvider=n;}isInitialized(){return this.manager.isInitialized()}async load(){let e=await this.manager.load();return await this.updateIndex(),e}update(e){return Promise.all([this.manager.update(e),this.updateIndex()]).then(([t])=>t)}async updateIndex(){let e=await this.configurationProvider.get();await this.configurationProvider.save({...e,projectPaths:[this.workingDirectory.get(),...e.projectPaths]});}};var Fo=class{constructor(e){this.fileSystem=e.fileSystem,this.executablePaths=e.executablePaths,this.executableExtensions=e.executableExtensions??[],this.executableCache=e.cache??new NoopCache;}locate(e){return this.executableCache.get(e,t=>this.findPath(t))}async findPath(e){for(let t of this.executablePaths)for(let n of [...this.executableExtensions,""]){let r=this.fileSystem.joinPaths(t,e+n.toLowerCase());if(r!==null&&await this.fileSystem.exists(r))return r}return null}};var jo=class{constructor(e){this.projectDirectory=e.projectDirectory,this.fileSystem=e.fileSystem,this.packageManager=e.packageManager;}async test(){return (await this.getPreferredPackageManager())?.includes(this.packageManager)===true}async getPreferredPackageManager(){let e=this.fileSystem.joinPaths(this.projectDirectory.get(),"package.json");if(!await this.fileSystem.exists(e))return null;let t;try{t=JSON.parse(await this.fileSystem.readTextFile(e));}catch{return null}return typeof t=="object"&&t!==null&&"packageManager"in t&&typeof t.packageManager=="string"?t.packageManager:null}};var Fn=class{constructor(e){this.cliVersion=e.cliVersion,this.autoUpdater=e.autoUpdater,this.deepLinkInstaller=e.deepLinkInstaller,this.configurationProvider=e.configurationProvider;}async execute(e){let t=await this.configurationProvider.get(),n=t.version;n!==this.cliVersion&&await this.configurationProvider.save({...t,version:this.cliVersion}),e.skipUpdateCheck!==true&&await this.autoUpdater.checkForUpdates(),e.skipDeepLinkCheck!==true&&await this.deepLinkInstaller(n!==this.cliVersion);}};var Uo=class{constructor(e){this.process=e.process,this.variable=e.variable,this.value=e.value;}test(){let e=this.process.getEnvValue(this.variable);return e===null?false:this.value?.test(e)===true}};var Wo=class{constructor(...e){this.providers=e;}async get(...e){for(let t of this.providers){let n=await t.get(...e)??null;if(n!==null)return n}return null}};var Vo=class{constructor(e){this.config=e;}async handle(){let{input:e,output:t,userApi:n}=this.config,r=await n.getInvitations();if(r.length!==0){if(r.length===1){let{id:i,organization:a}=r[0];await e.confirm({message:`${a.name} has invited you to join. Accept?`,default:true})&&await n.acceptInvitation(i);return}r.length>1&&t.inform(`You have ${r.length} pending invitations:`);for(let{id:i,organization:a}of r)await e.confirm({message:`Accept invitation to join ${a.name}?`,default:true})&&await n.acceptInvitation(i);}}};var qo=class{constructor(e){this.authenticator=e.authenticator,this.invitationForm=e.invitationForm;}getToken(){return this.authenticator.getToken()}async login(e){let t=await this.authenticator.login(e);return await this.invitationForm.handle({}),t}logout(){return this.authenticator.logout()}};var Ho=class o{static{this.EMPTY_SETTINGS={projectPaths:[]};}constructor({validator:e,cache:t,cacheKey:n}){this.cache=t,this.cacheKey=n,this.validator=e;}async get(){let e=await this.cache.get(this.cacheKey,()=>Promise.resolve(""));if(e==="")return o.EMPTY_SETTINGS;let t;try{t=JSON.parse(e);}catch{return o.EMPTY_SETTINGS}let n=await this.validator.validate(t);return n.valid?n.data:o.EMPTY_SETTINGS}async save(e){await this.cache.set(this.cacheKey,JSON.stringify(e));}};var Ko=class{constructor({fileSystem:e,configurationProvider:t}){this.fileSystem=e,this.configurationProvider=t;}async get(){return this.normalizeSettings(await this.configurationProvider.get())}async save(e){return this.configurationProvider.save(await this.normalizeSettings(e))}async normalizeSettings(e){return {...e,projectPaths:(await Promise.all([...new Set(e.projectPaths)].map(async t=>await this.fileSystem.exists(t)?[t]:[]))).flat()}}};var Go=class{constructor(e){this.config=e;}async execute(e){let{configurationManager:t,api:n,fileSystem:r,io:i}=this.config,a=await t.load(),s=e.environment??await i.input.select({message:"Which environment?",options:Ce.all().map(D=>({label:Ce.getLabel(D),value:D}))}),p=s==="PRODUCTION"?a.applications.production:a.applications.development;if(p===void 0)throw new d(`No ${Ce.getLabel(s).toLowerCase()} application found in the project configuration.`,{reason:"invalid_input"});let c=i.output.notify("Loading information"),l=e.name??`${(await n.user.getUser()).username} (CLI)`,u=await n.workspace.getFeatures({organizationSlug:a.organization,workspaceSlug:a.workspace});if(c.stop(),e.permissions?.includes("DATA_EXPORT")===true&&u?.features.dataExport!==true)throw new d("The workspace does not have the data export feature enabled.",{reason:"invalid_input"});let g=e.name??await Ue.prompt({input:i.input,label:"API key name",default:l}),y=e.permissions??await i.input.selectMultiple({message:"Select permissions",min:1,options:fe.all().map(D=>({label:fe.getLabel(D),value:D,disabled:D==="DATA_EXPORT"&&u?.features.dataExport!==true}))}),C=await n.application.createApiKey({organizationSlug:a.organization,workspaceSlug:a.workspace,applicationSlug:p,name:g,permissions:y});if(e.copy===true||await i.input.confirm({message:"Copy to clipboard?",default:false})){await Dd.write(C.secret),i.output.confirm("API key copied to clipboard");return}let v=`api-key-${C.id}.txt`;await r.writeTextFile(v,C.secret),i.output.confirm(`API key saved to \`${v}\``);}};var ol=Pt(rn());var Zo=class{constructor({apiKey:e,clock:t,tokenDuration:n}){this.apiKey=e,this.clock=t,this.tokenDuration=n;}getToken(){return Promise.resolve(this.token?.toString()??null)}async login(){return this.token=await this.issueToken(),this.token.toString()}logout(){return this.token=void 0,Promise.resolve()}async issueToken(){let e=ol.Instant.now(this.clock).getSeconds();return Token.of({kid:await this.apiKey.getIdentifierHash(),alg:"ES256",typ:"JWT"},{iat:e,nbf:e,exp:e+this.tokenDuration,iss:"cli.croct.com",aud:"app.croct.com",scope:["ADMIN"]}).signedWith(this.apiKey)}};var Jo=class{constructor(e){this.currentDirectory=e;}get(){return this.currentDirectory}setCurrentDirectory(e){this.currentDirectory=e;}toString(){return this.get()}};var Qo=class{constructor(e){this.process=e;}get(){return this.process.getCurrentDirectory()}setCurrentDirectory(e){this.process.changeDirectory(e);}toString(){return this.get()}};var Bo=class{constructor({authenticator:e,cacheKey:t,cacheProvider:n}){this.inFlightCache=new Map;this.authenticator=e,this.cacheKey=t,this.tokenCache=n;}getToken(){return this.tokenCache.get(this.cacheKey,()=>this.authenticator.getToken())}login(e){for(let[n,r]of this.inFlightCache.entries())if(deepEqual(e,n))return r;let t=this.issueToken(e).finally(()=>{this.inFlightCache.delete(e);});return this.inFlightCache.set(e,t),t}async issueToken(e){let t=await this.authenticator.login(e);return await this.tokenCache.set(this.cacheKey,t),t}async logout(){await this.authenticator.logout(),await this.tokenCache.delete(this.cacheKey);}};var al=Pt(rn());var Yo=class{constructor(e){this.revalidating=new Map;this.clock=e.clock,this.clockSkewTolerance=e.clockSkewTolerance,this.cacheProvider=e.cacheProvider,this.tokenFreshPeriod=e.tokenFreshPeriod,this.tokenIssuer=e.tokenIssuer;}async get(e,t){let n=await this.cacheProvider.get(e,async()=>await t(e)??"");if(n==="")return null;let r=this.parseToken(n);if(r!==null){let i=this.clockSkewTolerance,a=this.clock.getInstant().getSeconds();if(!r.isValidNow(a-i)&&!r.isValidNow(a+i))return null;this.revalidateToken(e,r).catch(()=>{});}return n}set(e,t){return this.cacheProvider.set(e,t)}delete(e){return this.cacheProvider.delete(e)}async revalidateToken(e,t){let n=this.clock.getInstant();if(this.revalidating.has(e))return;let r=t.getIssueTime(),i=al.Instant.ofEpochSecond(r+this.tokenFreshPeriod);n.isAfter(i)&&await this.renewToken(e,t);}async renewToken(e,t){let n=this.tokenIssuer(t);this.revalidating.set(e,true);try{await this.cacheProvider.set(e,await n);}finally{this.revalidating.delete(e);}}parseToken(e){let t;try{t=Token.parse(e);}catch{return null}return t}};var Xo=class{constructor(e){this.api=e.api,this.pollingInterval=e.pollingInterval;}async wait(e){let t=await this.api.closeSession(e);for(;t.status==="pending";)await this.delay(),t=await this.api.closeSession(e);switch(t.status){case "access-granted":return t.accessToken;case "recovery-granted":return t.recoveryToken}}delay(){return new Promise(e=>{setTimeout(e,this.pollingInterval);})}};var ea=class o{constructor(e){this.boxenStyle=e??{titleAlignment:"center",borderStyle:"round",padding:{top:1,bottom:1,right:2,left:2}};}formatCallout(e){return sl(re(e.message),{...this.boxenStyle,title:re(e.title,{basic:true}),textAlignment:e.alignment??"left",borderColor:on[e.semantics]})}formatError(e){return sl(o.formatErrorBody(e),{...this.boxenStyle,title:o.formatErrorTitle(e),borderColor:"red"})}static formatErrorTitle(e){return e instanceof d?{access_denied:"Access denied",invalid_configuration:"Invalid configuration",invalid_input:"Invalid input",not_found:"Not found",not_supported:"Not supported",precondition:"Precondition failed",unexpected_result:"Unexpected result",other:"Error"}[e.reason]:"Unexpected error"}static formatErrorBody(e){let t=re(d.formatMessage(e));if(e instanceof d){t+=o.formatErrorDetails(e);let{cause:n}=e.help;n!==void 0&&!o.isCauseReported(e.message,n)&&(t+=`
|
|
1882
1826
|
|
|
1883
1827
|
\u{1F6A8} ${ct.bold("Cause")}
|
|
1884
|
-
`,t+=`${
|
|
1828
|
+
`,t+=`${re(d.formatMessage(e.help.cause))}`),t+=o.formatErrorSuggestions(e),t+=o.formatErrorUsefulLinks(e);}return (!(e instanceof d)||e.reason==="other"&&e.help.cause instanceof Error)&&(t+=o.formatStackTrace(e)),t}static isCauseReported(e,t){return e.toLowerCase().includes(d.formatMessage(t).toLowerCase())}static formatErrorDetails(e){let t="",{details:n}=e.help;return n!==void 0&&(t+=`
|
|
1885
1829
|
|
|
1886
1830
|
\u{1F50D} ${ct.bold("Details")}
|
|
1887
|
-
`,t+=n.map(r=>` \u2022 ${
|
|
1831
|
+
`,t+=n.map(r=>` \u2022 ${re(r)}`).join(`
|
|
1888
1832
|
`)),t}static formatStackTrace(e){if(!(e instanceof Error)||e.stack===void 0)return "";let t=e.stack.split(`
|
|
1889
1833
|
`).map(n=>` \u203A ${n.trim().replace(/^at /,"")}`).slice(1);return `
|
|
1890
1834
|
|
|
@@ -1893,18 +1837,18 @@ ${t.join(`
|
|
|
1893
1837
|
`)}`}static formatErrorSuggestions(e){let{suggestions:t}=e.help,n="";return t!==void 0&&t.length>0&&(n+=`
|
|
1894
1838
|
|
|
1895
1839
|
\u{1F4A1} ${ct.bold("Suggestions")}
|
|
1896
|
-
`,n+=t.map(r=>` \u2022 ${
|
|
1840
|
+
`,n+=t.map(r=>` \u2022 ${re(r)}`).join(`
|
|
1897
1841
|
`)),n}static formatErrorUsefulLinks(e){let t=[],n="";switch(e.reason){case "invalid_input":case "precondition":t.push({label:"Documentation",url:"https://docs.croct.io/sdk/cli"});break;case "invalid_configuration":break;default:t.push({label:"Open an issue",url:"https://github.com/croct-tech/croct-cli/issues/new"});break}return e.help.links!==void 0&&t.push(...e.help.links),t.length>0&&(n+=`
|
|
1898
1842
|
|
|
1899
1843
|
\u{1F517} ${ct.bold("Useful links")}
|
|
1900
|
-
`,n+=t.map(({label:r,url:i})=>` \u2022 ${
|
|
1901
|
-
`)),n}};var ea=class{constructor(){this.listeners={};}on(e,t){this.listeners[e]===void 0&&(this.listeners[e]=new Set),this.listeners[e].add(t);}off(e,t){this.listeners[e]!==void 0&&this.listeners[e].delete(t);}async emit(e,...t){this.listeners[e]!==void 0&&await Promise.all(Array.from(this.listeners[e]).map(n=>n(...t)));}};var ta=class{constructor(){this.eventDispatcher=new ea;ze.on("SIGTERM",()=>this.exit()),ze.on("SIGINT",()=>this.exit()),ze.on("SIGHUP",()=>this.exit());}getCurrentDirectory(){return ze.cwd()}getEnvValue(e){return ze.env[e]??null}getEnvList(e){return this.getEnvValue(e)?.split(delimiter)??null}getPlatform(){return ze.platform}getStandardError(){return ze.stderr}getStandardInput(){return ze.stdin}getStandardOutput(){return ze.stdout}on(e,t){this.eventDispatcher.on(e,t);}off(e,t){this.eventDispatcher.off(e,t);}async exit(e){return await this.eventDispatcher.emit("exit").catch(()=>{}),ze.exit(e)}changeDirectory(e){ze.chdir(e);}};var na=class{constructor({callback:e}){this.callback=e;}async execute(e,t){try{return await this.callback(e,t)}catch(n){if(!(n instanceof S))throw S.fromCause(n)}}};var Ld=z$1.strictObject({}),ra=class extends I{constructor(){super(Ld);}};var ia=class o{static{this.REPOSITORY_PATTERNS=[/git\+(https:\/\/.+)\.git$/];}constructor(e){this.metadataProvider=e;}async get(e){let t=this.getMetadataUrl(e);if(t===null)throw new z("Unsupported NPM URL.",{reason:"not_supported",url:e});let{value:n}=await this.metadataProvider.get(t),r=o.getRepositoryUrl(n.repository);return r===null?{url:e,value:[]}:{url:r,value:[{pattern:".*",destination:r}]}}static getRepositoryUrl(e){for(let t of o.REPOSITORY_PATTERNS){let n=t.exec(e.url);if(n!==null)return new URL(`${n[1]}/`)}return null}getMetadataUrl(e){if(e.protocol!=="npm:")return null;let t=decodeURIComponent(e.hostname+e.pathname);return t.startsWith("/")&&(t=t.slice(1)),new URL(`https://registry.npmjs.org/${t}/latest`)}};var oa=class o{constructor({provider:e,reader:t}){this.provider=e,this.reader=t;}static text(e){return new o({provider:e,reader:t=>t.text()})}static json(e){return new o({provider:e,reader:t=>t.json()})}static blob(e){return new o({provider:e,reader:t=>t.blob()})}async get(e){let t=await this.provider.get(e),n;try{n=await this.reader(new Response(t.value.body));}catch(r){throw new z("Failed to read response body.",{reason:"unexpected_result",url:e,cause:r})}return {url:t.url,value:n}}};var zd=z$1.object({name:z$1.string(),repository:z$1.object({type:z$1.string(),url:z$1.string()})}),aa=class extends ee{constructor(){super(zd);}};var pa=class{constructor({provider:e,logger:t,label:n}){this.provider=e,this.logger=t,this.label=n;}get(e){return this.logger.nest({message:`\`${this.label??this.provider.constructor.name}\``,level:LogLevel.DEBUG},()=>this.trace(e))}async trace(e){this.logger.log({message:`URL: ${e}`,level:LogLevel.DEBUG});try{let t=await this.provider.get(e);return this.logger.log({message:"No errors",level:LogLevel.DEBUG}),t}catch(t){throw this.logger.log({message:`Error: ${d.formatMessage(t)}`,level:LogLevel.DEBUG}),t}}};var ca=class{constructor(e){this.storage=new AsyncLocalStorage;this.logger=e;}nest(e,t){let n=this.storage.getStore(),r={level:n!==void 0?n.level+1:0,logs:[]};return this.storage.run(r,async()=>{let i=await this.logNested(r,e,t);return n!==void 0?n.logs.push(...r.logs):(r.logs.forEach(a=>this.logger.log(a)),r.logs=[]),i})}async logNested(e,t,n){this.buffer(e,{...t,message:`\u250C\u2500 ${t.message}`});try{return await n()}finally{this.buffer(e,{...t,message:"\u2514\u2500"});}}log(e){let t=this.storage.getStore();if(t!==void 0){this.buffer(t,{...e,message:`\u2502 ${e.message}`});return}this.logger.log(e);}buffer(e,t){e.logs.push({...t,message:`${e.level>0?`${"\u2502 ".repeat(e.level)}`:""}${t.message}`});}};var la=class{constructor(e){this.output=e;}log(e){switch(e.level){case "debug":this.output.debug(e.message);break;case "info":this.output.inform(e.message);break;case "warning":this.output.warn(e.message);break;case "error":this.output.alert(e.message);}}};var ua=class o{static{this.PREFIX="?/";}constructor(e){this.rootPath=e.rootPath,this.importResolver=e.importResolver,this.exportMatcher=e.exportMatcher,this.importCodemod=e.importCodemod,this.fileSystem=e.fileSystem,this.scanFilter=e.filter;}apply(e){return this.importCodemod.apply(e,{transformer:t=>{if(!t.source.startsWith(o.PREFIX))return;let n=t.source.slice(o.PREFIX.length);return this.resolvePath(t,n,e)}})}async resolvePath(e,t,n){let r=this.rootPath.get(),i=new Minimatch(t.startsWith("./")?`${this.fileSystem.getRelativePath(r,this.fileSystem.getDirectoryName(n)).replace(/[\\/]/g,"/")}/${t.slice(2)}`:t);for await(let a of this.fileSystem.list(r,this.scanFilter))if(a.type==="file"&&i.match(a.name)&&await this.exportMatcher.test(await new Response(a.content).text(),e))return this.importResolver.getImportPath(this.fileSystem.joinPaths(r,a.name),n);throw new nt(`Unable to resolve import \`${t}\` from \`${n}\`.`,{reason:"not_found"})}};var Jt=class{constructor({codemods:e}){this.codemods=e;}async apply(e,t){let n={modified:false,result:e};for(let[r,i]of Object.entries(this.codemods))minimatch(e,r)&&(n=await i.apply(e,t));return n}};function ol(o){let e=typeof o=="string"?je(o,["jsx","typescript"]):o,t=[];return traverse(e,{ExportDeclaration:n=>{let{node:r}=n;if(f.isExportNamedDeclaration(r))if(r.specifiers.length>0)for(let i of r.specifiers)f.isExportSpecifier(i)?(!f.isIdentifier(i.exported)||i.exported.name!=="default")&&t.push(f.isIdentifier(i.exported)?i.exported.name:i.exported.value):f.isExportNamespaceSpecifier(i)&&f.isIdentifier(i.exported)&&t.push(i.exported.name);else if(f.isVariableDeclaration(r.declaration))for(let i of r.declaration.declarations)f.isVariableDeclarator(i)&&f.isIdentifier(i.id)&&t.push(i.id.name);else typeof r.declaration=="object"&&r.declaration!==null&&"id"in r.declaration&&f.isIdentifier(r.declaration.id)&&t.push(r.declaration.id.name);return n.skip()}}),t}async function al(o,e){let t=[];return traverse(o,{ImportDeclaration:n=>{let{node:r}=n,i=Promise.resolve(e(Vd(r)));return i!==void 0&&t.push(i.then(a=>typeof a=="string"&&r.source.value!==a?(r.source.value=a,true):false)),n.skip()}}),(await Promise.all(t)).some(n=>n)}function Vd(o){let e={names:[],source:o.source.value};for(let t of o.specifiers)f.isImportSpecifier(t)&&e.names.push(f.isIdentifier(t.imported)?t.imported.name:t.imported.value);return e}var da=class{async apply(e,t){let n=await al(e,t.transformer);return {result:e,modified:n}}};var Qt=class{constructor(...e){this.codemods=e;}async apply(e,t){let n=e,r=false;for(let i of this.codemods){let a=await i.apply(n,t);n=a.result,r=r||a.modified;}return {modified:r,result:n}}};var ga=class o{constructor(e,t){this.client=e,this.cache=t;}getHierarchy(e){return this.cache.get(o.getHierarchyKey(e),async()=>{let t=await this.resolveHierarchy(e);return await this.saveCache(e,t),t})}async resolveHierarchy(e){let{data:{organization:t}}=await this.client.execute(Fp,e),n=t?.id,r=t?.workspace?.id,i=t?.workspace?.application?.id;return o.checkMissing("organization",e.organizationSlug,n),"workspaceSlug"in e?(o.checkMissing("workspace",e.workspaceSlug,r),"applicationSlug"in e?(o.checkMissing("application",e.applicationSlug,i),{organizationId:n,workspaceId:r,applicationId:i}):{organizationId:n,workspaceId:r}):{organizationId:n}}async saveCache(e,t){let n=[this.setCache({organizationSlug:e.organizationSlug},{organizationId:t.organizationId})];"workspaceId"in t&&"workspaceSlug"in e&&n.push(this.setCache({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug},{organizationId:t.organizationId,workspaceId:t.workspaceId})),"applicationId"in t&&"applicationSlug"in e&&n.push(this.setCache({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,applicationSlug:e.applicationSlug},{organizationId:t.organizationId,workspaceId:t.workspaceId,applicationId:t.applicationId})),await Promise.all(n);}setCache(e,t){return this.cache.set(o.getHierarchyKey(e),t)}static getHierarchyKey(e){let t=[`organization:${e.organizationSlug}`];return "workspaceSlug"in e&&t.push(`workspace:${e.workspaceSlug}`),"applicationSlug"in e&&t.push(`application${e.applicationSlug}`),t.join("/")}static checkMissing(e,t,n){if(n===void 0)throw new oe(`No ${e} found with slug "${t}".`,[],{reason:"not_found"})}};var fa=class{constructor({macOsRegistry:e,firefoxRegistry:t,output:n}){this.macOsRegistry=e,this.firefoxRegistry=t,this.output=n;}isRegistered(e){return this.macOsRegistry.isRegistered(e)}async register(e){this.isFirefoxInstalled===void 0&&(this.isFirefoxInstalled=await this.firefoxRegistry.isRegistered(e.protocol)),await this.macOsRegistry.register(e);try{await this.firefoxRegistry.register(e);}catch(t){if(!(t instanceof q)||t.reason!=="not_found")throw t;return}this.isFirefoxInstalled||this.output.inform("**Firefox detected:** launch or restart it to finish the registration.");}async unregister(e){this.isFirefoxInstalled=await this.firefoxRegistry.isRegistered(e),await this.macOsRegistry.unregister(e),await this.firefoxRegistry.unregister(e);}};var ya=class o{static{this.PREFERENCES=['user_pref("network.protocol-handler.expose.%protocol%", false);','user_pref("network.protocol-handler.external.%protocol%", true);'];}constructor({fileSystem:e,appDirectory:t,...n}){this.fileSystem=e,this.profileDirectory=t,this.configuration=n;}static fromSystem(e,t){switch(e.getPlatform()){case "win32":{let n=e.getEnvValue("APPDATA")??e.getEnvValue("USERPROFILE");if(n===null)throw new q("Cannot determine the user profile directory.",{reason:"precondition"});return o.windows({...t,appDataDirectory:n})}case "darwin":{let n=e.getEnvValue("HOME");if(n===null)throw new q("Cannot determine the user home directory.",{reason:"precondition"});return o.macOs({...t,homeDirectory:n})}case "linux":{let n=e.getEnvValue("HOME");if(n===null)throw new q("Cannot determine the user home directory.",{reason:"precondition"});return o.linux({...t,homeDirectory:n})}default:throw new q(`Platform \`${e.getPlatform()}\` is not supported.`,{reason:"not_supported"})}}static windows(e){return new o({...e,appDirectory:e.fileSystem.joinPaths(e.appDataDirectory,"Mozilla","Firefox")})}static macOs(e){return new o({...e,appDirectory:e.fileSystem.joinPaths(e.homeDirectory,"Library","Application Support","Firefox")})}static linux(e){return new o({...e,appDirectory:e.fileSystem.joinPaths(e.homeDirectory,"snap","firefox","common",".mozilla","firefox")})}async isRegistered(e){let t=await this.getProfilePath();if(t===null)return false;let n=this.getUserPreferencesFilePath(t),r=await this.fileSystem.readTextFile(n).catch(()=>"");for(let i of this.getPreferences(e))if(!r.includes(i))return false;return true}async register(e){if(await this.isRegistered(e.protocol))return;let t=await this.getProfilePath();if(t===null)throw new q("Cannot find the default profile file.",{reason:"not_found"});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}
|
|
1844
|
+
`,n+=t.map(({label:r,url:i})=>` \u2022 ${Jl(r,i,{fallback:()=>`${r}: ${i}`})}`).join(`
|
|
1845
|
+
`)),n}};var ta=class{constructor(){this.listeners={};}on(e,t){this.listeners[e]===void 0&&(this.listeners[e]=new Set),this.listeners[e].add(t);}off(e,t){this.listeners[e]!==void 0&&this.listeners[e].delete(t);}async emit(e,...t){this.listeners[e]!==void 0&&await Promise.all(Array.from(this.listeners[e]).map(n=>n(...t)));}};var na=class{constructor(){this.eventDispatcher=new ta;ze.on("SIGTERM",()=>this.exit()),ze.on("SIGINT",()=>this.exit()),ze.on("SIGHUP",()=>this.exit());}getCurrentDirectory(){return ze.cwd()}getEnvValue(e){return ze.env[e]??null}getEnvList(e){return this.getEnvValue(e)?.split(delimiter)??null}getPlatform(){return ze.platform}getStandardError(){return ze.stderr}getStandardInput(){return ze.stdin}getStandardOutput(){return ze.stdout}on(e,t){this.eventDispatcher.on(e,t);}off(e,t){this.eventDispatcher.off(e,t);}async exit(e){return await this.eventDispatcher.emit("exit").catch(()=>{}),ze.exit(e)}changeDirectory(e){ze.chdir(e);}};var ra=class{constructor({callback:e}){this.callback=e;}async execute(e,t){try{return await this.callback(e,t)}catch(n){if(!(n instanceof h))throw h.fromCause(n)}}};var Fd=z$1.strictObject({}),ia=class extends I{constructor(){super(Fd);}};var oa=class o{static{this.REPOSITORY_PATTERNS=[/git\+(https:\/\/.+)\.git$/];}constructor(e){this.metadataProvider=e;}async get(e){let t=this.getMetadataUrl(e);if(t===null)throw new z("Unsupported NPM URL.",{reason:"not_supported",url:e});let{value:n}=await this.metadataProvider.get(t),r=o.getRepositoryUrl(n.repository);return r===null?{url:e,value:[]}:{url:r,value:[{pattern:".*",destination:r}]}}static getRepositoryUrl(e){for(let t of o.REPOSITORY_PATTERNS){let n=t.exec(e.url);if(n!==null)return new URL(`${n[1]}/`)}return null}getMetadataUrl(e){if(e.protocol!=="npm:")return null;let t=decodeURIComponent(e.hostname+e.pathname);return t.startsWith("/")&&(t=t.slice(1)),new URL(`https://registry.npmjs.org/${t}/latest`)}};var aa=class o{constructor({provider:e,reader:t}){this.provider=e,this.reader=t;}static text(e){return new o({provider:e,reader:t=>t.text()})}static json(e){return new o({provider:e,reader:t=>t.json()})}static blob(e){return new o({provider:e,reader:t=>t.blob()})}async get(e){let t=await this.provider.get(e),n;try{n=await this.reader(new Response(t.value.body));}catch(r){throw new z("Failed to read response body.",{reason:"unexpected_result",url:e,cause:r})}return {url:t.url,value:n}}};var jd=z$1.object({name:z$1.string(),repository:z$1.object({type:z$1.string(),url:z$1.string()})}),sa=class extends ee{constructor(){super(jd);}};var ca=class{constructor({provider:e,logger:t,label:n}){this.provider=e,this.logger=t,this.label=n;}get(e){return this.logger.nest({message:`\`${this.label??this.provider.constructor.name}\``,level:LogLevel.DEBUG},()=>this.trace(e))}async trace(e){this.logger.log({message:`URL: ${e}`,level:LogLevel.DEBUG});try{let t=await this.provider.get(e);return this.logger.log({message:"No errors",level:LogLevel.DEBUG}),t}catch(t){throw this.logger.log({message:`Error: ${d.formatMessage(t)}`,level:LogLevel.DEBUG}),t}}};var la=class{constructor(e){this.storage=new AsyncLocalStorage;this.logger=e;}nest(e,t){let n=this.storage.getStore(),r={level:n!==void 0?n.level+1:0,logs:[]};return this.storage.run(r,async()=>{let i=await this.logNested(r,e,t);return n!==void 0?n.logs.push(...r.logs):(r.logs.forEach(a=>this.logger.log(a)),r.logs=[]),i})}async logNested(e,t,n){this.buffer(e,{...t,message:`\u250C\u2500 ${t.message}`});try{return await n()}finally{this.buffer(e,{...t,message:"\u2514\u2500"});}}log(e){let t=this.storage.getStore();if(t!==void 0){this.buffer(t,{...e,message:`\u2502 ${e.message}`});return}this.logger.log(e);}buffer(e,t){e.logs.push({...t,message:`${e.level>0?`${"\u2502 ".repeat(e.level)}`:""}${t.message}`});}};var ua=class{constructor(e){this.output=e;}log(e){switch(e.level){case "debug":this.output.debug(e.message);break;case "info":this.output.inform(e.message);break;case "warning":this.output.warn(e.message);break;case "error":this.output.alert(e.message);}}};var ma=class o{static{this.PREFIX="?/";}constructor(e){this.rootPath=e.rootPath,this.importResolver=e.importResolver,this.exportMatcher=e.exportMatcher,this.importCodemod=e.importCodemod,this.fileSystem=e.fileSystem,this.scanFilter=e.filter;}apply(e){return this.importCodemod.apply(e,{transformer:t=>{if(!t.source.startsWith(o.PREFIX))return;let n=t.source.slice(o.PREFIX.length);return this.resolvePath(t,n,e)}})}async resolvePath(e,t,n){let r=this.rootPath.get(),i=new Minimatch(t.startsWith("./")?`${this.fileSystem.getRelativePath(r,this.fileSystem.getDirectoryName(n)).replace(/[\\/]/g,"/")}/${t.slice(2)}`:t);for await(let a of this.fileSystem.list(r,this.scanFilter))if(a.type==="file"&&i.match(a.name)&&await this.exportMatcher.test(await new Response(a.content).text(),e))return this.importResolver.getImportPath(this.fileSystem.joinPaths(r,a.name),n);throw new nt(`Unable to resolve import \`${t}\` from \`${n}\`.`,{reason:"not_found"})}};var Jt=class{constructor({codemods:e}){this.codemods=e;}async apply(e,t){let n={modified:false,result:e};for(let[r,i]of Object.entries(this.codemods))minimatch(e,r)&&(n=await i.apply(e,t));return n}};function pl(o){let e=typeof o=="string"?je(o,["jsx","typescript"]):o,t=[];return traverse(e,{ExportDeclaration:n=>{let{node:r}=n;if(f.isExportNamedDeclaration(r))if(r.specifiers.length>0)for(let i of r.specifiers)f.isExportSpecifier(i)?(!f.isIdentifier(i.exported)||i.exported.name!=="default")&&t.push(f.isIdentifier(i.exported)?i.exported.name:i.exported.value):f.isExportNamespaceSpecifier(i)&&f.isIdentifier(i.exported)&&t.push(i.exported.name);else if(f.isVariableDeclaration(r.declaration))for(let i of r.declaration.declarations)f.isVariableDeclarator(i)&&f.isIdentifier(i.id)&&t.push(i.id.name);else typeof r.declaration=="object"&&r.declaration!==null&&"id"in r.declaration&&f.isIdentifier(r.declaration.id)&&t.push(r.declaration.id.name);return n.skip()}}),t}async function cl(o,e){let t=[];return traverse(o,{ImportDeclaration:n=>{let{node:r}=n,i=Promise.resolve(e(Kd(r)));return i!==void 0&&t.push(i.then(a=>typeof a=="string"&&r.source.value!==a?(r.source.value=a,true):false)),n.skip()}}),(await Promise.all(t)).some(n=>n)}function Kd(o){let e={names:[],source:o.source.value};for(let t of o.specifiers)f.isImportSpecifier(t)&&e.names.push(f.isIdentifier(t.imported)?t.imported.name:t.imported.value);return e}var ga=class{async apply(e,t){let n=await cl(e,t.transformer);return {result:e,modified:n}}};var Qt=class{constructor(...e){this.codemods=e;}async apply(e,t){let n=e,r=false;for(let i of this.codemods){let a=await i.apply(n,t);n=a.result,r=r||a.modified;}return {modified:r,result:n}}};var fa=class o{constructor(e,t){this.client=e,this.cache=t;}getHierarchy(e){return this.cache.get(o.getHierarchyKey(e),async()=>{let t=await this.resolveHierarchy(e);return await this.saveCache(e,t),t})}async resolveHierarchy(e){let{data:{organization:t}}=await this.client.execute(Wp,e),n=t?.id,r=t?.workspace?.id,i=t?.workspace?.application?.id;return o.checkMissing("organization",e.organizationSlug,n),"workspaceSlug"in e?(o.checkMissing("workspace",e.workspaceSlug,r),"applicationSlug"in e?(o.checkMissing("application",e.applicationSlug,i),{organizationId:n,workspaceId:r,applicationId:i}):{organizationId:n,workspaceId:r}):{organizationId:n}}async saveCache(e,t){let n=[this.setCache({organizationSlug:e.organizationSlug},{organizationId:t.organizationId})];"workspaceId"in t&&"workspaceSlug"in e&&n.push(this.setCache({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug},{organizationId:t.organizationId,workspaceId:t.workspaceId})),"applicationId"in t&&"applicationSlug"in e&&n.push(this.setCache({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,applicationSlug:e.applicationSlug},{organizationId:t.organizationId,workspaceId:t.workspaceId,applicationId:t.applicationId})),await Promise.all(n);}setCache(e,t){return this.cache.set(o.getHierarchyKey(e),t)}static getHierarchyKey(e){let t=[`organization:${e.organizationSlug}`];return "workspaceSlug"in e&&t.push(`workspace:${e.workspaceSlug}`),"applicationSlug"in e&&t.push(`application${e.applicationSlug}`),t.join("/")}static checkMissing(e,t,n){if(n===void 0)throw new ae(`No ${e} found with slug "${t}".`,[],{reason:"not_found"})}};var ya=class{constructor({macOsRegistry:e,firefoxRegistry:t,output:n}){this.macOsRegistry=e,this.firefoxRegistry=t,this.output=n;}isRegistered(e){return this.macOsRegistry.isRegistered(e)}async register(e){this.isFirefoxInstalled===void 0&&(this.isFirefoxInstalled=await this.firefoxRegistry.isRegistered(e.protocol)),await this.macOsRegistry.register(e);try{await this.firefoxRegistry.register(e);}catch(t){if(!(t instanceof q)||t.reason!=="not_found")throw t;return}this.isFirefoxInstalled||this.output.inform("**Firefox detected:** launch or restart it to finish the registration.");}async unregister(e){this.isFirefoxInstalled=await this.firefoxRegistry.isRegistered(e),await this.macOsRegistry.unregister(e),await this.firefoxRegistry.unregister(e);}};var ha=class o{static{this.PREFERENCES=['user_pref("network.protocol-handler.expose.%protocol%", false);','user_pref("network.protocol-handler.external.%protocol%", true);'];}constructor({fileSystem:e,appDirectory:t,...n}){this.fileSystem=e,this.profileDirectory=t,this.configuration=n;}static fromSystem(e,t){switch(e.getPlatform()){case "win32":{let n=e.getEnvValue("APPDATA")??e.getEnvValue("USERPROFILE");if(n===null)throw new q("Cannot determine the user profile directory.",{reason:"precondition"});return o.windows({...t,appDataDirectory:n})}case "darwin":{let n=e.getEnvValue("HOME");if(n===null)throw new q("Cannot determine the user home directory.",{reason:"precondition"});return o.macOs({...t,homeDirectory:n})}case "linux":{let n=e.getEnvValue("HOME");if(n===null)throw new q("Cannot determine the user home directory.",{reason:"precondition"});return o.linux({...t,homeDirectory:n})}default:throw new q(`Platform \`${e.getPlatform()}\` is not supported.`,{reason:"not_supported"})}}static windows(e){return new o({...e,appDirectory:e.fileSystem.joinPaths(e.appDataDirectory,"Mozilla","Firefox")})}static macOs(e){return new o({...e,appDirectory:e.fileSystem.joinPaths(e.homeDirectory,"Library","Application Support","Firefox")})}static linux(e){return new o({...e,appDirectory:e.fileSystem.joinPaths(e.homeDirectory,"snap","firefox","common",".mozilla","firefox")})}async isRegistered(e){let t=await this.getProfilePath();if(t===null)return false;let n=this.getUserPreferencesFilePath(t),r=await this.fileSystem.readTextFile(n).catch(()=>"");for(let i of this.getPreferences(e))if(!r.includes(i))return false;return true}async register(e){if(await this.isRegistered(e.protocol))return;let t=await this.getProfilePath();if(t===null)throw new q("Cannot find the default profile file.",{reason:"not_found"});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}
|
|
1902
1846
|
${this.getPreferences(e.protocol).join(`
|
|
1903
1847
|
`)}`;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(`
|
|
1904
1848
|
`).filter(c=>!this.getPreferences(e).includes(c)).join(`
|
|
1905
|
-
`);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 ha=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 Sa=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 C=this.fileSystem.joinPaths("./",this.fileSystem.getRelativePath(this.fileSystem.getDirectoryName(u),y));for(let v of g.include){let D=new Minimatch(v,{partial:true,magicalBraces:true});if(!D.hasMagic()&&!v.includes(".")&&(D=new Minimatch(`${v.replace(/\/?$/,"")}/**/*`,{partial:true})),D.match(C))return o.mergeConfig({...g,rootConfigPath:a.rootConfigPath},p)}}}}return a}async locateParentConfig(e,t,n){let r=n;r.endsWith(".json")||(r+=".json");let i=this.fileSystem.joinPaths(t,r);if(await this.fileSystem.exists(i))return i;let a=this.fileSystem.joinPaths(e,"node_modules",r);return await this.fileSystem.exists(a)?a:null}async parseConfig(e){let t;try{t=JsonParser$1.parse(await this.fileSystem.readTextFile(e)).toJSON();}catch{return null}let n=await this.tsConfigValidator.validate(t);return n.valid?{rootConfigPath:e,matchedConfigPath:e,...n.data}:null}static mergeConfig(e,t){return {...t,...e,compilerOptions:{...t.compilerOptions,...e.compilerOptions}}}};var ba=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 Le(`Unable to locate executable for command \`${e.name}\`.`);return this.commandExecutor.run({...e,name:n},t)}};function pl(o){let e=typeof o=="string"?je(o,["jsx","typescript"]):o,t=false;return traverse(e,{enter:n=>{let{node:r}=n;if(Qd(r))return t=true,n.stop()}}),t}function Qd(o){return isTypeScript(o)||Bd(o)}function Bd(o){return (isImportSpecifier(o)||isImportDeclaration(o))&&(o.importKind==="type"||o.importKind==="typeof")}var Ia=class{async apply(e){if(!pl(e))return {modified:false,result:e};let t=createConfigItem([eg,{onlyRemoveTypeImports:true}]),n=createConfigItem([tg,{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],C=u.find((D,U)=>U>g&&!["CommentLine","CommentBlock"].includes(D.type));if(C===void 0)continue;C.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 va=class{constructor({executableLocator:e,command:t}){this.executableLocator=e,this.command=t;}async test(){return await this.executableLocator.locate(this.command)!==null}};var xa=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 wa=class{constructor({token:e}){this.token=e;}getToken(){return Promise.resolve(this.token.toString())}login(){this.reportUnsupportedOperation("login");}logout(){this.reportUnsupportedOperation("logout");}reportUnsupportedOperation(e){throw new d(`${e==="login"?"Login":"Logout"} is not supported when using an externally provided token.`,{title:"Unsupported operation",reason:"precondition",suggestions:["Do not specify the `--token` option or the `CROCT_TOKEN` environment variable."]})}};var Un=class{constructor(e){this.factory=e;}open(e){return this.instance===void 0&&(this.instance=this.factory()),this.instance.open(e)}};var Wn=class{constructor(e){this.output=e;}open(e){let t=e.replace(/([\\`*_{}[\]()#+\-.!])/g,"\\$1");return this.output.log(`[${t}](${t})`),Promise.resolve()}};var Pa=class{constructor(e){this.fallbackOpener=e;}async open(e){try{await ng(e);}catch{return this.fallbackOpener.open(e)}}};var Ca=class{constructor({packageManager:e}){this.packageManager=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Installing dependencies");try{await this.packageManager.installDependencies({logger:new ge({status:"Installing dependencies",notifier:r})});}catch(i){throw S.fromCause(i)}finally{r?.stop();}}};var ig=z$1.strictObject({}),ka=class extends I{constructor(){super(ig);}};var Aa=class{constructor({fileSystem:e}){this.fileSystem=e;}async execute({path:e,destination:t,overwrite:n=false}){let r=this.fileSystem.normalizeSeparators(e);if(!await this.fileSystem.exists(r))throw new S("Cannot move path because source does not exist.",{reason:"invalid_input",details:[`Source: ${r}`]});let i=this.fileSystem.normalizeSeparators(t);if(await this.fileSystem.exists(i)&&!n)throw new S("Cannot move path because destination already exists.",{reason:"precondition",details:[`Destination: ${i}`]});if(this.fileSystem.isSubPath(r,i))throw new S("Cannot move path to a subdirectory of itself.",{reason:"invalid_input",details:[`Source: ${r}`,`Destination: ${i}`]});try{await this.fileSystem.move(r,i,{overwrite:n});}catch(a){throw S.fromCause(a)}}};var Ea=class{constructor({fileSystem:e}){this.fileSystem=e;}async execute(e,t){t.set(e.result,await this.readFile(e));}async readFile({path:e,optional:t=false}){let n=this.fileSystem.normalizeSeparators(e);if(!await this.fileSystem.exists(n)){if(!t)throw new S("Cannot read file because it does not exist.",{reason:"precondition",details:[`Path: ${n}`]});return null}if(await this.fileSystem.isDirectory(n)){if(!t)throw new S("Cannot read file because the specified path is a directory.",{reason:"precondition",details:[`Path: ${n}`]});return null}try{return this.fileSystem.readTextFile(n)}catch(r){throw S.fromCause(r)}}};var og=z$1.strictObject({path:z$1.string().min(1),destination:z$1.string().min(1),overwrite:z$1.boolean().optional()}),Ra=class extends I{constructor(){super(og);}};var ag=z$1.strictObject({path:z$1.string().min(1),optional:z$1.boolean().optional(),result:z$1.string().min(1)}),Da=class extends I{constructor(){super(ag);}};var Ma=class{constructor({fileSystem:e}){this.fileSystem=e;}async execute({path:e}){let t=this.fileSystem.normalizeSeparators(e);if(await this.fileSystem.exists(t)&&!await this.fileSystem.isDirectory(t))throw new S("Cannot create directory because a file with the same name exists.",{reason:"precondition",details:[`Path: ${t}`]});try{await this.fileSystem.createDirectory(t,{recursive:!0});}catch(n){throw S.fromCause(n)}}};var sg=z$1.strictObject({path:z$1.string().min(1)}),Na=class extends I{constructor(){super(sg);}};var $a=class{constructor({fileSystem:e,input:t}){this.fileSystem=e,this.input=t;}async execute({path:e,content:t,...n}){let r=n.overwrite===true,i=this.fileSystem.normalizeSeparators(e);if(!r&&await this.fileSystem.exists(i)&&(r=this.input===void 0?false:await this.input.confirm({message:`Path \`${i}\` already exists. Do you want to overwrite it?`,default:false}),!r))throw new S("Failed to write file because the specified path already exists.",{reason:"precondition",details:[`File: ${i}`]});r&&await this.fileSystem.isDirectory(i)&&await this.fileSystem.delete(i,{recursive:true});try{await this.fileSystem.writeTextFile(i,t,{overwrite:r});}catch(a){throw S.fromCause(a)}}};var pg=z$1.strictObject({path:z$1.string().min(1),content:z$1.string(),overwrite:z$1.boolean().optional()}),za=class extends I{constructor(){super(pg);}};var _a=class{constructor(e){this.currentVersion=e.currentVersion,this.packageManager=e.packageManager,this.configurationProvider=e.configurationProvider,this.input=e.input,this.output=e.output,this.checkTimeout=e.checkTimeout,this.checkFrequency=e.checkFrequency;}async checkForUpdates(){let e=await this.configurationProvider.get();if(!this.isCheckEnabled(e))return;let t=await this.getLatestVersion();if(t===null||(await this.configurationProvider.save({...e,lastUpdateCheck:Date.now()}),fd.gte(this.currentVersion,t))||(this.output.announce({semantics:"info",title:"New version",message:`Update your CLI from ${this.currentVersion} \u2192 \`${t}\``}),!(await this.input?.confirm({message:"Would you like to update now?",default:true})??false)))return;let r=this.output.notify("Updating the CLI");try{await this.packageManager.updatePackage("croct",{global:ul,logger:new ge({status:"Updating the CLI",notifier:r})});}catch{let a=await this.packageManager.getPackageUpdateCommand("croct",{global:ul}),s=`${a.name} ${a.arguments?.join(" ")}`;r.alert("Failed to update the CLI automatically"),this.output.log(`Please run the command:
|
|
1906
|
-
\`${s}\``);return}r.confirm("CLI updated successfully!"),this.output.inform("The new version will take effect the next time you run a command");}isCheckEnabled(e){return e.lastUpdateCheck===void 0||Date.now()-e.lastUpdateCheck>this.checkFrequency}getLatestVersion(){let e=new AbortController;return setTimeout(()=>e.abort(),this.checkTimeout),fetch("https://registry.npmjs.org/croct/latest",{signal:e.signal}).then(t=>t.json()).then(t=>t.version).catch(()=>null)}};var Fa=class{constructor({fileSystem:e}){this.fileSystem=e;}async execute({path:e,recursive:t=false}){let n=this.fileSystem.normalizeSeparators(e);if(await this.fileSystem.exists(n)){if(!t&&await this.fileSystem.isDirectory(n)&&!await this.fileSystem.isEmptyDirectory(n))throw new S("Cannot delete non-empty directory when `recursive` is false.",{reason:"precondition",details:[`Path: ${n}`]});try{await this.fileSystem.delete(n,{recursive:t});}catch(r){throw S.fromCause(r)}}}};var lg=z$1.strictObject({path:z$1.string().min(1),recursive:z$1.boolean().optional()}),ja=class extends I{constructor(){super(lg);}};var Ua=class{constructor({projectDirectory:e,fileSystem:t,codemod:n,scanFilter:r}){this.projectDirectory=e,this.fileSystem=t,this.codemod=n,this.scanFilter=r;}async execute(e,t){let{output:n}=t,r=n?.notify("Resolving imports");try{await this.resolveImports(e.path);}finally{r?.stop();}}async resolveImports(e){let t=false,n=_t.fromPattern(e);for await(let r of this.fileSystem.list(this.projectDirectory.get(),this.scanFilter))await n.test(r.name)&&r.type==="file"&&(t=true,await this.codemod.apply(await this.fileSystem.getRealPath(r.name)));if(!t)throw new d("No matching files found for resolving imports.",{reason:"unexpected_result",details:[`Pattern: ${e}`]})}};var ug=z$1.strictObject({path:z$1.string().min(1)}),Wa=class extends I{constructor(){super(ug);}};var qa=class o{constructor(e){this.instances=new Map;this.configuration=e,this.initialDirectory=e.directories.current??e.process.getCurrentDirectory(),this.workingDirectory=new Zo(this.initialDirectory);}static{this.READ_ONLY_COMMANDS=new Set([_n,gn,fn,Nt,$t,mn,dn,Sn,an]);}static fromDefaults(e){let t=dg("com.croct.cli"),n=new ta;return new o({program:e.program??(()=>{throw new d("CLI is running in standalone mode.")}),process:e.process??n,quiet:e.quiet??false,debug:e.debug??false,stateless:e.stateless??false,interactive:e.interactive??!gg.isCI,version:e.version??"0.0.0",apiKey:e.apiKey,token:e.token,dnd:e.dnd??false,adminTokenDuration:e.adminTokenDuration??7*Xe.LocalTime.SECONDS_PER_DAY,apiKeyTokenDuration:e.apiKeyTokenDuration??30*Xe.LocalTime.SECONDS_PER_MINUTE,cliTokenDuration:e.cliTokenDuration??90*Xe.LocalTime.SECONDS_PER_DAY,cliTokenFreshPeriod:e.cliTokenFreshPeriod??15*Xe.LocalTime.SECONDS_PER_DAY,cliTokenIssuer:e.cliTokenIssuer??"croct.com",deepLinkProtocol:e.deepLinkProtocol??"croct",templateRegistryUrl:e.templateRegistryUrl??new URL("github://croct-tech/templates/templates/registry.json5"),adminUrl:e.adminUrl??new URL("https://app.croct.com"),adminTokenParameter:e.adminTokenParameter??"accessToken",adminGraphqlEndpoint:e?.adminGraphqlEndpoint??new URL("https://app.croct.com/graphql"),directories:{current:e.directories?.current??n.getCurrentDirectory(),config:e.directories?.config??t.config(),cache:e.directories?.cache??t.cache(),data:e.directories?.data??t.data(),home:e.directories?.home??homedir()},verificationLinkDestination:{accountActivation:e.verificationLinkDestination?.accountActivation??"./cli",passwordReset:e.verificationLinkDestination?.passwordReset??"./cli"},emailSubject:{passwordReset:e.emailSubject?.passwordReset??"Forgot password",accountActivation:e.emailSubject?.accountActivation??"Welcome to Croct"}})}welcome(e){let t=!this.configuration.interactive||this.configuration.dnd;return this.execute(new _n({cliVersion:this.configuration.version,autoUpdater:new _a({currentVersion:this.configuration.version,input:this.getInput(),configurationProvider:this.getCliConfigurationProvider(),packageManager:this.getNodePackageManager(),output:this.getOutput(),checkFrequency:Xe.LocalTime.MILLIS_PER_SECOND*Xe.LocalTime.SECONDS_PER_HOUR*6,checkTimeout:500}),configurationProvider:this.getCliConfigurationProvider(),deepLinkInstaller:n=>this.deepLink({operation:n?"optionally-update":"optionally-enable"})}),{skipDeepLinkCheck:t||e.skipDeepLinkCheck===true,skipUpdateCheck:t||e.skipUpdateCheck===true})}deepLink(e){return this.execute(new ha({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 $o({program:this.configuration.program,protocol:this.configuration.deepLinkProtocol,configurationProvider:this.getCliConfigurationProvider(),workingDirectory:new Jo(this.configuration.process),fileSystem:this.getFileSystem(),io:{input:this.getInput(),output:this.getOutput()}}),e)}init(e){let{process:t}=this.configuration;return this.execute(new ur({sdkProvider:this.getSdkProvider(),platformProvider:this.getPlatformProvider(),configurationManager:this.getConfigurationManager(),skipConfirmation:new Oo(new zn(new Ao(new Mn({fileSystem:this.getFileSystem(),files:[".git"]})))),api:{user:this.getUserApi(),organization:this.getOrganizationApi(),workspace:this.getWorkspaceApi()},form:{organization:new yr({input:this.getFormInput(),output:this.getOutput(),userApi:this.getUserApi()}),workspace:new hr({input:this.getFormInput(),output:this.getOutput(),organizationApi:this.getOrganizationApi()}),application:new Sr({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),slot:new Be({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})},io:{input:this.getInput(),output:this.getOutput()}}),{...e,organization:e.organization??t.getEnvValue("CROCT_ORGANIZATION")??void 0,workspace:e.workspace??t.getEnvValue("CROCT_WORKSPACE")??void 0,devApplication:e.devApplication??t.getEnvValue("CROCT_DEV_APPLICATION")??void 0,prodApplication:e.prodApplication??t.getEnvValue("CROCT_PROD_APPLICATION")??void 0,skipApiKeySetup:e.skipApiKeySetup??t.getEnvValue("CROCT_SKIP_API_KEY_SETUP")!==null})}install(e){return this.execute(new gn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),io:{input:this.getInput(),output:this.getOutput()}}),e)}upgrade(e){return this.execute(new fn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),form:{slotForm:new Be({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),componentForm:new ot({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})},io:{input:this.getInput(),output:this.getOutput()}}),e)}addSlot(e){return this.execute(new Nt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new Be({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}removeSlot(e){return this.execute(new mn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),slotForm:new Be({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}addComponent(e){return this.execute(new $t({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new ot({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}removeComponent(e){return this.execute(new dn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new ot({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}login(e){return this.execute(new mr({authenticator:this.getAuthenticator()}),e)}logout(){return this.execute(new an({authenticator:this.getAuthenticator(),output:this.getOutput()}),{})}admin(e){return this.execute(new wr({output:this.getOutput(),pageForm:new Mr({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 Sn({configurationManager:this.getConfigurationManager(),fileSystem:this.getFileSystem(),templateForm:new Zr({input:this.getFormInput(),form:{component:new ot({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),slot:new Be({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),experience:new Jr({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),audience:new Qr({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 Br({templateProvider:new jt({provider:new vn(this.getTemplateProvider()),validator:new An}),fileSystem:this.getFileSystem(),action:this.getImportAction(),io:{input:this.getInput(),output:this.getOutput()}})}createApiKey(e){return this.execute(new Ko({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 Ln(new $r(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 tr({input:this.configuration.process.getStandardInput(),output:this.configuration.process.getStandardOutput(),onAbort:()=>e.exit(),onInteractionStart:()=>e.suspend(),onInteractionEnd:()=>e.resume()});return this.configuration.dnd?new Ln(t):t})}getNonInteractiveOutput(e=false){let{configuration:t}=this,n=new on({output:t.process.getStandardOutput(),formatter:this.getLogFormatter(),interactive:false,quiet:e,onExit:()=>t.process.exit(),linkOpener:new Un(()=>new Wn(n))});return t.process.on("exit",()=>n.stop()),n}getHierarchicalLogger(){return this.share(this.getHierarchicalLogger,()=>new ca(this.getLogger()))}getLogger(){return this.share(this.getLogger,()=>{let e=new la(this.getOutput());return this.configuration.debug?e:new FilteredLogger(e,LogLevel.WARNING)})}getOutput(){return this.share(this.getOutput,()=>{let{configuration:e}=this,t=new on({output:e.process.getStandardOutput(),formatter:this.getLogFormatter(),interactive:this.configuration.interactive,quiet:this.configuration.quiet,onExit:()=>e.process.exit(),linkOpener:new Un(()=>{let n=new Wn(t);return this.configuration.dnd?n:new Pa(n)})});return e.process.on("exit",()=>t.stop()),t})}getLogFormatter(){return this.share(this.getLogFormatter,()=>new Xo)}getTemplateProvider(){return this.share(this.getTemplateProvider,()=>{let e=n=>new Ke({providers:["template.json5","template.json"].map(r=>new It({dataProvider:n,registryProvider:new Ht([{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 wn({resourceCache:new AutoSaveCache(new InMemoryCache),errorCache:new InMemoryCache,provider:new Ke({providers:[new It({dataProvider:this.traceProvider({label:"ResourceProvider",provider:e(new vt(new Ke({providers:[this.traceProvider({provider:this.createGitHubProvider(t)}),this.traceProvider({provider:new bn(t)})]})))}),registryProvider:this.traceProvider({label:"NpmRegistryProvider",provider:new ia(new jt({provider:oa.json(this.traceProvider({provider:this.getHttpProvider()})),validator:new aa}))})}),e(new vt(this.getFileProvider()))]})})})})}getFileProvider(){return this.share(this.getFileProvider,()=>{let e=this.traceProvider({provider:this.getHttpProvider()}),t=this.traceProvider({provider:new mi(this.getFileSystem(),this.getScanFilter())}),n=new Ke({providers:[t,this.traceProvider({provider:this.createGitHubProvider(e)}),this.traceProvider({provider:new bn(e)})]});return this.traceProvider({label:"FileProvider",provider:new Ke({providers:[t,this.traceProvider({provider:new It({baseUrl:new URL("./",this.configuration.templateRegistryUrl),dataProvider:this.traceProvider({label:"ResourceProvider",provider:n}),registryProvider:new qi({url:this.configuration.templateRegistryUrl,provider:this.traceProvider({label:"GlobalRegistryProvider",provider:new wn({errorCache:new InMemoryCache,resourceCache:new AutoSaveCache(new InMemoryCache),provider:new jt({provider:new vn(new vt(n)),validator:new hi})})})})})})]})})})}createGitHubProvider(e){let t=Date.now();return new di({cache:new AutoSaveCache(new InMemoryCache),provider:new Ke({providers:[new Ke({providers:[new It({dataProvider:e,registryProvider:new Ht([{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 pa({label:t,provider:e,logger:this.getHierarchicalLogger()})}getImportAction(){return this.share(this.getImportAction,()=>{let e=this.getFileSystem(),t=new Map,n={run:new N({action:new at(new $e(()=>new eo(n))),validator:new to}),try:new N({action:new at(new $e(()=>new ii(n.run))),validator:new xi}),test:new N({action:new at(new $e(()=>new Li(n.run))),validator:new _i}),repeat:new N({action:new at(new $e(()=>new Ro(n.run))),validator:new To}),print:new N({action:new Fi,validator:new Ui}),fail:new N({action:new Wi,validator:new Vi}),define:new N({action:new oo,validator:new io}),prompt:new N({action:new Qi,validator:new Bi}),"change-directory":new N({action:new lo({fileSystem:e,rootDirectory:this.initialDirectory,currentDirectory:this.workingDirectory}),validator:new co}),"open-link":new N({action:new no,validator:new ro}),"start-server":new N({action:new Yi({serverProvider:this.getServerProvider(),serverFactory:this.getServerFactory(),packageManager:this.getPackageManager(),serverMap:t}),validator:new Xi}),"stop-server":new N({action:new xa({serverMap:t}),validator:new ao}),"check-dependency":new N({action:new ui({packageManager:this.getPackageManager()}),validator:new wi}),download:new N({action:new Yr({fileSystem:e,provider:this.getFileProvider(),codemod:new Jt({codemods:{"**/*.{js,jsx,ts,tsx}":new Qt(this.getNodeImportResolverCodemod(),new Jt({codemods:{"**/*.{js,jsx}":new Qt(new qe({fileSystem:e,codemod:new We({codemod:new Ia,languages:["typescript","jsx"]})}))}}),new Ve(this.getJavaScriptFormatter()))}})}),validator:new Pi}),"resolve-import":new N({action:new Ua({projectDirectory:this.workingDirectory,fileSystem:e,scanFilter:this.getScanFilter(),codemod:new Jt({codemods:{"**/*.{js,jsx,ts,tsx}":new Qt(this.getNodeImportResolverCodemod(),new Ve(this.getJavaScriptFormatter()))}})}),validator:new Wa}),install:new N({action:new Ca({packageManager:this.getPackageManager()}),validator:new ka}),"add-dependency":new N({action:new Xr({packageManager:this.getPackageManager()}),validator:new ki}),"execute-package":new N({action:new uo({processObserver:this.configuration.process,packageManager:this.getPackageManager(),packageManagerProvider:this.getPackageManagerRegistry(),workingDirectory:this.workingDirectory,commandExecutor:this.getAsynchronousCommandExecutor(),commandTimeout:3*60*1e3,sourceChecker:{test:r=>r.protocol==="file:"||`${r}`.startsWith("https://github.com/croct-tech")}}),validator:new mo}),"locate-path":new N({action:new ei({projectDirectory:this.workingDirectory,fileSystem:e,scanFilter:this.getScanFilter()}),validator:new Ai}),"move-path":new N({action:new Aa({fileSystem:e}),validator:new Ra}),"delete-path":new N({action:new Fa({fileSystem:e}),validator:new ja}),"read-file":new N({action:new Ea({fileSystem:e}),validator:new Da}),"write-file":new N({action:new $a({fileSystem:e,input:this.getInput()}),validator:new za}),"replace-file-content":new N({action:new ti({fileSystem:e}),validator:new Ei}),"create-directory":new N({action:new Ma({fileSystem:e}),validator:new Na}),"integrate-croct":new N({action:new na({callback:async()=>{if(!await this.getConfigurationManager().isInitialized())return this.init({})}}),validator:new ra}),"add-slot":new N({action:new ni({installer:(r,i)=>{let a=this.getNonInteractiveOutput(true);return this.execute(new Nt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new Be({input:this.getNonInteractiveInput(),output:a,workspaceApi:this.getWorkspaceApi()}),io:{output:a}}),{slots:r,example:i})}}),validator:new Ri}),"add-component":new N({action:new ri({installer:r=>{let i=this.getNonInteractiveOutput(true);return this.execute(new $t({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new ot({input:this.getNonInteractiveInput(),output:i,workspaceApi:this.getWorkspaceApi()}),io:{output:i}}),{components:r})}}),validator:new Ti}),"create-resource":new N({action:new si({configurationManager:this.getConfigurationManager(),matcher:new ci({workspaceApi:this.getWorkspaceApi()}),api:{user:this.getUserApi(),workspace:this.getWorkspaceApi(),organization:this.getOrganizationApi()},mappingForm:new pi({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 Di}),"format-code":new N({action:new Ni({formatter:this.getCodeFormatter()}),validator:new $i}),import:new N({action:new at(new $e(()=>new bi({runner:n.run,templateProvider:new vi({evaluator:new Si({functions:Ms}),validator:new An,templateProvider:this.getTemplateProvider(),fileProvider:new vt(this.getFileProvider())}),variables:this.getActionVariables()}))),validator:new Mi})};return n.import})}getActionVariables(){let e=t=>new URL(t,this.configuration.adminUrl).toString();return {packageManager:ae.transient(()=>({name:this.getPackageManager().getName()})),project:{features:ae.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{features:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),quotas:ae.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{quotas:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),organization:ae.transient(async()=>{let{organization:t}=await this.getConfigurationManager().load();return {slug:t,url:e(`organizations/${t}`)}}),workspace:ae.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load();return {slug:n,url:e(`organizations/${t}/workspaces/${n}`)}}),application:ae.transient(async()=>{let{organization:t,workspace:n,applications:r}=await this.getConfigurationManager().load(),i=`organizations/${t}/workspaces/${n}/applications/`;return {development:{slug:r.development,url:e(i+r.development)},production:{slug:r.production,url:e(i+r.production)}}}),path:ae.transient(async()=>{let t=this.getSdk(),n=await this.getConfigurationManager().load();return t.getPaths(n)}),platform:ae.transient(async()=>await this.getPlatformProvider().get()??"unknown"),server:ae.transient(async()=>{let n=await this.getServerProvider().get();if(n===null)return null;try{let r=await n.getStatus();if(r.running)return {running:!0,url:r.url.toString()}}catch{}return {running:false}})}}}getHttpProvider(){return this.share(this.getHttpProvider,()=>new li({retry:{maxAttempts:3,delay:1e3}}))}getAuthenticator(){return this.share(this.getAuthenticator,()=>{if(this.configuration.apiKey!==void 0)return new Go({apiKey:this.configuration.apiKey,clock:this.getClock(),tokenDuration:this.configuration.apiKeyTokenDuration});if(this.configuration.token!==void 0)return new wa({token:this.configuration.token});let e=this.getFormInput(),t=new Ir({input:e,output:this.getOutput(),userApi:this.getUserApi(true),form:{signIn:new vr({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 xr({input:e,output:this.getOutput(),userApi:this.getUserApi(true),listener:this.getTokenListener(),emailLinkGenerator:this.createEmailLinkGenerator(this.configuration.emailSubject.accountActivation),verificationLinkDestination:this.configuration.verificationLinkDestination.accountActivation})}}),n=this.getUserApi(true),r=new Qo({cacheKey:"token",cacheProvider:new Bo({clock:this.getClock(),clockSkewTolerance:5,tokenFreshPeriod:this.configuration.cliTokenFreshPeriod,tokenIssuer:()=>n.issueToken({duration:this.configuration.cliTokenDuration}),cacheProvider:this.selectCacheProvider(()=>new xn({fileSystem:this.getFileSystem(),directory:this.configuration.directories.config,useKeyAsFileName:true}))}),authenticator:new Lr({default:this.configuration.interactive?t:new Nr({authenticator:t,instruction:{message:"Authentication required.",suggestions:["Run `login` to authenticate"],reason:"precondition"}}),credentials:t})});return this.configuration.interactive?new Vo({authenticator:r,invitationForm:new Wo({output:this.getOutput(),input:e,userApi:this.getUserApi(true)})}):r})}getSdk(){return this.share(this.getSdk,()=>{let e=new Gt(this.getSdkProvider(),new $e(()=>{throw new V("No suitable SDK detected.",{reason:"not_supported",suggestions:["Make sure you are running the command in the project root directory."]})}));return new ko(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 qt({discriminator:async()=>await this.getPlatformProvider().get()??i,mapping:{javascript:()=>new ar({...r,bundlers:["vite","parcel","tsup","rollup"]}),react:()=>new sr({...r,importResolver:n,codemod:{provider:new Ve(e,new qe({fileSystem:this.getFileSystem(),codemod:new We({languages:["typescript","jsx"],codemod:new ft({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 lr({...r,userApi:this.getUserApi(),applicationApi:this.getApplicationApi(),importResolver:n,codemod:{middleware:new Ve(e,new qe({fileSystem:this.getFileSystem(),codemod:new We({languages:["typescript","jsx"],codemod:new Er({matcherPattern:"/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",import:{module:"@croct/plug-next/middleware",middlewareName:"middleware",middlewareFactoryName:"withCroct",configName:"config",matcherName:"matcher"}})})})),appRouterProvider:new Ve(e,new qe({fileSystem:this.getFileSystem(),codemod:new We({languages:["typescript","jsx"],codemod:new ft({fallbackToNamedExports:false,fallbackCodemod:new Or({provider:{component:"CroctProvider",module:"@croct/plug-next/CroctProvider"}}),wrapper:{module:"@croct/plug-next/CroctProvider",component:"CroctProvider"},targets:{variable:"children"}})})})),pageRouterProvider:new Ve(e,new qe({fileSystem:this.getFileSystem(),codemod:new We({languages:["typescript","jsx"],codemod:new ft({fallbackToNamedExports:false,fallbackCodemod:new un({provider:{component:"CroctProvider",module:"@croct/plug-next/CroctProvider"}}),wrapper:{module:"@croct/plug-next/CroctProvider",component:"CroctProvider"},targets:{component:"Component"}})})})),fallbackProvider:new Ve(e,new qe({fileSystem:this.getFileSystem(),codemod:new We({languages:["typescript","jsx"],codemod:new ft({fallbackToNamedExports:false,fallbackCodemod:new un({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 Co(new qt({discriminator:async()=>await this.getPlatformProvider().get()??e,mapping:{javascript:()=>this.getJavaScriptFormatter(),react:()=>this.getJavaScriptFormatter(),nextjs:()=>this.getJavaScriptFormatter(),[e]:()=>{throw new V("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 Io(new Map(Object.entries(this.getPackageManagers()))))}getPackageManagers(){return this.getNodePackageManagers()}getPackageManager(){return this.share(this.getPackageManager,()=>new Dn(new Gt(this.getNodePackageManagerProvider(),new $e(()=>{throw new V("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 Dn(new Gt(this.getNodePackageManagerProvider(),new Ht(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 $n(new Uo(new wt({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new jo({process:this.configuration.process,variable:"npm_config_user_agent",value:new RegExp(`^${r}`)})}))}),new wt({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new zn(new Fo({packageManager:r,fileSystem:t,projectDirectory:this.workingDirectory}),new Mn({fileSystem:t,files:n[r]}))}))}),new wt({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new va({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 In,r={fileSystem:e,projectDirectory:this.workingDirectory,packageValidator:n};return {npm:new st({...r,agent:new go(t)}),yarn:new st({...r,agent:new fo(t)}),bun:new st({...r,agent:new yo(t)}),pnpm:new st({...r,agent:new ho(t)})}})}getServerProvider(){return this.share(this.getServerProvider,()=>{let e=Symbol("unknown");return new qt({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 Hi({packageManager:this.getNodePackageManager(),factory:this.getServerFactory(),parsers:[new Ki,new Gi,new Zi,new Ji]}))}getServerFactory(){return this.share(this.getServerFactory,()=>new po({commandExecutor:this.getAsynchronousCommandExecutor(),workingDirectory:this.workingDirectory,startupTimeout:60*1e3,startupCheckDelay:1.5*1e3,lookupMaxPorts:30,lookupTimeout:2*1e3,processObserver:this.configuration.process}))}getJavaScriptFormatter(){return this.share(this.getJavaScriptFormatter,()=>new Tr({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 So({fileSystem:this.getFileSystem(),tsConfigLoader:this.getTsConfigLoader(),projectDirectory:this.workingDirectory}))}getTsConfigLoader(){return this.share(this.getTsConfigLoader,()=>new Sa({fileSystem:this.getFileSystem(),tsconfigValidator:new bo}))}getAsynchronousCommandExecutor(){return this.share(this.getAsynchronousCommandExecutor,()=>new ba({executableLocator:this.getExecutableLocator(),commandExecutor:this.getCommandExecutor()}))}getSynchronousCommandExecutor(){return this.getCommandExecutor()}getCommandExecutor(){return this.share(this.getCommandExecutor,()=>new Po({currentDirectory:this.workingDirectory,windows:this.configuration.process.getPlatform()==="win32"}))}getExecutableLocator(){return this.share(this.getExecutableLocator,()=>{let{process:e}=this.configuration;return new _o({fileSystem:this.getFileSystem(),cache:new AutoSaveCache(new InMemoryCache),executablePaths:e.getEnvList("PATH")??[],executableExtensions:e.getEnvList("PATHEXT")??[]})})}getPlatformProvider(){return this.share(this.getPlatformProvider,()=>{let e=new st({projectDirectory:this.workingDirectory,packageValidator:new In,fileSystem:this.getFileSystem(),agent:new vo});return new $n(new wt({candidates:[{value:"nextjs",condition:new Nn({packageManager:e,dependencies:["next"]})},{value:"react",condition:new Nn({packageManager:e,dependencies:["react"]})},{value:"javascript",condition:new xo({packageManager:e})}]}),this.workingDirectory)})}getConfigurationManager(){return this.share(this.getConfigurationManager,()=>{let e=this.getOutput(),t=new dr({fileSystem:this.getFileSystem(),validator:new fi,projectDirectory:this.workingDirectory});return new zo({workingDirectory:this.workingDirectory,configurationProvider:this.getCliConfigurationProvider(),manager:new oi(this.configuration.interactive&&!this.isReadOnlyMode()?new Dr({manager:t,initializer:{initialize:async()=>{await this.init({}),e.break();}}}):t)})})}getNodeImportResolverCodemod(){return this.share(this.getNodeImportResolverCodemod,()=>{let e=this.getFileSystem(),t=this.getScanFilter();return new ua({fileSystem:e,rootPath:this.workingDirectory,filter:(n,r)=>r<=10&&t(n,r),importResolver:this.getNodeImportResolver(),importCodemod:new qe({fileSystem:e,codemod:new We({languages:["typescript","jsx"],codemod:new da})}),exportMatcher:{test:(n,{names:r})=>r.length===0?true:ol(n).some(i=>r.includes(i))}})})}getScanFilter(){return this.share(this.getScanFilter,()=>{let e=new Eo({fileSystem:this.getFileSystem(),workingDirectory:this.workingDirectory});return async t=>!await e.test(t)})}getUserApi(e=false){return e?new cn(this.getGraphqlClient(true)):this.share(this.getUserApi,()=>new cn(this.getGraphqlClient()))}getOrganizationApi(){return this.share(this.getOrganizationApi,()=>new gr(this.getGraphqlClient(),this.getHierarchyResolver()))}getWorkspaceApi(){return this.share(this.getWorkspaceApi,()=>new fr(this.getGraphqlClient(),this.getHierarchyResolver()))}getApplicationApi(){return this.share(this.getApplicationApi,()=>new br(this.getGraphqlClient(),this.getHierarchyResolver()))}getHierarchyResolver(){return this.share(this.getHierarchyResolver,()=>new ga(this.getGraphqlClient(),new InMemoryCache))}getGraphqlClient(e=false){return e?new sn({endpoint:this.configuration.adminGraphqlEndpoint,tokenProvider:{getToken:()=>this.getAuthenticator().getToken()}}):this.share(this.getGraphqlClient,()=>{let t=this.getAuthenticator();return new sn({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 _r({platform:e.process.getPlatform(),commandExecutor:this.getSynchronousCommandExecutor(),timeout:2e3,listener:new Yo({api:this.getUserApi(true),pollingInterval:1e3})})})}getFileSystem(){return this.share(this.getFileSystem,()=>new zr({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:Xe.Instant.now(n).getSeconds()})}getEmailLinkGenerator(){return this.share(this.getEmailLinkGenerator,()=>new Fr({detector:new jr(new Ur,new Wr),templates:{google:new Vr,icloud:new qr,microsoft:new Hr,proton:new Kr,yahoo:new Gr}}))}getClock(){return dl.SystemClock.UTC}getProtocolRegistryProvider(){return this.share(this.getProtocolRegistryProvider,()=>new $e(()=>{let e=this.getFileSystem(),{process:t}=this.configuration;switch(t.getPlatform()){case "darwin":{let n=e.joinPaths(this.configuration.directories.data,"apps");return new fa({output:this.getOutput(),macOsRegistry:new Do({fileSystem:e,appDirectory:n,commandExecutor:this.getAsynchronousCommandExecutor()}),firefoxRegistry:ya.macOs({fileSystem:e,homeDirectory:this.configuration.directories.home,appPath:e.joinPaths(n,`${this.configuration.deepLinkProtocol}.app`)})})}case "win32":return new Mo({commandExecutor:this.getAsynchronousCommandExecutor()});case "linux":return new No({fileSystem:e,homeDirectory:this.configuration.directories.home,commandExecutor:this.getAsynchronousCommandExecutor()});default:return null}}))}selectCacheProvider(e){return this.configuration.stateless?new InMemoryCache:e()}getCliConfigurationProvider(){return this.share(this.getCliConfigurationProvider,()=>{let e=this.getFileSystem();return new Ho({fileSystem:e,configurationProvider:new qo({cacheKey:"config.json",cache:this.selectCacheProvider(()=>new xn({fileSystem:e,directory:this.configuration.directories.config,useKeyAsFileName:true})),validator:new Lo})})})}async execute(e,t){if(this.isReadOnlyMode()&&!o.READ_ONLY_COMMANDS.has(e.constructor))return this.reportError(new d("This command does not support API key authentication.",{reason:"precondition",suggestions:["Run the command without specifying an API key."]}));try{await e.execute(t);}catch(n){let r=o.handleError(n);return n instanceof Error&&r instanceof Error&&(r.stack=n.stack),this.reportError(r)}}isReadOnlyMode(){return this.configuration.apiKey!==void 0}reportError(e){let t=this.getOutput();return t.report(o.handleError(e)),t.exit()}static handleError(e){switch(true){case e instanceof z:return new d(e.message,{...e.help,details:[`URL: ${e.url}`,...e.help.details??[]]});case e instanceof oe:if(e.isAccessDenied())return new d("Your user lacks the necessary permissions to complete this operation.",{reason:"access_denied",details:e.problems.map(t=>t.detail??t.title),suggestions:["Contact your organization or workspace administrator for assistance."],cause:e});break;case e instanceof S:if(e.tracing.length>0){let t=e.tracing.map(({name:n,source:r},i)=>{let a=r!==void 0?` at ${o.getSourceLocation(r)}`:"";return `${" ".repeat(i+1)}\u21B3 \`${n}\`${a}`}).join(`
|
|
1849
|
+
`);await this.fileSystem.writeTextFile(n,s,{overwrite:true});let p=o.parseHandlers(a);p.schemes[e]!==void 0&&(delete p.schemes[e],await this.fileSystem.writeTextFile(r,JSON.stringify(p),{overwrite:true}));}getUserPreferencesFilePath(e){return this.fileSystem.joinPaths(e,"user.js")}getHandlersFilePath(e){return this.fileSystem.joinPaths(e,"handlers.json")}async getProfilePath(){let e=this.getPath("profiles.ini");if(!await this.fileSystem.exists(e))return null;let t=Object.values(parse(await this.fileSystem.readTextFile(e))),n=[],r=[];for(let a of t)a.Default!==void 0&&n.push(a.Default),a.Path!==void 0&&(a.Default==="1"?r.unshift(a.Path):r.push(a.Path));if(r.length===0)return null;let i=r[0];for(let a of r)if(n.includes(a)){i=a;break}return this.getPath(i)}getPath(e){return this.fileSystem.joinPaths(this.profileDirectory,e)}getPreferences(e){return o.PREFERENCES.map(t=>t.replace(/%protocol%/g,e))}static parseHandlers(e){let t;try{t=JSON.parse(e);}catch{return {schemes:{}}}return typeof t!="object"||t===null?{schemes:{}}:!("schemes"in t)||typeof t.schemes!="object"||t.schemes===null?{...t,schemes:{}}:t}};var Sa=class{constructor(e){this.config=e;}async execute(e){let{protocolRegistryProvider:t,io:{output:n}}=this.config,r=await t.get();if(r===null){["optionally-enable","optionally-update"].includes(e.operation)||n.alert("Deep linking is not available on your platform.");return}try{await this.apply(r,e);}catch(i){n.alert(`Deep link error: ${d.formatCause(i)}`);}}apply(e,t){let{io:{output:n}}=this.config;switch(t.operation){case "optionally-enable":return this.optionallyEnable(e,n);case "optionally-update":return this.optionallyUpdate(e,n);case "disable":return this.disable(e,false,n);case "enable":return this.enable(e,false,n)}}async optionallyEnable(e,t){let{protocolHandler:n,io:{input:r}}=this.config;if(!await e.isRegistered(n.protocol)&&await r?.confirm({message:"Turn on deep links to streamline your experience?",default:false})===true)return this.enable(e,true,t)}async enable(e,t,n){let{cliPackage:r,packageManager:i,protocolHandler:a}=this.config;if(!t&&await e.isRegistered(a.protocol)){n?.inform("Deep links are already enabled");return}let s=n?.notify("Enabling deep links");try{let p=await i.getPackageCommand(r,["open","$url"]);await e.register({...a,command:`${p.name} ${(p.arguments??[]).join(" ")}`}),s?.confirm("Deep links enabled");}finally{s?.stop();}}async disable(e,t,n){let{protocolHandler:r}=this.config;if(!t&&!await e.isRegistered(r.protocol)){n?.inform("Deep links are not enabled");return}let i=n?.notify("Disabling deep links");try{await e.unregister(r.protocol),i?.confirm("Deep links disabled");}finally{i?.stop();}}async optionallyUpdate(e,t){let{protocolHandler:n}=this.config;if(!await e.isRegistered(n.protocol))return this.optionallyEnable(e,t);let r=t?.notify("Updating deep links");try{await this.disable(e,!0),await this.enable(e,!0),r?.confirm("Deep links updated");}finally{r?.stop();}}};var ba=class o{constructor({fileSystem:e,tsconfigValidator:t}){this.fileSystem=e,this.tsConfigValidator=t;}async load(e,t={}){let{fileNames:n=["tsconfig.json","jsconfig.json"]}=t,r=await this.fileSystem.getRealPath(e),i=await this.locateConfig(e,n,true);if(i===null)return null;let a=await this.resolveConfig({rootDirectory:r,configPath:i,fileNames:n,targetDirectories:(t.sourcePaths??[]).map(s=>this.fileSystem.isAbsolutePath(s)?s:this.fileSystem.joinPaths(r,s))});return a===null?null:{rootConfigPath:a.rootConfigPath,matchedConfigPath:a.matchedConfigPath,baseUrl:this.fileSystem.joinPaths(this.fileSystem.getDirectoryName(a.matchedConfigPath),a.compilerOptions?.baseUrl??"."),paths:a.compilerOptions?.paths??{}}}async locateConfig(e,t,n=false){for(let i of t){let a=this.fileSystem.joinPaths(e,i);if(await this.fileSystem.exists(a))return a}if(!n)return null;let r=this.fileSystem.getDirectoryName(e);return r===e?null:this.locateConfig(r,t)}async resolveConfig(e){let{configPath:t,fileNames:n,rootDirectory:r,targetDirectories:i}=e,a=await this.parseConfig(t);if(a?.extends!==void 0){let s=await this.locateParentConfig(r,this.fileSystem.getDirectoryName(t),a.extends);if(s!==null){let p=await this.resolveConfig({...e,configPath:s});p!==null&&(a=o.mergeConfig(a,p));}}if(a?.references!==void 0&&i.length>0){let{references:s,...p}=a;for(let c of a.references){let l=this.fileSystem.joinPaths(this.fileSystem.getDirectoryName(t),c.path),u=l.endsWith(".json")?l:await this.locateConfig(l,n);if(u===null)continue;let g=await this.resolveConfig({...e,configPath:u});if(g?.include!==void 0)for(let y of i){let C=this.fileSystem.joinPaths("./",this.fileSystem.getRelativePath(this.fileSystem.getDirectoryName(u),y));for(let v of g.include){let D=new Minimatch(v,{partial:true,magicalBraces:true});if(!D.hasMagic()&&!v.includes(".")&&(D=new Minimatch(`${v.replace(/\/?$/,"")}/**/*`,{partial:true})),D.match(C))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 Ia=class{constructor({commandExecutor:e,executableLocator:t}){this.executableLocator=t,this.commandExecutor=e;}async run(e,t={}){let n=await this.executableLocator.locate(e.name);if(n===null)throw new Le(`Unable to locate executable for command \`${e.name}\`.`);return this.commandExecutor.run({...e,name:n},t)}};function ul(o){let e=typeof o=="string"?je(o,["jsx","typescript"]):o,t=false;return traverse(e,{enter:n=>{let{node:r}=n;if(Xd(r))return t=true,n.stop()}}),t}function Xd(o){return isTypeScript(o)||eg(o)}function eg(o){return (isImportSpecifier(o)||isImportDeclaration(o))&&(o.importKind==="type"||o.importKind==="typeof")}var va=class{async apply(e){if(!ul(e))return {modified:false,result:e};let t=createConfigItem([rg,{onlyRemoveTypeImports:true}]),n=createConfigItem([ig,{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],C=u.find((D,U)=>U>g&&!["CommentLine","CommentBlock"].includes(D.type));if(C===void 0)continue;C.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 xa=class{constructor({executableLocator:e,command:t}){this.executableLocator=e,this.command=t;}async test(){return await this.executableLocator.locate(this.command)!==null}};var wa=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 Pa=class{constructor({token:e}){this.token=e;}getToken(){return Promise.resolve(this.token.toString())}login(){this.reportUnsupportedOperation("login");}logout(){this.reportUnsupportedOperation("logout");}reportUnsupportedOperation(e){throw new d(`${e==="login"?"Login":"Logout"} is not supported when using an externally provided token.`,{title:"Unsupported operation",reason:"precondition",suggestions:["Do not specify the `--token` option or the `CROCT_TOKEN` environment variable."]})}};var Wn=class{constructor(e){this.factory=e;}open(e){return this.instance===void 0&&(this.instance=this.factory()),this.instance.open(e)}};var Vn=class{constructor(e){this.output=e;}open(e){let t=e.replace(/([\\`*_{}[\]()#+\-.!])/g,"\\$1");return this.output.log(`[${t}](${t})`),Promise.resolve()}};var Ca=class{constructor(e){this.fallbackOpener=e;}async open(e){try{await og(e);}catch{return this.fallbackOpener.open(e)}}};var ka=class{constructor({packageManager:e}){this.packageManager=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Installing dependencies");try{await this.packageManager.installDependencies({logger:new ge({status:"Installing dependencies",notifier:r})});}catch(i){throw h.fromCause(i)}finally{r?.stop();}}};var sg=z$1.strictObject({}),Aa=class extends I{constructor(){super(sg);}};var Ea=class{constructor({fileSystem:e}){this.fileSystem=e;}async execute({path:e,destination:t,overwrite:n=false}){let r=this.fileSystem.normalizeSeparators(e);if(!await this.fileSystem.exists(r))throw new h("Cannot move path because source does not exist.",{reason:"invalid_input",details:[`Source: ${r}`]});let i=this.fileSystem.normalizeSeparators(t);if(await this.fileSystem.exists(i)&&!n)throw new h("Cannot move path because destination already exists.",{reason:"precondition",details:[`Destination: ${i}`]});if(this.fileSystem.isSubPath(r,i))throw new h("Cannot move path to a subdirectory of itself.",{reason:"invalid_input",details:[`Source: ${r}`,`Destination: ${i}`]});try{await this.fileSystem.move(r,i,{overwrite:n});}catch(a){throw h.fromCause(a)}}};var Oa=class{constructor({fileSystem:e}){this.fileSystem=e;}async execute(e,t){t.set(e.result,await this.readFile(e));}async readFile({path:e,optional:t=false}){let n=this.fileSystem.normalizeSeparators(e);if(!await this.fileSystem.exists(n)){if(!t)throw new h("Cannot read file because it does not exist.",{reason:"precondition",details:[`Path: ${n}`]});return null}if(await this.fileSystem.isDirectory(n)){if(!t)throw new h("Cannot read file because the specified path is a directory.",{reason:"precondition",details:[`Path: ${n}`]});return null}try{return this.fileSystem.readTextFile(n)}catch(r){throw h.fromCause(r)}}};var pg=z$1.strictObject({path:z$1.string().min(1),destination:z$1.string().min(1),overwrite:z$1.boolean().optional()}),Ta=class extends I{constructor(){super(pg);}};var cg=z$1.strictObject({path:z$1.string().min(1),optional:z$1.boolean().optional(),result:z$1.string().min(1)}),Ma=class extends I{constructor(){super(cg);}};var Na=class{constructor({fileSystem:e}){this.fileSystem=e;}async execute({path:e}){let t=this.fileSystem.normalizeSeparators(e);if(await this.fileSystem.exists(t)&&!await this.fileSystem.isDirectory(t))throw new h("Cannot create directory because a file with the same name exists.",{reason:"precondition",details:[`Path: ${t}`]});try{await this.fileSystem.createDirectory(t,{recursive:!0});}catch(n){throw h.fromCause(n)}}};var lg=z$1.strictObject({path:z$1.string().min(1)}),$a=class extends I{constructor(){super(lg);}};var La=class{constructor({fileSystem:e,input:t}){this.fileSystem=e,this.input=t;}async execute({path:e,content:t,...n}){let r=n.overwrite===true,i=this.fileSystem.normalizeSeparators(e);if(!r&&await this.fileSystem.exists(i)&&(r=this.input===void 0?false:await this.input.confirm({message:`Path \`${i}\` already exists. Do you want to overwrite it?`,default:false}),!r))throw new h("Failed to write file because the specified path already exists.",{reason:"precondition",details:[`File: ${i}`]});r&&await this.fileSystem.isDirectory(i)&&await this.fileSystem.delete(i,{recursive:true});try{await this.fileSystem.writeTextFile(i,t,{overwrite:r});}catch(a){throw h.fromCause(a)}}};var ug=z$1.strictObject({path:z$1.string().min(1),content:z$1.string(),overwrite:z$1.boolean().optional()}),_a=class extends I{constructor(){super(ug);}};var Fa=class{constructor(e){this.currentVersion=e.currentVersion,this.packageManager=e.packageManager,this.configurationProvider=e.configurationProvider,this.input=e.input,this.output=e.output,this.checkTimeout=e.checkTimeout,this.checkFrequency=e.checkFrequency;}async checkForUpdates(){let e=await this.configurationProvider.get();if(!this.isCheckEnabled(e))return;let t=await this.getLatestVersion();if(t===null||(await this.configurationProvider.save({...e,lastUpdateCheck:Date.now()}),Sd.gte(this.currentVersion,t))||(this.output.announce({semantics:"info",title:"New version",message:`Update your CLI from ${this.currentVersion} \u2192 \`${t}\``}),!(await this.input?.confirm({message:"Would you like to update now?",default:true})??false)))return;let r=this.output.notify("Updating the CLI");try{await this.packageManager.updatePackage("croct",{global:gl,logger:new ge({status:"Updating the CLI",notifier:r})});}catch{let a=await this.packageManager.getPackageUpdateCommand("croct",{global:gl}),s=`${a.name} ${a.arguments?.join(" ")}`;r.alert("Failed to update the CLI automatically"),this.output.log(`Please run the command:
|
|
1850
|
+
\`${s}\``);return}r.confirm("CLI updated successfully!"),this.output.inform("The new version will take effect the next time you run a command");}isCheckEnabled(e){return e.lastUpdateCheck===void 0||Date.now()-e.lastUpdateCheck>this.checkFrequency}getLatestVersion(){let e=new AbortController;return setTimeout(()=>e.abort(),this.checkTimeout),fetch("https://registry.npmjs.org/croct/latest",{signal:e.signal}).then(t=>t.json()).then(t=>t.version).catch(()=>null)}};var ja=class{constructor({fileSystem:e}){this.fileSystem=e;}async execute({path:e,recursive:t=false}){let n=this.fileSystem.normalizeSeparators(e);if(await this.fileSystem.exists(n)){if(!t&&await this.fileSystem.isDirectory(n)&&!await this.fileSystem.isEmptyDirectory(n))throw new h("Cannot delete non-empty directory when `recursive` is false.",{reason:"precondition",details:[`Path: ${n}`]});try{await this.fileSystem.delete(n,{recursive:t});}catch(r){throw h.fromCause(r)}}}};var dg=z$1.strictObject({path:z$1.string().min(1),recursive:z$1.boolean().optional()}),Ua=class extends I{constructor(){super(dg);}};var Wa=class{constructor({projectDirectory:e,fileSystem:t,codemod:n,scanFilter:r}){this.projectDirectory=e,this.fileSystem=t,this.codemod=n,this.scanFilter=r;}async execute(e,t){let{output:n}=t,r=n?.notify("Resolving imports");try{await this.resolveImports(e.path);}finally{r?.stop();}}async resolveImports(e){let t=false,n=_t.fromPattern(e);for await(let r of this.fileSystem.list(this.projectDirectory.get(),this.scanFilter))await n.test(r.name)&&r.type==="file"&&(t=true,await this.codemod.apply(await this.fileSystem.getRealPath(r.name)));if(!t)throw new d("No matching files found for resolving imports.",{reason:"unexpected_result",details:[`Pattern: ${e}`]})}};var gg=z$1.strictObject({path:z$1.string().min(1)}),Va=class extends I{constructor(){super(gg);}};var qa=class{constructor({configurationManager:e,applicationApi:t}){this.configurationManager=e,this.api=t;}async execute(e,t){let{output:n}=t,r=await this.configurationManager.load(),i=e.environment==="production"?r.applications.production:r.applications.development;if(i===void 0)throw new h("The project has no application configured for the selected environment.",{reason:"precondition"});let a=n?.notify("Creating API key"),s;try{s=await this.api.createApiKey({organizationSlug:r.organization,workspaceSlug:r.workspace,applicationSlug:i,name:e.keyName,permissions:e.permissions});}catch(p){throw h.fromCause(p)}finally{a?.stop();}t.set(e.result,s.secret);}};var fg=z$1.strictObject({keyName:z$1.string().min(1),environment:z$1.enum(["development","production"]),permissions:z$1.array(z$1.enum(fe.all().flatMap(o=>[o.toUpperCase(),o.toLowerCase()])).transform(fe.fromValue)).min(1),result:z$1.string().min(1)}),Ha=class extends I{constructor(){super(fg);}};var Ga=class o{constructor(e){this.instances=new Map;this.configuration=e,this.initialDirectory=e.directories.current??e.process.getCurrentDirectory(),this.workingDirectory=new Jo(this.initialDirectory);}static{this.READ_ONLY_COMMANDS=new Set([Fn,fn,yn,Nt,$t,dn,gn,bn,sn]);}static fromDefaults(e){let t=hg("com.croct.cli"),n=new na;return new o({program:e.program??(()=>{throw new d("CLI is running in standalone mode.")}),process:e.process??n,quiet:e.quiet??false,debug:e.debug??false,stateless:e.stateless??false,interactive:e.interactive??!Sg.isCI,version:e.version??"0.0.0",apiKey:e.apiKey,token:e.token,dnd:e.dnd??false,adminTokenDuration:e.adminTokenDuration??7*Xe.LocalTime.SECONDS_PER_DAY,apiKeyTokenDuration:e.apiKeyTokenDuration??30*Xe.LocalTime.SECONDS_PER_MINUTE,cliTokenDuration:e.cliTokenDuration??90*Xe.LocalTime.SECONDS_PER_DAY,cliTokenFreshPeriod:e.cliTokenFreshPeriod??15*Xe.LocalTime.SECONDS_PER_DAY,cliTokenIssuer:e.cliTokenIssuer??"croct.com",deepLinkProtocol:e.deepLinkProtocol??"croct",templateRegistryUrl:e.templateRegistryUrl??new URL("github://croct-tech/templates/templates/registry.json5"),adminUrl:e.adminUrl??new URL("https://app.croct.com"),adminTokenParameter:e.adminTokenParameter??"accessToken",adminGraphqlEndpoint:e?.adminGraphqlEndpoint??new URL("https://app.croct.com/graphql"),directories:{current:e.directories?.current??n.getCurrentDirectory(),config:e.directories?.config??t.config(),cache:e.directories?.cache??t.cache(),data:e.directories?.data??t.data(),home:e.directories?.home??homedir()},verificationLinkDestination:{accountActivation:e.verificationLinkDestination?.accountActivation??"./cli",passwordReset:e.verificationLinkDestination?.passwordReset??"./cli"},emailSubject:{passwordReset:e.emailSubject?.passwordReset??"Forgot password",accountActivation:e.emailSubject?.accountActivation??"Welcome to Croct"}})}welcome(e){let t=!this.configuration.interactive||this.configuration.dnd;return this.execute(new Fn({cliVersion:this.configuration.version,autoUpdater:new Fa({currentVersion:this.configuration.version,input:this.getInput(),configurationProvider:this.getCliConfigurationProvider(),packageManager:this.getNodePackageManager(),output:this.getOutput(),checkFrequency:Xe.LocalTime.MILLIS_PER_SECOND*Xe.LocalTime.SECONDS_PER_HOUR*6,checkTimeout:500}),configurationProvider:this.getCliConfigurationProvider(),deepLinkInstaller:n=>this.deepLink({operation:n?"optionally-update":"optionally-enable"})}),{skipDeepLinkCheck:t||e.skipDeepLinkCheck===true,skipUpdateCheck:t||e.skipUpdateCheck===true})}deepLink(e){return this.execute(new Sa({packageManager:this.getNodePackageManager(),protocolRegistryProvider:this.getProtocolRegistryProvider(),configurationProvider:this.getCliConfigurationProvider(),cliPackage:"croct@latest",protocolHandler:{id:"com.croct.cli",name:"croct-cli",protocol:this.configuration.deepLinkProtocol},io:{input:this.getInput(),output:this.getOutput()}}),e)}open(e){return this.execute(new Lo({program:this.configuration.program,protocol:this.configuration.deepLinkProtocol,configurationProvider:this.getCliConfigurationProvider(),workingDirectory:new Qo(this.configuration.process),fileSystem:this.getFileSystem(),io:{input:this.getInput(),output:this.getOutput()}}),e)}init(e){let{process:t}=this.configuration;return this.execute(new mr({sdkProvider:this.getSdkProvider(),platformProvider:this.getPlatformProvider(),configurationManager:this.getConfigurationManager(),skipConfirmation:new Ro(new _n(new Eo(new Nn({fileSystem:this.getFileSystem(),files:[".git"]})))),api:{user:this.getUserApi(),organization:this.getOrganizationApi(),workspace:this.getWorkspaceApi()},form:{organization:new hr({input:this.getFormInput(),output:this.getOutput(),userApi:this.getUserApi()}),workspace:new Sr({input:this.getFormInput(),output:this.getOutput(),organizationApi:this.getOrganizationApi()}),application:new br({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),slot:new Be({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})},io:{input:this.getInput(),output:this.getOutput()}}),{...e,organization:e.organization??t.getEnvValue("CROCT_ORGANIZATION")??void 0,workspace:e.workspace??t.getEnvValue("CROCT_WORKSPACE")??void 0,devApplication:e.devApplication??t.getEnvValue("CROCT_DEV_APPLICATION")??void 0,prodApplication:e.prodApplication??t.getEnvValue("CROCT_PROD_APPLICATION")??void 0,skipApiKeySetup:e.skipApiKeySetup??t.getEnvValue("CROCT_SKIP_API_KEY_SETUP")!==null})}install(e){return this.execute(new fn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),io:{input:this.getInput(),output:this.getOutput()}}),e)}upgrade(e){return this.execute(new yn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),form:{slotForm:new Be({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),componentForm:new ot({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})},io:{input:this.getInput(),output:this.getOutput()}}),e)}addSlot(e){return this.execute(new Nt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new Be({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}removeSlot(e){return this.execute(new dn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),slotForm:new Be({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}addComponent(e){return this.execute(new $t({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new ot({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}removeComponent(e){return this.execute(new gn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new ot({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}login(e){return this.execute(new dr({authenticator:this.getAuthenticator()}),e)}logout(){return this.execute(new sn({authenticator:this.getAuthenticator(),output:this.getOutput()}),{})}admin(e){return this.execute(new Pr({output:this.getOutput(),pageForm:new Nr({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 bn({configurationManager:this.getConfigurationManager(),fileSystem:this.getFileSystem(),templateForm:new Jr({input:this.getFormInput(),form:{component:new ot({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),slot:new Be({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),experience:new Qr({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),audience:new Br({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 Yr({templateProvider:new jt({provider:new xn(this.getTemplateProvider()),validator:new En}),fileSystem:this.getFileSystem(),action:this.getImportAction(),io:{input:this.getInput(),output:this.getOutput()}})}createApiKey(e){return this.execute(new Go({fileSystem:this.getFileSystem(),configurationManager:this.getConfigurationManager(),api:{user:this.getUserApi(),workspace:this.getWorkspaceApi(),application:this.getApplicationApi()},io:{input:this.getFormInput(),output:this.getOutput()}}),e)}getFormInput(e){return this.getInput()??this.getNonInteractiveInput(e)}getNonInteractiveInput(e){return new zn(new Lr(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 nr({input:this.configuration.process.getStandardInput(),output:this.configuration.process.getStandardOutput(),onAbort:()=>e.exit(),onInteractionStart:()=>e.suspend(),onInteractionEnd:()=>e.resume()});return this.configuration.dnd?new zn(t):t})}getNonInteractiveOutput(e=false){let{configuration:t}=this,n=new an({output:t.process.getStandardOutput(),formatter:this.getLogFormatter(),interactive:false,quiet:e,onExit:()=>t.process.exit(),linkOpener:new Wn(()=>new Vn(n))});return t.process.on("exit",()=>n.stop()),n}getHierarchicalLogger(){return this.share(this.getHierarchicalLogger,()=>new la(this.getLogger()))}getLogger(){return this.share(this.getLogger,()=>{let e=new ua(this.getOutput());return this.configuration.debug?e:new FilteredLogger(e,LogLevel.WARNING)})}getOutput(){return this.share(this.getOutput,()=>{let{configuration:e}=this,t=new an({output:e.process.getStandardOutput(),formatter:this.getLogFormatter(),interactive:this.configuration.interactive,quiet:this.configuration.quiet,onExit:()=>e.process.exit(),linkOpener:new Wn(()=>{let n=new Vn(t);return this.configuration.dnd?n:new Ca(n)})});return e.process.on("exit",()=>t.stop()),t})}getLogFormatter(){return this.share(this.getLogFormatter,()=>new ea)}getTemplateProvider(){return this.share(this.getTemplateProvider,()=>{let e=n=>new Ke({providers:["template.json5","template.json"].map(r=>new It({dataProvider:n,registryProvider:new Ht([{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 Pn({resourceCache:new AutoSaveCache(new InMemoryCache),errorCache:new InMemoryCache,provider:new Ke({providers:[new It({dataProvider:this.traceProvider({label:"ResourceProvider",provider:e(new vt(new Ke({providers:[this.traceProvider({provider:this.createGitHubProvider(t)}),this.traceProvider({provider:new In(t)})]})))}),registryProvider:this.traceProvider({label:"NpmRegistryProvider",provider:new oa(new jt({provider:aa.json(this.traceProvider({provider:this.getHttpProvider()})),validator:new sa}))})}),e(new vt(this.getFileProvider()))]})})})})}getFileProvider(){return this.share(this.getFileProvider,()=>{let e=this.traceProvider({provider:this.getHttpProvider()}),t=this.traceProvider({provider:new di(this.getFileSystem(),this.getScanFilter())}),n=new Ke({providers:[t,this.traceProvider({provider:this.createGitHubProvider(e)}),this.traceProvider({provider:new In(e)})]});return this.traceProvider({label:"FileProvider",provider:new Ke({providers:[t,this.traceProvider({provider:new It({baseUrl:new URL("./",this.configuration.templateRegistryUrl),dataProvider:this.traceProvider({label:"ResourceProvider",provider:n}),registryProvider:new Hi({url:this.configuration.templateRegistryUrl,provider:this.traceProvider({label:"GlobalRegistryProvider",provider:new Pn({errorCache:new InMemoryCache,resourceCache:new AutoSaveCache(new InMemoryCache),provider:new jt({provider:new xn(new vt(n)),validator:new Si})})})})})})]})})})}createGitHubProvider(e){let t=Date.now();return new gi({cache:new AutoSaveCache(new InMemoryCache),provider:new Ke({providers:[new Ke({providers:[new It({dataProvider:e,registryProvider:new Ht([{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 ca({label:t,provider:e,logger:this.getHierarchicalLogger()})}getImportAction(){return this.share(this.getImportAction,()=>{let e=this.getFileSystem(),t=new Map,n={run:new N({action:new at(new $e(()=>new to(n))),validator:new no}),try:new N({action:new at(new $e(()=>new oi(n.run))),validator:new wi}),test:new N({action:new at(new $e(()=>new zi(n.run))),validator:new Fi}),repeat:new N({action:new at(new $e(()=>new To(n.run))),validator:new Do}),print:new N({action:new ji,validator:new Wi}),fail:new N({action:new Vi,validator:new qi}),define:new N({action:new ao,validator:new oo}),prompt:new N({action:new Bi,validator:new Yi}),"change-directory":new N({action:new uo({fileSystem:e,rootDirectory:this.initialDirectory,currentDirectory:this.workingDirectory}),validator:new lo}),"open-link":new N({action:new ro,validator:new io}),"start-server":new N({action:new Xi({serverProvider:this.getServerProvider(),serverFactory:this.getServerFactory(),packageManager:this.getPackageManager(),serverMap:t}),validator:new eo}),"stop-server":new N({action:new wa({serverMap:t}),validator:new so}),"check-dependency":new N({action:new mi({packageManager:this.getPackageManager()}),validator:new Pi}),download:new N({action:new Xr({fileSystem:e,provider:this.getFileProvider(),codemod:new Jt({codemods:{"**/*.{js,jsx,ts,tsx}":new Qt(this.getNodeImportResolverCodemod(),new Jt({codemods:{"**/*.{js,jsx}":new Qt(new qe({fileSystem:e,codemod:new We({codemod:new va,languages:["typescript","jsx"]})}))}}),new Ve(this.getJavaScriptFormatter()))}})}),validator:new Ci}),"resolve-import":new N({action:new Wa({projectDirectory:this.workingDirectory,fileSystem:e,scanFilter:this.getScanFilter(),codemod:new Jt({codemods:{"**/*.{js,jsx,ts,tsx}":new Qt(this.getNodeImportResolverCodemod(),new Ve(this.getJavaScriptFormatter()))}})}),validator:new Va}),install:new N({action:new ka({packageManager:this.getPackageManager()}),validator:new Aa}),"add-dependency":new N({action:new ei({packageManager:this.getPackageManager()}),validator:new Ai}),"execute-package":new N({action:new mo({processObserver:this.configuration.process,packageManager:this.getPackageManager(),packageManagerProvider:this.getPackageManagerRegistry(),workingDirectory:this.workingDirectory,commandExecutor:this.getAsynchronousCommandExecutor(),commandTimeout:3*60*1e3,sourceChecker:{test:r=>r.protocol==="file:"||`${r}`.startsWith("https://github.com/croct-tech")}}),validator:new go}),"locate-path":new N({action:new ti({projectDirectory:this.workingDirectory,fileSystem:e,scanFilter:this.getScanFilter()}),validator:new Ei}),"move-path":new N({action:new Ea({fileSystem:e}),validator:new Ta}),"delete-path":new N({action:new ja({fileSystem:e}),validator:new Ua}),"read-file":new N({action:new Oa({fileSystem:e}),validator:new Ma}),"write-file":new N({action:new La({fileSystem:e,input:this.getInput()}),validator:new _a}),"replace-file-content":new N({action:new ni({fileSystem:e}),validator:new Oi}),"create-directory":new N({action:new Na({fileSystem:e}),validator:new $a}),"integrate-croct":new N({action:new ra({callback:async()=>{if(!await this.getConfigurationManager().isInitialized())return this.init({})}}),validator:new ia}),"add-slot":new N({action:new ri({installer:(r,i)=>{let a=this.getNonInteractiveOutput(true);return this.execute(new Nt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new Be({input:this.getNonInteractiveInput(),output:a,workspaceApi:this.getWorkspaceApi()}),io:{output:a}}),{slots:r,example:i})}}),validator:new Ti}),"add-component":new N({action:new ii({installer:r=>{let i=this.getNonInteractiveOutput(true);return this.execute(new $t({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new ot({input:this.getNonInteractiveInput(),output:i,workspaceApi:this.getWorkspaceApi()}),io:{output:i}}),{components:r})}}),validator:new Di}),"create-api-key":new N({action:new qa({applicationApi:this.getApplicationApi(),configurationManager:this.getConfigurationManager()}),validator:new Ha}),"create-resource":new N({action:new pi({configurationManager:this.getConfigurationManager(),matcher:new li({workspaceApi:this.getWorkspaceApi()}),api:{user:this.getUserApi(),workspace:this.getWorkspaceApi(),organization:this.getOrganizationApi()},mappingForm:new ci({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 Mi}),"format-code":new N({action:new $i({formatter:this.getCodeFormatter()}),validator:new Li}),import:new N({action:new at(new $e(()=>new Ii({runner:n.run,templateProvider:new xi({evaluator:new bi({functions:Ls}),validator:new En,templateProvider:this.getTemplateProvider(),fileProvider:new vt(this.getFileProvider())}),variables:this.getActionVariables()}))),validator:new Ni})};return n.import})}getActionVariables(){let e=t=>new URL(t,this.configuration.adminUrl).toString();return {packageManager:te.transient(()=>({name:this.getPackageManager().getName()})),project:{features:te.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{features:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),quotas:te.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{quotas:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),organization:te.transient(async()=>{let{organization:t}=await this.getConfigurationManager().load();return {slug:t,url:e(`organizations/${t}`)}}),workspace:te.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load();return {slug:n,url:e(`organizations/${t}/workspaces/${n}`)}}),application:te.transient(async()=>{let{organization:t,workspace:n,applications:r}=await this.getConfigurationManager().load(),i=`organizations/${t}/workspaces/${n}/applications/`,a=r.production;return {development:{slug:r.development,url:e(i+r.development),publicId:te.transient(async()=>{let p=await this.getWorkspaceApi().getApplication({organizationSlug:t,workspaceSlug:n,applicationSlug:r.development});if(p===null)throw new $("Development application not found.",{reason:"not_found"});return p.publicId})},production:{slug:r.production,url:e(i+r.production),publicId:a===void 0?a:te.transient(async()=>{let p=await this.getWorkspaceApi().getApplication({organizationSlug:t,workspaceSlug:n,applicationSlug:a});if(p===null)throw new $("Production application not found.",{reason:"not_found"});return p.publicId})}}}),path:te.transient(async()=>{let t=this.getSdk(),n=await this.getConfigurationManager().load();return t.getPaths(n)}),platform:te.transient(async()=>await this.getPlatformProvider().get()??"unknown"),server:te.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 ui({retry:{maxAttempts:3,delay:1e3}}))}getAuthenticator(){return this.share(this.getAuthenticator,()=>{if(this.configuration.apiKey!==void 0)return new Zo({apiKey:this.configuration.apiKey,clock:this.getClock(),tokenDuration:this.configuration.apiKeyTokenDuration});if(this.configuration.token!==void 0)return new Pa({token:this.configuration.token});let e=this.getFormInput(),t=new vr({input:e,output:this.getOutput(),userApi:this.getUserApi(true),form:{signIn:new xr({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 wr({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 Bo({cacheKey:"token",cacheProvider:new Yo({clock:this.getClock(),clockSkewTolerance:5,tokenFreshPeriod:this.configuration.cliTokenFreshPeriod,tokenIssuer:()=>n.issueToken({duration:this.configuration.cliTokenDuration}),cacheProvider:this.selectCacheProvider(()=>new wn({fileSystem:this.getFileSystem(),directory:this.configuration.directories.config,useKeyAsFileName:true}))}),authenticator:new zr({default:this.configuration.interactive?t:new $r({authenticator:t,instruction:{message:"Authentication required.",suggestions:["Run `login` to authenticate"],reason:"precondition"}}),credentials:t})});return this.configuration.interactive?new qo({authenticator:r,invitationForm:new Vo({output:this.getOutput(),input:e,userApi:this.getUserApi(true)})}):r})}getSdk(){return this.share(this.getSdk,()=>{let e=new Gt(this.getSdkProvider(),new $e(()=>{throw new V("No suitable SDK detected.",{reason:"not_supported",suggestions:["Make sure you are running the command in the project root directory."]})}));return new Ao(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 qt({discriminator:async()=>await this.getPlatformProvider().get()??i,mapping:{javascript:()=>new sr({...r,bundlers:["vite","parcel","tsup","rollup"]}),react:()=>new pr({...r,importResolver:n,codemod:{provider:new Ve(e,new qe({fileSystem:this.getFileSystem(),codemod:new We({languages:["typescript","jsx"],codemod:new ft({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 ur({...r,userApi:this.getUserApi(),applicationApi:this.getApplicationApi(),importResolver:n,codemod:{middleware:new Ve(e,new qe({fileSystem:this.getFileSystem(),codemod:new We({languages:["typescript","jsx"],codemod:new Or({matcherPattern:"/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",import:{module:"@croct/plug-next/middleware",middlewareName:"middleware",middlewareFactoryName:"withCroct",configName:"config",matcherName:"matcher"}})})})),appRouterProvider:new Ve(e,new qe({fileSystem:this.getFileSystem(),codemod:new We({languages:["typescript","jsx"],codemod:new ft({fallbackToNamedExports:false,fallbackCodemod:new Rr({provider:{component:"CroctProvider",module:"@croct/plug-next/CroctProvider"}}),wrapper:{module:"@croct/plug-next/CroctProvider",component:"CroctProvider"},targets:{variable:"children"}})})})),pageRouterProvider:new Ve(e,new qe({fileSystem:this.getFileSystem(),codemod:new We({languages:["typescript","jsx"],codemod:new ft({fallbackToNamedExports:false,fallbackCodemod:new mn({provider:{component:"CroctProvider",module:"@croct/plug-next/CroctProvider"}}),wrapper:{module:"@croct/plug-next/CroctProvider",component:"CroctProvider"},targets:{component:"Component"}})})})),fallbackProvider:new Ve(e,new qe({fileSystem:this.getFileSystem(),codemod:new We({languages:["typescript","jsx"],codemod:new ft({fallbackToNamedExports:false,fallbackCodemod:new mn({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 ko(new qt({discriminator:async()=>await this.getPlatformProvider().get()??e,mapping:{javascript:()=>this.getJavaScriptFormatter(),react:()=>this.getJavaScriptFormatter(),nextjs:()=>this.getJavaScriptFormatter(),[e]:()=>{throw new V("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 vo(new Map(Object.entries(this.getPackageManagers()))))}getPackageManagers(){return this.getNodePackageManagers()}getPackageManager(){return this.share(this.getPackageManager,()=>new Mn(new Gt(this.getNodePackageManagerProvider(),new $e(()=>{throw new V("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 Mn(new Gt(this.getNodePackageManagerProvider(),new Ht(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 Ln(new Wo(new wt({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new Uo({process:this.configuration.process,variable:"npm_config_user_agent",value:new RegExp(`^${r}`)})}))}),new wt({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new _n(new jo({packageManager:r,fileSystem:t,projectDirectory:this.workingDirectory}),new Nn({fileSystem:t,files:n[r]}))}))}),new wt({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new xa({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 vn,r={fileSystem:e,projectDirectory:this.workingDirectory,packageValidator:n};return {npm:new st({...r,agent:new fo(t)}),yarn:new st({...r,agent:new yo(t)}),bun:new st({...r,agent:new ho(t)}),pnpm:new st({...r,agent:new So(t)})}})}getServerProvider(){return this.share(this.getServerProvider,()=>{let e=Symbol("unknown");return new qt({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 Ki({packageManager:this.getNodePackageManager(),factory:this.getServerFactory(),parsers:[new Gi,new Zi,new Ji,new Qi]}))}getServerFactory(){return this.share(this.getServerFactory,()=>new co({commandExecutor:this.getAsynchronousCommandExecutor(),workingDirectory:this.workingDirectory,startupTimeout:60*1e3,startupCheckDelay:1.5*1e3,lookupMaxPorts:30,lookupTimeout:2*1e3,processObserver:this.configuration.process}))}getJavaScriptFormatter(){return this.share(this.getJavaScriptFormatter,()=>new Dr({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 bo({fileSystem:this.getFileSystem(),tsConfigLoader:this.getTsConfigLoader(),projectDirectory:this.workingDirectory}))}getTsConfigLoader(){return this.share(this.getTsConfigLoader,()=>new ba({fileSystem:this.getFileSystem(),tsconfigValidator:new Io}))}getAsynchronousCommandExecutor(){return this.share(this.getAsynchronousCommandExecutor,()=>new Ia({executableLocator:this.getExecutableLocator(),commandExecutor:this.getCommandExecutor()}))}getSynchronousCommandExecutor(){return this.getCommandExecutor()}getCommandExecutor(){return this.share(this.getCommandExecutor,()=>new Co({currentDirectory:this.workingDirectory,windows:this.configuration.process.getPlatform()==="win32"}))}getExecutableLocator(){return this.share(this.getExecutableLocator,()=>{let{process:e}=this.configuration;return new Fo({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 st({projectDirectory:this.workingDirectory,packageValidator:new vn,fileSystem:this.getFileSystem(),agent:new xo});return new Ln(new wt({candidates:[{value:"nextjs",condition:new $n({packageManager:e,dependencies:["next"]})},{value:"react",condition:new $n({packageManager:e,dependencies:["react"]})},{value:"javascript",condition:new wo({packageManager:e})}]}),this.workingDirectory)})}getConfigurationManager(){return this.share(this.getConfigurationManager,()=>{let e=this.getOutput(),t=new gr({fileSystem:this.getFileSystem(),validator:new yi,projectDirectory:this.workingDirectory});return new _o({workingDirectory:this.workingDirectory,configurationProvider:this.getCliConfigurationProvider(),manager:new ai(this.configuration.interactive&&!this.isReadOnlyMode()?new Mr({manager:t,initializer:{initialize:async()=>{await this.init({}),e.break();}}}):t)})})}getNodeImportResolverCodemod(){return this.share(this.getNodeImportResolverCodemod,()=>{let e=this.getFileSystem(),t=this.getScanFilter();return new ma({fileSystem:e,rootPath:this.workingDirectory,filter:(n,r)=>r<=10&&t(n,r),importResolver:this.getNodeImportResolver(),importCodemod:new qe({fileSystem:e,codemod:new We({languages:["typescript","jsx"],codemod:new ga})}),exportMatcher:{test:(n,{names:r})=>r.length===0?true:pl(n).some(i=>r.includes(i))}})})}getScanFilter(){return this.share(this.getScanFilter,()=>{let e=new Oo({fileSystem:this.getFileSystem(),workingDirectory:this.workingDirectory});return async t=>!await e.test(t)})}getUserApi(e=false){return e?new ln(this.getGraphqlClient(true)):this.share(this.getUserApi,()=>new ln(this.getGraphqlClient()))}getOrganizationApi(){return this.share(this.getOrganizationApi,()=>new fr(this.getGraphqlClient(),this.getHierarchyResolver()))}getWorkspaceApi(){return this.share(this.getWorkspaceApi,()=>new yr(this.getGraphqlClient(),this.getHierarchyResolver()))}getApplicationApi(){return this.share(this.getApplicationApi,()=>new Ir(this.getGraphqlClient(),this.getHierarchyResolver()))}getHierarchyResolver(){return this.share(this.getHierarchyResolver,()=>new fa(this.getGraphqlClient(),new InMemoryCache))}getGraphqlClient(e=false){return e?new pn({endpoint:this.configuration.adminGraphqlEndpoint,tokenProvider:{getToken:()=>this.getAuthenticator().getToken()}}):this.share(this.getGraphqlClient,()=>{let t=this.getAuthenticator();return new pn({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 Fr({platform:e.process.getPlatform(),commandExecutor:this.getSynchronousCommandExecutor(),timeout:2e3,listener:new Xo({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:Xe.Instant.now(n).getSeconds()})}getEmailLinkGenerator(){return this.share(this.getEmailLinkGenerator,()=>new jr({detector:new Ur(new Wr,new Vr),templates:{google:new qr,icloud:new Hr,microsoft:new Kr,proton:new Gr,yahoo:new Zr}}))}getClock(){return yl.SystemClock.UTC}getProtocolRegistryProvider(){return this.share(this.getProtocolRegistryProvider,()=>new $e(()=>{let e=this.getFileSystem(),{process:t}=this.configuration;switch(t.getPlatform()){case "darwin":{let n=e.joinPaths(this.configuration.directories.data,"apps");return new ya({output:this.getOutput(),macOsRegistry:new Mo({fileSystem:e,appDirectory:n,commandExecutor:this.getAsynchronousCommandExecutor()}),firefoxRegistry:ha.macOs({fileSystem:e,homeDirectory:this.configuration.directories.home,appPath:e.joinPaths(n,`${this.configuration.deepLinkProtocol}.app`)})})}case "win32":return new No({commandExecutor:this.getAsynchronousCommandExecutor()});case "linux":return new $o({fileSystem:e,homeDirectory:this.configuration.directories.home,commandExecutor:this.getAsynchronousCommandExecutor()});default:return null}}))}selectCacheProvider(e){return this.configuration.stateless?new InMemoryCache:e()}getCliConfigurationProvider(){return this.share(this.getCliConfigurationProvider,()=>{let e=this.getFileSystem();return new Ko({fileSystem:e,configurationProvider:new Ho({cacheKey:"config.json",cache:this.selectCacheProvider(()=>new wn({fileSystem:e,directory:this.configuration.directories.config,useKeyAsFileName:true})),validator:new zo})})})}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 ae: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 h: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(`
|
|
1907
1851
|
`);return new d(`${e.message}
|
|
1908
1852
|
|
|
1909
1853
|
\u25B6\uFE0F **Trace**
|
|
1910
|
-
${t}`,e.help)}break;case e instanceof ut: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
|
|
1854
|
+
${t}`,e.help)}break;case e instanceof ut: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 Fs={version:"0.8.2"};function hl(o){let e=new qs().name("croct").description("Manage your Croct projects").enablePositionalOptions().option("--cwd <path>","The working directory.",S=>{try{return realpathSync(S)}catch{throw new De("The path does not exist.")}}).addOption(new X("--api-key <key>","The API key to use for authentication.").env("CROCT_API_KEY").argParser(S=>{try{return ApiKey.parse(S)}catch{throw new De("The API key is malformed.")}}).conflicts("token")).addOption(new X("--token <token>","The JWT-formatted token to use for authentication.").env("CROCT_TOKEN").argParser(S=>{let P;try{P=Token.parse(S);}catch{throw new De("The token is malformed.")}if(!P.isValidNow())throw new De("The token is expired.");return P})).option("--registry <url>","The template registry.",S=>{if(!URL.canParse(S))throw new De("Malformed URL.");return S}).option("--no-interaction","Run the CLI in non-interactive mode.").addOption(new X("--stateless","Run the CLI without saving any state locally.").env("CROCT_STATELESS").default(false)).addOption(new X("--dnd","Run the CLI with minimal interaction and interruption.").env("CROCT_DND").default(false)).addOption(new X("-q, --quiet","Disable output messages.").default(false).implies({interaction:false})).option("--debug","Enable debug mode.").version(Fs.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 S=>{await o.cli?.open({url:S});});let t=e.command("login").description("Authenticate your user."),n=new X("-u, --username <username>","The email."),r=new X("-p, --password <password>","The password.");t.command("credentials",{isDefault:true}).description("Authenticate using credentials.").addOption(o.interactive?n:n.makeOptionMandatory()).addOption(o.interactive?r:r.makeOptionMandatory()).action(async S=>{await o.cli?.login({method:"credentials",username:S.username,password:S.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 S=>{await o.cli?.admin({page:S!==void 0?S.join(" "):o.interactive?void 0:"/"});});let i=new X("--wor <workspace-slug>","The workspace slug."),a=new X("--org <organization-slug>","The organization slug."),s=new X("--dev-app <application-slug>","The development application slug."),p=new X("--prod-app <application-slug>","The production application slug.");e.command("init").description("Configure the project.").option("-o, --override","Override any existing configuration.").addOption(new X("-n, --new <resource>","The resources to create.").choices(["organization","org","workspace","wor","application","app"])).addOption(new X("-s, --sdk <platform>","The SDK to use.").choices(["javascript","react","next"])).addOption(new X("--skip-api-key-setup","Opt-out of API key setup.").default(false).env("CROCT_SKIP_API_KEY_SETUP")).addOption(o.interactive?a:a.makeOptionMandatory()).addOption(o.interactive?i:i.makeOptionMandatory()).addOption(o.interactive?s:s.makeOptionMandatory()).addOption(p).action(async S=>{await o.cli?.init({override:S.override,new:(()=>{switch(S.new){case "organization":case "org":return "organization";case "workspace":case "wor":return "workspace";case "application":case "app":return "application";default:return}})(),sdk:S.sdk,organization:S.org,workspace:S.wor,devApplication:S.devApp,prodApplication:S.prodApp,skipApiKeySetup:S.skipApiKeySetup});}),e.command("install").description("Install content and types.").action(async()=>{await o.cli?.install({});}),e.command("update").description("Update content and types.").action(async()=>{await o.cli?.install({clean:true});}),e.command("upgrade").description("Upgrade components and slots to the latest version.").option("-s, --slots <slots...>","The slots to upgrade.").option("-c, --components <components...>","The components to upgrade.").action(async S=>{await o.cli?.upgrade({slots:S.slots??(S.components!==void 0?[]:void 0),components:S.components??(S.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(S,P)=>{await o.cli?.addSlot({slots:S,example:P.example});}),c.command("component").description("Add a component to your project.").argument(o.interactive?"[components...]":"<components...>").action(async S=>{await o.cli?.addComponent({components:S});});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 S=>{await o.cli?.removeSlot({slots:S});}),l.command("component").description("Remove a component from your project.").argument(o.interactive?"[components...]":"<components...>").action(async S=>{await o.cli?.removeComponent({components:S});});let u=e.command("create").description("Create a resource in your project.");u.command("template").description("Create a template from your project.").addArgument(new Hs("<path>","The path to the file.").argOptional()).option("-e, --empty","Create an empty template.").action(async(S,P)=>{await o.cli?.createTemplate({file:S,empty:P.empty});});let g=new X("--permissions <permissions...>","The permissions of the API key.").argParser(S=>S.split(",").map(P=>{try{return fe.fromValue(P)}catch{throw new De(`Unknown permission "${P}".`)}})),y=new X("--env <environment>","The environment of the API key.").choices(["prod","dev"]).argParser(S=>S==="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 S=>{await o.cli?.createApiKey({name:S.name,permissions:S.permissions,environment:S.env,copy:S.copy});});let C={},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(S,P)=>{await o.cli?.useTemplate({template:S,options:Object.fromEntries(Object.entries(P).map(([B,Se])=>[C[B],Se]))});});for(let[S,P]of Object.entries(o.template??{})){let B=`--${S}${P.type!=="boolean"?" <value>":""}`,Se=new X(B,P.description).makeOptionMandatory(P.required===true);switch(P.type){case "string":P.choices!==void 0&&P.choices.length>0&&Se.choices(P.choices);break;case "number":Se.argParser(H=>{let le=Number.parseFloat(H);if(Number.isNaN(le))throw new De("The value must be a number.");return le});break;case "array":Se.argParser(H=>{let le;try{le=JSON.parse(H);}catch{}if(le===void 0||!Array.isArray(le))throw new De("The value must be a JSON array.");return le});break;case "object":Se.argParser(H=>{let le;try{le=JSON.parse(H);}catch{throw new De("The JSON is malformed.")}if(typeof le!="object"||le===null)throw new De("The value must be a JSON object.")});break}C[Se.attributeName()]=S,v.addOption(Se);}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 Cg(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 kg(o){return o.length>=2&&["enable","disable"].includes(o[0])&&o[1]==="deep-link"}async function js(o=process.argv,e=true){let t=hl({interactive:true}).parse(o),n=t.opts(),r=Ga.fromDefaults({program:p=>js(t.args.slice(0,2).concat(p)),version:Fs.version,quiet:n.quiet,debug:n.debug,interactive:n.interaction?void 0:false,stateless:n.stateless,apiKey:n.apiKey,token:n.token,dnd:n.dnd,templateRegistryUrl:n.registry===void 0?void 0:new URL(n.registry)}),i=Cg(t.args),a=i!==null?await r.getTemplateOptions(i).catch(()=>null):void 0,s=hl({cli:r,interactive:n.interaction,template:a});e&&await r.welcome({skipDeepLinkCheck:kg(t.args)}),await s.parseAsync(o);}js();
|