croct 0.12.2 → 0.12.13
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 -133
- package/package.json +8 -7
package/index.js
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {createRequire}from'module';import {Command,InvalidOptionArgumentError,Option,Argument}from'@commander-js/extra-typings';import {createReadStream
|
|
3
|
-
var
|
|
4
|
-
`),i
|
|
2
|
+
import {createRequire}from'module';import {Command,InvalidOptionArgumentError,Option,Argument}from'@commander-js/extra-typings';import {realpathSync,createReadStream}from'fs';import {ApiKey}from'@croct/sdk/apiKey';import {Token}from'@croct/sdk/token';import {InMemoryCache,AutoSaveCache,NoopCache}from'@croct/cache';import {LocalTime,Instant,TimeZone,LocalDateTime}from'@croct/time';import {SystemClock}from'@croct/time/clock/systemClock.js';import {homedir,tmpdir}from'os';import ud from'xdg-app-paths';import os from'ci-info';import {FilteredLogger,LogLevel}from'@croct/logging';import Rc from'prompts';import {PassThrough,Readable}from'stream';import va from'cli-cursor';import et from'chalk';import xa from'readline';import {WriteStream}from'tty';import _c from'strip-ansi';import Oc from'is-unicode-supported';import {render}from'@croct/md-lite/rendering.js';import Tc 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 {JsonParser,JsonObjectNode,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$1}from'@babel/parser';import {randomUUID,createHash}from'crypto';import {parse,print}from'recast';import Ma from'recast/parsers/_babel_options.js';import {stringSimilarity}from'string-similarity-js';import {realpath,lstat,readdir,symlink,link,mkdir,writeFile,rm as rm$1,rename,readFile,mkdtemp,cp as cp$1}from'fs/promises';import {delimiter,extname,sep,basename,dirname,relative,isAbsolute,join}from'path';import {minimatch,Minimatch}from'minimatch';import {deepEqual}from'fast-equals';import {z,ZodPromise,ZodOptional,ZodTuple,ZodArray,ZodRecord,ZodObject,ZodEffects,ZodAny,ZodPipeline,ZodUnion,ZodDiscriminatedUnion}from'zod';import ze from'jsep';import zl from'@jsep-plugin/object';import $l from'@jsep-plugin/spread';import Fl from'@jsep-plugin/regex';import Jp from'is-plain-obj';import am from'semver';import {spawn,spawnSync}from'child_process';import um from'ignore';import Im from'clipboardy';import yc from'boxen';import Re from'process';import {AsyncLocalStorage}from'async_hooks';import {parse as parse$2}from'ini';import Gm from'@babel/plugin-transform-typescript';import Jm from'@babel/plugin-syntax-decorators';import Bm from'open';import wc from'is-installed-globally';createRequire(import.meta.url);
|
|
3
|
+
var Ac=Object.defineProperty;var Ec=(a,e)=>{for(var t in e)Ac(a,t,{get:e[t],enumerable:true});};var kn=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,i)=>({title:n.label,value:`${i}`,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]:" "},i=`Press <${e.key}> to continue`,o=e.key!==void 0?n[e.key]??e.key:void 0,r=false;return this.interact({type:"invisible",message:e.message,validate:s=>o===void 0||s===o?true:i,onState:function(p){if(!r){if(p.value===""){this.error&&e.key!==t.enter&&this.bell();return}o===void 0||p.value===o?(r=true,this.submit()):(this.bell(),this.reset(),o!==void 0&&(this.error=true,this.errorMsg=i));}}})}async interact(e,t){this.configuration.onInteractionStart?.();let{output:n,onAbort:i}=this.configuration,o,r={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
|
+
`),o=i());}};try{return await Rc(r,t).then(s=>s.value??o)}finally{this.configuration.onInteractionEnd?.();}}};var Ve=Oc(),Lt={neutral:"cyan",info:"blue",error:"red",warning:"yellow",success:"green",secondary:"grey"},zc={neutral:Ve?"\u279C":">",info:Ve?"\u2139":"i",error:Ve?"\u2718":"\xD7",warning:Ve?"\u26A0":"\u203C",success:Ve?"\u2714":"\u221A",secondary:Ve?"\u21B3":"\u203A"};function Q(a,e={}){let t=e.basic===true?a:$c(a);if(Ve||(t=strip(t)),e.text!==void 0&&(t=et[Lt[e.text]](t)),e.icon!==void 0){let{semantics:n,symbol:i}=e.icon;t=i!==void 0?`${et[Lt[n]](i[Ve?"unicode":"ascii"])} ${t}`:`${et[Lt[n]](zc[n])} ${t}`;}return t}function $c(a){return render(a,{fragment:e=>e.children.join(""),text:e=>e.content,bold:e=>et.bold(e.children),italic:e=>et.italic(e.children),strike:e=>et.strikethrough(e.children),code:e=>et.cyan(e.content),link:e=>Tc(e.children,e.href,{fallback:(t,n)=>t.includes(n)?t:`${t} (${n})`}),image:e=>unescape(e.source),paragraph:e=>`${e.children.join("")}
|
|
5
5
|
|
|
6
|
-
`}).trim()}var
|
|
7
|
-
`).map(p=>t===0?1:Math.ceil([
|
|
8
|
-
`);}e&&this.lineCount>
|
|
9
|
-
${Q(e.subtitle,{text:"secondary",icon:{semantics:"secondary"}})}`),n}static getSemantics(e){return e==="loading"||e==="pending"?"neutral":e}},An=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,
|
|
10
|
-
`);}format(e,t,n="neutral"){let
|
|
11
|
-
${Q(t,{text:n,icon:{semantics:n,symbol:{unicode:"\u21B3",ascii:"\u203A"}}})}`),
|
|
6
|
+
`}).trim()}var ss=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"].map(a=>et.cyan(a)),wa=class a{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(i=>({title:i.title,subtitle:i.subtitle,status:n.status??"pending",task:i.task}));}suspend(){this.active&&(this.stopRendering(true),va.show());}stop(e){this.active&&(this.active=false,this.stopRendering(e!==void 0?!e:this.options.clear===true),va.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&&(va.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++)xa.moveCursor(this.output,0,-1),xa.clearLine(this.output,0);this.lineCount=0;}render(e=false){let t=this.output instanceof WriteStream?this.output.columns:0,n=[],i=0;for(let o of this.tasks){let r=this.formatTask(o);i=r.split(`
|
|
7
|
+
`).map(p=>t===0?1:Math.ceil([..._c(p)].length/t)).reduce((p,c)=>p+c,i),n.push(`${r}${e?"\x1B[0K":""}
|
|
8
|
+
`);}e&&this.lineCount>i?this.clear():xa.moveCursor(this.output,0,-this.lineCount);for(let o of n)this.output.write(o);this.lineCount=i;}formatTask(e){let t=a.getSemantics(e.status),n=e.status==="loading"?`${ss[this.frame%ss.length]} ${Q(e.title)}`:Q(e.title,{icon:{semantics:t,symbol:e.status==="pending"?{unicode:"\u25F7",ascii:"\u25A0"}:void 0}});return e.subtitle!==void 0&&(n+=`
|
|
9
|
+
${Q(e.subtitle,{text:"secondary",icon:{semantics:"secondary"}})}`),n}static getSemantics(e){return e==="loading"||e==="pending"?"neutral":e}},An=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,i)=>{t.setStatus(0,{status:"loading",title:n,subtitle:i});},confirm:(n,i)=>{t.setStatus(0,{status:"success",title:n,subtitle:i}),t.stop(true);},alert:(n,i)=>{t.setStatus(0,{status:"error",title:n,subtitle:i}),t.stop(true);},warn:(n,i)=>{t.setStatus(0,{status:"warning",title:n,subtitle:i}),t.stop(true);}}}monitor(e){let t=this.addWatcher(e),n=t.start();return {wait:()=>n,stop:()=>t.stop()}}addWatcher(e,t={}){for(let i of this.watchers)i.suspend();let n=new wa(e.tasks,this.output,{clear:e.clear,concurrent:e.concurrent,...t,onStop:i=>this.removeWatcher(i)});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 En=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(i=>this.notify(i.title,e.clear)),n=e.concurrent===true?Promise.all(e.tasks.map((i,o)=>i.task(t[o]))):e.tasks.reduce((i,o,r)=>i.then(()=>o.task(t[r])),Promise.resolve());return {stop:()=>{t.forEach(i=>i.stop(false));},wait:()=>n.then(()=>{})}}notify(e,t=false){let n=(o,r,s,p=!t)=>{!this.stopped&&!i.stopped&&p&&this.log(o??i.lastStatus,r??i.latestDetails,s);let c=this.notifiers.indexOf(i);c!==-1&&this.notifiers.splice(c,1);},i={stopped:false,lastStatus:e,latestDetails:void 0,stop:(o=false)=>{n(i.lastStatus,i.latestDetails,"neutral",o);},update:(o,r)=>{i.lastStatus=o??i.lastStatus,i.latestDetails=r;},confirm:(o,r)=>{n(o,r,"success");},alert:(o,r)=>{n(o,r,"error");},warn:(o,r)=>{n(o,r,"warning");}};return this.notifiers.push(i),i}log(e,t,n){this.output.write(`${this.format(e,t,n)}
|
|
10
|
+
`);}format(e,t,n="neutral"){let i=Q(e,{icon:{semantics:n}});return t!==void 0&&(i+=`
|
|
11
|
+
${Q(t,{text:n,icon:{semantics:n,symbol:{unicode:"\u21B3",ascii:"\u203A"}}})}`),i}};var Ut=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 An(this.output):new En(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(`
|
|
12
12
|
`);}announce(e){this.write(`${this.formatter.formatCallout(e)}
|
|
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
|
|
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 i=this.taskMonitor.monitor(e(t,o=>{i.stop(),n(o);}));}):this.taskMonitor.monitor(e).wait()}report(e){this.stop(),this.write(`${this.formatter.formatError(e)}
|
|
14
14
|
`,true);}exit(){return this.stop(),this.onExit()}writeLog(e,t){this.write(`${Q(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 a extends Error{constructor(e,t={}){super(e),this.help=t,this.reason=t.reason??"other",Object.setPrototypeOf(this,a.prototype);}static formatMessage(e){let t=a.extractMessage(e).trim();return t.length===0?t:t.charAt(0).toUpperCase()+t.slice(1)+(/^[^\n.]+$/.test(t)?".":"")}static formatCause(e){let t=a.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 X=class a extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,a.prototype);}};var
|
|
16
|
-
`);if(n.length<2)return t.join("");let
|
|
17
|
-
`).trim()}function gt(a){return a.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 ae=class a{constructor({notifier:e,status:t}){this.notifier=e,this.status=t;}log(e){let t=a.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
|
|
15
|
+
`);}write(e,t=false){(!this.quiet||t)&&(this.suspend(),this.output.write(e),this.resume());}};var d=class a extends Error{constructor(e,t={}){super(e),this.help=t,this.reason=t.reason??"other",Object.setPrototypeOf(this,a.prototype);}static formatMessage(e){let t=a.extractMessage(e).trim();return t.length===0?t:t.charAt(0).toUpperCase()+t.slice(1)+(/^[^\n.]+$/.test(t)?".":"")}static formatCause(e){let t=a.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 X=class a extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,a.prototype);}};var D=class a{constructor(e,t,n){this.min=t,this.max=n,this.versions=e??[];}static isValid(e){try{return a.parse(e),!0}catch{return false}}static between(e,t){if(e===t)return new a([e]);if(e>t)throw new Error(`Out of order range ${e}-${t}`);return new a(void 0,e,t)}static of(e){return new a([e])}static either(...e){if(e.length===0)throw new Error("No versions specified.");return new a([...new Set(e)].sort((t,n)=>t-n))}static parse(e){if(/^\d+$/.test(e))return new a([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?a.between(Number.parseInt(t.min,10),Number.parseInt(t.max,10)):a.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 i=e;i<=t;i++)n.push(i);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 r=e.getExactVersion();return this.getMinVersion()<=r&&r<=this.getMaxVersion()}let i=this.getMinVersion(),o=this.getMaxVersion();return e.getVersions().some(r=>i<=r&&r<=o)}let t=this.getVersions(),n=e.getVersions();return t.length===0||n.length===0?false:t.some(i=>n.includes(i))}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 o=e.getExactVersion();return this.getMinVersion()<=o&&o<=this.getMaxVersion()}let n=this.getMinVersion(),i=this.getMaxVersion();return e.getVersions().every(o=>n<=o&&o<=i)}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 a.between(e.getExactVersion()+1,this.getMaxVersion());if(this.getMaxVersion()===e.getExactVersion())return a.between(this.getMinVersion(),e.getExactVersion()-1)}else if(e.isRange()){if(this.getMinVersion()===e.getMinVersion())return a.between(e.getMaxVersion()+1,this.getMaxVersion());if(this.getMaxVersion()===e.getMaxVersion())return a.between(this.getMinVersion(),e.getMinVersion()-1)}else if(e.isSet()&&e.getVersions().every((o,r)=>o===e.getMinVersion()+r)){if(this.getMinVersion()===e.getMinVersion())return a.between(e.getMaxVersion()+1,this.getMaxVersion());if(this.getMaxVersion()===e.getMaxVersion())return a.between(this.getMinVersion(),e.getMinVersion()-1)}}if(e.isRange()){let n=e.getMinVersion(),i=e.getMaxVersion();return a.either(...this.getVersions().filter(o=>o<n||o>i))}let t=e.getVersions();return a.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 a.between(this.getMinVersion(),e.getExactVersion());if(e.getExactVersion()+1===this.getMinVersion())return a.between(e.getExactVersion(),this.getMaxVersion())}else if(e.isRange()){if(this.getMaxVersion()+1===e.getMinVersion()||e.getMaxVersion()+1===this.getMinVersion())return a.between(Math.min(this.getMinVersion(),e.getMinVersion()),Math.max(this.getMaxVersion(),e.getMaxVersion()))}else if(e.isSet()&&this.contains(this))return this}return a.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 Y(a,...e){let t=[];for(let o=0;o<a.length;o++)t.push(a[o]),o<e.length&&t.push(e[o]);let n=t.join("").split(`
|
|
16
|
+
`);if(n.length<2)return t.join("");let i=n[1].search(/\S/);return n.map(o=>o.slice(i)).join(`
|
|
17
|
+
`).trim()}function gt(a){return a.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 ae=class a{constructor({notifier:e,status:t}){this.notifier=e,this.status=t;}log(e){let t=a.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 i=t[n].trim();if(i!=="")return i}return ""}};var We=class a{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,this.plugins=e.plugins??[];}async generateSlotExample(e,t){let n=this.projectDirectory.get(),i=[];for(let o of await this.generateSlotExampleFiles(e,t)){let r=this.fileSystem.joinPaths(n,this.fileSystem.getDirectoryName(o.path));await this.fileSystem.createDirectory(r,{recursive:true}).catch(()=>null);let s=this.fileSystem.joinPaths(n,o.path);await this.fileSystem.writeTextFile(s,o.code,{overwrite:true}),i.push(s);}await this.formatter.format(i);}async setup(e){let{input:t,output:n}=e,i=await this.resolveInstallationPlan(e),o={...i.configuration,paths:{content:".",...await this.getPaths(e.configuration),...i.configuration.paths}},r={...e,configuration:{...e.configuration,...o,applications:e.configuration.applications}},s=[];if(s.push({title:"Install dependencies",task:async p=>{p.update("Installing dependencies");let c=new ae({status:"Installing dependencies",notifier:p});try{await this.packageManager.addDependencies(["croct"],{dev:!0,logger:c}),await this.packageManager.addDependencies([...i.dependencies,a.CONTENT_PACKAGE],{logger:c}),p.confirm("Dependencies installed");}catch(l){p.alert("Failed to install dependencies",d.formatMessage(l));}}}),s.push(...i.tasks),Object.keys(o.slots).length>0&&s.push({title:"Download content",task:async p=>{p.update("Downloading content");try{await this.updateContent(r,{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(r,{notifier:p,clean:!0});}catch(c){p.alert("Failed to generate types",d.formatMessage(c));}try{await this.registerTypeFile(r,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 --no-interaction 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 o}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 i=await this.locateFile(...e);return i!==null?i:n}resolveInstallationPlan(e){let t=this.getInstallationPlan(e),n={packageManager:this.packageManager,projectDirectory:this.projectDirectory,fileSystem:this.fileSystem};for(let i of this.plugins)t=t.then(async o=>{let r=await i.getInstallationPlan(e,n);return {tasks:[...o.tasks,...r.tasks??[]],dependencies:[...o.dependencies,...r.dependencies??[]],configuration:{...o.configuration,...r.configuration}}});return t}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:i}=e,o=t.notifier??n.notify("Updating content");if(Object.entries(i.slots).length===0){o.confirm("No slots to update");return}let s=await this.mountContentPackageFolder();if(s===null){o.alert(`The package ${a.CONTENT_PACKAGE} is not installed`);return}let p=this.fileSystem.joinPaths(s.directory,"slot");for await(let _ of this.fileSystem.list(p,(S,P)=>P===0))_.type==="directory"&&await this.fileSystem.delete(this.fileSystem.joinPaths(p,_.name),{recursive:true});let c={},l={},u={};for(let[_,S]of Object.entries(await this.loadContent(e,t.clean))){let P=Math.max(...S.map(({version:H})=>H));for(let{version:H,content:ue}of S)for(let[V,re]of Object.entries(ue)){let _t=`${_}@${H}`;c[V]===void 0&&(c[V]={});let ba=`${gt(`${_}-${V}`)}V${H}`,Ia=`./${V}/${_t}`;u[V]===void 0&&(u[V]={}),c[V][_t]=Ia,u[V][_t]=`${ba}`,l[ba]=Ia,H===P&&(c[V][_]=Ia,u[V][_]=`${ba}`);let kc=this.fileSystem.joinPaths(p,V);await this.fileSystem.isDirectory(kc)||await this.fileSystem.createDirectory(this.fileSystem.joinPaths(p,V),{recursive:true}),await this.fileSystem.writeTextFile(this.fileSystem.joinPaths(p,V,`${_t}.js`),`export default ${JSON.stringify(re,null,2)};`,{overwrite:true}),await this.fileSystem.writeTextFile(this.fileSystem.joinPaths(p,V,`${_t}.cjs`),`module.exports = ${JSON.stringify(re,null,2)};`,{overwrite:true});}}let g=Object.entries(l).map(([_,S])=>`import ${_} from '${S}.js';`).join(`
|
|
18
18
|
`),y=`const contentMap = ${JSON.stringify(u,null,2).replace(/(?<=: )"(.*?)"/g,"$1")};
|
|
19
19
|
|
|
20
20
|
`;await this.fileSystem.writeTextFile(this.fileSystem.joinPaths(p,"getSlotContent.js"),`${g}
|
|
21
21
|
|
|
22
22
|
${y}`+Y`
|
|
23
|
-
const defaultLocale = ${JSON.stringify(
|
|
23
|
+
const defaultLocale = ${JSON.stringify(i.defaultLocale)};
|
|
24
24
|
|
|
25
25
|
export function getSlotContent(slotId, language = defaultLocale) {
|
|
26
26
|
if (contentMap[language]?.[slotId] !== undefined) {
|
|
@@ -33,11 +33,11 @@ ${y}`+Y`
|
|
|
33
33
|
|
|
34
34
|
return null;
|
|
35
35
|
}
|
|
36
|
-
`,{overwrite:true});let v=Object.entries(l).map(([
|
|
36
|
+
`,{overwrite:true});let v=Object.entries(l).map(([_,S])=>`const ${_} = require('${S}.cjs');`).join(`
|
|
37
37
|
`);await this.fileSystem.writeTextFile(this.fileSystem.joinPaths(p,"getSlotContent.cjs"),`${v}
|
|
38
38
|
|
|
39
39
|
${y}`+Y`
|
|
40
|
-
const defaultLocale = ${JSON.stringify(
|
|
40
|
+
const defaultLocale = ${JSON.stringify(i.defaultLocale)};
|
|
41
41
|
|
|
42
42
|
module.exports = {
|
|
43
43
|
getSlotContent: function getSlotContent(slotId, language = defaultLocale) {
|
|
@@ -55,7 +55,7 @@ ${y}`+Y`
|
|
|
55
55
|
`,{overwrite:true});let A=`const contentMap = ${JSON.stringify(c,null,2).replace(/"(\.\/.*?)"/g,'() => import("$1.js")')};
|
|
56
56
|
|
|
57
57
|
`;await this.fileSystem.writeTextFile(this.fileSystem.joinPaths(p,"loadSlotContent.js"),A+Y`
|
|
58
|
-
const defaultLocale = ${JSON.stringify(
|
|
58
|
+
const defaultLocale = ${JSON.stringify(i.defaultLocale)};
|
|
59
59
|
|
|
60
60
|
export function loadSlotContent(slotId, language = defaultLocale) {
|
|
61
61
|
if (contentMap[language]?.[slotId] !== undefined) {
|
|
@@ -71,7 +71,7 @@ ${y}`+Y`
|
|
|
71
71
|
`,{overwrite:true});let M=`const contentMap = ${JSON.stringify(c,null,2).replace(/"(\.\/.*?)"/g,'() => Promise.resolve(require("$1.cjs"))')};
|
|
72
72
|
|
|
73
73
|
`;await this.fileSystem.writeTextFile(this.fileSystem.joinPaths(p,"loadSlotContent.cjs"),M+Y`
|
|
74
|
-
const defaultLocale = ${JSON.stringify(
|
|
74
|
+
const defaultLocale = ${JSON.stringify(i.defaultLocale)};
|
|
75
75
|
|
|
76
76
|
module.exports = {
|
|
77
77
|
loadSlotContent: function loadSlotContent(slotId, language = defaultLocale) {
|
|
@@ -86,7 +86,7 @@ ${y}`+Y`
|
|
|
86
86
|
return Promise.resolve(null);
|
|
87
87
|
}
|
|
88
88
|
};
|
|
89
|
-
`,{overwrite:true}),
|
|
89
|
+
`,{overwrite:true}),o.confirm("Content updated");}async loadContent(e,t=false){let{configuration:n}=e;if(n.paths?.content===void 0)return this.loadRemoteContent(e);let i=this.fileSystem.joinPaths(n.paths.content,"slots.json");if(!t&&await this.fileSystem.exists(i))return this.loadLocalContent(i);let o=await this.loadRemoteContent(e);return await this.saveContent(o,i),o}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 X("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),i={};for(let[o,r]of n)i[o]=D.parse(r).getVersions();return Object.fromEntries(await Promise.all(n.map(async([o])=>[o,await Promise.all(i[o].map(r=>this.workspaceApi.getSlotStaticContent({organizationSlug:t.organization,workspaceSlug:t.workspace,slotSlug:o},r).then(s=>({version:r,content:Object.fromEntries(s.map(({locale:p,content:c})=>[p,c]))}))))])))}async updateTypes(e,t={}){let{output:n,configuration:i}=e,o=t.notifier??n.notify("Updating types"),r=this.getTypeFile(i.paths?.content??this.projectDirectory.get());if(t.clean===true||!await this.fileSystem.exists(r)){let s="";(Object.keys(i.slots).length>0||Object.keys(i.components).length>0)&&(s=`${await this.generateTypes(i)}`),s=Y`
|
|
90
90
|
/**
|
|
91
91
|
* Generated by the Croct CLI.
|
|
92
92
|
*
|
|
@@ -98,12 +98,12 @@ ${y}`+Y`
|
|
|
98
98
|
// module
|
|
99
99
|
|
|
100
100
|
export {};
|
|
101
|
-
`.replace("// module",s),await this.fileSystem.writeTextFile(
|
|
101
|
+
`.replace("// module",s),await this.fileSystem.writeTextFile(r,s,{overwrite:true});}o.confirm("Types updated");}async generateTypes(e){let{organization:t,workspace:n,components:i,slots:o}=await this.resolveVersions(e);return this.workspaceApi.generateTypes({organizationSlug:t,workspaceSlug:n,target:"PLUG_JS",components:Object.entries(i).map(([r,s])=>({id:r,version:s})),slots:Object.entries(o).map(([r,s])=>({id:r,version:s}))})}async registerTypeFile(e,t){let n=await this.getPaths(e.configuration),i=await this.getTypeScriptConfigPath([n.components,n.examples]),o=t??e.output.notify("Registering type file");if(i===null)throw new X("TypeScript configuration not found");let r=this.projectDirectory.get();if(!this.fileSystem.isSubPath(r,i)){let l=this.fileSystem.getRelativePath(r,i);throw new X(`TypeScript configuration is outside the project directory: \`${l}\``)}let s=e.configuration.paths?.content??this.projectDirectory.get(),p=this.fileSystem.getRelativePath(this.fileSystem.getDirectoryName(i),this.getTypeFile(s)).replace(/\\/g,"/"),c=JsonParser$1.parse(await this.fileSystem.readTextFile(i),JsonObjectNode$1);if(c.has("files")){let l=c.get("files",JsonArrayNode$1).toJSON();if(l.includes(p))return o.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(i,c.toString(),{overwrite:true}),o.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[i,o]=await Promise.all([Promise.all(n.map(r=>this.workspaceApi.getSlot({organizationSlug:e.organization,workspaceSlug:e.workspace,slotSlug:r}))).then(r=>r.filter(s=>s!==null)),Promise.all(t.map(r=>this.workspaceApi.getComponent({organizationSlug:e.organization,workspaceSlug:e.workspace,componentSlug:r}))).then(r=>r.filter(s=>s!==null))]);return {...e,components:Object.fromEntries(Object.entries(e.components).flatMap(([r,s])=>{let p=D.parse(s).getVersions().filter(c=>o.some(l=>l.slug===r&&c<=l.version.major));return p.length===0?[]:[[r,D.either(...p).toString()]]})),slots:Object.fromEntries(Object.entries(e.slots).flatMap(([r,s])=>{let p=D.parse(s).getVersions().filter(c=>i.some(l=>l.slug===r&&c<=l.version.major));return p.length===0?[]:[[r,D.either(...p).toString()]]}))}}async mountContentPackageFolder(){let e=await this.packageManager.getDependency(a.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 X("The file path must be relative");let i=this.fileSystem.joinPaths(t,n);if(await this.fileSystem.exists(i))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 Oe=class a{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+=`
|
|
102
102
|
`.repeat(e),this}write(e,t=true){return this.code+=this.indentCode(`${e}`)+(t?`
|
|
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+=a.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:
|
|
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,(
|
|
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+=a.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:i=false}=t;switch(typeof e){case "string":{let o=e.replace(new RegExp(n,"g"),`\\${n}`);return this.append(`${n}${o}${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 r=0;r<e.length;r++)this.appendIndentation().appendValue(e[r],t),r<e.length-1&&this.append(", ").newLine();return this.outdent().newLine().write("]",false)}let o=Object.entries(e);if(o.length===0)return this.append("{}");this.append("{").newLine().indent();for(let r=0;r<o.length;r++){let[s,p]=o[r];this.appendIndentation(),i||!isIdentifier(s)?this.appendValue(s,t):this.append(s),this.append(": ").appendValue(p,t),r<o.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,`
|
|
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,(i,o,r,s)=>t||s>0?(o??r).toUpperCase():(o??r).toLowerCase())}};function Rn(a){let e=a.split(/(?<![A-Z])(?=[A-Z])|_/),t=e[0];return [t[0].toUpperCase()+t.slice(1).toLowerCase(),...e.slice(1).map(o=>o.toLowerCase())].join(" ")}function ps(a){return a.normalize("NFD").toLocaleLowerCase().replace(/(^[^a-z]+|[^a-z0-9_ &-]+)/ig,"").split(/[^a-z0-9]+/i).filter(e=>e!=="").join("-")}function ft(a){return Object.entries(a).sort(([,e],[,t])=>{let n=e.position??Number.MAX_SAFE_INTEGER,i=t.position??Number.MAX_SAFE_INTEGER;return n-i})}var On=class a{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>${a.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 i=t.itemLabel!==void 0?gt(t.itemLabel):"item";e.write("<ol>").indent().write(`\${${n}.map(${i} => \``).indent().write("<li>").indent();let o=a.isInline(t.items);o&&e.appendIndentation(),this.writeContentSnippet(e,t.items,i),o&&e.newLine(),e.outdent().write("</li>").outdent().write("`).join('')}").outdent().write("</ol>");break}case "structure":e.write("<ul>").indent();for(let[i,o]of ft(t.attributes))o.private!==true&&(o.optional===true&&(e.write(`\${${n}.${i} && \``),e.indent()),this.writeAttributeSnippet(e,o,`${n}.${i}`),o.optional===true&&(e.outdent(),e.write("`}")));e.outdent().write("</ul>");break;case "union":for(let[i,o]of Object.entries(t.types))e.write(`\${${n}._type === '${i}' && \``).indent(),this.writeContentSnippet(e,o,n),e.outdent().write("`}");break}}writeAttributeSnippet(e,t,n){let i=t.type,o=t.label!==void 0?a.escapeEntities(t.label).replace(/`/g,"\\`"):Rn(n.split(".").pop());switch(i.type){case "boolean":case "text":case "number":{e.write("<li>",false).append(`<strong>${o}:</strong> `),this.writeContentSnippet(e,i,n),e.append("</li>").newLine();break}default:e.write("<li>").indent().write(`<strong>${o}</strong>`),this.writeContentSnippet(e,i,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 Oe(this.options.indentationSize)}};var Dn=class a extends We{constructor({bundlers:e,...t}){super(t),this.bundlers=e;}async generateSlotExampleFiles(e,t){let{configuration:n}=t,[i,o,r]=await Promise.all([this.isTypeScriptProject(),this.detectBundler(),this.workspaceApi.getApplication({organizationSlug:n.organization,workspaceSlug:n.workspace,applicationSlug:n.applications.development})]);if(r===null)throw new X(`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 On({fileSystem:this.fileSystem,language:i?"typescript":"javascript",appId:r.publicId,fallbackContent:o===null?a.extractFallbackContent(e.content[t.configuration.defaultLocale],e.resolvedDefinition):void 0,containerId:"slot",slotPath:this.fileSystem.joinPaths(p,`slot.${i?"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=>a.extractFallbackContent(n,t.items));case "structure":{let n=t,i={};for(let[o,r]of ft(n.attributes)){if(r.private===true)continue;let s=a.extractFallbackContent(e.attributes[o],n.attributes[o].type);(r.optional!==true||s!==null)&&(i[o]=s);}return i}}}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 _e=class a{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=a.escapeRegex(e);return new RegExp(`^${n}\\s*=`,"m").test(t)}async setVariables(e){let t=await this.read();try{for(let[n,i]of Object.entries(e))await this.setVariable(n,i);}catch(n){throw await this.write(t),n}}async setVariable(e,t){let n=await this.read(),i=a.escapeRegex(e);if(n==="")return this.write(`${e}=${t}`);let o=`${e}=${t}`,r=n.replace(new RegExp(`${i}\\s*=\\s*((?!['"\`]).*$|\`(?:\\.|[^\`])*\`|'(?:\\.|[^'])*'|"(?:\\.|[^"])*")`,"m"),o);return r!==n||r.includes(o)?this.write(r):this.write(`${n}${n.endsWith(`
|
|
105
105
|
`)?"":`
|
|
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 ht=class a{constructor({fileSystem:e,...t}){this.options=t,this.fileSystem=e;}generate(e){let t=a.replaceVariables(this.options.slotFilePath,e.id),n=a.replaceVariables(this.options.slotComponentName,e.id);return {files:[this.generatePageFile(e,{name:n,path:t,importPath:a.replaceVariables(this.options.slotImportPath,e.id),definition:e}),this.generateSlotFile(e,t,n)]}}generatePageFile(e,t){let n=this.createWriter(),r=a.replaceVariables(this.options.pageFilePath,e.id),i=a.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?gt(t.itemLabel):"item";e.write("<ol>").indent().write(`{${n}.map((${r}, index) => (`).indent().write("<li key={index}>").indent();let i=a.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 ft(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,o]of Object.entries(t.types))e.write(`{${n}._type === '${i}' && (`).indent(),this.writeRenderingSnippet(e,o,n),e.outdent().write(")}");r&&e.outdent().write("</>");break}}}writeAttributeSnippet(e,t,n){let r=t.type,i=a.escapeEntities(t.label??Rn(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 Oe(this.options.indentationSize)}static replaceVariables(e,t){return e.replace(/%name%/g,a.formatName(t,true)).replace(/%slug%/g,ss(t))}static formatName(e,t=false){return Oe.formatName(e,t)}static isInline(e){return ["number","text","boolean"].includes(e.type)}};var St=class extends ht{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,r=n!=="content"?`content: ${n}`:n;e.write(`const ${r} = useContent('${t.id}@${t.version}');`).newLine();}isSlotFetchAsync(){return false}isSlotFetchBlocking(){return false}hasSuspenseBoundary(){return false}};var Dn=class a extends We{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"}`),o=this.fileSystem.joinPaths(r.examples,`%slug%-example${n?".tsx":".jsx"}`);return new St({fileSystem:this.fileSystem,language:await this.isTypeScriptProject()?"tsx":"jsx",contentVariable:"content",slotImportPath:await this.importResolver.getImportPath(i,this.fileSystem.getDirectoryName(o)),slotFilePath:i,slotComponentName:"%name%",pageFilePath:o,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 Le(this.fileSystem,this.fileSystem.joinPaths(n,".env.production")),developmentFile:new Le(this.fileSystem,this.fileSystem.joinPaths(n,".env.development"))}}}getInstallationTasks(e){let t=[],n=e.project.env,{configuration:r}=e,i=null,o=()=>(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 X(`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 o();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:a.getAppIdProperty(await o(),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 qe=class a extends d{constructor(e,t={}){super(e,t),Object.setPrototypeOf(this,a.prototype);}},Mn=class a extends qe{constructor(e){super(e),Object.setPrototypeOf(this,a.prototype);}};function Te(a,e,t){try{return parse$1(a,{...t,sourceType:"module",plugins:[...e,...t?.plugins??[]]})}catch{throw new Mn("The source code contains syntax errors.")}}function ps(a){let e={locales:Array()},t;try{t=Te(a,["jsx","typescript"]);}catch{return {i18n:e}}return traverse(t,{ObjectProperty:n=>{if(Pa(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)&&Pa(i.key)==="locales"){let o=i.value;if(f.isArrayExpression(o))for(let s of o.elements)s!==null&&f.isStringLiteral(s)&&e.locales.push(s.value);}else if(f.isObjectProperty(i)&&Pa(i.key)==="defaultLocale"){let o=i.value;o!==null&&f.isStringLiteral(o)&&(e.defaultLocale=o.value);}return n.stop()}}),{i18n:e}}function Pa(a){return f.isIdentifier(a)?a.name:f.isStringLiteral(a)?a.value:null}var Nn=class extends ht{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=Oe.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=Oe.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 ee=class a extends d{constructor(e,t=[],n={}){super(e,{...n,details:n.details??t.map(r=>r.detail??r.title)}),Object.setPrototypeOf(this,a.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 ye=(t=>(t.DEVELOPMENT="DEVELOPMENT",t.PRODUCTION="PRODUCTION",t))(ye||{});(n=>{function a(r){switch(r){case "DEVELOPMENT":return "Development";case "PRODUCTION":return "Production"}}n.getLabel=a;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;})(ye||={});var se=(n=>(n.READ_RESOURCES="RESOURCE_READ_ACCESS",n.ISSUE_TOKEN="TOKEN_ISSUE",n.EXPORT_DATA="DATA_EXPORT",n))(se||{});(n=>{function a(r){switch(r){case "RESOURCE_READ_ACCESS":return "Read resources";case "TOKEN_ISSUE":return "Issue tokens";case "DATA_EXPORT":return "Export data"}}n.getLabel=a;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;})(se||={});var zn=class a extends We{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()]),o=await this.isTypeScriptProject(),s=await this.getPaths(t.configuration),p=this.fileSystem.joinPaths(s.components,`%slug%${o?".tsx":".jsx"}`),c=this.fileSystem.joinPaths(s.examples,"%slug%"),l=await this.importResolver.getImportPath(p,c),u=r?"tsx":"jsx";return (i?new St({fileSystem:this.fileSystem,language:u,contentVariable:"content",slotImportPath:l,slotFilePath:p,slotComponentName:"%name%",pageFilePath:this.fileSystem.joinPaths(c,`index${o?".tsx":".jsx"}`),pageComponentName:"Page"}):new Nn({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 o=t.locales.filter(c=>r.locales.includes(c)||c===t.defaultLocale),s=o.length>0?o: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,r]=await Promise.all([this.isTypeScriptProject(),this.getPageDirectory(),this.isFallbackMode(),this.packageManager.hasDirectDependency("next","<16")]),i={typescript:e,router:await this.detectRouter(t),sourceDirectory:t.startsWith("src")?"src":".",pageDirectory:t},o=r?"middleware":"proxy",[s,p]=await Promise.all([this.locateFile(...[`${o}.js`,`${o}.ts`].map(u=>this.fileSystem.joinPaths(i.sourceDirectory,u))),this.locateFile(...(i.router==="app"?[this.fileSystem.joinPaths("app","layout"),this.fileSystem.joinPaths("app","layout")]:[this.fileSystem.joinPaths("pages","_app"),this.fileSystem.joinPaths("pages","_app")]).flatMap(u=>["js","jsx","ts","tsx"].map(g=>this.fileSystem.joinPaths(i.sourceDirectory,`${u}.${g}`))))]),c=i.typescript?"ts":"js",l=this.projectDirectory.get();return {...i,fallbackMode:n,env:{localFile:new Le(this.fileSystem,this.fileSystem.joinPaths(l,".env.local")),developmentFile:new Le(this.fileSystem,this.fileSystem.joinPaths(l,".env.development")),productionFile:new Le(this.fileSystem,this.fileSystem.joinPaths(l,".env.production"))},proxy:{name:o,file:s??this.fileSystem.joinPaths(i.sourceDirectory,`${o}.${c}`)},provider:{file:p??(i.router==="app"?this.fileSystem.joinPaths(i.sourceDirectory,"app",`layout.${c}x`):this.fileSystem.joinPaths(i.sourceDirectory,"pages",`_app.${c}x`))}}}getInstallationTasks(e){let t=[];if(!e.project.fallbackMode){let n=e.project.proxy.name;t.push({title:`Configure ${n}`,task:async r=>{r.update(`Configuring ${n}`);try{await this.updateCode(this.codemod[n],e.project.proxy.file),r.confirm(`${a.capitalize(n)} configured`);}catch(i){r.alert(`Failed to install ${n}`,d.formatMessage(i));}}});}return 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,o]=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 X(`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 X(c instanceof ee&&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}),o===null?Promise.resolve():t.productionFile.setVariables({NEXT_PUBLIC_CROCT_APP_ID:o.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:""}}:ps(t)}isFallbackMode(){return this.packageManager.hasDirectDependency("next","<=13")}static capitalize(e){return e.charAt(0).toUpperCase()+e.slice(1)}};var tt=(n=>(n.NEXTJS="nextjs",n.REACT="react",n.JAVASCRIPT="javascript",n))(tt||{});(e=>{function a(t){switch(t){case "nextjs":return "Next.js";case "react":return "React";case "javascript":return "JavaScript"}}e.getName=a;})(tt||={});var $n=class a{constructor(e){this.config=e;}async execute(e){let{configurationManager:t,platformProvider:n,sdkProvider:r,io:{output:i}}=this.config,o=e.override!==true&&await t.isInitialized()?{...await t.loadPartial()}:null,s=await n.get(),p=s!==null?`${tt.getName(s)} project`:"project";i.break(),i.announce({semantics:"neutral",title:"\u{1F44B} Welcome to Croct",alignment:"center",message:`Let's configure your ${p} to get started!`}),i.break();let c=await this.getOrganization({new:e.new==="organization"},e.new==="organization"?void 0:e.organization??o?.organization),l=await this.getWorkspace({organization:c,new:c.new!==true&&e.new==="workspace"},e.new==="workspace"||c.new===true?void 0:e.workspace??o?.workspace),u={organization:c,workspace:l,platform:s??"javascript",new:l.new!==true&&e.new==="application"},g=await this.getApplication({...u,environment:"DEVELOPMENT"},e.new!==void 0||l.new===true?void 0:e.devApplication??o?.applications?.development),y={organization:c.slug,workspace:l.slug,applications:{development:g.slug},defaultLocale:l.defaultLocale,locales:[...new Set([...o?.locales??[],...l.locales])],slots:o?.slots??{},components:o?.components??{},paths:o?.paths??{}},v=await this.resolveApplication({...u,environment:"PRODUCTION"},e.new!==void 0?void 0:e.prodApplication??o?.applications?.production);if(v!==null&&(y.applications.production=v.slug),o!==null){await t.update(y),i.confirm("Project configuration updated");return}let A=await r.get();if(A===null){await t.update(y),i.warn("No suitable SDK found, skipping project configuration");return}await t.update(await this.configure(A,y,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(o=>{if(o instanceof ee&&o.isAccessDenied())return null;throw o});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(o=>{if(o instanceof ee&&o.isAccessDenied())return null;throw o});if(i===null)throw new d(`No workspace found with slug "${t}".`,{reason:"invalid_input"});return i}async resolveApplication(e,t){let{api:n}=this.config,r=e.workspace.website??e.organization.website??void 0,i=r!==void 0&&new URL(r).hostname!=="localhost";if(e.environment==="DEVELOPMENT"||i||t!==void 0||e.new===true)return this.getApplication(e,t);let o=n.workspace.getApplications({organizationSlug:e.organization.slug,workspaceSlug:e.workspace.slug});for(let s of await o)if(s.environment===e.environment)return this.getApplication(e,t);return null}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(o=>{if(o instanceof ee&&o.isAccessDenied())return null;throw o});if(i===null)throw new d(`No application found with slug "${t}".`,{reason:"invalid_input"});if(i.environment!==e.environment)throw new d(`No ${ye.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 a.canonicalizePaths(i)}static canonicalizePaths(e){return e.paths===void 0?e:{...e,paths:Object.fromEntries(Object.entries(e.paths).map(([t,n])=>[t,a.canonicalizePath(n)]))}}static canonicalizePath(e){return e.replace(/\\/g,"/")}};var Fn=class{constructor(e){this.authenticator=e.authenticator;}async execute(e){await this.authenticator.logout(),await this.authenticator.login(e);}};var Vt=class{constructor({output:e,authenticator:t}){this.authenticator=t,this.output=e;}async execute(){await this.authenticator.logout(),this.output.confirm("Logged out");}};var ve=class a extends d{constructor(e,t={}){super(e,{...t,reason:t.reason??"invalid_configuration"}),Object.setPrototypeOf(this,a.prototype);}};var _n=class a{static{this.CONFIGURATION_SCHEMA="https://schema.croct.com/json/v1/project.json";}constructor(e){this.fileSystem=e.fileSystem,this.fullValidator=e.fullValidator,this.partialValidator=e.partialValidator,this.configurationFile=e.configurationFile;}async isInitialized(e="any"){if(e==="any")return this.fileSystem.exists(this.configurationFile);let t=e==="full"?this.fullValidator:this.partialValidator;try{return (await this.loadConfigurationFile(t)).configuration!==null}catch(n){if(n instanceof ve)return false;throw n}}async load(){let{configuration:e}=await this.loadConfigurationFile(this.fullValidator);if(e===null)throw new ve("Project configuration not found.",{reason:"not_found",suggestions:["Run `init` command to initialize the project"]});return e}async loadPartial(){let e={};try{e=(await this.loadConfigurationFile(this.partialValidator)).configuration??{};}catch(t){if(!(t instanceof ve))throw t}return e}async update(e){return this.updateConfigurationFile(await this.validateConfiguration(this.fullValidator,e))}async updateConfigurationFile(e){let t=await this.loadConfigurationFile(this.partialValidator),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:a.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(e){let t={path:this.configurationFile,source:null,configuration:null},n;try{t.source=await this.fileSystem.readTextFile(t.path),n=JsonParser$1.parse(t.source).toJSON();}catch{return t}return n!==null&&(t.configuration=await this.validateConfiguration(e,n,t),t.configuration?.$schema!==void 0&&delete t.configuration?.$schema),t}async validateConfiguration(e,t,n){let r=await e.validate(t);if(!r.valid){let i=r.violations[0];throw new ve("The project configuration is invalid.",{details:[...n!==void 0?[`File: file://${n.path.replace(/\\/g,"/")}`]:[],`Cause: ${i.message}`,`Violation path: ${i.path}`]})}return r.data}};var Wt=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,o=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 o.json().then(s=>{let{data:p,errors:c}=s;if(c!==void 0)throw new ee(c[0].message.replace(/"/g,"`"),c.map(({extensions:l})=>({...l,detail:l.detail?.replace(/"/g,"`")})));return {data:p,headers:o.headers}})}};function Aa(a,e){return a.slice(0,a.indexOf("-",e-1)===e-1?e-1:e)}function*qt({baseName:a,alwaysSuffixed:e=false}){let t=a.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 Aa(n,30),n.length<29&&t.length>2&&(yield Aa(t.join("-"),30)));;){let r=Math.floor(Math.random()*1e4).toString();yield `${Aa(n,30-r.length-1)}-${r}`;}}function nt(a){let{baseName:e,query:t,client:n,alwaysSuffixed:r}=a;return Kc({baseName:e,alwaysSuffixed:r},async i=>{let o=[i.next().value,i.next().value,i.next().value],{data:{checkAvailability:s}}=await n.execute(t,{...a.variables??{},slugFirstOption:o[0],slugSecondOption:o[1],slugThirdOption:o[2]}),p=[s.slugFirstOption,s.slugSecondOption,s.slugThirdOption];return o.find((c,l)=>p[l])??null})}async function Kc(a,e){let t=qt(a),n;do n=await e(t);while(n===null);return n}var E=class extends String{constructor(e,t){super(e),this.value=e,this.__meta__=t;}toString(){return this.value}},ls=new E(`
|
|
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 ht=class a{constructor({fileSystem:e,...t}){this.options=t,this.fileSystem=e;}generate(e){let t=a.replaceVariables(this.options.slotFilePath,e.id),n=a.replaceVariables(this.options.slotComponentName,e.id);return {files:[this.generatePageFile(e,{name:n,path:t,importPath:a.replaceVariables(this.options.slotImportPath,e.id),definition:e}),this.generateSlotFile(e,t,n)]}}generatePageFile(e,t){let n=this.createWriter(),i=a.replaceVariables(this.options.pageFilePath,e.id),o=a.replaceVariables(this.options.pageComponentName,e.id);return this.writePageSnippet(n,o,t),{path:i,language:this.options.language,code:n.toString()}}generateSlotFile(e,t,n){let i=this.createWriter();return this.writeSlotSnippet(i,e,n),{path:t,language:this.options.language,code:i.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 i=t.itemLabel!==void 0?gt(t.itemLabel):"item";e.write("<ol>").indent().write(`{${n}.map((${i}, index) => (`).indent().write("<li key={index}>").indent();let o=a.isInline(t.items);o&&e.appendIndentation(),this.writeRenderingSnippet(e,t.items,i),o&&e.newLine(),e.outdent().write("</li>").outdent().write("))}").outdent().write("</ol>");break}case "structure":e.write("<ul>").indent();for(let[i,o]of ft(t.attributes))o.private!==true&&(o.optional===true&&(e.write(`{${n}.${i} && (`),e.indent()),this.writeAttributeSnippet(e,{name:i,...o},n),o.optional===true&&(e.outdent(),e.write(")}")));e.outdent().write("</ul>");break;case "union":{let i=!n.includes(".");i&&e.write("<>").indent();for(let[o,r]of Object.entries(t.types))e.write(`{${n}._type === '${o}' && (`).indent(),this.writeRenderingSnippet(e,r,n),e.outdent().write(")}");i&&e.outdent().write("</>");break}}}writeAttributeSnippet(e,t,n){let i=t.type,o=a.escapeEntities(t.label??Rn(t.name));switch(i.type){case "boolean":case "text":case "number":{e.write("<li>",false).append(`<strong>${o}:</strong> `),this.writeRenderingSnippet(e,i,`${n}.${t.name}`),e.append("</li>").newLine();break}default:e.write("<li>").indent().write(`<strong>${o}</strong>`),this.writeRenderingSnippet(e,i,`${n}.${t.name}`),e.outdent().write("</li>");break}}static escapeEntities(e){return e.replace(/([&"<>])/g,t=>({"&":"&",'"':""","<":"<",">":">"})[t]??t)}createWriter(){return new Oe(this.options.indentationSize)}static replaceVariables(e,t){return e.replace(/%name%/g,a.formatName(t,true)).replace(/%slug%/g,ps(t))}static formatName(e,t=false){return Oe.formatName(e,t)}static isInline(e){return ["number","text","boolean"].includes(e.type)}};var St=class extends ht{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,i=n!=="content"?`content: ${n}`:n;e.write(`const ${i} = useContent('${t.id}@${t.version}');`).newLine();}isSlotFetchAsync(){return false}isSlotFetchBlocking(){return false}hasSuspenseBoundary(){return false}};var Tn=class a extends We{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(),i=await this.getPaths(t.configuration),o=this.fileSystem.joinPaths(i.components,`%slug%${n?".tsx":".jsx"}`),r=this.fileSystem.joinPaths(i.examples,`%slug%-example${n?".tsx":".jsx"}`);return new St({fileSystem:this.fileSystem,language:await this.isTypeScriptProject()?"tsx":"jsx",contentVariable:"content",slotImportPath:await this.importResolver.getImportPath(o,this.fileSystem.getDirectoryName(r)),slotFilePath:o,slotComponentName:"%name%",pageFilePath:r,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 t=await this.getEnvVarProperty(),n=this.projectDirectory.get();return {typescript:await this.isTypeScriptProject(),sourceDirectory:"src",provider:{file:await this.locateFile(...["App","main","index"].flatMap(i=>["js","jsx","ts","tsx"].map(o=>`${i}.${o}`)).map(i=>this.fileSystem.joinPaths("src",i)))},env:t===null?void 0:{property:t,productionFile:new _e(this.fileSystem,this.fileSystem.joinPaths(n,".env.production")),developmentFile:new _e(this.fileSystem,this.fileSystem.joinPaths(n,".env.development"))}}}getInstallationTasks(e){let t=[],n=e.project.env,{configuration:i}=e,o=null,r=()=>(o===null&&(o=Promise.all([this.workspaceApi.getApplication({organizationSlug:i.organization,workspaceSlug:i.workspace,applicationSlug:i.applications.development}),i.applications.production===void 0?null:this.workspaceApi.getApplication({organizationSlug:i.organization,workspaceSlug:i.workspace,applicationSlug:i.applications.production})]).then(([s,p])=>s===null?Promise.reject(new X(`Development application ${i.applications.development} not found`,{reason:"not_found"})):{development:s.publicId,production:p?.publicId})),o);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 r();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:a.getAppIdProperty(await r(),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 qe=class a extends d{constructor(e,t={}){super(e,t),Object.setPrototypeOf(this,a.prototype);}},Mn=class a extends qe{constructor(e){super(e),Object.setPrototypeOf(this,a.prototype);}};function De(a,e,t){try{return parse$1(a,{...t,sourceType:"module",plugins:[...e,...t?.plugins??[]]})}catch{throw new Mn("The source code contains syntax errors.")}}function cs(a){let e={locales:Array()},t;try{t=De(a,["jsx","typescript"]);}catch{return {i18n:e}}return traverse(t,{ObjectProperty:n=>{if(Pa(n.node.key)!=="i18n")return n.skip();let i=n.node.value;if(!f.isObjectExpression(i))return n.stop();for(let o of i.properties)if(f.isObjectProperty(o)&&Pa(o.key)==="locales"){let r=o.value;if(f.isArrayExpression(r))for(let s of r.elements)s!==null&&f.isStringLiteral(s)&&e.locales.push(s.value);}else if(f.isObjectProperty(o)&&Pa(o.key)==="defaultLocale"){let r=o.value;r!==null&&f.isStringLiteral(r)&&(e.defaultLocale=r.value);}return n.stop()}}),{i18n:e}}function Pa(a){return f.isIdentifier(a)?a.name:f.isStringLiteral(a)?a.value:null}var Nn=class extends ht{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=Oe.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=Oe.formatName(t.id,true),i=this.options.contentVariable;if(this.options.language==="jsx"){e.append(`(${i})`);return}e.append(`(${i}: ${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 ee=class a extends d{constructor(e,t=[],n={}){super(e,{...n,details:n.details??t.map(i=>i.detail??i.title)}),Object.setPrototypeOf(this,a.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 ye=(t=>(t.DEVELOPMENT="DEVELOPMENT",t.PRODUCTION="PRODUCTION",t))(ye||{});(n=>{function a(i){switch(i){case "DEVELOPMENT":return "Development";case "PRODUCTION":return "Production"}}n.getLabel=a;function e(){return Object.values(n).filter(i=>typeof i=="string")}n.all=e;function t(i){let o=i.toUpperCase();if(!n.all().includes(o))throw new Error(`Invalid environment value "${i}".`);return o}n.fromValue=t;})(ye||={});var se=(n=>(n.READ_RESOURCES="RESOURCE_READ_ACCESS",n.ISSUE_TOKEN="TOKEN_ISSUE",n.EXPORT_DATA="DATA_EXPORT",n))(se||{});(n=>{function a(i){switch(i){case "RESOURCE_READ_ACCESS":return "Read resources";case "TOKEN_ISSUE":return "Issue tokens";case "DATA_EXPORT":return "Export data"}}n.getLabel=a;function e(){return Object.values(n).filter(i=>typeof i=="string")}n.all=e;function t(i){let o=i.toUpperCase();if(!n.all().includes(o))throw new Error(`Invalid permission value "${i}".`);return o}n.fromValue=t;})(se||={});var zn=class a extends We{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,i,o]=await Promise.all([this.detectRouter(),this.isTypeScriptProject(),this.isFallbackMode()]),r=await this.isTypeScriptProject(),s=await this.getPaths(t.configuration),p=this.fileSystem.joinPaths(s.components,`%slug%${r?".tsx":".jsx"}`),c=this.fileSystem.joinPaths(s.examples,"%slug%"),l=await this.importResolver.getImportPath(p,c),u=i?"tsx":"jsx";return (o?new St({fileSystem:this.fileSystem,language:u,contentVariable:"content",slotImportPath:l,slotFilePath:p,slotComponentName:"%name%",pageFilePath:this.fileSystem.joinPaths(c,`index${r?".tsx":".jsx"}`),pageComponentName:"Page"}):new Nn({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"}${i?".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:i},o]=await Promise.all([this.getConfig(),this.getProjectInfo()]);o.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 r=t.locales.filter(c=>i.locales.includes(c)||c===t.defaultLocale),s=r.length>0?r:i.locales,p=i.defaultLocale!==void 0&&s.includes(i.defaultLocale)?i.defaultLocale:t.defaultLocale;return {dependencies:[o.fallbackMode?"@croct/plug-react":"@croct/plug-next"],tasks:this.getInstallationTasks({...e,project:o}),configuration:{...t,locales:s,defaultLocale:p,paths:{...t.paths,examples:o.pageDirectory}}}}async getProjectInfo(){let[e,t,n,i]=await Promise.all([this.isTypeScriptProject(),this.getPageDirectory(),this.isFallbackMode(),this.packageManager.hasDirectDependency("next","<16")]),o={typescript:e,router:await this.detectRouter(t),sourceDirectory:t.startsWith("src")?"src":".",pageDirectory:t},r=i?"middleware":"proxy",[s,p]=await Promise.all([this.locateFile(...[`${r}.js`,`${r}.ts`].map(u=>this.fileSystem.joinPaths(o.sourceDirectory,u))),this.locateFile(...(o.router==="app"?[this.fileSystem.joinPaths("app","layout"),this.fileSystem.joinPaths("app","layout")]:[this.fileSystem.joinPaths("pages","_app"),this.fileSystem.joinPaths("pages","_app")]).flatMap(u=>["js","jsx","ts","tsx"].map(g=>this.fileSystem.joinPaths(o.sourceDirectory,`${u}.${g}`))))]),c=o.typescript?"ts":"js",l=this.projectDirectory.get();return {...o,fallbackMode:n,env:{localFile:new _e(this.fileSystem,this.fileSystem.joinPaths(l,".env.local")),developmentFile:new _e(this.fileSystem,this.fileSystem.joinPaths(l,".env.development")),productionFile:new _e(this.fileSystem,this.fileSystem.joinPaths(l,".env.production"))},proxy:{name:r,file:s??this.fileSystem.joinPaths(o.sourceDirectory,`${r}.${c}`)},provider:{file:p??(o.router==="app"?this.fileSystem.joinPaths(o.sourceDirectory,"app",`layout.${c}x`):this.fileSystem.joinPaths(o.sourceDirectory,"pages",`_app.${c}x`))}}}getInstallationTasks(e){let t=[];if(!e.project.fallbackMode){let n=e.project.proxy.name;t.push({title:`Configure ${n}`,task:async i=>{i.update(`Configuring ${n}`);try{await this.updateCode(this.codemod[n],e.project.proxy.file),i.confirm(`${a.capitalize(n)} configured`);}catch(o){i.alert(`Failed to install ${n}`,d.formatMessage(o));}}});}return t.push({title:"Configure provider",task:async n=>{n.update("Configuring provider");try{await this.installProvider({...e,notifier:n}),n.confirm("Provider configured");}catch(i){n.alert("Failed to install provider",d.formatMessage(i));}}}),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(i){n.alert("Failed to update .env.local",d.formatMessage(i));}}}),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:i}=e;i.update("Loading information");let[o,r]=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(o===null)throw new X(`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();i.update("Creating API key");let p;try{p=await this.applicationApi.createApiKey({organizationSlug:n.organization,workspaceSlug:n.workspace,applicationSlug:o.slug,name:`${s.username} CLI`,permissions:["TOKEN_ISSUE"]});}catch(c){throw c instanceof d?new X(c instanceof ee&&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:o.publicId}),r===null?Promise.resolve():t.productionFile.setVariables({NEXT_PUBLIC_CROCT_APP_ID:r.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:""}}:cs(t)}isFallbackMode(){return this.packageManager.hasDirectDependency("next","<=13")}static capitalize(e){return e.charAt(0).toUpperCase()+e.slice(1)}};var tt=(n=>(n.NEXTJS="nextjs",n.REACT="react",n.JAVASCRIPT="javascript",n))(tt||{});(e=>{function a(t){switch(t){case "nextjs":return "Next.js";case "react":return "React";case "javascript":return "JavaScript"}}e.getName=a;})(tt||={});var $n=class a{constructor(e){this.config=e;}async execute(e){let{configurationManager:t,platformProvider:n,sdkProvider:i,io:{output:o}}=this.config,r=e.override!==true&&await t.isInitialized()?{...await t.loadPartial()}:null,s=await n.get(),p=s!==null?`${tt.getName(s)} project`:"project";o.break(),o.announce({semantics:"neutral",title:"\u{1F44B} Welcome to Croct",alignment:"center",message:`Let's configure your ${p} to get started!`}),o.break();let c=await this.getOrganization({new:e.new==="organization"},e.new==="organization"?void 0:e.organization??r?.organization),l=await this.getWorkspace({organization:c,new:c.new!==true&&e.new==="workspace"},e.new==="workspace"||c.new===true?void 0:e.workspace??r?.workspace),u={organization:c,workspace:l,platform:s??"javascript",new:l.new!==true&&e.new==="application"},g=await this.getApplication({...u,environment:"DEVELOPMENT"},e.new!==void 0||l.new===true?void 0:e.devApplication??r?.applications?.development),y={organization:c.slug,workspace:l.slug,applications:{development:g.slug},defaultLocale:l.defaultLocale,locales:[...new Set([...r?.locales??[],...l.locales])],slots:r?.slots??{},components:r?.components??{},paths:r?.paths??{}},v=await this.resolveApplication({...u,environment:"PRODUCTION"},e.new!==void 0?void 0:e.prodApplication??r?.applications?.production);if(v!==null&&(y.applications.production=v.slug),r!==null){await t.update(y),o.confirm("Project configuration updated");return}let A=await i.get();if(A===null){await t.update(y),o.warn("No suitable SDK found, skipping project configuration");return}await t.update(await this.configure(A,y,e.skipApiKeySetup===true));}async getOrganization(e,t){let{form:n,api:i}=this.config,o=t===void 0?await n.organization.handle(e):await i.user.getOrganization(t).catch(r=>{if(r instanceof ee&&r.isAccessDenied())return null;throw r});if(o===null)throw new d(`No organization found with slug "${t}".`,{reason:"invalid_input"});return o}async getWorkspace(e,t){let{form:n,api:i}=this.config,o=t===void 0?await n.workspace.handle(e):await i.organization.getWorkspace({organizationSlug:e.organization.slug,workspaceSlug:t}).catch(r=>{if(r instanceof ee&&r.isAccessDenied())return null;throw r});if(o===null)throw new d(`No workspace found with slug "${t}".`,{reason:"invalid_input"});return o}async resolveApplication(e,t){let{api:n}=this.config,i=e.workspace.website??e.organization.website??void 0,o=i!==void 0&&new URL(i).hostname!=="localhost";if(e.environment==="DEVELOPMENT"||o||t!==void 0||e.new===true)return this.getApplication(e,t);let r=n.workspace.getApplications({organizationSlug:e.organization.slug,workspaceSlug:e.workspace.slug});for(let s of await r)if(s.environment===e.environment)return this.getApplication(e,t);return null}async getApplication(e,t){let{form:n,api:i}=this.config,o=t===void 0?await n.application.handle(e):await i.workspace.getApplication({organizationSlug:e.organization.slug,workspaceSlug:e.workspace.slug,applicationSlug:t}).catch(r=>{if(r instanceof ee&&r.isAccessDenied())return null;throw r});if(o===null)throw new d(`No application found with slug "${t}".`,{reason:"invalid_input"});if(o.environment!==e.environment)throw new d(`No ${ye.getLabel(e.environment).toUpperCase()} application found with slug "${t}".`,{reason:"invalid_input"});return o}async configure(e,t,n){let{skipConfirmation:i}=this.config,o=await e.setup({input:this.config.io.input===void 0||await i.get()?void 0:this.config.io.input,output:this.config.io.output,skipApiKeySetup:n,configuration:t});return a.canonicalizePaths(o)}static canonicalizePaths(e){return e.paths===void 0?e:{...e,paths:Object.fromEntries(Object.entries(e.paths).map(([t,n])=>[t,a.canonicalizePath(n)]))}}static canonicalizePath(e){return e.replace(/\\/g,"/")}};var Fn=class{constructor(e){this.authenticator=e.authenticator;}async execute(e){await this.authenticator.logout(),await this.authenticator.login(e);}};var Vt=class{constructor({output:e,authenticator:t}){this.authenticator=t,this.output=e;}async execute(){await this.authenticator.logout(),this.output.confirm("Logged out");}};var ve=class a extends d{constructor(e,t={}){super(e,{...t,reason:t.reason??"invalid_configuration"}),Object.setPrototypeOf(this,a.prototype);}};var jn=class a{static{this.CONFIGURATION_SCHEMA="https://schema.croct.com/json/v1/project.json";}constructor(e){this.fileSystem=e.fileSystem,this.fullValidator=e.fullValidator,this.partialValidator=e.partialValidator,this.configurationFile=e.configurationFile;}async isInitialized(e="any"){if(e==="any")return this.fileSystem.exists(this.configurationFile);let t=e==="full"?this.fullValidator:this.partialValidator;try{return (await this.loadConfigurationFile(t)).configuration!==null}catch(n){if(n instanceof ve)return false;throw n}}async load(){let{configuration:e}=await this.loadConfigurationFile(this.fullValidator);if(e===null)throw new ve("Project configuration not found.",{reason:"not_found",suggestions:["Run `init` command to initialize the project"]});return e}async loadPartial(){let e={};try{e=(await this.loadConfigurationFile(this.partialValidator)).configuration??{};}catch(t){if(!(t instanceof ve))throw t}return e}async update(e){return this.updateConfigurationFile(await this.validateConfiguration(this.fullValidator,e))}async updateConfigurationFile(e){let t=await this.loadConfigurationFile(this.partialValidator),i=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,i,{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:a.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(e){let t={path:this.configurationFile,source:null,configuration:null},n;try{t.source=await this.fileSystem.readTextFile(t.path),n=JsonParser.parse(t.source).toJSON();}catch{return t}return n!==null&&(t.configuration=await this.validateConfiguration(e,n,t),t.configuration?.$schema!==void 0&&delete t.configuration?.$schema),t}async validateConfiguration(e,t,n){let i=await e.validate(t);if(!i.valid){let o=i.violations[0];throw new ve("The project configuration is invalid.",{details:[...n!==void 0?[`File: file://${n.path.replace(/\\/g,"/")}`]:[],`Cause: ${o.message}`,`Violation path: ${o.path}`]})}return i.data}};var Wt=class{constructor(e){this.configuration=e;}async execute(e,...[t]){let{tokenProvider:n,endpoint:i}=this.configuration,o=n!==void 0?await n.getToken():null,r=await fetch(i,{method:"POST",headers:{accept:"application/json","content-type":"application/json",...o!==null?{Authorization:`Bearer ${o}`}:{}},body:JSON.stringify({query:e,variables:t})});return r.json().then(s=>{let{data:p,errors:c}=s;if(c!==void 0)throw new ee(c[0].message.replace(/"/g,"`"),c.map(({extensions:l})=>({...l,detail:l.detail?.replace(/"/g,"`")})));return {data:p,headers:r.headers}})}};function Aa(a,e){return a.slice(0,a.indexOf("-",e-1)===e-1?e-1:e)}function*qt({baseName:a,alwaysSuffixed:e=false}){let t=a.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 Aa(n,30),n.length<29&&t.length>2&&(yield Aa(t.join("-"),30)));;){let i=Math.floor(Math.random()*1e4).toString();yield `${Aa(n,30-i.length-1)}-${i}`;}}function nt(a){let{baseName:e,query:t,client:n,alwaysSuffixed:i}=a;return Jc({baseName:e,alwaysSuffixed:i},async o=>{let r=[o.next().value,o.next().value,o.next().value],{data:{checkAvailability:s}}=await n.execute(t,{...a.variables??{},slugFirstOption:r[0],slugSecondOption:r[1],slugThirdOption:r[2]}),p=[s.slugFirstOption,s.slugSecondOption,s.slugThirdOption];return r.find((c,l)=>p[l])??null})}async function Jc(a,e){let t=qt(a),n;do n=await e(t);while(n===null);return n}var E=class extends String{constructor(e,t){super(e),this.value=e,this.__meta__=t;}toString(){return this.value}},us=new E(`
|
|
107
107
|
query ApplicationSlugAvailability($workspaceId: WorkspaceId!, $slugFirstOption: ReadableId!, $slugSecondOption: ReadableId!, $slugThirdOption: ReadableId!) {
|
|
108
108
|
checkAvailability {
|
|
109
109
|
slugFirstOption: applicationSlug(
|
|
@@ -120,7 +120,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
120
120
|
)
|
|
121
121
|
}
|
|
122
122
|
}
|
|
123
|
-
`),
|
|
123
|
+
`),ms=new E(`
|
|
124
124
|
query Applications($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
|
|
125
125
|
organization(slug: $organizationSlug) {
|
|
126
126
|
workspace(slug: $workspaceSlug) {
|
|
@@ -145,7 +145,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
145
145
|
}
|
|
146
146
|
}
|
|
147
147
|
}
|
|
148
|
-
`),
|
|
148
|
+
`),ds=new E(`
|
|
149
149
|
query Application($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $applicationSlug: ReadableId!) {
|
|
150
150
|
organization(slug: $organizationSlug) {
|
|
151
151
|
workspace(slug: $workspaceSlug) {
|
|
@@ -166,7 +166,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
166
166
|
}
|
|
167
167
|
}
|
|
168
168
|
}
|
|
169
|
-
`),
|
|
169
|
+
`),gs=new E(`
|
|
170
170
|
mutation CreateApplication($workspaceId: WorkspaceId!, $payload: CreateWebApplicationPayload!) {
|
|
171
171
|
createWebApplication(workspaceId: $workspaceId, payload: $payload) {
|
|
172
172
|
id
|
|
@@ -183,7 +183,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
183
183
|
}
|
|
184
184
|
}
|
|
185
185
|
}
|
|
186
|
-
`),
|
|
186
|
+
`),fs=new E(`
|
|
187
187
|
mutation CreateApiKey($applicationId: ApplicationId!, $payload: CreateApiKeyPayload!) {
|
|
188
188
|
createApiKey(applicationId: $applicationId, payload: $payload) {
|
|
189
189
|
apiKey {
|
|
@@ -194,7 +194,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
194
194
|
apiKeyValue
|
|
195
195
|
}
|
|
196
196
|
}
|
|
197
|
-
`),
|
|
197
|
+
`),ys=new E(`
|
|
198
198
|
query Audiences($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
|
|
199
199
|
organization(slug: $organizationSlug) {
|
|
200
200
|
workspace(slug: $workspaceSlug) {
|
|
@@ -211,7 +211,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
211
211
|
}
|
|
212
212
|
}
|
|
213
213
|
}
|
|
214
|
-
`),
|
|
214
|
+
`),hs=new E(`
|
|
215
215
|
query Audience($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $audienceSlug: ReadableId!) {
|
|
216
216
|
organization(slug: $organizationSlug) {
|
|
217
217
|
workspace(slug: $workspaceSlug) {
|
|
@@ -224,43 +224,43 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
224
224
|
}
|
|
225
225
|
}
|
|
226
226
|
}
|
|
227
|
-
`),
|
|
227
|
+
`),Ss=new E(`
|
|
228
228
|
mutation SignIn($payload: SignInPayload!) {
|
|
229
229
|
signIn(payload: $payload) {
|
|
230
230
|
token
|
|
231
231
|
}
|
|
232
232
|
}
|
|
233
|
-
`),
|
|
233
|
+
`),bs=new E(`
|
|
234
234
|
mutation SignUp($payload: SignUpPayload!) {
|
|
235
235
|
signUp(payload: $payload) {
|
|
236
236
|
userId
|
|
237
237
|
}
|
|
238
238
|
}
|
|
239
|
-
`),
|
|
239
|
+
`),Is=new E(`
|
|
240
240
|
mutation IssueToken($payload: IssueTokenPayload!) {
|
|
241
241
|
issueToken(payload: $payload)
|
|
242
242
|
}
|
|
243
|
-
`),
|
|
243
|
+
`),vs=new E(`
|
|
244
244
|
mutation ResetPassword($payload: ResetPasswordPayload!) {
|
|
245
245
|
resetPassword(payload: $payload) {
|
|
246
246
|
token
|
|
247
247
|
}
|
|
248
248
|
}
|
|
249
|
-
`),
|
|
249
|
+
`),xs=new E(`
|
|
250
250
|
mutation RequestPasswordReset($email: String!, $sessionId: UserSessionId) {
|
|
251
251
|
sendResetLink(email: $email, sessionId: $sessionId)
|
|
252
252
|
}
|
|
253
|
-
`),
|
|
253
|
+
`),ws=new E(`
|
|
254
254
|
mutation RetryActivation($email: String!, $sessionId: UserSessionId!) {
|
|
255
255
|
retry {
|
|
256
256
|
accountActivation(sessionId: $sessionId, email: $email)
|
|
257
257
|
}
|
|
258
258
|
}
|
|
259
|
-
`),
|
|
259
|
+
`),Ps=new E(`
|
|
260
260
|
mutation CreateSession($redirectDestination: String) {
|
|
261
261
|
createSession(redirectDestination: $redirectDestination)
|
|
262
262
|
}
|
|
263
|
-
`),
|
|
263
|
+
`),Cs=new E(`
|
|
264
264
|
mutation CloseSession($sessionId: UserSessionId!) {
|
|
265
265
|
closeSession(sessionId: $sessionId) {
|
|
266
266
|
__typename
|
|
@@ -272,7 +272,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
272
272
|
}
|
|
273
273
|
}
|
|
274
274
|
}
|
|
275
|
-
`),
|
|
275
|
+
`),ks=new E(`
|
|
276
276
|
query Components($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
|
|
277
277
|
organization(slug: $organizationSlug) {
|
|
278
278
|
workspace(slug: $workspaceSlug) {
|
|
@@ -304,7 +304,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
304
304
|
}
|
|
305
305
|
}
|
|
306
306
|
}
|
|
307
|
-
`),
|
|
307
|
+
`),As=new E(`
|
|
308
308
|
query Component($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $componentSlug: ReadableId!, $majorVersion: Int) {
|
|
309
309
|
organization(slug: $organizationSlug) {
|
|
310
310
|
workspace(slug: $workspaceSlug) {
|
|
@@ -332,7 +332,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
332
332
|
}
|
|
333
333
|
}
|
|
334
334
|
}
|
|
335
|
-
`),
|
|
335
|
+
`),Es=new E(`
|
|
336
336
|
query Experience($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $experienceId: ExperienceId!) {
|
|
337
337
|
organization(slug: $organizationSlug) {
|
|
338
338
|
workspace(slug: $workspaceSlug) {
|
|
@@ -486,7 +486,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
486
486
|
}
|
|
487
487
|
}
|
|
488
488
|
}
|
|
489
|
-
`),
|
|
489
|
+
`),Rs=new E(`
|
|
490
490
|
query Experiences($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $status: [ExperienceStatus!]) {
|
|
491
491
|
organization(slug: $organizationSlug) {
|
|
492
492
|
workspace(slug: $workspaceSlug) {
|
|
@@ -542,7 +542,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
542
542
|
}
|
|
543
543
|
}
|
|
544
544
|
}
|
|
545
|
-
`),
|
|
545
|
+
`),Os=new E(`
|
|
546
546
|
query ResourceIdQuery($organizationSlug: ReadableId!, $workspaceSlug: ReadableId, $applicationSlug: ReadableId) {
|
|
547
547
|
organization(slug: $organizationSlug) {
|
|
548
548
|
id
|
|
@@ -554,7 +554,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
554
554
|
}
|
|
555
555
|
}
|
|
556
556
|
}
|
|
557
|
-
`),
|
|
557
|
+
`),Ds=new E(`
|
|
558
558
|
query Organization($slug: ReadableId!) {
|
|
559
559
|
organization(slug: $slug) {
|
|
560
560
|
id
|
|
@@ -582,7 +582,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
582
582
|
}
|
|
583
583
|
}
|
|
584
584
|
}
|
|
585
|
-
`),
|
|
585
|
+
`),Ms=new E(`
|
|
586
586
|
mutation SetupOrganization($payload: CreateConfiguredOrganizationPayload!) {
|
|
587
587
|
createConfiguredOrganization(payload: $payload) {
|
|
588
588
|
organization {
|
|
@@ -596,7 +596,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
596
596
|
}
|
|
597
597
|
}
|
|
598
598
|
}
|
|
599
|
-
`),
|
|
599
|
+
`),Ns=new E(`
|
|
600
600
|
query FindOrganizationSlug($slugFirstOption: ReadableId!, $slugSecondOption: ReadableId!, $slugThirdOption: ReadableId!) {
|
|
601
601
|
checkAvailability {
|
|
602
602
|
slugFirstOption: organizationSlug(slug: $slugFirstOption)
|
|
@@ -604,7 +604,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
604
604
|
slugThirdOption: organizationSlug(slug: $slugThirdOption)
|
|
605
605
|
}
|
|
606
606
|
}
|
|
607
|
-
`),
|
|
607
|
+
`),zs=new E(`
|
|
608
608
|
query OrganizationMetadata($url: String!) {
|
|
609
609
|
websiteMetadata(url: $url) {
|
|
610
610
|
url
|
|
@@ -622,7 +622,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
622
622
|
}
|
|
623
623
|
}
|
|
624
624
|
}
|
|
625
|
-
`)
|
|
625
|
+
`),$s=new E(`
|
|
626
626
|
query Slots($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
|
|
627
627
|
organization(slug: $organizationSlug) {
|
|
628
628
|
workspace(slug: $workspaceSlug) {
|
|
@@ -668,7 +668,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
668
668
|
}
|
|
669
669
|
}
|
|
670
670
|
}
|
|
671
|
-
`)
|
|
671
|
+
`),Fs=new E(`
|
|
672
672
|
query Slot($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $slotSlug: ReadableId!, $majorVersion: Int) {
|
|
673
673
|
organization(slug: $organizationSlug) {
|
|
674
674
|
workspace(slug: $workspaceSlug) {
|
|
@@ -710,7 +710,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
710
710
|
}
|
|
711
711
|
}
|
|
712
712
|
}
|
|
713
|
-
`),
|
|
713
|
+
`),js=new E(`
|
|
714
714
|
query SlotStaticContent($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $slotSlug: ReadableId!, $majorVersion: Int) {
|
|
715
715
|
organization(slug: $organizationSlug) {
|
|
716
716
|
workspace(slug: $workspaceSlug) {
|
|
@@ -742,7 +742,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
742
742
|
}
|
|
743
743
|
}
|
|
744
744
|
}
|
|
745
|
-
`),
|
|
745
|
+
`),Us=new E(`
|
|
746
746
|
query Username($slugFirstOption: ReadableId!, $slugSecondOption: ReadableId!, $slugThirdOption: ReadableId!) {
|
|
747
747
|
checkAvailability {
|
|
748
748
|
slugFirstOption: username(username: $slugFirstOption)
|
|
@@ -750,19 +750,19 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
750
750
|
slugThirdOption: username(username: $slugThirdOption)
|
|
751
751
|
}
|
|
752
752
|
}
|
|
753
|
-
`),
|
|
753
|
+
`),Vs=new E(`
|
|
754
754
|
query UserEmail($email: String!) {
|
|
755
755
|
checkAvailability {
|
|
756
756
|
email(email: $email)
|
|
757
757
|
}
|
|
758
758
|
}
|
|
759
|
-
`),
|
|
759
|
+
`),Ws=new E(`
|
|
760
760
|
mutation AcceptInvitation($invitationId: InvitationId!) {
|
|
761
761
|
acceptInvitation(invitationId: $invitationId) {
|
|
762
762
|
id
|
|
763
763
|
}
|
|
764
764
|
}
|
|
765
|
-
`),
|
|
765
|
+
`),qs=new E(`
|
|
766
766
|
query Invitations {
|
|
767
767
|
invitations(first: 100) {
|
|
768
768
|
edges {
|
|
@@ -782,7 +782,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
782
782
|
}
|
|
783
783
|
}
|
|
784
784
|
}
|
|
785
|
-
`),
|
|
785
|
+
`),Ks=new E(`
|
|
786
786
|
query Workspace($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
|
|
787
787
|
organization(slug: $organizationSlug) {
|
|
788
788
|
workspace(slug: $workspaceSlug) {
|
|
@@ -803,7 +803,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
803
803
|
}
|
|
804
804
|
}
|
|
805
805
|
}
|
|
806
|
-
`),
|
|
806
|
+
`),Hs=new E(`
|
|
807
807
|
query Workspaces($organizationSlug: ReadableId!) {
|
|
808
808
|
organization(slug: $organizationSlug) {
|
|
809
809
|
workspaces(first: 100) {
|
|
@@ -828,7 +828,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
828
828
|
}
|
|
829
829
|
}
|
|
830
830
|
}
|
|
831
|
-
`),
|
|
831
|
+
`),Gs=new E(`
|
|
832
832
|
mutation CreateWorkspace($organizationId: OrganizationId!, $payload: CreateWorkspacePayload!) {
|
|
833
833
|
createWorkspace(organizationId: $organizationId, payload: $payload) {
|
|
834
834
|
id
|
|
@@ -847,7 +847,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
847
847
|
}
|
|
848
848
|
}
|
|
849
849
|
}
|
|
850
|
-
`),
|
|
850
|
+
`),Js=new E(`
|
|
851
851
|
query FindWorkspaceSlug($organizationId: OrganizationId!, $slugFirstOption: ReadableId!, $slugSecondOption: ReadableId!, $slugThirdOption: ReadableId!) {
|
|
852
852
|
checkAvailability {
|
|
853
853
|
slugFirstOption: workspaceSlug(
|
|
@@ -864,7 +864,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
864
864
|
)
|
|
865
865
|
}
|
|
866
866
|
}
|
|
867
|
-
`),
|
|
867
|
+
`),Bs=new E(`
|
|
868
868
|
query WorkspaceFeatures($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
|
|
869
869
|
organization(slug: $organizationSlug) {
|
|
870
870
|
workspace(slug: $workspaceSlug) {
|
|
@@ -886,7 +886,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
886
886
|
}
|
|
887
887
|
}
|
|
888
888
|
}
|
|
889
|
-
`),
|
|
889
|
+
`),Zs=new E(`
|
|
890
890
|
mutation CreateResources($workspaceId: WorkspaceId!, $payload: CreateWorkspaceResourcePayload!) {
|
|
891
891
|
createWorkspaceResources(workspaceId: $workspaceId, payload: $payload) {
|
|
892
892
|
slots
|
|
@@ -898,7 +898,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
898
898
|
}
|
|
899
899
|
}
|
|
900
900
|
}
|
|
901
|
-
`);var Gc={"\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":ls,"\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":us,"\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":ms,"\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":ds,"\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":gs,"\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":fs,"\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":ys,"\n mutation SignIn($payload: SignInPayload!) {\n signIn(payload: $payload) {\n token\n }\n }\n":hs,"\n mutation SignUp($payload: SignUpPayload!) {\n signUp(payload: $payload) {\n userId\n }\n }\n":Ss,"\n mutation IssueToken($payload: IssueTokenPayload!) {\n issueToken(payload: $payload) \n }\n":bs,"\n mutation ResetPassword($payload: ResetPasswordPayload!) {\n resetPassword(payload: $payload) {\n token\n }\n }\n":Is,"\n mutation RequestPasswordReset($email: String!, $sessionId: UserSessionId) {\n sendResetLink(email: $email, sessionId: $sessionId)\n }\n":vs,"\n mutation RetryActivation($email: String!, $sessionId: UserSessionId!) {\n retry {\n accountActivation(sessionId: $sessionId, email: $email)\n }\n }\n":xs,"\n mutation CreateSession($redirectDestination: String) {\n createSession(redirectDestination: $redirectDestination)\n }\n":ws,"\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":Ps,"\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":Cs,"\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":ks,"\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":As,"\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":Es,"\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":Rs,"\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":Os,"\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":Ts,"\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":Ds,"\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":Ms,"\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":Ns,"\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":zs,"\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":$s,"\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":Fs,"\n mutation GenerateTyping($workspaceId: WorkspaceId!, $payload: GenerateTypingPayload!) {\n generateTyping(workspaceId: $workspaceId, payload: $payload)\n }\n":_s,"\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":Ls,"\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":js,"\n query UserEmail($email: String!) {\n checkAvailability {\n email(email: $email)\n }\n }\n":Us,"\n mutation AcceptInvitation($invitationId: InvitationId!) {\n acceptInvitation(invitationId: $invitationId) {\n id\n }\n }\n":Vs,"\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":Ws,"\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":qs,"\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":Ks,"\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":Hs,"\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":Gs,"\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 dynamicAttributesPerContent\n audiencesPerExperience\n }\n capabilities {\n features(requiredFeatures: [\n CROSS_DEVICE_EXPERIMENT,\n API_DATA_EXPORT\n ])\n }\n } \n }\n }\n":Js,"\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":Bs};function C(a){return Gc[a]??{}}var Zs=C(`
|
|
901
|
+
`);var Zc={"\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":us,"\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":ms,"\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":ds,"\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":gs,"\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":fs,"\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":ys,"\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":hs,"\n mutation SignIn($payload: SignInPayload!) {\n signIn(payload: $payload) {\n token\n }\n }\n":Ss,"\n mutation SignUp($payload: SignUpPayload!) {\n signUp(payload: $payload) {\n userId\n }\n }\n":bs,"\n mutation IssueToken($payload: IssueTokenPayload!) {\n issueToken(payload: $payload) \n }\n":Is,"\n mutation ResetPassword($payload: ResetPasswordPayload!) {\n resetPassword(payload: $payload) {\n token\n }\n }\n":vs,"\n mutation RequestPasswordReset($email: String!, $sessionId: UserSessionId) {\n sendResetLink(email: $email, sessionId: $sessionId)\n }\n":xs,"\n mutation RetryActivation($email: String!, $sessionId: UserSessionId!) {\n retry {\n accountActivation(sessionId: $sessionId, email: $email)\n }\n }\n":ws,"\n mutation CreateSession($redirectDestination: String) {\n createSession(redirectDestination: $redirectDestination)\n }\n":Ps,"\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":Cs,"\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":ks,"\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":As,"\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":Es,"\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":Rs,"\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":Os,"\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":Ds,"\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":Ts,"\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":Ms,"\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":Ns,"\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":zs,"\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":$s,"\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":Fs,"\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":js,"\n mutation GenerateTyping($workspaceId: WorkspaceId!, $payload: GenerateTypingPayload!) {\n generateTyping(workspaceId: $workspaceId, payload: $payload)\n }\n":_s,"\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":Ls,"\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":Us,"\n query UserEmail($email: String!) {\n checkAvailability {\n email(email: $email)\n }\n }\n":Vs,"\n mutation AcceptInvitation($invitationId: InvitationId!) {\n acceptInvitation(invitationId: $invitationId) {\n id\n }\n }\n":Ws,"\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":qs,"\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":Ks,"\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":Hs,"\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":Gs,"\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":Js,"\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 dynamicAttributesPerContent\n audiencesPerExperience\n }\n capabilities {\n features(requiredFeatures: [\n CROSS_DEVICE_EXPERIMENT,\n API_DATA_EXPORT\n ])\n }\n } \n }\n }\n":Bs,"\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":Zs};function C(a){return Zc[a]??{}}var Qs=C(`
|
|
902
902
|
query ResourceIdQuery(
|
|
903
903
|
$organizationSlug: ReadableId!,
|
|
904
904
|
$workspaceSlug: ReadableId,
|
|
@@ -914,7 +914,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
914
914
|
}
|
|
915
915
|
}
|
|
916
916
|
}
|
|
917
|
-
`),
|
|
917
|
+
`),Xs=C(`
|
|
918
918
|
query Organization($slug: ReadableId!) {
|
|
919
919
|
organization(slug: $slug) {
|
|
920
920
|
id
|
|
@@ -926,7 +926,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
926
926
|
email
|
|
927
927
|
}
|
|
928
928
|
}
|
|
929
|
-
`),
|
|
929
|
+
`),Ys=C(`
|
|
930
930
|
query Organizations {
|
|
931
931
|
organizations(first: 300) {
|
|
932
932
|
edges {
|
|
@@ -942,7 +942,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
942
942
|
}
|
|
943
943
|
}
|
|
944
944
|
}
|
|
945
|
-
`),
|
|
945
|
+
`),ep=C(`
|
|
946
946
|
mutation SetupOrganization($payload: CreateConfiguredOrganizationPayload!) {
|
|
947
947
|
createConfiguredOrganization(payload: $payload) {
|
|
948
948
|
organization {
|
|
@@ -956,7 +956,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
956
956
|
}
|
|
957
957
|
}
|
|
958
958
|
}
|
|
959
|
-
`),
|
|
959
|
+
`),tp=C(`
|
|
960
960
|
query FindOrganizationSlug(
|
|
961
961
|
$slugFirstOption: ReadableId!
|
|
962
962
|
$slugSecondOption: ReadableId!
|
|
@@ -968,7 +968,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
968
968
|
slugThirdOption: organizationSlug(slug: $slugThirdOption)
|
|
969
969
|
}
|
|
970
970
|
}
|
|
971
|
-
`),
|
|
971
|
+
`),np=C(`
|
|
972
972
|
query OrganizationMetadata($url: String!) {
|
|
973
973
|
websiteMetadata(url: $url){
|
|
974
974
|
url
|
|
@@ -986,7 +986,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
986
986
|
}
|
|
987
987
|
}
|
|
988
988
|
}
|
|
989
|
-
`);var
|
|
989
|
+
`);var ip=C(`
|
|
990
990
|
query User {
|
|
991
991
|
userAccount {
|
|
992
992
|
id
|
|
@@ -1001,7 +1001,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1001
1001
|
}
|
|
1002
1002
|
}
|
|
1003
1003
|
}
|
|
1004
|
-
`),
|
|
1004
|
+
`),op=C(`
|
|
1005
1005
|
query Username(
|
|
1006
1006
|
$slugFirstOption: ReadableId!
|
|
1007
1007
|
$slugSecondOption: ReadableId!
|
|
@@ -1013,19 +1013,19 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1013
1013
|
slugThirdOption: username(username: $slugThirdOption)
|
|
1014
1014
|
}
|
|
1015
1015
|
}
|
|
1016
|
-
`),
|
|
1016
|
+
`),rp=C(`
|
|
1017
1017
|
query UserEmail($email: String!) {
|
|
1018
1018
|
checkAvailability {
|
|
1019
1019
|
email(email: $email)
|
|
1020
1020
|
}
|
|
1021
1021
|
}
|
|
1022
|
-
`),
|
|
1022
|
+
`),ap=C(`
|
|
1023
1023
|
mutation AcceptInvitation($invitationId: InvitationId!) {
|
|
1024
1024
|
acceptInvitation(invitationId: $invitationId) {
|
|
1025
1025
|
id
|
|
1026
1026
|
}
|
|
1027
1027
|
}
|
|
1028
|
-
`),
|
|
1028
|
+
`),sp=C(`
|
|
1029
1029
|
query Invitations {
|
|
1030
1030
|
invitations(first: 100) {
|
|
1031
1031
|
edges {
|
|
@@ -1045,43 +1045,43 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1045
1045
|
}
|
|
1046
1046
|
}
|
|
1047
1047
|
}
|
|
1048
|
-
`);var
|
|
1048
|
+
`);var pp=C(`
|
|
1049
1049
|
mutation SignIn($payload: SignInPayload!) {
|
|
1050
1050
|
signIn(payload: $payload) {
|
|
1051
1051
|
token
|
|
1052
1052
|
}
|
|
1053
1053
|
}
|
|
1054
|
-
`),
|
|
1054
|
+
`),cp=C(`
|
|
1055
1055
|
mutation SignUp($payload: SignUpPayload!) {
|
|
1056
1056
|
signUp(payload: $payload) {
|
|
1057
1057
|
userId
|
|
1058
1058
|
}
|
|
1059
1059
|
}
|
|
1060
|
-
`),
|
|
1060
|
+
`),lp=C(`
|
|
1061
1061
|
mutation IssueToken($payload: IssueTokenPayload!) {
|
|
1062
1062
|
issueToken(payload: $payload)
|
|
1063
1063
|
}
|
|
1064
|
-
`),
|
|
1064
|
+
`),up=C(`
|
|
1065
1065
|
mutation ResetPassword($payload: ResetPasswordPayload!) {
|
|
1066
1066
|
resetPassword(payload: $payload) {
|
|
1067
1067
|
token
|
|
1068
1068
|
}
|
|
1069
1069
|
}
|
|
1070
|
-
`),
|
|
1070
|
+
`),mp=C(`
|
|
1071
1071
|
mutation RequestPasswordReset($email: String!, $sessionId: UserSessionId) {
|
|
1072
1072
|
sendResetLink(email: $email, sessionId: $sessionId)
|
|
1073
1073
|
}
|
|
1074
|
-
`),
|
|
1074
|
+
`),dp=C(`
|
|
1075
1075
|
mutation RetryActivation($email: String!, $sessionId: UserSessionId!) {
|
|
1076
1076
|
retry {
|
|
1077
1077
|
accountActivation(sessionId: $sessionId, email: $email)
|
|
1078
1078
|
}
|
|
1079
1079
|
}
|
|
1080
|
-
`),
|
|
1080
|
+
`),gp=C(`
|
|
1081
1081
|
mutation CreateSession($redirectDestination: String) {
|
|
1082
1082
|
createSession(redirectDestination: $redirectDestination)
|
|
1083
1083
|
}
|
|
1084
|
-
`),
|
|
1084
|
+
`),fp=C(`
|
|
1085
1085
|
mutation CloseSession($sessionId: UserSessionId!) {
|
|
1086
1086
|
closeSession(sessionId: $sessionId) {
|
|
1087
1087
|
__typename
|
|
@@ -1093,7 +1093,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1093
1093
|
}
|
|
1094
1094
|
}
|
|
1095
1095
|
}
|
|
1096
|
-
`);var Kt=class a{constructor(e){this.client=e;}async getUser(){let{data:e}=await this.client.execute(
|
|
1096
|
+
`);var Kt=class a{constructor(e){this.client=e;}async getUser(){let{data:e}=await this.client.execute(ip),{id:t,user:n}=e.userAccount,{profile:{lastName:i=null}}=n;return {id:t,username:n.profile.firstName,email:n.email,firstName:n.profile.firstName,expertise:n.profile.expertise,...i!==null?{lastName:i}:{}}}async isEmailRegistered(e){let{data:t}=await this.client.execute(rp,{email:e});return !t.checkAvailability.email}async requestPasswordReset(e){await this.client.execute(mp,{email:e.email,sessionId:e.sessionId});}async resetPassword(e){let{data:t}=await this.client.execute(up,{payload:{password:e.password,token:e.token}});return t.resetPassword.token}async retryActivation(e){await this.client.execute(dp,{email:e.email,sessionId:e.sessionId});}async registerUser(e){await this.client.execute(cp,{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(gp,{redirectDestination:e?.destination});return t.createSession}async closeSession(e){let{data:t}=await this.client.execute(fp,{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(pp,{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(lp,{payload:{duration:e.duration}});return t.issueToken}async getOrganization(e){let{data:t}=await this.client.execute(Xs,{slug:e}),n=t.organization??null;return n===null?null:a.normalizeOrganization(n)}async getOrganizations(){let{data:e}=await this.client.execute(Ys);return (e.organizations.edges??[]).flatMap(n=>{let i=n?.node??null;return i===null||i.slug==="demo"?[]:[a.normalizeOrganization(i)]})}async setupOrganization(e){let{data:t}=await this.client.execute(ep,{payload:await this.getOrganizationSetupPayload(e)}),{organization:n}=t.createConfiguredOrganization,{logo:i=null,website:o=null}=n;return {id:n.id,name:n.name,slug:n.slug,type:n.type,email:n.email,...i!==null?{logo:i}:{},...o!==null?{website:o}:{}}}async getOrganizationSetupPayload(e){let t=new URL(e.website),n=await this.getUser(),i=`${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(i,true),type:"PERSONAL"},workspace:{name:"Personal workspace",slug:qt({baseName:i,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 o=await this.getOrganizationMetadata(t),r=`${t.protocol}//${o.domain}`,s=o.logo!==null&&o.logo!==void 0&&o.logo.width>=64&&o.logo.height>=64?o.logo.data:void 0;return {locale:o.languages[0]??e.locale,timeZone:e.timeZone,acceptedTerms:true,organization:{website:r,email:n.email,name:o.siteName,slug:await this.generateOrganizationSlug(o.siteName,false),type:"BUSINESS",logo:s},workspace:{name:o.siteName,slug:qt({baseName:o.siteName,alwaysSuffixed:false}).next().value,logo:s,website:r},applications:[{environment:"PRODUCTION",name:"Website",slug:"website-prod",website:t.origin,platform:o.platform},{environment:"DEVELOPMENT",name:"Website",slug:"website-dev",website:t.origin,platform:o.platform}],audiences:[],components:[],experiences:[],slots:[],redirectUrl:e.redirectUrl}}async getInvitations(){let{data:e}=await this.client.execute(sp);return (e.invitations.edges??[]).flatMap(n=>{let i=n?.node??null;return i===null?[]:[{id:i.id,invitationTime:i.invitationTime,organization:a.normalizeOrganization(i.organization)}]})}async acceptInvitation(e){await this.client.execute(ap,{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(np,{url:e.toString()});return t.websiteMetadata}generateOrganizationSlug(e,t=false){return nt({query:tp,baseName:e,client:this.client,alwaysSuffixed:t})}generateUsername(e){return nt({query:op,baseName:e,client:this.client,alwaysSuffixed:false})}};var yp=C(`
|
|
1097
1097
|
query Workspace($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
|
|
1098
1098
|
organization(slug: $organizationSlug) {
|
|
1099
1099
|
workspace(slug: $workspaceSlug) {
|
|
@@ -1114,7 +1114,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1114
1114
|
}
|
|
1115
1115
|
}
|
|
1116
1116
|
}
|
|
1117
|
-
`),
|
|
1117
|
+
`),hp=C(`
|
|
1118
1118
|
query Workspaces($organizationSlug: ReadableId!) {
|
|
1119
1119
|
organization(slug: $organizationSlug) {
|
|
1120
1120
|
workspaces(first: 100) {
|
|
@@ -1139,7 +1139,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1139
1139
|
}
|
|
1140
1140
|
}
|
|
1141
1141
|
}
|
|
1142
|
-
`),
|
|
1142
|
+
`),Sp=C(`
|
|
1143
1143
|
mutation CreateWorkspace($organizationId: OrganizationId!, $payload: CreateWorkspacePayload!) {
|
|
1144
1144
|
createWorkspace(organizationId: $organizationId, payload: $payload) {
|
|
1145
1145
|
id
|
|
@@ -1158,7 +1158,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1158
1158
|
}
|
|
1159
1159
|
}
|
|
1160
1160
|
}
|
|
1161
|
-
`),
|
|
1161
|
+
`),bp=C(`
|
|
1162
1162
|
query FindWorkspaceSlug(
|
|
1163
1163
|
$organizationId: OrganizationId!
|
|
1164
1164
|
$slugFirstOption: ReadableId!
|
|
@@ -1171,7 +1171,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1171
1171
|
slugThirdOption: workspaceSlug(organizationId: $organizationId, slug: $slugThirdOption)
|
|
1172
1172
|
}
|
|
1173
1173
|
}
|
|
1174
|
-
`),
|
|
1174
|
+
`),Ip=C(`
|
|
1175
1175
|
query WorkspaceFeatures($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
|
|
1176
1176
|
organization(slug: $organizationSlug) {
|
|
1177
1177
|
workspace(slug: $workspaceSlug) {
|
|
@@ -1196,7 +1196,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1196
1196
|
}
|
|
1197
1197
|
}
|
|
1198
1198
|
}
|
|
1199
|
-
`),
|
|
1199
|
+
`),vp=C(`
|
|
1200
1200
|
mutation CreateResources($workspaceId: WorkspaceId!, $payload: CreateWorkspaceResourcePayload!) {
|
|
1201
1201
|
createWorkspaceResources(workspaceId: $workspaceId, payload: $payload) {
|
|
1202
1202
|
slots
|
|
@@ -1208,7 +1208,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1208
1208
|
}
|
|
1209
1209
|
}
|
|
1210
1210
|
}
|
|
1211
|
-
`);var
|
|
1211
|
+
`);var _n=class a{constructor(e,t){this.client=e,this.hierarchyResolver=t;}async getWorkspace(e){let{data:t}=await this.client.execute(yp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),n=t.organization?.workspace??null;return n===null?null:a.normalizeWorkspace(n)}async getWorkspaces(e){let{data:t}=await this.client.execute(hp,{organizationSlug:e.organizationSlug});return (t.organization?.workspaces.edges??[]).flatMap(i=>{let o=i?.node??null;return o===null?[]:[a.normalizeWorkspace(o)]})}static normalizeWorkspace(e){let{logo:t=null,website:n=null,locales:{edges:i=[]}}=e;return {id:e.id,name:e.name,slug:e.slug,timeZone:e.timeZone,defaultLocale:e.defaultLocale,locales:i?.flatMap(o=>{let r=o?.node?.code??null;return r===null?[]:[r]})??[],...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(Sp,{organizationId:t.organizationId,payload:{name:e.name,slug:await this.generateWorkspaceSlug(t.organizationId,e.name),timeZone:e.timeZone,defaultLocale:e.defaultLocale,website:e.website}}),i=n.createWorkspace,{logo:o=null,website:r=null,locales:{edges:s=[]}}=i;return {id:i.id,name:i.name,slug:i.slug,timeZone:i.timeZone,defaultLocale:i.defaultLocale,locales:s?.flatMap(p=>{let c=p?.node?.code??null;return c===null?[]:[c]})??[],...o!==null?{logo:o}:{},...r!==null?{website:r}:{}}}generateWorkspaceSlug(e,t){return nt({query:bp,baseName:t,client:this.client,variables:{organizationId:e}})}};var xp=C(`
|
|
1212
1212
|
query Audiences($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
|
|
1213
1213
|
organization(slug: $organizationSlug) {
|
|
1214
1214
|
workspace(slug: $workspaceSlug) {
|
|
@@ -1225,7 +1225,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1225
1225
|
}
|
|
1226
1226
|
}
|
|
1227
1227
|
}
|
|
1228
|
-
`),
|
|
1228
|
+
`),wp=C(`
|
|
1229
1229
|
query Audience(
|
|
1230
1230
|
$organizationSlug: ReadableId!,
|
|
1231
1231
|
$workspaceSlug: ReadableId!,
|
|
@@ -1242,7 +1242,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1242
1242
|
}
|
|
1243
1243
|
}
|
|
1244
1244
|
}
|
|
1245
|
-
`);var
|
|
1245
|
+
`);var Pp=C(`
|
|
1246
1246
|
query Slots($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
|
|
1247
1247
|
organization(slug: $organizationSlug) {
|
|
1248
1248
|
workspace(slug: $workspaceSlug) {
|
|
@@ -1288,7 +1288,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1288
1288
|
}
|
|
1289
1289
|
}
|
|
1290
1290
|
}
|
|
1291
|
-
`),
|
|
1291
|
+
`),Cp=C(`
|
|
1292
1292
|
query Slot(
|
|
1293
1293
|
$organizationSlug: ReadableId!,
|
|
1294
1294
|
$workspaceSlug: ReadableId!,
|
|
@@ -1335,7 +1335,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1335
1335
|
}
|
|
1336
1336
|
}
|
|
1337
1337
|
}
|
|
1338
|
-
`),
|
|
1338
|
+
`),kp=C(`
|
|
1339
1339
|
query SlotStaticContent(
|
|
1340
1340
|
$organizationSlug: ReadableId!,
|
|
1341
1341
|
$workspaceSlug: ReadableId!,
|
|
@@ -1353,7 +1353,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1353
1353
|
}
|
|
1354
1354
|
}
|
|
1355
1355
|
}
|
|
1356
|
-
`);var
|
|
1356
|
+
`);var Ap=C(`
|
|
1357
1357
|
query ApplicationSlugAvailability(
|
|
1358
1358
|
$workspaceId: WorkspaceId!
|
|
1359
1359
|
$slugFirstOption: ReadableId!
|
|
@@ -1366,7 +1366,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1366
1366
|
slugThirdOption: applicationSlug(workspaceId: $workspaceId, slug: $slugThirdOption)
|
|
1367
1367
|
}
|
|
1368
1368
|
}
|
|
1369
|
-
`),
|
|
1369
|
+
`),Ep=C(`
|
|
1370
1370
|
query Applications($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
|
|
1371
1371
|
organization(slug: $organizationSlug) {
|
|
1372
1372
|
workspace(slug: $workspaceSlug) {
|
|
@@ -1391,7 +1391,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1391
1391
|
}
|
|
1392
1392
|
}
|
|
1393
1393
|
}
|
|
1394
|
-
`),
|
|
1394
|
+
`),Rp=C(`
|
|
1395
1395
|
query Application($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $applicationSlug: ReadableId!) {
|
|
1396
1396
|
organization(slug: $organizationSlug) {
|
|
1397
1397
|
workspace(slug: $workspaceSlug) {
|
|
@@ -1412,7 +1412,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1412
1412
|
}
|
|
1413
1413
|
}
|
|
1414
1414
|
}
|
|
1415
|
-
`),
|
|
1415
|
+
`),Op=C(`
|
|
1416
1416
|
mutation CreateApplication($workspaceId: WorkspaceId!, $payload: CreateWebApplicationPayload!) {
|
|
1417
1417
|
createWebApplication(workspaceId: $workspaceId, payload: $payload) {
|
|
1418
1418
|
id
|
|
@@ -1429,7 +1429,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1429
1429
|
}
|
|
1430
1430
|
}
|
|
1431
1431
|
}
|
|
1432
|
-
`),
|
|
1432
|
+
`),Dp=C(`
|
|
1433
1433
|
mutation CreateApiKey($applicationId: ApplicationId!, $payload: CreateApiKeyPayload!) {
|
|
1434
1434
|
createApiKey(applicationId: $applicationId, payload: $payload) {
|
|
1435
1435
|
apiKey {
|
|
@@ -1472,7 +1472,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1472
1472
|
}
|
|
1473
1473
|
}
|
|
1474
1474
|
}
|
|
1475
|
-
`),
|
|
1475
|
+
`),Mp=C(`
|
|
1476
1476
|
query Component(
|
|
1477
1477
|
$organizationSlug: ReadableId!,
|
|
1478
1478
|
$workspaceSlug: ReadableId!,
|
|
@@ -1505,7 +1505,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1505
1505
|
}
|
|
1506
1506
|
}
|
|
1507
1507
|
}
|
|
1508
|
-
`);var
|
|
1508
|
+
`);var Np=C(`
|
|
1509
1509
|
query Experience(
|
|
1510
1510
|
$organizationSlug: ReadableId!,
|
|
1511
1511
|
$workspaceSlug: ReadableId!,
|
|
@@ -1663,7 +1663,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1663
1663
|
}
|
|
1664
1664
|
}
|
|
1665
1665
|
}
|
|
1666
|
-
`),
|
|
1666
|
+
`),zp=C(`
|
|
1667
1667
|
query Experiences($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $status: [ExperienceStatus!]) {
|
|
1668
1668
|
organization(slug: $organizationSlug) {
|
|
1669
1669
|
workspace(slug: $workspaceSlug) {
|
|
@@ -1719,23 +1719,23 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1719
1719
|
}
|
|
1720
1720
|
}
|
|
1721
1721
|
}
|
|
1722
|
-
`);var
|
|
1722
|
+
`);var $p=C(`
|
|
1723
1723
|
mutation GenerateTyping($workspaceId: WorkspaceId!, $payload: GenerateTypingPayload!) {
|
|
1724
1724
|
generateTyping(workspaceId: $workspaceId, payload: $payload)
|
|
1725
1725
|
}
|
|
1726
|
-
`);function bt(a){return {model:a,api:Object.fromEntries(Object.entries(a).map(([e,t])=>[t,e]))}}var Ra=bt({javascript:"JAVASCRIPT",react:"REACT",nextjs:"NEXT"}),Oa=bt({DEVELOPMENT:"DEVELOPMENT",PRODUCTION:"PRODUCTION"}),$p=bt({NEVER_RECEIVED_TRAFFIC:"NEVER_RECEIVED_TRAFFIC",NOT_RECEIVING_TRAFFIC:"NOT_RECEIVING_TRAFFIC",RECEIVING_TRAFFIC:"RECEIVING_TRAFFIC"}),Zc=bt({PLUG_JS:"PLUG_JS"}),Ta=bt({DRAFT:"DRAFT",ACTIVE:"ACTIVE",SCHEDULED:"SCHEDULED",PAUSED:"PAUSED",ARCHIVED:"ARCHIVED"}),Qc=bt({DRAFT:"DRAFT",ACTIVE:"ACTIVE",SCHEDULED:"SCHEDULED",PAUSED:"PAUSED",FINISHED:"FINISHED",INDIRECTLY_PAUSED:"INDIRECTLY_PAUSED"}),jn=class a{constructor(e,t){this.client=e,this.hierarchyResolver=t;}async getFeatures(e){let{data:t}=await this.client.execute(bp,{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,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(Ap,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.applications.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[a.normalizeApplication(i)]})}async getApplication(e){let{data:t}=await this.client.execute(Ep,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,applicationSlug:e.applicationSlug}),n=t.organization?.workspace?.application??null;return n===null?null:a.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:Oa.api[e.environment],platform:Ra.api[e.platform??"JAVASCRIPT"],publicId:e.publicId,trafficStatus:$p.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(Rp,{workspaceId:t.workspaceId,payload:{name:e.name,website:e.website,environment:Oa.model[e.environment],platform:Ra.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:Oa.api[r.environment],platform:Ra.api[r.platform??"JAVASCRIPT"],publicId:r.publicId,trafficStatus:$p.api[r.applicationStatus],...i!==null?{logo:i}:{}}}async getAudiences(e){let{data:t}=await this.client.execute(vp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.audiences.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[a.normalizeAudience(i)]})}async getAudience(e){let{data:t}=await this.client.execute(xp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,audienceSlug:e.audienceSlug}),n=t.organization?.workspace?.audience??null;return n===null?null:a.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(Tp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.components.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[a.normalizeComponent(i)]})}async getComponent(e){let{data:t}=await this.client.execute(Dp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,componentSlug:e.componentSlug,majorVersion:e.majorVersion}),n=t.organization?.workspace?.component??null;return n===null?null:a.normalizeComponent(n)}static normalizeComponent(e){let{definition:t,metadata:{directReferences:n,indirectReferences:r,referenceMetadata:i}}=e.definition,o=e.description??null;return {id:e.id,name:e.name,slug:e.customId,...o!==null?{description:o}:{},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(wp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.slots.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[a.normalizeSlot(i)]})}async getSlot(e){let{data:t}=await this.client.execute(Pp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,slotSlug:e.slotSlug,majorVersion:e.majorVersion}),n=t.organization?.workspace?.slot??null;return n===null?null:a.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(Cp,{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(zp,{workspaceId:t.workspaceId,payload:{target:Zc.model[e.target],components:e.components,slots:e.slots}});return n.generateTyping}async getExperiences(e){let{data:t}=await this.client.execute(Np,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,status:e.status===void 0?void 0:(Array.isArray(e.status)?e.status:[e.status]).map(r=>Ta.model[r])});return (t.organization?.workspace?.experiences.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[a.normalizeExperience(i)]})}async getExperience(e){let{data:t}=await this.client.execute(Mp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,experienceId:e.experienceId}),n=t.organization?.workspace?.experience??null;return n===null?null:a.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:Ta.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:o=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:Ta.api[e.status],hasExperiments:e.hasExperiments,audiences:t.map(l=>l.customId),slots:Object.values(c),...r!==null?{experiment:{...i!==null?{name:i}:{},...o!==null?{goalId:o}:{},...s!==null?{crossDevice:s}:{},...p!==null?{traffic:p}:{},..."status"in r?{status:Qc.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:a.normalizeLocalizedContent(l.content?.default.contents??[],c),segmented:(l.content?.segmented??[]).map(v=>({id:v.groupId,audiences:v.audiences.map(A=>A.audienceId),content:a.normalizeLocalizedContent(v.contents,c)}))}}})}}:{},content:{default:a.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:a.normalizeLocalizedContent(l.contents,c)}))}}}static normalizeLocalizedContent(e,t){let n={};for(let r of e){let{locale:i,slotId:o}=r,s=t[o];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,o])=>({customId:i,name:o.name,description:o.description,definition:o.schema})),slots:Object.entries(e.slots??{}).map(([i,o])=>({customId:i,name:o.name,component:o.component,defaultContent:Object.entries(o.content).map(([s,p])=>({locale:s,content:p}))})),audiences:Object.entries(e.audiences??{}).map(([i,o])=>({customId:i,name:o.name,criteria:o.criteria})),experiences:(e.experiences??[]).map(i=>{let o=i.experiment??null;return {name:i.name,audiences:i.audiences,slots:i.slots,experiment:o!==null?{name:o.name,goalId:o.goalId,traffic:o.traffic,crossDevice:o.crossDevice===true,variants:o.variants.map(s=>({id:randomUUID(),name:s.name??"",baseline:s.baseline===true,allocation:s.allocation??0,content:a.createContentVariantGroup(s.content)}))}:void 0,content:a.createContentVariantGroup(i.content),validate:true,publish:i.draft!==true}})},{data:{createWorkspaceResources:r}}=await this.client.execute(Ip,{workspaceId:t.workspaceId,payload:n});return {components:Object.fromEntries(n.components.map(({customId:i},o)=>[i,r.components[o]])),slots:Object.fromEntries(n.slots.map(({customId:i},o)=>[i,r.slots[o]])),audiences:Object.fromEntries(n.audiences.map(({customId:i},o)=>[i,r.audiences[o]])),experiences:r.experiences.map(i=>{let o=i.experimentId??null;return {experienceId:i.id,...o!==null?{experimentId:o}:{}}})}}static createContentVariantGroup(e){return {default:{id:randomUUID(),contents:a.createSlotContentMap(e.default??{})},segmented:(e.segmented??[]).map(t=>({id:randomUUID(),audiences:t.audiences,contents:a.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 nt({query:kp,baseName:`${t} ${n==="DEVELOPMENT"?"dev":"prod"}`,client:this.client,variables:{workspaceId:e}})}};var rt;(t=>{function a(){return Intl.DateTimeFormat().resolvedOptions().locale.toLowerCase()}t.getLocale=a;function e(){return Intl.DateTimeFormat().resolvedOptions().timeZone}t.getTimeZone=e;})(rt||={});var It=class a{constructor(e){this.config=e;}static prompt(e){return new a(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 Un=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=rt.getTimeZone(),o=rt.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 It.prompt({input:r,label:"Organization website"}),p=this.notify("Setting up organization");try{let c=await t.setupOrganization({website:s,locale:o,timeZone:i});return p.confirm(`Organization: ${c.name}`),{...c,new:!0}}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,o=setInterval(()=>{i>=n.length?clearInterval(o):r.update(n[i++]);},3e3);return o.unref(),{confirm:(s,p)=>{clearInterval(o),r.confirm(s,p);},stop:s=>{clearInterval(o),r.stop(s);}}}};var De=class a{constructor(e){this.config=e;}static prompt(e){return new a(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 Vn=class a{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 o=n.notify("Loading workspaces"),s=await t.getWorkspaces({organizationSlug:i.slug}),p=a.getDefaultWorkspace(s,e.default);if(p!==null)return o.confirm(`Workspace: ${p.name}`),p;if(o.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,o=t?await De.prompt({input:r,label:"Workspace name",default:e.name}):e.name,s=rt.getLocale(),p=rt.getTimeZone(),c=i.notify("Creating workspace");try{let l=await n.createWorkspace({organizationSlug:e.slug,name:o,website:e.website,defaultLocale:s,timeZone:p});return c.confirm(`Workspace: ${l.name}`),{...l,new:t}}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 Wn=class a{constructor(e){this.config=e;}async handle(e){let{workspaceApi:t,output:n,input:r}=this.config,{organization:i,workspace:o,environment:s}=e,p=n.notify("Loading applications"),c=await t.getApplications({workspaceSlug:o.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(a.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:o,workspace:s,platform:p,environment:c}=e,l=e.new===true,u=l?await De.prompt({input:i,label:c==="DEVELOPMENT"?"Development application name":"Production application name",default:"Website",validator:A=>t.every(M=>M.name.toLowerCase()!==A.toLowerCase()||M.environment!==c)||"Name already in use"}):"Website",g=s.website??o.website??void 0,y=l||!a.isValidUrl(g,c)?await It.prompt({input:i,label:c==="DEVELOPMENT"?"Development application URL":"Production application URL",default:g,validate:A=>URL.canParse(A)?a.isValidUrl(A,c)?true:"Production URL must not be localhost":"Invalid URL"}):g,v=r.notify("Configuring application");try{let A=await n.createApplication({organizationSlug:o.slug,workspaceSlug:s.slug,name:u,website:y,environment:c,platform:p,timeZone:s.timeZone});return v.confirm(a.formatSelection(A)),{...A,new:!0}}finally{v.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 qn=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(Op,{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(se.fromValue),secret:n.createApiKey.apiKeyValue}}};var Ke=class a{constructor(e){this.config=e;}static prompt(e){return new a(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 Kn=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,o=e.username??await Ke.prompt({input:t,label:"Enter your email"}),s=n.notify("Finding account"),p=await r.isEmailRegistered(o);return s.stop(),p?(e.password===void 0&&n.inform("Account found, please sign in"),i.signIn.handle({email:o,password:e.password,retry:true})):(n.inform("New account, please sign up"),i.signUp.handle({email:o}))}logout(){return Promise.resolve()}};var He=class a{constructor(e){this.config=e;}static prompt(e){return new a(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 Hn=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:o}=this.config,s=e??await Ke.prompt({input:this.config.input,label:"Enter your email"}),p=t,c="retry-password";for(;c==="retry-password";){let l=p??await He.prompt({input:r,label:"Password"});p=void 0;let u=i.notify("Checking credentials");try{let g=await o.signIn({email:s,password:l,duration:this.config.tokenDuration});return u.confirm("Logged in"),g}catch(g){if(g instanceof ee){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"),o=await n.createSession({destination:this.config.verificationLinkDestination.accountActivation});await n.retryActivation({email:e,sessionId:o}),i.confirm(`Link sent to \`${e}\``);let s=await this.getInboxLink(r,e),p=this.waitToken(o);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"),o=await n.createSession({destination:this.config.verificationLinkDestination.passwordReset});await n.requestPasswordReset({email:e,sessionId:o}),i.confirm(`Link sent to \`${e}\``);let s=await this.getInboxLink(r,e),p=this.waitToken(o);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 He.prompt({input:e,label:"Enter your new password"}),i=await He.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 Gn=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 o=await De.prompt({input:t,minimumLength:2,maximumLength:30,label:"Name"}),[s,p]=o.replace(/\s+/g," ").trim().split(" "),c=e.email??await Ke.prompt({input:t,label:"Email"}),l=await He.prompt({input:t,label:"Password",validator:M=>/[A-Z]/.test(M)?/[a-z]/.test(M)?/[^A-Za-z]/.test(M)?M.length<8?"Minimum of 8 characters":M.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 M=>M!==null&&await t.confirm({message:"Open your inbox?",default:true})?M.toString():null);g=n.notify("Waiting for account activation");let v=r.wait(await u);y!==null&&await n.open(y);let A=await v;return g.confirm("Account activated"),A}};var Jn=class{constructor(e){this.config=e;}async execute(e){let{output:t,pageForm:n,userApi:r}=this.config,i=await this.config.configurationManager.load(),o=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(o.startsWith("/")?o.slice(1):o,this.config.adminUrl);c.searchParams.set(this.config.adminTokenParameter,p),await t.open(c.toString());}};function pe(a,e){let t=[],n=null;if(traverse(a,{ImportDeclaration:i=>{let{node:o}=i;if(o.source.value!==e.moduleName)return i.skip();t.push({declaration:o});let s=o.importKind??"value";for(let p of o.specifiers)if(!(!f.isImportSpecifier(p)||Yc(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:o,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:o}=i;if(o.importKind==="type"&&e.type==="value"){o.importKind="value";for(let s of o.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,o.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 o=i.importKind??"value";if(o==="value"||o===e.type){let s=f.importSpecifier(f.identifier(e.localName??e.importName),f.identifier(e.importName));return o!==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"),a.program.body.unshift(r),{modified:true,localName:e.localName??e.importName}}function Yc(a){return f.isIdentifier(a)?a.name:a.value}function Je(a,e){let t=typeof a=="string"?Te(a,["jsx","typescript"]):a,n=null;return traverse(t,{ImportDeclaration:r=>{let{node:i}=r;if(!Ht(i.source.value,e.moduleName))return r.skip();for(let o of i.specifiers??[]){if(f.isImportDefaultSpecifier(o)){Ht("default",e.importName)&&(n=o.local.name);continue}if(f.isImportNamespaceSpecifier(o)){Ht("*",e.importName)&&(n=o.local.name);continue}if(f.isImportSpecifier(o)&&Ht(o.imported,e.importName))return n=o.local.name,r.skip()}return r.skip()}}),n}function Ht(a,e){return typeof a!="string"?Ht(f.isIdentifier(a)?a.name:a.value,e):typeof e=="string"?a===e:e.test(a)}function Bn(a){let e=[];for(let[t,n]of Object.entries(a))e.push(f.jsxAttribute(f.jsxIdentifier(t),f.jsxExpressionContainer(it(n))));return e}function it(a){switch(a.type){case "reference":return a.path.length<2?f.identifier(a.path[0]):a.path.slice(2).reduce((e,t)=>f.memberExpression(e,f.identifier(t)),f.memberExpression(f.identifier(a.path[0]),f.identifier(a.path[1])));case "literal":return typeof a.value=="string"?f.stringLiteral(a.value):typeof a.value=="number"?f.numericLiteral(a.value):typeof a.value=="boolean"?f.booleanLiteral(a.value):f.nullLiteral();case "comparison":return f.binaryExpression(a.operator,it(a.left),it(a.right));case "ternary":return f.conditionalExpression(f.binaryExpression(a.condition.operator,it(a.condition.left),it(a.condition.right)),it(a.consequent),it(a.alternate))}}var ot=class a{constructor(e){this.configuration=e;}apply(e,t){let n=Je(e,{importName:this.configuration.wrapper.component,moduleName:this.configuration.wrapper.module}),r=n??this.configuration.wrapper.component,i=[],o=1;if(traverse(e,{ExportDefaultDeclaration:p=>(o=this.wrapDeclaration(p.node.declaration,r,e,t),p.stop()),ExportNamedDeclaration:p=>(i.push(p.node),p.skip())}),o===1&&this.configuration?.fallbackToNamedExports===true)for(let p of i){if(f.isFunctionDeclaration(p.declaration)&&(o=this.wrapBlockStatement(p.declaration.body,r,e,t),o===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)){o=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)&&(o=this.wrapDeclaration(l.init,r,e,t),o===0))break}if(o===0)break}if(o===0&&n===null){let{body:p}=e.program;f.isImportDeclaration(p[0])||p.unshift(f.emptyStatement()),pe(e,{type:"value",moduleName:this.configuration.wrapper.module,importName:this.configuration.wrapper.component});}let s=this.configuration?.fallbackCodemod;return o===1&&s!==void 0?s.apply(e,t):Promise.resolve({modified:o===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 o=i.init??null;if(o!==null)return this.wrapDeclaration(o,t,n,r)}else return this.wrapBlockStatement(i.body,t,n,r)}return 1}wrapBlockStatement(e,t,n,r){let i=a.findReturnStatement(e),o=i?.argument??null;if(i!==null&&o!==null){let s=this.insertWrapper(o,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:o,index:s}=i,p=[...o.children??[]],c=p.splice(s,1)[0];return i.parent.children=p.length===0?[f.jsxText(`
|
|
1727
|
-
`),this.wrapElement(c,t,
|
|
1728
|
-
`)]:[...p.slice(0,s),this.wrapElement(c,t,
|
|
1726
|
+
`);function bt(a){return {model:a,api:Object.fromEntries(Object.entries(a).map(([e,t])=>[t,e]))}}var Ra=bt({javascript:"JAVASCRIPT",react:"REACT",nextjs:"NEXT"}),Oa=bt({DEVELOPMENT:"DEVELOPMENT",PRODUCTION:"PRODUCTION"}),Fp=bt({NEVER_RECEIVED_TRAFFIC:"NEVER_RECEIVED_TRAFFIC",NOT_RECEIVING_TRAFFIC:"NOT_RECEIVING_TRAFFIC",RECEIVING_TRAFFIC:"RECEIVING_TRAFFIC"}),Yc=bt({PLUG_JS:"PLUG_JS"}),Da=bt({DRAFT:"DRAFT",ACTIVE:"ACTIVE",SCHEDULED:"SCHEDULED",PAUSED:"PAUSED",ARCHIVED:"ARCHIVED"}),el=bt({DRAFT:"DRAFT",ACTIVE:"ACTIVE",SCHEDULED:"SCHEDULED",PAUSED:"PAUSED",FINISHED:"FINISHED",INDIRECTLY_PAUSED:"INDIRECTLY_PAUSED"}),Ln=class a{constructor(e,t){this.client=e,this.hierarchyResolver=t;}async getFeatures(e){let{data:t}=await this.client.execute(Ip,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),n=t.organization?.workspace??null;if(n===null)return null;let{quotas:i,capabilities:{features:o}}=n;return {quotas:{audiences:i.audience,remainingAudiences:i.remainingAudiences,components:i.component,remainingComponents:i.remainingComponents,slots:i.slot,remainingSlots:i.remainingSlots,experiences:i.experience,remainingExperiences:i.remainingExperiences,dynamicAttributesPerContent:i.dynamicAttributesPerContent,audiencesPerExperience:i.audiencesPerExperience},features:{crossDevice:o.includes("CROSS_DEVICE_EXPERIMENT"),dataExport:o.includes("API_DATA_EXPORT")}}}async getApplications(e){let{data:t}=await this.client.execute(Ep,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.applications.edges??[]).flatMap(i=>{let o=i?.node??null;return o===null?[]:[a.normalizeApplication(o)]})}async getApplication(e){let{data:t}=await this.client.execute(Rp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,applicationSlug:e.applicationSlug}),n=t.organization?.workspace?.application??null;return n===null?null:a.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:Oa.api[e.environment],platform:Ra.api[e.platform??"JAVASCRIPT"],publicId:e.publicId,trafficStatus:Fp.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(Op,{workspaceId:t.workspaceId,payload:{name:e.name,website:e.website,environment:Oa.model[e.environment],platform:Ra.model[e.platform],timeZone:e.timeZone,slug:await this.generateApplicationSlug(t.workspaceId,e.name,e.environment)}}),i=n.createWebApplication,{logo:o=null}=i;return {id:i.id,name:i.name,slug:i.slug,timeZone:i.settings.timeZone,website:i.website,environment:Oa.api[i.environment],platform:Ra.api[i.platform??"JAVASCRIPT"],publicId:i.publicId,trafficStatus:Fp.api[i.applicationStatus],...o!==null?{logo:o}:{}}}async getAudiences(e){let{data:t}=await this.client.execute(xp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.audiences.edges??[]).flatMap(i=>{let o=i?.node??null;return o===null?[]:[a.normalizeAudience(o)]})}async getAudience(e){let{data:t}=await this.client.execute(wp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,audienceSlug:e.audienceSlug}),n=t.organization?.workspace?.audience??null;return n===null?null:a.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(Tp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.components.edges??[]).flatMap(i=>{let o=i?.node??null;return o===null?[]:[a.normalizeComponent(o)]})}async getComponent(e){let{data:t}=await this.client.execute(Mp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,componentSlug:e.componentSlug,majorVersion:e.majorVersion}),n=t.organization?.workspace?.component??null;return n===null?null:a.normalizeComponent(n)}static normalizeComponent(e){let{definition:t,metadata:{directReferences:n,indirectReferences:i,referenceMetadata:o}}=e.definition,r=e.description??null;return {id:e.id,name:e.name,slug:e.customId,...r!==null?{description:r}:{},definition:t,version:{major:e.definition.version.major,minor:e.definition.version.minor},metadata:{directReferences:n.map(s=>o.find(({componentId:p})=>p===s)?.referenceName??s),indirectReferences:i.map(s=>o.find(({componentId:p})=>p===s)?.referenceName??s)}}}async getSlots(e){let{data:t}=await this.client.execute(Pp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.slots.edges??[]).flatMap(i=>{let o=i?.node??null;return o===null?[]:[a.normalizeSlot(o)]})}async getSlot(e){let{data:t}=await this.client.execute(Cp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,slotSlug:e.slotSlug,majorVersion:e.majorVersion}),n=t.organization?.workspace?.slot??null;return n===null?null:a.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(i=>n.referenceMetadata.find(({componentId:o})=>o===i)?.referenceName??i),indirectReferences:n.indirectReferences.map(i=>n.referenceMetadata.find(({componentId:o})=>o===i)?.referenceName??i)}}}:{},version:{major:e.content.version.major,minor:e.content.version.minor},resolvedDefinition:e.content.componentDefinition.resolvedDefinition,content:Object.fromEntries(e.content.default.map(({locale:i,content:o})=>[i,o]))}}async getSlotStaticContent(e,t){let{data:n}=await this.client.execute(kp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,slotSlug:e.slotSlug,majorVersion:t});return (n.organization?.workspace?.slot?.staticContent??[]).map(o=>({locale:o.locale,content:o.content}))}async generateTypes(e){let t=await this.hierarchyResolver.getHierarchy({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),{data:n}=await this.client.execute($p,{workspaceId:t.workspaceId,payload:{target:Yc.model[e.target],components:e.components,slots:e.slots}});return n.generateTyping}async getExperiences(e){let{data:t}=await this.client.execute(zp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,status:e.status===void 0?void 0:(Array.isArray(e.status)?e.status:[e.status]).map(i=>Da.model[i])});return (t.organization?.workspace?.experiences.edges??[]).flatMap(i=>{let o=i?.node??null;return o===null?[]:[a.normalizeExperience(o)]})}async getExperience(e){let{data:t}=await this.client.execute(Np,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,experienceId:e.experienceId}),n=t.organization?.workspace?.experience??null;return n===null?null:a.normalizeExperienceDetails(n)}static normalizeExperience(e){let t=e.settings?.audiences??e.draft?.audiences??[],n=e.settings?.slots??e.draft?.slots??[],i=e.currentExperiment?.name??e.draft?.experiment?.name??null;return {id:e.id,name:e.name,priority:e.priority??e.draft?.priority??0,status:Da.api[e.status],audiences:t.map(o=>o.customId),slots:n.flatMap(({slot:o=null})=>o===null?[]:[o.customId]),...i!==null?{experiment:{name:i}}:{}}}static normalizeExperienceDetails(e){let t=e.settings?.audiences??e.draft?.audiences??[],n=e.settings?.slots??e.draft?.slots??[],i=e.currentExperiment??e.draft?.experiment??null,{name:o=null,goalId:r=null,crossDevice:s=null,traffic:p=null}=i??{},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:Da.api[e.status],hasExperiments:e.hasExperiments,audiences:t.map(l=>l.customId),slots:Object.values(c),...i!==null?{experiment:{...o!==null?{name:o}:{},...r!==null?{goalId:r}:{},...s!==null?{crossDevice:s}:{},...p!==null?{traffic:p}:{},..."status"in i?{status:el.api[i.status]}:{},variants:(i.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:a.normalizeLocalizedContent(l.content?.default.contents??[],c),segmented:(l.content?.segmented??[]).map(v=>({id:v.groupId,audiences:v.audiences.map(A=>A.audienceId),content:a.normalizeLocalizedContent(v.contents,c)}))}}})}}:{},content:{default:a.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:a.normalizeLocalizedContent(l.contents,c)}))}}}static normalizeLocalizedContent(e,t){let n={};for(let i of e){let{locale:o,slotId:r}=i,s=t[r];s!==void 0&&(n[s]===void 0&&(n[s]={}),n[s][o]=i.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(([o,r])=>({customId:o,name:r.name,description:r.description,definition:r.schema})),slots:Object.entries(e.slots??{}).map(([o,r])=>({customId:o,name:r.name,component:r.component,defaultContent:Object.entries(r.content).map(([s,p])=>({locale:s,content:p}))})),audiences:Object.entries(e.audiences??{}).map(([o,r])=>({customId:o,name:r.name,criteria:r.criteria})),experiences:(e.experiences??[]).map(o=>{let r=o.experiment??null;return {name:o.name,audiences:o.audiences,slots:o.slots,experiment:r!==null?{name:r.name,goalId:r.goalId,traffic:r.traffic,crossDevice:r.crossDevice===true,variants:r.variants.map(s=>({id:randomUUID(),name:s.name??"",baseline:s.baseline===true,allocation:s.allocation??0,content:a.createContentVariantGroup(s.content)}))}:void 0,content:a.createContentVariantGroup(o.content),validate:true,publish:o.draft!==true}})},{data:{createWorkspaceResources:i}}=await this.client.execute(vp,{workspaceId:t.workspaceId,payload:n});return {components:Object.fromEntries(n.components.map(({customId:o},r)=>[o,i.components[r]])),slots:Object.fromEntries(n.slots.map(({customId:o},r)=>[o,i.slots[r]])),audiences:Object.fromEntries(n.audiences.map(({customId:o},r)=>[o,i.audiences[r]])),experiences:i.experiences.map(o=>{let r=o.experimentId??null;return {experienceId:o.id,...r!==null?{experimentId:r}:{}}})}}static createContentVariantGroup(e){return {default:{id:randomUUID(),contents:a.createSlotContentMap(e.default??{})},segmented:(e.segmented??[]).map(t=>({id:randomUUID(),audiences:t.audiences,contents:a.createSlotContentMap(t.content)}))}}static createSlotContentMap(e){return Object.entries(e).flatMap(([t,n])=>Object.entries(n).map(([i,o])=>({slot:t,locale:i,content:o})))}generateApplicationSlug(e,t,n){return nt({query:Ap,baseName:`${t} ${n==="DEVELOPMENT"?"dev":"prod"}`,client:this.client,variables:{workspaceId:e}})}};var it;(t=>{function a(){return Intl.DateTimeFormat().resolvedOptions().locale.toLowerCase()}t.getLocale=a;function e(){return Intl.DateTimeFormat().resolvedOptions().timeZone}t.getTimeZone=e;})(it||={});var It=class a{constructor(e){this.config=e;}static prompt(e){return new a(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 Un=class{constructor(e){this.config=e;}async handle(e={}){let{userApi:t,output:n,input:i}=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 i.select({message:"Select organization",options:l.map(u=>({value:u,label:u.name}))})}let o=it.getTimeZone(),r=it.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 It.prompt({input:i,label:"Organization website"}),p=this.notify("Setting up organization");try{let c=await t.setupOrganization({website:s,locale:r,timeZone:o});return p.confirm(`Organization: ${c.name}`),{...c,new:!0}}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"],i=t.notify(e),o=0,r=setInterval(()=>{o>=n.length?clearInterval(r):i.update(n[o++]);},3e3);return r.unref(),{confirm:(s,p)=>{clearInterval(r),i.confirm(s,p);},stop:s=>{clearInterval(r),i.stop(s);}}}};var Te=class a{constructor(e){this.config=e;}static prompt(e){return new a(e).handle()}handle(){let{input:e,validator:t,minimumLength:n=2,maximumLength:i=30}=this.config;return e.prompt({message:this.config.label,default:this.config.default,initial:this.config.initial,validate:o=>/(^\s|\s$|\s{2,})/.test(o)?"No leading, trailing, or multiple spaces.":o.length<n?`Minimum of ${n} characters`:o.length>i?`Maximum of ${i} characters`:t?.(o)??true})}};var Vn=class a{constructor(e){this.config=e;}async handle(e){let{organizationApi:t,output:n,input:i}=this.config,{organization:o}=e;if(e.new===false){let r=n.notify("Loading workspaces"),s=await t.getWorkspaces({organizationSlug:o.slug}),p=a.getDefaultWorkspace(s,e.default);if(p!==null)return r.confirm(`Workspace: ${p.name}`),p;if(r.stop(),s.length>0)return i.select({message:"Select workspace",options:s.map(c=>({value:c,label:c.name}))})}return this.setupWorkspace(o,e.new===true)}async setupWorkspace(e,t){let{organizationApi:n,input:i,output:o}=this.config,r=t?await Te.prompt({input:i,label:"Workspace name",default:e.name}):e.name,s=it.getLocale(),p=it.getTimeZone(),c=o.notify("Creating workspace");try{let l=await n.createWorkspace({organizationSlug:e.slug,name:r,website:e.website,defaultLocale:s,timeZone:p});return c.confirm(`Workspace: ${l.name}`),{...l,new:t}}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 Wn=class a{constructor(e){this.config=e;}async handle(e){let{workspaceApi:t,output:n,input:i}=this.config,{organization:o,workspace:r,environment:s}=e,p=n.notify("Loading applications"),c=await t.getApplications({workspaceSlug:r.slug,organizationSlug:o.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(a.formatSelection(u)),u}return i.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:i,input:o}=this.config,{organization:r,workspace:s,platform:p,environment:c}=e,l=e.new===true,u=l?await Te.prompt({input:o,label:c==="DEVELOPMENT"?"Development application name":"Production application name",default:"Website",validator:A=>t.every(M=>M.name.toLowerCase()!==A.toLowerCase()||M.environment!==c)||"Name already in use"}):"Website",g=s.website??r.website??void 0,y=l||!a.isValidUrl(g,c)?await It.prompt({input:o,label:c==="DEVELOPMENT"?"Development application URL":"Production application URL",default:g,validate:A=>URL.canParse(A)?a.isValidUrl(A,c)?true:"Production URL must not be localhost":"Invalid URL"}):g,v=i.notify("Configuring application");try{let A=await n.createApplication({organizationSlug:r.slug,workspaceSlug:s.slug,name:u,website:y,environment:c,platform:p,timeZone:s.timeZone});return v.confirm(a.formatSelection(A)),{...A,new:!0}}finally{v.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 qn=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(Dp,{applicationId:t.applicationId,payload:{name:e.name,permissions:e.permissions}}),{apiKey:i}=n.createApiKey;return {id:i.id,name:i.name,permissions:i.permissions.map(se.fromValue),secret:n.createApiKey.apiKeyValue}}};var Ke=class a{constructor(e){this.config=e;}static prompt(e){return new a(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 Kn=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:i,form:o}=this.config,r=e.username??await Ke.prompt({input:t,label:"Enter your email"}),s=n.notify("Finding account"),p=await i.isEmailRegistered(r);return s.stop(),p?(e.password===void 0&&n.inform("Account found, please sign in"),o.signIn.handle({email:r,password:e.password,retry:true})):(n.inform("New account, please sign up"),o.signUp.handle({email:r}))}logout(){return Promise.resolve()}};var He=class a{constructor(e){this.config=e;}static prompt(e){return new a(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 Hn=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:i,output:o,userApi:r}=this.config,s=e??await Ke.prompt({input:this.config.input,label:"Enter your email"}),p=t,c="retry-password";for(;c==="retry-password";){let l=p??await He.prompt({input:i,label:"Password"});p=void 0;let u=o.notify("Checking credentials");try{let g=await r.signIn({email:s,password:l,duration:this.config.tokenDuration});return u.confirm("Logged in"),g}catch(g){if(g instanceof ee){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 i.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 i.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);default:return o.exit()}}async retryActivation(e){let{output:t,userApi:n,emailLinkGenerator:{verification:i}}=this.config,o=t.notify("Sending email"),r=await n.createSession({destination:this.config.verificationLinkDestination.accountActivation});await n.retryActivation({email:e,sessionId:r}),o.confirm(`Link sent to \`${e}\``);let s=await this.getInboxLink(i,e),p=this.waitToken(r);return s!==null&&await t.open(s),p}async resetPassword(e){let{output:t,userApi:n,emailLinkGenerator:{recovery:i}}=this.config,o=t.notify("Sending link to reset password"),r=await n.createSession({destination:this.config.verificationLinkDestination.passwordReset});await n.requestPasswordReset({email:e,sessionId:r}),o.confirm(`Link sent to \`${e}\``);let s=await this.getInboxLink(i,e),p=this.waitToken(r);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 i=await He.prompt({input:e,label:"Enter your new password"}),o=await He.prompt({input:e,label:"Confirm your new password"});if(i!==o){t.warn("Passwords do not match, please try again");continue}n=i;}return n}async getInboxLink(e,t){let{input:n}=this.config,i=await e(t);return i!==null&&await n.confirm({message:"Open your inbox?",default:true})?i.toString():null}async waitToken(e){let{output:t,listener:n}=this.config,i=t.notify("Waiting for confirmation"),o=await n.wait(e);return i.confirm("Login completed"),o}};var Gn=class{constructor(e){this.config=e;}async handle(e){let{input:t,output:n,listener:i,userApi:o}=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 r=await Te.prompt({input:t,minimumLength:2,maximumLength:30,label:"Name"}),[s,p]=r.replace(/\s+/g," ").trim().split(" "),c=e.email??await Ke.prompt({input:t,label:"Email"}),l=await He.prompt({input:t,label:"Password",validator:M=>/[A-Z]/.test(M)?/[a-z]/.test(M)?/[^A-Za-z]/.test(M)?M.length<8?"Minimum of 8 characters":M.length>256?"Maximum of 256 characters":true:"Must contain a special character":"Must contain a lowercase letter":"Must contain an uppercase letter"}),u=o.createSession({destination:this.config.verificationLinkDestination}),g=n.notify("Creating account");await o.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 M=>M!==null&&await t.confirm({message:"Open your inbox?",default:true})?M.toString():null);g=n.notify("Waiting for account activation");let v=i.wait(await u);y!==null&&await n.open(y);let A=await v;return g.confirm("Account activated"),A}};var Jn=class{constructor(e){this.config=e;}async execute(e){let{output:t,pageForm:n,userApi:i}=this.config,o=await this.config.configurationManager.load(),r=await n.handle({page:e.page,organizationSlug:o.organization,workspaceSlug:o.workspace,devApplicationSlug:o.applications.development,prodApplicationSlug:o.applications.production}),s=t.notify("Logging in..."),p=await i.issueToken({duration:this.config.adminTokenDuration});s.stop();let c=new URL(r.startsWith("/")?r.slice(1):r,this.config.adminUrl);c.searchParams.set(this.config.adminTokenParameter,p),await t.open(c.toString());}};function pe(a,e){let t=[],n=null;if(traverse(a,{ImportDeclaration:o=>{let{node:r}=o;if(r.source.value!==e.moduleName)return o.skip();t.push({declaration:r});let s=r.importKind??"value";for(let p of r.specifiers)if(!(!f.isImportSpecifier(p)||nl(p.imported)!==e.importName)){if(s==="value"&&(p.importKind===null||p.importKind===e.type)||s==="type"&&e.type==="type")return n=p.local.name,o.stop();t.unshift({declaration:r,specifier:p,localName:p.local.name});}return o.skip()}}),n!==null)return {modified:false,localName:n};if(t.length>0){for(let o of t){let{declaration:r}=o;if(r.importKind==="type"&&e.type==="value"){r.importKind="value";for(let s of r.specifiers)f.isImportSpecifier(s)&&s!==o.specifier&&(s.importKind="type");if(o.localName===void 0){let s=f.importSpecifier(f.identifier(e.localName??e.importName),f.identifier(e.importName));s.importKind=e.type,r.specifiers.push(s);}return {modified:true,localName:o.localName??e.importName}}if(o.specifier!==void 0&&o.specifier.importKind==="type"&&e.type==="value")return o.specifier.importKind="value",{modified:true,localName:o.localName}}for(let{declaration:o}of t){let r=o.importKind??"value";if(r==="value"||r===e.type){let s=f.importSpecifier(f.identifier(e.localName??e.importName),f.identifier(e.importName));return r!==e.type&&(s.importKind="type"),o.specifiers.push(s),{modified:true,localName:e.localName??e.importName}}}}let i=f.importDeclaration([f.importSpecifier(f.identifier(e.localName??e.importName),f.identifier(e.importName))],f.stringLiteral(e.moduleName));return e.type==="type"&&(i.importKind="type"),a.program.body.unshift(i),{modified:true,localName:e.localName??e.importName}}function nl(a){return f.isIdentifier(a)?a.name:a.value}function Je(a,e){let t=typeof a=="string"?De(a,["jsx","typescript"]):a,n=null;return traverse(t,{ImportDeclaration:i=>{let{node:o}=i;if(!Ht(o.source.value,e.moduleName))return i.skip();for(let r of o.specifiers??[]){if(f.isImportDefaultSpecifier(r)){Ht("default",e.importName)&&(n=r.local.name);continue}if(f.isImportNamespaceSpecifier(r)){Ht("*",e.importName)&&(n=r.local.name);continue}if(f.isImportSpecifier(r)&&Ht(r.imported,e.importName))return n=r.local.name,i.skip()}return i.skip()}}),n}function Ht(a,e){return typeof a!="string"?Ht(f.isIdentifier(a)?a.name:a.value,e):typeof e=="string"?a===e:e.test(a)}function Bn(a){let e=[];for(let[t,n]of Object.entries(a))e.push(f.jsxAttribute(f.jsxIdentifier(t),f.jsxExpressionContainer(ot(n))));return e}function ot(a){switch(a.type){case "reference":return a.path.length<2?f.identifier(a.path[0]):a.path.slice(2).reduce((e,t)=>f.memberExpression(e,f.identifier(t)),f.memberExpression(f.identifier(a.path[0]),f.identifier(a.path[1])));case "literal":return typeof a.value=="string"?f.stringLiteral(a.value):typeof a.value=="number"?f.numericLiteral(a.value):typeof a.value=="boolean"?f.booleanLiteral(a.value):f.nullLiteral();case "comparison":return f.binaryExpression(a.operator,ot(a.left),ot(a.right));case "ternary":return f.conditionalExpression(f.binaryExpression(a.condition.operator,ot(a.condition.left),ot(a.condition.right)),ot(a.consequent),ot(a.alternate))}}var rt=class a{constructor(e){this.configuration=e;}apply(e,t){let n=Je(e,{importName:this.configuration.wrapper.component,moduleName:this.configuration.wrapper.module}),i=n??this.configuration.wrapper.component,o=[],r=1;if(traverse(e,{ExportDefaultDeclaration:p=>(r=this.wrapDeclaration(p.node.declaration,i,e,t),p.stop()),ExportNamedDeclaration:p=>(o.push(p.node),p.skip())}),r===1&&this.configuration?.fallbackToNamedExports===true)for(let p of o){if(f.isFunctionDeclaration(p.declaration)&&(r=this.wrapBlockStatement(p.declaration.body,i,e,t),r===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,i,e,t)===0:false)){r=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)&&(r=this.wrapDeclaration(l.init,i,e,t),r===0))break}if(r===0)break}if(r===0&&n===null){let{body:p}=e.program;f.isImportDeclaration(p[0])||p.unshift(f.emptyStatement()),pe(e,{type:"value",moduleName:this.configuration.wrapper.module,importName:this.configuration.wrapper.component});}let s=this.configuration?.fallbackCodemod;return r===1&&s!==void 0?s.apply(e,t):Promise.resolve({modified:r===0,result:e})}wrapDeclaration(e,t,n,i){if(f.isArrowFunctionExpression(e)){if(f.isBlockStatement(e.body))return this.wrapBlockStatement(e.body,t,n,i);let o=this.insertWrapper(e.body,t,n,i);return o.result!==0?o.result:(e.body=o.node,0)}if(f.isFunctionExpression(e)||f.isFunctionDeclaration(e))return this.wrapBlockStatement(e.body,t,n,i);if(f.isIdentifier(e)){let o=this.findComponentDeclaration(n,e.name);if(o!==null)if(f.isVariableDeclarator(o)){let r=o.init??null;if(r!==null)return this.wrapDeclaration(r,t,n,i)}else return this.wrapBlockStatement(o.body,t,n,i)}return 1}wrapBlockStatement(e,t,n,i){let o=a.findReturnStatement(e),r=o?.argument??null;if(o!==null&&r!==null){let s=this.insertWrapper(r,t,n,i);return s.result!==0?s.result:(o.argument=f.parenthesizedExpression(s.node),0)}return 1}insertWrapper(e,t,n,i){if(this.containsElement(e,t))return {result:2,node:e};let o=this.findTargetChildren(n,e);if(o!==null){let{parent:r,index:s}=o,p=[...r.children??[]],c=p.splice(s,1)[0];return o.parent.children=p.length===0?[f.jsxText(`
|
|
1727
|
+
`),this.wrapElement(c,t,i),f.jsxText(`
|
|
1728
|
+
`)]:[...p.slice(0,s),this.wrapElement(c,t,i),...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,i)}:{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(`
|
|
1729
1729
|
`),e,f.jsxText(`
|
|
1730
|
-
`)])}getProviderProps(e){return Bn({...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(o){let{node:s}=o;if(s===t)return o.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)};}}}),o.stop()}}),n)}static findReturnStatement(e){let t=null;return traverseFast(e,n=>{t===null&&f.isReturnStatement(n)&&(t=n);}),t}};var il="default"in Ma?Ma.default:Ma,xe=class{constructor(e){this.codemod=e.codemod;}async apply(e,t){let n=parse(e,{parser:{parse:(i,o)=>{let s=il(o);return s.plugins.push("jsx","typescript"),parse$1(i,s)}}}),r=await this.codemod.apply(n,t);return r.modified?{modified:true,result:print(r.result,{reuseWhitespace:false}).code}:{modified:false,result:e}}};function Lp(a,e){let t=typeof a=="string"?Te(a,["jsx","typescript"]):a,n=false;return traverse(t,{ExportAllDeclaration:r=>{let{node:i}=r;return !f.isStringLiteral(i.source)||!Na(i.source,e.moduleName)||(n=true),r.skip()},ExportNamedDeclaration:r=>{let{node:i}=r;if(!f.isStringLiteral(i.source)||!Na(i.source,e.moduleName))return r.skip();if(e.importName===void 0)return n=true,r.skip();for(let o of i.specifiers)if(f.isExportSpecifier(o)&&Na(o.local,e.importName))return n=true,r.skip();return r.skip()}}),n}function Na(a,e){let t=f.isIdentifier(a)?a.name:a.value;return typeof e=="string"?t===e:e.test(t)}function jp(a,e){let t=[],n=false,r=false;if(traverse(a,{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)||za(u.local)!==e.importName||e.exportName!==void 0&&za(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}=a.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!==za(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 o=f.exportNamedDeclaration(null,[f.exportSpecifier(f.identifier(e.importName),f.identifier(e.exportName??e.importName))],f.stringLiteral(e.moduleName));return e.type==="type"&&(o.exportKind="type"),i.push(o),true}function za(a){return f.isIdentifier(a)?a.name:a.value}var Zn=class a{constructor(e){this.configuration=e;}apply(e){let{body:t}=e.program,n=Lp(e,{moduleName:this.configuration.import.module,importName:this.configuration.import.proxyName}),r=a.findConfig(e),i=()=>{t.push(f.exportNamedDeclaration(f.variableDeclaration("const",[f.variableDeclarator(f.identifier("config"),f.objectExpression([f.objectProperty(f.identifier("matcher"),f.stringLiteral(this.configuration.matcherPattern))]))])));};if(n)return r!==null?Promise.resolve({modified:false,result:e}):(i(),Promise.resolve({modified:true,result:e}));let o=Je(e,{moduleName:this.configuration.import.module,importName:this.configuration.import.proxyFactoryName}),s=Je(e,{moduleName:this.configuration.import.module,importName:this.configuration.import.proxyName}),p=[];if(o!==null&&p.push(o),s!==null&&p.push(s),p.length>0&&a.isCalled(e,p))return Promise.resolve({modified:false,result:e});let c=a.refactorProxy(e,this.configuration.exportName,o??this.configuration.import.proxyFactoryName,r!==null&&r.matcher?r.name:void 0);if(c===null){if(r===null)return jp(e,{type:"value",moduleName:this.configuration.import.module,importName:this.configuration.import.proxyName}),i(),Promise.resolve({modified:true,result:e});c=f.exportDefaultDeclaration(f.callExpression(f.identifier(o??this.configuration.import.proxyFactoryName),[f.objectExpression([f.objectProperty(f.identifier("matcher"),f.memberExpression(f.identifier(r.name),f.identifier("matcher")))])])),t.push(c);}if(r!==null){this.configureMatcher(r.object,this.configuration.matcherPattern);let l=t.indexOf(r.root),u=t.indexOf(c);if(l>u){t.splice(u,0,...t.splice(l,1));for(let g of a.findReferencesFrom(r.root,e.program)){let y=t.indexOf(g);y>u&&t.splice(u,0,...t.splice(y,1));}}}return o===null&&pe(e,{type:"value",moduleName:this.configuration.import.module,importName:this.configuration.import.proxyFactoryName}),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(o=>f.isStringLiteral(o)&&o.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 refactorProxy(e,t,n,r){let i=null;return traverse(e,{ExportNamedDeclaration:o=>{let{node:s}=o,{declaration:p,specifiers:c=[]}=s;if(f.isFunctionDeclaration(p))return f.isFunctionDeclaration(s.declaration)&&f.isIdentifier(s.declaration.id)&&s.declaration.id.name===t?(o.replaceWith(f.exportNamedDeclaration(f.variableDeclaration("const",[f.variableDeclarator(f.identifier(t),a.wrapProxy(f.isFunctionDeclaration(s.declaration)?a.createFunctionExpression(s.declaration):s.declaration,n,r))]),[])),i=a.getRootNode(o),o.stop()):o.skip();if(f.isVariableDeclaration(p)){for(let l of p.declarations)if(f.isVariableDeclarator(l)&&f.isIdentifier(l.id)&&l.id.name===t){let u=l.init??null;if(u!==null)return l.init=a.wrapProxy(u,n,r),i=a.getRootNode(o),o.stop()}}for(let l of c)if(f.isExportSpecifier(l)&&f.isIdentifier(l.exported)&&f.isIdentifier(l.local)&&[t,"default"].includes(l.exported.name))return i=a.replaceProxyDeclaration(e,l.local.name,n,r),o.stop();return o.skip()},ExportDefaultDeclaration:o=>{let{node:s}=o,{declaration:p}=s;return f.isArrowFunctionExpression(p)?(o.replaceWith(f.exportDefaultDeclaration(a.wrapProxy(p,n,r))),i=a.getRootNode(o),o.stop()):f.isFunctionDeclaration(p)?(o.replaceWith(f.exportDefaultDeclaration(a.wrapProxy(a.createFunctionExpression(p,true),n,r))),i=a.getRootNode(o),o.stop()):f.isIdentifier(p)?(i=a.replaceProxyDeclaration(e,p.name,n,r),o.stop()):o.skip()}}),i}static replaceProxyDeclaration(e,t,n,r){let i=null;return traverse(e,{VariableDeclarator:o=>{let{node:s}=o;if(f.isIdentifier(s.id)&&s.id.name===t){let p=s.init??null;return p!==null&&(s.init=a.wrapProxy(p,n,r),i=a.getRootNode(o)),o.stop()}return o.skip()},FunctionDeclaration:o=>{let{node:s}=o;return f.isIdentifier(s.id)&&s.id.name===t?(o.replaceWith(a.wrapFunctionDeclaration(s,n,r,f.isIdentifier(s.id)?s.id.name:void 0)),i=a.getRootNode(o),o.stop()):o.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 o of r.declarations)if(f.isVariableDeclarator(o)&&f.isIdentifier(o.id)&&o.id.name==="config"){let s=f.isIdentifier(o.init)?a.findVariableDeclarator(e,o.init.name):{name:"config",root:a.getRootNode(n),declaration:o};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:a.hasMatcherProperty(s.declaration.init)},n.stop()}}for(let o of i)if(f.isExportSpecifier(o)&&f.isIdentifier(o.exported)&&f.isIdentifier(o.local)&&o.exported.name==="config"){let s=a.findVariableDeclarator(e,o.local.name);return s!==null&&f.isObjectExpression(s.declaration.init)&&(t={name:s.name,root:s.root,object:s.declaration.init,matcher:a.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=a.findVariableDeclarator(e,i.init.name):n={name:t,root:a.getRootNode(r),declaration:i},r.stop()):r.skip()}}),n}static wrapProxy(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="proxy"){return f.variableDeclaration("const",[f.variableDeclarator(f.identifier(r),a.wrapProxy(a.createFunctionExpression(e),t,n))])}static findReferencesFrom(e,t){let n=new Set;traverse(t,{enter:i=>{let{node:o}=i;if(o===e)return i.traverse({Identifier:function(p){let c=p.node;return a.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:o}=i;return f.isIdentifier(o.id)&&n.has(o.id.name)&&r.push(a.getRootNode(i)),i.skip()},FunctionDeclaration:i=>{if(!f.isProgram(i.parent))return;let{node:o}=i;return f.isIdentifier(o.id)&&n.has(o.id.name)&&r.push(a.getRootNode(i)),i.skip()},ClassDeclaration:i=>{if(!f.isProgram(i.parent))return;let{node:o}=i;return f.isIdentifier(o.id)&&n.has(o.id.name)&&r.push(a.getRootNode(i)),i.skip()}}),[...new Set(r.flatMap(i=>[i,...a.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 we=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 Pe=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 qe("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 qe("Failed to write file",{cause:i,details:[`File: file://${e.replace(/\\/g,"/")}`]})}return {modified:r.modified,result:e}}};var Qn=class{constructor(e){this.configuration=e;}apply(e,t={}){let n=t.typescript??false,{body:r}=e.program,i=pe(e,{type:"value",moduleName:this.configuration.provider.module,importName:this.configuration.provider.component}),o=n?pe(e,{type:"type",moduleName:"react",importName:"PropsWithChildren"}):null,s=n?pe(e,{type:"type",moduleName:"react",importName:"ReactNode"}):null,p=f.objectPattern([f.objectProperty(f.identifier("children"),f.identifier("children"))]);o!==null&&(p.typeAnnotation=f.tsTypeAnnotation(f.tsTypeReference(f.identifier(o.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(`
|
|
1730
|
+
`)])}getProviderProps(e){return Bn({...this.configuration.wrapper.props,...e?.props})}containsElement(e,t){let n=false;return traverseFast(e,i=>{!n&&f.isJSXOpeningElement(i)&&f.isJSXIdentifier(i.name)&&i.name.name===t&&(n=true);}),n}findComponentDeclaration(e,t){let n=null;return traverse(e,{VariableDeclaration:i=>{if(!f.isProgram(i.parent))return i.skip();for(let o of i.node.declarations)if(f.isVariableDeclarator(o)&&f.isIdentifier(o.id)&&o.id.name===t)return n=o,i.stop();return i.skip()},FunctionDeclaration:i=>{if(!f.isProgram(i.parent))return i.skip();let{id:o}=i.node;return f.isIdentifier(o)&&o.name===t?(n=i.node,i.stop()):i.skip()}}),n}findTargetChildren(e,t){let n=null,{configuration:i}=this;return i.targets?.variable===void 0&&i.targets?.component===void 0?null:(traverse(e,{enter:function(r){let{node:s}=r;if(s===t)return r.traverse({JSXExpressionContainer:p=>{let{expression:c}=p.node;if(i.targets?.variable!==void 0&&f.isIdentifier(c)&&c.name===i.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(i.targets?.component!==void 0&&f.isJSXOpeningElement(c)&&f.isJSXIdentifier(c.name)&&c.name.name===i.targets.component&&p.parent!==null){let l=p.parent;n={parent:l,index:l.children.indexOf(p.node)};}}}),r.stop()}}),n)}static findReturnStatement(e){let t=null;return traverseFast(e,n=>{t===null&&f.isReturnStatement(n)&&(t=n);}),t}};var sl="default"in Ma?Ma.default:Ma,xe=class{constructor(e){this.codemod=e.codemod;}async apply(e,t){let n=parse(e,{parser:{parse:(o,r)=>{let s=sl(r);return s.plugins.push("jsx","typescript"),parse$1(o,s)}}}),i=await this.codemod.apply(n,t);return i.modified?{modified:true,result:print(i.result,{reuseWhitespace:false}).code}:{modified:false,result:e}}};function Lp(a,e){let t=typeof a=="string"?De(a,["jsx","typescript"]):a,n=false;return traverse(t,{ExportAllDeclaration:i=>{let{node:o}=i;return !f.isStringLiteral(o.source)||!Na(o.source,e.moduleName)||(n=true),i.skip()},ExportNamedDeclaration:i=>{let{node:o}=i;if(!f.isStringLiteral(o.source)||!Na(o.source,e.moduleName))return i.skip();if(e.importName===void 0)return n=true,i.skip();for(let r of o.specifiers)if(f.isExportSpecifier(r)&&Na(r.local,e.importName))return n=true,i.skip();return i.skip()}}),n}function Na(a,e){let t=f.isIdentifier(a)?a.name:a.value;return typeof e=="string"?t===e:e.test(t)}function Up(a,e){let t=[],n=false,i=false;if(traverse(a,{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,i=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",i=true),s.stop();if(e.importName===void 0||!f.isExportSpecifier(u)||za(u.local)!==e.importName||e.exportName!==void 0&&za(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 i;let{body:o}=a.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!==za(g.exported)||e.type==="type"&&l!=="type"&&g.exportKind!=="type");u.length===0?o.splice(o.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"),o.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 r=f.exportNamedDeclaration(null,[f.exportSpecifier(f.identifier(e.importName),f.identifier(e.exportName??e.importName))],f.stringLiteral(e.moduleName));return e.type==="type"&&(r.exportKind="type"),o.push(r),true}function za(a){return f.isIdentifier(a)?a.name:a.value}var Zn=class a{constructor(e){this.configuration=e;}apply(e){let{body:t}=e.program,n=Lp(e,{moduleName:this.configuration.import.module,importName:this.configuration.import.proxyName}),i=a.findConfig(e),o=()=>{t.push(f.exportNamedDeclaration(f.variableDeclaration("const",[f.variableDeclarator(f.identifier("config"),f.objectExpression([f.objectProperty(f.identifier("matcher"),f.stringLiteral(this.configuration.matcherPattern))]))])));};if(n)return i!==null?Promise.resolve({modified:false,result:e}):(o(),Promise.resolve({modified:true,result:e}));let r=Je(e,{moduleName:this.configuration.import.module,importName:this.configuration.import.proxyFactoryName}),s=Je(e,{moduleName:this.configuration.import.module,importName:this.configuration.import.proxyName}),p=[];if(r!==null&&p.push(r),s!==null&&p.push(s),p.length>0&&a.isCalled(e,p))return Promise.resolve({modified:false,result:e});let c=a.refactorProxy(e,this.configuration.exportName,r??this.configuration.import.proxyFactoryName,i!==null&&i.matcher?i.name:void 0);if(c===null){if(i===null)return Up(e,{type:"value",moduleName:this.configuration.import.module,importName:this.configuration.import.proxyName}),o(),Promise.resolve({modified:true,result:e});c=f.exportDefaultDeclaration(f.callExpression(f.identifier(r??this.configuration.import.proxyFactoryName),[f.objectExpression([f.objectProperty(f.identifier("matcher"),f.memberExpression(f.identifier(i.name),f.identifier("matcher")))])])),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 a.findReferencesFrom(i.root,e.program)){let y=t.indexOf(g);y>u&&t.splice(u,0,...t.splice(y,1));}}}return r===null&&pe(e,{type:"value",moduleName:this.configuration.import.module,importName:this.configuration.import.proxyFactoryName}),Promise.resolve({modified:true,result:e})}configureMatcher(e,t){let n=false;for(let i of e.properties)if(f.isObjectProperty(i)&&f.isIdentifier(i.key)&&i.key.name==="matcher"){if(f.isStringLiteral(i.value)){if(i.value.value===t)break;i.value=f.arrayExpression([i.value,f.stringLiteral(t)]),n=true;break}if(f.isArrayExpression(i.value)){let{elements:o}=i.value;o.some(r=>f.isStringLiteral(r)&&r.value===t)||(o.push(f.stringLiteral(t)),n=true);break}f.isIdentifier(i.value)&&(i.value=f.arrayExpression([f.spreadElement(f.conditionalExpression(f.callExpression(f.memberExpression(f.identifier("Array"),f.identifier("isArray")),[i.value]),i.value,f.arrayExpression([i.value]))),f.stringLiteral(t)]),n=true);}return n}static refactorProxy(e,t,n,i){let o=null;return traverse(e,{ExportNamedDeclaration:r=>{let{node:s}=r,{declaration:p,specifiers:c=[]}=s;if(f.isFunctionDeclaration(p))return f.isFunctionDeclaration(s.declaration)&&f.isIdentifier(s.declaration.id)&&s.declaration.id.name===t?(r.replaceWith(f.exportNamedDeclaration(f.variableDeclaration("const",[f.variableDeclarator(f.identifier(t),a.wrapProxy(f.isFunctionDeclaration(s.declaration)?a.createFunctionExpression(s.declaration):s.declaration,n,i))]),[])),o=a.getRootNode(r),r.stop()):r.skip();if(f.isVariableDeclaration(p)){for(let l of p.declarations)if(f.isVariableDeclarator(l)&&f.isIdentifier(l.id)&&l.id.name===t){let u=l.init??null;if(u!==null)return l.init=a.wrapProxy(u,n,i),o=a.getRootNode(r),r.stop()}}for(let l of c)if(f.isExportSpecifier(l)&&f.isIdentifier(l.exported)&&f.isIdentifier(l.local)&&[t,"default"].includes(l.exported.name))return o=a.replaceProxyDeclaration(e,l.local.name,n,i),r.stop();return r.skip()},ExportDefaultDeclaration:r=>{let{node:s}=r,{declaration:p}=s;return f.isArrowFunctionExpression(p)?(r.replaceWith(f.exportDefaultDeclaration(a.wrapProxy(p,n,i))),o=a.getRootNode(r),r.stop()):f.isFunctionDeclaration(p)?(r.replaceWith(f.exportDefaultDeclaration(a.wrapProxy(a.createFunctionExpression(p,true),n,i))),o=a.getRootNode(r),r.stop()):f.isIdentifier(p)?(o=a.replaceProxyDeclaration(e,p.name,n,i),r.stop()):r.skip()}}),o}static replaceProxyDeclaration(e,t,n,i){let o=null;return traverse(e,{VariableDeclarator:r=>{let{node:s}=r;if(f.isIdentifier(s.id)&&s.id.name===t){let p=s.init??null;return p!==null&&(s.init=a.wrapProxy(p,n,i),o=a.getRootNode(r)),r.stop()}return r.skip()},FunctionDeclaration:r=>{let{node:s}=r;return f.isIdentifier(s.id)&&s.id.name===t?(r.replaceWith(a.wrapFunctionDeclaration(s,n,i,f.isIdentifier(s.id)?s.id.name:void 0)),o=a.getRootNode(r),r.stop()):r.skip()}}),o}static isCalled(e,t){let n=false;return traverse(e,{CallExpression:i=>{let{node:o}=i;return f.isIdentifier(o.callee)&&t.includes(o.callee.name)?(n=true,i.stop()):i.skip()}}),n}static findConfig(e){let t=null;return traverse(e,{ExportNamedDeclaration:n=>{let{declaration:i,specifiers:o=[]}=n.node;if(f.isVariableDeclaration(i)){for(let r of i.declarations)if(f.isVariableDeclarator(r)&&f.isIdentifier(r.id)&&r.id.name==="config"){let s=f.isIdentifier(r.init)?a.findVariableDeclarator(e,r.init.name):{name:"config",root:a.getRootNode(n),declaration:r};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:a.hasMatcherProperty(s.declaration.init)},n.stop()}}for(let r of o)if(f.isExportSpecifier(r)&&f.isIdentifier(r.exported)&&f.isIdentifier(r.local)&&r.exported.name==="config"){let s=a.findVariableDeclarator(e,r.local.name);return s!==null&&f.isObjectExpression(s.declaration.init)&&(t={name:s.name,root:s.root,object:s.declaration.init,matcher:a.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:i=>{if(!f.isProgram(i.parentPath.parent))return i.skip();let{node:o}=i;return f.isVariableDeclarator(o)&&f.isIdentifier(o.id)&&o.id.name===t?(f.isIdentifier(o.init)?n=a.findVariableDeclarator(e,o.init.name):n={name:t,root:a.getRootNode(i),declaration:o},i.stop()):i.skip()}}),n}static wrapProxy(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,i="proxy"){return f.variableDeclaration("const",[f.variableDeclarator(f.identifier(i),a.wrapProxy(a.createFunctionExpression(e),t,n))])}static findReferencesFrom(e,t){let n=new Set;traverse(t,{enter:o=>{let{node:r}=o;if(r===e)return o.traverse({Identifier:function(p){let c=p.node;return a.isVariableReference(p.parent,c)&&n.add(c.name),p.skip()}}),o.stop()}});let i=[];return traverse(t,{VariableDeclarator:o=>{if(!f.isProgram(o.parentPath.parent))return o.skip();let{node:r}=o;return f.isIdentifier(r.id)&&n.has(r.id.name)&&i.push(a.getRootNode(o)),o.skip()},FunctionDeclaration:o=>{if(!f.isProgram(o.parent))return;let{node:r}=o;return f.isIdentifier(r.id)&&n.has(r.id.name)&&i.push(a.getRootNode(o)),o.skip()},ClassDeclaration:o=>{if(!f.isProgram(o.parent))return;let{node:r}=o;return f.isIdentifier(r.id)&&n.has(r.id.name)&&i.push(a.getRootNode(o)),o.skip()}}),[...new Set(i.flatMap(o=>[o,...a.findReferencesFrom(o,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 we=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 Pe=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(o){throw new qe("Failed to read file.",{cause:o,details:[`File: file://${e.replace(/\\/g,"/")}`]})}let i=await this.codemod.apply(n,t);if(i.modified)try{await this.fileSystem.writeTextFile(e,i.result,{overwrite:!0});}catch(o){throw new qe("Failed to write file",{cause:o,details:[`File: file://${e.replace(/\\/g,"/")}`]})}return {modified:i.modified,result:e}}};var Qn=class{constructor(e){this.configuration=e;}apply(e,t={}){let n=t.typescript??false,{body:i}=e.program,o=pe(e,{type:"value",moduleName:this.configuration.provider.module,importName:this.configuration.provider.component}),r=n?pe(e,{type:"type",moduleName:"react",importName:"PropsWithChildren"}):null,s=n?pe(e,{type:"type",moduleName:"react",importName:"ReactNode"}):null,p=f.objectPattern([f.objectProperty(f.identifier("children"),f.identifier("children"))]);r!==null&&(p.typeAnnotation=f.tsTypeAnnotation(f.tsTypeReference(f.identifier(r.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(`
|
|
1731
1731
|
`),f.jsxElement(f.jsxOpeningElement(f.jsxIdentifier("body"),[]),f.jsxClosingElement(f.jsxIdentifier("body")),[f.jsxText(`
|
|
1732
|
-
`),f.jsxElement(f.jsxOpeningElement(f.jsxIdentifier(
|
|
1732
|
+
`),f.jsxElement(f.jsxOpeningElement(f.jsxIdentifier(o.localName),[]),f.jsxClosingElement(f.jsxIdentifier(o.localName)),[f.jsxText(`
|
|
1733
1733
|
`),f.jsxExpressionContainer(f.identifier("children")),f.jsxText(`
|
|
1734
1734
|
`)]),f.jsxText(`
|
|
1735
1735
|
`)]),f.jsxText(`
|
|
1736
|
-
`)])))]));return s!==null&&(c.returnType=f.tsTypeAnnotation(f.tsTypeReference(f.identifier(s.localName)))),
|
|
1736
|
+
`)])))]));return s!==null&&(c.returnType=f.tsTypeAnnotation(f.tsTypeReference(f.identifier(s.localName)))),i.push(f.exportDefaultDeclaration(c)),Promise.resolve({modified:true,result:e})}};var Gt=class{constructor(e){this.configuration=e;}apply(e,t={}){let n=t.typescript??false,{body:i}=e.program,o=pe(e,{type:"value",moduleName:this.configuration.provider.module,importName:this.configuration.provider.component}),r=n?pe(e,{type:"type",moduleName:"next/app",importName:"AppProps"}):null,s=n?pe(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"))]);r!==null&&(p.typeAnnotation=f.tsTypeAnnotation(f.tsTypeReference(f.identifier(r.localName))));let c=f.functionDeclaration(f.identifier("App"),[p],f.blockStatement([f.returnStatement(f.parenthesizedExpression(f.jsxElement(f.jsxOpeningElement(f.jsxIdentifier(o.localName),Bn(this.configuration.provider.props??{})),f.jsxClosingElement(f.jsxIdentifier(o.localName)),[f.jsxText(`
|
|
1737
1737
|
`),f.jsxElement(f.jsxOpeningElement(f.jsxIdentifier("Component"),[f.jsxSpreadAttribute(f.identifier("pageProps"))]),f.jsxClosingElement(f.jsxIdentifier("Component")),[]),f.jsxText(`
|
|
1738
|
-
`)])))]));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 Xn=class a extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,a.prototype);}};var Yn=class a{constructor(e){this.configuration=e;}async format(e){let t=await this.getCommand(e);if(t!==null)try{await this.run(t);}catch{}}run(e){let{commandExecutor:t,workingDirectory:n,timeout:r}=this.configuration;if(t.runSync(e,{workingDirectory:n.get(),timeout:r}).exitCode!==0)throw new Xn("Failed to format code.");return Promise.resolve()}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 o=await n.getDependency(i.package);if(o===null)continue;let s=a.getBinPath(o,i.bin);if(s!==null)return {name:r.joinPaths(o.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 vt=class a{constructor(e){this.config=e;}async execute(e){let{sdk:t,configurationManager:n,io:r}=this.config,{output:i}=r,o=await n.load(),s=await this.getSlots(o,e);if(s.length===0){i.inform("No slots to add");return}let p={input:r.input,output:r.output,configuration:{...o,slots:{...o.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])=>o.slots[u.slug]===void 0||!T.parse(o.slots[u.slug]).contains(T.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,o=t.slots===void 0?void 0:a.getVersionMap(t.slots,e.slots),s=Object.keys(e.slots),p=await n.handle({organizationSlug:e.organization,workspaceSlug:e.workspace,preselected:o===void 0?void 0:Object.keys(o),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=o?.[c.slug];if(l===void 0||l.getMaxVersion()===c.version.major)return [c,l??T.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(!T.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 o=T.parse(i);if(o.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&&(o=T.parse(t[r]).with(o),o.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,o]}))}};var je=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 o=e.preselected??[];if(o.length>0)return i.filter(({slug:p})=>o.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 xt=class a{constructor(e){this.config=e;}async execute(e){let{sdk:t,configurationManager:n,io:r}=this.config,{output:i}=r,o=await n.load(),s=await this.getComponents(o,e);if(s.length===0){i.inform("No components to add");return}let p={input:r.input,output:r.output,configuration:{...o,components:{...o.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:a.getVersionMap(t.components,e.components),o=Object.keys(e.components),s=await n.handle({organizationSlug:e.organization,workspaceSlug:e.workspace,preselected:i===void 0?void 0:Object.keys(i),selected:o});if(o.length===s.length&&s.every(p=>o.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??T.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(!T.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 o=T.parse(i);if(o.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&&(o=T.parse(t[r]).with(o),o.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,o]}))}};var Be=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:o})=>n.includes(o)));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 o=e.preselected??[];if(o.length>0)return t.filter(({slug:p})=>o.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 o of i)if(!t.some(({slug:s})=>s===o)){let s=e.find(({slug:p})=>p===o);s!==void 0&&n.set(s.slug,s);}}return [...n.values()]}};var Jt=class a{constructor(e){this.config=e;}async execute(e){let{sdk:t,configurationManager:n,slotForm:r,io:i}=this.config,{output:o}=i,s=await n.load(),p=e.slots===void 0?void 0:a.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 o.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),o.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 o=T.parse(t[r]);if(!T.isValid(i))return [r,o];let s=T.parse(i);return o.intersects(s)?s.contains(o)?[r,null]:[r,o.without(s)]:[r,o]}))}};var Bt=class a{constructor(e){this.config=e;}async execute(e){let{sdk:t,configurationManager:n,componentForm:r,io:i}=this.config,{output:o}=i,s=await n.load(),p=e.components===void 0?void 0:a.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 o.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()]]))}};o.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 o=T.parse(t[r]);if(!T.isValid(i))return [r,o];let s=T.parse(i);return o.intersects(s)?s.contains(o)?[r,null]:[r,o.without(s)]:[r,o]}))}};var er=class{constructor({manager:e,initializer:t}){this.manager=e,this.initializer=t;}isInitialized(e){return this.manager.isInitialized(e)}async load(){return await this.isInitialized("full")||await this.initializer.initialize(),this.manager.load()}loadPartial(){return this.manager.loadPartial()}update(e){return this.manager.update(e)}};var Zt=class a{constructor(e){this.configuration=e;}async execute(e){let{sdk:t,io:n}=this.configuration,r={input:n.input,output:n.output,configuration:await this.getConfiguration(e.partialConfiguration??false)};await t.update(r,{clean:e.clean});}async getConfiguration(e){let{configurationManager:t}=this.configuration;if(!e||await t.isInitialized("full"))return t.load();let{applications:n,...r}=await t.loadPartial();return {paths:{},slots:{},components:{},get organization(){return a.reportConfigurationError("organization")},get workspace(){return a.reportConfigurationError("workspace")},applications:{get development(){return a.reportConfigurationError("applications.development")},get production(){return a.reportConfigurationError("applications.production")},...n},get defaultLocale(){return a.reportConfigurationError("defaultLocale")},get locales(){return a.reportConfigurationError("locales")},...r}}static reportConfigurationError(e){throw new ve(`The \`${e}\` property is not defined in the project configuration.`,{reason:"invalid_configuration",suggestions:["Run `init` command to initialize the project configuration."]})}};var tr=class a{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 a.resolvePath(await this.getPage(e.page,e),e)}getPage(e,t){if(e!==void 0){let r=a.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(a.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(a.getSitemap(t))){let o=stringSimilarity(e,i);o>r&&(n=a.SITEMAP[i],r=o);}return n}static getSitemap(e){return e.prodApplicationSlug!==void 0?a.SITEMAP:Object.fromEntries(Object.entries(a.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 rr=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 ir=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 Qt=class a{constructor(e){this.config=e;}async execute(e){let{sdk:t,configurationManager:n,io:r}=this.config,i=await n.load(),o=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(o.map(c=>[c.slug,a.resolveVersion(c.version.major,i.slots[c.slug])]))},components:{...i.components,...Object.fromEntries(s.map(c=>[c.slug,a.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 o=r.filter(s=>!i.some(p=>p.slug===s));throw new d(`Components not found: \`${o.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 o=r.filter(s=>!i.some(p=>p.slug===s));throw new d(`Slots not found: \`${o.join("`, `")}\`.`,{reason:"precondition",suggestions:["Run `remove slot` to remove a slot from your configuration."]})}return i}static resolveVersion(e,t){let n=T.of(e);if(t===void 0)return n.toString();let r=T.parse(t);return r.isExact()?n.toString():r.isRange()?r.getMaxVersion()>=n.getMaxVersion()?t:T.between(r.getMinVersion(),n.getMaxVersion()).toString():T.either(...r.getVersions(),...n.getVersions()).toString()}};var Xt=class a extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,a.prototype);}};var or=class a{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(a.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(a.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 o=await this.execute(()=>readdir(e));for(let s of o){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 o=relative(t,e);if(n.isFile()){let s=()=>this.execute(()=>createReadStream(e));yield {type:"file",name:o,get content(){return s()}};}else n.isDirectory()?(yield {type:"directory",name:o},yield*this.listRelatively(e,t,r+1,i)):n.isSymbolicLink()?yield {type:"symlink",name:o,target:await this.execute(()=>realpath(e))}:yield {type:"link",name:o,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(a.isErrorCode(t,["ENOENT","ENOTDIR"]))return false;throw t}}delete(e,t){return rm$1(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$1(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=>a.reportError(n)):t}catch(t){a.reportError(t);}}static reportError(e){if(e instanceof Error){let t=Object.entries(a.ERRORS);for(let[n,r]of t)if(a.isErrorCode(e,[n]))throw new Xt(r,{reason:a.ERROR_REASONS[n]??"other",cause:e,details:[`Code: ${n}`]})}throw new Xt("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 ar=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=Y`
|
|
1738
|
+
`)])))]));return s!==null&&(c.returnType=f.tsTypeAnnotation(f.tsTypeReference(f.identifier(s.localName)))),i.push(f.exportDefaultDeclaration(c)),Promise.resolve({modified:true,result:e})}};var Xn=class a extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,a.prototype);}};var Yn=class a{constructor(e){this.configuration=e;}async format(e){let t=await this.getCommand(e);if(t!==null)try{await this.run(t);}catch{}}run(e){let{commandExecutor:t,workingDirectory:n,timeout:i}=this.configuration;if(t.runSync(e,{workingDirectory:n.get(),timeout:i}).exitCode!==0)throw new Xn("Failed to format code.");return Promise.resolve()}async getCommand(e){let{tools:t,packageManager:n,fileSystem:i}=this.configuration;for(let o of t){if(!await n.hasDirectDependency(o.package))continue;let r=await n.getDependency(o.package);if(r===null)continue;let s=a.getBinPath(r,o.bin);if(s!==null)return {name:i.joinPaths(r.directory,i.normalizeSeparators(s)),arguments:o.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 vt=class a{constructor(e){this.config=e;}async execute(e){let{sdk:t,configurationManager:n,io:i}=this.config,{output:o}=i,r=await n.load(),s=await this.getSlots(r,e);if(s.length===0){o.inform("No slots to add");return}let p={input:i.input,output:i.output,configuration:{...r,slots:{...r.slots,...Object.fromEntries(s.map(([u,g])=>[u.slug,g.toString()]))}}};await n.update(p.configuration),o.confirm("Configuration updated"),await t.update(p,{clean:true});let c=s.filter(([u])=>r.slots[u.slug]===void 0||!D.parse(r.slots[u.slug]).contains(D.of(u.version.major)));if(c.length>0&&(e.example??await i.input?.confirm({message:"Generate an example implementation?",default:true})??false)){let u=o.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:i,io:{output:o}}=this.config,r=t.slots===void 0?void 0:a.getVersionMap(t.slots,e.slots),s=Object.keys(e.slots),p=await n.handle({organizationSlug:e.organization,workspaceSlug:e.workspace,preselected:r===void 0?void 0:Object.keys(r),selected:t.example===true?[]:s});if(s.length===p.length&&p.every(c=>s.includes(c.slug))&&o.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=r?.[c.slug];if(l===void 0||l.getMaxVersion()===c.version.major)return [c,l??D.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 i.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[i,o]=n.split("@",2);if(o===void 0)return [i,void 0];if(!D.isValid(o))throw new d(`Invalid version specifier \`${o}\` for slot \`${i}\`.`,{reason:"invalid_input",suggestions:["Version must be exact (i.e. `1`), range (i.e. `1 - 2`), or set (i.e. `1 || 2`)."]});let r=D.parse(o);if(r.getCardinality()>5)throw new d(`The number of versions specified for slot \`${i}\` exceeds 5 major versions.`,{reason:"invalid_input",suggestions:["Narrow down the number of versions to 5 or less."]});if(t[i]!==void 0&&(r=D.parse(t[i]).with(r),r.getCardinality()>5))throw new d(`The cumulative number of versions for slot \`${i}\` cannot exceed 5 major versions.`,{reason:"invalid_input",suggestions:["Narrow down the number of versions to 5 or less."]});return [i,r]}))}};var Le=class{constructor(e){this.config=e;}async handle(e){let{output:t,input:n}=this.config,i=t.notify("Loading slots"),o=await this.getSlots(e,e.allowed);i.stop();let r=e.preselected??[];if(r.length>0)return o.filter(({slug:p})=>r.includes(p));let s=e.selected??[];return o.length===0||s.length>0&&o.every(({slug:p})=>s.includes(p))?o.filter(({slug:p})=>s.includes(p)):e.selectionConfirmation!==void 0&&!await n.confirm(e.selectionConfirmation)?o.filter(({slug:c})=>s.includes(c)):n.selectMultiple({message:"Select slots",options:o.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,i=await n.getSlots({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return t===void 0?i:i.filter(({slug:o})=>t.includes(o))}};var xt=class a{constructor(e){this.config=e;}async execute(e){let{sdk:t,configurationManager:n,io:i}=this.config,{output:o}=i,r=await n.load(),s=await this.getComponents(r,e);if(s.length===0){o.inform("No components to add");return}let p={input:i.input,output:i.output,configuration:{...r,components:{...r.components,...Object.fromEntries(s.map(([c,l])=>[c.slug,l.toString()]))}}};await n.update(p.configuration),o.confirm("Configuration updated"),await t.update(p,{clean:true});}async getComponents(e,t){let{componentForm:n,io:{output:i}}=this.config,o=t.components===void 0?void 0:a.getVersionMap(t.components,e.components),r=Object.keys(e.components),s=await n.handle({organizationSlug:e.organization,workspaceSlug:e.workspace,preselected:o===void 0?void 0:Object.keys(o),selected:r});if(r.length===s.length&&s.every(p=>r.includes(p.slug))&&i.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=o?.[p.slug];if(c===void 0||c.getMaxVersion()===p.version.major)return [p,c??D.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[i,o]=n.split("@",2);if(o===void 0)return [i,void 0];if(!D.isValid(o))throw new d(`Invalid version specifier \`${o}\` for component \`${i}\`.`,{reason:"invalid_input",suggestions:["Version must be exact (i.e. `1`), range (i.e. `1 - 2`), or set (i.e. `1 || 2`)."]});let r=D.parse(o);if(r.getCardinality()>5)throw new d(`The number of versions specified for component \`${i}\` exceeds 5 major versions.`,{reason:"invalid_input",suggestions:["Narrow down the number of versions to 5 or less."]});if(t[i]!==void 0&&(r=D.parse(t[i]).with(r),r.getCardinality()>5))throw new d(`The cumulative number of versions for component \`${i}\` cannot exceed 5 major versions.`,{reason:"invalid_input",suggestions:["Narrow down the number of versions to 5 or less."]});return [i,r]}))}};var Be=class{constructor(e){this.config=e;}async handle(e){let{workspaceApi:t}=this.config,{allowed:n}=e,i=await t.getComponents({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),o=await this.selectComponents(e,n===void 0?i:i.filter(({slug:r})=>n.includes(r)));return e.includeDependencies===true&&o.push(...this.getReferencedComponents(i,o)),o}async selectComponents(e,t){let{output:n,input:i}=this.config;n.notify("Loading components").stop();let r=e.preselected??[];if(r.length>0)return t.filter(({slug:p})=>r.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 i.confirm(e.selectionConfirmation)?t.filter(({slug:c})=>s.includes(c)):i.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 i of t){let o=new Set([...i.metadata.directReferences,...i.metadata.indirectReferences]);for(let r of o)if(!t.some(({slug:s})=>s===r)){let s=e.find(({slug:p})=>p===r);s!==void 0&&n.set(s.slug,s);}}return [...n.values()]}};var Jt=class a{constructor(e){this.config=e;}async execute(e){let{sdk:t,configurationManager:n,slotForm:i,io:o}=this.config,{output:r}=o,s=await n.load(),p=e.slots===void 0?void 0:a.getVersionMap(e.slots,s.slots),c=await i.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 r.inform("No slots to remove.");let l={input:o.input,output:o.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),r.confirm("Configuration updated"),await t.update(l,{clean:true});}static getVersionMap(e,t){return Object.fromEntries(e.map(n=>{let[i,o]=n.split("@",2);if(t[i]===void 0||o===void 0)return [i,null];let r=D.parse(t[i]);if(!D.isValid(o))return [i,r];let s=D.parse(o);return r.intersects(s)?s.contains(r)?[i,null]:[i,r.without(s)]:[i,r]}))}};var Bt=class a{constructor(e){this.config=e;}async execute(e){let{sdk:t,configurationManager:n,componentForm:i,io:o}=this.config,{output:r}=o,s=await n.load(),p=e.components===void 0?void 0:a.getVersionMap(e.components,s.components),c=await i.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 r.alert("No components to remove.");let l={input:o.input,output:o.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()]]))}};r.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[i,o]=n.split("@",2);if(t[i]===void 0||o===void 0)return [i,null];let r=D.parse(t[i]);if(!D.isValid(o))return [i,r];let s=D.parse(o);return r.intersects(s)?s.contains(r)?[i,null]:[i,r.without(s)]:[i,r]}))}};var ei=class{constructor({manager:e,initializer:t}){this.manager=e,this.initializer=t;}isInitialized(e){return this.manager.isInitialized(e)}async load(){return await this.isInitialized("full")||await this.initializer.initialize(),this.manager.load()}loadPartial(){return this.manager.loadPartial()}update(e){return this.manager.update(e)}};var Zt=class a{constructor(e){this.configuration=e;}async execute(e){let{sdk:t,io:n}=this.configuration,i={input:n.input,output:n.output,configuration:await this.getConfiguration(e.partialConfiguration??false)};await t.update(i,{clean:e.clean});}async getConfiguration(e){let{configurationManager:t}=this.configuration;if(!e||await t.isInitialized("full"))return t.load();let{applications:n,...i}=await t.loadPartial();return {paths:{},slots:{},components:{},get organization(){return a.reportConfigurationError("organization")},get workspace(){return a.reportConfigurationError("workspace")},applications:{get development(){return a.reportConfigurationError("applications.development")},get production(){return a.reportConfigurationError("applications.production")},...n},get defaultLocale(){return a.reportConfigurationError("defaultLocale")},get locales(){return a.reportConfigurationError("locales")},...i}}static reportConfigurationError(e){throw new ve(`The \`${e}\` property is not defined in the project configuration.`,{reason:"invalid_configuration",suggestions:["Run `init` command to initialize the project configuration."]})}};var ti=class a{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 a.resolvePath(await this.getPage(e.page,e),e)}getPage(e,t){if(e!==void 0){let i=a.findMatch(e,t);if(i!==null)return Promise.resolve(i)}let{input:n}=this.config;return n.select({message:"Where do you want to go?",options:Object.entries(a.SITEMAP).map(([i,o])=>({value:o,label:i}))})}static findMatch(e,t){if(e.startsWith("/"))return e;let n=null,i=.5;for(let o of Object.keys(a.getSitemap(t))){let r=stringSimilarity(e,o);r>i&&(n=a.SITEMAP[o],i=r);}return n}static getSitemap(e){return e.prodApplicationSlug!==void 0?a.SITEMAP:Object.fromEntries(Object.entries(a.SITEMAP).filter(([,t])=>!t.includes(":prod-application")))}static resolvePath(e,t){return e.replace(/:(organization|workspace|(dev|prod)-application)/g,(n,i)=>{switch(i){case "organization":return t.organizationSlug;case "workspace":return t.workspaceSlug;case "dev-application":return t.devApplicationSlug;case "prod-application":return t.prodApplicationSlug??""}})}};var ni=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 ii=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 oi=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 Qt=class a{constructor(e){this.config=e;}async execute(e){let{sdk:t,configurationManager:n,io:i}=this.config,o=await n.load(),r=await this.selectSlots(o,e.slots),s=await this.selectComponents(o,e.components),p={input:i.input,output:i.output,configuration:{...o,slots:{...o.slots,...Object.fromEntries(r.map(c=>[c.slug,a.resolveVersion(c.version.major,o.slots[c.slug])]))},components:{...o.components,...Object.fromEntries(s.map(c=>[c.slug,a.resolveVersion(c.version.major,o.components[c.slug])]))}}};await n.update(p.configuration),await t.update(p,{clean:true});}async selectComponents(e,t){let{form:{componentForm:n}}=this.config,i=t===void 0?Object.keys(e.components):t,o=i.length===0?[]:await n.handle({organizationSlug:e.organization,workspaceSlug:e.workspace,preselected:i});if(i.length>0&&o.length!==i.length){let r=i.filter(s=>!o.some(p=>p.slug===s));throw new d(`Components not found: \`${r.join("`, `")}\`.`,{reason:"precondition",suggestions:["Run `remove component` to remove a component from your configuration."]})}return o}async selectSlots(e,t){let{form:{slotForm:n}}=this.config,i=t===void 0?Object.keys(e.slots):t,o=i.length===0?[]:await n.handle({organizationSlug:e.organization,workspaceSlug:e.workspace,preselected:i});if(i.length>0&&o.length!==i.length){let r=i.filter(s=>!o.some(p=>p.slug===s));throw new d(`Slots not found: \`${r.join("`, `")}\`.`,{reason:"precondition",suggestions:["Run `remove slot` to remove a slot from your configuration."]})}return o}static resolveVersion(e,t){let n=D.of(e);if(t===void 0)return n.toString();let i=D.parse(t);return i.isExact()?n.toString():i.isRange()?i.getMaxVersion()>=n.getMaxVersion()?t:D.between(i.getMinVersion(),n.getMaxVersion()).toString():D.either(...i.getVersions(),...n.getVersions()).toString()}};var Xt=class a extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,a.prototype);}};var ri=class a{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),i=this.resolvePath(t),o=relative(n,i);return !o.startsWith("..")&&!isAbsolute(o)}isSymbolicLink(e){return this.execute(async()=>{try{return (await lstat(this.resolvePath(e))).isSymbolicLink()}catch(t){if(a.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(a.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,i){if(!await i(e,n))return;let o=await this.execute(()=>lstat(e)).catch(()=>null);if(o===null)return;if(!o.isDirectory())return yield*this.createEntry(e,dirname(t),o,n,i);let r=await this.execute(()=>readdir(e));for(let s of r){let p=join(e,s),c=await this.execute(()=>lstat(p));await i(p,n)&&(yield*this.createEntry(p,t,c,n,i));}}async*createEntry(e,t,n,i,o){let r=relative(t,e);if(n.isFile()){let s=()=>this.execute(()=>createReadStream(e));yield {type:"file",name:r,get content(){return s()}};}else n.isDirectory()?(yield {type:"directory",name:r},yield*this.listRelatively(e,t,i+1,o)):n.isSymbolicLink()?yield {type:"symlink",name:r,target:await this.execute(()=>realpath(e))}:yield {type:"link",name:r,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(a.isErrorCode(t,["ENOENT","ENOTDIR"]))return false;throw t}}delete(e,t){return rm$1(this.resolvePath(e),{recursive:t?.recursive??false,force:true})}move(e,t,n){return this.execute(async()=>{let i=this.resolvePath(e),o=this.resolvePath(t);n?.overwrite===true&&await rm$1(o,{force:true,recursive:true}),await mkdir(dirname(o),{recursive:true}),await rename(i,o);})}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=>a.reportError(n)):t}catch(t){a.reportError(t);}}static reportError(e){if(e instanceof Error){let t=Object.entries(a.ERRORS);for(let[n,i]of t)if(a.isErrorCode(e,[n]))throw new Xt(i,{reason:a.ERROR_REASONS[n]??"other",cause:e,details:[`Code: ${n}`]})}throw new Xt("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 ai=class{constructor(e){this.configuration=e;}wait(e){let{listener:t}=this.configuration;return new Promise((n,i)=>{this.focus(()=>t.wait(e).then(n,i));})}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=Y`
|
|
1739
1739
|
Add-Type @"
|
|
1740
1740
|
using System;
|
|
1741
1741
|
using System.Runtime.InteropServices;
|
|
@@ -1751,37 +1751,37 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1751
1751
|
`,n=Y`
|
|
1752
1752
|
${t}
|
|
1753
1753
|
[Window]::GetForegroundWindow()
|
|
1754
|
-
`,
|
|
1754
|
+
`,i=this.runCommand({name:"powershell",arguments:["-Command",`& {${n}}`]});if(await e(),i!==null){let o=Y`
|
|
1755
1755
|
${t}
|
|
1756
|
-
[Window]::SetForegroundWindow(${
|
|
1757
|
-
[Window]::ShowWindow(${
|
|
1758
|
-
`;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 sr=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 pr=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 cr=class a{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=a.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(o=>typeof o=="string"?o===t:o.test(t)))return Promise.resolve(n);return Promise.resolve(null)}};var lr=class a{static{this.DEFAULT_DOMAINS={google:["google.com"],microsoft:["outlook.com"]};}constructor(e=a.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 o of i)for(let s of n)if(s.endsWith(`.${o}.`))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 ur=class a{generate(e){return new URL(`https://mail.google.com/mail${a.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=TimeZone.of(Intl.DateTimeFormat().resolvedOptions().timeZone),i=Instant.ofEpochSecond(e.timestamp),o=LocalDateTime.ofInstant(i,r).getLocalDate();t.push(`after:${o}`);}return t.push("in:anywhere"),n+=`/#search/${t.map(r=>encodeURIComponent(r)).join("+")}`,n}};var mr=class{generate(e){return new URL("https://www.icloud.com/mail")}};var dr=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 a{generate(e){return new URL(`https://mail.proton.me/u/0/all-mail${a.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 fr=class a{generate(e){return new URL(`https://mail.yahoo.com/d/search${a.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 en=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 o=!1;await t.exists(i)&&(o=await n.input?.confirm({message:`Overwrite existing file at \`${i}\`?`,default:!1})??!1),await t.writeTextFile(i,JSON.stringify(r,null,2),{overwrite:o});}catch(o){throw new d("Failed to write template file",{reason:"other",cause:o})}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(o=>[o.slug,{name:o.name,criteria:o.criteria}])),components:Object.fromEntries(r.components.map(o=>[o.slug,{name:o.name,description:o.description,schema:o.definition}])),slots:Object.fromEntries(r.slots.map(o=>[o.slug,{name:o.name,component:o.component?.slug??"",content:o.content}])),experiences:r.experiences.map(o=>{let{experiment:s}=o,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:o.name,draft:o.status==="DRAFT",audiences:o.audiences,slots:o.slots,content:o.content,...p!==void 0?{experiment:p}:{}}})};for(let[o,s]of Object.entries(i))typeof s=="object"&&s!==null&&(Array.isArray(s)&&s.length===0||Object.keys(s).length===0)&&delete i[o];return i}};var yr=class{constructor(e){this.config=e;}async handle(e){let{input:t,form:n}=this.config,r={components:[],slots:[],audiences:[],experiences:[]},i=new Set,o=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))o.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:[...o],selectionConfirmation:{message:o.size>0?"Do you want to include other slots?":"Do you want to include slots?",default:false}});let p=new Set(r.slots.map(c=>c.component?.slug??""));return r.components=await n.component.handle({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,includeDependencies:true,selected:[...p],selectionConfirmation:{message:p.size>0?"Do you want to include other components?":"Do you want to include components?",default:false}}),r.audiences=await n.audience.handle({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,selected:[...i],selectionConfirmation:{message:i.size>0?"Do you want to include other audiences?":"Do you want to include audiences?",default:false}}),r}};var hr=class{constructor(e){this.config=e;}async handle(e){let{output:t,input:n,workspaceApi:r}=this.config,i=t.notify("Loading experiences"),o=await r.getExperiences({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});i.stop();let{confirmation:s}=e;if(o.length===0||s!==void 0&&!await n.confirm({message:s}))return [];let p=await n.selectMultiple({message:"Select experiences",options:o.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 Sr=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 o=e.preselected??[];if(o.length>0)return i.filter(({slug:p})=>o.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 a extends d{constructor(e,{tracing:t,...n}={}){super(e,n),this.tracing=t??[],Object.setPrototypeOf(this,a.prototype);}static fromCause(e,t={}){let{message:n,...r}=t;if(!(e instanceof Error))return new a(n??d.formatMessage(e),{...r,cause:e});let i=new a(n??e.message,{cause:e,...e instanceof d?e.help:{},...r,tracing:[...r.tracing??[],...e instanceof a?e.tracing:[]]});return i.stack=e.stack,i}};var wt=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,o=await this.resolveUrl(r);return t.execute({template:o.toString(),options:i},new wt({input:n.input,output:n.output,baseUrl:o}))}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 pt(a,e){if(URL.canParse(a))return new URL(a);let t=new URL(e.href.replace(/^(.*:)(?!\/)/,"$1/"));return new URL(a,t)}var Ir=class{constructor(e){this.config=e;}async execute(e,t){let{fileSystem:n}=this.config,{input:r}=t,i=pt(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 o=n.normalizeSeparators(e.destination),{output:s}=t,p=s?.notify("Downloading sources");try{await this.download(i,{...e,destination:o},r);}finally{p?.stop();}e.result?.destination!==void 0&&t.set(e.result.destination,o);}async download(e,t,n){let{provider:r,fileSystem:i,codemod:o}=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,v])=>[i.normalizeSeparators(y),i.normalizeSeparators(v)]));for await(let y of l){let v=this.resolvePath(i.normalizeSeparators(y.name),g);if(i.isAbsolutePath(v))throw new h("Path to downloaded file cannot be absolute.",{reason:"precondition",details:[`Path: ${v}`],suggestions:["Use relative paths"]});if(!(c!==void 0&&!c.match(v))){if(y.name=i.joinPaths(s,v),y.type==="link"||y.type==="symlink"){let A=i.normalizeSeparators(y.target);if(i.isAbsolutePath(A)||!i.isSubPath(s,A))continue;y.target=A;}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 o.apply(await i.getRealPath(y.name));}resolvePath(e,t){if(e in t)return t[e];let{fileSystem:n}=this.config,r="",i=e,o=n.getSeparator();for(let[s,p]of Object.entries(t)){let c=s.endsWith(o)?s:s+o;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 vr=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 ae({status:"Installing dependencies",notifier:r})});}catch(i){throw h.fromCause(i)}finally{r?.stop();}}};var Pt=class a{constructor(e){this.matcher=e;}static fromPattern(e){return new a(new Minimatch(e.replace(/^\.\//,"").replace(/\\/g,"/")))}test(e){return Promise.resolve(this.matcher.match(e))}};var xr=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=(o,s)=>t.depth!==void 0&&s>t.depth?false:this.scanFilter!==void 0?this.scanFilter(o,s):true,r=[],i=Pt.fromPattern(e);for await(let o of this.fileSystem.list(this.projectDirectory.get(),n))if(await i.test(o.name)){if(t.matcher===void 0)r.push(o.name);else if(o.type==="file"){let s=await new Response(o.content).text();this.matches(s,t.matcher)&&r.push(o.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 wr=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(o){throw h.fromCause(o)}}}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:o}of t){let s=i===true?"gi":"g";n=n.replace(new RegExp(r,s),`${o}`);}return n}};var Pr=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 Cr=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 kr=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 j=class a extends d{constructor(e,t={}){super(e,t),Object.setPrototypeOf(this,a.prototype);}};var Ze=class{constructor(e){this.provider=e;}get action(){return Promise.resolve(this.provider.get()).catch(e=>{throw e instanceof j?new h(e.message,e.help):e})}async execute(e,t){return (await this.action).execute(e,t)}};var Ar=class{constructor(e){this.manager=e;}isInitialized(e){return this.manager.isInitialized(e)}load(){return this.configuration===void 0&&(this.configuration=this.manager.load()),this.configuration}loadPartial(){return this.manager.loadPartial()}update(e){return this.configuration=this.manager.update(e),this.configuration}};var Va;(r=>{function a(i){let o=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:o,slots:s,audiences:p,locales:l,experiences:c}}r.analyze=a;function e(i){let o=t(i.content);for(let s of i.experiment?.variants??[]){let p=t(s.content);p.audiences.forEach(c=>o.audiences.add(c)),p.slots.forEach(c=>o.slots.add(c));}return {...o}}function t(i){let o=new Set,s=new Set,p=0;for(let[u,g]of Object.entries(i.default??{})){o.add(u);for(let[y,v]of Object.entries(g))s.add(y),p=Math.max(p,n(v));}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)){o.add(g);for(let[v,A]of Object.entries(y))s.add(v),p=Math.max(p,n(A));}}return {slots:o,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((o,s)=>o+s,0);case "list":return i.items.map(n).reduce((o,s)=>o+s,0)}}})(Va||={});var Er=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 Rr=class a{constructor(e){this.config=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Analyzing resources"),i=Va.analyze(e.resources),{configurationManager:o,api:{workspace:s}}=this.config,p=await o.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=a.getWarnings(i,c.workspace);if(g.length>0)for(let y of g)n.warn(`${y}`);}e.result!==void 0&&a.setVariables(e.result,l,u,t);}async createPlan(e,t,n){let{mappingForm:r,matcher:i}=this.config,o=await i.match({resources:e,workspaceSlug:n.configuration.workspace,organizationSlug:n.configuration.organization}),s=Object.entries(o.audiences).filter(v=>!("id"in v[1])),p=Object.entries(o.components).filter(v=>!("id"in v[1])),c=Object.entries(o.slots).filter(v=>!("id"in v[1])),l=o.experiences.filter(v=>!("id"in v));await this.checkRequiredQuota(n,{components:p.length,slots:c.length,audiences:s.length,experiences:l.length});let u=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)}}),g={},{workspace:y}=n;for(let v of t.locales)y.locales.includes(v)||(g[v]=y.defaultLocale);return {matches:o,mapping:u,resources:new Er({componentMapping:u.components,audienceMapping:u.audiences,slotMapping:u.slots,dynamicAttributesPerContent:y.quotas.dynamicAttributesPerContent,maximumAudiencePerExperience:y.quotas.audiencesPerExperience,isCrossDeviceFeatureEnabled:y.features.crossDevice,localeMapping:g}).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 o=a.getRemainingQuota(e.workspace,r);if(o<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: ${o}`,`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,o]of Object.entries(r))if(o.size>0)throw new d(`Some ${i} referenced in the template are missing`,{title:"Invalid template",reason:"invalid_input",details:[`Missing ${i}: ${Array.from(o).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),o=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??{}))o.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);}),...[...o].map(async c=>{await p.workspace.getAudience({organizationSlug:n.configuration.organization,workspaceSlug:n.configuration.workspace,audienceSlug:c})!==null&&o.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:o,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,o=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[o].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[o].experimentId;l!==void 0&&r.set(e.experiments[s],l);}(!("id"in p)||p.id===void 0)&&o++;}}};var Ct=class a{constructor(e){this.config=e;}static prompt(e){return new a(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 Or=class{constructor(e){this.config=e;}async handle(e){let{input:t,workspaceApi:n}=this.config,{resources:r,...i}=e,o=r.slots??[],s=r.components??[],p=r.audiences??[],[c,l,u]=await Promise.all([o.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 H=await Ct.prompt({input:t,initial:P,unavailableSlugs:S,label:`Component \`${P}\` already exists, enter a new component ID:`});S.push(H),y[P]=H;}}let v=o.filter(S=>c.some(P=>P.slug===S)),A={};if(v.length>0){let S=c.map(P=>P.slug);for(let P of v){let H=await Ct.prompt({input:t,initial:P,unavailableSlugs:S,label:`Slot \`${P}\` already exists, enter a new slot ID:`});S.push(H),A[P]=H;}}let M=p.filter(S=>u.some(P=>P.slug===S)),L={};if(M.length>0){let S=u.map(P=>P.slug);for(let P of M){let H=await Ct.prompt({input:t,initial:P,unavailableSlugs:S,label:`Audience \`${P}\` already exists, enter a new audience ID:`});S.push(H),L[P]=H;}}return {components:y,slots:A,audiences:L}}};var Tr=class a{constructor(e){this.config=e;}async match(e){let{resources:t,...n}=e,[r,i,o,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:o,experiences:s}}async mapAudiences(e,t){let{workspaceApi:n}=this.config,r=await Promise.all(Object.keys(e).map(async o=>[o,await n.getAudience({...t,audienceSlug:o})])),i={};for(let[o,s]of r)i[o]=s===null||!a.isSimilarAudience(e[o],s)?e[o]:s;return i}async mapComponents(e,t){let{workspaceApi:n}=this.config,r=await Promise.all(Object.keys(e).map(async o=>[o,await n.getComponent({...t,componentSlug:o})])),i={};for(let[o,s]of r)i[o]=s===null||!a.isSimilarComponent(e[o],s)?e[o]:s;return i}async mapSlots(e,t){let{workspaceApi:n}=this.config,r=await Promise.all(Object.keys(e).map(async o=>[o,await n.getSlot({...t,slotSlug:o})])),i={};for(let[o,s]of r)i[o]=s===null||!a.isSimilarSlot(e[o],s)?e[o]:s;return i}async mapExperiences(e,t){let{workspaceApi:n}=this.config,i=(await n.getExperiences({...t,status:["ACTIVE","PAUSED","DRAFT"]})).map(o=>{let s=null;function p(){return s===null&&(s=n.getExperience({...t,experienceId:o.id})),s}return {...o,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 o=>{for(let s of i)if(await this.matchesExperience(o,s)){let{details:p,...c}=s;return c}return o}))}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||!a.isSimilarExperimentContent(e.experiment.variants,i.variants))?false:a.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(a.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)&&a.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 o of Object.values(r))if(Object.values(i).some(s=>deepEqual(o,s)))return true}}return false}};var $=class a extends j{constructor(e,{url:t,...n}){super(e,n),Object.setPrototypeOf(this,a.prototype),this.url=t;}},Me=class a extends ${constructor(e,t){super(e,{...t,reason:t.reason??"not_found"}),Object.setPrototypeOf(this,a.prototype);}};var Dr=class a{constructor(e={}){this.configuration=e;}async get(e){if(!["http:","https:"].includes(e.protocol))throw new $("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 Me("Resource not found.",{url:e});let{maxAttempts:r=0,delay:i=1e3}=this.configuration.retry??{};if(a.isSuccessful(n))return n;if(a.isRetryableCode(n.status)&&t<r)return await new Promise(o=>{setTimeout(o,i);}),this.fetch(e,t+1);throw new $(n.statusText,{url:e})}static isSuccessful(e){return e.ok&&e.body!==null}static isRetryableCode(e){return e>=500||[429,408].includes(e)}};var Mr=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 o=[];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&&o.push(s);}if(o.length>0){let{message:s,...p}=e.help??{};throw new h(s??"Missing required dependencies.",{...p,details:o.map(({dependency:c,issue:l})=>`\`${c}\`: ${l}`)})}}async checkRequirement(e){let{name:t,version:n,optional:r=false}=e;if(n===void 0){let o=await this.packageManager.hasDirectDependency(t);if(o||r)return {dependency:t,satisfied:o}}else {let o=await this.packageManager.hasDirectDependency(t,n);if(o||r)return {dependency:t,satisfied:o}}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 lt=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,o)=>r[Number.parseInt(o,10)]),this.baseUrl)}return e}async loadMappings(e){let t=await this.registryProvider.get(e);return Array.isArray(t)?t:t.value}};var Ne=class a{static{this.DEFAULT_EXPECTED_ERRORS=["not_supported","not_found","other"];}constructor({providers:e,expectedErrors:t}){this.providers=e,this.expectedErrors=t??a.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 Me("Resource not found.",{url:e})}isExpectedError(e){return e instanceof $&&this.expectedErrors.includes(e.reason)}};var Nr=class a{constructor(e,t){this.fileSystem=e,this.filter=t;}get(e){if(!a.supportsUrl(e))throw new $(`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 zr=class a{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 $("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 o=r.pathname.split("/"),s=o.slice(4),p=s.join("/")===t&&e.length===1?o.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://${a.RAW_HOST}`);return c.pathname=`/${t}/${n}/${e.ref??"HEAD"}/${p}`,c},o=await this.loadGitTree(e),s=[];if(r===null)s.push(...o.map(p=>i(p.path)));else {let p=o.find(c=>c.path===r);if(p===void 0)throw new $("File not found.",{reason:"not_found",url:e.canonicalUrl});p.type==="tree"?s.push(...o.filter(c=>c.path.startsWith(r)&&c.type==="blob").map(c=>i(c.path))):s.push(i(r));}if(s.length>a.MAX_DOWNLOAD_FILES)throw new $(`The number of files to download exceeds the limit of ${a.MAX_DOWNLOAD_FILES}.`,{reason:"precondition",url:e.canonicalUrl});return s}parseUrl(e){if(!a.isUrlSupported(e))return null;let t,n,r=null,i,o=((e.protocol===a.PROTOCOL?e.hostname:"")+e.pathname).replace(/^\/+/,"").split("/"),s=null;return e.hostname===a.MAIN_HOST?(s=e,[t=null,n=null,,r=null,...i]=o):[t=null,n=null,...i]=o,t===null||n===null?null:(s===null&&(s=new URL(`https://${a.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://${a.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===a.MAIN_HOST:e.protocol===a.PROTOCOL}};var tn=class a{constructor(e){this.provider=e;}async get(e){if(!a.supportsUrl(e))throw new $("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 G=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,o)=>typeof o=="string"?i===""?o:`${i}.${o}`:`${i}[${o}]`,""),message:r.message}))}}};var Cl=z.object({name:z.string(),version:z.string().optional(),dependencies:z.record(z.string()).optional(),devDependencies:z.record(z.string()).optional(),bin:z.record(z.string()).optional(),scripts:z.record(z.string()).optional(),packageManager:z.string().optional()}),nn=class extends G{constructor(){super(Cl);}};var Qe=z.string().regex(/^[a-z]+(-?[a-z0-9]+)*$/i,"An identifier must start with a letter and contain only letters, numbers, and hyphens."),$r=z.string().regex(/^[a-z]{2,3}([-_][a-z]{2,3})?$/i,"Locale must be in the form of en, en_US, or en-US."),Fr=z.string().refine(T.isValid,"Version must be exact (1), range (1 - 2), or set (1, 2).").refine(a=>{try{return T.parse(a).getCardinality()<=5}catch{return false}},"Version range must not exceed 5 major versions.");function te(a){return a.optional().catch(void 0)}var kl=z.object({$schema:te(z.string()),organization:te(Qe),workspace:te(Qe),applications:te(z.object({development:te(Qe),production:te(Qe)})),locales:te(z.array($r).min(1)),defaultLocale:te($r),slots:te(z.record(Fr)),components:te(z.record(Fr)),paths:te(z.object({source:te(z.string()),utilities:te(z.string()),components:te(z.string()),examples:te(z.string()),content:te(z.string())}))}),Al=z.strictObject({$schema:z.string().optional(),organization:Qe,workspace:Qe,applications:z.strictObject({development:Qe,production:Qe.optional()}),locales:z.array($r).min(1),defaultLocale:$r,slots:z.record(Fr).default({}),components:z.record(Fr).default({}),paths:z.strictObject({source:z.string().optional(),utilities:z.string().optional(),components:z.string().optional(),examples:z.string().optional(),content:z.string().optional()}).optional()}).refine(a=>a.locales.includes(a.defaultLocale),{message:"The default locale is not included in the list of locales.",path:["defaultLocale"]}),_r=class extends G{constructor(){super(Al);}},Lr=class extends G{constructor(){super(kl);}};var kt=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(o=>` \u2022 **${o.path}**: ${o.message}`).join(`
|
|
1756
|
+
[Window]::SetForegroundWindow(${i})
|
|
1757
|
+
[Window]::ShowWindow(${i}, 9)
|
|
1758
|
+
`;this.runCommand({name:"powershell",arguments:["-Command",`& {${o}}`]});}}runCommand(e){let{commandExecutor:t,timeout:n}=this.configuration;try{let i=t.runSync(e,{timeout:n});return i.exitCode!==0?null:i.output.trim()}catch{return null}}};var si=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 pi=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 ci=class a{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=a.DEFAULT_DOMAINS){this.domains=e;}detect(e){let t=e.toLowerCase().split("@")[1];for(let[n,i]of Object.entries(this.domains))if(i.some(r=>typeof r=="string"?r===t:r.test(t)))return Promise.resolve(n);return Promise.resolve(null)}};var li=class a{static{this.DEFAULT_DOMAINS={google:["google.com"],microsoft:["outlook.com"]};}constructor(e=a.DEFAULT_DOMAINS){this.domains=e;}async detect(e){let t=e.toLowerCase().split("@")[1],n=await this.lookup(t);for(let[i,o]of Object.entries(this.domains))for(let r of o)for(let s of n)if(s.endsWith(`.${r}.`))return i;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(i=>{if(!i.ok)throw new Error("Failed to lookup domain");return i.json()});}catch{return []}return n.Answer===void 0?[]:n.Answer.map(i=>i.data)}};var ui=class a{generate(e){return new URL(`https://mail.google.com/mail${a.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 i=TimeZone.of(Intl.DateTimeFormat().resolvedOptions().timeZone),o=Instant.ofEpochSecond(e.timestamp),r=LocalDateTime.ofInstant(o,i).getLocalDate();t.push(`after:${r}`);}return t.push("in:anywhere"),n+=`/#search/${t.map(i=>encodeURIComponent(i)).join("+")}`,n}};var mi=class{generate(e){return new URL("https://www.icloud.com/mail")}};var di=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 gi=class a{generate(e){return new URL(`https://mail.proton.me/u/0/all-mail${a.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 fi=class a{generate(e){return new URL(`https://mail.yahoo.com/d/search${a.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 en=class{constructor(e){this.config=e;}async execute(e){let{fileSystem:t,io:n}=this.config,i=await this.createTemplate(e.empty??false),o=e.file??t.joinPaths(".","template.json5");try{let r=!1;await t.exists(o)&&(r=await n.input?.confirm({message:`Overwrite existing file at \`${o}\`?`,default:!1})??!1),await t.writeTextFile(o,JSON.stringify(i,null,2),{overwrite:r});}catch(r){throw new d("Failed to write template file",{reason:"other",cause:r})}n.output.confirm(`Template created at \`${o}\``);}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(),i=await t.handle({organizationSlug:n.organization,workspaceSlug:n.workspace}),o={audiences:Object.fromEntries(i.audiences.map(r=>[r.slug,{name:r.name,criteria:r.criteria}])),components:Object.fromEntries(i.components.map(r=>[r.slug,{name:r.name,description:r.description,schema:r.definition}])),slots:Object.fromEntries(i.slots.map(r=>[r.slug,{name:r.name,component:r.component?.slug??"",content:r.content}])),experiences:i.experiences.map(r=>{let{experiment:s}=r,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:r.name,draft:r.status==="DRAFT",audiences:r.audiences,slots:r.slots,content:r.content,...p!==void 0?{experiment:p}:{}}})};for(let[r,s]of Object.entries(o))typeof s=="object"&&s!==null&&(Array.isArray(s)&&s.length===0||Object.keys(s).length===0)&&delete o[r];return o}};var yi=class{constructor(e){this.config=e;}async handle(e){let{input:t,form:n}=this.config,i={components:[],slots:[],audiences:[],experiences:[]},o=new Set,r=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))o.add(c);for(let c of s.flatMap(l=>l.slots))r.add(c);i.experiences=s,s.some(c=>c.experiment!==void 0)&&(await t.confirm({message:"Include experiments?",default:false})||(i.experiences=i.experiences.map(c=>{let{experiment:l,...u}=c;return u})));}i.slots=await n.slot.handle({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,selected:[...r],selectionConfirmation:{message:r.size>0?"Do you want to include other slots?":"Do you want to include slots?",default:false}});let p=new Set(i.slots.map(c=>c.component?.slug??""));return i.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}}),i.audiences=await n.audience.handle({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,selected:[...o],selectionConfirmation:{message:o.size>0?"Do you want to include other audiences?":"Do you want to include audiences?",default:false}}),i}};var hi=class{constructor(e){this.config=e;}async handle(e){let{output:t,input:n,workspaceApi:i}=this.config,o=t.notify("Loading experiences"),r=await i.getExperiences({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});o.stop();let{confirmation:s}=e;if(r.length===0||s!==void 0&&!await n.confirm({message:s}))return [];let p=await n.selectMultiple({message:"Select experiences",options:r.map(l=>({value:l,label:l.name}))});o=t.notify("Loading details");let c=await Promise.all(p.flatMap(async({id:l})=>{let u=await i.getExperience({experienceId:l,organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return u===null?[]:[u]}));return o.stop(),c.flat()}};var Si=class{constructor(e){this.config=e;}async handle(e){let{output:t,input:n}=this.config,i=t.notify("Loading audiences"),o=await this.getAudiences(e,e.allowed);i.stop();let r=e.preselected??[];if(r.length>0)return o.filter(({slug:p})=>r.includes(p));let s=e.selected??[];return o.length===0||s.length>0&&o.every(({slug:p})=>s.includes(p))?o.filter(({slug:p})=>s.includes(p)):e.selectionConfirmation!==void 0&&!await n.confirm(e.selectionConfirmation)?o.filter(({slug:c})=>s.includes(c)):n.selectMultiple({message:"Select audiences",options:o.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,i=await n.getAudiences({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return t===void 0?i:i.filter(({slug:o})=>t.includes(o))}};var h=class a extends d{constructor(e,{tracing:t,...n}={}){super(e,n),this.tracing=t??[],Object.setPrototypeOf(this,a.prototype);}static fromCause(e,t={}){let{message:n,...i}=t;if(!(e instanceof Error))return new a(n??d.formatMessage(e),{...i,cause:e});let o=new a(n??e.message,{cause:e,...e instanceof d?e.help:{},...i,tracing:[...i.tracing??[],...e instanceof a?e.tracing:[]]});return o.stack=e.stack,o}};var wt=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 bi=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:i,options:o}=e,r=await this.resolveUrl(i);return t.execute({template:r.toString(),options:o},new wt({input:n.input,output:n.output,baseUrl:r}))}async resolveUrl(e){let{fileSystem:t}=this.config,n=e;if(URL.canParse(e)){let i=new URL(e.replace(/(?<=^[a-z]+:\/*)([^/.:]+)/i,o=>o.replace(/@/g,"%40")));if(i.protocol!=="file:")return i;n=t.normalizeSeparators(i.pathname);}try{return new URL(`file://${await t.getRealPath(n)}`)}catch(i){throw new h(`Template file not found at \`${n}\`.`,{reason:"invalid_input",cause:i,suggestions:["Check the file path and try again."]})}}};function pt(a,e){if(URL.canParse(a))return new URL(a);let t=new URL(e.href.replace(/^(.*:)(?!\/)/,"$1/"));return new URL(a,t)}var Ii=class{constructor(e){this.config=e;}async execute(e,t){let{fileSystem:n}=this.config,{input:i}=t,o=pt(e.source,t.baseUrl);if(o.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: ${o}`]});let r=n.normalizeSeparators(e.destination),{output:s}=t,p=s?.notify("Downloading sources");try{await this.download(o,{...e,destination:r},i);}finally{p?.stop();}e.result?.destination!==void 0&&t.set(e.result.destination,r);}async download(e,t,n){let{provider:i,fileSystem:o,codemod:r}=this.config,{destination:s,overwrite:p=false}=t,c=t.filter!==void 0?new Minimatch(t.filter):void 0,{value:l}=await i.get(e),u=[],g=Object.fromEntries(Object.entries(t.mapping??{}).map(([y,v])=>[o.normalizeSeparators(y),o.normalizeSeparators(v)]));for await(let y of l){let v=this.resolvePath(o.normalizeSeparators(y.name),g);if(o.isAbsolutePath(v))throw new h("Path to downloaded file cannot be absolute.",{reason:"precondition",details:[`Path: ${v}`],suggestions:["Use relative paths"]});if(!(c!==void 0&&!c.match(v))){if(y.name=o.joinPaths(s,v),y.type==="link"||y.type==="symlink"){let A=o.normalizeSeparators(y.target);if(o.isAbsolutePath(A)||!o.isSubPath(s,A))continue;y.target=A;}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 o.createDirectory(o.getDirectoryName(y.name),{recursive:true}),await o.create(y);for(let y of u)y.type==="file"&&await r.apply(await o.getRealPath(y.name));}resolvePath(e,t){if(e in t)return t[e];let{fileSystem:n}=this.config,i="",o=e,r=n.getSeparator();for(let[s,p]of Object.entries(t)){let c=s.endsWith(r)?s:s+r;e.startsWith(c)&&c.length>i.length&&(i=c,o=n.joinPaths(p,e.slice(c.length)));}return o}async createDirectory(e,t,n,i){let{fileSystem:o}=this.config;if(!await o.exists(t))return o.createDirectory(t,{recursive:true});if(e.length===1&&e[0].type==="file"){if(!n&&await o.exists(e[0].name)&&await i?.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 o.isDirectory(t)){if(!n&&!await o.isEmptyDirectory(t)&&await i?.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 i?.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 o.delete(t,{recursive:true}),await o.createDirectory(t,{recursive:true});}};var vi=class{constructor({packageManager:e}){this.packageManager=e;}async execute(e,t){let{output:n}=t,i=n?.notify("Installing dependencies");try{await this.packageManager.addDependencies(e.dependencies,{dev:e.development??!1,logger:new ae({status:"Installing dependencies",notifier:i})});}catch(o){throw h.fromCause(o)}finally{i?.stop();}}};var Pt=class a{constructor(e){this.matcher=e;}static fromPattern(e){return new a(new Minimatch(e.replace(/^\.\//,"").replace(/\\/g,"/")))}test(e){return Promise.resolve(this.matcher.match(e))}};var xi=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,i=n?.notify("Locating files");try{await this.findMatches(e,t);}finally{i?.stop();}}async findMatches(e,t){t.set(e.result,await this.findMatch(e.path,e));}async findMatch(e,t){let n=(r,s)=>t.depth!==void 0&&s>t.depth?false:this.scanFilter!==void 0?this.scanFilter(r,s):true,i=[],o=Pt.fromPattern(e);for await(let r of this.fileSystem.list(this.projectDirectory.get(),n))if(await o.test(r.name)){if(t.matcher===void 0)i.push(r.name);else if(r.type==="file"){let s=await new Response(r.content).text();this.matches(s,t.matcher)&&i.push(r.name);}if(t.limit!==void 0&&i.length>=t.limit)break}return i}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 wi=class{constructor({fileSystem:e}){this.fileSystem=e;}async execute(e,t){let{output:n}=t,i=n.notify("Replacing file content");try{await this.replaceFiles(e);}finally{i.stop();}}async replaceFiles(e){let t=false;for(let{path:n,replacements:i}of e.files){let o=this.fileSystem.normalizeSeparators(n);if(await this.fileSystem.exists(o)){t=true;try{await this.fileSystem.writeTextFile(o,this.replaceContent(await this.fileSystem.readTextFile(o),i),{overwrite:!0});}catch(r){throw h.fromCause(r)}}}if(!t)throw new h("No files matched for content replacement.",{reason:"unexpected_result"})}replaceContent(e,t){let n=e;for(let{pattern:i,caseSensitive:o,value:r}of t){let s=o===true?"gi":"g";n=n.replace(new RegExp(i,s),`${r}`);}return n}};var Pi=class{constructor({installer:e}){this.installer=e;}async execute(e,t){let{output:n}=t,i=n?.notify("Installing slots");try{await this.installer(e.slots,e.example===!0);}catch(o){throw h.fromCause(o)}finally{i?.stop();}}};var Ci=class{constructor({installer:e}){this.installer=e;}async execute(e,t){let{output:n}=t,i=n?.notify("Installing components");try{await this.installer(e.components);}catch(o){throw h.fromCause(o)}finally{i?.stop();}}};var ki=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 L=class a extends d{constructor(e,t={}){super(e,t),Object.setPrototypeOf(this,a.prototype);}};var Ze=class{constructor(e){this.provider=e;}get action(){return Promise.resolve(this.provider.get()).catch(e=>{throw e instanceof L?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(e){return this.manager.isInitialized(e)}load(){return this.configuration===void 0&&(this.configuration=this.manager.load()),this.configuration}loadPartial(){return this.manager.loadPartial()}update(e){return this.configuration=this.manager.update(e),this.configuration}};var Va;(i=>{function a(o){let r=new Set(Object.values(o.slots??{}).map(u=>u.component)??[]),s=new Set(o.experiences?.flatMap(u=>u.slots)??[]),p=new Set(o.experiences?.flatMap(u=>u.audiences)??[]),c=(o.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(o.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:r,slots:s,audiences:p,locales:l,experiences:c}}i.analyze=a;function e(o){let r=t(o.content);for(let s of o.experiment?.variants??[]){let p=t(s.content);p.audiences.forEach(c=>r.audiences.add(c)),p.slots.forEach(c=>r.slots.add(c));}return {...r}}function t(o){let r=new Set,s=new Set,p=0;for(let[u,g]of Object.entries(o.default??{})){r.add(u);for(let[y,v]of Object.entries(g))s.add(y),p=Math.max(p,n(v));}let c=new Set,l=0;for(let u of o.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)){r.add(g);for(let[v,A]of Object.entries(y))s.add(v),p=Math.max(p,n(A));}}return {slots:r,audiences:c,locales:s,audiencesPerExperience:l,dynamicContentPerContent:p}}function n(o){switch(o.type){case "boolean":case "text":case "number":return o.value.type==="dynamic"?1:0;case "structure":return Object.values(o.attributes).map(n).reduce((r,s)=>r+s,0);case "list":return o.items.map(n).reduce((r,s)=>r+s,0)}}})(Va||={});var Ei=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(i=>this.refactoring.audienceMapping[i]??i),slots:e.slots.map(i=>this.refactoring.slotMapping[i]??i),experiment:n!==void 0?{...n,variants:n.variants.map(i=>({...i,content:this.refactorPersonalizedContent(i.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 i=n.audiences.filter(o=>t.includes(o));return i.length===0?[]:{audiences:i,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 i=this.refactoring.localeMapping[t];return i===null||i!==void 0&&e[i]!==void 0?[]:[[i??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,i])=>[n,this.refactorContent(i,t)]))};case "list":return {...e,items:e.items.map(n=>this.refactorContent(n,t))}}}};var Ri=class a{constructor(e){this.config=e;}async execute(e,t){let{output:n}=t,i=n?.notify("Analyzing resources"),o=Va.analyze(e.resources),{configurationManager:r,api:{workspace:s}}=this.config,p=await r.load(),c=await this.getProjectInfo(p);await this.checkMissingResources({...o,locales:new Set},e.resources,c);let l=await this.createPlan(e.resources,o,c);i?.update("Creating resources");let u=await s.createResources({organizationSlug:p.organization,workspaceSlug:p.workspace,...l.resources});if(i?.stop(),n!==void 0){let g=a.getWarnings(o,c.workspace);if(g.length>0)for(let y of g)n.warn(`${y}`);}e.result!==void 0&&a.setVariables(e.result,l,u,t);}async createPlan(e,t,n){let{mappingForm:i,matcher:o}=this.config,r=await o.match({resources:e,workspaceSlug:n.configuration.workspace,organizationSlug:n.configuration.organization}),s=Object.entries(r.audiences).filter(v=>!("id"in v[1])),p=Object.entries(r.components).filter(v=>!("id"in v[1])),c=Object.entries(r.slots).filter(v=>!("id"in v[1])),l=r.experiences.filter(v=>!("id"in v));await this.checkRequiredQuota(n,{components:p.length,slots:c.length,audiences:s.length,experiences:l.length});let u=await i.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)}}),g={},{workspace:y}=n;for(let v of t.locales)y.locales.includes(v)||(g[v]=y.defaultLocale);return {matches:r,mapping:u,resources:new Ei({componentMapping:u.components,audienceMapping:u.audiences,slotMapping:u.slots,dynamicAttributesPerContent:y.quotas.dynamicAttributesPerContent,maximumAudiencePerExperience:y.quotas.audiencesPerExperience,isCrossDeviceFeatureEnabled:y.features.crossDevice,localeMapping:g}).refactor({components:Object.fromEntries(p),slots:Object.fromEntries(c),audiences:Object.fromEntries(s),experiences:l})}}async getProjectInfo(e){let{api:t}=this.config,[n,i]=await Promise.all([t.organization.getWorkspace({organizationSlug:e.organization,workspaceSlug:e.workspace}),t.workspace.getFeatures({organizationSlug:e.organization,workspaceSlug:e.workspace})]);if(n==null||i==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,...i}}}async checkRequiredQuota(e,t){let{api:{user:n}}=this.config;for(let[i,o]of Object.entries(t)){let r=a.getRemainingQuota(e.workspace,i);if(r<o){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 ${i}`),s.email!==void 0&&p.searchParams.set("email",s.email),new d(`Not enough ${i} quota available in your workspace.`,{title:"Insufficient quota",reason:"precondition",links:[{label:"Request more quota",url:p.toString()}],details:[`Available: ${r}`,`Required: ${o}`],suggestions:[`Free up quota by removing unused ${i}`,"Request additional quota from support"]})}}}async checkMissingResources(e,t,n){let i=await this.findMissingResources(e,t,n);for(let[o,r]of Object.entries(i))if(r.size>0)throw new d(`Some ${o} referenced in the template are missing`,{title:"Invalid template",reason:"invalid_input",details:[`Missing ${o}: ${Array.from(r).join(", ")}`],suggestions:["Report this issue to the template author"]})}async findMissingResources(e,t,n){let i=new Set(e.components),o=new Set(e.slots),r=new Set(e.audiences),s=new Set(e.locales);for(let c of Object.keys(t.components??{}))i.delete(c);for(let c of Object.keys(t.slots??{}))o.delete(c);for(let c of Object.keys(t.audiences??{}))r.delete(c);let{api:p}=this.config;return await Promise.all([...[...i].map(async c=>{await p.workspace.getComponent({organizationSlug:n.configuration.organization,workspaceSlug:n.configuration.workspace,componentSlug:c})!==null&&i.delete(c);}),...[...o].map(async c=>{await p.workspace.getSlot({organizationSlug:n.configuration.organization,workspaceSlug:n.configuration.workspace,slotSlug:c})!==null&&o.delete(c);}),...[...r].map(async c=>{await p.workspace.getAudience({organizationSlug:n.configuration.organization,workspaceSlug:n.configuration.workspace,audienceSlug:c})!==null&&r.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:i,slots:o,audiences:r,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,i){if(e.audiences!==void 0)for(let[s]of Object.entries(t.matches.audiences??{}))e.audiences[s]!==void 0&&i.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&&i.set(p.id,c),p.version!==void 0&&i.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&&i.set(p.id,c),p.version!==void 0&&i.set(p.version,"version"in l?l.version.major:1);}}let{experiences:o}=t.matches,r=0;for(let[s,p]of o.entries()){if(e.experiences?.[s]!==void 0&&i.set(e.experiences[s],"id"in p&&p.id!==void 0?p.id:n.experiences[r].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[r].experimentId;l!==void 0&&i.set(e.experiments[s],l);}(!("id"in p)||p.id===void 0)&&r++;}}};var Ct=class a{constructor(e){this.config=e;}static prompt(e){return new a(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 Oi=class{constructor(e){this.config=e;}async handle(e){let{input:t,workspaceApi:n}=this.config,{resources:i,...o}=e,r=i.slots??[],s=i.components??[],p=i.audiences??[],[c,l,u]=await Promise.all([r.length>0?n.getSlots(o):new Array,s.length>0?n.getComponents(o):new Array,p.length>0?n.getAudiences(o):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 H=await Ct.prompt({input:t,initial:P,unavailableSlugs:S,label:`Component \`${P}\` already exists, enter a new component ID:`});S.push(H),y[P]=H;}}let v=r.filter(S=>c.some(P=>P.slug===S)),A={};if(v.length>0){let S=c.map(P=>P.slug);for(let P of v){let H=await Ct.prompt({input:t,initial:P,unavailableSlugs:S,label:`Slot \`${P}\` already exists, enter a new slot ID:`});S.push(H),A[P]=H;}}let M=p.filter(S=>u.some(P=>P.slug===S)),_={};if(M.length>0){let S=u.map(P=>P.slug);for(let P of M){let H=await Ct.prompt({input:t,initial:P,unavailableSlugs:S,label:`Audience \`${P}\` already exists, enter a new audience ID:`});S.push(H),_[P]=H;}}return {components:y,slots:A,audiences:_}}};var Di=class a{constructor(e){this.config=e;}async match(e){let{resources:t,...n}=e,[i,o,r,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:i,slots:o,audiences:r,experiences:s}}async mapAudiences(e,t){let{workspaceApi:n}=this.config,i=await Promise.all(Object.keys(e).map(async r=>[r,await n.getAudience({...t,audienceSlug:r})])),o={};for(let[r,s]of i)o[r]=s===null||!a.isSimilarAudience(e[r],s)?e[r]:s;return o}async mapComponents(e,t){let{workspaceApi:n}=this.config,i=await Promise.all(Object.keys(e).map(async r=>[r,await n.getComponent({...t,componentSlug:r})])),o={};for(let[r,s]of i)o[r]=s===null||!a.isSimilarComponent(e[r],s)?e[r]:s;return o}async mapSlots(e,t){let{workspaceApi:n}=this.config,i=await Promise.all(Object.keys(e).map(async r=>[r,await n.getSlot({...t,slotSlug:r})])),o={};for(let[r,s]of i)o[r]=s===null||!a.isSimilarSlot(e[r],s)?e[r]:s;return o}async mapExperiences(e,t){let{workspaceApi:n}=this.config,o=(await n.getExperiences({...t,status:["ACTIVE","PAUSED","DRAFT"]})).map(r=>{let s=null;function p(){return s===null&&(s=n.getExperience({...t,experienceId:r.id})),s}return {...r,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 r=>{for(let s of o)if(await this.matchesExperience(r,s)){let{details:p,...c}=s;return c}return r}))}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[i,o=null]=await Promise.all([t.details.content,t.details.experiment]);return e.experiment!==void 0&&(o===null||e.experiment.goalId!==o.goalId||e.experiment.traffic!==o.traffic||e.experiment.crossDevice!==o.crossDevice||!a.isSimilarExperimentContent(e.experiment.variants,o.variants))?false:a.isSimilarPersonalizedContent(e.content,i??{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(i=>deepEqual(n,i)))}static isSimilarExperimentContent(e,t){return e.length!==t.length?false:e.some((n,i)=>deepEqual(n,t[i]))}static isSimilarPersonalizedContent(e,t){if(a.isSimilarSlotContent(e.default??{},t.default??{}))return true;for(let n of e.segmented??[])for(let i of t.segmented??[])if(deepEqual(n.audiences,i.audiences)&&a.isSimilarSlotContent(n.content,i.content))return true;return false}static isSimilarSlotContent(e,t){for(let[n,i]of Object.entries(e)){let o=t[n];if(o!==void 0){for(let r of Object.values(i))if(Object.values(o).some(s=>deepEqual(r,s)))return true}}return false}};var $=class a extends L{constructor(e,{url:t,...n}){super(e,n),Object.setPrototypeOf(this,a.prototype),this.url=t;}},Me=class a extends ${constructor(e,t){super(e,{...t,reason:t.reason??"not_found"}),Object.setPrototypeOf(this,a.prototype);}};var Ti=class a{constructor(e={}){this.configuration=e;}async get(e){if(!["http:","https:"].includes(e.protocol))throw new $("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 Me("Resource not found.",{url:e});let{maxAttempts:i=0,delay:o=1e3}=this.configuration.retry??{};if(a.isSuccessful(n))return n;if(a.isRetryableCode(n.status)&&t<i)return await new Promise(r=>{setTimeout(r,o);}),this.fetch(e,t+1);throw new $(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,i=n?.notify("Checking dependencies"),o;try{o=await Promise.all(e.dependencies.map(s=>this.checkRequirement(s)));}finally{i?.stop();}let r=[];for(let s of o){if(e?.result?.[s.dependency]!==void 0){t.set(e.result[s.dependency],s.satisfied);continue}s.issue!==void 0&&r.push(s);}if(r.length>0){let{message:s,...p}=e.help??{};throw new h(s??"Missing required dependencies.",{...p,details:r.map(({dependency:c,issue:l})=>`\`${c}\`: ${l}`)})}}async checkRequirement(e){let{name:t,version:n,optional:i=false}=e;if(n===void 0){let r=await this.packageManager.hasDirectDependency(t);if(r||i)return {dependency:t,satisfied:r}}else {let r=await this.packageManager.hasDirectDependency(t,n);if(r||i)return {dependency:t,satisfied:r}}let o=await this.packageManager.getDependency(t);return {dependency:t,satisfied:false,issue:o===null?"not installed":`${n!==void 0?`version \`${n}\` is required`:""}found \`${o.version??"unknown"}\``}}};var lt=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 i=e.href.match(typeof t=="string"?new RegExp(t):t);if(i!==null)return n instanceof URL?n:new URL(n.replace(/\$([0-9]+)/g,(o,r)=>i[Number.parseInt(r,10)]),this.baseUrl)}return e}async loadMappings(e){let t=await this.registryProvider.get(e);return Array.isArray(t)?t:t.value}};var Ne=class a{static{this.DEFAULT_EXPECTED_ERRORS=["not_supported","not_found","other"];}constructor({providers:e,expectedErrors:t}){this.providers=e,this.expectedErrors=t??a.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 Me("Resource not found.",{url:e})}isExpectedError(e){return e instanceof $&&this.expectedErrors.includes(e.reason)}};var Ni=class a{constructor(e,t){this.fileSystem=e,this.filter=t;}get(e){if(!a.supportsUrl(e))throw new $(`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 zi=class a{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 $("Unsupported GitHub URL.",{reason:"not_supported",url:e});let n=await this.resolveFiles(t),i=await Promise.all(n.map(async o=>({url:o,response:(await this.provider.get(o)).value})));return {url:t.canonicalUrl,value:this.yieldFiles(i,t.path??"")}}async*yieldFiles(e,t){let n=new Set;for(let{url:i,response:o}of e){let r=i.pathname.split("/"),s=r.slice(4),p=s.join("/")===t&&e.length===1?r.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(o.body)};}}async resolveFiles(e){let{username:t,repository:n,path:i}=e,o=p=>{let c=new URL(`https://${a.RAW_HOST}`);return c.pathname=`/${t}/${n}/${e.ref??"HEAD"}/${p}`,c},r=await this.loadGitTree(e),s=[];if(i===null)s.push(...r.map(p=>o(p.path)));else {let p=r.find(c=>c.path===i);if(p===void 0)throw new $("File not found.",{reason:"not_found",url:e.canonicalUrl});p.type==="tree"?s.push(...r.filter(c=>c.path.startsWith(i)&&c.type==="blob").map(c=>o(c.path))):s.push(o(i));}if(s.length>a.MAX_DOWNLOAD_FILES)throw new $(`The number of files to download exceeds the limit of ${a.MAX_DOWNLOAD_FILES}.`,{reason:"precondition",url:e.canonicalUrl});return s}parseUrl(e){if(!a.isUrlSupported(e))return null;let t,n,i=null,o,r=((e.protocol===a.PROTOCOL?e.hostname:"")+e.pathname).replace(/^\/+/,"").split("/"),s=null;return e.hostname===a.MAIN_HOST?(s=e,[t=null,n=null,,i=null,...o]=r):[t=null,n=null,...o]=r,t===null||n===null?null:(s===null&&(s=new URL(`https://${a.MAIN_HOST}`),s.pathname=`/${t}/${n}/blob/master/${o.join("/")}`),{canonicalUrl:s,username:t,repository:n,ref:i,path:o!==void 0&&o.length>0?o.join("/"):null})}loadGitTree({username:e,repository:t,ref:n}){let i=new URL(`https://${a.API_HOST}`);return i.pathname=`repos/${e}/${t}/git/trees/${n??"HEAD"}`,i.searchParams.set("recursive","true"),this.cache.get(i.toString(),()=>this.provider.get(i).then(o=>o.value.json()).then(({tree:o})=>o))}static isUrlSupported(e){return e.protocol==="https:"?e.hostname===a.MAIN_HOST:e.protocol===a.PROTOCOL}};var tn=class a{constructor(e){this.provider=e;}async get(e){if(!a.supportsUrl(e))throw new $("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 G=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(i=>({path:i.path.reduce((o,r)=>typeof r=="string"?o===""?r:`${o}.${r}`:`${o}[${r}]`,""),message:i.message}))}}};var El=z.object({name:z.string(),version:z.string().optional(),dependencies:z.record(z.string()).optional(),devDependencies:z.record(z.string()).optional(),bin:z.record(z.string()).optional(),scripts:z.record(z.string()).optional(),packageManager:z.string().optional()}),nn=class extends G{constructor(){super(El);}};var Qe=z.string().regex(/^[a-z]+(-?[a-z0-9]+)*$/i,"An identifier must start with a letter and contain only letters, numbers, and hyphens."),$i=z.string().regex(/^[a-z]{2,3}([-_][a-z]{2,3})?$/i,"Locale must be in the form of en, en_US, or en-US."),Fi=z.string().refine(D.isValid,"Version must be exact (1), range (1 - 2), or set (1, 2).").refine(a=>{try{return D.parse(a).getCardinality()<=5}catch{return false}},"Version range must not exceed 5 major versions.");function te(a){return a.optional().catch(void 0)}var Rl=z.object({$schema:te(z.string()),organization:te(Qe),workspace:te(Qe),applications:te(z.object({development:te(Qe),production:te(Qe)})),locales:te(z.array($i).min(1)),defaultLocale:te($i),slots:te(z.record(Fi)),components:te(z.record(Fi)),paths:te(z.object({source:te(z.string()),utilities:te(z.string()),components:te(z.string()),examples:te(z.string()),content:te(z.string())}))}),Ol=z.strictObject({$schema:z.string().optional(),organization:Qe,workspace:Qe,applications:z.strictObject({development:Qe,production:Qe.optional()}),locales:z.array($i).min(1),defaultLocale:$i,slots:z.record(Fi).default({}),components:z.record(Fi).default({}),paths:z.strictObject({source:z.string().optional(),utilities:z.string().optional(),components:z.string().optional(),examples:z.string().optional(),content:z.string().optional()}).optional()}).refine(a=>a.locales.includes(a.defaultLocale),{message:"The default locale is not included in the list of locales.",path:["defaultLocale"]}),ji=class extends G{constructor(){super(Ol);}},_i=class extends G{constructor(){super(Rl);}};var kt=class{constructor({provider:e,validator:t}){this.provider=e,this.validator=t;}async get(e){let{value:t,...n}=await this.provider.get(e),i=await this.validator.validate(t);if(!i.valid){let o=i.violations.map(r=>` \u2022 **${r.path}**: ${r.message}`).join(`
|
|
1759
1759
|
|
|
1760
1760
|
`);throw new $(`The response data is invalid:
|
|
1761
1761
|
|
|
1762
|
-
${i}`,{reason:"invalid_input",url:e})}return {...n,value:r.data}}};var ut=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 Me("File not found.",{url:e});return {...n,value:await new Response(r.value.content).text()}}};var rn=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 $("Malformed JSON.",{reason:"precondition",url:e,cause:r})}}};var Rl=z.strictObject({pattern:z.string().refine(a=>{try{return new RegExp(a),!0}catch{return {message:"Invalid regular expression."}}}),destination:z.string()}),Ol=z.array(Rl),Ur=class extends G{constructor(){super(Ol);}};var on=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 an=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 At;(e=>{function a(...t){return t.reduce((n,r)=>Object.defineProperties(n,Object.getOwnPropertyDescriptors(r)),{})}e.merge=a;})(At||={});var N=class a extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,a.prototype);}};var pn=class a extends N{constructor(e,t){super(e,t),Object.setPrototypeOf(this,a.prototype);}},Wa=Symbol("regex"),Vr=class a{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 sn(e)},"-":{evaluate:async e=>-await q(e)},"+":{evaluate:async e=>+await q(e)}};}static{this.BINARY_OPERATORS={"||":{precedence:1,evaluate:async(e,t)=>await sn(e)||sn(t)},"??":{precedence:1,evaluate:async(e,t)=>{let n=null;try{n=await e();}catch(r){if(!(r instanceof pn))throw r}return n??t()}},"&&":{precedence:2,evaluate:async(e,t)=>await sn(e)&&sn(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 q(e)<await q(t)},">":{precedence:7,evaluate:async(e,t)=>await q(e)>await q(t)},"<=":{precedence:7,evaluate:async(e,t)=>await q(e)<=await q(t)},">=":{precedence:7,evaluate:async(e,t)=>await q(e)>=await q(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 N(`Operands must be numbers or strings, got ${d.describeType(n)} and ${d.describeType(r)}.`);return n+r}},"-":{precedence:9,evaluate:async(e,t)=>await q(e)-await q(t)},"*":{precedence:10,evaluate:async(e,t)=>await q(e)*await q(t)},"/":{precedence:10,evaluate:async(e,t)=>await q(e)/await q(t)},"%":{precedence:10,evaluate:async(e,t)=>await q(e)%await q(t)},"**":{precedence:11,evaluate:async(e,t)=>(await q(e))**await q(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;ze.plugins.register(Dl),ze.plugins.register(Ml),ze.plugins.register(Nl),ze.removeAllUnaryOps();for(let r of Object.keys(a.UNARY_OPERATORS))ze.addUnaryOp(r);ze.removeAllBinaryOps();for(let[r,{precedence:i}]of Object.entries(a.BINARY_OPERATORS))ze.addBinaryOp(r,i);ze.removeAllLiterals();for(let[r,i]of Object.entries(a.LITERALS))ze.addLiteral(r,i);let n;try{n=ze(e);}catch(r){throw new N("Malformed expression.",{cause:r,details:[`Expression: ${e}`]})}return this.cache.set(e,n),n}async evaluateExpression(e,t){switch(true){case J(e,"Literal"):if(e.raw.startsWith("/")){let n=e.raw.lastIndexOf("/"),r=e.raw.slice(n+1),i=e.raw.slice(1,n),o=new String(e.raw);return Object.assign(o,{[Wa]:new RegExp(i,r)}),o}return e.value;case J(e,"ThisExpression"):case J(e,"Identifier"):{let n=e.type==="ThisExpression"?"this":e.name,r=t?.variables?.[n];if(r===void 0)throw new N(`Variable \`${n}\` is unknown.`);return r}case J(e,"ArrayExpression"):return (await Promise.all(e.elements.map(async r=>{if(r===null)return [];if(J(r,"SpreadElement")){let i=await this.evaluateExpression(r.argument,t);if(!Array.isArray(i))throw new N(`Spread expression must evaluate to an array, got ${d.describeType(i)}.`);return i}return [await this.evaluateExpression(r,t)]}))).flat();case J(e,"ObjectExpression"):{let n=await Promise.all(e.properties.map(async r=>{if(J(r,"SpreadElement")){let o=await this.evaluateExpression(r.argument,t);if(typeof o!="object"||o===null)throw new N(`Spread expression must evaluate to an object, got ${d.describeType(o)}.`);return Object.entries(o)}return r.value===void 0&&J(r.key,"Identifier")?[[r.key.name,await this.evaluateExpression(r.key,t)]]:[[J(r.key,"Identifier")?r.key.name:await this.evaluateExpression(r.key,t).then(o=>{if(typeof o!="string"&&typeof o!="number")throw new N(`Property name must be a string or a number, got ${d.describeType(o)}.`);return o}),await this.evaluateExpression(r.value,t)]]}));return Object.fromEntries(n.flat())}case J(e,"UnaryExpression"):return a.UNARY_OPERATORS[e.operator].evaluate(()=>this.evaluateExpression(e.argument,t));case J(e,"BinaryExpression"):return a.BINARY_OPERATORS[e.operator].evaluate(()=>this.evaluateExpression(e.left,t),()=>this.evaluateExpression(e.right,t));case J(e,"MemberExpression"):{let n=await this.evaluateExpression(e.object,t).then(a.unbox);if(typeof n!="object"||n===null)throw new N("Cannot access property of a non-object.");let r=J(e.property,"Identifier")?e.property.name:await this.evaluateExpression(e.property,t);if(typeof r=="number"){if(!Array.isArray(n))throw new N("Cannot access array index of a non-array.");if(r<0||r>=n.length)throw new pn("Array index is out of bounds.");return n[r]}if(typeof r!="string")throw new N(`Property name must be a string, got ${d.describeType(r)}.`);if(!a.isPropertyAllowed(n,r))throw new pn(`Property \`${r}\` does not exist or is not accessible.`);return n[r]}case J(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,o)=>{let s=r[o];if(J(i,"SpreadElement")){if(!Array.isArray(s))throw new N(`Spread argument must evaluate to an array, got ${d.describeType(s)}.`);return s}return [s]}))}case J(e,"ConditionalExpression"):return await this.evaluateExpression(e.test,t)?this.evaluateExpression(e.consequent,t):this.evaluateExpression(e.alternate,t);default:throw new N(`Unexpected expression type \`${e.type}\`.`)}}async getCallee(e,t){if(J(e,"Identifier")){let n=t?.functions?.[e.name]??this.configuration.functions?.[e.name];if(n===void 0)throw new N(`Function \`${e.name}\` does not exist.`);return n}if(J(e,"MemberExpression")){let n=await this.resolve(this.evaluateExpression(e.object,t)).then(a.unbox),r=J(e.property,"Identifier")?e.property.name:await this.evaluateExpression(e.property,t);if(typeof r!="string")throw new N(`Method name must be a string, got ${d.describeType(r)}.`);if(!a.isMethodAllowed(n,r))throw new N(`Method \`${r}\` does not exist or is not accessible.`);let i=n[r].bind(n);return (...o)=>i(...o.map(a.unbox))}throw new N("Callee is not callable.")}static isMethodAllowed(e,t){return typeof e=="string"?a.ALLOWED_STRING_METHODS.includes(t):Array.isArray(e)?a.ALLOWED_ARRAY_METHODS.includes(t):e instanceof RegExp?a.ALLOWED_REGEX_METHODS.includes(t):false}static isPropertyAllowed(e,t){return typeof e=="string"?a.ALLOWED_STRING_PROPERTIES.includes(t):Array.isArray(e)?a.ALLOWED_ARRAY_PROPERTIES.includes(t):e instanceof RegExp?a.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)&&(a.isBoxed(e)||typeof e!="object"||e===null))return e;let t=await e;if(a.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&&Wa in e?e[Wa]:e}static isBoxed(e){return e instanceof String||e instanceof Number||e instanceof Boolean}};function J(a,e){return a.type===e}async function q(a){let e=await a();if(typeof e!="number")throw new N(`Number expected, got ${d.describeType(e)}.`);return e}async function sn(a){let e=await a();if(typeof e!="boolean")throw new N(`Boolean expected, got ${d.describeType(e)}.`);return e}var Et=z.strictObject({description:z.string(),required:z.boolean().optional()}),zl=z.union([z.string(),z.number(),z.boolean(),z.null()]),cn=z.lazy(()=>z.union([zl,z.array(cn),z.record(cn)])),$l=z.discriminatedUnion("type",[Et.extend({type:z.literal("reference"),default:z.string().optional()}),Et.extend({type:z.literal("string"),choices:z.array(z.string()).optional(),default:z.string().optional()}),Et.extend({type:z.literal("number"),default:z.number().optional()}),Et.extend({type:z.literal("boolean"),default:z.boolean().optional()}),Et.extend({type:z.literal("array"),default:z.array(cn).optional()}),Et.extend({type:z.literal("object"),default:z.record(z.string(),cn).optional()})]),Fl=z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/).min(1),_l=z.strictObject({$schema:z.string().optional(),title:z.string().min(1),description:z.string().min(1),metadata:z.record(z.string(),cn).optional(),options:z.record(Fl,$l).optional(),actions:z.array(z.any())}),ln=class extends G{constructor(){super(_l);}};var Wr=class a{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(`
|
|
1762
|
+
${o}`,{reason:"invalid_input",url:e})}return {...n,value:i.data}}};var ut=class{constructor(e){this.provider=e;}async get(e){let{value:t,...n}=await this.provider.get(e),i=await t.next();if(i.done===true||i.value.type!=="file")throw new Me("File not found.",{url:e});return {...n,value:await new Response(i.value.content).text()}}};var on=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(i){throw new $("Malformed JSON.",{reason:"precondition",url:e,cause:i})}}};var Tl=z.strictObject({pattern:z.string().refine(a=>{try{return new RegExp(a),!0}catch{return {message:"Invalid regular expression."}}}),destination:z.string()}),Ml=z.array(Tl),Ui=class extends G{constructor(){super(Ml);}};var rn=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 an=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 At;(e=>{function a(...t){return t.reduce((n,i)=>Object.defineProperties(n,Object.getOwnPropertyDescriptors(i)),{})}e.merge=a;})(At||={});var N=class a extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,a.prototype);}};var pn=class a extends N{constructor(e,t){super(e,t),Object.setPrototypeOf(this,a.prototype);}},Wa=Symbol("regex"),Vi=class a{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 sn(e)},"-":{evaluate:async e=>-await q(e)},"+":{evaluate:async e=>+await q(e)}};}static{this.BINARY_OPERATORS={"||":{precedence:1,evaluate:async(e,t)=>await sn(e)||sn(t)},"??":{precedence:1,evaluate:async(e,t)=>{let n=null;try{n=await e();}catch(i){if(!(i instanceof pn))throw i}return n??t()}},"&&":{precedence:2,evaluate:async(e,t)=>await sn(e)&&sn(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 q(e)<await q(t)},">":{precedence:7,evaluate:async(e,t)=>await q(e)>await q(t)},"<=":{precedence:7,evaluate:async(e,t)=>await q(e)<=await q(t)},">=":{precedence:7,evaluate:async(e,t)=>await q(e)>=await q(t)},"+":{precedence:9,evaluate:async(e,t)=>{let[n,i]=await Promise.all([e(),t()]);if(typeof n=="string"||typeof i=="string")return `${n}${i}`;if(typeof n!="number"||typeof i!="number")throw new N(`Operands must be numbers or strings, got ${d.describeType(n)} and ${d.describeType(i)}.`);return n+i}},"-":{precedence:9,evaluate:async(e,t)=>await q(e)-await q(t)},"*":{precedence:10,evaluate:async(e,t)=>await q(e)*await q(t)},"/":{precedence:10,evaluate:async(e,t)=>await q(e)/await q(t)},"%":{precedence:10,evaluate:async(e,t)=>await q(e)%await q(t)},"**":{precedence:11,evaluate:async(e,t)=>(await q(e))**await q(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;ze.plugins.register(zl),ze.plugins.register($l),ze.plugins.register(Fl),ze.removeAllUnaryOps();for(let i of Object.keys(a.UNARY_OPERATORS))ze.addUnaryOp(i);ze.removeAllBinaryOps();for(let[i,{precedence:o}]of Object.entries(a.BINARY_OPERATORS))ze.addBinaryOp(i,o);ze.removeAllLiterals();for(let[i,o]of Object.entries(a.LITERALS))ze.addLiteral(i,o);let n;try{n=ze(e);}catch(i){throw new N("Malformed expression.",{cause:i,details:[`Expression: ${e}`]})}return this.cache.set(e,n),n}async evaluateExpression(e,t){switch(true){case J(e,"Literal"):if(e.raw.startsWith("/")){let n=e.raw.lastIndexOf("/"),i=e.raw.slice(n+1),o=e.raw.slice(1,n),r=new String(e.raw);return Object.assign(r,{[Wa]:new RegExp(o,i)}),r}return e.value;case J(e,"ThisExpression"):case J(e,"Identifier"):{let n=e.type==="ThisExpression"?"this":e.name,i=t?.variables?.[n];if(i===void 0)throw new N(`Variable \`${n}\` is unknown.`);return i}case J(e,"ArrayExpression"):return (await Promise.all(e.elements.map(async i=>{if(i===null)return [];if(J(i,"SpreadElement")){let o=await this.evaluateExpression(i.argument,t);if(!Array.isArray(o))throw new N(`Spread expression must evaluate to an array, got ${d.describeType(o)}.`);return o}return [await this.evaluateExpression(i,t)]}))).flat();case J(e,"ObjectExpression"):{let n=await Promise.all(e.properties.map(async i=>{if(J(i,"SpreadElement")){let r=await this.evaluateExpression(i.argument,t);if(typeof r!="object"||r===null)throw new N(`Spread expression must evaluate to an object, got ${d.describeType(r)}.`);return Object.entries(r)}return i.value===void 0&&J(i.key,"Identifier")?[[i.key.name,await this.evaluateExpression(i.key,t)]]:[[J(i.key,"Identifier")?i.key.name:await this.evaluateExpression(i.key,t).then(r=>{if(typeof r!="string"&&typeof r!="number")throw new N(`Property name must be a string or a number, got ${d.describeType(r)}.`);return r}),await this.evaluateExpression(i.value,t)]]}));return Object.fromEntries(n.flat())}case J(e,"UnaryExpression"):return a.UNARY_OPERATORS[e.operator].evaluate(()=>this.evaluateExpression(e.argument,t));case J(e,"BinaryExpression"):return a.BINARY_OPERATORS[e.operator].evaluate(()=>this.evaluateExpression(e.left,t),()=>this.evaluateExpression(e.right,t));case J(e,"MemberExpression"):{let n=await this.evaluateExpression(e.object,t).then(a.unbox);if(typeof n!="object"||n===null)throw new N("Cannot access property of a non-object.");let i=J(e.property,"Identifier")?e.property.name:await this.evaluateExpression(e.property,t);if(typeof i=="number"){if(!Array.isArray(n))throw new N("Cannot access array index of a non-array.");if(i<0||i>=n.length)throw new pn("Array index is out of bounds.");return n[i]}if(typeof i!="string")throw new N(`Property name must be a string, got ${d.describeType(i)}.`);if(!a.isPropertyAllowed(n,i))throw new pn(`Property \`${i}\` does not exist or is not accessible.`);return n[i]}case J(e,"CallExpression"):{let[n,i]=await Promise.all([this.getCallee(e.callee,t),Promise.all(e.arguments.map(o=>this.resolve(this.evaluateExpression(o,t))))]);return n(...e.arguments.flatMap((o,r)=>{let s=i[r];if(J(o,"SpreadElement")){if(!Array.isArray(s))throw new N(`Spread argument must evaluate to an array, got ${d.describeType(s)}.`);return s}return [s]}))}case J(e,"ConditionalExpression"):return await this.evaluateExpression(e.test,t)?this.evaluateExpression(e.consequent,t):this.evaluateExpression(e.alternate,t);default:throw new N(`Unexpected expression type \`${e.type}\`.`)}}async getCallee(e,t){if(J(e,"Identifier")){let n=t?.functions?.[e.name]??this.configuration.functions?.[e.name];if(n===void 0)throw new N(`Function \`${e.name}\` does not exist.`);return n}if(J(e,"MemberExpression")){let n=await this.resolve(this.evaluateExpression(e.object,t)).then(a.unbox),i=J(e.property,"Identifier")?e.property.name:await this.evaluateExpression(e.property,t);if(typeof i!="string")throw new N(`Method name must be a string, got ${d.describeType(i)}.`);if(!a.isMethodAllowed(n,i))throw new N(`Method \`${i}\` does not exist or is not accessible.`);let o=n[i].bind(n);return (...r)=>o(...r.map(a.unbox))}throw new N("Callee is not callable.")}static isMethodAllowed(e,t){return typeof e=="string"?a.ALLOWED_STRING_METHODS.includes(t):Array.isArray(e)?a.ALLOWED_ARRAY_METHODS.includes(t):e instanceof RegExp?a.ALLOWED_REGEX_METHODS.includes(t):false}static isPropertyAllowed(e,t){return typeof e=="string"?a.ALLOWED_STRING_PROPERTIES.includes(t):Array.isArray(e)?a.ALLOWED_ARRAY_PROPERTIES.includes(t):e instanceof RegExp?a.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)&&(a.isBoxed(e)||typeof e!="object"||e===null))return e;let t=await e;if(a.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(([i,o])=>o===void 0?[]:[[i,this.resolve(o)]])));return Object.isFrozen(t)?Object.freeze(n):Object.isSealed(t)&&Object.seal(n),n}return t}static unbox(e){return e instanceof String&&Wa in e?e[Wa]:e}static isBoxed(e){return e instanceof String||e instanceof Number||e instanceof Boolean}};function J(a,e){return a.type===e}async function q(a){let e=await a();if(typeof e!="number")throw new N(`Number expected, got ${d.describeType(e)}.`);return e}async function sn(a){let e=await a();if(typeof e!="boolean")throw new N(`Boolean expected, got ${d.describeType(e)}.`);return e}var Et=z.strictObject({description:z.string(),required:z.boolean().optional()}),jl=z.union([z.string(),z.number(),z.boolean(),z.null()]),cn=z.lazy(()=>z.union([jl,z.array(cn),z.record(cn)])),_l=z.discriminatedUnion("type",[Et.extend({type:z.literal("reference"),default:z.string().optional()}),Et.extend({type:z.literal("string"),choices:z.array(z.string()).optional(),default:z.string().optional()}),Et.extend({type:z.literal("number"),default:z.number().optional()}),Et.extend({type:z.literal("boolean"),default:z.boolean().optional()}),Et.extend({type:z.literal("array"),default:z.array(cn).optional()}),Et.extend({type:z.literal("object"),default:z.record(z.string(),cn).optional()})]),Ll=z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/).min(1),Ul=z.strictObject({$schema:z.string().optional(),title:z.string().min(1),description:z.string().min(1),metadata:z.record(z.string(),cn).optional(),options:z.record(Ll,_l).optional(),actions:z.array(z.any())}),ln=class extends G{constructor(){super(Ul);}};var Wi=class a{constructor(e){this.resolving=[];this.config=e;}async execute(e,t){await this.importTemplate(e,t);}async importTemplate(e,t){let{url:n,value:i}=await this.loadTemplate(e.template,t.baseUrl,t.output),o=await this.getInputValues(i,e.options);if(this.resolving.includes(n.href)){let s=[...this.resolving,n.href].map((p,c)=>` ${c+1}. ${p}`).join(`
|
|
1763
1763
|
`);throw new h(`Circular dependency detected while loading templates:
|
|
1764
1764
|
|
|
1765
|
-
${s}`,{reason:"invalid_input"})}this.resolving.push(n.toString());let
|
|
1766
|
-
`?(this.line++,this.column=1):this.column++,
|
|
1765
|
+
${s}`,{reason:"invalid_input"})}this.resolving.push(n.toString());let r=new wt({input:t.input,output:t.output,baseUrl:n});a.shareVariables(o.references,t,r);try{await this.run(i,o.values,r);}finally{this.resolving.pop();}a.shareVariables(o.references,r,t);}async getInputValues(e,t={}){let n={},i=[];for(let[o,r]of Object.entries(e.options??{})){let s=t[o];if(s===void 0&&r.required===true)throw new h(`Missing required option \`${o}\`.`,{reason:"invalid_input"});let p=await(s??r.resolveDefault?.(this.config.variables));p===void 0?n[o]=null:(r.type==="reference"?(a.checkOptionValue(o,p,{...r,type:"string"}),i.push(p)):a.checkOptionValue(o,p,r),n[o]=p);}return {values:n,references:i}}async run(e,t,n){let{runner:i,variables:o}=this.config,{output:r}=n;for(let{resolve:s}of e.actions){let p=r.notify("Resolving options"),c;try{c=await s(At.merge(o,{options:t,get this(){return n.getVariables()}}));}catch(l){throw h.fromCause(l,{message:"Unable to resolve action definition."})}finally{p.stop();}await i.execute({actions:[c]},n);}}async loadTemplate(e,t,n){let i=this.config.templateProvider,o=pt(e,t),r=n.notify("Loading template");try{return await i.get(o)}catch(s){throw s instanceof Me?new d(`No template found at \`${decodeURIComponent(o.toString())}\`.`,{cause:s,reason:"invalid_input",suggestions:["Check if the template path or URL is correct and try again."]}):s}finally{r.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 i=t.getVariables();for(let o of e)i[o]!==void 0&&n.set(o,i[o]);}};var T=class{constructor(e){this.configuration=e;}async execute(e,t){let{action:n,validator:i}=this.configuration,o=await i.validate(e);if(!o.valid){let r=o.violations.map(s=>(s.path===""?s.message:`**${s.path}**: ${s.message}`).replace(/'/g,"`"));throw new h("Invalid action options.",{reason:"invalid_input",details:r})}await n.execute(o.data,t);}};var un;(n=>{let a=Symbol("source");function e(i){return i[a]??null}n.get=e;function t(i,o){i[a]=o;}n.set=t;})(un||={});var qi=class a{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 [...a.from(e,t)]}static from(e,t){return new a(a.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,i=0,o="";for(;this.cursor<this.chars.length;){let r=this.chars[this.cursor],s=r==="$"&&this.chars[this.cursor+1]==="{";if(!(i+t+n>0)&&s&&o.length>0)return this.createLiteralFragment(o,e);if(this.cursor++,this.index++,r===`
|
|
1766
|
+
`?(this.line++,this.column=1):this.column++,o+=r,t>0||n>0)r==="\\"?(o+=this.chars[this.cursor],this.cursor++,this.index++,this.column++):t>0&&r==="'"?t--:n>0&&r==='"'&&n--;else if(i>0){if(r==="'"?t++:r==='"'?n++:r==="{"?i++:r==="}"&&i--,i===0)return this.createExpressionFragment(o,e)}else s&&(o+=this.chars[this.cursor],i++,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(i>0)throw new d("Unbalanced braces in template string.",{details:[`Location: line ${e.line}, column ${e.column}`]});return this.createLiteralFragment(o,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 B=class a extends Promise{#t;#n;#e;constructor(e,t=false){super(()=>{}),this.#t=e,this.#n=t;}static from(e){return new a(e)}static transient(e){return new a(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 ce=class a extends ${constructor(e,{violations:t,...n}){super(e,n),this.violations=t,Object.setPrototypeOf(this,a.prototype);}},Ki=class a{constructor({evaluator:e,validator:t,templateProvider:n,fileProvider:i}){this.loading=[];this.evaluator=e,this.validator=t,this.templateProvider=n,this.fileProvider=i;}async get(e){let{url:t,value:n}=await this.templateProvider.get(e),i;try{i=a.cleanJson(JsonParser.parse(n,JsonObjectNode));}catch(g){throw new ce("Failed to parse the JSON template.",{reason:"invalid_input",url:t,cause:g,violations:[{path:"",message:d.formatMessage(g)}]})}let o=i.toJSON(),r=await this.validator.validate(o);if(!r.valid){let g=r.violations.map(y=>` \u2022 **${y.path}**: ${y.message}`).join(`
|
|
1767
1767
|
|
|
1768
1768
|
`);throw new ce(`The template contains errors:
|
|
1769
1769
|
|
|
1770
|
-
${g}`,{reason:"invalid_input",url:t,violations:
|
|
1770
|
+
${g}`,{reason:"invalid_input",url:t,violations:r.violations})}let{options:s,actions:p,...c}=r.data,l=i.get("actions",JsonArrayNode),u=this.parseOptions(i,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 i=e.get("options",JsonObjectNode);return Object.fromEntries(Object.entries(t).map(([o,r])=>{if(r.default===void 0)return [o,r];let s=i.get(o,JsonObjectNode).get("default");return [o,{...r,resolveDefault:p=>this.resolve(s,p,n)}]}))}resolve(e,t,n,i=""){return e instanceof JsonArrayNode?e.elements.map((o,r)=>this.resolve(o,t,n,`${i}[${r}]`)):e instanceof JsonObjectNode?B.transient(async()=>{let o=Object.fromEntries(await Promise.all(e.properties.map(async r=>{let s=await this.interpolate(r.key,t,n,i);if(typeof s!="string"&&typeof s!="number"){let c=r.key.location.start;throw new ce("Unexpected object key type.",{url:n,reason:"invalid_input",violations:[{path:i,message:`Expected object key to resolve to string or number at line ${c.line}, column ${c.column} but got ${d.describeType(s)}.`}]})}let p=i===""?`${s}`:`${i}.${s}`;return [s,B.transient(()=>this.resolve(r.value,t,n,p))]})));return un.set(o,{url:n,start:e.location.start,end:e.location.end}),o}):e instanceof JsonPrimitiveNode&&typeof e.value=="string"?B.transient(()=>this.interpolate(e,t,n,i)):e.toJSON()}interpolate(e,t,n,i){let o=qi.parse(e);if(o.length===1){let r=o[0];return r.type==="literal"?r.source:this.evaluate(a.createExpressionNode(r),t,n,i)}return Promise.all(o.map(async r=>{if(r.type==="literal")return r.source;let s=a.createExpressionNode(r),p=await this.evaluate(s,t,n,i);if(p!==null&&!["string","number","boolean"].includes(typeof p)){let c=e.location.start;throw new ce("Unexpected expression result.",{reason:"invalid_input",url:n,violations:[{path:i,message:`Expected expression \`${r.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(r=>r.join(""))}async evaluate(e,t,n,i){let o=(e instanceof JsonIdentifierNode?e.token.value:e.value).trim();try{return await this.evaluator.evaluate(o,{variables:t,functions:{url:(r="")=>{if(typeof r!="string"){let s=e.location.start;throw new N("Invalid argument for function `url`.",{reason:"invalid_input",details:[`The \`url\` argument of the \`url\` function must be a string, but got ${d.describeType(r)} at line ${s.line}, column ${s.column}.`]})}return pt(r,n).toString()},import:(r,s)=>{if(typeof r!="string"){let p=e.location.start;throw new N("Invalid argument for function `import`.",{reason:"invalid_input",details:[`The \`url\` argument of the \`import\` function must be a string, but got ${d.describeType(r)} 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 N("Invalid argument for function `import`.",{reason:"invalid_input",details:[`The \`properties\` argument of the \`import\` function must be an object, but got ${d.describeType(r)} at line ${p.line}, column ${p.column}.`]})}return this.import(pt(r,n),s===void 0?t:At.merge(t,{this:Promise.resolve(t.this).then(p=>typeof p=="object"&&p!==null&&!Array.isArray(p)?At.merge(p,s):s)}),n,i)}}})}catch(r){let s=e.location.start;throw new ce("Failed to evaluate expression.",{reason:"invalid_input",url:n,cause:r,violations:[{path:i,message:`Evaluation of \`${o}\` at line ${s.line}, column ${s.column} failed because ${d.formatCause(r)}`}]})}}async import(e,t,n,i){if(e.protocol==="file:"&&n.protocol!=="file:")throw new ce("Unsafe import URL.",{reason:"precondition",url:e,violations:[{path:i,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(`
|
|
1771
1771
|
`);throw new ce(`Circular dependency detected while loading templates:
|
|
1772
1772
|
|
|
1773
|
-
${p}`,{reason:"invalid_input",url:e,violations:[{path:r,message:"Imported template creates a circular dependency."}]})}let{url:i,value:o}=await this.fileProvider.get(e),s;try{s=a.cleanJson(JsonParser$1.parse(o));}catch(p){throw new ce("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 Ha=Symbol("any-property"),Jp=Symbol("any-index"),dn=Symbol("passthrough"),Rt=Symbol("resolve"),I=class a extends G{async validate(e){let t=this.findPassthroughPaths(this.schema),n;try{n=await this.resolveOptions(e,t);}catch(r){if(r instanceof ce)return {valid:false,violations:r.violations};throw r}return super.validate(n).then(r=>(r.valid&&a.restoreSymbols(n,r.data),r))}async resolveOptions(e,t,n=[]){if(typeof e!="object"||e===null||a.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[o,s]of e.entries()){let p=[...n,o];a.isPassthroughPath(p,t)?i[o]=s:r[o]=this.resolveOptions(await s,t,p);}for(let[o,s]of (await Promise.all(r)).entries())s!==void 0&&(i[o]=s);return i}return {...e,...Object.fromEntries(await Promise.all(Object.entries(e).map(async([r,i])=>{let o=[...n,r];return a.isPassthroughPath(o,t)?[r,i]:[r,await this.resolveOptions(await i,t,o)]})))}}static isPassthroughPath(e,t){for(let n of t)if(n.length===e.length+1)for(let[r,i]of n.entries()){let o=typeof e[r]=="number"?Jp:Ha;if(r<e.length?i!==e[r]&&i!==o:i!==Rt&&i!==dn)break;if(r===n.length-1)return i===dn}return false}findPassthroughPaths(e,t=[]){if(e instanceof ZodPromise)return [[...t,dn]];if(e instanceof ZodOptional)return this.findPassthroughPaths(e.unwrap(),t);if(e instanceof ZodTuple)return [[...t,Rt],...e.items.flatMap((n,r)=>this.findPassthroughPaths(n,[...t,r]))];if(e instanceof ZodArray)return [[...t,Rt],...this.findPassthroughPaths(e.element,[...t,Jp])];if(e instanceof ZodRecord)return [[...t,Rt],...this.findPassthroughPaths(e.valueSchema,[...t,Ha])];if(e instanceof ZodObject){let n=[[...t,Rt],...Object.entries(e.shape).flatMap(([r,i])=>this.findPassthroughPaths(i,[...t,r]))];return e._def.unknownKeys==="passthrough"&&n.push([...t,Ha,dn]),n}if(e instanceof ZodEffects){let n=e.innerType();return n instanceof ZodAny?[[...t,dn]]: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,Rt]]}static restoreSymbols(e,t){if(Array.isArray(e)&&Array.isArray(t)){for(let[n,r]of e.entries())n<t.length&&a.restoreSymbols(r,t[n]);return}if(!(!Gp(e)||!Gp(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&&a.restoreSymbols(r,t[n]);}}};var Yl=z.strictObject({action:z.instanceof(Promise),else:z.instanceof(Promise).optional(),finally:z.instanceof(Promise).optional(),help:z.strictObject({message:z.string().min(1).optional(),links:z.array(z.strictObject({url:z.string().url(),label:z.string().min(1)})).optional(),suggestions:z.array(z.string().min(1)).optional()}).optional()}),Hr=class extends I{constructor(){super(Yl);}};var eu=z.strictObject({name:z.string().min(1),version:z.string().min(1).optional(),optional:z.boolean().optional()}),tu=z.strictObject({dependencies:z.array(eu),help:z.strictObject({message:z.string().min(1).optional(),links:z.array(z.strictObject({url:z.string().url(),label:z.string().min(1)})).optional(),suggestions:z.array(z.string().min(1)).optional()}).optional(),result:z.record(z.string().min(1)).optional()}),Gr=class extends I{constructor(){super(tu);}};var nu=z.strictObject({source:z.string().min(1),filter:z.string().min(1).optional(),destination:z.string().min(1),mapping:z.record(z.string().min(1),z.string().min(1)).optional(),overwrite:z.boolean().optional(),result:z.strictObject({destination:z.string().min(1).optional()}).optional()}),Jr=class extends I{constructor(){super(nu);}};var ru=z.strictObject({dependencies:z.array(z.string().min(1)).min(1),development:z.boolean().optional()}),Zr=class extends I{constructor(){super(ru);}};var iu=z.strictObject({pattern:z.string().min(1),caseSensitive:z.boolean().optional()}),Bp=z.union([iu,z.strictObject({type:z.enum(["and","or"]),matchers:z.array(z.lazy(()=>Bp)).min(1)})]),ou=z.strictObject({path:z.string().min(1),matcher:Bp.optional(),limit:z.number().int().positive().optional(),depth:z.number().int().nonnegative().optional(),result:z.string()}),Qr=class extends I{constructor(){super(ou);}};var au=z.strictObject({files:z.array(z.strictObject({path:z.string(),replacements:z.array(z.strictObject({pattern:z.string().refine(a=>{try{return new RegExp(a),!0}catch{return {message:"Invalid regular expression pattern"}}}),caseSensitive:z.boolean().optional(),value:z.union([z.string(),z.number()])})).min(1)})).min(1)}),Xr=class extends I{constructor(){super(au);}};var su=z.strictObject({slots:z.array(z.string().min(1)).min(1),example:z.boolean().optional()}),ei=class extends I{constructor(){super(su);}};var pu=z.strictObject({components:z.array(z.string().min(1)).min(1)}),ti=class extends I{constructor(){super(pu);}};var cu=z.strictObject({name:z.string().min(1),criteria:z.string().min(1)}),mt=z.strictObject({title:z.string().optional(),description:z.string().optional()}),lu=mt.extend({type:z.literal("boolean"),label:z.strictObject({true:z.string(),false:z.string()}).optional(),default:z.boolean().optional()}),uu=z.strictObject({label:z.string().optional(),description:z.string().optional(),default:z.boolean().optional(),position:z.number().optional()}),mu=mt.extend({type:z.literal("text"),minimumLength:z.number().optional(),maximumLength:z.number().optional(),format:z.string().optional(),pattern:z.string().optional(),choices:z.record(uu).optional()}),du=mt.extend({type:z.literal("number"),integer:z.boolean().optional(),minimum:z.number().optional(),maximum:z.number().optional()}),gu=z.lazy(()=>z.strictObject({type:z.lazy(()=>ec),label:z.string().optional(),description:z.string().optional(),optional:z.boolean().optional(),private:z.boolean().optional(),position:z.number().optional()})),Ba=mt.extend({type:z.literal("structure"),attributes:z.record(z.string(),gu)}),fu=mt.extend({type:z.literal("list"),items:z.lazy(()=>ec),itemLabel:z.string().optional(),minimumLength:z.number().optional(),maximumLength:z.number().optional()}),yu=z.union([z.string(),z.number(),z.boolean(),z.null()]),Ja=z.lazy(()=>z.union([yu,z.array(Ja),z.record(Ja)])),Xp=mt.extend({type:z.literal("reference"),id:z.string(),properties:z.record(z.string(),Ja).optional()}),Yp=mt.extend({type:z.literal("union"),types:z.record(z.string(),z.discriminatedUnion("type",[Ba,Xp]))}),ec=z.discriminatedUnion("type",[lu,mu,du,Ba,fu,Yp,Xp]),hu=z.discriminatedUnion("type",[Ba,Yp]),Su=z.strictObject({name:z.string().min(1),description:z.string().min(1).optional(),schema:hu}),bu=z.union([z.strictObject({type:z.literal("static"),value:z.string()}),z.strictObject({type:z.literal("dynamic"),expression:z.string(),nullable:z.literal(false),default:z.string()}),z.strictObject({type:z.literal("dynamic"),expression:z.string(),nullable:z.literal(true),default:z.string().optional()})]),Iu=z.union([z.strictObject({type:z.literal("static"),value:z.number()}),z.strictObject({type:z.literal("dynamic"),nullable:z.literal(false),default:z.number(),expression:z.string()}),z.strictObject({type:z.literal("dynamic"),nullable:z.literal(true),default:z.number().optional(),expression:z.string()})]),vu=z.union([z.strictObject({type:z.literal("static"),value:z.boolean()}),z.strictObject({type:z.literal("dynamic"),nullable:z.literal(false),default:z.boolean(),expression:z.string()}),z.strictObject({type:z.literal("dynamic"),nullable:z.literal(true),default:z.boolean().optional(),expression:z.string()})]),xu=z.strictObject({type:z.literal("text"),value:bu}),wu=z.strictObject({type:z.literal("number"),value:Iu}),Pu=z.strictObject({type:z.literal("boolean"),value:vu}),tc=z.strictObject({type:z.literal("structure"),name:z.string().optional(),attributes:z.record(z.string(),z.lazy(()=>nc))}),Cu=z.strictObject({type:z.literal("list"),items:z.array(z.lazy(()=>z.intersection(nc,z.object({label:z.string().optional()}))))}),nc=z.discriminatedUnion("type",[xu,wu,Pu,tc,Cu]),rc=z.record(z.string(),tc),ku=z.strictObject({name:z.string().min(1),component:z.string().min(1),content:rc}),ic=z.record(z.string(),rc),Au=z.strictObject({audiences:z.array(z.string()),content:ic}),oc=z.strictObject({default:ic.optional(),segmented:z.array(Au).optional()}),Eu=z.strictObject({name:z.string(),content:oc,baseline:z.boolean().optional(),allocation:z.number().min(0)}),Ru=z.strictObject({name:z.string(),draft:z.boolean().optional(),audiences:z.array(z.string()),slots:z.array(z.string()),experiment:z.strictObject({name:z.string(),goalId:z.string().optional(),crossDevice:z.boolean().optional(),traffic:z.number().min(0).max(1),variants:z.array(Eu)}).optional(),content:oc}),Ou=z.record(z.string().min(1),z.string().min(1)),Zp=z.record(z.union([z.string().min(1).regex(/^\d+$/),z.number().nonnegative()]),z.string().min(1)),Qp=z.record(z.string().min(1),z.strictObject({id:z.string().min(1).optional(),version:z.string().min(1).optional()})),Tu=z.strictObject({resources:z.strictObject({audiences:z.record(z.string().min(1),cu).optional(),components:z.record(z.string().min(1),Su).optional(),slots:z.record(z.string().min(1),ku).optional(),experiences:z.array(Ru).optional()}),result:z.strictObject({audiences:Ou.optional(),components:Qp.optional(),slots:Qp.optional(),experiences:Zp.optional(),experiments:Zp.optional()}).optional()}),ni=class extends I{constructor(){super(Tu);}};var Du=z.union([z.string(),z.number(),z.boolean(),z.null()]),Za=z.lazy(()=>z.union([Du,z.array(Za),z.record(Za)])),Mu=z.strictObject({template:z.string().min(1),options:z.record(z.string().min(1),Za).optional()}),ri=class extends I{constructor(){super(Mu);}};var ii=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 Nu=z.strictObject({files:z.array(z.string().min(1)).min(1)}),oi=class extends I{constructor(){super(Nu);}};var Ot=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 j(`No value found for discriminator "${String(e)}".`,{reason:"not_supported"});return t instanceof Function?t():t.get()}};var ai=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 zu=z.strictObject({condition:z.boolean(),then:z.instanceof(Promise),else:z.instanceof(Promise).optional()}),pi=class extends I{constructor(){super(zu);}};var ci=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 $u=z.strictObject({semantics:z.enum(["neutral","info","error","warning","success"]).optional(),title:z.string().optional(),message:z.string()}),ui=class extends I{constructor(){super($u);}};var mi=class{execute(e){let{message:t,...n}=e;throw new h(t,{...n,reason:"precondition"})}};var Fu=z.strictObject({title:z.string().min(1).optional(),message:z.string().min(1),links:z.array(z.strictObject({label:z.string().min(1),url:z.string().url()})).optional(),suggestions:z.array(z.string().min(1)).optional(),details:z.array(z.string().min(1)).optional()}),di=class extends I{constructor(){super(Fu);}};var gi=class{constructor({url:e,provider:t}){this.url=e,this.provider=t;}get(){return this.provider.get(this.url)}};var Tt=class{constructor(e){this.data=e;}get(){return Promise.resolve(this.data)}};var fi=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 j("No server found.")}};var yi=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 hi=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 Si=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 bi=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,o=n!==null?n[1]:"localhost";return {protocol:r!==null&&r[1]==="true"?"https":"http",host:o,...i!==null?{port:i}:{},defaultPort:5173}}};var Ii=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 _u=z.strictObject({type:z.literal("confirmation"),message:z.string(),default:z.boolean().optional(),result:z.string()}),Xa=z.string(),Lu=z.preprocess(a=>typeof a=="string"?{value:a,label:a}:a,z.strictObject({value:Xa,label:z.string().min(1).optional(),disabled:z.boolean().optional()})).transform(a=>({...a,label:a.label??a.value.toString()})),ju=z.strictObject({type:z.literal("choice"),message:z.string(),options:z.array(Lu),default:Xa.optional(),result:z.string()}),Uu=z.preprocess(a=>typeof a=="string"?{value:a,label:a}:a,z.strictObject({value:Xa,label:z.string().min(1).optional(),selected:z.boolean().optional(),disabled:z.boolean().optional()})).transform(a=>({...a,label:a.label??a.value.toString()})),Vu=z.strictObject({type:z.literal("multi-choice"),message:z.string(),min:z.number().optional(),max:z.number().optional(),options:z.array(Uu),result:z.string()}),Wu=z.strictObject({type:z.literal("text"),message:z.string(),default:z.string().optional(),required:z.boolean().optional(),result:z.string()}),qu=z.strictObject({type:z.literal("keypress"),message:z.string(),key:z.union([z.literal("enter"),z.literal("space"),z.string().length(1)]).optional(),result:z.string().optional()}),Ku=z.discriminatedUnion("type",[_u,ju,Vu,Wu,qu]),vi=class extends I{constructor(){super(Ku);}};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 ae({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 Gu=z.strictObject({server:z.strictObject({script:z.string(),arguments:z.array(z.string()).optional(),url:z.string()}).optional(),result:z.strictObject({id:z.string().optional(),url:z.string().optional()}).optional()}),wi=class extends I{constructor(){super(Gu);}};var Pi=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 ce&&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:un.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 ac=z.object({name:z.string().min(1)}).passthrough(),Bu=z.strictObject({actions:z.union([ac,z.array(ac)])}),Ci=class extends I{constructor(){super(Bu);}};var ki=class{async execute(e,t){let{output:n}=t;await n.open(e.url);}};var Zu=z.strictObject({url:z.string().url()}),Ai=class extends I{constructor(){super(Zu);}};var Qu=z.union([z.string(),z.number(),z.boolean(),z.null()]),Ya=z.lazy(()=>z.union([Qu,z.array(Ya),z.record(Ya)])),Xu=z.strictObject({variables:z.record(z.string(),Ya)}),Ei=class extends I{constructor(){super(Xu);}};var Ri=class{execute(e,t){for(let[n,r]of Object.entries(e.variables))t.set(n,r);return Promise.resolve()}};var Yu=z.strictObject({id:z.string()}),Oi=class extends I{constructor(){super(Yu);}};var Dt=class a extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,a.prototype);}};var le=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===`
|
|
1774
|
-
`){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,
|
|
1775
|
-
`)}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
|
|
1776
|
-
`)}static getRawString(e){return
|
|
1773
|
+
${p}`,{reason:"invalid_input",url:e,violations:[{path:i,message:"Imported template creates a circular dependency."}]})}let{url:o,value:r}=await this.fileProvider.get(e),s;try{s=a.cleanJson(JsonParser.parse(r));}catch(p){throw new ce("Failed to parse referenced JSON.",{reason:"invalid_input",cause:p,url:o,violations:[{path:i,message:d.formatMessage(p)}]})}this.loading.push(o.toString());try{return this.resolve(s,t,o,i)}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 Ha=Symbol("any-property"),Bp=Symbol("any-index"),dn=Symbol("passthrough"),Rt=Symbol("resolve"),I=class a extends G{async validate(e){let t=this.findPassthroughPaths(this.schema),n;try{n=await this.resolveOptions(e,t);}catch(i){if(i instanceof ce)return {valid:false,violations:i.violations};throw i}return super.validate(n).then(i=>(i.valid&&a.restoreSymbols(n,i.data),i))}async resolveOptions(e,t,n=[]){if(typeof e!="object"||e===null||a.isPassthroughPath(n,t))return e;if(e instanceof Promise)return this.resolveOptions(await e,t,n);if(Array.isArray(e)){let i=new Array(e.length),o=new Array(e.length);for(let[r,s]of e.entries()){let p=[...n,r];a.isPassthroughPath(p,t)?o[r]=s:i[r]=this.resolveOptions(await s,t,p);}for(let[r,s]of (await Promise.all(i)).entries())s!==void 0&&(o[r]=s);return o}return {...e,...Object.fromEntries(await Promise.all(Object.entries(e).map(async([i,o])=>{let r=[...n,i];return a.isPassthroughPath(r,t)?[i,o]:[i,await this.resolveOptions(await o,t,r)]})))}}static isPassthroughPath(e,t){for(let n of t)if(n.length===e.length+1)for(let[i,o]of n.entries()){let r=typeof e[i]=="number"?Bp:Ha;if(i<e.length?o!==e[i]&&o!==r:o!==Rt&&o!==dn)break;if(i===n.length-1)return o===dn}return false}findPassthroughPaths(e,t=[]){if(e instanceof ZodPromise)return [[...t,dn]];if(e instanceof ZodOptional)return this.findPassthroughPaths(e.unwrap(),t);if(e instanceof ZodTuple)return [[...t,Rt],...e.items.flatMap((n,i)=>this.findPassthroughPaths(n,[...t,i]))];if(e instanceof ZodArray)return [[...t,Rt],...this.findPassthroughPaths(e.element,[...t,Bp])];if(e instanceof ZodRecord)return [[...t,Rt],...this.findPassthroughPaths(e.valueSchema,[...t,Ha])];if(e instanceof ZodObject){let n=[[...t,Rt],...Object.entries(e.shape).flatMap(([i,o])=>this.findPassthroughPaths(o,[...t,i]))];return e._def.unknownKeys==="passthrough"&&n.push([...t,Ha,dn]),n}if(e instanceof ZodEffects){let n=e.innerType();return n instanceof ZodAny?[[...t,dn]]: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,Rt]]}static restoreSymbols(e,t){if(Array.isArray(e)&&Array.isArray(t)){for(let[n,i]of e.entries())n<t.length&&a.restoreSymbols(i,t[n]);return}if(!(!Jp(e)||!Jp(t))){for(let n of Object.getOwnPropertySymbols(e))Object.assign(t,{[n]:e[n]});for(let[n,i]of Object.entries(e))n in t&&a.restoreSymbols(i,t[n]);}}};var nu=z.strictObject({action:z.instanceof(Promise),else:z.instanceof(Promise).optional(),finally:z.instanceof(Promise).optional(),help:z.strictObject({message:z.string().min(1).optional(),links:z.array(z.strictObject({url:z.string().url(),label:z.string().min(1)})).optional(),suggestions:z.array(z.string().min(1)).optional()}).optional()}),Hi=class extends I{constructor(){super(nu);}};var iu=z.strictObject({name:z.string().min(1),version:z.string().min(1).optional(),optional:z.boolean().optional()}),ou=z.strictObject({dependencies:z.array(iu),help:z.strictObject({message:z.string().min(1).optional(),links:z.array(z.strictObject({url:z.string().url(),label:z.string().min(1)})).optional(),suggestions:z.array(z.string().min(1)).optional()}).optional(),result:z.record(z.string().min(1)).optional()}),Gi=class extends I{constructor(){super(ou);}};var ru=z.strictObject({source:z.string().min(1),filter:z.string().min(1).optional(),destination:z.string().min(1),mapping:z.record(z.string().min(1),z.string().min(1)).optional(),overwrite:z.boolean().optional(),result:z.strictObject({destination:z.string().min(1).optional()}).optional()}),Ji=class extends I{constructor(){super(ru);}};var au=z.strictObject({dependencies:z.array(z.string().min(1)).min(1),development:z.boolean().optional()}),Zi=class extends I{constructor(){super(au);}};var su=z.strictObject({pattern:z.string().min(1),caseSensitive:z.boolean().optional()}),Zp=z.union([su,z.strictObject({type:z.enum(["and","or"]),matchers:z.array(z.lazy(()=>Zp)).min(1)})]),pu=z.strictObject({path:z.string().min(1),matcher:Zp.optional(),limit:z.number().int().positive().optional(),depth:z.number().int().nonnegative().optional(),result:z.string()}),Qi=class extends I{constructor(){super(pu);}};var cu=z.strictObject({files:z.array(z.strictObject({path:z.string(),replacements:z.array(z.strictObject({pattern:z.string().refine(a=>{try{return new RegExp(a),!0}catch{return {message:"Invalid regular expression pattern"}}}),caseSensitive:z.boolean().optional(),value:z.union([z.string(),z.number()])})).min(1)})).min(1)}),Xi=class extends I{constructor(){super(cu);}};var lu=z.strictObject({slots:z.array(z.string().min(1)).min(1),example:z.boolean().optional()}),eo=class extends I{constructor(){super(lu);}};var uu=z.strictObject({components:z.array(z.string().min(1)).min(1)}),to=class extends I{constructor(){super(uu);}};var mu=z.strictObject({name:z.string().min(1),criteria:z.string().min(1)}),mt=z.strictObject({title:z.string().optional(),description:z.string().optional()}),du=mt.extend({type:z.literal("boolean"),label:z.strictObject({true:z.string(),false:z.string()}).optional(),default:z.boolean().optional()}),gu=z.strictObject({label:z.string().optional(),description:z.string().optional(),default:z.boolean().optional(),position:z.number().optional()}),fu=mt.extend({type:z.literal("text"),minimumLength:z.number().optional(),maximumLength:z.number().optional(),format:z.string().optional(),pattern:z.string().optional(),choices:z.record(gu).optional()}),yu=mt.extend({type:z.literal("number"),integer:z.boolean().optional(),minimum:z.number().optional(),maximum:z.number().optional()}),hu=z.lazy(()=>z.strictObject({type:z.lazy(()=>tc),label:z.string().optional(),description:z.string().optional(),optional:z.boolean().optional(),private:z.boolean().optional(),position:z.number().optional()})),Ba=mt.extend({type:z.literal("structure"),attributes:z.record(z.string(),hu)}),Su=mt.extend({type:z.literal("list"),items:z.lazy(()=>tc),itemLabel:z.string().optional(),minimumLength:z.number().optional(),maximumLength:z.number().optional()}),bu=z.union([z.string(),z.number(),z.boolean(),z.null()]),Ja=z.lazy(()=>z.union([bu,z.array(Ja),z.record(Ja)])),Yp=mt.extend({type:z.literal("reference"),id:z.string(),properties:z.record(z.string(),Ja).optional()}),ec=mt.extend({type:z.literal("union"),types:z.record(z.string(),z.discriminatedUnion("type",[Ba,Yp]))}),tc=z.discriminatedUnion("type",[du,fu,yu,Ba,Su,ec,Yp]),Iu=z.discriminatedUnion("type",[Ba,ec]),vu=z.strictObject({name:z.string().min(1),description:z.string().min(1).optional(),schema:Iu}),xu=z.union([z.strictObject({type:z.literal("static"),value:z.string()}),z.strictObject({type:z.literal("dynamic"),expression:z.string(),nullable:z.literal(false),default:z.string()}),z.strictObject({type:z.literal("dynamic"),expression:z.string(),nullable:z.literal(true),default:z.string().optional()})]),wu=z.union([z.strictObject({type:z.literal("static"),value:z.number()}),z.strictObject({type:z.literal("dynamic"),nullable:z.literal(false),default:z.number(),expression:z.string()}),z.strictObject({type:z.literal("dynamic"),nullable:z.literal(true),default:z.number().optional(),expression:z.string()})]),Pu=z.union([z.strictObject({type:z.literal("static"),value:z.boolean()}),z.strictObject({type:z.literal("dynamic"),nullable:z.literal(false),default:z.boolean(),expression:z.string()}),z.strictObject({type:z.literal("dynamic"),nullable:z.literal(true),default:z.boolean().optional(),expression:z.string()})]),nc=z.strictObject({type:z.literal("text"),value:xu}),ic=z.strictObject({type:z.literal("number"),value:wu}),oc=z.strictObject({type:z.literal("boolean"),value:Pu}),Za=z.strictObject({type:z.literal("structure"),name:z.string().optional(),attributes:z.record(z.string(),z.lazy(()=>ku))}),Cu=z.lazy(()=>z.discriminatedUnion("type",[nc.extend({label:z.string().optional()}),ic.extend({label:z.string().optional()}),oc.extend({label:z.string().optional()}),Za.extend({label:z.string().optional()}),rc.extend({label:z.string().optional()})])),rc=z.strictObject({type:z.literal("list"),items:z.array(Cu)}),ku=z.discriminatedUnion("type",[nc,ic,oc,Za,rc]),ac=z.record(z.string(),Za),Au=z.strictObject({name:z.string().min(1),component:z.string().min(1),content:ac}),sc=z.record(z.string(),ac),Eu=z.strictObject({audiences:z.array(z.string()),content:sc}),pc=z.strictObject({default:sc.optional(),segmented:z.array(Eu).optional()}),Ru=z.strictObject({name:z.string(),content:pc,baseline:z.boolean().optional(),allocation:z.number().min(0)}),Ou=z.strictObject({name:z.string(),draft:z.boolean().optional(),audiences:z.array(z.string()),slots:z.array(z.string()),experiment:z.strictObject({name:z.string(),goalId:z.string().optional(),crossDevice:z.boolean().optional(),traffic:z.number().min(0).max(1),variants:z.array(Ru)}).optional(),content:pc}),Du=z.record(z.string().min(1),z.string().min(1)),Qp=z.record(z.union([z.string().min(1).regex(/^\d+$/),z.number().nonnegative()]),z.string().min(1)),Xp=z.record(z.string().min(1),z.strictObject({id:z.string().min(1).optional(),version:z.string().min(1).optional()})),Tu=z.strictObject({resources:z.strictObject({audiences:z.record(z.string().min(1),mu).optional(),components:z.record(z.string().min(1),vu).optional(),slots:z.record(z.string().min(1),Au).optional(),experiences:z.array(Ou).optional()}),result:z.strictObject({audiences:Du.optional(),components:Xp.optional(),slots:Xp.optional(),experiences:Qp.optional(),experiments:Qp.optional()}).optional()}),no=class extends I{constructor(){super(Tu);}};var Mu=z.union([z.string(),z.number(),z.boolean(),z.null()]),Qa=z.lazy(()=>z.union([Mu,z.array(Qa),z.record(Qa)])),Nu=z.strictObject({template:z.string().min(1),options:z.record(z.string().min(1),Qa).optional()}),io=class extends I{constructor(){super(Nu);}};var oo=class{constructor({formatter:e}){this.formatter=e;}async execute(e,t){let{output:n}=t,i=n.notify("Formatting code");try{await this.formatter.format(e.files);}catch(o){throw h.fromCause(o)}finally{i.stop();}}};var zu=z.strictObject({files:z.array(z.string().min(1)).min(1)}),ro=class extends I{constructor(){super(zu);}};var Ot=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 L(`No value found for discriminator "${String(e)}".`,{reason:"not_supported"});return t instanceof Function?t():t.get()}};var ao=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 $u=z.strictObject({condition:z.boolean(),then:z.instanceof(Promise),else:z.instanceof(Promise).optional()}),po=class extends I{constructor(){super($u);}};var co=class{execute(e,t){let n=t.output,i=e.semantics??"neutral";return e.title===void 0?n.log(e.message,i):n.announce({alignment:"left",semantics:i,title:e.title,message:e.message}),Promise.resolve()}};var Fu=z.strictObject({semantics:z.enum(["neutral","info","error","warning","success"]).optional(),title:z.string().optional(),message:z.string()}),uo=class extends I{constructor(){super(Fu);}};var mo=class{execute(e){let{message:t,...n}=e;throw new h(t,{...n,reason:"precondition"})}};var ju=z.strictObject({title:z.string().min(1).optional(),message:z.string().min(1),links:z.array(z.strictObject({label:z.string().min(1),url:z.string().url()})).optional(),suggestions:z.array(z.string().min(1)).optional(),details:z.array(z.string().min(1)).optional()}),go=class extends I{constructor(){super(ju);}};var fo=class{constructor({url:e,provider:t}){this.url=e,this.provider=t;}get(){return this.provider.get(this.url)}};var Dt=class{constructor(e){this.data=e;}get(){return Promise.resolve(this.data)}};var yo=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 i of this.parsers){let o=i.parse(n);if(o!==null)return this.factory.create({...o,command:await this.packageManager.getScriptCommand(t)})}throw new L("No server found.")}};var ho=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+)/),i=t!==null?Number.parseInt(t[1],10):null,o=n!==null?n[1]:"localhost";return {protocol:e.includes("-https")?"https":"http",host:o,...i!==null?{port:i}:{},defaultPort:3e3}}};var So=class{parse(e){if(!e.includes("vite"))return null;let t=e.match(/--port\s*(\d+)/),n=e.match(/--host\s*(\S+)/),i=t!==null?Number.parseInt(t[1],10):null;return {protocol:"http",host:n!==null?n[1]:"localhost",...i!==null?{port:i}:{},defaultPort:5173}}};var bo=class{parse(e){if(!e.includes("parcel"))return null;let t=e.match(/(?:-p|--port)\s*(\d+)/),n=e.match(/--host\s*(\S+)/),i=t!==null?Number.parseInt(t[1],10):null,o=n!==null?n[1]:"localhost";return {protocol:e.includes("--https")?"https":"http",host:o,...i!==null?{port:i}:{},defaultPort:1234}}};var Io=class{parse(e){if(!e.includes("react-scripts start"))return null;let t=e.match(/PORT=(\d+)/),n=e.match(/HOST=(\S+)/),i=e.match(/HTTPS=(\S+)/),o=t!==null?Number.parseInt(t[1],10):null,r=n!==null?n[1]:"localhost";return {protocol:i!==null&&i[1]==="true"?"https":"http",host:r,...o!==null?{port:o}:{},defaultPort:5173}}};var vo=class{async execute(e,t){let{input:n}=t,i=n===void 0?this.getDefaultValue(e):await this.prompt(e,n);if(i===void 0)throw new h("Action requires user input.",{reason:"precondition",suggestions:["Retry in interactive mode"]});e.result!==void 0&&t.set(e.result,i);}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,...i}=e;return t.prompt({...i,validate:o=>n&&o===""?"This value is required.":true})}case "keypress":return t.wait(e)}}};var _u=z.strictObject({type:z.literal("confirmation"),message:z.string(),default:z.boolean().optional(),result:z.string()}),Ya=z.string(),Lu=z.preprocess(a=>typeof a=="string"?{value:a,label:a}:a,z.strictObject({value:Ya,label:z.string().min(1).optional(),disabled:z.boolean().optional()})).transform(a=>({...a,label:a.label??a.value.toString()})),Uu=z.strictObject({type:z.literal("choice"),message:z.string(),options:z.array(Lu),default:Ya.optional(),result:z.string()}),Vu=z.preprocess(a=>typeof a=="string"?{value:a,label:a}:a,z.strictObject({value:Ya,label:z.string().min(1).optional(),selected:z.boolean().optional(),disabled:z.boolean().optional()})).transform(a=>({...a,label:a.label??a.value.toString()})),Wu=z.strictObject({type:z.literal("multi-choice"),message:z.string(),min:z.number().optional(),max:z.number().optional(),options:z.array(Vu),result:z.string()}),qu=z.strictObject({type:z.literal("text"),message:z.string(),default:z.string().optional(),required:z.boolean().optional(),result:z.string()}),Ku=z.strictObject({type:z.literal("keypress"),message:z.string(),key:z.union([z.literal("enter"),z.literal("space"),z.string().length(1)]).optional(),result:z.string().optional()}),Hu=z.discriminatedUnion("type",[_u,Uu,Wu,qu,Ku]),xo=class extends I{constructor(){super(Hu);}};var wo=class{constructor({serverFactory:e,serverProvider:t,packageManager:n,serverMap:i}){this.factory=e,this.provider=t,this.packageManager=n,this.serverMap=i;}async execute(e,t){let{output:n}=t,i=n.notify("Checking server"),o;try{o=await this.startServer(i,e.server);}finally{i.stop();}e.result?.url!==void 0&&t.set(e.result.url,o.url.toString()),e.result?.id!==void 0&&t.set(e.result.id,o.id??null);}async startServer(e,t){let n=await this.getServer(t),i=await n.getStatus();if(i.running)return {url:i.url,owned:false};e.update("Starting server");let o=randomUUID();return this.serverMap.set(o,n),{id:o,url:await n.start({logger:new ae({status:"Starting server",notifier:e})}),owned:true}}async getServer(e){if(e===void 0){let o=await this.provider.get();if(o===null)throw new d("No server detected.");return o}let t=new URL(e.url),n=t.protocol==="https:",i=n?443:80;return this.factory.create({host:t.hostname,protocol:n?"https":"http",defaultPort:t.port===""?i:Number.parseInt(t.port,10),command:await this.packageManager.getScriptCommand(e.script,e.arguments)})}};var Ju=z.strictObject({server:z.strictObject({script:z.string(),arguments:z.array(z.string()).optional(),url:z.string()}).optional(),result:z.strictObject({id:z.string().optional(),url:z.string().optional()}).optional()}),Po=class extends I{constructor(){super(Ju);}};var Co=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(i){if(i instanceof ce&&i.help.cause instanceof JsonParseError){let{location:o}=i.help.cause;throw h.fromCause(i,{tracing:[{name:n.name,source:{url:i.url,start:o.start,end:o.end}}]})}throw h.fromCause(i,{tracing:[{name:n.name,source:un.get(n)??void 0}]})}}run({name:e,...t},n){let i=this.actions[e];if(i===void 0)throw new h(`Unsupported action \`${e}\`.`,{reason:"invalid_input"});return i.execute(t,n)}};var cc=z.object({name:z.string().min(1)}).passthrough(),Zu=z.strictObject({actions:z.union([cc,z.array(cc)])}),ko=class extends I{constructor(){super(Zu);}};var Ao=class{async execute(e,t){let{output:n}=t;await n.open(e.url);}};var Qu=z.strictObject({url:z.string().url()}),Eo=class extends I{constructor(){super(Qu);}};var Xu=z.union([z.string(),z.number(),z.boolean(),z.null()]),es=z.lazy(()=>z.union([Xu,z.array(es),z.record(es)])),Yu=z.strictObject({variables:z.record(z.string(),es)}),Ro=class extends I{constructor(){super(Yu);}};var Oo=class{execute(e,t){for(let[n,i]of Object.entries(e.variables))t.set(n,i);return Promise.resolve()}};var em=z.strictObject({id:z.string()}),Do=class extends I{constructor(){super(em);}};var Tt=class a extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,a.prototype);}};var le=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 i=this.lines[this.cursor.row];for(let o=this.cursor.column;o<i.length;o++)i[o]=" ";this.cursor.column=0;continue}if(n===`
|
|
1774
|
+
`){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,i]=t,o=n?.split(";").map(r=>r===""?0:Number.parseInt(r,10))??[];switch(i){case "A":{let r=o[0]??1;this.cursor.row=Math.max(0,this.cursor.row-r);break}case "B":{let r=o[0]??1;this.cursor.row+=r,this.resize(this.cursor.row);break}case "C":{let r=o[0]??1;this.cursor.column+=r;break}case "D":{let r=o[0]??1;this.cursor.column=Math.max(0,this.cursor.column-r);break}case "E":{let r=o[0]??1;this.cursor.row+=r,this.resize(this.cursor.row),this.cursor.column=0;break}case "F":{let r=o[0]??1;this.cursor.row=Math.max(0,this.cursor.row-r),this.cursor.column=0;break}case "G":{let r=(o[0]??1)-1;this.cursor.column=Math.max(0,r);break}case "H":case "f":{let r=(o[0]??1)-1,s=(o[1]??1)-1;this.cursor.row=Math.max(0,r),this.resize(this.cursor.row),this.cursor.column=Math.max(0,s);break}case "K":{let r=o[0]??0,s=this.lines[this.cursor.row];switch(r){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(o[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(`
|
|
1775
|
+
`)}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 i=0;i<n.length;i++)if(n[i]!==this.snapshot[t][i]){e.push(n.join(""));break}}return e.join(`
|
|
1776
|
+
`)}static getRawString(e){return _c(e)}};var To=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:i,processObserver:o}=this.configuration;try{this.execution=await t.run(n,{workingDirectory:i.get()});}catch(g){throw new Tt("Failed to start server.",{cause:g})}let r=new AbortController,s=()=>(r.abort(),this.stop());if(this.execution.onExit(()=>{this.execution=void 0,o.off("exit",s);}),!this.execution.running)throw new Tt("Failed to start server.");o.on("exit",s);let{output:p}=this.execution,c=new le,l=(async()=>{for await(let g of p){if(r.signal.aborted)return;c.write(g),e?.log({level:LogLevel.DEBUG,message:g});}})(),u=await this.waitStart(r);if(r.abort(),await l,u===null){e?.log({level:LogLevel.ERROR,message:"Unable to reach the server after it was started."});let g=le.getRawString(c.getSnapshot()).trim();throw new Tt(`Server is unreachable${g===""?".":`:
|
|
1777
1777
|
|
|
1778
|
-
${g}`}`)}return u}async stop(){await this.execution?.kill("SIGINT"),this.execution=void 0;}async waitStart(e){let{startupCheckDelay:t,startupTimeout:n}=this.configuration,
|
|
1779
|
-
`,"[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:
|
|
1778
|
+
${g}`}`)}return u}async stop(){await this.execution?.kill("SIGINT"),this.execution=void 0;}async waitStart(e){let{startupCheckDelay:t,startupTimeout:n}=this.configuration,i=setTimeout(()=>e.abort(),n);i.unref(),e.signal.addEventListener("abort",()=>{clearTimeout(i);});let o=()=>new Promise(r=>{let s=()=>{r(),e.signal.removeEventListener("abort",s);};setTimeout(r,t),e.signal.addEventListener("abort",s);});do{let r=await this.findAddress(e);if(r!==null)return r;await o();}while(!e.signal.aborted);return null}async findAddress(e){let{lookupTimeout:t,lookupMaxPorts:n,server:{protocol:i,host:o,port:r,defaultPort:s}}=this.configuration,p=r??s,c=r??s+n-1,l=new AbortController;e!==void 0&&e.signal.addEventListener("abort",()=>l.abort()),setTimeout(()=>l.abort(),t).unref();let g=new URL(`${i}://${o}`);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 Mo=class{constructor(e){this.configuration=e;}create(e){return Promise.resolve(new To({...this.configuration,command:e.command,server:{protocol:e.protocol,host:e.host,defaultPort:e.defaultPort,port:e.port}}))}};var nm=z.strictObject({path:z.string()}),No=class extends I{constructor(){super(nm);}};var zo=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 $o=class a{static{this.INPUT_MAP={"[space]":" ","[enter]":`
|
|
1779
|
+
`,"[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:i}=t,{sourceChecker:o}=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 r=await this.resolveCommand(e),s=a.formatCommand(r);if(e.script!==true&&!await o.test(t.baseUrl)){if(n===void 0)throw new h("Action requires explicit user confirmation.",{reason:"precondition",details:["Retry in interactive mode."]});if(i.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=i.notify(`Running \`${s}\``),c;try{c=await this.executeCommand(r,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:i,workingDirectory:o,commandExecutor:r,commandTimeout:s}=this.configuration,p=await r.run(e,{workingDirectory:o.get(),timeout:s,inheritIo:n===true}),c=()=>{p.kill();};i.on("exit",c),p.onExit(()=>i.off("exit",c));let l=a.formatCommand(e);n===true&&t.stop(true);let u=new le,g=new ae({status:`Running \`${l}\``,notifier:t});if(n!==true){let A=Array.isArray(n)?[...n]:[];A.length===0&&await p.endWriting();for await(let M of p.output){u.write(M),g.log({level:LogLevel.DEBUG,message:le.getRawString(M)});let _=u.getSnapshotDiff();for(let[S,P]of A.entries())if(P.pattern===true?new RegExp(P.when).test(_):_.includes(P.when)){u.saveSnapshot(),P.always!==true&&A.splice(S,1);for(let ue of P.then??[])await p.write(a.INPUT_MAP[ue]??ue);P.final===true&&(await p.endWriting(),A.length=0);break}}}let y=-1;try{y=await p.wait();}catch(A){throw new h("Command execution failed.",{reason:"unexpected_result",cause:A})}let v=le.getRawString(u.getSnapshot()).trim();if(y!==0)throw new h(`Command execution failed${v===""?".":`:
|
|
1780
1780
|
|
|
1781
|
-
${v}`}`,{reason:"unexpected_result"});return v}static formatCommand(e){return [e.name.split(/[\\/]/).pop(),...(e.arguments??[]).map(t=>!t.startsWith("-")&&t.includes(" ")?JSON.stringify(t):t)].join(" ")}};var
|
|
1781
|
+
${v}`}`,{reason:"unexpected_result"});return v}static formatCommand(e){return [e.name.split(/[\\/]/).pop(),...(e.arguments??[]).map(t=>!t.startsWith("-")&&t.includes(" ")?JSON.stringify(t):t)].join(" ")}};var om=z.array(z.object({when:z.string(),pattern:z.boolean().optional(),always:z.boolean().optional(),then:z.array(z.string()).min(1).optional(),final:z.boolean().optional()}).superRefine((a,e)=>{if(a.then===void 0&&a.final===void 0&&e.addIssue({code:z.ZodIssueCode.custom,message:"Either `then` or `final` must be defined"}),a.final===true&&a.always===true&&e.addIssue({code:z.ZodIssueCode.custom,path:["always"],message:"Final interactions must have `always` set to `false`"}),a.pattern===true)try{new RegExp(a.when);}catch{e.addIssue({code:z.ZodIssueCode.custom,path:["pattern"],message:"The `when` field must be a valid regular expression"});}})).min(1).optional().refine(a=>a===void 0||a.some(e=>e.final===true),{message:"At least one interaction must have `final` set to `true`"}),rm=z.strictObject({command:z.string(),script:z.boolean().optional(),arguments:z.array(z.string()).optional(),runner:z.string().optional(),interactions:z.union([z.boolean(),om]),output:z.string().optional()}),Fo=class extends I{constructor(){super(rm);}};var fe=class a extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,a.prototype);}};var Xe=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&&am.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 fe("Package file not found in the project.",{reason:"precondition",details:[`File: ${n}`]});let i=await this.fileSystem.readTextFile(n),o=JsonParser.parse(i,JsonObjectNode);if(o.has("scripts")){let r=o.get("scripts",JsonObjectNode),s=t;if(r.has(e)){let c=r.get(e).toJSON();if(typeof c=="string"&&c.includes(t))return;s=`${c} && ${t}`;}r.set(e,s);}else o.set("scripts",{[e]:t});await this.fileSystem.writeTextFile(n,o.toString(),{overwrite:true});}async findPackageManifestPath(e,t){let n=t??this.projectDirectory.get(),i=this.fileSystem.joinPaths(n,"node_modules",e,"package.json"),o=this.manifestPath.get(i);if(o!==void 0)return o;let r=i;if(!await this.fileSystem.exists(i)){let s=this.fileSystem.getDirectoryName(n);r=s!==n?await this.findPackageManifestPath(e,s):null;}return this.manifestPath.set(i,r),r}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 Fe=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 fe(`Package manager \`${this.getCommandName()}\` is not installed.`);let i=await this.commandRunner.run(e,{...n,workingDirectory:this.projectDirectory.get()}),o=new le;for await(let r of i.output)o.write(r),t?.log({level:LogLevel.DEBUG,message:le.getRawString(r).trim(),details:{output:le.getRawString(o.getSnapshot()).trim()}});if(await i.wait()!==0){let r=le.getRawString(o.getSnapshot()).trim();throw t?.log({level:LogLevel.ERROR,message:`Failed to run \`${e.name}\` command.`,details:{command:e.name,arguments:e.arguments??[],output:r}}),new fe(`Failed to run \`${e.name}\` command${r===""?".":`:
|
|
1782
1782
|
|
|
1783
|
-
${
|
|
1784
|
-
${s}`),{exitCode:
|
|
1783
|
+
${r}`}`)}}getExecutable(e){return this.executableLocator.locate(e)}};var jo=class extends Fe{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 _o=class extends Fe{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 Lo=class extends Fe{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 Uo=class extends Fe{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 Vo=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(),i=this.fileSystem.isAbsolutePath(t)?t:this.fileSystem.joinPaths(n,t),o=this.fileSystem.isAbsolutePath(e)?e:this.fileSystem.joinPaths(n,e),r=await this.tsConfigLoader.load(n,{sourcePaths:[i]}),s=/\.m(?:js|ts)?$/.test(o)?o:o.replace(/\.(ts|js)x?$/,"");if(r!==null&&this.fileSystem.isSubPath(n,s)){let c=this.fileSystem.getRelativePath(n,s),l=0,u=null;for(let[g,y]of Object.entries(r.paths)){let v=this.fileSystem.normalizeSeparators(g.replace(/\*$/,""));for(let A of y){let M=A.replace(/\*$/,""),_=this.fileSystem.getRelativePath(n,this.fileSystem.joinPaths(r.baseUrl,M));if(c.startsWith(_)){let S=M.length;if(S>l){l=S;let P=c.slice(_.length).replace(/^[\\/]+/,"");u=v+P;}}}}if(u!==null)return Promise.resolve(u.replace(/\\+/g,"/"))}let p=this.fileSystem.getRelativePath(this.fileSystem.joinPaths(i,".."),s).replace(/\\/g,"/");return Promise.resolve(/^\.\.?\/ ?/.test(p)?p:`./${p}`)}};var pm=z.object({extends:z.string().optional(),references:z.array(z.object({path:z.string()})).optional(),include:z.array(z.string()).optional(),compilerOptions:z.object({baseUrl:z.string().optional(),paths:z.record(z.array(z.string())).optional()}).optional()}),Wo=class extends G{constructor(){super(pm);}};var fn=class{constructor(e){this.provider=e;}get manager(){return Promise.resolve(this.provider.get()).catch(e=>{throw e instanceof L?new fe(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 qo=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 L(`No value found for key \`${e}\`.`,{reason:"not_found"});return Promise.resolve(t)}};var Ko=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 fe("The package manager is not installed")}};var Mt=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 Ae=class{constructor(e){this.callback=e;}get(...e){return this.callback(...e)}};var dt=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 yn=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 hn=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 Ho=class{constructor({packageManager:e}){this.packageManager=e;}test(){return this.packageManager.isProject()}};var Ee=class a extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,a.prototype);}};var Go=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 Jo=class a{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,i=this.prepareCommand(e),o=spawn(i.name,i.arguments??[],{stdio:t.inheritIo===true?"inherit":"pipe",shell:i.shell,cwd:t?.workingDirectory??this.currentDirectory?.get(),signal:n}),r=new Go,s=[],p=null;o.on("error",u=>{r.close(),p=n?.aborted===true?new Ee("Command timed out.",{reason:"precondition",cause:u}):new Ee(`Failed to run command: ${d.formatCause(u)}`,{cause:u});for(let g of s)g(p);});let c=u=>{r.push(u.toString());};o.stdout?.on("data",c),o.stderr?.on("data",c);let l=[];return o.on("exit",u=>{r.close();for(let g of l)g(u??1);}),Promise.resolve({output:r,get running(){return o.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(o.stdin===null){y(new Ee("Subprocess is not writable."));return}o.stdin.write(u,v=>{v===null?g():y(v);});}),endWriting:()=>new Promise(u=>{if(o.stdin===null||o.exitCode!==null){u();return}o.stdin.end(u);}),read:async()=>{let u="";for await(let g of r)u+=g;return u},wait:()=>new Promise((u,g)=>{if(p!==null){g(p);return}if(o.exitCode!==null){u(o.exitCode);return}s.push(g),o.on("exit",y=>{u(y??1);});}),kill:u=>new Promise((g,y)=>{if(o.exitCode!==null){g();return}o.stdout?.destroy(),o.stderr?.destroy(),o.stdin?.destroy(),o.kill(u)?g():y(new Ee("Failed to kill the subprocess."));})})}runSync(e,t={}){let n=t.timeout!==void 0?AbortSignal.timeout(t.timeout):void 0,i=this.prepareCommand(e),o=spawnSync(i.name,i.arguments,{stdio:[t.inheritIo===true?"inherit":"ignore","pipe","pipe"],cwd:t?.workingDirectory??this.currentDirectory?.get(),shell:i.shell,signal:n});if(o.error!==void 0){let{error:p}=o;throw n?.aborted===true?new Ee("Command timed out.",{reason:"precondition",cause:p}):new Ee(`Failed to run command: ${d.formatCause(p)}`,{cause:p})}let r=o.stdout.toString(),s=o.stderr.toString();return r!==""&&s!==""&&(r=`${r}
|
|
1784
|
+
${s}`),{exitCode:o.status??1,output:r}}prepareCommand(e){return this.isWindowShell(e.name)?{name:a.escapeCommand(e.name),arguments:(e.arguments??[]).map(a.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 Bo=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 L?new fe(e.message,e.help):e})}};var Zo=class{constructor(e){this.provider=e;}get sdk(){return Promise.resolve(this.provider.get()).catch(e=>{throw e instanceof L?new X(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 Sn=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 Qo=class{constructor(e){this.predicate=e;}async test(...e){return !await this.predicate.test(...e)}};var Xo=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 i=um();i.add(await this.fileSystem.readTextFile(t)),n={test:o=>{if(!this.fileSystem.isSubPath(e,o))return Promise.resolve(false);let r=this.fileSystem.getRelativePath(e,o);return r===""?Promise.resolve(false):Promise.resolve(i.ignores(r))}};}return this.cache.set(t,n),n}};var Yo=class{constructor(e){this.predicate=e;}get(...e){return this.predicate.test(...e)}};var bn=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 In=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 ts={};Ec(ts,{basename:()=>gm,dirname:()=>fm,ext:()=>dm,uuid:()=>ym});var dm=a=>{if(typeof a!="string")throw new N(`The \`path\` argument of the \`ext\` function must be a string, but got ${d.describeType(a)}.`);return a.split(".").pop()??""},gm=(a,e=false)=>{if(typeof a!="string")throw new N(`The \`path\` argument of the \`basename\` function must be a string, but got ${d.describeType(a)}.`);if(typeof e!="boolean")throw new N(`The \`omitExtension\` argument of the \`basename\` function must be a boolean, but got ${d.describeType(e)}.`);let t=a.split(/[\\/]/).pop()??"";return e?t.replace(/\.[^/.]+$/,""):t},fm=a=>{if(typeof a!="string")throw new N(`The \`path\` argument of the \`dirname\` function must be a string, but got ${d.describeType(a)}.`);return a.replace(/[\\/][^\\/]*$/,"")},ym=()=>randomUUID();var er=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 hm=z.strictObject({condition:z.instanceof(Promise),actions:z.instanceof(Promise)}),tr=class extends I{constructor(){super(hm);}};var U=class a extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,a.prototype);}};var nr=class a{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 U("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 U(`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(i){throw new U("Failed to unregister protocol handler.",{cause:i})}}async install(e){let t=this.getLauncherAppPath(e.protocol),n=this.getHandlerAppPath(e.protocol),i=this.createLauncherApp(e,n),o=this.createHandlerApp(e),r=await this.fileSystem.createTemporaryDirectory("protocol"),s=this.fileSystem.joinPaths(r,"launcher.scpt"),p=this.fileSystem.joinPaths(r,"handler.scpt");await this.fileSystem.writeTextFile(s,i),await this.fileSystem.writeTextFile(p,o),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:a.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",Y`
|
|
1785
1785
|
use AppleScript version "2.4"
|
|
1786
1786
|
use framework "Foundation"
|
|
1787
1787
|
use framework "AppKit"
|
|
@@ -1807,7 +1807,7 @@ ${s}`),{exitCode:i.status??1,output:o}}prepareCommand(e){return this.isWindowShe
|
|
|
1807
1807
|
do script "${n}"
|
|
1808
1808
|
activate
|
|
1809
1809
|
end tell
|
|
1810
|
-
`}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
|
|
1810
|
+
`}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 ir=class a{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 U("Failed to register protocol handler",{cause:t})}}async install(e){let t=a.getRegistryPath(e.protocol),n=a.getCommandRegistryPath(e.protocol),i=a.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",i,"/f"]});}async unregister(e){let t=await this.findCommand(e);if(t!==null){if(!t.startsWith(a.getCommand("")))throw new U(`Application registered for protocol \`${e}\` is externally managed.`,{reason:"precondition"});try{await this.execute({name:"REG",arguments:["DELETE",`${a.getRegistryPath(e)}`,"/f"]});}catch(n){throw new U("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",`${a.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 a.getRegistryPath(e,"shell\\open\\command")}static getRegistryPath(e,t){return `HKCU\\Software\\Classes\\${e}${t!==void 0?`\\${t}`:""}`}};var or=class a{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),a.createDesktopEntry(e)),await this.updateDesktopDatabase();}catch(t){throw new U("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),i=this.getDesktopEntryPath(e);if(t!==i||n?.startsWith(a.COMMAND)!==true)throw new U(`Application registered for protocol \`${e}\` is externally managed.`,{reason:"precondition"});try{await this.fileSystem.delete(t),await this.updateDesktopDatabase();}catch(o){throw new U("Failed to unregister protocol handler.",{cause:o})}}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 Y`
|
|
1811
1811
|
[Desktop Entry]
|
|
1812
1812
|
Type=Application
|
|
1813
1813
|
Name=${e.name}
|
|
@@ -1815,33 +1815,33 @@ ${s}`),{exitCode:i.status??1,output:o}}prepareCommand(e){return this.isWindowShe
|
|
|
1815
1815
|
StartupNotify=false
|
|
1816
1816
|
Terminal=true
|
|
1817
1817
|
MimeType=x-scheme-handler/${e.protocol}
|
|
1818
|
-
`}getDesktopEntryPath(e){return this.fileSystem.joinPaths(this.getApplicationPath(),`${e}.desktop`)}getApplicationPath(){return this.fileSystem.joinPaths(this.homeDirectory,".local","share","applications")}};var io=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 o=i.join(" ");r.inform(`The command is \`${o}\``),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,o=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:`${o} (current)`,value:""},{label:c,value:c},...s.map(l=>({value:l,label:l}))]});}else i.inform(`You are currently in \`${o}\``),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:o,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 hm=z.strictObject({version:z.string().optional(),projectPaths:z.array(z.string().min(1)),isDeepLinkingEnabled:z.boolean().optional(),lastUpdateCheck:z.number().optional()}),oo=class extends G{constructor(){super(hm);}};var ao=class{constructor({manager:e,workingDirectory:t,configurationProvider:n}){this.manager=e,this.workingDirectory=t,this.configurationProvider=n;}isInitialized(e){return this.manager.isInitialized(e)}async load(){let e=await this.manager.load();return await this.updateIndex(),e}async loadPartial(){let e=this.manager.loadPartial();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 so=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 po=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 vn=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 co=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 lo=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 uo=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:o}=r[0];await e.confirm({message:`${o.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:o}of r)await e.confirm({message:`Accept invitation to join ${o.name}?`,default:true})&&await n.acceptInvitation(i);}}};var mo=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 go=class a{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 a.EMPTY_SETTINGS;let t;try{t=JSON.parse(e);}catch{return a.EMPTY_SETTINGS}let n=await this.validator.validate(t);return n.valid?n.data:a.EMPTY_SETTINGS}async save(e){await this.cache.set(this.cacheKey,JSON.stringify(e));}};var fo=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 yo=class{constructor(e){this.config=e;}async execute(e){let{configurationManager:t,api:n,fileSystem:r,io:i}=this.config,o=await t.load(),s=i.output.notify("Loading information"),p=await this.getEnvironment(o,e.environment),c=this.getApplicationSlug(o,p),l=e.name??`${(await n.user.getUser()).username} (CLI)`,u=await n.workspace.getFeatures({organizationSlug:o.organization,workspaceSlug:o.workspace});if(s.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 De.prompt({input:i.input,label:"API key name",default:l}),y=e.permissions??await i.input.selectMultiple({message:"Select permissions",min:1,options:se.all().map(M=>({label:se.getLabel(M),value:M,disabled:M==="DATA_EXPORT"&&u?.features.dataExport!==true}))}),v=await n.application.createApiKey({organizationSlug:o.organization,workspaceSlug:o.workspace,applicationSlug:c,name:g,permissions:y});if(e.copy===true||await i.input.confirm({message:"Copy to clipboard?",default:false})){await bm.write(v.secret),i.output.confirm("API key copied to clipboard");return}let A=`api-key-${v.id}.txt`;await r.writeTextFile(A,v.secret),i.output.confirm(`API key saved to \`${A}\``);}getApplicationSlug(e,t){let n=t==="PRODUCTION"?e.applications.production:e.applications.development;if(n===void 0)throw new d(`No ${ye.getLabel(t).toLowerCase()} application found in the project configuration.`,{reason:"invalid_input"});return n}getEnvironment(e,t){if(t!==void 0)return Promise.resolve(t);if(e.applications.production===void 0)return Promise.resolve("DEVELOPMENT");let{io:{input:n}}=this.config;return n.select({message:"Select environment",options:ye.all().map(r=>({label:ye.getLabel(r),value:r}))})}};var ho=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=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 So=class{constructor(e){this.currentDirectory=e;}get(){return this.currentDirectory}setCurrentDirectory(e){this.currentDirectory=e;}toString(){return this.get()}};var bo=class{constructor(e){this.process=e;}get(){return this.process.getCurrentDirectory()}setCurrentDirectory(e){this.process.changeDirectory(e);}toString(){return this.get()}};var Io=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 vo=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,o=this.clock.getInstant().getSeconds();if(!r.isValidNow(o-i)&&!r.isValidNow(o+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=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 wo=class a{constructor(e){this.boxenStyle=e??{titleAlignment:"center",borderStyle:"round",padding:{top:1,bottom:1,right:2,left:2}};}formatCallout(e){return dc(Q(e.message),{...this.boxenStyle,title:Q(e.title,{basic:true}),textAlignment:e.alignment??"left",borderColor:jt[e.semantics]})}formatError(e){return dc(a.formatErrorBody(e),{...this.boxenStyle,title:a.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=Q(d.formatMessage(e));if(e instanceof d){t+=a.formatErrorDetails(e);let{cause:n}=e.help;n!==void 0&&!a.isCauseReported(e.message,n)&&(t+=`
|
|
1818
|
+
`}getDesktopEntryPath(e){return this.fileSystem.joinPaths(this.getApplicationPath(),`${e}.desktop`)}getApplicationPath(){return this.fileSystem.joinPaths(this.homeDirectory,".local","share","applications")}};var rr=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:i}=this.config.io;if(n===void 0)throw new d("Deep links requires explicit user interaction.",{reason:"precondition",details:["Retry in interactive mode."]});let o=this.parseArguments(t);i.announce({semantics:"neutral",title:"\u{1F517} Croct link",message:"You just opened a link to a `Croct CLI` command.",alignment:"center"});let r=o.join(" ");i.inform(`The command is \`${r}\``),await n.confirm({message:"Continue?",default:true})&&(await this.selectDirectory(n),await this.config.program(o));}async selectDirectory(e){let{workingDirectory:t,configurationProvider:n,fileSystem:i,io:{output:o}}=this.config,r=t.get(),{projectPaths:s}=await n.get(),p="";if(s.length>0){let c=i.getDirectoryName(s[0]);p=await e.select({message:"Where should this command run?",options:[{label:`${r} (current)`,value:""},{label:c,value:c},...s.map(l=>({value:l,label:l}))]});}else o.inform(`You are currently in \`${r}\``),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:r,validate:async c=>await i.isDirectory(c)?true:"Enter a valid directory path."});p!==""&&t.setCurrentDirectory(p);}parseArguments(e){let t=[];for(let i of (e.hostname+e.pathname).split("/"))i!==""&&t.push(i);let n=[];for(let[i,o]of e.searchParams){if(i==="arg"){n.push(o);continue}if(o===""){t.push(`-${i.length===1?"":"-"}${i}`);continue}t.push(`--${i}`),t.push(o);}return t.push(...n),t}isValidUrl(e){return e.protocol===`${this.config.protocol}:`&&e.username===""&&e.password===""&&e.port===""&&e.hash===""}};var Sm=z.strictObject({version:z.string().optional(),projectPaths:z.array(z.string().min(1)),isDeepLinkingEnabled:z.boolean().optional(),lastUpdateCheck:z.number().optional()}),ar=class extends G{constructor(){super(Sm);}};var sr=class{constructor({manager:e,workingDirectory:t,configurationProvider:n}){this.manager=e,this.workingDirectory=t,this.configurationProvider=n;}isInitialized(e){return this.manager.isInitialized(e)}async load(){let e=await this.manager.load();return await this.updateIndex(),e}async loadPartial(){let e=this.manager.loadPartial();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 pr=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 i=this.fileSystem.joinPaths(t,e+n.toLowerCase());if(i!==null&&await this.fileSystem.exists(i))return i}return null}};var cr=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 vn=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 lr=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 ur=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 mr=class{constructor(e){this.config=e;}async handle(){let{input:e,output:t,userApi:n}=this.config,i=await n.getInvitations();if(i.length!==0){if(i.length===1){let{id:o,organization:r}=i[0];await e.confirm({message:`${r.name} has invited you to join. Accept?`,default:true})&&await n.acceptInvitation(o);return}i.length>1&&t.inform(`You have ${i.length} pending invitations:`);for(let{id:o,organization:r}of i)await e.confirm({message:`Accept invitation to join ${r.name}?`,default:true})&&await n.acceptInvitation(o);}}};var dr=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 gr=class a{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 a.EMPTY_SETTINGS;let t;try{t=JSON.parse(e);}catch{return a.EMPTY_SETTINGS}let n=await this.validator.validate(t);return n.valid?n.data:a.EMPTY_SETTINGS}async save(e){await this.cache.set(this.cacheKey,JSON.stringify(e));}};var fr=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 yr=class{constructor(e){this.config=e;}async execute(e){let{configurationManager:t,api:n,fileSystem:i,io:o}=this.config,r=await t.load(),s=o.output.notify("Loading information"),p=await this.getEnvironment(r,e.environment),c=this.getApplicationSlug(r,p),l=e.name??`${(await n.user.getUser()).username} (CLI)`,u=await n.workspace.getFeatures({organizationSlug:r.organization,workspaceSlug:r.workspace});if(s.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 Te.prompt({input:o.input,label:"API key name",default:l}),y=e.permissions??await o.input.selectMultiple({message:"Select permissions",min:1,options:se.all().map(M=>({label:se.getLabel(M),value:M,disabled:M==="DATA_EXPORT"&&u?.features.dataExport!==true}))}),v=await n.application.createApiKey({organizationSlug:r.organization,workspaceSlug:r.workspace,applicationSlug:c,name:g,permissions:y});if(e.copy===true||await o.input.confirm({message:"Copy to clipboard?",default:false})){await Im.write(v.secret),o.output.confirm("API key copied to clipboard");return}let A=`api-key-${v.id}.txt`;await i.writeTextFile(A,v.secret),o.output.confirm(`API key saved to \`${A}\``);}getApplicationSlug(e,t){let n=t==="PRODUCTION"?e.applications.production:e.applications.development;if(n===void 0)throw new d(`No ${ye.getLabel(t).toLowerCase()} application found in the project configuration.`,{reason:"invalid_input"});return n}getEnvironment(e,t){if(t!==void 0)return Promise.resolve(t);if(e.applications.production===void 0)return Promise.resolve("DEVELOPMENT");let{io:{input:n}}=this.config;return n.select({message:"Select environment",options:ye.all().map(i=>({label:ye.getLabel(i),value:i}))})}};var hr=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=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 Sr=class{constructor(e){this.currentDirectory=e;}get(){return this.currentDirectory}setCurrentDirectory(e){this.currentDirectory=e;}toString(){return this.get()}};var br=class{constructor(e){this.process=e;}get(){return this.process.getCurrentDirectory()}setCurrentDirectory(e){this.process.changeDirectory(e);}toString(){return this.get()}};var Ir=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,i]of this.inFlightCache.entries())if(deepEqual(e,n))return i;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 vr=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 i=this.parseToken(n);if(i!==null){let o=this.clockSkewTolerance,r=this.clock.getInstant().getSeconds();if(!i.isValidNow(r-o)&&!i.isValidNow(r+o))return null;this.revalidateToken(e,i).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 i=t.getIssueTime(),o=Instant.ofEpochSecond(i+this.tokenFreshPeriod);n.isAfter(o)&&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 xr=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 wr=class a{constructor(e){this.boxenStyle=e??{titleAlignment:"center",borderStyle:"round",padding:{top:1,bottom:1,right:2,left:2}};}formatCallout(e){return yc(Q(e.message),{...this.boxenStyle,title:Q(e.title,{basic:true}),textAlignment:e.alignment??"left",borderColor:Lt[e.semantics]})}formatError(e){return yc(a.formatErrorBody(e),{...this.boxenStyle,title:a.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=Q(d.formatMessage(e));if(e instanceof d){t+=a.formatErrorDetails(e);let{cause:n}=e.help;n!==void 0&&!a.isCauseReported(e.message,n)&&(t+=`
|
|
1819
1819
|
|
|
1820
1820
|
\u{1F6A8} ${et.bold("Cause")}
|
|
1821
1821
|
`,t+=`${Q(d.formatMessage(e.help.cause))}`),t+=a.formatErrorSuggestions(e),t+=a.formatErrorUsefulLinks(e);}return (!(e instanceof d)||e.reason==="other"&&e.help.cause instanceof Error)&&(t+=a.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+=`
|
|
1822
1822
|
|
|
1823
1823
|
\u{1F50D} ${et.bold("Details")}
|
|
1824
|
-
`,t+=n.map(
|
|
1824
|
+
`,t+=n.map(i=>` \u2022 ${Q(i)}`).join(`
|
|
1825
1825
|
`)),t}static formatStackTrace(e){if(!(e instanceof Error)||e.stack===void 0)return "";let t=e.stack.split(`
|
|
1826
|
-
`).map(n=>` \u203A ${n.trim().replace(/^at /,"")}`).slice(1);return `
|
|
1826
|
+
`).map((n=>` \u203A ${n.trim().replace(/^at /,"")}`)).slice(1);return `
|
|
1827
1827
|
|
|
1828
1828
|
\u{1F4C4} ${et.bold("Stack trace")}
|
|
1829
1829
|
${t.join(`
|
|
1830
1830
|
`)}`}static formatErrorSuggestions(e){let{suggestions:t}=e.help,n="";return t!==void 0&&t.length>0&&(n+=`
|
|
1831
1831
|
|
|
1832
1832
|
\u{1F4A1} ${et.bold("Suggestions")}
|
|
1833
|
-
`,n+=t.map(
|
|
1833
|
+
`,n+=t.map(i=>` \u2022 ${Q(i)}`).join(`
|
|
1834
1834
|
`)),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+=`
|
|
1835
1835
|
|
|
1836
1836
|
\u{1F517} ${et.bold("Useful links")}
|
|
1837
|
-
`,n+=t.map(({label:
|
|
1838
|
-
`)),n}};var Po=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 Co=class{constructor(){this.eventDispatcher=new Po;Re.on("SIGTERM",()=>this.exit()),Re.on("SIGINT",()=>this.exit()),Re.on("SIGHUP",()=>this.exit());}getCurrentDirectory(){return Re.cwd()}getEnvValue(e){return Re.env[e]??null}getEnvList(e){return this.getEnvValue(e)?.split(delimiter)??null}getPlatform(){return Re.platform}getStandardError(){return Re.stderr}getStandardInput(){return Re.stdin}getStandardOutput(){return Re.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(()=>{}),Re.exit(e)}changeDirectory(e){Re.chdir(e);}};var ko=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 Em=z.strictObject({}),Ao=class extends I{constructor(){super(Em);}};var Eo=class a{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 $("Unsupported NPM URL.",{reason:"not_supported",url:e});let{value:n}=await this.metadataProvider.get(t),r=a.getRepositoryUrl(n.repository);return r===null?{url:e,value:[]}:{url:r,value:[{pattern:".*",destination:r}]}}static getRepositoryUrl(e){for(let t of a.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 Ro=class a{constructor({provider:e,reader:t}){this.provider=e,this.reader=t;}static text(e){return new a({provider:e,reader:t=>t.text()})}static json(e){return new a({provider:e,reader:t=>t.json()})}static blob(e){return new a({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 $("Failed to read response body.",{reason:"unexpected_result",url:e,cause:r})}return {url:t.url,value:n}}};var Rm=z.object({name:z.string(),repository:z.object({type:z.string(),url:z.string()})}),Oo=class extends G{constructor(){super(Rm);}};var Do=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 Mo=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(o=>this.logger.log(o)),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 No=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 zo=class a{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(a.PREFIX))return;let n=t.source.slice(a.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 o of this.fileSystem.list(r,this.scanFilter))if(o.type==="file"&&i.match(o.name)&&await this.exportMatcher.test(await new Response(o.content).text(),e))return this.importResolver.getImportPath(this.fileSystem.joinPaths(r,o.name),n);throw new qe(`Unable to resolve import \`${t}\` from \`${n}\`.`,{reason:"not_found"})}};var zt=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 gc(a){let e=typeof a=="string"?Te(a,["jsx","typescript"]):a,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 fc(a,e){let t=[];return traverse(a,{ImportDeclaration:n=>{let{node:r}=n,i=Promise.resolve(e(zm(r)));return i!==void 0&&t.push(i.then(o=>typeof o=="string"&&r.source.value!==o?(r.source.value=o,true):false)),n.skip()}}),(await Promise.all(t)).some(n=>n)}function zm(a){let e={names:[],source:a.source.value};for(let t of a.specifiers)f.isImportSpecifier(t)&&e.names.push(f.isIdentifier(t.imported)?t.imported.name:t.imported.value);return e}var Fo=class{async apply(e,t){let n=await fc(e,t.transformer);return {result:e,modified:n}}};var $t=class{constructor(...e){this.codemods=e;}async apply(e,t){let n=e,r=false;for(let i of this.codemods){let o=await i.apply(n,t);n=o.result,r=r||o.modified;}return {modified:r,result:n}}};var _o=class a{constructor(e,t){this.client=e,this.cache=t;}getHierarchy(e){return this.cache.get(a.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(Zs,e),n=t?.id,r=t?.workspace?.id,i=t?.workspace?.application?.id;return a.checkMissing("organization",e.organizationSlug,n),"workspaceSlug"in e?(a.checkMissing("workspace",e.workspaceSlug,r),"applicationSlug"in e?(a.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(a.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 ee(`No ${e} found with slug "${t}".`,[],{reason:"not_found"})}};var Lo=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 U)||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 jo=class a{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 U("Cannot determine the user profile directory.",{reason:"precondition"});return a.windows({...t,appDataDirectory:n})}case "darwin":{let n=e.getEnvValue("HOME");if(n===null)throw new U("Cannot determine the user home directory.",{reason:"precondition"});return a.macOs({...t,homeDirectory:n})}case "linux":{let n=e.getEnvValue("HOME");if(n===null)throw new U("Cannot determine the user home directory.",{reason:"precondition"});return a.linux({...t,homeDirectory:n})}default:throw new U(`Platform \`${e.getPlatform()}\` is not supported.`,{reason:"not_supported"})}}static windows(e){return new a({...e,appDirectory:e.fileSystem.joinPaths(e.appDataDirectory,"Mozilla","Firefox")})}static macOs(e){return new a({...e,appDirectory:e.fileSystem.joinPaths(e.homeDirectory,"Library","Application Support","Firefox")})}static linux(e){return new a({...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 U("Cannot find the default profile file.",{reason:"not_found"});let n=this.getUserPreferencesFilePath(t),r=this.getHandlersFilePath(t),[i,o]=await Promise.all([await this.fileSystem.readTextFile(n).catch(()=>""),this.fileSystem.readTextFile(r).catch(()=>"")]),s=`${i}
|
|
1837
|
+
`,n+=t.map(({label:i,url:o})=>` \u2022 ${Tc(i,o,{fallback:()=>`${i}: ${o}`})}`).join(`
|
|
1838
|
+
`)),n}};var Pr=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 Cr=class{constructor(){this.eventDispatcher=new Pr;Re.on("SIGTERM",()=>this.exit()),Re.on("SIGINT",()=>this.exit()),Re.on("SIGHUP",()=>this.exit());}getCurrentDirectory(){return Re.cwd()}getEnvValue(e){return Re.env[e]??null}getEnvList(e){return this.getEnvValue(e)?.split(delimiter)??null}getPlatform(){return Re.platform}getStandardError(){return Re.stderr}getStandardInput(){return Re.stdin}getStandardOutput(){return Re.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(()=>{}),Re.exit(e)}changeDirectory(e){Re.chdir(e);}};var kr=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 Rm=z.strictObject({}),Ar=class extends I{constructor(){super(Rm);}};var Er=class a{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 $("Unsupported NPM URL.",{reason:"not_supported",url:e});let{value:n}=await this.metadataProvider.get(t),i=a.getRepositoryUrl(n.repository);return i===null?{url:e,value:[]}:{url:i,value:[{pattern:".*",destination:i}]}}static getRepositoryUrl(e){for(let t of a.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 Rr=class a{constructor({provider:e,reader:t}){this.provider=e,this.reader=t;}static text(e){return new a({provider:e,reader:t=>t.text()})}static json(e){return new a({provider:e,reader:t=>t.json()})}static blob(e){return new a({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(i){throw new $("Failed to read response body.",{reason:"unexpected_result",url:e,cause:i})}return {url:t.url,value:n}}};var Om=z.object({name:z.string(),repository:z.object({type:z.string(),url:z.string()})}),Or=class extends G{constructor(){super(Om);}};var Tr=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 Mr=class{constructor(e){this.storage=new AsyncLocalStorage;this.logger=e;}nest(e,t){let n=this.storage.getStore(),i={level:n!==void 0?n.level+1:0,logs:[]};return this.storage.run(i,async()=>{let o=await this.logNested(i,e,t);return n!==void 0?n.logs.push(...i.logs):(i.logs.forEach(r=>this.logger.log(r)),i.logs=[]),o})}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 Nr=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 zr=class a{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(a.PREFIX))return;let n=t.source.slice(a.PREFIX.length);return this.resolvePath(t,n,e)}})}async resolvePath(e,t,n){let i=this.rootPath.get(),o=new Minimatch(t.startsWith("./")?`${this.fileSystem.getRelativePath(i,this.fileSystem.getDirectoryName(n)).replace(/[\\/]/g,"/")}/${t.slice(2)}`:t);for await(let r of this.fileSystem.list(i,this.scanFilter))if(r.type==="file"&&o.match(r.name)&&await this.exportMatcher.test(await new Response(r.content).text(),e))return this.importResolver.getImportPath(this.fileSystem.joinPaths(i,r.name),n);throw new qe(`Unable to resolve import \`${t}\` from \`${n}\`.`,{reason:"not_found"})}};var zt=class{constructor({codemods:e}){this.codemods=e;}async apply(e,t){let n={modified:false,result:e};for(let[i,o]of Object.entries(this.codemods))minimatch(e,i)&&(n=await o.apply(e,t));return n}};function hc(a){let e=typeof a=="string"?De(a,["jsx","typescript"]):a,t=[];return traverse(e,{ExportDeclaration:n=>{let{node:i}=n;if(f.isExportNamedDeclaration(i))if(i.specifiers.length>0)for(let o of i.specifiers)f.isExportSpecifier(o)?(!f.isIdentifier(o.exported)||o.exported.name!=="default")&&t.push(f.isIdentifier(o.exported)?o.exported.name:o.exported.value):f.isExportNamespaceSpecifier(o)&&f.isIdentifier(o.exported)&&t.push(o.exported.name);else if(f.isVariableDeclaration(i.declaration))for(let o of i.declaration.declarations)f.isVariableDeclarator(o)&&f.isIdentifier(o.id)&&t.push(o.id.name);else typeof i.declaration=="object"&&i.declaration!==null&&"id"in i.declaration&&f.isIdentifier(i.declaration.id)&&t.push(i.declaration.id.name);return n.skip()}}),t}async function Sc(a,e){let t=[];return traverse(a,{ImportDeclaration:n=>{let{node:i}=n,o=Promise.resolve(e($m(i)));return o!==void 0&&t.push(o.then(r=>typeof r=="string"&&i.source.value!==r?(i.source.value=r,true):false)),n.skip()}}),(await Promise.all(t)).some(n=>n)}function $m(a){let e={names:[],source:a.source.value};for(let t of a.specifiers)f.isImportSpecifier(t)&&e.names.push(f.isIdentifier(t.imported)?t.imported.name:t.imported.value);return e}var Fr=class{async apply(e,t){let n=await Sc(e,t.transformer);return {result:e,modified:n}}};var $t=class{constructor(...e){this.codemods=e;}async apply(e,t){let n=e,i=false;for(let o of this.codemods){let r=await o.apply(n,t);n=r.result,i=i||r.modified;}return {modified:i,result:n}}};var jr=class a{constructor(e,t){this.client=e,this.cache=t;}getHierarchy(e){return this.cache.get(a.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(Qs,e),n=t?.id,i=t?.workspace?.id,o=t?.workspace?.application?.id;return a.checkMissing("organization",e.organizationSlug,n),"workspaceSlug"in e?(a.checkMissing("workspace",e.workspaceSlug,i),"applicationSlug"in e?(a.checkMissing("application",e.applicationSlug,o),{organizationId:n,workspaceId:i,applicationId:o}):{organizationId:n,workspaceId:i}):{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(a.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 ee(`No ${e} found with slug "${t}".`,[],{reason:"not_found"})}};var _r=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 U)||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 Lr=class a{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 U("Cannot determine the user profile directory.",{reason:"precondition"});return a.windows({...t,appDataDirectory:n})}case "darwin":{let n=e.getEnvValue("HOME");if(n===null)throw new U("Cannot determine the user home directory.",{reason:"precondition"});return a.macOs({...t,homeDirectory:n})}case "linux":{let n=e.getEnvValue("HOME");if(n===null)throw new U("Cannot determine the user home directory.",{reason:"precondition"});return a.linux({...t,homeDirectory:n})}default:throw new U(`Platform \`${e.getPlatform()}\` is not supported.`,{reason:"not_supported"})}}static windows(e){return new a({...e,appDirectory:e.fileSystem.joinPaths(e.appDataDirectory,"Mozilla","Firefox")})}static macOs(e){return new a({...e,appDirectory:e.fileSystem.joinPaths(e.homeDirectory,"Library","Application Support","Firefox")})}static linux(e){return new a({...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),i=await this.fileSystem.readTextFile(n).catch(()=>"");for(let o of this.getPreferences(e))if(!i.includes(o))return false;return true}async register(e){if(await this.isRegistered(e.protocol))return;let t=await this.getProfilePath();if(t===null)throw new U("Cannot find the default profile file.",{reason:"not_found"});let n=this.getUserPreferencesFilePath(t),i=this.getHandlersFilePath(t),[o,r]=await Promise.all([await this.fileSystem.readTextFile(n).catch(()=>""),this.fileSystem.readTextFile(i).catch(()=>"")]),s=`${o}
|
|
1839
1839
|
${this.getPreferences(e.protocol).join(`
|
|
1840
|
-
`)}`;await this.fileSystem.writeTextFile(n,s,{overwrite:true});let p=a.parseHandlers(
|
|
1840
|
+
`)}`;await this.fileSystem.writeTextFile(n,s,{overwrite:true});let p=a.parseHandlers(r);p.schemes[e.protocol]={ask:true,action:2,handlers:[{name:e.name,path:this.configuration.appPath}]},await this.fileSystem.writeTextFile(i,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),i=this.getHandlersFilePath(t),[o,r]=await Promise.all([await this.fileSystem.readTextFile(n).catch(()=>""),this.fileSystem.readTextFile(i).catch(()=>"")]),s=o.split(`
|
|
1841
1841
|
`).filter(c=>!this.getPreferences(e).includes(c)).join(`
|
|
1842
|
-
`);await this.fileSystem.writeTextFile(n,s,{overwrite:true});let p=a.parseHandlers(o);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$2(await this.fileSystem.readTextFile(e))),n=[],r=[];for(let o of t)o.Default!==void 0&&n.push(o.Default),o.Path!==void 0&&(o.Default==="1"?r.unshift(o.Path):r.push(o.Path));if(r.length===0)return null;let i=r[0];for(let o of r)if(n.includes(o)){i=o;break}return this.getPath(i)}getPath(e){return this.fileSystem.joinPaths(this.profileDirectory,e)}getPreferences(e){return a.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 Uo=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:o}=this.config;if(!t&&await e.isRegistered(o.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({...o,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 Vo=class a{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 o=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 o===null?null:{rootConfigPath:o.rootConfigPath,matchedConfigPath:o.matchedConfigPath,baseUrl:this.fileSystem.joinPaths(this.fileSystem.getDirectoryName(o.matchedConfigPath),o.compilerOptions?.baseUrl??"."),paths:o.compilerOptions?.paths??{}}}async locateConfig(e,t,n=false){for(let i of t){let o=this.fileSystem.joinPaths(e,i);if(await this.fileSystem.exists(o))return o}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,o=await this.parseConfig(t);if(o?.extends!==void 0){let s=await this.locateParentConfig(r,this.fileSystem.getDirectoryName(t),o.extends);if(s!==null){let p=await this.resolveConfig({...e,configPath:s});p!==null&&(o=a.mergeConfig(o,p));}}if(o?.references!==void 0&&i.length>0){let{references:s,...p}=o;for(let c of o.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 v=this.fileSystem.joinPaths("./",this.fileSystem.getRelativePath(this.fileSystem.getDirectoryName(u),y));for(let A of g.include){let M=new Minimatch(A,{partial:true,magicalBraces:true});if(!M.hasMagic()&&!A.includes(".")&&(M=new Minimatch(`${A.replace(/\/?$/,"")}/**/*`,{partial:true})),M.match(v))return a.mergeConfig({...g,rootConfigPath:o.rootConfigPath},p)}}}}return o}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 o=this.fileSystem.joinPaths(e,"node_modules",r);return await this.fileSystem.exists(o)?o: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 Wo=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 Ee(`Unable to locate executable for command \`${e.name}\`.`);return this.commandExecutor.run({...e,name:n},t)}};function hc(a){let e=typeof a=="string"?Te(a,["jsx","typescript"]):a,t=false;return traverse(e,{enter:n=>{let{node:r}=n;if(Vm(r))return t=true,n.stop()}}),t}function Vm(a){return isTypeScript(a)||Wm(a)}function Wm(a){return (isImportSpecifier(a)||isImportDeclaration(a))&&(a.importKind==="type"||a.importKind==="typeof")}var qo=class{async apply(e){if(!hc(e))return {modified:false,result:e};let t=createConfigItem([Hm,{onlyRemoveTypeImports:true}]),n=createConfigItem([Gm,{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],v=u.find((M,L)=>L>g&&!["CommentLine","CommentBlock"].includes(M.type));if(v===void 0)continue;v.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 Ko=class{constructor({executableLocator:e,command:t}){this.executableLocator=e,this.command=t;}async test(){return await this.executableLocator.locate(this.command)!==null}};var Ho=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 Go=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 Pn=class{constructor(e){this.factory=e;}open(e){return this.instance===void 0&&(this.instance=this.factory()),this.instance.open(e)}};var Cn=class{constructor(e){this.output=e;}open(e){let t=e.replace(/([\\`*_{}[\]()#+\-.!])/g,"\\$1");return this.output.log(`[${t}](${t})`),Promise.resolve()}};var Jo=class{constructor(e){this.fallbackOpener=e;}async open(e){try{await Jm(e);}catch{return this.fallbackOpener.open(e)}}};var Bo=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 ae({status:"Installing dependencies",notifier:r})});}catch(i){throw h.fromCause(i)}finally{r?.stop();}}};var Zm=z.strictObject({}),Zo=class extends I{constructor(){super(Zm);}};var Qo=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(o){throw h.fromCause(o)}}};var Xo=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 Qm=z.strictObject({path:z.string().min(1),destination:z.string().min(1),overwrite:z.boolean().optional()}),ea=class extends I{constructor(){super(Qm);}};var Xm=z.strictObject({path:z.string().min(1),optional:z.boolean().optional(),result:z.string().min(1)}),na=class extends I{constructor(){super(Xm);}};var ra=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 Ym=z.strictObject({path:z.string().min(1)}),ia=class extends I{constructor(){super(Ym);}};var oa=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(o){throw h.fromCause(o)}}};var ed=z.strictObject({path:z.string().min(1),content:z.string(),overwrite:z.boolean().optional()}),sa=class extends I{constructor(){super(ed);}};var pa=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()}),om.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:Ic,logger:new ae({status:"Updating the CLI",notifier:r})});}catch{let o=await this.packageManager.getPackageUpdateCommand("croct",{global:Ic}),s=`${o.name} ${o.arguments?.join(" ")}`;r.alert("Failed to update the CLI automatically"),this.output.log(`Please run the command:
|
|
1843
|
-
\`${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 ca=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 nd=z.strictObject({path:z.string().min(1),recursive:z.boolean().optional()}),la=class extends I{constructor(){super(nd);}};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=Pt.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 rd=z.strictObject({path:z.string().min(1)}),ma=class extends I{constructor(){super(rd);}};var da=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 o=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{o?.stop();}t.set(e.result,s.secret);}};var id=z.strictObject({keyName:z.string().min(1),environment:z.enum(["development","production"]),permissions:z.array(z.enum(se.all().flatMap(a=>[a.toUpperCase(),a.toLowerCase()])).transform(se.fromValue)).min(1),result:z.string().min(1)}),ga=class extends I{constructor(){super(id);}};var fa=class{apply(e,t){if(t===void 0)return Promise.resolve({modified:false,result:e});if(Je(e,{moduleName:/@storyblok\/(js|react)/,importName:/storyblokInit|\*/})===null)return Promise.resolve({modified:false,result:e});let r=t.module!==void 0?Je(e,{importName:t.name,moduleName:t.module}):null,i=r??t.name,o=false;if(traverse(e,{CallExpression:s=>{let{callee:p}=s.node;f.isIdentifier(p)&&p.name==="storyblokInit"&&(s.node.arguments=[f.callExpression(f.identifier(i),s.node.arguments)],o=true),f.isMemberExpression(p)&&f.isIdentifier(p.property)&&p.property.name==="storyblokInit"&&(s.node.arguments=[f.callExpression(f.identifier(i),s.node.arguments)],o=true);}}),o&&r===null){let{body:s}=e.program;f.isImportDeclaration(s[0])||s.unshift(f.emptyStatement()),pe(e,{type:"value",moduleName:t.module,importName:t.name});}return Promise.resolve({modified:o,result:e})}};var ya=class{constructor(e){this.codemod=e.codemod,this.scanFilter=e.scanFilter;}async getInstallationPlan(e,t){if(!await t.packageManager.hasDependency("@storyblok/js"))return {};let n=[];return n.push({title:"Configure Storyblok integration",task:async r=>{r.update("Configuring Storyblok integration");try{await this.configureStoryblok(t),r.confirm("Storyblok configured");}catch(i){r.alert("Failed to configure Storyblok",d.formatMessage(i));}}}),{tasks:n,dependencies:["@croct/plug-storyblok"]}}async configureStoryblok(e){let t=await this.findStoryblokInitializationFiles(e);if(t.length===0)throw new d("Could not find any file containing Storyblok initialization.");let n=t.map(r=>this.codemod.apply(r).then(i=>i.modified));if(!(await Promise.all(n)).some(r=>r))throw new d("Could not find any Storyblok initialization to configure.")}async findStoryblokInitializationFiles(e){let{fileSystem:t,projectDirectory:n}=e,r=n.get(),i=t.list(r,async(s,p)=>{if(!await this.scanFilter(s,p)||p>20)return false;let c=extname(s).toLowerCase();return c===""||c===".js"||c===".ts"||c===".jsx"||c===".tsx"}),o=[];for await(let s of i){if(s.type!=="file")continue;let p=t.joinPaths(r,s.name);(await t.readTextFile(p)).includes("storyblokInit")&&o.push(p);}return o}};var Sa=class a{constructor(e){this.instances=new Map;this.configuration=e,this.initialDirectory=e.directories.current??e.process.getCurrentDirectory(),this.workingDirectory=new So(this.initialDirectory);}static{this.READ_ONLY_COMMANDS=new Set([vn,Zt,Qt,vt,xt,Jt,Bt,en,Vt]);}static fromDefaults(e){let t=ld("com.croct.cli"),n=new Co;return new a({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??rs.isCI,interactive:e.interactive??!rs.isCI,version:e.version??"0.0.0",apiKey:e.apiKey,token:e.token,dnd:e.dnd??rs.isCI,adminTokenDuration:e.adminTokenDuration??7*LocalTime.SECONDS_PER_DAY,apiKeyTokenDuration:e.apiKeyTokenDuration??30*LocalTime.SECONDS_PER_MINUTE,cliTokenDuration:e.cliTokenDuration??90*LocalTime.SECONDS_PER_DAY,cliTokenFreshPeriod:e.cliTokenFreshPeriod??15*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"),configurationFile:e.configurationFile??"croct.json",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 vn({cliVersion:this.configuration.version,autoUpdater:new pa({currentVersion:this.configuration.version,input:this.getInput(),configurationProvider:this.getCliConfigurationProvider(),packageManager:this.getNodePackageManager(),output:this.getOutput(),checkFrequency:LocalTime.MILLIS_PER_SECOND*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 Uo({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 io({program:this.configuration.program,protocol:this.configuration.deepLinkProtocol,configurationProvider:this.getCliConfigurationProvider(),workingDirectory:new bo(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 $n({sdkProvider:this.getSdkProvider(),platformProvider:this.getPlatformProvider(),configurationManager:this.getConfigurationManager(),skipConfirmation:new Xi(new In(new Zi(new yn({fileSystem:this.getFileSystem(),files:[".git"]})))),api:{user:this.getUserApi(),organization:this.getOrganizationApi(),workspace:this.getWorkspaceApi()},form:{organization:new Un({input:this.getFormInput(),output:this.getOutput(),userApi:this.getUserApi()}),workspace:new Vn({input:this.getFormInput(),output:this.getOutput(),organizationApi:this.getOrganizationApi()}),application:new Wn({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),slot:new je({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})},io:{input:this.getInput(),output:this.getOutput()}}),{...e,organization:e.organization??t.getEnvValue("CROCT_ORGANIZATION")??void 0,workspace:e.workspace??t.getEnvValue("CROCT_WORKSPACE")??void 0,devApplication:e.devApplication??t.getEnvValue("CROCT_DEV_APPLICATION")??void 0,prodApplication:e.prodApplication??t.getEnvValue("CROCT_PROD_APPLICATION")??void 0,skipApiKeySetup:e.skipApiKeySetup??t.getEnvValue("CROCT_SKIP_API_KEY_SETUP")!==null})}install(e){let t=!this.configuration.interactive||this.configuration.dnd;return this.execute(new Zt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),io:{input:this.getInput(),output:this.getOutput()}}),{clean:e.clean??false,partialConfiguration:e.partialConfiguration??t})}upgrade(e){return this.execute(new Qt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),form:{slotForm:new je({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),componentForm:new Be({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})},io:{input:this.getInput(),output:this.getOutput()}}),e)}addSlot(e){return this.execute(new vt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new je({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}removeSlot(e){return this.execute(new Jt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),slotForm:new je({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}addComponent(e){return this.execute(new xt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new Be({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}removeComponent(e){return this.execute(new Bt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new Be({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}login(e){return this.execute(new Fn({authenticator:this.getAuthenticator()}),e)}logout(){return this.execute(new Vt({authenticator:this.getAuthenticator(),output:this.getOutput()}),{})}admin(e){return this.execute(new Jn({output:this.getOutput(),pageForm:new tr({input:this.getFormInput()}),configurationManager:this.getConfigurationManager(),userApi:this.getUserApi(),adminUrl:this.configuration.adminUrl,adminTokenParameter:this.configuration.adminTokenParameter,adminTokenDuration:this.configuration.adminTokenDuration}),e)}createTemplate(e){return this.execute(new en({configurationManager:this.getConfigurationManager(),fileSystem:this.getFileSystem(),templateForm:new yr({input:this.getFormInput(),form:{component:new Be({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),slot:new je({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),experience:new hr({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),audience:new Sr({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 kt({provider:new rn(this.getTemplateProvider()),validator:new ln}),fileSystem:this.getFileSystem(),action:this.getImportAction(),io:{input:this.getInput(),output:this.getOutput()}})}createApiKey(e){return this.execute(new yo({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 bn(new rr(e??{message:"Input is not available in non-interactive mode."}))}getInput(){if(this.configuration.interactive)return this.share(this.getInput,()=>{let e=this.getOutput(),t=new kn({input:this.configuration.process.getStandardInput(),output:this.configuration.process.getStandardOutput(),onAbort:()=>e.exit(),onInteractionStart:()=>e.suspend(),onInteractionEnd:()=>e.resume()});return this.configuration.dnd?new bn(t):t})}getNonInteractiveOutput(e=false){let{configuration:t}=this,n=new Ut({output:t.process.getStandardOutput(),formatter:this.getLogFormatter(),interactive:false,quiet:e,onExit:()=>t.process.exit(),linkOpener:new Pn(()=>new Cn(n))});return t.process.on("exit",()=>n.stop()),n}getHierarchicalLogger(){return this.share(this.getHierarchicalLogger,()=>new Mo(this.getLogger()))}getLogger(){return this.share(this.getLogger,()=>{let e=new No(this.getOutput());return this.configuration.debug?e:new FilteredLogger(e,LogLevel.WARNING)})}getOutput(){return this.share(this.getOutput,()=>{let{configuration:e}=this,t=new Ut({output:e.process.getStandardOutput(),formatter:this.getLogFormatter(),interactive:this.configuration.interactive,quiet:this.configuration.quiet,onExit:()=>e.process.exit(),linkOpener:new Pn(()=>{let n=new Cn(t);return this.configuration.dnd?n:new Jo(n)})});return e.process.on("exit",()=>t.stop()),t})}getLogFormatter(){return this.share(this.getLogFormatter,()=>new wo)}getTemplateProvider(){return this.share(this.getTemplateProvider,()=>{let e=n=>new Ne({providers:["template.json5","template.json"].map(r=>new lt({dataProvider:n,registryProvider:new Tt([{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 an({resourceCache:new AutoSaveCache(new InMemoryCache),errorCache:new InMemoryCache,provider:new Ne({providers:[new lt({dataProvider:this.traceProvider({label:"ResourceProvider",provider:e(new ut(new Ne({providers:[this.traceProvider({provider:this.createGitHubProvider(t)}),this.traceProvider({provider:new tn(t)})]})))}),registryProvider:this.traceProvider({label:"NpmRegistryProvider",provider:new Eo(new kt({provider:Ro.json(this.traceProvider({provider:this.getHttpProvider()})),validator:new Oo}))})}),e(new ut(this.getFileProvider()))]})})})})}getFileProvider(){return this.share(this.getFileProvider,()=>{let e=this.traceProvider({provider:this.getHttpProvider()}),t=this.traceProvider({provider:new Nr(this.getFileSystem(),this.getScanFilter())}),n=new Ne({providers:[t,this.traceProvider({provider:this.createGitHubProvider(e)}),this.traceProvider({provider:new tn(e)})]});return this.traceProvider({label:"FileProvider",provider:new Ne({providers:[t,this.traceProvider({provider:new lt({baseUrl:new URL("./",this.configuration.templateRegistryUrl),dataProvider:this.traceProvider({label:"ResourceProvider",provider:n}),registryProvider:new gi({url:this.configuration.templateRegistryUrl,provider:this.traceProvider({label:"GlobalRegistryProvider",provider:new an({errorCache:new InMemoryCache,resourceCache:new AutoSaveCache(new InMemoryCache),provider:new kt({provider:new rn(new ut(n)),validator:new Ur})})})})})})]})})})}createGitHubProvider(e){let t=Date.now();return new zr({cache:new AutoSaveCache(new InMemoryCache),provider:new Ne({providers:[new Ne({providers:[new lt({dataProvider:e,registryProvider:new Tt([{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 Do({label:t,provider:e,logger:this.getHierarchicalLogger()})}getImportAction(){return this.share(this.getImportAction,()=>{let e=this.getFileSystem(),t=new Map,n={run:new D({action:new Ze(new Ae(()=>new Pi(n))),validator:new Ci}),try:new D({action:new Ze(new Ae(()=>new kr(n.run))),validator:new Hr}),test:new D({action:new Ze(new Ae(()=>new ai(n.run))),validator:new pi}),repeat:new D({action:new Ze(new Ae(()=>new Yi(n.run))),validator:new eo}),print:new D({action:new ci,validator:new ui}),fail:new D({action:new mi,validator:new di}),define:new D({action:new Ri,validator:new Ei}),prompt:new D({action:new Ii,validator:new vi}),"change-directory":new D({action:new Ni({fileSystem:e,rootDirectory:this.initialDirectory,currentDirectory:this.workingDirectory}),validator:new Mi}),"open-link":new D({action:new ki,validator:new Ai}),"start-server":new D({action:new xi({serverProvider:this.getServerProvider(),serverFactory:this.getServerFactory(),packageManager:this.getPackageManager(),serverMap:t}),validator:new wi}),"stop-server":new D({action:new Ho({serverMap:t}),validator:new Oi}),"check-dependency":new D({action:new Mr({packageManager:this.getPackageManager()}),validator:new Gr}),download:new D({action:new Ir({fileSystem:e,provider:this.getFileProvider(),codemod:new zt({codemods:{"**/*.{js,jsx,ts,tsx}":new $t(this.getNodeImportResolverCodemod(),new zt({codemods:{"**/*.{js,jsx}":new $t(new Pe({fileSystem:e,codemod:new xe({codemod:new qo,languages:["typescript","jsx"]})}))}}),new we(this.getJavaScriptFormatter()))}})}),validator:new Jr}),"resolve-import":new D({action:new ua({projectDirectory:this.workingDirectory,fileSystem:e,scanFilter:this.getScanFilter(),codemod:new zt({codemods:{"**/*.{js,jsx,ts,tsx}":new $t(this.getNodeImportResolverCodemod(),new we(this.getJavaScriptFormatter()))}})}),validator:new ma}),install:new D({action:new Bo({packageManager:this.getPackageManager()}),validator:new Zo}),"add-dependency":new D({action:new vr({packageManager:this.getPackageManager()}),validator:new Zr}),"execute-package":new D({action:new zi({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 $i}),"locate-path":new D({action:new xr({projectDirectory:this.workingDirectory,fileSystem:e,scanFilter:this.getScanFilter()}),validator:new Qr}),"move-path":new D({action:new Qo({fileSystem:e}),validator:new ea}),"delete-path":new D({action:new ca({fileSystem:e}),validator:new la}),"read-file":new D({action:new Xo({fileSystem:e}),validator:new na}),"write-file":new D({action:new oa({fileSystem:e,input:this.getInput()}),validator:new sa}),"replace-file-content":new D({action:new wr({fileSystem:e}),validator:new Xr}),"create-directory":new D({action:new ra({fileSystem:e}),validator:new ia}),"integrate-croct":new D({action:new ko({callback:async()=>{if(!await this.getConfigurationManager().isInitialized("full"))return this.init({})}}),validator:new Ao}),"add-slot":new D({action:new Pr({installer:(r,i)=>{let o=this.getNonInteractiveOutput(true);return this.execute(new vt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new je({input:this.getNonInteractiveInput(),output:o,workspaceApi:this.getWorkspaceApi()}),io:{output:o}}),{slots:r,example:i})}}),validator:new ei}),"add-component":new D({action:new Cr({installer:r=>{let i=this.getNonInteractiveOutput(true);return this.execute(new xt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new Be({input:this.getNonInteractiveInput(),output:i,workspaceApi:this.getWorkspaceApi()}),io:{output:i}}),{components:r})}}),validator:new ti}),"create-api-key":new D({action:new da({applicationApi:this.getApplicationApi(),configurationManager:this.getConfigurationManager()}),validator:new ga}),"create-resource":new D({action:new Rr({configurationManager:this.getConfigurationManager(),matcher:new Tr({workspaceApi:this.getWorkspaceApi()}),api:{user:this.getUserApi(),workspace:this.getWorkspaceApi(),organization:this.getOrganizationApi()},mappingForm:new Or({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 ni}),"format-code":new D({action:new ii({formatter:this.getCodeFormatter()}),validator:new oi}),import:new D({action:new Ze(new Ae(()=>new Wr({runner:n.run,templateProvider:new Kr({evaluator:new Vr({functions:es}),validator:new ln,templateProvider:this.getTemplateProvider(),fileProvider:new ut(this.getFileProvider())}),variables:this.getActionVariables()}))),validator:new ri})};return n.import})}getActionVariables(){let e=t=>new URL(t,this.configuration.adminUrl).toString();return {packageManager:B.transient(()=>({name:this.getPackageManager().getName()})),project:{features:B.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{features:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),quotas:B.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{quotas:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),organization:B.transient(async()=>{let{organization:t}=await this.getConfigurationManager().load();return {slug:t,url:e(`organizations/${t}`)}}),workspace:B.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load();return {slug:n,url:e(`organizations/${t}/workspaces/${n}`)}}),application:B.transient(async()=>{let{organization:t,workspace:n,applications:r}=await this.getConfigurationManager().load(),i=`organizations/${t}/workspaces/${n}/applications/`,o=r.production;return {development:{slug:r.development,url:e(i+r.development),publicId:B.transient(async()=>{let p=await this.getWorkspaceApi().getApplication({organizationSlug:t,workspaceSlug:n,applicationSlug:r.development});if(p===null)throw new N("Development application not found.",{reason:"not_found"});return p.publicId})},production:{slug:r.production,url:e(i+r.production),publicId:o===void 0?o:B.transient(async()=>{let p=await this.getWorkspaceApi().getApplication({organizationSlug:t,workspaceSlug:n,applicationSlug:o});if(p===null)throw new N("Production application not found.",{reason:"not_found"});return p.publicId})}}}),path:B.transient(async()=>{let t=this.getSdk(),n=await this.getConfigurationManager().load();return t.getPaths(n)}),platform:B.transient(async()=>await this.getPlatformProvider().get()??"unknown"),server:B.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 Dr({retry:{maxAttempts:3,delay:1e3}}))}getAuthenticator(){return this.share(this.getAuthenticator,()=>{if(this.configuration.apiKey!==void 0)return new ho({apiKey:this.configuration.apiKey,clock:this.getClock(),tokenDuration:this.configuration.apiKeyTokenDuration});if(this.configuration.token!==void 0)return new Go({token:this.configuration.token});let e=this.getFormInput(),t=new Kn({input:e,output:this.getOutput(),userApi:this.getUserApi(true),form:{signIn:new Hn({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 Gn({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 Io({cacheKey:"token",cacheProvider:new vo({clock:this.getClock(),clockSkewTolerance:5,tokenFreshPeriod:this.configuration.cliTokenFreshPeriod,tokenIssuer:()=>n.issueToken({duration:this.configuration.cliTokenDuration}),cacheProvider:this.selectCacheProvider(()=>new on({fileSystem:this.getFileSystem(),directory:this.configuration.directories.config,useKeyAsFileName:true}))}),authenticator:new ir({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 mo({authenticator:r,invitationForm:new uo({output:this.getOutput(),input:e,userApi:this.getUserApi(true)})}):r})}getSdk(){return this.share(this.getSdk,()=>{let e=new Mt(this.getSdkProvider(),new Ae(()=>{throw new j("No suitable SDK detected.",{reason:"not_supported",suggestions:["Make sure you are running the command in the project root directory."]})}));return new Bi(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 Ot({discriminator:async()=>await this.getPlatformProvider().get()??i,mapping:{javascript:()=>new Tn({...r,plugins:[this.createStoryblokPlugin("javascript")],bundlers:["vite","parcel","tsup","rollup"]}),react:()=>new Dn({...r,plugins:[this.createStoryblokPlugin("react")],importResolver:n,codemod:{provider:new we(e,new Pe({fileSystem:this.getFileSystem(),codemod:new xe({languages:["typescript","jsx"],codemod:new ot({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 o={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"}}},s=p=>new we(e,new Pe({fileSystem:this.getFileSystem(),codemod:new xe({languages:["typescript","jsx"],codemod:new Zn({matcherPattern:"/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",exportName:p,import:{module:`@croct/plug-next/${p}`,proxyName:p,proxyFactoryName:"withCroct"}})})}));return new zn({...r,plugins:[this.createStoryblokPlugin("nextjs")],userApi:this.getUserApi(),applicationApi:this.getApplicationApi(),importResolver:n,codemod:{proxy:s("proxy"),middleware:s("middleware"),appRouterProvider:new we(e,new Pe({fileSystem:this.getFileSystem(),codemod:new xe({languages:["typescript","jsx"],codemod:new ot({fallbackToNamedExports:false,fallbackCodemod:new Qn({provider:{component:"CroctProvider",module:"@croct/plug-next/CroctProvider"}}),wrapper:{module:"@croct/plug-next/CroctProvider",component:"CroctProvider"},targets:{variable:"children"}})})})),pageRouterProvider:new we(e,new Pe({fileSystem:this.getFileSystem(),codemod:new xe({languages:["typescript","jsx"],codemod:new ot({fallbackToNamedExports:false,fallbackCodemod:new Gt({provider:{component:"CroctProvider",module:"@croct/plug-next/CroctProvider"}}),wrapper:{module:"@croct/plug-next/CroctProvider",component:"CroctProvider"},targets:{component:"Component"}})})})),fallbackProvider:new we(e,new Pe({fileSystem:this.getFileSystem(),codemod:new xe({languages:["typescript","jsx"],codemod:new ot({fallbackToNamedExports:false,fallbackCodemod:new Gt({provider:{component:"CroctProvider",module:"@croct/plug-react",props:o}}),wrapper:{module:"@croct/plug-react",component:"CroctProvider",props:o},targets:{component:"Component"}})})}))}})},[i]:()=>null}})})}getCodeFormatter(){return this.share(this.getCodeFormatter,()=>{let e=Symbol("unknown");return new Ji(new Ot({discriminator:async()=>await this.getPlatformProvider().get()??e,mapping:{javascript:()=>this.getJavaScriptFormatter(),react:()=>this.getJavaScriptFormatter(),nextjs:()=>this.getJavaScriptFormatter(),[e]:()=>{throw new j("No code formatter detected.",{reason:"not_supported",suggestions:["Make sure you are running the command in the project root directory."]})}}}))})}createStoryblokPlugin(e){let t=new fa,n={javascript:"js",react:"react",nextjs:"next"};return new ya({scanFilter:this.getScanFilter(),codemod:new we(this.getJavaScriptFormatter(),new Pe({fileSystem:this.getFileSystem(),codemod:new xe({languages:["typescript","jsx"],codemod:{apply:r=>t.apply(r,{name:"withCroct",module:`@croct/plug-storyblok/${n[e]}`})}})}))})}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 Wi(new Map(Object.entries(this.getPackageManagers()))))}getPackageManagers(){return this.getNodePackageManagers()}getPackageManager(){return this.share(this.getPackageManager,()=>new fn(new Mt(this.getNodePackageManagerProvider(),new Ae(()=>{throw new j("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 fn(new Mt(this.getNodePackageManagerProvider(),new Tt(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 Sn(new lo(new dt({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new co({process:this.configuration.process,variable:"npm_config_user_agent",value:new RegExp(`^${r}`)})}))}),new dt({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new In(new po({packageManager:r,fileSystem:t,projectDirectory:this.workingDirectory}),new yn({fileSystem:t,files:n[r]}))}))}),new dt({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new Ko({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 nn,r={fileSystem:e,projectDirectory:this.workingDirectory,packageValidator:n};return {npm:new Xe({...r,agent:new Fi(t)}),yarn:new Xe({...r,agent:new _i(t)}),bun:new Xe({...r,agent:new Li(t)}),pnpm:new Xe({...r,agent:new ji(t)})}})}getServerProvider(){return this.share(this.getServerProvider,()=>{let e=Symbol("unknown");return new Ot({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 fi({packageManager:this.getNodePackageManager(),factory:this.getServerFactory(),parsers:[new yi,new hi,new Si,new bi]}))}getServerFactory(){return this.share(this.getServerFactory,()=>new Di({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 Yn({commandExecutor:this.getSynchronousCommandExecutor(),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 Ui({fileSystem:this.getFileSystem(),tsConfigLoader:this.getTsConfigLoader(),projectDirectory:this.workingDirectory}))}getTsConfigLoader(){return this.share(this.getTsConfigLoader,()=>new Vo({fileSystem:this.getFileSystem(),tsconfigValidator:new Vi}))}getAsynchronousCommandExecutor(){return this.share(this.getAsynchronousCommandExecutor,()=>new Wo({executableLocator:this.getExecutableLocator(),commandExecutor:this.getCommandExecutor()}))}getSynchronousCommandExecutor(){return this.getCommandExecutor()}getCommandExecutor(){return this.share(this.getCommandExecutor,()=>new Gi({currentDirectory:this.workingDirectory,windows:this.configuration.process.getPlatform()==="win32"}))}getExecutableLocator(){return this.share(this.getExecutableLocator,()=>{let{process:e}=this.configuration;return new so({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 Xe({projectDirectory:this.workingDirectory,packageValidator:new nn,fileSystem:this.getFileSystem(),agent:new qi});return new Sn(new dt({candidates:[{value:"nextjs",condition:new hn({packageManager:e,dependencies:["next"]})},{value:"react",condition:new hn({packageManager:e,dependencies:["react"]})},{value:"javascript",condition:new Ki({packageManager:e})}]}),this.workingDirectory)})}getConfigurationManager(){return this.share(this.getConfigurationManager,()=>{let e=this.getFileSystem(),t=new _n({fileSystem:e,fullValidator:new _r,partialValidator:new Lr,projectDirectory:this.workingDirectory,configurationFile:e.isAbsolutePath(this.configuration.configurationFile)?this.configuration.configurationFile:e.joinPaths(this.workingDirectory.get(),this.configuration.configurationFile)});return new ao({workingDirectory:this.workingDirectory,configurationProvider:this.getCliConfigurationProvider(),manager:new Ar(this.isReadOnlyMode()?t:new er({manager:t,initializer:{initialize:()=>this.init({})}}))})})}getNodeImportResolverCodemod(){return this.share(this.getNodeImportResolverCodemod,()=>{let e=this.getFileSystem(),t=this.getScanFilter();return new zo({fileSystem:e,rootPath:this.workingDirectory,filter:(n,r)=>r<=10&&t(n,r),importResolver:this.getNodeImportResolver(),importCodemod:new Pe({fileSystem:e,codemod:new xe({languages:["typescript","jsx"],codemod:new Fo})}),exportMatcher:{test:(n,{names:r})=>r.length===0?true:gc(n).some(i=>r.includes(i))}})})}getScanFilter(){return this.share(this.getScanFilter,()=>{let e=new Qi({fileSystem:this.getFileSystem(),workingDirectory:this.workingDirectory});return async t=>!await e.test(t)})}getUserApi(e=false){return e?new Kt(this.getGraphqlClient(true)):this.share(this.getUserApi,()=>new Kt(this.getGraphqlClient()))}getOrganizationApi(){return this.share(this.getOrganizationApi,()=>new Ln(this.getGraphqlClient(),this.getHierarchyResolver()))}getWorkspaceApi(){return this.share(this.getWorkspaceApi,()=>new jn(this.getGraphqlClient(),this.getHierarchyResolver()))}getApplicationApi(){return this.share(this.getApplicationApi,()=>new qn(this.getGraphqlClient(),this.getHierarchyResolver()))}getHierarchyResolver(){return this.share(this.getHierarchyResolver,()=>new _o(this.getGraphqlClient(),new InMemoryCache))}getGraphqlClient(e=false){return e?new Wt({endpoint:this.configuration.adminGraphqlEndpoint,tokenProvider:{getToken:()=>this.getAuthenticator().getToken()}}):this.share(this.getGraphqlClient,()=>{let t=this.getAuthenticator();return new Wt({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 ar({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 or({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:Instant.now(n).getSeconds()})}getEmailLinkGenerator(){return this.share(this.getEmailLinkGenerator,()=>new sr({detector:new pr(new cr,new lr),templates:{google:new ur,icloud:new mr,microsoft:new dr,proton:new gr,yahoo:new fr}}))}getClock(){return SystemClock.UTC}getProtocolRegistryProvider(){return this.share(this.getProtocolRegistryProvider,()=>new Ae(()=>{let e=this.getFileSystem(),{process:t}=this.configuration;switch(t.getPlatform()){case "darwin":{let n=e.joinPaths(this.configuration.directories.data,"apps");return new Lo({output:this.getOutput(),macOsRegistry:new to({fileSystem:e,appDirectory:n,commandExecutor:this.getAsynchronousCommandExecutor()}),firefoxRegistry:jo.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 ro({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 fo({fileSystem:e,configurationProvider:new go({cacheKey:"config.json",cache:this.selectCacheProvider(()=>new on({fileSystem:e,directory:this.configuration.directories.config,useKeyAsFileName:true})),validator:new oo})})})}async execute(e,t){if(this.isReadOnlyMode()&&!a.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=a.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(a.handleError(e)),t.exit()}static handleError(e){switch(true){case e instanceof $:return new d(e.message,{...e.help,details:[`URL: ${e.url}`,...e.help.details??[]]});case e instanceof ee: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 o=r!==void 0?` at ${a.getSourceLocation(r)}`:"";return `${" ".repeat(i+1)}\u21B3 \`${n}\`${o}`}).join(`
|
|
1842
|
+
`);await this.fileSystem.writeTextFile(n,s,{overwrite:true});let p=a.parseHandlers(r);p.schemes[e]!==void 0&&(delete p.schemes[e],await this.fileSystem.writeTextFile(i,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$2(await this.fileSystem.readTextFile(e))),n=[],i=[];for(let r of t)r.Default!==void 0&&n.push(r.Default),r.Path!==void 0&&(r.Default==="1"?i.unshift(r.Path):i.push(r.Path));if(i.length===0)return null;let o=i[0];for(let r of i)if(n.includes(r)){o=r;break}return this.getPath(o)}getPath(e){return this.fileSystem.joinPaths(this.profileDirectory,e)}getPreferences(e){return a.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 Ur=class{constructor(e){this.config=e;}async execute(e){let{protocolRegistryProvider:t,io:{output:n}}=this.config,i=await t.get();if(i===null){["optionally-enable","optionally-update"].includes(e.operation)||n.alert("Deep linking is not available on your platform.");return}try{await this.apply(i,e);}catch(o){n.alert(`Deep link error: ${d.formatCause(o)}`);}}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:i}}=this.config;if(!await e.isRegistered(n.protocol)&&await i?.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:i,packageManager:o,protocolHandler:r}=this.config;if(!t&&await e.isRegistered(r.protocol)){n?.inform("Deep links are already enabled");return}let s=n?.notify("Enabling deep links");try{let p=await o.getPackageCommand(i,["open","$url"]);await e.register({...r,command:`${p.name} ${(p.arguments??[]).join(" ")}`}),s?.confirm("Deep links enabled");}finally{s?.stop();}}async disable(e,t,n){let{protocolHandler:i}=this.config;if(!t&&!await e.isRegistered(i.protocol)){n?.inform("Deep links are not enabled");return}let o=n?.notify("Disabling deep links");try{await e.unregister(i.protocol),o?.confirm("Deep links disabled");}finally{o?.stop();}}async optionallyUpdate(e,t){let{protocolHandler:n}=this.config;if(!await e.isRegistered(n.protocol))return this.optionallyEnable(e,t);let i=t?.notify("Updating deep links");try{await this.disable(e,!0),await this.enable(e,!0),i?.confirm("Deep links updated");}finally{i?.stop();}}};var Vr=class a{constructor({fileSystem:e,tsconfigValidator:t}){this.fileSystem=e,this.tsConfigValidator=t;}async load(e,t={}){let{fileNames:n=["tsconfig.json","jsconfig.json"]}=t,i=await this.fileSystem.getRealPath(e),o=await this.locateConfig(e,n,true);if(o===null)return null;let r=await this.resolveConfig({rootDirectory:i,configPath:o,fileNames:n,targetDirectories:(t.sourcePaths??[]).map(s=>this.fileSystem.isAbsolutePath(s)?s:this.fileSystem.joinPaths(i,s))});return r===null?null:{rootConfigPath:r.rootConfigPath,matchedConfigPath:r.matchedConfigPath,baseUrl:this.fileSystem.joinPaths(this.fileSystem.getDirectoryName(r.matchedConfigPath),r.compilerOptions?.baseUrl??"."),paths:r.compilerOptions?.paths??{}}}async locateConfig(e,t,n=false){for(let o of t){let r=this.fileSystem.joinPaths(e,o);if(await this.fileSystem.exists(r))return r}if(!n)return null;let i=this.fileSystem.getDirectoryName(e);return i===e?null:this.locateConfig(i,t)}async resolveConfig(e){let{configPath:t,fileNames:n,rootDirectory:i,targetDirectories:o}=e,r=await this.parseConfig(t);if(r?.extends!==void 0){let s=await this.locateParentConfig(i,this.fileSystem.getDirectoryName(t),r.extends);if(s!==null){let p=await this.resolveConfig({...e,configPath:s});p!==null&&(r=a.mergeConfig(r,p));}}if(r?.references!==void 0&&o.length>0){let{references:s,...p}=r;for(let c of r.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 o){let v=this.fileSystem.joinPaths("./",this.fileSystem.getRelativePath(this.fileSystem.getDirectoryName(u),y));for(let A of g.include){let M=new Minimatch(A,{partial:true,magicalBraces:true});if(!M.hasMagic()&&!A.includes(".")&&(M=new Minimatch(`${A.replace(/\/?$/,"")}/**/*`,{partial:true})),M.match(v))return a.mergeConfig({...g,rootConfigPath:r.rootConfigPath},p)}}}}return r}async locateParentConfig(e,t,n){let i=n;i.endsWith(".json")||(i+=".json");let o=this.fileSystem.joinPaths(t,i);if(await this.fileSystem.exists(o))return o;let r=this.fileSystem.joinPaths(e,"node_modules",i);return await this.fileSystem.exists(r)?r: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 Wr=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 Ee(`Unable to locate executable for command \`${e.name}\`.`);return this.commandExecutor.run({...e,name:n},t)}};function Ic(a){let e=typeof a=="string"?De(a,["jsx","typescript"]):a,t=false;return traverse(e,{enter:n=>{let{node:i}=n;if(Wm(i))return t=true,n.stop()}}),t}function Wm(a){return isTypeScript(a)||qm(a)}function qm(a){return (isImportSpecifier(a)||isImportDeclaration(a))&&(a.importKind==="type"||a.importKind==="typeof")}var qr=class{async apply(e){if(!Ic(e))return {modified:false,result:e};let t=createConfigItem([Gm,{onlyRemoveTypeImports:true}]),n=createConfigItem([Jm,{legacy:true}]),i={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],v=u.find((M,_)=>_>g&&!["CommentLine","CommentBlock"].includes(M.type));if(v===void 0)continue;v.loc.start.line-y.loc.end.line>1&&c.push(l);}}if(c.length>0){let l=noop();l.comments=c,s.insertBefore(l);}}},o=await transformFromAstAsync(e,void 0,{plugins:[{name:"comment-remover",visitor:{Program:i,TSTypeAliasDeclaration:i,TSInterfaceDeclaration:i,TSDeclareFunction:i,TSDeclareMethod:i,TSImportType:i,TSModuleDeclaration:i}},t,n],ast:true,configFile:false});return {result:o?.ast??e,modified:(o?.ast??null)!==null}}};var Kr=class{constructor({executableLocator:e,command:t}){this.executableLocator=e,this.command=t;}async test(){return await this.executableLocator.locate(this.command)!==null}};var Hr=class{constructor({serverMap:e}){this.serverMap=e;}async execute({id:e},t){let{output:n}=t,i=this.serverMap.get(e);if(i===void 0)throw new d(`No server with id "${e}" found.`);let o=n.notify("Stopping server");try{await i.stop();}finally{o.stop();}this.serverMap.delete(e);}};var Gr=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 Pn=class{constructor(e){this.factory=e;}open(e){return this.instance===void 0&&(this.instance=this.factory()),this.instance.open(e)}};var Cn=class{constructor(e){this.output=e;}open(e){let t=e.replace(/([\\`*_{}[\]()#+\-.!])/g,"\\$1");return this.output.log(`[${t}](${t})`),Promise.resolve()}};var Jr=class{constructor(e){this.fallbackOpener=e;}async open(e){try{await Bm(e);}catch{return this.fallbackOpener.open(e)}}};var Br=class{constructor({packageManager:e}){this.packageManager=e;}async execute(e,t){let{output:n}=t,i=n?.notify("Installing dependencies");try{await this.packageManager.installDependencies({logger:new ae({status:"Installing dependencies",notifier:i})});}catch(o){throw h.fromCause(o)}finally{i?.stop();}}};var Qm=z.strictObject({}),Zr=class extends I{constructor(){super(Qm);}};var Qr=class{constructor({fileSystem:e}){this.fileSystem=e;}async execute({path:e,destination:t,overwrite:n=false}){let i=this.fileSystem.normalizeSeparators(e);if(!await this.fileSystem.exists(i))throw new h("Cannot move path because source does not exist.",{reason:"invalid_input",details:[`Source: ${i}`]});let o=this.fileSystem.normalizeSeparators(t);if(await this.fileSystem.exists(o)&&!n)throw new h("Cannot move path because destination already exists.",{reason:"precondition",details:[`Destination: ${o}`]});if(this.fileSystem.isSubPath(i,o))throw new h("Cannot move path to a subdirectory of itself.",{reason:"invalid_input",details:[`Source: ${i}`,`Destination: ${o}`]});try{await this.fileSystem.move(i,o,{overwrite:n});}catch(r){throw h.fromCause(r)}}};var Xr=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(i){throw h.fromCause(i)}}};var Xm=z.strictObject({path:z.string().min(1),destination:z.string().min(1),overwrite:z.boolean().optional()}),ea=class extends I{constructor(){super(Xm);}};var Ym=z.strictObject({path:z.string().min(1),optional:z.boolean().optional(),result:z.string().min(1)}),na=class extends I{constructor(){super(Ym);}};var ia=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 ed=z.strictObject({path:z.string().min(1)}),oa=class extends I{constructor(){super(ed);}};var ra=class{constructor({fileSystem:e,input:t}){this.fileSystem=e,this.input=t;}async execute({path:e,content:t,...n}){let i=n.overwrite===true,o=this.fileSystem.normalizeSeparators(e);if(!i&&await this.fileSystem.exists(o)&&(i=this.input===void 0?false:await this.input.confirm({message:`Path \`${o}\` already exists. Do you want to overwrite it?`,default:false}),!i))throw new h("Failed to write file because the specified path already exists.",{reason:"precondition",details:[`File: ${o}`]});i&&await this.fileSystem.isDirectory(o)&&await this.fileSystem.delete(o,{recursive:true});try{await this.fileSystem.writeTextFile(o,t,{overwrite:i});}catch(r){throw h.fromCause(r)}}};var td=z.strictObject({path:z.string().min(1),content:z.string(),overwrite:z.boolean().optional()}),sa=class extends I{constructor(){super(td);}};var pa=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()}),am.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 i=this.output.notify("Updating the CLI");try{await this.packageManager.updatePackage("croct",{global:wc,logger:new ae({status:"Updating the CLI",notifier:i})});}catch{let o=await this.packageManager.getPackageUpdateCommand("croct",{global:wc}),r=`${o.name} ${o.arguments?.join(" ")}`;i.alert("Failed to update the CLI automatically"),this.output.log(`Please run the command:
|
|
1843
|
+
\`${r}\``);return}i.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 ca=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(i){throw h.fromCause(i)}}}};var id=z.strictObject({path:z.string().min(1),recursive:z.boolean().optional()}),la=class extends I{constructor(){super(id);}};var ua=class{constructor({projectDirectory:e,fileSystem:t,codemod:n,scanFilter:i}){this.projectDirectory=e,this.fileSystem=t,this.codemod=n,this.scanFilter=i;}async execute(e,t){let{output:n}=t,i=n?.notify("Resolving imports");try{await this.resolveImports(e.path);}finally{i?.stop();}}async resolveImports(e){let t=false,n=Pt.fromPattern(e);for await(let i of this.fileSystem.list(this.projectDirectory.get(),this.scanFilter))await n.test(i.name)&&i.type==="file"&&(t=true,await this.codemod.apply(await this.fileSystem.getRealPath(i.name)));if(!t)throw new d("No matching files found for resolving imports.",{reason:"unexpected_result",details:[`Pattern: ${e}`]})}};var od=z.strictObject({path:z.string().min(1)}),ma=class extends I{constructor(){super(od);}};var da=class{constructor({configurationManager:e,applicationApi:t}){this.configurationManager=e,this.api=t;}async execute(e,t){let{output:n}=t,i=await this.configurationManager.load(),o=e.environment==="production"?i.applications.production:i.applications.development;if(o===void 0)throw new h("The project has no application configured for the selected environment.",{reason:"precondition"});let r=n?.notify("Creating API key"),s;try{s=await this.api.createApiKey({organizationSlug:i.organization,workspaceSlug:i.workspace,applicationSlug:o,name:e.keyName,permissions:e.permissions});}catch(p){throw h.fromCause(p)}finally{r?.stop();}t.set(e.result,s.secret);}};var rd=z.strictObject({keyName:z.string().min(1),environment:z.enum(["development","production"]),permissions:z.array(z.enum(se.all().flatMap(a=>[a.toUpperCase(),a.toLowerCase()])).transform(se.fromValue)).min(1),result:z.string().min(1)}),ga=class extends I{constructor(){super(rd);}};var fa=class{apply(e,t){if(t===void 0)return Promise.resolve({modified:false,result:e});if(Je(e,{moduleName:/@storyblok\/(js|react)/,importName:/storyblokInit|\*/})===null)return Promise.resolve({modified:false,result:e});let i=t.module!==void 0?Je(e,{importName:t.name,moduleName:t.module}):null,o=i??t.name,r=false;if(traverse(e,{CallExpression:s=>{let{callee:p}=s.node,c=f.isIdentifier(p)&&p.name==="storyblokInit",l=f.isMemberExpression(p)&&f.isIdentifier(p.property)&&p.property.name==="storyblokInit";if(!c&&!l)return;let u=s.node.arguments;u.length===1&&f.isCallExpression(u[0])&&f.isIdentifier(u[0].callee)&&u[0].callee.name===o||(s.node.arguments=[f.callExpression(f.identifier(o),u)],r=true);}}),r&&i===null){let{body:s}=e.program;f.isImportDeclaration(s[0])||s.unshift(f.emptyStatement()),pe(e,{type:"value",moduleName:t.module,importName:t.name});}return Promise.resolve({modified:r,result:e})}};var ya=class{constructor(e){this.codemod=e.codemod,this.scanFilter=e.scanFilter;}async getInstallationPlan(e,t){if(!await t.packageManager.hasDependency("@storyblok/js"))return {};let n=[];return n.push({title:"Configure Storyblok integration",task:async i=>{i.update("Configuring Storyblok integration");try{await this.configureStoryblok(t),i.confirm("Storyblok configured");}catch(o){i.alert("Failed to configure Storyblok",d.formatMessage(o));}}}),{tasks:n,dependencies:["@croct/plug-storyblok"]}}async configureStoryblok(e){let t=await this.findStoryblokInitializationFiles(e);if(t.length===0)throw new d("Could not find any file containing Storyblok initialization.");let n=t.map(i=>this.codemod.apply(i).then(o=>o.modified));if(!(await Promise.all(n)).some(i=>i))throw new d("Could not find any Storyblok initialization to configure.")}async findStoryblokInitializationFiles(e){let{fileSystem:t,projectDirectory:n}=e,i=n.get(),o=t.list(i,async(s,p)=>{if(!await this.scanFilter(s,p)||p>20)return false;let c=extname(s).toLowerCase();return c===""||c===".js"||c===".ts"||c===".jsx"||c===".tsx"}),r=[];for await(let s of o){if(s.type!=="file")continue;let p=t.joinPaths(i,s.name);(await t.readTextFile(p)).includes("storyblokInit")&&r.push(p);}return r}};var Sa=class a{constructor(e){this.instances=new Map;this.configuration=e,this.initialDirectory=e.directories.current??e.process.getCurrentDirectory(),this.workingDirectory=new Sr(this.initialDirectory);}static{this.READ_ONLY_COMMANDS=new Set([vn,Zt,Qt,vt,xt,Jt,Bt,en,Vt]);}static fromDefaults(e){let t=ud("com.croct.cli"),n=new Cr;return new a({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??os.isCI,interactive:e.interactive??!os.isCI,version:e.version??"0.0.0",apiKey:e.apiKey,token:e.token,dnd:e.dnd??os.isCI,adminTokenDuration:e.adminTokenDuration??7*LocalTime.SECONDS_PER_DAY,apiKeyTokenDuration:e.apiKeyTokenDuration??30*LocalTime.SECONDS_PER_MINUTE,cliTokenDuration:e.cliTokenDuration??90*LocalTime.SECONDS_PER_DAY,cliTokenFreshPeriod:e.cliTokenFreshPeriod??15*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"),configurationFile:e.configurationFile??"croct.json",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 vn({cliVersion:this.configuration.version,autoUpdater:new pa({currentVersion:this.configuration.version,input:this.getInput(),configurationProvider:this.getCliConfigurationProvider(),packageManager:this.getNodePackageManager(),output:this.getOutput(),checkFrequency:LocalTime.MILLIS_PER_SECOND*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 Ur({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 rr({program:this.configuration.program,protocol:this.configuration.deepLinkProtocol,configurationProvider:this.getCliConfigurationProvider(),workingDirectory:new br(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 $n({sdkProvider:this.getSdkProvider(),platformProvider:this.getPlatformProvider(),configurationManager:this.getConfigurationManager(),skipConfirmation:new Yo(new In(new Qo(new yn({fileSystem:this.getFileSystem(),files:[".git"]})))),api:{user:this.getUserApi(),organization:this.getOrganizationApi(),workspace:this.getWorkspaceApi()},form:{organization:new Un({input:this.getFormInput(),output:this.getOutput(),userApi:this.getUserApi()}),workspace:new Vn({input:this.getFormInput(),output:this.getOutput(),organizationApi:this.getOrganizationApi()}),application:new Wn({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),slot:new Le({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){let t=!this.configuration.interactive||this.configuration.dnd;return this.execute(new Zt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),io:{input:this.getInput(),output:this.getOutput()}}),{clean:e.clean??false,partialConfiguration:e.partialConfiguration??t})}upgrade(e){return this.execute(new Qt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),form:{slotForm:new Le({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),componentForm:new Be({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})},io:{input:this.getInput(),output:this.getOutput()}}),e)}addSlot(e){return this.execute(new vt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new Le({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}removeSlot(e){return this.execute(new Jt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),slotForm:new Le({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}addComponent(e){return this.execute(new xt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new Be({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}removeComponent(e){return this.execute(new Bt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new Be({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}login(e){return this.execute(new Fn({authenticator:this.getAuthenticator()}),e)}logout(){return this.execute(new Vt({authenticator:this.getAuthenticator(),output:this.getOutput()}),{})}admin(e){return this.execute(new Jn({output:this.getOutput(),pageForm:new ti({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 en({configurationManager:this.getConfigurationManager(),fileSystem:this.getFileSystem(),templateForm:new yi({input:this.getFormInput(),form:{component:new Be({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),slot:new Le({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),experience:new hi({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),audience:new Si({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(),i=this.getOutput().notify("Loading template options");try{return await t.getOptions(e)}finally{i.stop();}}getUseTemplateCommand(){return new bi({templateProvider:new kt({provider:new on(this.getTemplateProvider()),validator:new ln}),fileSystem:this.getFileSystem(),action:this.getImportAction(),io:{input:this.getInput(),output:this.getOutput()}})}createApiKey(e){return this.execute(new yr({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 bn(new ii(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 kn({input:this.configuration.process.getStandardInput(),output:this.configuration.process.getStandardOutput(),onAbort:()=>e.exit(),onInteractionStart:()=>e.suspend(),onInteractionEnd:()=>e.resume()});return this.configuration.dnd?new bn(t):t})}getNonInteractiveOutput(e=false){let{configuration:t}=this,n=new Ut({output:t.process.getStandardOutput(),formatter:this.getLogFormatter(),interactive:false,quiet:e,onExit:()=>t.process.exit(),linkOpener:new Pn(()=>new Cn(n))});return t.process.on("exit",()=>n.stop()),n}getHierarchicalLogger(){return this.share(this.getHierarchicalLogger,()=>new Mr(this.getLogger()))}getLogger(){return this.share(this.getLogger,()=>{let e=new Nr(this.getOutput());return this.configuration.debug?e:new FilteredLogger(e,LogLevel.WARNING)})}getOutput(){return this.share(this.getOutput,()=>{let{configuration:e}=this,t=new Ut({output:e.process.getStandardOutput(),formatter:this.getLogFormatter(),interactive:this.configuration.interactive,quiet:this.configuration.quiet,onExit:()=>e.process.exit(),linkOpener:new Pn(()=>{let n=new Cn(t);return this.configuration.dnd?n:new Jr(n)})});return e.process.on("exit",()=>t.stop()),t})}getLogFormatter(){return this.share(this.getLogFormatter,()=>new wr)}getTemplateProvider(){return this.share(this.getTemplateProvider,()=>{let e=n=>new Ne({providers:["template.json5","template.json"].map(i=>new lt({dataProvider:n,registryProvider:new Dt([{pattern:/^(https:\/\/(?:www\.)?github.com\/[^/]+\/[^/]+)\/?$/,destination:`$1/blob/main/${i}`},{pattern:/^(.+?:\/*[^/]+(\/+[^/.]+|\/[^/]+(?=\/))*)\/*$/,destination:`$1/${i}`}])}))}),t=this.traceProvider({provider:this.getHttpProvider()});return this.traceProvider({label:"TemplateProvider",provider:new an({resourceCache:new AutoSaveCache(new InMemoryCache),errorCache:new InMemoryCache,provider:new Ne({providers:[new lt({dataProvider:this.traceProvider({label:"ResourceProvider",provider:e(new ut(new Ne({providers:[this.traceProvider({provider:this.createGitHubProvider(t)}),this.traceProvider({provider:new tn(t)})]})))}),registryProvider:this.traceProvider({label:"NpmRegistryProvider",provider:new Er(new kt({provider:Rr.json(this.traceProvider({provider:this.getHttpProvider()})),validator:new Or}))})}),e(new ut(this.getFileProvider()))]})})})})}getFileProvider(){return this.share(this.getFileProvider,()=>{let e=this.traceProvider({provider:this.getHttpProvider()}),t=this.traceProvider({provider:new Ni(this.getFileSystem(),this.getScanFilter())}),n=new Ne({providers:[t,this.traceProvider({provider:this.createGitHubProvider(e)}),this.traceProvider({provider:new tn(e)})]});return this.traceProvider({label:"FileProvider",provider:new Ne({providers:[t,this.traceProvider({provider:new lt({baseUrl:new URL("./",this.configuration.templateRegistryUrl),dataProvider:this.traceProvider({label:"ResourceProvider",provider:n}),registryProvider:new fo({url:this.configuration.templateRegistryUrl,provider:this.traceProvider({label:"GlobalRegistryProvider",provider:new an({errorCache:new InMemoryCache,resourceCache:new AutoSaveCache(new InMemoryCache),provider:new kt({provider:new on(new ut(n)),validator:new Ui})})})})})})]})})})}createGitHubProvider(e){let t=Date.now();return new zi({cache:new AutoSaveCache(new InMemoryCache),provider:new Ne({providers:[new Ne({providers:[new lt({dataProvider:e,registryProvider:new Dt([{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 Tr({label:t,provider:e,logger:this.getHierarchicalLogger()})}getImportAction(){return this.share(this.getImportAction,()=>{let e=this.getFileSystem(),t=new Map,n={run:new T({action:new Ze(new Ae(()=>new Co(n))),validator:new ko}),try:new T({action:new Ze(new Ae(()=>new ki(n.run))),validator:new Hi}),test:new T({action:new Ze(new Ae(()=>new ao(n.run))),validator:new po}),repeat:new T({action:new Ze(new Ae(()=>new er(n.run))),validator:new tr}),print:new T({action:new co,validator:new uo}),fail:new T({action:new mo,validator:new go}),define:new T({action:new Oo,validator:new Ro}),prompt:new T({action:new vo,validator:new xo}),"change-directory":new T({action:new zo({fileSystem:e,rootDirectory:this.initialDirectory,currentDirectory:this.workingDirectory}),validator:new No}),"open-link":new T({action:new Ao,validator:new Eo}),"start-server":new T({action:new wo({serverProvider:this.getServerProvider(),serverFactory:this.getServerFactory(),packageManager:this.getPackageManager(),serverMap:t}),validator:new Po}),"stop-server":new T({action:new Hr({serverMap:t}),validator:new Do}),"check-dependency":new T({action:new Mi({packageManager:this.getPackageManager()}),validator:new Gi}),download:new T({action:new Ii({fileSystem:e,provider:this.getFileProvider(),codemod:new zt({codemods:{"**/*.{js,jsx,ts,tsx}":new $t(this.getNodeImportResolverCodemod(),new zt({codemods:{"**/*.{js,jsx}":new $t(new Pe({fileSystem:e,codemod:new xe({codemod:new qr,languages:["typescript","jsx"]})}))}}),new we(this.getJavaScriptFormatter()))}})}),validator:new Ji}),"resolve-import":new T({action:new ua({projectDirectory:this.workingDirectory,fileSystem:e,scanFilter:this.getScanFilter(),codemod:new zt({codemods:{"**/*.{js,jsx,ts,tsx}":new $t(this.getNodeImportResolverCodemod(),new we(this.getJavaScriptFormatter()))}})}),validator:new ma}),install:new T({action:new Br({packageManager:this.getPackageManager()}),validator:new Zr}),"add-dependency":new T({action:new vi({packageManager:this.getPackageManager()}),validator:new Zi}),"execute-package":new T({action:new $o({processObserver:this.configuration.process,packageManager:this.getPackageManager(),packageManagerProvider:this.getPackageManagerRegistry(),workingDirectory:this.workingDirectory,commandExecutor:this.getAsynchronousCommandExecutor(),commandTimeout:180*1e3,sourceChecker:{test:i=>i.protocol==="file:"||`${i}`.startsWith("https://github.com/croct-tech")}}),validator:new Fo}),"locate-path":new T({action:new xi({projectDirectory:this.workingDirectory,fileSystem:e,scanFilter:this.getScanFilter()}),validator:new Qi}),"move-path":new T({action:new Qr({fileSystem:e}),validator:new ea}),"delete-path":new T({action:new ca({fileSystem:e}),validator:new la}),"read-file":new T({action:new Xr({fileSystem:e}),validator:new na}),"write-file":new T({action:new ra({fileSystem:e,input:this.getInput()}),validator:new sa}),"replace-file-content":new T({action:new wi({fileSystem:e}),validator:new Xi}),"create-directory":new T({action:new ia({fileSystem:e}),validator:new oa}),"integrate-croct":new T({action:new kr({callback:async()=>{if(!await this.getConfigurationManager().isInitialized("full"))return this.init({})}}),validator:new Ar}),"add-slot":new T({action:new Pi({installer:(i,o)=>{let r=this.getNonInteractiveOutput(true);return this.execute(new vt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new Le({input:this.getNonInteractiveInput(),output:r,workspaceApi:this.getWorkspaceApi()}),io:{output:r}}),{slots:i,example:o})}}),validator:new eo}),"add-component":new T({action:new Ci({installer:i=>{let o=this.getNonInteractiveOutput(true);return this.execute(new xt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new Be({input:this.getNonInteractiveInput(),output:o,workspaceApi:this.getWorkspaceApi()}),io:{output:o}}),{components:i})}}),validator:new to}),"create-api-key":new T({action:new da({applicationApi:this.getApplicationApi(),configurationManager:this.getConfigurationManager()}),validator:new ga}),"create-resource":new T({action:new Ri({configurationManager:this.getConfigurationManager(),matcher:new Di({workspaceApi:this.getWorkspaceApi()}),api:{user:this.getUserApi(),workspace:this.getWorkspaceApi(),organization:this.getOrganizationApi()},mappingForm:new Oi({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 no}),"format-code":new T({action:new oo({formatter:this.getCodeFormatter()}),validator:new ro}),import:new T({action:new Ze(new Ae(()=>new Wi({runner:n.run,templateProvider:new Ki({evaluator:new Vi({functions:ts}),validator:new ln,templateProvider:this.getTemplateProvider(),fileProvider:new ut(this.getFileProvider())}),variables:this.getActionVariables()}))),validator:new io})};return n.import})}getActionVariables(){let e=t=>new URL(t,this.configuration.adminUrl).toString();return {packageManager:B.transient(()=>({name:this.getPackageManager().getName()})),project:{features:B.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{features:i}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return i??{}}),quotas:B.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{quotas:i}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return i??{}}),organization:B.transient(async()=>{let{organization:t}=await this.getConfigurationManager().load();return {slug:t,url:e(`organizations/${t}`)}}),workspace:B.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load();return {slug:n,url:e(`organizations/${t}/workspaces/${n}`)}}),application:B.transient(async()=>{let{organization:t,workspace:n,applications:i}=await this.getConfigurationManager().load(),o=`organizations/${t}/workspaces/${n}/applications/`,r=i.production;return {development:{slug:i.development,url:e(o+i.development),publicId:B.transient(async()=>{let p=await this.getWorkspaceApi().getApplication({organizationSlug:t,workspaceSlug:n,applicationSlug:i.development});if(p===null)throw new N("Development application not found.",{reason:"not_found"});return p.publicId})},production:{slug:i.production,url:e(o+i.production),publicId:r===void 0?r:B.transient(async()=>{let p=await this.getWorkspaceApi().getApplication({organizationSlug:t,workspaceSlug:n,applicationSlug:r});if(p===null)throw new N("Production application not found.",{reason:"not_found"});return p.publicId})}}}),path:B.transient(async()=>{let t=this.getSdk(),n=await this.getConfigurationManager().load();return t.getPaths(n)}),platform:B.transient(async()=>await this.getPlatformProvider().get()??"unknown"),server:B.transient(async()=>{let n=await this.getServerProvider().get();if(n===null)return null;try{let i=await n.getStatus();if(i.running)return {running:!0,url:i.url.toString()}}catch{}return {running:false}})}}}getHttpProvider(){return this.share(this.getHttpProvider,()=>new Ti({retry:{maxAttempts:3,delay:1e3}}))}getAuthenticator(){return this.share(this.getAuthenticator,()=>{if(this.configuration.apiKey!==void 0)return new hr({apiKey:this.configuration.apiKey,clock:this.getClock(),tokenDuration:this.configuration.apiKeyTokenDuration});if(this.configuration.token!==void 0)return new Gr({token:this.configuration.token});let e=this.getFormInput(),t=new Kn({input:e,output:this.getOutput(),userApi:this.getUserApi(true),form:{signIn:new Hn({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 Gn({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),i=new Ir({cacheKey:"token",cacheProvider:new vr({clock:this.getClock(),clockSkewTolerance:5,tokenFreshPeriod:this.configuration.cliTokenFreshPeriod,tokenIssuer:()=>n.issueToken({duration:this.configuration.cliTokenDuration}),cacheProvider:this.selectCacheProvider(()=>new rn({fileSystem:this.getFileSystem(),directory:this.configuration.directories.config,useKeyAsFileName:true}))}),authenticator:new oi({default:this.configuration.interactive?t:new ni({authenticator:t,instruction:{message:"Authentication required.",suggestions:["Run `login` to authenticate"],reason:"precondition"}}),credentials:t})});return this.configuration.interactive?new dr({authenticator:i,invitationForm:new mr({output:this.getOutput(),input:e,userApi:this.getUserApi(true)})}):i})}getSdk(){return this.share(this.getSdk,()=>{let e=new Mt(this.getSdkProvider(),new Ae(()=>{throw new L("No suitable SDK detected.",{reason:"not_supported",suggestions:["Make sure you are running the command in the project root directory."]})}));return new Zo(e)})}getSdkProvider(){return this.share(this.getSdkProvider,()=>{let e=this.getJavaScriptFormatter(),t=this.getFileSystem(),n=this.getNodeImportResolver(),i={projectDirectory:this.workingDirectory,packageManager:this.getNodePackageManager(),fileSystem:t,formatter:e,workspaceApi:this.getWorkspaceApi(),tsConfigLoader:this.getTsConfigLoader()},o=Symbol("unknown");return new Ot({discriminator:async()=>await this.getPlatformProvider().get()??o,mapping:{javascript:()=>new Dn({...i,plugins:[this.createStoryblokPlugin("javascript")],bundlers:["vite","parcel","tsup","rollup"]}),react:()=>new Tn({...i,plugins:[this.createStoryblokPlugin("react")],importResolver:n,codemod:{provider:new we(e,new Pe({fileSystem:this.getFileSystem(),codemod:new xe({languages:["typescript","jsx"],codemod:new rt({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 r={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"}}},s=p=>new we(e,new Pe({fileSystem:this.getFileSystem(),codemod:new xe({languages:["typescript","jsx"],codemod:new Zn({matcherPattern:"/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",exportName:p,import:{module:`@croct/plug-next/${p}`,proxyName:p,proxyFactoryName:"withCroct"}})})}));return new zn({...i,plugins:[this.createStoryblokPlugin("nextjs")],userApi:this.getUserApi(),applicationApi:this.getApplicationApi(),importResolver:n,codemod:{proxy:s("proxy"),middleware:s("middleware"),appRouterProvider:new we(e,new Pe({fileSystem:this.getFileSystem(),codemod:new xe({languages:["typescript","jsx"],codemod:new rt({fallbackToNamedExports:false,fallbackCodemod:new Qn({provider:{component:"CroctProvider",module:"@croct/plug-next/CroctProvider"}}),wrapper:{module:"@croct/plug-next/CroctProvider",component:"CroctProvider"},targets:{variable:"children"}})})})),pageRouterProvider:new we(e,new Pe({fileSystem:this.getFileSystem(),codemod:new xe({languages:["typescript","jsx"],codemod:new rt({fallbackToNamedExports:false,fallbackCodemod:new Gt({provider:{component:"CroctProvider",module:"@croct/plug-next/CroctProvider"}}),wrapper:{module:"@croct/plug-next/CroctProvider",component:"CroctProvider"},targets:{component:"Component"}})})})),fallbackProvider:new we(e,new Pe({fileSystem:this.getFileSystem(),codemod:new xe({languages:["typescript","jsx"],codemod:new rt({fallbackToNamedExports:false,fallbackCodemod:new Gt({provider:{component:"CroctProvider",module:"@croct/plug-react",props:r}}),wrapper:{module:"@croct/plug-react",component:"CroctProvider",props:r},targets:{component:"Component"}})})}))}})},[o]:()=>null}})})}getCodeFormatter(){return this.share(this.getCodeFormatter,()=>{let e=Symbol("unknown");return new Bo(new Ot({discriminator:async()=>await this.getPlatformProvider().get()??e,mapping:{javascript:()=>this.getJavaScriptFormatter(),react:()=>this.getJavaScriptFormatter(),nextjs:()=>this.getJavaScriptFormatter(),[e]:()=>{throw new L("No code formatter detected.",{reason:"not_supported",suggestions:["Make sure you are running the command in the project root directory."]})}}}))})}createStoryblokPlugin(e){let t=new fa,n={javascript:"js",react:"react",nextjs:"next"};return new ya({scanFilter:this.getScanFilter(),codemod:new we(this.getJavaScriptFormatter(),new Pe({fileSystem:this.getFileSystem(),codemod:new xe({languages:["typescript","jsx"],codemod:{apply:i=>t.apply(i,{name:"withCroct",module:`@croct/plug-storyblok/${n[e]}`})}})}))})}share(e,t){let n=this.instances.get(e);if(n===void 0){let i=t();return this.instances.set(e,i),i}return n}getPackageManagerRegistry(){return this.share(this.getPackageManagerRegistry,()=>new qo(new Map(Object.entries(this.getPackageManagers()))))}getPackageManagers(){return this.getNodePackageManagers()}getPackageManager(){return this.share(this.getPackageManager,()=>new fn(new Mt(this.getNodePackageManagerProvider(),new Ae(()=>{throw new L("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 fn(new Mt(this.getNodePackageManagerProvider(),new Dt(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 Sn(new ur(new dt({candidates:Object.entries(e).map(([i,o])=>({value:o,condition:new lr({process:this.configuration.process,variable:"npm_config_user_agent",value:new RegExp(`^${i}`)})}))}),new dt({candidates:Object.entries(e).map(([i,o])=>({value:o,condition:new In(new cr({packageManager:i,fileSystem:t,projectDirectory:this.workingDirectory}),new yn({fileSystem:t,files:n[i]}))}))}),new dt({candidates:Object.entries(e).map(([i,o])=>({value:o,condition:new Kr({executableLocator:this.getExecutableLocator(),command:i})}))})),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 nn,i={fileSystem:e,projectDirectory:this.workingDirectory,packageValidator:n};return {npm:new Xe({...i,agent:new jo(t)}),yarn:new Xe({...i,agent:new _o(t)}),bun:new Xe({...i,agent:new Lo(t)}),pnpm:new Xe({...i,agent:new Uo(t)})}})}getServerProvider(){return this.share(this.getServerProvider,()=>{let e=Symbol("unknown");return new Ot({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 yo({packageManager:this.getNodePackageManager(),factory:this.getServerFactory(),parsers:[new ho,new So,new bo,new Io]}))}getServerFactory(){return this.share(this.getServerFactory,()=>new Mo({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 Yn({commandExecutor:this.getSynchronousCommandExecutor(),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 Vo({fileSystem:this.getFileSystem(),tsConfigLoader:this.getTsConfigLoader(),projectDirectory:this.workingDirectory}))}getTsConfigLoader(){return this.share(this.getTsConfigLoader,()=>new Vr({fileSystem:this.getFileSystem(),tsconfigValidator:new Wo}))}getAsynchronousCommandExecutor(){return this.share(this.getAsynchronousCommandExecutor,()=>new Wr({executableLocator:this.getExecutableLocator(),commandExecutor:this.getCommandExecutor()}))}getSynchronousCommandExecutor(){return this.getCommandExecutor()}getCommandExecutor(){return this.share(this.getCommandExecutor,()=>new Jo({currentDirectory:this.workingDirectory,windows:this.configuration.process.getPlatform()==="win32"}))}getExecutableLocator(){return this.share(this.getExecutableLocator,()=>{let{process:e}=this.configuration;return new pr({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 Xe({projectDirectory:this.workingDirectory,packageValidator:new nn,fileSystem:this.getFileSystem(),agent:new Ko});return new Sn(new dt({candidates:[{value:"nextjs",condition:new hn({packageManager:e,dependencies:["next"]})},{value:"react",condition:new hn({packageManager:e,dependencies:["react"]})},{value:"javascript",condition:new Ho({packageManager:e})}]}),this.workingDirectory)})}getConfigurationManager(){return this.share(this.getConfigurationManager,()=>{let e=this.getFileSystem(),t=new jn({fileSystem:e,fullValidator:new ji,partialValidator:new _i,projectDirectory:this.workingDirectory,configurationFile:e.isAbsolutePath(this.configuration.configurationFile)?this.configuration.configurationFile:e.joinPaths(this.workingDirectory.get(),this.configuration.configurationFile)});return new sr({workingDirectory:this.workingDirectory,configurationProvider:this.getCliConfigurationProvider(),manager:new Ai(this.isReadOnlyMode()?t:new ei({manager:t,initializer:{initialize:()=>this.init({})}}))})})}getNodeImportResolverCodemod(){return this.share(this.getNodeImportResolverCodemod,()=>{let e=this.getFileSystem(),t=this.getScanFilter();return new zr({fileSystem:e,rootPath:this.workingDirectory,filter:(n,i)=>i<=10&&t(n,i),importResolver:this.getNodeImportResolver(),importCodemod:new Pe({fileSystem:e,codemod:new xe({languages:["typescript","jsx"],codemod:new Fr})}),exportMatcher:{test:(n,{names:i})=>i.length===0?true:hc(n).some(o=>i.includes(o))}})})}getScanFilter(){return this.share(this.getScanFilter,()=>{let e=new Xo({fileSystem:this.getFileSystem(),workingDirectory:this.workingDirectory});return async t=>!await e.test(t)})}getUserApi(e=false){return e?new Kt(this.getGraphqlClient(true)):this.share(this.getUserApi,()=>new Kt(this.getGraphqlClient()))}getOrganizationApi(){return this.share(this.getOrganizationApi,()=>new _n(this.getGraphqlClient(),this.getHierarchyResolver()))}getWorkspaceApi(){return this.share(this.getWorkspaceApi,()=>new Ln(this.getGraphqlClient(),this.getHierarchyResolver()))}getApplicationApi(){return this.share(this.getApplicationApi,()=>new qn(this.getGraphqlClient(),this.getHierarchyResolver()))}getHierarchyResolver(){return this.share(this.getHierarchyResolver,()=>new jr(this.getGraphqlClient(),new InMemoryCache))}getGraphqlClient(e=false){return e?new Wt({endpoint:this.configuration.adminGraphqlEndpoint,tokenProvider:{getToken:()=>this.getAuthenticator().getToken()}}):this.share(this.getGraphqlClient,()=>{let t=this.getAuthenticator();return new Wt({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 ai({platform:e.process.getPlatform(),commandExecutor:this.getSynchronousCommandExecutor(),timeout:2e3,listener:new xr({api:this.getUserApi(true),pollingInterval:1e3})})})}getFileSystem(){return this.share(this.getFileSystem,()=>new ri({workingDirectory:this.workingDirectory,defaultEncoding:"utf-8"}))}createEmailLinkGenerator(e){let t=this.getEmailLinkGenerator(),n=this.getClock();return i=>t.generate({recipient:i,sender:"croct.com",subject:e,timestamp:Instant.now(n).getSeconds()})}getEmailLinkGenerator(){return this.share(this.getEmailLinkGenerator,()=>new si({detector:new pi(new ci,new li),templates:{google:new ui,icloud:new mi,microsoft:new di,proton:new gi,yahoo:new fi}}))}getClock(){return SystemClock.UTC}getProtocolRegistryProvider(){return this.share(this.getProtocolRegistryProvider,()=>new Ae(()=>{let e=this.getFileSystem(),{process:t}=this.configuration;switch(t.getPlatform()){case "darwin":{let n=e.joinPaths(this.configuration.directories.data,"apps");return new _r({output:this.getOutput(),macOsRegistry:new nr({fileSystem:e,appDirectory:n,commandExecutor:this.getAsynchronousCommandExecutor()}),firefoxRegistry:Lr.macOs({fileSystem:e,homeDirectory:this.configuration.directories.home,appPath:e.joinPaths(n,`${this.configuration.deepLinkProtocol}.app`)})})}case "win32":return new ir({commandExecutor:this.getAsynchronousCommandExecutor()});case "linux":return new or({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 fr({fileSystem:e,configurationProvider:new gr({cacheKey:"config.json",cache:this.selectCacheProvider(()=>new rn({fileSystem:e,directory:this.configuration.directories.config,useKeyAsFileName:true})),validator:new ar})})})}async execute(e,t){if(this.isReadOnlyMode()&&!a.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 i=a.handleError(n);return n instanceof Error&&i instanceof Error&&(i.stack=n.stack),this.reportError(i)}}isReadOnlyMode(){return this.configuration.apiKey!==void 0}reportError(e){let t=this.getOutput();return t.report(a.handleError(e)),t.exit()}static handleError(e){switch(true){case e instanceof $:return new d(e.message,{...e.help,details:[`URL: ${e.url}`,...e.help.details??[]]});case e instanceof ee: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:i},o)=>{let r=i!==void 0?` at ${a.getSourceLocation(i)}`:"";return `${" ".repeat(o+1)}\u21B3 \`${n}\`${r}`}).join(`
|
|
1844
1844
|
`);return new d(`${e.message}
|
|
1845
1845
|
|
|
1846
1846
|
\u25B6\uFE0F **Trace**
|
|
1847
|
-
${t}`,e.help)}break;case e instanceof ve: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
|
|
1847
|
+
${t}`,e.help)}break;case e instanceof ve: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 rs={version:"0.12.13"};function Cc(a){let e=new Command().name("croct").description("Manage your Croct projects").enablePositionalOptions().option("--cwd <path>","The working directory.",S=>{try{return realpathSync(S)}catch{throw new InvalidOptionArgumentError("The path does not exist.")}}).addOption(new Option("--api-key <key>","The API key to use for authentication.").env("CROCT_API_KEY").argParser(S=>{try{return ApiKey.parse(S)}catch{throw new InvalidOptionArgumentError("The API key is malformed.")}}).conflicts("token")).addOption(new Option("--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 InvalidOptionArgumentError("The token is malformed.")}if(!P.isValidNow())throw new InvalidOptionArgumentError("The token is expired.");return P})).option("--registry <url>","The template registry.",S=>{if(!URL.canParse(S))throw new InvalidOptionArgumentError("Malformed URL.");return S}).option("--no-interaction","Run the CLI in non-interactive mode.").option("--config <path>","Path to the configuration file.").addOption(new Option("--stateless","Run the CLI without saving any state locally.").env("CROCT_STATELESS").default(false)).addOption(new Option("--dnd","Run the CLI with minimal interaction and interruption.").env("CROCT_DND").default(false)).addOption(new Option("-q, --quiet","Disable output messages.").default(false).implies({interaction:false})).option("--debug","Enable debug mode.").version(rs.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 a.cli?.open({url:S});});let t=e.command("login").description("Authenticate your user."),n=new Option("-u, --username <username>","The email."),i=new Option("-p, --password <password>","The password.");t.command("credentials",{isDefault:true}).description("Authenticate using credentials.").addOption(a.interactive?n:n.makeOptionMandatory()).addOption(a.interactive?i:i.makeOptionMandatory()).action(async S=>{await a.cli?.login({method:"credentials",username:S.username,password:S.password});}),e.command("logout").description("Logout the current user.").action(async()=>{await a.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 a.cli?.admin({page:S!==void 0?S.join(" "):a.interactive?void 0:"/"});});let o=new Option("--wor <workspace-slug>","The workspace slug."),r=new Option("--org <organization-slug>","The organization slug."),s=new Option("--dev-app <application-slug>","The development application slug."),p=new Option("--prod-app <application-slug>","The production application slug.");e.command("init").description("Configure the project.").option("-o, --override","Override any existing configuration.").addOption(new Option("-n, --new <resource>","The resources to create.").choices(["organization","org","workspace","wor","application","app"])).addOption(new Option("-s, --sdk <platform>","The SDK to use.").choices(["javascript","react","next"])).addOption(new Option("--skip-api-key-setup","Opt-out of API key setup.").default(false).env("CROCT_SKIP_API_KEY_SETUP")).addOption(a.interactive?r:r.makeOptionMandatory()).addOption(a.interactive?o:o.makeOptionMandatory()).addOption(a.interactive?s:s.makeOptionMandatory()).addOption(p).action(async S=>{await a.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 a.cli?.install({});}),e.command("update").description("Update content and types.").action(async()=>{await a.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 a.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(a.interactive?"[slots...]":"<slots...>").option("-e, --example","Generate an implementation example.").action(async(S,P)=>{await a.cli?.addSlot({slots:S,example:P.example});}),c.command("component").description("Add a component to your project.").argument(a.interactive?"[components...]":"<components...>").action(async S=>{await a.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(a.interactive?"[slots...]":"<slots...>").action(async S=>{await a.cli?.removeSlot({slots:S});}),l.command("component").description("Remove a component from your project.").argument(a.interactive?"[components...]":"<components...>").action(async S=>{await a.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 Argument("<path>","The path to the file.").argOptional()).option("-e, --empty","Create an empty template.").action(async(S,P)=>{await a.cli?.createTemplate({file:S,empty:P.empty});});let g=new Option("--permissions <permissions...>","The permissions of the API key.").argParser(S=>S.split(",").map(P=>{try{return se.fromValue(P)}catch{throw new InvalidOptionArgumentError(`Unknown permission "${P}".`)}})),y=new Option("--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(a.interactive?g:g.makeOptionMandatory()).addOption(a.interactive?y:y.makeOptionMandatory()).option("-c, --copy","Copy the API key to the clipboard.").action(async S=>{await a.cli?.createApiKey({name:S.name,permissions:S.permissions,environment:S.env,copy:S.copy});});let v={},A=e.command("use").description("Use a template.").argument("template","The path to the template.").passThroughOptions(a.cli===void 0).allowUnknownOption(a.cli===void 0||a.template===null).action(async(S,P)=>{await a.cli?.useTemplate({template:S,options:Object.fromEntries(Object.entries(P).map(([H,ue])=>[v[H],ue]))});});for(let[S,P]of Object.entries(a.template??{})){let H=`--${S}${P.type!=="boolean"?" <value>":""}`,ue=new Option(H,P.description).makeOptionMandatory(P.required===true);switch(P.type){case "string":P.choices!==void 0&&P.choices.length>0&&ue.choices(P.choices);break;case "number":ue.argParser(V=>{let re=Number.parseFloat(V);if(Number.isNaN(re))throw new InvalidOptionArgumentError("The value must be a number.");return re});break;case "array":ue.argParser(V=>{let re;try{re=JSON.parse(V);}catch{}if(re===void 0||!Array.isArray(re))throw new InvalidOptionArgumentError("The value must be a JSON array.");return re});break;case "object":ue.argParser(V=>{let re;try{re=JSON.parse(V);}catch{throw new InvalidOptionArgumentError("The JSON is malformed.")}if(typeof re!="object"||re===null)throw new InvalidOptionArgumentError("The value must be a JSON object.")});break}v[ue.attributeName()]=S,A.addOption(ue);}return e.command("enable").description("Enable a feature.").command("deep-link").description("Enable deep link support.").action(async()=>{await a.cli?.deepLink({operation:"enable"});}),e.command("disable").description("Disable a feature.").command("deep-link").description("Disable deep link support.").action(async()=>{await a.cli?.deepLink({operation:"disable"});}),e}function Id(a){let e=["use","help use"];for(let t of e){let n=t.split(" ").length;if(a.length>n&&a.slice(0,n).join(" ")===t&&(a[n]??"")!=="")return a[n]}return null}function vd(a){return a.length>=2&&["enable","disable"].includes(a[0])&&a[1]==="deep-link"}async function as(a=process.argv,e=true){let t=Cc({interactive:true}).parse(a),n=t.opts(),i=Sa.fromDefaults({program:p=>as(t.args.slice(0,2).concat(p)),version:rs.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),configurationFile:n.config}),o=Id(t.args),r=o!==null?await i.getTemplateOptions(o).catch(()=>null):void 0,s=Cc({cli:i,interactive:n.interaction,template:r});e&&await i.welcome({skipDeepLinkCheck:vd(t.args)}),await s.parseAsync(a);}as();
|