@tailorkit/cli 0.1.0-beta.2 → 0.1.0-beta.20
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/LICENSE.md +201 -0
- package/dist/assets/agent-BSIUE6vC.js +1 -0
- package/dist/assets/agent-tui-DujCIubK.js +1 -0
- package/dist/index.js +103 -154
- package/package.json +19 -22
- package/LICENSE +0 -674
- package/dist/assets/builder-wgJqHM_A.js +0 -2
package/dist/index.js
CHANGED
|
@@ -1,53 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{fileURLToPath as e}from"node:url";import{dirname as t}from"node:path";const n=e(import.meta.url);t(n);import{createRequire as r}from"node:module";import{cancel as i,confirm as a,intro as o,isCancel as s,log as c,outro as l,select as u,spinner as d,text as f}from"@clack/prompts";import{cac as p}from"cac";import m from"picocolors";import{chmod as h,mkdir as g,
|
|
3
|
-
|
|
4
|
-
`+e.mark.snippet),r+` `+n):r}function r(e,t){Error.call(this),this.name=`YAMLException`,this.reason=e,this.mark=t,this.message=n(this,!1),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=Error().stack||``}r.prototype=Object.create(Error.prototype),r.prototype.constructor=r,r.prototype.toString=function(e){return this.name+`: `+n(this,e)},t.exports=r})),de=E(((e,t)=>{var n=le();function r(e,t,n,r,i){let a=``,o=``,s=Math.floor(i/2)-1;return r-t>s&&(a=` ... `,t=r-s+a.length),n-r>s&&(o=` ...`,n=r+s-o.length),{str:a+e.slice(t,n).replace(/\t/g,`→`)+o,pos:r-t+a.length}}function i(e,t){return n.repeat(` `,t-e.length)+e}function a(e,t){if(t=Object.create(t||null),!e.buffer)return null;t.maxLength||(t.maxLength=79),typeof t.indent!=`number`&&(t.indent=1),typeof t.linesBefore!=`number`&&(t.linesBefore=3),typeof t.linesAfter!=`number`&&(t.linesAfter=2);let a=/\r?\n|\r|\0/g,o=[0],s=[],c,l=-1;for(;c=a.exec(e.buffer);)s.push(c.index),o.push(c.index+c[0].length),e.position<=c.index&&l<0&&(l=o.length-2);l<0&&(l=o.length-1);let u=``,d=Math.min(e.line+t.linesAfter,s.length).toString().length,f=t.maxLength-(t.indent+d+3);for(let a=1;a<=t.linesBefore&&!(l-a<0);a++){let c=r(e.buffer,o[l-a],s[l-a],e.position-(o[l]-o[l-a]),f);u=n.repeat(` `,t.indent)+i((e.line-a+1).toString(),d)+` | `+c.str+`
|
|
5
|
-
`+u}let p=r(e.buffer,o[l],s[l],e.position,f);u+=n.repeat(` `,t.indent)+i((e.line+1).toString(),d)+` | `+p.str+`
|
|
6
|
-
`,u+=n.repeat(`-`,t.indent+d+3+p.pos)+`^
|
|
7
|
-
`;for(let a=1;a<=t.linesAfter&&!(l+a>=s.length);a++){let c=r(e.buffer,o[l+a],s[l+a],e.position-(o[l]-o[l+a]),f);u+=n.repeat(` `,t.indent)+i((e.line+a+1).toString(),d)+` | `+c.str+`
|
|
8
|
-
`}return u.replace(/\n$/,``)}t.exports=a})),k=E(((e,t)=>{var n=ue(),r=[`kind`,`multi`,`resolve`,`construct`,`instanceOf`,`predicate`,`represent`,`representName`,`defaultStyle`,`styleAliases`],i=[`scalar`,`sequence`,`mapping`];function a(e){let t={};return e!==null&&Object.keys(e).forEach(function(n){e[n].forEach(function(e){t[String(e)]=n})}),t}function o(e,t){if(t||={},Object.keys(t).forEach(function(t){if(r.indexOf(t)===-1)throw new n(`Unknown option "`+t+`" is met in definition of "`+e+`" YAML type.`)}),this.options=t,this.tag=e,this.kind=t.kind||null,this.resolve=t.resolve||function(){return!0},this.construct=t.construct||function(e){return e},this.instanceOf=t.instanceOf||null,this.predicate=t.predicate||null,this.represent=t.represent||null,this.representName=t.representName||null,this.defaultStyle=t.defaultStyle||null,this.multi=t.multi||!1,this.styleAliases=a(t.styleAliases||null),i.indexOf(this.kind)===-1)throw new n(`Unknown kind "`+this.kind+`" is specified for "`+e+`" YAML type.`)}t.exports=o})),fe=E(((e,t)=>{var n=ue(),r=k();function i(e,t){let n=[];return e[t].forEach(function(e){let t=n.length;n.forEach(function(n,r){n.tag===e.tag&&n.kind===e.kind&&n.multi===e.multi&&(t=r)}),n[t]=e}),n}function a(){let e={scalar:{},sequence:{},mapping:{},fallback:{},multi:{scalar:[],sequence:[],mapping:[],fallback:[]}};function t(t){t.multi?(e.multi[t.kind].push(t),e.multi.fallback.push(t)):e[t.kind][t.tag]=e.fallback[t.tag]=t}for(let e=0,n=arguments.length;e<n;e+=1)arguments[e].forEach(t);return e}function o(e){return this.extend(e)}o.prototype.extend=function(e){let t=[],s=[];if(e instanceof r)s.push(e);else if(Array.isArray(e))s=s.concat(e);else if(e&&(Array.isArray(e.implicit)||Array.isArray(e.explicit)))e.implicit&&(t=t.concat(e.implicit)),e.explicit&&(s=s.concat(e.explicit));else throw new n(`Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })`);t.forEach(function(e){if(!(e instanceof r))throw new n(`Specified list of YAML types (or a single Type object) contains a non-Type object.`);if(e.loadKind&&e.loadKind!==`scalar`)throw new n(`There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.`);if(e.multi)throw new n(`There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.`)}),s.forEach(function(e){if(!(e instanceof r))throw new n(`Specified list of YAML types (or a single Type object) contains a non-Type object.`)});let c=Object.create(o.prototype);return c.implicit=(this.implicit||[]).concat(t),c.explicit=(this.explicit||[]).concat(s),c.compiledImplicit=i(c,`implicit`),c.compiledExplicit=i(c,`explicit`),c.compiledTypeMap=a(c.compiledImplicit,c.compiledExplicit),c},t.exports=o})),A=E(((e,t)=>{t.exports=new(k())(`tag:yaml.org,2002:str`,{kind:`scalar`,construct:function(e){return e===null?``:e}})})),pe=E(((e,t)=>{t.exports=new(k())(`tag:yaml.org,2002:seq`,{kind:`sequence`,construct:function(e){return e===null?[]:e}})})),j=E(((e,t)=>{t.exports=new(k())(`tag:yaml.org,2002:map`,{kind:`mapping`,construct:function(e){return e===null?{}:e}})})),M=E(((e,t)=>{t.exports=new(fe())({explicit:[A(),pe(),j()]})})),me=E(((e,t)=>{var n=k();function r(e){if(e===null)return!0;let t=e.length;return t===1&&e===`~`||t===4&&(e===`null`||e===`Null`||e===`NULL`)}function i(){return null}function a(e){return e===null}t.exports=new n(`tag:yaml.org,2002:null`,{kind:`scalar`,resolve:r,construct:i,predicate:a,represent:{canonical:function(){return`~`},lowercase:function(){return`null`},uppercase:function(){return`NULL`},camelcase:function(){return`Null`},empty:function(){return``}},defaultStyle:`lowercase`})})),N=E(((e,t)=>{var n=k();function r(e){if(e===null)return!1;let t=e.length;return t===4&&(e===`true`||e===`True`||e===`TRUE`)||t===5&&(e===`false`||e===`False`||e===`FALSE`)}function i(e){return e===`true`||e===`True`||e===`TRUE`}function a(e){return Object.prototype.toString.call(e)===`[object Boolean]`}t.exports=new n(`tag:yaml.org,2002:bool`,{kind:`scalar`,resolve:r,construct:i,predicate:a,represent:{lowercase:function(e){return e?`true`:`false`},uppercase:function(e){return e?`TRUE`:`FALSE`},camelcase:function(e){return e?`True`:`False`}},defaultStyle:`lowercase`})})),he=E(((e,t)=>{var n=le(),r=k();function i(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function a(e){return e>=48&&e<=55}function o(e){return e>=48&&e<=57}function s(e){if(e===null)return!1;let t=e.length,n=0,r=!1;if(!t)return!1;let s=e[n];if((s===`-`||s===`+`)&&(s=e[++n]),s===`0`){if(n+1===t)return!0;if(s=e[++n],s===`b`){for(n++;n<t;n++){if(s=e[n],s!==`0`&&s!==`1`)return!1;r=!0}return r&&isFinite(c(e))}if(s===`x`){for(n++;n<t;n++){if(!i(e.charCodeAt(n)))return!1;r=!0}return r&&isFinite(c(e))}if(s===`o`){for(n++;n<t;n++){if(!a(e.charCodeAt(n)))return!1;r=!0}return r&&isFinite(c(e))}}for(;n<t;n++){if(!o(e.charCodeAt(n)))return!1;r=!0}return r?isFinite(c(e)):!1}function c(e){let t=e,n=1,r=t[0];if((r===`-`||r===`+`)&&(r===`-`&&(n=-1),t=t.slice(1),r=t[0]),t===`0`)return 0;if(r===`0`){if(t[1]===`b`)return n*parseInt(t.slice(2),2);if(t[1]===`x`)return n*parseInt(t.slice(2),16);if(t[1]===`o`)return n*parseInt(t.slice(2),8)}return n*parseInt(t,10)}function l(e){return c(e)}function u(e){return Object.prototype.toString.call(e)===`[object Number]`&&e%1==0&&!n.isNegativeZero(e)}t.exports=new r(`tag:yaml.org,2002:int`,{kind:`scalar`,resolve:s,construct:l,predicate:u,represent:{binary:function(e){return e>=0?`0b`+e.toString(2):`-0b`+e.toString(2).slice(1)},octal:function(e){return e>=0?`0o`+e.toString(8):`-0o`+e.toString(8).slice(1)},decimal:function(e){return e.toString(10)},hexadecimal:function(e){return e>=0?`0x`+e.toString(16).toUpperCase():`-0x`+e.toString(16).toUpperCase().slice(1)}},defaultStyle:`decimal`,styleAliases:{binary:[2,`bin`],octal:[8,`oct`],decimal:[10,`dec`],hexadecimal:[16,`hex`]}})})),P=E(((e,t)=>{var n=le(),r=k(),i=RegExp(`^(?:[-+]?(?:[0-9]+)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$`),a=RegExp(`^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$`);function o(e){return e===null||!i.test(e)?!1:isFinite(parseFloat(e,10))?!0:a.test(e)}function s(e){let t=e.toLowerCase(),n=t[0]===`-`?-1:1;return`+-`.indexOf(t[0])>=0&&(t=t.slice(1)),t===`.inf`?n===1?1/0:-1/0:t===`.nan`?NaN:n*parseFloat(t,10)}var c=/^[-+]?[0-9]+e/;function l(e,t){if(isNaN(e))switch(t){case`lowercase`:return`.nan`;case`uppercase`:return`.NAN`;case`camelcase`:return`.NaN`}else if(e===1/0)switch(t){case`lowercase`:return`.inf`;case`uppercase`:return`.INF`;case`camelcase`:return`.Inf`}else if(e===-1/0)switch(t){case`lowercase`:return`-.inf`;case`uppercase`:return`-.INF`;case`camelcase`:return`-.Inf`}else if(n.isNegativeZero(e))return`-0.0`;let r=e.toString(10);return c.test(r)?r.replace(`e`,`.e`):r}function u(e){return Object.prototype.toString.call(e)===`[object Number]`&&(e%1!=0||n.isNegativeZero(e))}t.exports=new r(`tag:yaml.org,2002:float`,{kind:`scalar`,resolve:o,construct:s,predicate:u,represent:l,defaultStyle:`lowercase`})})),F=E(((e,t)=>{t.exports=M().extend({implicit:[me(),N(),he(),P()]})})),I=E(((e,t)=>{t.exports=F()})),ge=E(((e,t)=>{var n=k(),r=RegExp(`^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$`),i=RegExp(`^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$`);function a(e){return e===null?!1:r.exec(e)!==null||i.exec(e)!==null}function o(e){let t=0,n=null,a=r.exec(e);if(a===null&&(a=i.exec(e)),a===null)throw Error(`Date resolve error`);let o=+a[1],s=a[2]-1,c=+a[3];if(!a[4])return new Date(Date.UTC(o,s,c));let l=+a[4],u=+a[5],d=+a[6];if(a[7]){for(t=a[7].slice(0,3);t.length<3;)t+=`0`;t=+t}if(a[9]){let e=+a[10],t=+(a[11]||0);n=(e*60+t)*6e4,a[9]===`-`&&(n=-n)}let f=new Date(Date.UTC(o,s,c,l,u,d,t));return n&&f.setTime(f.getTime()-n),f}function s(e){return e.toISOString()}t.exports=new n(`tag:yaml.org,2002:timestamp`,{kind:`scalar`,resolve:a,construct:o,instanceOf:Date,represent:s})})),_e=E(((e,t)=>{var n=k();function r(e){return e===`<<`||e===null}t.exports=new n(`tag:yaml.org,2002:merge`,{kind:`scalar`,resolve:r})})),ve=E(((e,t)=>{var n=k(),r=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
|
|
9
|
-
\r`;function i(e){if(e===null)return!1;let t=0,n=e.length,i=r;for(let r=0;r<n;r++){let n=i.indexOf(e.charAt(r));if(!(n>64)){if(n<0)return!1;t+=6}}return t%8==0}function a(e){let t=e.replace(/[\r\n=]/g,``),n=t.length,i=r,a=0,o=[];for(let e=0;e<n;e++)e%4==0&&e&&(o.push(a>>16&255),o.push(a>>8&255),o.push(a&255)),a=a<<6|i.indexOf(t.charAt(e));let s=n%4*6;return s===0?(o.push(a>>16&255),o.push(a>>8&255),o.push(a&255)):s===18?(o.push(a>>10&255),o.push(a>>2&255)):s===12&&o.push(a>>4&255),new Uint8Array(o)}function o(e){let t=``,n=0,i=e.length,a=r;for(let r=0;r<i;r++)r%3==0&&r&&(t+=a[n>>18&63],t+=a[n>>12&63],t+=a[n>>6&63],t+=a[n&63]),n=(n<<8)+e[r];let o=i%3;return o===0?(t+=a[n>>18&63],t+=a[n>>12&63],t+=a[n>>6&63],t+=a[n&63]):o===2?(t+=a[n>>10&63],t+=a[n>>4&63],t+=a[n<<2&63],t+=a[64]):o===1&&(t+=a[n>>2&63],t+=a[n<<4&63],t+=a[64],t+=a[64]),t}function s(e){return Object.prototype.toString.call(e)===`[object Uint8Array]`}t.exports=new n(`tag:yaml.org,2002:binary`,{kind:`scalar`,resolve:i,construct:a,predicate:s,represent:o})})),ye=E(((e,t)=>{var n=k(),r=Object.prototype.hasOwnProperty,i=Object.prototype.toString;function a(e){if(e===null)return!0;let t={},n=e;for(let e=0,a=n.length;e<a;e+=1){let a=n[e],o=!1;if(i.call(a)!==`[object Object]`)return!1;let s;for(s in a)if(r.call(a,s)){if(!o)o=!0;else return!1}if(!o||r.call(t,s))return!1;Object.defineProperty(t,s,{value:!0})}return!0}function o(e){return e===null?[]:e}t.exports=new n(`tag:yaml.org,2002:omap`,{kind:`sequence`,resolve:a,construct:o})})),L=E(((e,t)=>{var n=k(),r=Object.prototype.toString;function i(e){if(e===null)return!0;let t=e,n=Array(t.length);for(let e=0,i=t.length;e<i;e+=1){let i=t[e];if(r.call(i)!==`[object Object]`)return!1;let a=Object.keys(i);if(a.length!==1)return!1;n[e]=[a[0],i[a[0]]]}return!0}function a(e){if(e===null)return[];let t=e,n=Array(t.length);for(let e=0,r=t.length;e<r;e+=1){let r=t[e],i=Object.keys(r);n[e]=[i[0],r[i[0]]]}return n}t.exports=new n(`tag:yaml.org,2002:pairs`,{kind:`sequence`,resolve:i,construct:a})})),be=E(((e,t)=>{var n=k(),r=Object.prototype.hasOwnProperty;function i(e){if(e===null)return!0;let t=e;for(let e in t)if(r.call(t,e)&&t[e]!==null)return!1;return!0}function a(e){return e===null?{}:e}t.exports=new n(`tag:yaml.org,2002:set`,{kind:`mapping`,resolve:i,construct:a})})),xe=E(((e,t)=>{t.exports=I().extend({implicit:[ge(),_e()],explicit:[ve(),ye(),L(),be()]})})),Se=E(((e,t)=>{var n=le(),r=ue(),i=de(),a=xe(),o=Object.prototype.hasOwnProperty,s=1,c=2,l=3,u=4,d=1,f=2,p=3,m=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,h=/[\x85\u2028\u2029]/,g=/[,\[\]{}]/,_=/^(?:!|!!|![0-9A-Za-z-]+!)$/,v=/^(?:!|[^,\[\]{}])(?:%[0-9a-f]{2}|[0-9a-z\-#;/?:@&=+$,_.!~*'()\[\]])*$/i;function y(e){return Object.prototype.toString.call(e)}function b(e){return e===10||e===13}function x(e){return e===9||e===32}function S(e){return e===9||e===32||e===10||e===13}function C(e){return e===44||e===91||e===93||e===123||e===125}function w(e){if(e>=48&&e<=57)return e-48;let t=e|32;return t>=97&&t<=102?t-97+10:-1}function ee(e){return e===120?2:e===117?4:e===85?8:0}function te(e){return e>=48&&e<=57?e-48:-1}function ne(e){switch(e){case 48:return`\0`;case 97:return`\x07`;case 98:return`\b`;case 116:return` `;case 9:return` `;case 110:return`
|
|
10
|
-
`;case 118:return`\v`;case 102:return`\f`;case 114:return`\r`;case 101:return`\x1B`;case 32:return` `;case 34:return`"`;case 47:return`/`;case 92:return`\\`;case 78:return`
`;case 95:return`\xA0`;case 76:return`\u2028`;case 80:return`\u2029`;default:return``}}function re(e){return e<=65535?String.fromCharCode(e):String.fromCharCode((e-65536>>10)+55296,(e-65536&1023)+56320)}function ie(e,t,n){t===`__proto__`?Object.defineProperty(e,t,{configurable:!0,enumerable:!0,writable:!0,value:n}):e[t]=n}var ae=Array(256),oe=Array(256);for(let e=0;e<256;e++)ae[e]=+!!ne(e),oe[e]=ne(e);function T(e,t){this.input=e,this.filename=t.filename||null,this.schema=t.schema||a,this.onWarning=t.onWarning||null,this.legacy=t.legacy||!1,this.json=t.json||!1,this.listener=t.listener||null,this.maxDepth=typeof t.maxDepth==`number`?t.maxDepth:100,this.maxTotalMergeKeys=typeof t.maxTotalMergeKeys==`number`?t.maxTotalMergeKeys:1e4,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=e.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.depth=0,this.totalMergeKeys=0,this.firstTabInLine=-1,this.documents=[],this.anchorMapTransactions=[]}function E(e,t){let n={name:e.filename,buffer:e.input.slice(0,-1),position:e.position,line:e.line,column:e.position-e.lineStart};return n.snippet=i(n),new r(t,n)}function D(e,t){throw E(e,t)}function se(e,t){e.onWarning&&e.onWarning.call(null,E(e,t))}function O(e,t,n){let r=e.anchorMapTransactions;if(r.length!==0){let n=r[r.length-1];o.call(n,t)||(n[t]={existed:o.call(e.anchorMap,t),value:e.anchorMap[t]})}e.anchorMap[t]=n}function ce(e){e.anchorMapTransactions.push(Object.create(null))}function k(e){let t=e.anchorMapTransactions.pop(),n=e.anchorMapTransactions;if(n.length===0)return;let r=n[n.length-1],i=Object.keys(t);for(let e=0,n=i.length;e<n;e+=1){let n=i[e];o.call(r,n)||(r[n]=t[n])}}function fe(e){let t=e.anchorMapTransactions.pop(),n=Object.keys(t);for(let r=n.length-1;r>=0;--r){let i=t[n[r]];i.existed?e.anchorMap[n[r]]=i.value:delete e.anchorMap[n[r]]}}function A(e){return{position:e.position,line:e.line,lineStart:e.lineStart,lineIndent:e.lineIndent,firstTabInLine:e.firstTabInLine,tag:e.tag,anchor:e.anchor,kind:e.kind,result:e.result}}function pe(e,t){e.position=t.position,e.line=t.line,e.lineStart=t.lineStart,e.lineIndent=t.lineIndent,e.firstTabInLine=t.firstTabInLine,e.tag=t.tag,e.anchor=t.anchor,e.kind=t.kind,e.result=t.result}var j={YAML:function(e,t,n){e.version!==null&&D(e,`duplication of %YAML directive`),n.length!==1&&D(e,`YAML directive accepts exactly one argument`);let r=/^([0-9]+)\.([0-9]+)$/.exec(n[0]);r===null&&D(e,`ill-formed argument of the YAML directive`);let i=parseInt(r[1],10),a=parseInt(r[2],10);i!==1&&D(e,`unacceptable YAML version of the document`),e.version=n[0],e.checkLineBreaks=a<2,a!==1&&a!==2&&se(e,`unsupported YAML version of the document`)},TAG:function(e,t,n){let r;n.length!==2&&D(e,`TAG directive accepts exactly two arguments`);let i=n[0];r=n[1],_.test(i)||D(e,`ill-formed tag handle (first argument) of the TAG directive`),o.call(e.tagMap,i)&&D(e,`there is a previously declared suffix for "`+i+`" tag handle`),v.test(r)||D(e,`ill-formed tag prefix (second argument) of the TAG directive`);try{r=decodeURIComponent(r)}catch{D(e,`tag prefix is malformed: `+r)}e.tagMap[i]=r}};function M(e,t,n,r){if(t<n){let i=e.input.slice(t,n);if(r)for(let t=0,n=i.length;t<n;t+=1){let n=i.charCodeAt(t);n===9||n>=32&&n<=1114111||D(e,`expected valid JSON character`)}else m.test(i)&&D(e,`the stream contains non-printable characters`);e.result+=i}}function me(e,t,r,i){n.isObject(r)||D(e,`cannot merge mappings; the provided source object is unacceptable`);let a=Object.keys(r);for(let n=0,s=a.length;n<s;n+=1){let s=a[n];e.maxTotalMergeKeys!==-1&&++e.totalMergeKeys>e.maxTotalMergeKeys&&D(e,`merge keys exceeded maxTotalMergeKeys (`+e.maxTotalMergeKeys+`)`),o.call(t,s)||(ie(t,s,r[s]),i[s]=!0)}}function N(e,t,n,r,i,a,s,c,l){if(Array.isArray(i)){i=Array.prototype.slice.call(i);for(let t=0,n=i.length;t<n;t+=1)Array.isArray(i[t])&&D(e,`nested arrays are not supported inside keys`),typeof i==`object`&&y(i[t])===`[object Object]`&&(i[t]=`[object Object]`)}if(typeof i==`object`&&y(i)===`[object Object]`&&(i=`[object Object]`),i=String(i),t===null&&(t={}),r===`tag:yaml.org,2002:merge`){if(Array.isArray(a))for(let r=0,i=a.length;r<i;r+=1)me(e,t,a[r],n);else me(e,t,a,n)}else!e.json&&!o.call(n,i)&&o.call(t,i)&&(e.line=s||e.line,e.lineStart=c||e.lineStart,e.position=l||e.position,D(e,`duplicated mapping key`)),ie(t,i,a),delete n[i];return t}function he(e){let t=e.input.charCodeAt(e.position);t===10?e.position++:t===13?(e.position++,e.input.charCodeAt(e.position)===10&&e.position++):D(e,`a line break is expected`),e.line+=1,e.lineStart=e.position,e.firstTabInLine=-1}function P(e,t,n){let r=0,i=e.input.charCodeAt(e.position);for(;i!==0;){for(;x(i);)i===9&&e.firstTabInLine===-1&&(e.firstTabInLine=e.position),i=e.input.charCodeAt(++e.position);if(t&&i===35)do i=e.input.charCodeAt(++e.position);while(i!==10&&i!==13&&i!==0);if(b(i))for(he(e),i=e.input.charCodeAt(e.position),r++,e.lineIndent=0;i===32;)e.lineIndent++,i=e.input.charCodeAt(++e.position);else break}return n!==-1&&r!==0&&e.lineIndent<n&&se(e,`deficient indentation`),r}function F(e){let t=e.position,n=e.input.charCodeAt(t);return!!((n===45||n===46)&&n===e.input.charCodeAt(t+1)&&n===e.input.charCodeAt(t+2)&&(t+=3,n=e.input.charCodeAt(t),n===0||S(n)))}function I(e,t){t===1?e.result+=` `:t>1&&(e.result+=n.repeat(`
|
|
11
|
-
`,t-1))}function ge(e,t,n){let r,i,a,o,s,c,l=e.kind,u=e.result,d=e.input.charCodeAt(e.position);if(S(d)||C(d)||d===35||d===38||d===42||d===33||d===124||d===62||d===39||d===34||d===37||d===64||d===96)return!1;if(d===63||d===45){let t=e.input.charCodeAt(e.position+1);if(S(t)||n&&C(t))return!1}for(e.kind=`scalar`,e.result=``,r=i=e.position,a=!1;d!==0;){if(d===58){let t=e.input.charCodeAt(e.position+1);if(S(t)||n&&C(t))break}else if(d===35){if(S(e.input.charCodeAt(e.position-1)))break}else if(e.position===e.lineStart&&F(e)||n&&C(d))break;else if(b(d)){if(o=e.line,s=e.lineStart,c=e.lineIndent,P(e,!1,-1),e.lineIndent>=t){a=!0,d=e.input.charCodeAt(e.position);continue}e.position=i,e.line=o,e.lineStart=s,e.lineIndent=c;break}a&&=(M(e,r,i,!1),I(e,e.line-o),r=i=e.position,!1),x(d)||(i=e.position+1),d=e.input.charCodeAt(++e.position)}return M(e,r,i,!1),e.result?!0:(e.kind=l,e.result=u,!1)}function _e(e,t){let n,r,i=e.input.charCodeAt(e.position);if(i!==39)return!1;for(e.kind=`scalar`,e.result=``,e.position++,n=r=e.position;(i=e.input.charCodeAt(e.position))!==0;)if(i===39){if(M(e,n,e.position,!0),i=e.input.charCodeAt(++e.position),i===39)n=e.position,e.position++,r=e.position;else return!0}else b(i)?(M(e,n,r,!0),I(e,P(e,!1,t)),n=r=e.position):e.position===e.lineStart&&F(e)?D(e,`unexpected end of the document within a single quoted scalar`):(e.position++,x(i)||(r=e.position));D(e,`unexpected end of the stream within a single quoted scalar`)}function ve(e,t){let n,r,i,a=e.input.charCodeAt(e.position);if(a!==34)return!1;for(e.kind=`scalar`,e.result=``,e.position++,n=r=e.position;(a=e.input.charCodeAt(e.position))!==0;)if(a===34)return M(e,n,e.position,!0),e.position++,!0;else if(a===92){if(M(e,n,e.position,!0),a=e.input.charCodeAt(++e.position),b(a))P(e,!1,t);else if(a<256&&ae[a])e.result+=oe[a],e.position++;else if((i=ee(a))>0){let t=i,n=0;for(;t>0;t--)a=e.input.charCodeAt(++e.position),(i=w(a))>=0?n=(n<<4)+i:D(e,`expected hexadecimal character`);e.result+=re(n),e.position++}else D(e,`unknown escape sequence`);n=r=e.position}else b(a)?(M(e,n,r,!0),I(e,P(e,!1,t)),n=r=e.position):e.position===e.lineStart&&F(e)?D(e,`unexpected end of the document within a double quoted scalar`):(e.position++,x(a)||(r=e.position));D(e,`unexpected end of the stream within a double quoted scalar`)}function ye(e,t){let n=!0,r,i,a,o=e.tag,c,l=e.anchor,u,d,f,p,m=Object.create(null),h,g,_,v=e.input.charCodeAt(e.position);if(v===91)u=93,p=!1,c=[];else if(v===123)u=125,p=!0,c={};else return!1;for(e.anchor!==null&&O(e,e.anchor,c),v=e.input.charCodeAt(++e.position);v!==0;){if(P(e,!0,t),v=e.input.charCodeAt(e.position),v===u)return e.position++,e.tag=o,e.anchor=l,e.kind=p?`mapping`:`sequence`,e.result=c,!0;n?v===44&&D(e,`expected the node content, but found ','`):D(e,`missed comma between flow collection entries`),g=h=_=null,d=f=!1,v===63&&S(e.input.charCodeAt(e.position+1))&&(d=f=!0,e.position++,P(e,!0,t)),r=e.line,i=e.lineStart,a=e.position,R(e,t,s,!1,!0),g=e.tag,h=e.result,P(e,!0,t),v=e.input.charCodeAt(e.position),(f||e.line===r)&&v===58&&(d=!0,v=e.input.charCodeAt(++e.position),P(e,!0,t),R(e,t,s,!1,!0),_=e.result),p?N(e,c,m,g,h,_,r,i,a):d?c.push(N(e,null,m,g,h,_,r,i,a)):c.push(h),P(e,!0,t),v=e.input.charCodeAt(e.position),v===44?(n=!0,v=e.input.charCodeAt(++e.position)):n=!1}D(e,`unexpected end of the stream within a flow collection`)}function L(e,t){let r,i=d,a=!1,o=!1,s=t,c=0,l=!1,u,m=e.input.charCodeAt(e.position);if(m===124)r=!1;else if(m===62)r=!0;else return!1;for(e.kind=`scalar`,e.result=``;m!==0;)if(m=e.input.charCodeAt(++e.position),m===43||m===45)d===i?i=m===43?p:f:D(e,`repeat of a chomping mode identifier`);else if((u=te(m))>=0)u===0?D(e,`bad explicit indentation width of a block scalar; it cannot be less than one`):o?D(e,`repeat of an indentation width identifier`):(s=t+u-1,o=!0);else break;if(x(m)){do m=e.input.charCodeAt(++e.position);while(x(m));if(m===35)do m=e.input.charCodeAt(++e.position);while(!b(m)&&m!==0)}for(;m!==0;){for(he(e),e.lineIndent=0,m=e.input.charCodeAt(e.position);(!o||e.lineIndent<s)&&m===32;)e.lineIndent++,m=e.input.charCodeAt(++e.position);if(!o&&e.lineIndent>s&&(s=e.lineIndent),b(m)){c++;continue}if(!o&&s===0&&D(e,`missing indentation for block scalar`),e.lineIndent<s){i===p?e.result+=n.repeat(`
|
|
12
|
-
`,a?1+c:c):i===d&&a&&(e.result+=`
|
|
13
|
-
`);break}r?x(m)?(l=!0,e.result+=n.repeat(`
|
|
14
|
-
`,a?1+c:c)):l?(l=!1,e.result+=n.repeat(`
|
|
15
|
-
`,c+1)):c===0?a&&(e.result+=` `):e.result+=n.repeat(`
|
|
16
|
-
`,c):e.result+=n.repeat(`
|
|
17
|
-
`,a?1+c:c),a=!0,o=!0,c=0;let t=e.position;for(;!b(m)&&m!==0;)m=e.input.charCodeAt(++e.position);M(e,t,e.position,!1)}return!0}function be(e,t){let n=e.tag,r=e.anchor,i=[],a=!1;if(e.firstTabInLine!==-1)return!1;e.anchor!==null&&O(e,e.anchor,i);let o=e.input.charCodeAt(e.position);for(;o!==0&&(e.firstTabInLine!==-1&&(e.position=e.firstTabInLine,D(e,`tab characters must not be used in indentation`)),!(o!==45||!S(e.input.charCodeAt(e.position+1))));){if(a=!0,e.position++,P(e,!0,-1)&&e.lineIndent<=t){i.push(null),o=e.input.charCodeAt(e.position);continue}let n=e.line;if(R(e,t,l,!1,!0),i.push(e.result),P(e,!0,-1),o=e.input.charCodeAt(e.position),(e.line===n||e.lineIndent>t)&&o!==0)D(e,`bad indentation of a sequence entry`);else if(e.lineIndent<t)break}return a?(e.tag=n,e.anchor=r,e.kind=`sequence`,e.result=i,!0):!1}function Se(e,t,n){let r,i,a,o,s=e.tag,l=e.anchor,d={},f=Object.create(null),p=null,m=null,h=null,g=!1,_=!1;if(e.firstTabInLine!==-1)return!1;e.anchor!==null&&O(e,e.anchor,d);let v=e.input.charCodeAt(e.position);for(;v!==0;){!g&&e.firstTabInLine!==-1&&(e.position=e.firstTabInLine,D(e,`tab characters must not be used in indentation`));let y=e.input.charCodeAt(e.position+1),b=e.line;if((v===63||v===58)&&S(y))v===63?(g&&(N(e,d,f,p,m,null,i,a,o),p=m=h=null),_=!0,g=!0,r=!0):g?(g=!1,r=!0):D(e,`incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line`),e.position+=1,v=y;else{if(i=e.line,a=e.lineStart,o=e.position,!R(e,n,c,!1,!0))break;if(e.line===b){for(v=e.input.charCodeAt(e.position);x(v);)v=e.input.charCodeAt(++e.position);if(v===58)v=e.input.charCodeAt(++e.position),S(v)||D(e,`a whitespace character is expected after the key-value separator within a block mapping`),g&&(N(e,d,f,p,m,null,i,a,o),p=m=h=null),_=!0,g=!1,r=!1,p=e.tag,m=e.result;else if(_)D(e,`can not read an implicit mapping pair; a colon is missed`);else return e.tag=s,e.anchor=l,!0}else if(_)D(e,`can not read a block mapping entry; a multiline key may not be an implicit key`);else return e.tag=s,e.anchor=l,!0}if((e.line===b||e.lineIndent>t)&&(g&&(i=e.line,a=e.lineStart,o=e.position),R(e,t,u,!0,r)&&(g?m=e.result:h=e.result),g||(N(e,d,f,p,m,h,i,a,o),p=m=h=null),P(e,!0,-1),v=e.input.charCodeAt(e.position)),(e.line===b||e.lineIndent>t)&&v!==0)D(e,`bad indentation of a mapping entry`);else if(e.lineIndent<t)break}return g&&N(e,d,f,p,m,null,i,a,o),_&&(e.tag=s,e.anchor=l,e.kind=`mapping`,e.result=d),_}function Ce(e){let t=!1,n=!1,r,i,a=e.input.charCodeAt(e.position);if(a!==33)return!1;e.tag!==null&&D(e,`duplication of a tag property`),a=e.input.charCodeAt(++e.position),a===60?(t=!0,a=e.input.charCodeAt(++e.position)):a===33?(n=!0,r=`!!`,a=e.input.charCodeAt(++e.position)):r=`!`;let s=e.position;if(t){do a=e.input.charCodeAt(++e.position);while(a!==0&&a!==62);e.position<e.length?(i=e.input.slice(s,e.position),a=e.input.charCodeAt(++e.position)):D(e,`unexpected end of the stream within a verbatim tag`)}else{for(;a!==0&&!S(a);)a===33&&(n?D(e,`tag suffix cannot contain exclamation marks`):(r=e.input.slice(s-1,e.position+1),_.test(r)||D(e,`named tag handle cannot contain such characters`),n=!0,s=e.position+1)),a=e.input.charCodeAt(++e.position);i=e.input.slice(s,e.position),g.test(i)&&D(e,`tag suffix cannot contain flow indicator characters`)}i&&!v.test(i)&&D(e,`tag name cannot contain such characters: `+i);try{i=decodeURIComponent(i)}catch{D(e,`tag name is malformed: `+i)}return t?e.tag=i:o.call(e.tagMap,r)?e.tag=e.tagMap[r]+i:r===`!`?e.tag=`!`+i:r===`!!`?e.tag=`tag:yaml.org,2002:`+i:D(e,`undeclared tag handle "`+r+`"`),!0}function we(e){let t=e.input.charCodeAt(e.position);if(t!==38)return!1;e.anchor!==null&&D(e,`duplication of an anchor property`),t=e.input.charCodeAt(++e.position);let n=e.position;for(;t!==0&&!S(t)&&!C(t);)t=e.input.charCodeAt(++e.position);return e.position===n&&D(e,`name of an anchor node must contain at least one character`),e.anchor=e.input.slice(n,e.position),!0}function Te(e){let t=e.input.charCodeAt(e.position);if(t!==42)return!1;t=e.input.charCodeAt(++e.position);let n=e.position;for(;t!==0&&!S(t)&&!C(t);)t=e.input.charCodeAt(++e.position);e.position===n&&D(e,`name of an alias node must contain at least one character`);let r=e.input.slice(n,e.position);return o.call(e.anchorMap,r)||D(e,`unidentified alias "`+r+`"`),e.result=e.anchorMap[r],P(e,!0,-1),!0}function Ee(e,t,n,r){let i=A(e);return ce(e),pe(e,t),e.tag=null,e.anchor=null,e.kind=null,e.result=null,Se(e,n,r)&&e.kind===`mapping`?(k(e),!0):(fe(e),pe(e,i),!1)}function R(e,t,n,r,i){let a,d,f=1,p=!1,m=!1,h=null,g,_,v;e.depth>=e.maxDepth&&D(e,`nesting exceeded maxDepth (`+e.maxDepth+`)`),e.depth+=1,e.listener!==null&&e.listener(`open`,e),e.tag=null,e.anchor=null,e.kind=null,e.result=null;let y=a=d=u===n||l===n;if(r&&P(e,!0,-1)&&(p=!0,e.lineIndent>t?f=1:e.lineIndent===t?f=0:e.lineIndent<t&&(f=-1)),f===1)for(;;){let n=e.input.charCodeAt(e.position),r=A(e);if(p&&(n===33&&e.tag!==null||n===38&&e.anchor!==null)||!Ce(e)&&!we(e))break;h===null&&(h=r),P(e,!0,-1)?(p=!0,d=y,e.lineIndent>t?f=1:e.lineIndent===t?f=0:e.lineIndent<t&&(f=-1)):d=!1}if(d&&=p||i,f===1||u===n){if(_=s===n||c===n?t:t+1,v=e.position-e.lineStart,f===1){if(d&&(be(e,v)||Se(e,v,_))||ye(e,_))m=!0;else{let t=e.input.charCodeAt(e.position);h!==null&&y&&!d&&t!==124&&t!==62&&Ee(e,h,h.position-h.lineStart,_)||a&&L(e,_)||_e(e,_)||ve(e,_)?m=!0:Te(e)?(m=!0,(e.tag!==null||e.anchor!==null)&&D(e,`alias node should not have any properties`)):ge(e,_,s===n)&&(m=!0,e.tag===null&&(e.tag=`?`)),e.anchor!==null&&O(e,e.anchor,e.result)}}else f===0&&(m=d&&be(e,v))}if(e.tag===null)e.anchor!==null&&O(e,e.anchor,e.result);else if(e.tag===`?`){e.result!==null&&e.kind!==`scalar`&&D(e,`unacceptable node kind for !<?> tag; it should be "scalar", not "`+e.kind+`"`);for(let t=0,n=e.implicitTypes.length;t<n;t+=1)if(g=e.implicitTypes[t],g.resolve(e.result)){e.result=g.construct(e.result),e.tag=g.tag,e.anchor!==null&&O(e,e.anchor,e.result);break}}else if(e.tag!==`!`){if(o.call(e.typeMap[e.kind||`fallback`],e.tag))g=e.typeMap[e.kind||`fallback`][e.tag];else{g=null;let t=e.typeMap.multi[e.kind||`fallback`];for(let n=0,r=t.length;n<r;n+=1)if(e.tag.slice(0,t[n].tag.length)===t[n].tag){g=t[n];break}}g||D(e,`unknown tag !<`+e.tag+`>`),e.result!==null&&g.kind!==e.kind&&D(e,`unacceptable node kind for !<`+e.tag+`> tag; it should be "`+g.kind+`", not "`+e.kind+`"`),g.resolve(e.result,e.tag)?(e.result=g.construct(e.result,e.tag),e.anchor!==null&&O(e,e.anchor,e.result)):D(e,`cannot resolve a node with !<`+e.tag+`> explicit tag`)}return e.listener!==null&&e.listener(`close`,e),--e.depth,e.tag!==null||e.anchor!==null||m}function De(e){let t=e.position,n=!1,r;for(e.version=null,e.checkLineBreaks=e.legacy,e.tagMap=Object.create(null),e.anchorMap=Object.create(null);(r=e.input.charCodeAt(e.position))!==0&&(P(e,!0,-1),r=e.input.charCodeAt(e.position),!(e.lineIndent>0||r!==37));){n=!0,r=e.input.charCodeAt(++e.position);let t=e.position;for(;r!==0&&!S(r);)r=e.input.charCodeAt(++e.position);let i=e.input.slice(t,e.position),a=[];for(i.length<1&&D(e,`directive name must not be less than one character in length`);r!==0;){for(;x(r);)r=e.input.charCodeAt(++e.position);if(r===35){do r=e.input.charCodeAt(++e.position);while(r!==0&&!b(r));break}if(b(r))break;for(t=e.position;r!==0&&!S(r);)r=e.input.charCodeAt(++e.position);a.push(e.input.slice(t,e.position))}r!==0&&he(e),o.call(j,i)?j[i](e,i,a):se(e,`unknown document directive "`+i+`"`)}if(P(e,!0,-1),e.lineIndent===0&&e.input.charCodeAt(e.position)===45&&e.input.charCodeAt(e.position+1)===45&&e.input.charCodeAt(e.position+2)===45?(e.position+=3,P(e,!0,-1)):n&&D(e,`directives end mark is expected`),R(e,e.lineIndent-1,u,!1,!0),P(e,!0,-1),e.checkLineBreaks&&h.test(e.input.slice(t,e.position))&&se(e,`non-ASCII line breaks are interpreted as content`),e.documents.push(e.result),e.position===e.lineStart&&F(e)){e.input.charCodeAt(e.position)===46&&(e.position+=3,P(e,!0,-1));return}e.position<e.length-1&&D(e,`end of the stream or a document separator is expected`)}function Oe(e,t){e=String(e),t||={},e.length!==0&&(e.charCodeAt(e.length-1)!==10&&e.charCodeAt(e.length-1)!==13&&(e+=`
|
|
18
|
-
`),e.charCodeAt(0)===65279&&(e=e.slice(1)));let n=new T(e,t),r=e.indexOf(`\0`);for(r!==-1&&(n.position=r,D(n,`null byte is not allowed in input`)),n.input+=`\0`;n.input.charCodeAt(n.position)===32;)n.lineIndent+=1,n.position+=1;for(;n.position<n.length-1;)De(n);return n.documents}function ke(e,t,n){typeof t==`object`&&t&&n===void 0&&(n=t,t=null);let r=Oe(e,n);if(typeof t!=`function`)return r;for(let e=0,n=r.length;e<n;e+=1)t(r[e])}function Ae(e,t){let n=Oe(e,t);if(n.length!==0){if(n.length===1)return n[0];throw new r(`expected a single document in the stream, but found more`)}}t.exports.loadAll=ke,t.exports.load=Ae})),Ce=E(((e,t)=>{var n=le(),r=ue(),i=xe(),a=Object.prototype.toString,o=Object.prototype.hasOwnProperty,s=65279,c=9,l=10,u=13,d=32,f=33,p=34,m=35,h=37,g=38,_=39,v=42,y=44,b=45,x=58,S=61,C=62,w=63,ee=64,te=91,ne=93,re=96,ie=123,ae=124,oe=125,T={};T[0]=`\\0`,T[7]=`\\a`,T[8]=`\\b`,T[9]=`\\t`,T[10]=`\\n`,T[11]=`\\v`,T[12]=`\\f`,T[13]=`\\r`,T[27]=`\\e`,T[34]=`\\"`,T[92]=`\\\\`,T[133]=`\\N`,T[160]=`\\_`,T[8232]=`\\L`,T[8233]=`\\P`;var E=[`y`,`Y`,`yes`,`Yes`,`YES`,`on`,`On`,`ON`,`n`,`N`,`no`,`No`,`NO`,`off`,`Off`,`OFF`],D=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;function se(e,t){if(t===null)return{};let n={},r=Object.keys(t);for(let i=0,a=r.length;i<a;i+=1){let a=r[i],s=String(t[a]);a.slice(0,2)===`!!`&&(a=`tag:yaml.org,2002:`+a.slice(2));let c=e.compiledTypeMap.fallback[a];c&&o.call(c.styleAliases,s)&&(s=c.styleAliases[s]),n[a]=s}return n}function O(e){let t,i,a=e.toString(16).toUpperCase();if(e<=255)t=`x`,i=2;else if(e<=65535)t=`u`,i=4;else if(e<=4294967295)t=`U`,i=8;else throw new r(`code point within a string may not be greater than 0xFFFFFFFF`);return`\\`+t+n.repeat(`0`,i-a.length)+a}var ce=1,de=2;function k(e){this.schema=e.schema||i,this.indent=Math.max(1,e.indent||2),this.noArrayIndent=e.noArrayIndent||!1,this.skipInvalid=e.skipInvalid||!1,this.flowLevel=n.isNothing(e.flowLevel)?-1:e.flowLevel,this.styleMap=se(this.schema,e.styles||null),this.sortKeys=e.sortKeys||!1,this.lineWidth=e.lineWidth||80,this.noRefs=e.noRefs||!1,this.noCompatMode=e.noCompatMode||!1,this.condenseFlow=e.condenseFlow||!1,this.quotingType=e.quotingType===`"`?de:ce,this.forceQuotes=e.forceQuotes||!1,this.replacer=typeof e.replacer==`function`?e.replacer:null,this.implicitTypes=this.schema.compiledImplicit,this.explicitTypes=this.schema.compiledExplicit,this.tag=null,this.result=``,this.duplicates=[],this.usedDuplicates=null}function fe(e,t){let r=n.repeat(` `,t),i=0,a=``,o=e.length;for(;i<o;){let t,n=e.indexOf(`
|
|
19
|
-
`,i);n===-1?(t=e.slice(i),i=o):(t=e.slice(i,n+1),i=n+1),t.length&&t!==`
|
|
20
|
-
`&&(a+=r),a+=t}return a}function A(e,t){return`
|
|
21
|
-
`+n.repeat(` `,e.indent*t)}function pe(e,t){for(let n=0,r=e.implicitTypes.length;n<r;n+=1)if(e.implicitTypes[n].resolve(t))return!0;return!1}function j(e){return e===d||e===c}function M(e){return e>=32&&e<=126||e>=161&&e<=55295&&e!==8232&&e!==8233||e>=57344&&e<=65533&&e!==s||e>=65536&&e<=1114111}function me(e){return M(e)&&e!==s&&e!==u&&e!==l}function N(e,t,n){let r=me(e),i=r&&!j(e);return(n?r:r&&e!==y&&e!==te&&e!==ne&&e!==ie&&e!==oe)&&e!==m&&!(t===x&&!i)||me(t)&&!j(t)&&e===m||t===x&&i}function he(e){return M(e)&&e!==s&&!j(e)&&e!==b&&e!==w&&e!==x&&e!==y&&e!==te&&e!==ne&&e!==ie&&e!==oe&&e!==m&&e!==g&&e!==v&&e!==f&&e!==ae&&e!==S&&e!==C&&e!==_&&e!==p&&e!==h&&e!==ee&&e!==re}function P(e){return!j(e)&&e!==x}function F(e,t){let n=e.charCodeAt(t),r;return n>=55296&&n<=56319&&t+1<e.length&&(r=e.charCodeAt(t+1),r>=56320&&r<=57343)?(n-55296)*1024+r-56320+65536:n}function I(e){return/^\n* /.test(e)}var ge=1,_e=2,ve=3,ye=4,L=5;function be(e,t,n,r,i,a,o,s){let c,u=0,d=null,f=!1,p=!1,m=r!==-1,h=-1,g=he(F(e,0))&&P(F(e,e.length-1));if(t||o)for(c=0;c<e.length;u>=65536?c+=2:c++){if(u=F(e,c),!M(u))return L;g&&=N(u,d,s),d=u}else{for(c=0;c<e.length;u>=65536?c+=2:c++){if(u=F(e,c),u===l)f=!0,m&&(p||=c-h-1>r&&e[h+1]!==` `,h=c);else if(!M(u))return L;g&&=N(u,d,s),d=u}p||=m&&c-h-1>r&&e[h+1]!==` `}return!f&&!p?g&&!o&&!i(e)?ge:a===de?L:_e:n>9&&I(e)?L:o?a===de?L:_e:p?ye:ve}function Se(e,t,n,i,a){e.dump=function(){if(t.length===0)return e.quotingType===de?`""`:`''`;if(!e.noCompatMode&&(E.indexOf(t)!==-1||D.test(t)))return e.quotingType===de?`"`+t+`"`:`'`+t+`'`;let o=e.indent*Math.max(1,n),s=e.lineWidth===-1?-1:Math.max(Math.min(e.lineWidth,40),e.lineWidth-o),c=i||e.flowLevel>-1&&n>=e.flowLevel;function l(t){return pe(e,t)}switch(be(t,c,e.indent,s,l,e.quotingType,e.forceQuotes&&!i,a)){case ge:return t;case _e:return`'`+t.replace(/'/g,`''`)+`'`;case ve:return`|`+Ce(t,e.indent)+we(fe(t,o));case ye:return`>`+Ce(t,e.indent)+we(fe(Te(t,s),o));case L:return`"`+R(t,s)+`"`;default:throw new r(`impossible error: invalid scalar style`)}}()}function Ce(e,t){let n=I(e)?String(t):``,r=e[e.length-1]===`
|
|
22
|
-
`;return n+(r&&(e[e.length-2]===`
|
|
23
|
-
`||e===`
|
|
24
|
-
`)?`+`:r?``:`-`)+`
|
|
25
|
-
`}function we(e){return e[e.length-1]===`
|
|
26
|
-
`?e.slice(0,-1):e}function Te(e,t){let n=/(\n+)([^\n]*)/g,r=function(){let r=e.indexOf(`
|
|
27
|
-
`);return r=r===-1?e.length:r,n.lastIndex=r,Ee(e.slice(0,r),t)}(),i=e[0]===`
|
|
28
|
-
`||e[0]===` `,a,o;for(;o=n.exec(e);){let e=o[1],n=o[2];a=n[0]===` `,r+=e+(!i&&!a&&n!==``?`
|
|
29
|
-
`:``)+Ee(n,t),i=a}return r}function Ee(e,t){if(e===``||e[0]===` `)return e;let n=/ [^ ]/g,r,i=0,a,o=0,s=0,c=``;for(;r=n.exec(e);)s=r.index,s-i>t&&(a=o>i?o:s,c+=`
|
|
30
|
-
`+e.slice(i,a),i=a+1),o=s;return c+=`
|
|
31
|
-
`,e.length-i>t&&o>i?c+=e.slice(i,o)+`
|
|
32
|
-
`+e.slice(o+1):c+=e.slice(i),c.slice(1)}function R(e){let t=``,n=0;for(let r=0;r<e.length;n>=65536?r+=2:r++){n=F(e,r);let i=T[n];!i&&M(n)?(t+=e[r],n>=65536&&(t+=e[r+1])):t+=i||O(n)}return t}function De(e,t,n){let r=``,i=e.tag;for(let i=0,a=n.length;i<a;i+=1){let a=n[i];e.replacer&&(a=e.replacer.call(n,String(i),a)),(z(e,t,a,!1,!1)||a===void 0&&z(e,t,null,!1,!1))&&(r!==``&&(r+=`,`+(e.condenseFlow?``:` `)),r+=e.dump)}e.tag=i,e.dump=`[`+r+`]`}function Oe(e,t,n,r){let i=``,a=e.tag;for(let a=0,o=n.length;a<o;a+=1){let o=n[a];e.replacer&&(o=e.replacer.call(n,String(a),o)),(z(e,t+1,o,!0,!0,!1,!0)||o===void 0&&z(e,t+1,null,!0,!0,!1,!0))&&((!r||i!==``)&&(i+=A(e,t)),e.dump&&l===e.dump.charCodeAt(0)?i+=`-`:i+=`- `,i+=e.dump)}e.tag=a,e.dump=i||`[]`}function ke(e,t,n){let r=``,i=e.tag,a=Object.keys(n);for(let i=0,o=a.length;i<o;i+=1){let o=``;r!==``&&(o+=`, `),e.condenseFlow&&(o+=`"`);let s=a[i],c=n[s];e.replacer&&(c=e.replacer.call(n,s,c)),z(e,t,s,!1,!1)&&(e.dump.length>1024&&(o+=`? `),o+=e.dump+(e.condenseFlow?`"`:``)+`:`+(e.condenseFlow?``:` `),z(e,t,c,!1,!1)&&(o+=e.dump,r+=o))}e.tag=i,e.dump=`{`+r+`}`}function Ae(e,t,n,i){let a=``,o=e.tag,s=Object.keys(n);if(e.sortKeys===!0)s.sort();else if(typeof e.sortKeys==`function`)s.sort(e.sortKeys);else if(e.sortKeys)throw new r(`sortKeys must be a boolean or a function`);for(let r=0,o=s.length;r<o;r+=1){let o=``;(!i||a!==``)&&(o+=A(e,t));let c=s[r],u=n[c];if(e.replacer&&(u=e.replacer.call(n,c,u)),!z(e,t+1,c,!0,!0,!0))continue;let d=e.tag!==null&&e.tag!==`?`||e.dump&&e.dump.length>1024;d&&(e.dump&&l===e.dump.charCodeAt(0)?o+=`?`:o+=`? `),o+=e.dump,d&&(o+=A(e,t)),z(e,t+1,u,!0,d)&&(e.dump&&l===e.dump.charCodeAt(0)?o+=`:`:o+=`: `,o+=e.dump,a+=o)}e.tag=o,e.dump=a||`{}`}function je(e,t,n){let i=n?e.explicitTypes:e.implicitTypes;for(let s=0,c=i.length;s<c;s+=1){let c=i[s];if((c.instanceOf||c.predicate)&&(!c.instanceOf||typeof t==`object`&&t instanceof c.instanceOf)&&(!c.predicate||c.predicate(t))){if(e.tag=n?c.multi&&c.representName?c.representName(t):c.tag:`?`,c.represent){let n=e.styleMap[c.tag]||c.defaultStyle,i;if(a.call(c.represent)===`[object Function]`)i=c.represent(t,n);else if(o.call(c.represent,n))i=c.represent[n](t,n);else throw new r(`!<`+c.tag+`> tag resolver accepts not "`+n+`" style`);e.dump=i}return!0}}return!1}function z(e,t,n,i,o,s,c){e.tag=null,e.dump=n,je(e,n,!1)||je(e,n,!0);let l=a.call(e.dump),u=i;i&&=e.flowLevel<0||e.flowLevel>t;let d=l===`[object Object]`||l===`[object Array]`,f,p;if(d&&(f=e.duplicates.indexOf(n),p=f!==-1),(e.tag!==null&&e.tag!==`?`||p||e.indent!==2&&t>0)&&(o=!1),p&&e.usedDuplicates[f])e.dump=`*ref_`+f;else{if(d&&p&&!e.usedDuplicates[f]&&(e.usedDuplicates[f]=!0),l===`[object Object]`)i&&Object.keys(e.dump).length!==0?(Ae(e,t,e.dump,o),p&&(e.dump=`&ref_`+f+e.dump)):(ke(e,t,e.dump),p&&(e.dump=`&ref_`+f+` `+e.dump));else if(l===`[object Array]`)i&&e.dump.length!==0?(e.noArrayIndent&&!c&&t>0?Oe(e,t-1,e.dump,o):Oe(e,t,e.dump,o),p&&(e.dump=`&ref_`+f+e.dump)):(De(e,t,e.dump),p&&(e.dump=`&ref_`+f+` `+e.dump));else if(l===`[object String]`)e.tag!==`?`&&Se(e,e.dump,t,s,u);else if(l===`[object Undefined]`)return!1;else{if(e.skipInvalid)return!1;throw new r(`unacceptable kind of an object to dump `+l)}if(e.tag!==null&&e.tag!==`?`){let t=encodeURI(e.tag[0]===`!`?e.tag.slice(1):e.tag).replace(/!/g,`%21`);t=e.tag[0]===`!`?`!`+t:t.slice(0,18)===`tag:yaml.org,2002:`?`!!`+t.slice(18):`!<`+t+`>`,e.dump=t+` `+e.dump}}return!0}function Me(e,t){let n=[],r=[];Ne(e,n,r);let i=r.length;for(let e=0;e<i;e+=1)t.duplicates.push(n[r[e]]);t.usedDuplicates=Array(i)}function Ne(e,t,n){if(typeof e==`object`&&e){let r=t.indexOf(e);if(r!==-1)n.indexOf(r)===-1&&n.push(r);else if(t.push(e),Array.isArray(e))for(let r=0,i=e.length;r<i;r+=1)Ne(e[r],t,n);else{let r=Object.keys(e);for(let i=0,a=r.length;i<a;i+=1)Ne(e[r[i]],t,n)}}}function B(e,t){t||={};let n=new k(t);n.noRefs||Me(e,n);let r=e;return n.replacer&&(r=n.replacer.call({"":r},``,r)),z(n,0,r,!0,!0)?n.dump+`
|
|
33
|
-
`:``}t.exports.dump=B})),we=E(((e,t)=>{var n=Se(),r=Ce();function i(e,t){return function(){throw Error(`Function yaml.`+e+` is removed in js-yaml 4. Use yaml.`+t+` instead, which is now safe by default.`)}}t.exports.Type=k(),t.exports.Schema=fe(),t.exports.FAILSAFE_SCHEMA=M(),t.exports.JSON_SCHEMA=F(),t.exports.CORE_SCHEMA=I(),t.exports.DEFAULT_SCHEMA=xe(),t.exports.load=n.load,t.exports.loadAll=n.loadAll,t.exports.dump=r.dump,t.exports.YAMLException=ue(),t.exports.types={binary:ve(),float:P(),map:j(),null:me(),pairs:L(),set:be(),timestamp:ge(),bool:N(),int:he(),merge:_e(),omap:ye(),seq:pe(),str:A()},t.exports.safeLoad=i(`safeLoad`,`load`),t.exports.safeLoadAll=i(`safeLoadAll`,`loadAll`),t.exports.safeDump=i(`safeDump`,`dump`)})),Te=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.loadYaml=e.loadJson=e.loadJs=e.loadJsSync=void 0;var t=D(`fs/promises`),n=D(`url`);e.loadJsSync=function(e){return delete D.cache[D.resolve(e)],D(e)},e.loadJs=async function(r){try{let{href:e}=(0,n.pathToFileURL)(await(0,t.realpath)(r));return(await import(e)).default}catch(t){try{return(0,e.loadJsSync)(r,``)}catch(e){throw e.code===`ERR_REQUIRE_ESM`||e instanceof SyntaxError&&e.toString().includes(`Cannot use import statement outside a module`)?t:e}}},e.loadJson=function(e,t){try{return JSON.parse(t)}catch(t){throw t.message=`JSON Error in ${e}:\n${t.message}`,t}};var r;e.loadYaml=function(e,t){r===void 0&&(r=we());try{return r.load(t)}catch(t){throw t.message=`YAML Error in ${e}:\n${t.message}`,t}}})),Ee=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.defaultLoadersSync=e.defaultLoaders=e.metaSearchPlaces=e.globalConfigSearchPlacesSync=e.globalConfigSearchPlaces=e.getDefaultSearchPlacesSync=e.getDefaultSearchPlaces=void 0;var t=Te();function n(e){return[`package.json`,`.${e}rc`,`.${e}rc.json`,`.${e}rc.yaml`,`.${e}rc.yml`,`.${e}rc.js`,`.${e}rc.ts`,`.${e}rc.cjs`,`.${e}rc.mjs`,`.config/${e}rc`,`.config/${e}rc.json`,`.config/${e}rc.yaml`,`.config/${e}rc.yml`,`.config/${e}rc.js`,`.config/${e}rc.ts`,`.config/${e}rc.cjs`,`.config/${e}rc.mjs`,`${e}.config.js`,`${e}.config.ts`,`${e}.config.cjs`,`${e}.config.mjs`]}e.getDefaultSearchPlaces=n;function r(e){return[`package.json`,`.${e}rc`,`.${e}rc.json`,`.${e}rc.yaml`,`.${e}rc.yml`,`.${e}rc.js`,`.${e}rc.ts`,`.${e}rc.cjs`,`.config/${e}rc`,`.config/${e}rc.json`,`.config/${e}rc.yaml`,`.config/${e}rc.yml`,`.config/${e}rc.js`,`.config/${e}rc.ts`,`.config/${e}rc.cjs`,`${e}.config.js`,`${e}.config.ts`,`${e}.config.cjs`]}e.getDefaultSearchPlacesSync=r,e.globalConfigSearchPlaces=[`config`,`config.json`,`config.yaml`,`config.yml`,`config.js`,`config.ts`,`config.cjs`,`config.mjs`],e.globalConfigSearchPlacesSync=[`config`,`config.json`,`config.yaml`,`config.yml`,`config.js`,`config.ts`,`config.cjs`],e.metaSearchPlaces=[`package.json`,`package.yaml`,`.config/config.json`,`.config/config.yaml`,`.config/config.yml`,`.config/config.js`,`.config/config.ts`,`.config/config.cjs`,`.config/config.mjs`],e.defaultLoaders=Object.freeze({".mjs":t.loadJs,".cjs":t.loadJs,".js":t.loadJs,".ts":t.loadJs,".cts":t.loadJs,".mts":t.loadJs,".json":t.loadJson,".yaml":t.loadYaml,".yml":t.loadYaml,noExt:t.loadYaml}),e.defaultLoadersSync=Object.freeze({".cjs":t.loadJsSync,".js":t.loadJsSync,".cts":t.loadJsSync,".ts":t.loadJsSync,".json":t.loadJson,".yaml":t.loadYaml,".yml":t.loadYaml,noExt:t.loadYaml})})),R=E(((e,t)=>{var n=D(`path`),r=D(`os`),i=r.homedir(),a=r.tmpdir(),{env:o}=process,s=e=>{let t=n.join(i,`Library`);return{data:n.join(t,`Application Support`,e),config:n.join(t,`Preferences`,e),cache:n.join(t,`Caches`,e),log:n.join(t,`Logs`,e),temp:n.join(a,e)}},c=e=>{let t=o.APPDATA||n.join(i,`AppData`,`Roaming`),r=o.LOCALAPPDATA||n.join(i,`AppData`,`Local`);return{data:n.join(r,e,`Data`),config:n.join(t,e,`Config`),cache:n.join(r,e,`Cache`),log:n.join(r,e,`Log`),temp:n.join(a,e)}},l=e=>{let t=n.basename(i);return{data:n.join(o.XDG_DATA_HOME||n.join(i,`.local`,`share`),e),config:n.join(o.XDG_CONFIG_HOME||n.join(i,`.config`),e),cache:n.join(o.XDG_CACHE_HOME||n.join(i,`.cache`),e),log:n.join(o.XDG_STATE_HOME||n.join(i,`.local`,`state`),e),temp:n.join(a,t,e)}},u=(e,t)=>{if(typeof e!=`string`)throw TypeError(`Expected string, got ${typeof e}`);return t=Object.assign({suffix:`nodejs`},t),t.suffix&&(e+=`-${t.suffix}`),process.platform===`darwin`?s(e):process.platform===`win32`?c(e):l(e)};t.exports=u,t.exports.default=u})),De=E((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,"__esModule",{value:!0}),e.isDirectorySync=e.isDirectory=e.removeUndefinedValuesFromObject=e.decodeFileContent=e.getPropertyByPath=e.emplace=void 0;var i=r(D(`fs`));function a(e,t,n){let r=e.get(t);if(r!==void 0)return r;let i=n();return e.set(t,i),i}e.emplace=a;function o(e,t){return typeof t==`string`&&Object.prototype.hasOwnProperty.call(e,t)?e[t]:(typeof t==`string`?t.split(`.`):t).reduce((e,t)=>e===void 0?e:e[t],e)}e.getPropertyByPath=o;function s(e){return e[0]===255&&e[1]===254?new TextDecoder(`utf-16le`).decode(e):e[0]===254&&e[1]===255?new TextDecoder(`utf-16be`).decode(e):e.toString(`utf-8`)}e.decodeFileContent=s;function c(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}e.removeUndefinedValuesFromObject=c;async function l(e){try{return(await i.promises.stat(e)).isDirectory()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}e.isDirectory=l;function u(e){try{return i.default.statSync(e).isDirectory()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}e.isDirectorySync=u})),Oe=E((e=>{var t=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.getExtensionDescription=e.ExplorerBase=void 0;var n=t(R()),r=t(D(`os`)),i=t(D(`path`)),a=De();e.ExplorerBase=class{#e=!1;config;loadCache;searchCache;constructor(e){this.config=e,e.cache&&(this.loadCache=new Map,this.searchCache=new Map),this.#t()}set loadingMetaConfig(e){this.#e=e}#t(){let e=this.config;for(let t of e.searchPlaces){let e=i.default.extname(t),n=this.config.loaders[e||`noExt`]??this.config.loaders.default;if(n===void 0)throw Error(`Missing loader for ${o(t)}.`);if(typeof n!=`function`)throw Error(`Loader for ${o(t)} is not a function: Received ${typeof n}.`)}}clearLoadCache(){this.loadCache&&this.loadCache.clear()}clearSearchCache(){this.searchCache&&this.searchCache.clear()}clearCaches(){this.clearLoadCache(),this.clearSearchCache()}toCosmiconfigResult(e,t){if(t===null)return null;if(t===void 0)return{filepath:e,config:void 0,isEmpty:!0};if(this.config.applyPackagePropertyPathToConfiguration||this.#e){let e=this.config.packageProp??this.config.moduleName;t=(0,a.getPropertyByPath)(t,e)}return t===void 0?{filepath:e,config:void 0,isEmpty:!0}:{config:t,filepath:e}}validateImports(e,t,n){let r=i.default.dirname(e);for(let a of t){if(typeof a!=`string`)throw Error(`${e}: Key $import must contain a string or a list of strings`);let t=i.default.resolve(r,a);if(t===e)throw Error(`Self-import detected in ${e}`);let o=n.indexOf(t);if(o!==-1)throw Error(`Circular import detected:
|
|
34
|
-
${[...n,t].map((e,t)=>`${t+1}. ${e}`).join(`
|
|
35
|
-
`)} (same as ${o+1}.)`)}}getSearchPlacesForDir(e,t){return(e.isGlobalConfig?t:this.config.searchPlaces).map(t=>i.default.join(e.path,t))}getGlobalConfigDir(){return(0,n.default)(this.config.moduleName,{suffix:``}).config}*getGlobalDirs(e){let t=i.default.resolve(this.config.stopDir??r.default.homedir());yield{path:e,isGlobalConfig:!1};let n=e;for(;n!==t;){let e=i.default.dirname(n);if(e===n)break;yield{path:e,isGlobalConfig:!1},n=e}yield{path:this.getGlobalConfigDir(),isGlobalConfig:!0}}};function o(e){return e?`extension "${e}"`:`files without extensions`}e.getExtensionDescription=o})),ke=E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.mergeAll=e.hasOwn=void 0,e.hasOwn=Function.prototype.call.bind(Object.prototype.hasOwnProperty);var t=Function.prototype.call.bind(Object.prototype.toString);function n(e){return t(e)===`[object Object]`}function r(t,i,a){for(let o of Object.keys(i)){if(o===`__proto__`||o===`constructor`)continue;let s=i[o];if((0,e.hasOwn)(t,o)){if(Array.isArray(t[o])&&Array.isArray(s)){if(a.mergeArrays){t[o].push(...s);continue}}else if(n(t[o])&&n(s)){t[o]=r(t[o],s,a);continue}}t[o]=s}return t}function i(e,t){return e.reduce((e,n)=>r(e,n,t),{})}e.mergeAll=i})),Ae=E((e=>{var t=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.Explorer=void 0;var n=t(D(`fs/promises`)),r=t(D(`path`)),i=Ee(),a=Oe(),o=ke(),s=De();e.Explorer=class extends a.ExplorerBase{async load(e){e=r.default.resolve(e);let t=async()=>await this.config.transform(await this.#e(e));return this.loadCache?await(0,s.emplace)(this.loadCache,e,t):await t()}async search(e=``){if(this.config.metaConfigFilePath){this.loadingMetaConfig=!0;let e=await this.load(this.config.metaConfigFilePath);if(this.loadingMetaConfig=!1,e&&!e.isEmpty)return e}e=r.default.resolve(e);let t=this.#i(e),n=await t.next();if(n.done)throw Error(`Could not find any folders to iterate through (start from ${e})`);let a=n.value,o=async()=>{if(await(0,s.isDirectory)(a.path))for(let e of this.getSearchPlacesForDir(a,i.globalConfigSearchPlaces))try{let t=await this.#e(e);if(t!==null&&!(t.isEmpty&&this.config.ignoreEmptySearchPlaces))return await this.config.transform(t)}catch(e){if(e.code===`ENOENT`||e.code===`EISDIR`||e.code===`ENOTDIR`||e.code===`EACCES`)continue;throw e}let e=await t.next();return e.done?await this.config.transform(null):(a=e.value,this.searchCache?await(0,s.emplace)(this.searchCache,a.path,o):await o())};return this.searchCache?await(0,s.emplace)(this.searchCache,e,o):await o()}async#e(e,t=[]){let r=(0,s.decodeFileContent)(await n.default.readFile(e));return this.toCosmiconfigResult(e,await this.#t(e,r,t))}async#t(e,t,n){let i=await this.#n(e,t);if(!i||!(0,o.hasOwn)(i,`$import`))return i;let a=r.default.dirname(e),{$import:s,...c}=i,l=Array.isArray(s)?s:[s],u=[...n,e];this.validateImports(e,l,u);let d=await Promise.all(l.map(async e=>{let t=r.default.resolve(a,e);return(await this.#e(t,u))?.config}));return(0,o.mergeAll)([...d,c],{mergeArrays:this.config.mergeImportArrays})}async#n(e,t){if(t.trim()===``)return;let n=r.default.extname(e),i=this.config.loaders[n||`noExt`]??this.config.loaders.default;if(!i)throw Error(`No loader specified for ${(0,a.getExtensionDescription)(n)}`);try{let a=await i(e,t);return r.default.basename(e,n)===`package`?(0,s.getPropertyByPath)(a,this.config.packageProp??this.config.moduleName)??null:a}catch(t){throw t.filepath=e,t}}async#r(e){try{return await n.default.stat(e),!0}catch{return!1}}async*#i(e){switch(this.config.searchStrategy){case`none`:yield{path:e,isGlobalConfig:!1};return;case`project`:{let t=e;for(;;){yield{path:t,isGlobalConfig:!1};let e=!1;for(let n of[`json`,`yaml`]){let i=r.default.join(t,`package.${n}`);if(await this.#r(i)){e=!0;break}}if(e)return;let n=r.default.dirname(t);if(n===t)return;t=n}}case`global`:yield*this.getGlobalDirs(e)}}}})),je=E((e=>{var t=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.ExplorerSync=void 0;var n=t(D(`fs`)),r=t(D(`path`)),i=Ee(),a=Oe(),o=ke(),s=De();e.ExplorerSync=class extends a.ExplorerBase{load(e){e=r.default.resolve(e);let t=()=>this.config.transform(this.#e(e));return this.loadCache?(0,s.emplace)(this.loadCache,e,t):t()}search(e=``){if(this.config.metaConfigFilePath){this.loadingMetaConfig=!0;let e=this.load(this.config.metaConfigFilePath);if(this.loadingMetaConfig=!1,e&&!e.isEmpty)return e}e=r.default.resolve(e);let t=this.#i(e),n=t.next();if(n.done)throw Error(`Could not find any folders to iterate through (start from ${e})`);let a=n.value,o=()=>{if((0,s.isDirectorySync)(a.path))for(let e of this.getSearchPlacesForDir(a,i.globalConfigSearchPlacesSync))try{let t=this.#e(e);if(t!==null&&!(t.isEmpty&&this.config.ignoreEmptySearchPlaces))return this.config.transform(t)}catch(e){if(e.code===`ENOENT`||e.code===`EISDIR`||e.code===`ENOTDIR`||e.code===`EACCES`)continue;throw e}let e=t.next();return e.done?this.config.transform(null):(a=e.value,this.searchCache?(0,s.emplace)(this.searchCache,a.path,o):o())};return this.searchCache?(0,s.emplace)(this.searchCache,e,o):o()}#e(e,t=[]){let r=(0,s.decodeFileContent)(n.default.readFileSync(e));return this.toCosmiconfigResult(e,this.#t(e,r,t))}#t(e,t,n){let i=this.#n(e,t);if(!i||!(0,o.hasOwn)(i,`$import`))return i;let a=r.default.dirname(e),{$import:s,...c}=i,l=Array.isArray(s)?s:[s],u=[...n,e];this.validateImports(e,l,u);let d=l.map(e=>{let t=r.default.resolve(a,e);return this.#e(t,u)?.config});return(0,o.mergeAll)([...d,c],{mergeArrays:this.config.mergeImportArrays})}#n(e,t){if(t.trim()===``)return;let n=r.default.extname(e),i=this.config.loaders[n||`noExt`]??this.config.loaders.default;if(!i)throw Error(`No loader specified for ${(0,a.getExtensionDescription)(n)}`);try{let a=i(e,t);return r.default.basename(e,n)===`package`?(0,s.getPropertyByPath)(a,this.config.packageProp??this.config.moduleName)??null:a}catch(t){throw t.filepath=e,t}}#r(e){try{return n.default.statSync(e),!0}catch{return!1}}*#i(e){switch(this.config.searchStrategy){case`none`:yield{path:e,isGlobalConfig:!1};return;case`project`:{let t=e;for(;;){yield{path:t,isGlobalConfig:!1};let e=!1;for(let n of[`json`,`yaml`]){let i=r.default.join(t,`package.${n}`);if(this.#r(i)){e=!0;break}}if(e)return;let n=r.default.dirname(t);if(n===t)return;t=n}}case`global`:yield*this.getGlobalDirs(e)}}loadSync(e){return this.load(e)}searchSync(e=``){return this.search(e)}}})),z=(0,E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.defaultLoadersSync=e.defaultLoaders=e.globalConfigSearchPlacesSync=e.globalConfigSearchPlaces=e.getDefaultSearchPlacesSync=e.getDefaultSearchPlaces=e.cosmiconfigSync=e.cosmiconfig=void 0;var t=Ee();Object.defineProperty(e,"defaultLoaders",{enumerable:!0,get:function(){return t.defaultLoaders}}),Object.defineProperty(e,"defaultLoadersSync",{enumerable:!0,get:function(){return t.defaultLoadersSync}}),Object.defineProperty(e,"getDefaultSearchPlaces",{enumerable:!0,get:function(){return t.getDefaultSearchPlaces}}),Object.defineProperty(e,"getDefaultSearchPlacesSync",{enumerable:!0,get:function(){return t.getDefaultSearchPlacesSync}}),Object.defineProperty(e,"globalConfigSearchPlaces",{enumerable:!0,get:function(){return t.globalConfigSearchPlaces}}),Object.defineProperty(e,"globalConfigSearchPlacesSync",{enumerable:!0,get:function(){return t.globalConfigSearchPlacesSync}});var n=Ae(),r=je(),i=De(),a=function(e){return e};function o(){let e=new r.ExplorerSync({moduleName:`cosmiconfig`,stopDir:process.cwd(),searchPlaces:t.metaSearchPlaces,ignoreEmptySearchPlaces:!1,applyPackagePropertyPathToConfiguration:!0,loaders:t.defaultLoaders,transform:a,cache:!0,metaConfigFilePath:null,mergeImportArrays:!0,mergeSearchPlaces:!0,searchStrategy:`none`}).search();if(!e)return null;if(e.config?.loaders)throw Error(`Can not specify loaders in meta config file`);if(e.config?.searchStrategy)throw Error(`Can not specify searchStrategy in meta config file`);let n={mergeSearchPlaces:!0,...e.config??{}};return{config:(0,i.removeUndefinedValuesFromObject)(n),filepath:e.filepath}}function s(e,t,n){let r=n.searchPlaces?.map(t=>t.replace(`{name}`,e));return n.mergeSearchPlaces?[...r??[],...t]:r??t}function c(e,t,n){let r=o();if(!r)return{...t,...(0,i.removeUndefinedValuesFromObject)(n),loaders:{...t.loaders,...n.loaders}};let a=r.config,c=n.searchPlaces??t.searchPlaces;return{...t,...(0,i.removeUndefinedValuesFromObject)(n),metaConfigFilePath:r.filepath,...a,searchPlaces:s(e,c,a),loaders:{...t.loaders,...n.loaders}}}function l(e){if(e.searchStrategy!=null&&e.searchStrategy!==`global`&&e.stopDir)throw Error('Can not supply `stopDir` option with `searchStrategy` other than "global"')}function u(e,n){return l(n),c(e,{moduleName:e,searchPlaces:(0,t.getDefaultSearchPlaces)(e),ignoreEmptySearchPlaces:!0,cache:!0,transform:a,loaders:t.defaultLoaders,metaConfigFilePath:null,mergeImportArrays:!0,mergeSearchPlaces:!0,searchStrategy:n.stopDir?`global`:`none`},n)}function d(e,n){return l(n),c(e,{moduleName:e,searchPlaces:(0,t.getDefaultSearchPlacesSync)(e),ignoreEmptySearchPlaces:!0,cache:!0,transform:a,loaders:t.defaultLoadersSync,metaConfigFilePath:null,mergeImportArrays:!0,mergeSearchPlaces:!0,searchStrategy:n.stopDir?`global`:`none`},n)}function f(e,t={}){let r=u(e,t),i=new n.Explorer(r);return{search:i.search.bind(i),load:i.load.bind(i),clearLoadCache:i.clearLoadCache.bind(i),clearSearchCache:i.clearSearchCache.bind(i),clearCaches:i.clearCaches.bind(i)}}e.cosmiconfig=f;function p(e,t={}){let n=d(e,t),i=new r.ExplorerSync(n);return{search:i.search.bind(i),load:i.load.bind(i),clearLoadCache:i.clearLoadCache.bind(i),clearSearchCache:i.clearSearchCache.bind(i),clearCaches:i.clearCaches.bind(i)}}e.cosmiconfigSync=p}))().cosmiconfig)(`tailorkit`,{searchPlaces:[`tailorkit.config.ts`,`tailorkit.config.mjs`,`tailorkit.config.js`]}),Me=async(e,t=process.cwd())=>{let n=ee.resolve(t),r=e===void 0?await z.search(n):await z.load(ee.resolve(n,e));if(r===null)throw Error(`Could not find tailorkit config from ${n}.`);return{config:ce.parse(r.config),filepath:r.filepath,root:ee.dirname(r.filepath)}};function Ne(e){return e[0]??{}}function B(e){return Array.isArray(e)?e:e==null?[]:[e]}var Pe=`orpc`,Fe=`@orpc/shared`,Ie=`1.15.0`,Le=class extends Error{constructor(...e){super(...e),this.name=`AbortError`}};function Re(e){let t;return()=>{if(t)return t.result;let n=e();return t={result:n},n}}function ze(e){let t=Promise.resolve();return(...n)=>t=t.catch(()=>{}).then(()=>e(...n))}var Be=2,Ve=`__${Fe}@${Ie}/otel/config__`;function He(){return globalThis[Ve]}function Ue(e,t={},n){return(He()?.tracer)?.startSpan(e,t,n)}function V(e,t,n={}){if(!e)return;let r=We(t);e.recordException(r),(!n.signal?.aborted||n.signal.reason!==t)&&e.setStatus({code:Be,message:r.message})}function We(e){if(e instanceof Error){let t={message:e.message,name:e.name,stack:e.stack};return`code`in e&&(typeof e.code==`string`||typeof e.code==`number`)&&(t.code=e.code),t}return{message:String(e)}}async function H({name:e,context:t,...n},r){let i=He()?.tracer;if(!i)return r();let a=async e=>{try{return await r(e)}catch(t){throw V(e,t,n),t}finally{e.end()}};return t?i.startActiveSpan(e,n,t,a):i.startActiveSpan(e,n,a)}async function Ge(e,t){let n=He();if(!e||!n)return t();let r=n.trace.setSpan(n.context.active(),e);return n.context.with(r,t)}function U(e){return!e||typeof e!=`object`?!1:`next`in e&&typeof e.next==`function`&&Symbol.asyncIterator in e&&typeof e[Symbol.asyncIterator]==`function`}var Ke=Symbol.asyncDispose??Symbol.for(`asyncDispose`),qe=class{#e=!1;#t=!1;#n;#r;constructor(e,t){this.#n=t,this.#r=ze(async()=>{if(this.#e)return{done:!0,value:void 0};try{let t=await e();return t.done&&(this.#e=!0),t}catch(e){throw this.#e=!0,e}finally{this.#e&&!this.#t&&(this.#t=!0,await this.#n(`next`))}})}next(){return this.#r()}async return(e){return this.#e=!0,this.#t||(this.#t=!0,await this.#n(`return`)),{done:!0,value:e}}async throw(e){throw this.#e=!0,this.#t||(this.#t=!0,await this.#n(`throw`)),e}async[Ke](){this.#e=!0,this.#t||(this.#t=!0,await this.#n(`dispose`))}[Symbol.asyncIterator](){return this}};function Je({name:e,...t},n){let r;return new qe(async()=>{r??=Ue(e);try{let e=await Ge(r,()=>n.next());return r?.addEvent(e.done?`completed`:`yielded`),e}catch(e){throw V(r,e,t),e}},async e=>{try{e!==`next`&&await Ge(r,()=>n.return?.())}catch(e){throw V(r,e,t),e}finally{r?.end()}})}function Ye(e,t,n){let r=(t,i)=>{let a=e[i];return a?a({...t,next:(e=t)=>r(e,i+1)}):n(t)};return r(t,0)}function Xe(e){if(e)return JSON.parse(e)}function Ze(e){return JSON.stringify(e)}function Qe(e){return et(e)?Object.getPrototypeOf(e)?.constructor:null}function $e(e){if(!e||typeof e!=`object`)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||!t||!t.constructor}function et(e){return!!e&&(typeof e==`object`||typeof e==`function`)}function tt(e,...t){return typeof e==`function`?e(...t):e}function nt(e){return new Proxy(e,{get(e,t,n){let r=Reflect.get(e,t,n);return t!==`then`||typeof r!=`function`?r:new Proxy(r,{apply(t,n,r){if(r.length!==2||r.some(e=>!it(e)))return Reflect.apply(t,n,r);let i=!0;r[0].call(n,nt(new Proxy(e,{get:(e,t,n)=>{if(i&&t===`then`){i=!1;return}return Reflect.get(e,t,n)}})))}})}})}var rt=/^\s*function\s*\(\)\s*\{\s*\[native code\]\s*\}\s*$/;function it(e){return typeof e==`function`&&rt.test(e.toString())}function at(e,t){return new Proxy(typeof e==`function`?t:e,{get(n,r){let i=r in t?t:tt(e),a=Reflect.get(i,r);return typeof a==`function`?a.bind(i):a},has(n,r){return Reflect.has(t,r)||Reflect.has(tt(e),r)}})}function ot(e){try{return decodeURIComponent(e)}catch{return e}}var st=`@orpc/client`,ct=`1.15.0`,lt=new Set([`bind`,`valueOf`,`toString`,`toJSON`]),ut={BAD_REQUEST:{status:400,message:`Bad Request`},UNAUTHORIZED:{status:401,message:`Unauthorized`},FORBIDDEN:{status:403,message:`Forbidden`},NOT_FOUND:{status:404,message:`Not Found`},METHOD_NOT_SUPPORTED:{status:405,message:`Method Not Supported`},NOT_ACCEPTABLE:{status:406,message:`Not Acceptable`},TIMEOUT:{status:408,message:`Request Timeout`},CONFLICT:{status:409,message:`Conflict`},PRECONDITION_FAILED:{status:412,message:`Precondition Failed`},PAYLOAD_TOO_LARGE:{status:413,message:`Payload Too Large`},UNSUPPORTED_MEDIA_TYPE:{status:415,message:`Unsupported Media Type`},UNPROCESSABLE_CONTENT:{status:422,message:`Unprocessable Content`},TOO_MANY_REQUESTS:{status:429,message:`Too Many Requests`},CLIENT_CLOSED_REQUEST:{status:499,message:`Client Closed Request`},INTERNAL_SERVER_ERROR:{status:500,message:`Internal Server Error`},NOT_IMPLEMENTED:{status:501,message:`Not Implemented`},BAD_GATEWAY:{status:502,message:`Bad Gateway`},SERVICE_UNAVAILABLE:{status:503,message:`Service Unavailable`},GATEWAY_TIMEOUT:{status:504,message:`Gateway Timeout`}};function dt(e,t){return t??ut[e]?.status??500}function ft(e,t){return t||ut[e]?.message||e}var pt,W=class e extends Error{defined;code;status;data;static{let t=Symbol.for(`__${st}@${ct}/error/ORPC_ERROR_CONSTRUCTORS__`);globalThis[t]??=new WeakSet,pt=globalThis[t],pt.add(e)}constructor(e,...t){let n=Ne(t);if(n.status!==void 0&&!ht(n.status))throw Error(`[ORPCError] Invalid error status code.`);let r=ft(e,n.message);super(r,n),this.code=e,this.status=dt(e,n.status),this.defined=n.defined??!1,this.data=n.data}toJSON(){return{defined:this.defined,code:this.code,status:this.status,message:this.message,data:this.data}}static[Symbol.hasInstance](e){if(pt.has(this)){let t=Qe(e);if(t&&pt.has(t))return!0}return super[Symbol.hasInstance](e)}};function mt(e){return e instanceof W?e:new W(`INTERNAL_SERVER_ERROR`,{message:`Internal server error`,cause:e})}function ht(e){return e<200||e>=400}function gt(e){if(!$e(e))return!1;let t=[`defined`,`code`,`status`,`message`,`data`];return!Object.keys(e).some(e=>!t.includes(e))&&`defined`in e&&typeof e.defined==`boolean`&&`code`in e&&typeof e.code==`string`&&`status`in e&&typeof e.status==`number`&&ht(e.status)&&`message`in e&&typeof e.message==`string`}function _t(e,t={}){return new W(e.code,{...t,...e})}var vt=class extends TypeError{},yt=class extends TypeError{},bt=class extends Error{data;constructor(e){super(e?.message??`An error event was received`,e),this.data=e?.data}},xt=/\r\n|\r(?!\n)|\n/,St=/(?:\r\n|\r(?!\n)|\n){2}/,Ct=/(?:\r\n|\r(?!\n)|\n){2}/g,wt=13,Tt=10,Et=32;function Dt(e){let t={data:void 0,event:void 0,id:void 0,retry:void 0,comments:[]};for(let n of e.split(xt)){if(n===``)continue;let e=n.indexOf(`:`),r=e===-1?``:n.slice(n.charCodeAt(e+1)===Et?e+2:e+1);if(e===0){t.comments.push(r);continue}switch(e===-1?n:n.slice(0,e)){case`data`:t.data=t.data===void 0?r:`${t.data}
|
|
36
|
-
${r}`;break;case`event`:t.event=r;break;case`id`:t.id=r;break;case`retry`:{let e=Number.parseInt(r,10);e>=0&&e.toString()===r&&(t.retry=e);break}}}return t}var Ot=class{constructor(e={}){this.options=e}pending=[];tail=``;discardLeadingLF=!1;feed(e){if(e===``||this.discardLeadingLF&&(this.discardLeadingLF=!1,e.charCodeAt(0)===Tt&&(e=e.slice(1),e===``)))return;let t=this.tail+e;if(!St.test(t)){this.pending.push(e),this.tail=t.slice(-3);return}this.pending.push(e);let n=this.pending.length===1?e:this.pending.join(``),r=n.length-t.length,i=[],a=0;for(let e of t.matchAll(Ct))i.push(n.slice(a,r+e.index)),a=r+e.index+e[0].length;let o=n.slice(a);this.pending.length=0,this.tail=o.slice(-3),o===``?this.discardLeadingLF=e.charCodeAt(e.length-1)===wt:this.pending.push(o);for(let e of i){let t=Dt(e);this.options.onEvent&&this.options.onEvent(t)}}end(){if(this.pending.length!==0)throw new yt(`Event Iterator ended before complete`)}},kt=class extends TransformStream{constructor(){let e;super({start(t){e=new Ot({onEvent:e=>{t.enqueue(e)}})},transform(t){e.feed(t)},flush(){e.end()}})}},At=/\r\n|[\n\r]/,jt=/\r\n|[\n\r]/g;function Mt(e){return At.test(e)}function Nt(e){if(Mt(e))throw new vt(`Event's id must not contain a carriage return or newline character`)}function Pt(e){if(Mt(e))throw new vt(`Event's event must not contain a carriage return or newline character`)}function Ft(e){if(!Number.isInteger(e)||e<0)throw new vt(`Event's retry must be a integer and >= 0`)}function It(e){if(Mt(e))throw new vt(`Event's comment must not contain a carriage return or newline character`)}function Lt(e){return e===void 0?``:`data: ${e.replace(jt,`
|
|
37
|
-
data: `)}
|
|
38
|
-
`}function Rt(e){let t=``;for(let n of e??[])It(n),t+=`: ${n}
|
|
39
|
-
`;return t}function zt(e){let t=``;return t+=Rt(e.comments),e.event!==void 0&&(Pt(e.event),t+=`event: ${e.event}
|
|
40
|
-
`),e.retry!==void 0&&(Ft(e.retry),t+=`retry: ${e.retry}
|
|
41
|
-
`),e.id!==void 0&&(Nt(e.id),t+=`id: ${e.id}
|
|
42
|
-
`),t+=Lt(e.data),t+=`
|
|
43
|
-
`,t}var Bt=Symbol(`ORPC_EVENT_SOURCE_META`);function Vt(e,t){if(t.id===void 0&&t.retry===void 0&&!t.comments?.length)return e;if(t.id!==void 0&&Nt(t.id),t.retry!==void 0&&Ft(t.retry),t.comments!==void 0)for(let e of t.comments)It(e);return new Proxy(e,{get(e,n,r){return n===Bt?t:Reflect.get(e,n,r)}})}function Ht(e){return et(e)?Reflect.get(e,Bt):void 0}var Ut=class extends qe{hibernationCallback;constructor(e){super(async()=>{throw Error(`Cannot iterate over hibernating iterator directly`)},async e=>{if(e!==`next`)throw Error(`Cannot cleanup hibernating iterator directly`)}),this.hibernationCallback=e}};function Wt(e,t=`inline`){return`${t}; filename="${e.replace(/[^\x20-\x7E]/g,`_`).replace(/"/g,`\\"`)}"; filename*=utf-8''${encodeURIComponent(e).replace(/['()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%(7C|60|5E)/g,(e,t)=>String.fromCharCode(Number.parseInt(t,16)))}`}function Gt(e){let t=e.match(/filename\*=(UTF-8'')?([^;]*)/i);if(t&&typeof t[2]==`string`)return ot(t[2]);let n=e.match(/filename="((?:\\"|[^"])*)"/i);if(n&&typeof n[1]==`string`)return n[1].replace(/\\"/g,`"`)}function Kt(e,t){let n={...e};for(let e in t)Array.isArray(t[e])?n[e]=[...B(n[e]),...t[e]]:t[e]!==void 0&&(n[e]=Array.isArray(n[e])?[...n[e],t[e]]:n[e]===void 0?t[e]:[n[e],t[e]]);return n}function qt(e,t){let n=async e=>{let n=await t.error(e);if(n!==e){let t=Ht(e);t&&et(n)&&(n=Vt(n,t))}return n};return new qe(async()=>{let{done:r,value:i}=await(async()=>{try{return await e.next()}catch(e){throw await n(e)}})(),a=await t.value(i,r);if(a!==i){let e=Ht(i);e&&et(a)&&(a=Vt(a,e))}return{done:r,value:a}},async()=>{try{await e.return?.()}catch(e){throw await n(e)}})}function Jt(e){return{...e,context:e.context??{}}}function Yt(e,t={}){let n=t.path??[];return nt(new Proxy(async(...[t,r={}])=>await e.call(n,t,Jt(r)),{get(r,i){return typeof i!=`string`||lt.has(i)?Reflect.get(r,i):Yt(e,{...t,path:[...n,i]})}}))}function Xt(e,t={}){let n=(e?.pipeThrough(new TextDecoderStream).pipeThrough(new kt))?.getReader(),r,i=!1;return new qe(async()=>{r??=Ue(`consume_event_iterator_stream`);try{for(;;){if(n===void 0)return{done:!0,value:void 0};let{done:e,value:t}=await Ge(r,()=>n.read());if(e){if(i)throw new Le(`Stream was cancelled`);return{done:!0,value:void 0}}switch(t.event){case`message`:{let e=Xe(t.data);return et(e)&&(e=Vt(e,t)),r?.addEvent(`message`),{done:!1,value:e}}case`error`:{let e=new bt({data:Xe(t.data)});throw e=Vt(e,t),r?.addEvent(`error`),e}case`done`:{let e=Xe(t.data);return et(e)&&(e=Vt(e,t)),r?.addEvent(`done`),{done:!0,value:e}}default:r?.addEvent(`maybe_keepalive`)}}}catch(e){throw e instanceof bt||V(r,e,t),e}},async e=>{try{e!==`next`&&(i=!0,r?.addEvent(`cancelled`)),await Ge(r,()=>n?.cancel())}catch(e){throw V(r,e,t),e}finally{r?.end()}})}function Zt(e,t={}){let n=t.eventIteratorKeepAliveEnabled??!0,r=t.eventIteratorKeepAliveInterval??5e3,i=t.eventIteratorKeepAliveComment??``,a=t.eventIteratorInitialCommentEnabled??!0,o=t.eventIteratorInitialComment??``,s=!1,c,l;return new ReadableStream({start(e){l=Ue(`stream_event_iterator`),a&&e.enqueue(zt({comments:[o]}))},async pull(t){try{n&&(c=setInterval(()=>{t.enqueue(zt({comments:[i]})),l?.addEvent(`keepalive`)},r));let a=await Ge(l,()=>e.next());if(clearInterval(c),s)return;let o=Ht(a.value);if(!a.done||a.value!==void 0||o!==void 0){let e=a.done?`done`:`message`;t.enqueue(zt({...o,event:e,data:Ze(a.value)})),l?.addEvent(e)}a.done&&(t.close(),l?.end())}catch(e){if(clearInterval(c),s)return;e instanceof bt?(t.enqueue(zt({...Ht(e),event:`error`,data:Ze(e.data)})),l?.addEvent(`error`),t.close()):(V(l,e),t.error(e)),l?.end()}},async cancel(){try{s=!0,clearInterval(c),l?.addEvent(`cancelled`),await Ge(l,()=>e.return?.())}catch(e){throw V(l,e),e}finally{l?.end()}}}).pipeThrough(new TextEncoderStream)}function Qt(e,t={}){return H({name:`parse_standard_body`,signal:t.signal},async()=>{let n=e.headers.get(`content-disposition`);if(typeof n==`string`){let t=Gt(n)??`blob`,r=await e.blob();return new File([r],t,{type:r.type})}let r=e.headers.get(`content-type`);if(!r||r.startsWith(`application/json`))return Xe(await e.text());if(r.startsWith(`multipart/form-data`))return await e.formData();if(r.startsWith(`application/x-www-form-urlencoded`)){let t=await e.text();return new URLSearchParams(t)}if(r.startsWith(`text/event-stream`))return Xt(e.body,t);if(r.startsWith(`text/plain`))return await e.text();let i=await e.blob();return new File([i],`blob`,{type:i.type})})}function $t(e,t,n={}){if(e instanceof ReadableStream)return e;let r=t.get(`content-disposition`);if(t.delete(`content-type`),t.delete(`content-disposition`),e!==void 0)return e instanceof Blob?(t.set(`content-type`,e.type),t.set(`content-length`,e.size.toString()),t.set(`content-disposition`,r??Wt(e instanceof File?e.name:`blob`)),e):e instanceof FormData||e instanceof URLSearchParams?e:U(e)?(t.set(`content-type`,`text/event-stream`),Zt(e,n)):(t.set(`content-type`,`application/json`),Ze(e))}function en(e,t={}){return e.forEach((e,n)=>{Array.isArray(t[n])?t[n].push(e):t[n]=t[n]===void 0?e:[t[n],e]}),t}function tn(e,t=new Headers){for(let[n,r]of Object.entries(e))if(Array.isArray(r))for(let e of r)t.append(n,e);else r!==void 0&&t.append(n,r);return t}function nn(e,t={}){let n=tn(e.headers),r=$t(e.body,n,t);return new Request(e.url,{signal:e.signal,method:e.method,headers:n,body:r})}function rn(e,t={}){return{body:Re(()=>Qt(e,t)),status:e.status,get headers(){let t=en(e.headers);return Object.defineProperty(this,"headers",{value:t,writable:!0}),t},set headers(e){Object.defineProperty(this,"headers",{value:e,writable:!0})}}}var an=class{plugins;constructor(e=[]){this.plugins=[...e].sort((e,t)=>(e.order??0)-(t.order??0))}init(e){for(let t of this.plugins)t.init?.(e)}},on=class{constructor(e,t,n={}){this.codec=e,this.sender=t,new an(n.plugins).init(n),this.interceptors=B(n.interceptors),this.clientInterceptors=B(n.clientInterceptors)}interceptors;clientInterceptors;call(e,t,n){return H({name:`${Pe}.${e.join(`/`)}`,signal:n.signal},r=>(r?.setAttribute(`rpc.system`,Pe),r?.setAttribute(`rpc.method`,e.join(`.`)),U(t)&&(t=Je({name:`consume_event_iterator_input`,signal:n.signal},t)),Ye(this.interceptors,{...n,path:e,input:t},async({path:e,input:t,...n})=>{let i=He(),a,o=i?.trace.getActiveSpan()??r;o&&i&&(a=i?.trace.setSpan(i.context.active(),o));let s=await H({name:`encode_request`,context:a},()=>this.codec.encode(e,t,n)),c=await Ye(this.clientInterceptors,{...n,input:t,path:e,request:s},({input:e,path:t,request:n,...r})=>H({name:`send_request`,signal:r.signal,context:a},()=>this.sender.call(n,r,t,e))),l=await H({name:`decode_response`,context:a},()=>this.codec.decode(c,n,e,t));return U(l)?Je({name:`consume_event_iterator_output`,signal:n.signal},l):l})))}},G={BIGINT:0,DATE:1,NAN:2,UNDEFINED:3,URL:4,REGEXP:5,SET:6,MAP:7},sn=class{customSerializers;constructor(e={}){if(this.customSerializers=e.customJsonSerializers??[],this.customSerializers.length!==new Set(this.customSerializers.map(e=>e.type)).size)throw Error(`Custom serializer type must be unique.`)}serialize(e,t=[],n=[],r=[],i=[]){for(let a of this.customSerializers)if(a.condition(e)){let o=this.serialize(a.serialize(e),t,n,r,i);return n.push([a.type,...t]),o}if(e instanceof Blob)return r.push(t),i.push(e),[e,n,r,i];if(typeof e==`bigint`)return n.push([G.BIGINT,...t]),[e.toString(),n,r,i];if(e instanceof Date)return n.push([G.DATE,...t]),Number.isNaN(e.getTime())?[null,n,r,i]:[e.toISOString(),n,r,i];if(Number.isNaN(e))return n.push([G.NAN,...t]),[null,n,r,i];if(e instanceof URL)return n.push([G.URL,...t]),[e.toString(),n,r,i];if(e instanceof RegExp)return n.push([G.REGEXP,...t]),[e.toString(),n,r,i];if(e instanceof Set){let a=this.serialize(Array.from(e),t,n,r,i);return n.push([G.SET,...t]),a}if(e instanceof Map){let a=this.serialize(Array.from(e.entries()),t,n,r,i);return n.push([G.MAP,...t]),a}if(Array.isArray(e))return[e.map((e,a)=>e===void 0?(n.push([G.UNDEFINED,...t,a]),null):this.serialize(e,[...t,a],n,r,i)[0]),n,r,i];if($e(e)){let a={};for(let o in e)(o!==`toJSON`||typeof e[o]!=`function`)&&(a[o]=this.serialize(e[o],[...t,o],n,r,i)[0]);return[a,n,r,i]}return[e,n,r,i]}deserialize(e,t,n,r){let i={data:e};n&&r&&n.forEach((e,t)=>{let n=i,a=`data`;e.forEach(e=>{if(n=n[a],a=e,!Object.hasOwn(n,a))throw Error(`Security error: accessing non-existent path during deserialization. Path segment: ${a}`)}),n[a]=r(t)});for(let e of t){let t=e[0],n=i,r=`data`;for(let t=1;t<e.length;t++)if(n=n[r],r=e[t],!Object.hasOwn(n,r))throw Error(`Security error: accessing non-existent path during deserialization. Path segment: ${r}`);for(let e of this.customSerializers)if(e.type===t){n[r]=e.deserialize(n[r]);break}switch(t){case G.BIGINT:n[r]=BigInt(n[r]);break;case G.DATE:n[r]=new Date(n[r]??`Invalid Date`);break;case G.NAN:n[r]=NaN;break;case G.UNDEFINED:n[r]=void 0;break;case G.URL:n[r]=new URL(n[r]);break;case G.REGEXP:{let[,e,t]=n[r].match(/^\/(.*)\/([a-z]*)$/);n[r]=new RegExp(e,t);break}case G.SET:n[r]=new Set(n[r]);break;case G.MAP:n[r]=new Map(n[r])}}return i.data}};function cn(e){return`/${e.map(encodeURIComponent).join(`/`)}`}function ln(e){return typeof e.forEach==`function`?en(e):e}function un(e){return Object.entries(ut).find(([,t])=>t.status===e)?.[0]??`MALFORMED_ORPC_ERROR_RESPONSE`}var dn=class{constructor(e,t){this.serializer=e,this.baseUrl=t.url,this.maxUrlLength=t.maxUrlLength??2083,this.fallbackMethod=t.fallbackMethod??`POST`,this.expectedMethod=t.method??this.fallbackMethod,this.headers=t.headers??{}}baseUrl;maxUrlLength;fallbackMethod;expectedMethod;headers;async encode(e,t,n){let r=ln(await tt(this.headers,n,e,t));n.lastEventId!==void 0&&(r=Kt(r,{"last-event-id":n.lastEventId}));let i=await tt(this.expectedMethod,n,e,t),a=await tt(this.baseUrl,n,e,t),o=new URL(a);o.pathname=`${o.pathname.replace(/\/$/,``)}${cn(e)}`;let s=this.serializer.serialize(t);if(i===`GET`&&!(s instanceof FormData)&&!U(s)){let a=await tt(this.maxUrlLength,n,e,t),c=new URL(o);if(c.searchParams.append(`data`,Ze(s)),c.toString().length<=a)return{body:void 0,method:i,headers:r,url:c,signal:n.signal}}return{url:o,method:i===`GET`?this.fallbackMethod:i,headers:r,body:s,signal:n.signal}}async decode(e){let t=!ht(e.status),n=await(async()=>{let t=!1;try{let n=await e.body();return t=!0,this.serializer.deserialize(n)}catch(e){throw Error(t?`Invalid RPC response format.`:`Cannot parse response body, please check the response body and content-type.`,{cause:e})}})();if(!t)throw gt(n)?_t(n):new W(un(e.status),{status:e.status,data:{...e,body:n}});return n}},fn=class{constructor(e){this.jsonSerializer=e}serialize(e){return U(e)?qt(e,{value:async e=>this.#e(e,!1),error:async e=>new bt({data:this.#e(mt(e).toJSON(),!1),cause:e})}):this.#e(e,!0)}#e(e,t){let[n,r,i,a]=this.jsonSerializer.serialize(e),o=r.length===0?void 0:r;if(!t||a.length===0)return{json:n,meta:o};let s=new FormData;return s.set(`data`,Ze({json:n,meta:o,maps:i})),a.forEach((e,t)=>{s.set(t.toString(),e)}),s}deserialize(e){return U(e)?qt(e,{value:async e=>this.#t(e),error:async e=>{if(!(e instanceof bt))return e;let t=this.#t(e.data);return gt(t)?_t(t,{cause:e}):new bt({data:t,cause:e})}}):this.#t(e)}#t(e){if(e===void 0)return;if(!(e instanceof FormData))return this.jsonSerializer.deserialize(e.json,e.meta??[]);let t=JSON.parse(e.get(`data`));return this.jsonSerializer.deserialize(t.json,t.meta??[],t.maps,t=>e.get(t.toString()))}},pn=class extends on{constructor(e,t){let n=new dn(new fn(new sn(t)),t);super(n,e,t)}},mn=class extends an{initRuntimeAdapter(e){for(let t of this.plugins)t.initRuntimeAdapter?.(e)}},hn=class{fetch;toFetchRequestOptions;adapterInterceptors;constructor(e){new mn(e.plugins).initRuntimeAdapter(e),this.fetch=e.fetch??globalThis.fetch.bind(globalThis),this.toFetchRequestOptions=e,this.adapterInterceptors=B(e.adapterInterceptors)}async call(e,t,n,r){let i=nn(e,this.toFetchRequestOptions);return rn(await Ye(this.adapterInterceptors,{...t,request:i,path:n,input:r,init:{redirect:`manual`}},({request:e,path:t,input:n,init:r,...i})=>this.fetch(e,r,i,t,n)),{signal:i.signal})}},gn=class extends pn{constructor(e){let t=new hn(e);super(t,e)}},_n=class extends Error{issues;data;constructor(e){super(e.message,e),this.issues=e.issues,this.data=e.data}};function vn(e,t){return{...e,...t}}async function yn(e,t){let{code:n,status:r,message:i,data:a,cause:o,defined:s}=t,c=e?.[t.code];if(!c||dt(t.code,c.status)!==t.status)return s?new W(n,{defined:!1,status:r,message:i,data:a,cause:o}):t;if(!c.data)return s?t:new W(n,{defined:!0,status:r,message:i,data:a,cause:o});let l=await c.data[`~standard`].validate(t.data);return l.issues?s?new W(n,{defined:!1,status:r,message:i,data:a,cause:o}):t:new W(n,{defined:!0,status:r,message:i,data:l.value,cause:o})}var bn=class{"~orpc";constructor(e){if(e.route?.successStatus&&ht(e.route.successStatus))throw Error(`[ContractProcedure] Invalid successStatus.`);if(Object.values(e.errorMap).some(e=>e&&e.status&&!ht(e.status)))throw Error(`[ContractProcedure] Invalid error status code.`);this[`~orpc`]=e}};function xn(e){return e instanceof bn||(typeof e==`object`||typeof e==`function`)&&e!==null&&`~orpc`in e&&typeof e[`~orpc`]==`object`&&e[`~orpc`]!==null&&`errorMap`in e[`~orpc`]&&`route`in e[`~orpc`]&&`meta`in e[`~orpc`]}function Sn(e,t){return{...e,...t}}function Cn(e,t){return{...e,...t}}function wn(e,t){return e.path?{...e,path:`${t}${e.path}`}:e}function Tn(e,t){return{...e,tags:[...t,...e.tags??[]]}}function En(e,t){return e?`${e}${t}`:t}function Dn(e,t){return e?[...e,...t]:t}function On(e,t){let n=e;return t.prefix&&(n=wn(n,t.prefix)),t.tags?.length&&(n=Tn(n,t.tags)),n}function kn(e,t){if(xn(e))return new bn({...e[`~orpc`],errorMap:vn(t.errorMap,e[`~orpc`].errorMap),route:On(e[`~orpc`].route,t)});if(typeof e!=`object`||!e)return e;let n={};for(let r in e)n[r]=kn(e[r],t);return n}new class e extends bn{constructor(e){super(e),this[`~orpc`].prefix=e.prefix,this[`~orpc`].tags=e.tags}$meta(t){return new e({...this[`~orpc`],meta:t})}$route(t){return new e({...this[`~orpc`],route:t})}$input(t){return new e({...this[`~orpc`],inputSchema:t})}errors(t){return new e({...this[`~orpc`],errorMap:vn(this[`~orpc`].errorMap,t)})}meta(t){return new e({...this[`~orpc`],meta:Sn(this[`~orpc`].meta,t)})}route(t){return new e({...this[`~orpc`],route:Cn(this[`~orpc`].route,t)})}input(t){return new e({...this[`~orpc`],inputSchema:t})}output(t){return new e({...this[`~orpc`],outputSchema:t})}prefix(t){return new e({...this[`~orpc`],prefix:En(this[`~orpc`].prefix,t)})}tag(...t){return new e({...this[`~orpc`],tags:Dn(this[`~orpc`].tags,t)})}router(e){return kn(e,this[`~orpc`])}}({errorMap:{},route:{},meta:{}});var An=Symbol(`ORPC_LAZY_SYMBOL`);function jn(e,t={}){return{[An]:{loader:e,meta:t}}}function Mn(e){return(typeof e==`object`||typeof e==`function`)&&e!==null&&An in e}function Nn(e){return e[An].meta}function Pn(e){return Mn(e)?e[An].loader():Promise.resolve({default:e})}function Fn(e,t){if(t.length>e.length)return!1;for(let n=0;n<e.length;n++){if(t[n]===void 0)return!0;if(e[n]!==t[n])return!1}return!0}function In(e,t,n){return n.dedupeLeading&&Fn(t,e)?t:[...e,...t]}function Ln(e,t){return[...e,t]}var Rn=class{"~orpc";constructor(e){this[`~orpc`]=e}};function zn(e){return e instanceof Rn||xn(e)&&`middlewares`in e[`~orpc`]&&`inputValidationIndex`in e[`~orpc`]&&`outputValidationIndex`in e[`~orpc`]&&`handler`in e[`~orpc`]}function Bn(e,t){return{...e,...t}}function Vn(e){return new Proxy(e,{get(t,n){return typeof n==`string`?(...t)=>{let r=Ne(t),i=e[n];return new W(n,{defined:!!i,status:i?.status,message:r.message??i?.message,data:r.data,cause:r.cause})}:Reflect.get(t,n)}})}function Hn(e){return{output:e,context:{}}}function Un(e,...t){let n=Ne(t);return async(...[t,r])=>{let i=B(n.path),{default:a}=await Pn(e),o=r?.context??{},s=await tt(n.context??{},o),c=Vn(a[`~orpc`].errorMap),l=async e=>e instanceof W?await yn(a[`~orpc`].errorMap,e):e;try{let e=await H({name:`call_procedure`,signal:r?.signal},e=>(e?.setAttribute(`procedure.path`,[...i]),Ye(B(n.interceptors),{context:s,input:t,errors:c,path:i,procedure:a,signal:r?.signal,lastEventId:r?.lastEventId},e=>Kn(e.procedure,e))));return U(e)?e instanceof Ut?e:at(e,qt(Je({name:`consume_event_iterator_output`,signal:r?.signal},e),{value:e=>e,error:e=>l(e)})):e}catch(e){throw await l(e)}}}async function Wn(e,t){let n=e[`~orpc`].inputSchema;return n?H({name:`validate_input`},async()=>{let e=await n[`~standard`].validate(t);if(e.issues)throw new W(`BAD_REQUEST`,{message:`Input validation failed`,data:{issues:e.issues},cause:new _n({message:`Input validation failed`,issues:e.issues,data:t})});return e.value}):t}async function Gn(e,t){let n=e[`~orpc`].outputSchema;return n?H({name:`validate_output`},async()=>{let e=await n[`~standard`].validate(t);if(e.issues)throw new W(`INTERNAL_SERVER_ERROR`,{message:`Output validation failed`,cause:new _n({message:`Output validation failed`,issues:e.issues,data:t})});return e.value}):t}async function Kn(e,t){let n=e[`~orpc`].middlewares,r=Math.min(Math.max(0,e[`~orpc`].inputValidationIndex),n.length),i=Math.min(Math.max(0,e[`~orpc`].outputValidationIndex),n.length),a=async(o,s,c)=>{let l=c;o===r&&(l=await Wn(e,l));let u=n[o],d=u?await H({name:`middleware.${u.name}`,signal:t.signal},async e=>(e?.setAttribute(`middleware.index`,o),e?.setAttribute(`middleware.name`,u.name),(await u({...t,context:s,next:async(...[e])=>{let t=e?.context??{};return{output:await a(o+1,Bn(s,t),l),context:t}}},l,Hn)).output)):await H({name:`handler`,signal:t.signal},()=>e[`~orpc`].handler({...t,context:s,input:l}));return o===i?await Gn(e,d):d};return a(0,t.context,t.input)}function qn(e,t){let n=e;for(let e=0;e<t.length;e++){let r=t[e];if(!n||zn(n)||!et(n))return;if(!Mn(n)){n=n[r];continue}let i=n,a=t.slice(e);return jn(async()=>Pn(qn((await Pn(i)).default,a)),Nn(i))}return n}function Jn(e){return new Proxy(e,{get(t,n){return typeof n==`string`?Jn(qn(e,[n])):Reflect.get(t,n)}})}function Yn(e,t){if(Mn(e)){let n=Nn(e),r=n?.prefix?En(t.prefix,n?.prefix):t.prefix;return Jn(jn(async()=>{let{default:n}=await Pn(e);return Pn(Yn(n,t))},{...n,prefix:r}))}if(zn(e)){let n=In(t.middlewares,e[`~orpc`].middlewares,{dedupeLeading:t.dedupeLeadingMiddlewares}),r=n.length-e[`~orpc`].middlewares.length;return new Rn({...e[`~orpc`],route:On(e[`~orpc`].route,t),errorMap:vn(t.errorMap,e[`~orpc`].errorMap),middlewares:n,inputValidationIndex:e[`~orpc`].inputValidationIndex+r,outputValidationIndex:e[`~orpc`].outputValidationIndex+r})}if(typeof e!=`object`||!e)return e;let n={};for(let r in e)n[r]=Yn(e[r],t);return n}var Xn=e=>{switch(e){case`label`:return`.`;case`matrix`:return`;`;case`simple`:return`,`;default:return`&`}},Zn=e=>{switch(e){case`form`:return`,`;case`pipeDelimited`:return`|`;case`spaceDelimited`:return`%20`;default:return`,`}},Qn=e=>{switch(e){case`label`:return`.`;case`matrix`:return`;`;case`simple`:return`,`;default:return`&`}},$n=({allowReserved:e,explode:t,name:n,style:r,value:i})=>{if(!t){let t=(e?i:i.map(e=>encodeURIComponent(e))).join(Zn(r));switch(r){case`label`:return`.${t}`;case`matrix`:return`;${n}=${t}`;case`simple`:return t;default:return`${n}=${t}`}}let a=Xn(r),o=i.map(t=>r===`label`||r===`simple`?e?t:encodeURIComponent(t):er({allowReserved:e,name:n,value:t})).join(a);return r===`label`||r===`matrix`?a+o:o},er=({allowReserved:e,name:t,value:n})=>{if(n==null)return``;if(typeof n==`object`)throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${t}=${e?n:encodeURIComponent(n)}`},tr=({allowReserved:e,explode:t,name:n,style:r,value:i,valueOnly:a})=>{if(i instanceof Date)return a?i.toISOString():`${n}=${i.toISOString()}`;if(r!==`deepObject`&&!t){let t=[];Object.entries(i).forEach(([n,r])=>{t=[...t,n,e?r:encodeURIComponent(r)]});let a=t.join(`,`);switch(r){case`form`:return`${n}=${a}`;case`label`:return`.${a}`;case`matrix`:return`;${n}=${a}`;default:return a}}let o=Qn(r),s=Object.entries(i).map(([t,i])=>er({allowReserved:e,name:r===`deepObject`?`${n}[${t}]`:t,value:i})).join(o);return r===`label`||r===`matrix`?o+s:s},nr=/\{[^{}]+\}/g,rr=({path:e,url:t})=>{let n=t,r=t.match(nr);if(r)for(let t of r){let r=!1,i=t.substring(1,t.length-1),a=`simple`;i.endsWith(`*`)&&(r=!0,i=i.substring(0,i.length-1)),i.startsWith(`.`)?(i=i.substring(1),a=`label`):i.startsWith(`;`)&&(i=i.substring(1),a=`matrix`);let o=e[i];if(o==null)continue;if(Array.isArray(o)){n=n.replace(t,$n({explode:r,name:i,style:a,value:o}));continue}if(typeof o==`object`){n=n.replace(t,tr({explode:r,name:i,style:a,value:o,valueOnly:!0}));continue}if(a===`matrix`){n=n.replace(t,`;${er({name:i,value:o})}`);continue}let s=encodeURIComponent(a===`label`?`.${o}`:o);n=n.replace(t,s)}return n},ir=({baseUrl:e,path:t,query:n,querySerializer:r,url:i})=>{let a=i.startsWith(`/`)?i:`/${i}`,o=(e??``)+a;t&&(o=rr({path:t,url:o}));let s=n?r(n):``;return s.startsWith(`?`)&&(s=s.substring(1)),s&&(o+=`?${s}`),o};function ar(e){let t=e.body!==void 0;if(t&&e.bodySerializer)return`serializedBody`in e?e.serializedBody!==void 0&&e.serializedBody!==``?e.serializedBody:null:e.body===``?null:e.body;if(t)return e.body}var or=async(e,t)=>{let n=typeof t==`function`?await t(e):t;if(n)return e.scheme===`bearer`?`Bearer ${n}`:e.scheme===`basic`?`Basic ${btoa(n)}`:n},sr={bodySerializer:e=>JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t)},cr=({parameters:e={},...t}={})=>n=>{let r=[];if(n&&typeof n==`object`)for(let i in n){let a=n[i];if(a==null)continue;let o=e[i]||t;if(Array.isArray(a)){let e=$n({allowReserved:o.allowReserved,explode:!0,name:i,style:`form`,value:a,...o.array});e&&r.push(e)}else if(typeof a==`object`){let e=tr({allowReserved:o.allowReserved,explode:!0,name:i,style:`deepObject`,value:a,...o.object});e&&r.push(e)}else{let e=er({allowReserved:o.allowReserved,name:i,value:a});e&&r.push(e)}}return r.join(`&`)},lr=e=>{if(!e)return`stream`;let t=e.split(`;`)[0]?.trim();if(t){if(t.startsWith(`application/json`)||t.endsWith(`+json`))return`json`;if(t===`multipart/form-data`)return`formData`;if([`application/`,`audio/`,`image/`,`video/`].some(e=>t.startsWith(e)))return`blob`;if(t.startsWith(`text/`))return`text`}},ur=(e,t)=>t?!!(e.headers.has(t)||e.query?.[t]||e.headers.get(`Cookie`)?.includes(`${t}=`)):!1;async function dr(e){for(let t of e.security??[]){if(ur(e,t.name))continue;let n=await or(t,e.auth);if(!n)continue;let r=t.name??`Authorization`;switch(t.in){case`query`:e.query||={},e.query[r]=n;break;case`cookie`:e.headers.append(`Cookie`,`${r}=${n}`);break;default:e.headers.set(r,n)}}}var fr=e=>ir({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:typeof e.querySerializer==`function`?e.querySerializer:cr(e.querySerializer),url:e.url}),pr=(e,t)=>{let n={...e,...t};return n.baseUrl?.endsWith(`/`)&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=hr(e.headers,t.headers),n},mr=e=>{let t=[];return e.forEach((e,n)=>{t.push([n,e])}),t},hr=(...e)=>{let t=new Headers;for(let n of e){if(!n)continue;let e=n instanceof Headers?mr(n):Object.entries(n);for(let[n,r]of e)if(r===null)t.delete(n);else if(Array.isArray(r))for(let e of r)t.append(n,e);else r!==void 0&&t.set(n,typeof r==`object`?JSON.stringify(r):r)}return t},gr=class{fns=[];clear(){this.fns=[]}eject(e){let t=this.getInterceptorIndex(e);this.fns[t]&&(this.fns[t]=null)}exists(e){let t=this.getInterceptorIndex(e);return!!this.fns[t]}getInterceptorIndex(e){return typeof e==`number`?this.fns[e]?e:-1:this.fns.indexOf(e)}update(e,t){let n=this.getInterceptorIndex(e);return this.fns[n]?(this.fns[n]=t,e):!1}use(e){return this.fns.push(e),this.fns.length-1}},_r=()=>({error:new gr,request:new gr,response:new gr}),vr=cr({allowReserved:!1,array:{explode:!0,style:`form`},object:{explode:!0,style:`deepObject`}}),yr={"Content-Type":`application/json`},br=(e={})=>({...sr,headers:yr,parseAs:`auto`,querySerializer:vr,...e});function xr({onRequest:e,onSseError:t,onSseEvent:n,responseTransformer:r,responseValidator:i,sseDefaultRetryDelay:a,sseMaxRetryAttempts:o,sseMaxRetryDelay:s,sseSleepFn:c,url:l,...u}){let d,f=c??(e=>new Promise(t=>setTimeout(t,e)));return{stream:async function*(){let c=a??3e3,p=0,m=u.signal??new AbortController().signal;for(;!m.aborted;){p++;let a=u.headers instanceof Headers?u.headers:new Headers(u.headers);d!==void 0&&a.set(`Last-Event-ID`,d);try{let t={redirect:`follow`,...u,body:u.serializedBody,headers:a,signal:m},o=new Request(l,t);e&&(o=await e(l,t));let s=await(u.fetch??globalThis.fetch)(o);if(!s.ok)throw Error(`SSE failed: ${s.status} ${s.statusText}`);if(!s.body)throw Error(`No body in SSE response`);let f=s.body.pipeThrough(new TextDecoderStream).getReader(),p=``,h=()=>{try{f.cancel()}catch{}};m.addEventListener(`abort`,h);try{for(;;){let{done:e,value:t}=await f.read();if(e)break;p+=t,p=p.replace(/\r\n?/g,`
|
|
2
|
+
import{fileURLToPath as e}from"node:url";import{dirname as t}from"node:path";const n=e(import.meta.url);t(n);import{createRequire as r}from"node:module";import{cancel as i,confirm as a,intro as o,isCancel as s,log as c,outro as l,select as u,spinner as d,text as f}from"@clack/prompts";import{cac as p}from"cac";import m from"picocolors";import{chmod as h,mkdir as g,mkdtemp as _,readFile as v,readdir as y,realpath as b,rm as x,stat as S,writeFile as C}from"node:fs/promises";import{homedir as w,platform as T}from"node:os";import E from"node:path";import{loadTailorKitConfig as ee}from"@tailorkit/app/config/loader";import{ORPCError as D,ORPCError as O,createORPCClient as te,wrapAsyncIteratorPreservingEventMeta as ne}from"@orpc/client";import{RPCLink as re}from"@orpc/client/fetch";import{z as k}from"zod";import{asSchema as A,uiMessageChunkSchema as ie}from"ai";import{RPCLink as ae}from"@orpc/client/websocket";import{createHash as oe}from"node:crypto";import{execFile as se,spawn as ce}from"node:child_process";import{existsSync as le}from"node:fs";import{promisify as ue}from"node:util";import{gzip as de}from"node:zlib";import{Liquid as fe}from"liquidjs";function j(e){return Array.isArray(e)?e:e==null?[]:[e]}function pe(e){return!e||typeof e!=`object`?!1:`next`in e&&typeof e.next==`function`&&Symbol.asyncIterator in e&&typeof e[Symbol.asyncIterator]==`function`}function M(e){if(!e)return!1;let t=typeof e;return t===`object`||t===`function`}var me=`orpc`;Object.getPrototypeOf(async function*(){}).constructor;function he(e){return M(e)?Object.getPrototypeOf(e)?.constructor:null}function ge(e,t){let n={...e};for(let e of t)delete n[e];return n}function N(e,t){return{...e,...t}}function P(e,t,n){t=j(t),n=j(n);let r=e;for(let e of n)e.init&&(r=e.init(r));let i=[...t,...n];for(let e of i)e.apply&&(r=e.apply(r));return[r,i]}var _e=class e{"~orpc";constructor(e){this[`~orpc`]=e}static[Symbol.hasInstance](t){return this===e?he(t)===e||M(t)&&M(t[`~orpc`])&&M(t[`~orpc`].errorMap)&&M(t[`~orpc`].meta)&&(t[`~orpc`].inputSchemas===void 0||Array.isArray(t[`~orpc`].inputSchemas))&&(t[`~orpc`].outputSchemas===void 0||Array.isArray(t[`~orpc`].outputSchemas)):Function.prototype[Symbol.hasInstance].call(this,t)}};function ve(e,t){if(e instanceof _e){let[n,r]=P(t.meta,t.metaPlugins,e[`~orpc`].metaPlugins);return new _e({...e[`~orpc`],errorMap:N(t.errorMap,e[`~orpc`].errorMap),meta:n,metaPlugins:r})}if(!M(e))return e;let n={};for(let r of Object.keys(e))n[r]=ve(e[r],t);return n}var ye=class extends Error{name=`ValidationError`;issues;invalidData;constructor(e){super(e.message,e),this.issues=e.issues,this.invalidData=e.invalidData}},be=Symbol.for(`ORPC_HIDDEN_META_PLUGINS`);function F(e){if(M(e))return e[be]}(class e extends _e{constructor(e){super(e)}static create(){return new e({errorMap:{},meta:{}})}meta(...t){let[n,r]=P(this[`~orpc`].meta,this[`~orpc`].metaPlugins,t);return new e({...this[`~orpc`],meta:n,metaPlugins:r})}errors(t){let n=new e({...this[`~orpc`],errorMap:N(this[`~orpc`].errorMap,t)}),r=F(t);return r&&(n=n.meta(...r)),n}input(t){let n=new e({...this[`~orpc`],inputSchemas:[...j(this[`~orpc`].inputSchemas),t]}),r=F(t);return r&&(n=n.meta(...r)),n}output(t){let n=new e({...this[`~orpc`],outputSchemas:[...j(this[`~orpc`].outputSchemas),t]}),r=F(t);return r&&(n=n.meta(...r)),n}router(e){return ve(e,this[`~orpc`])}}).create();var xe=Symbol.for(`ORPC_ASYNC_ITERATOR_OBJECT_SCHEMA_DETAILS`);function Se(e,t){return{"~standard":{[xe]:{yieldSchema:e,returnSchema:t},vendor:me,version:1,validate(n){return pe(n)?{value:ne(n,{async mapResult(n){let r=n.done?t:e;if(!r)return n;let i=await r[`~standard`].validate(n.value);if(i.issues)throw new D(`ASYNC_ITERATOR_OBJECT_VALIDATION_FAILED`,{message:`AsyncIteratorObject validation failed`,cause:new ye({issues:i.issues,message:`AsyncIteratorObject validation failed`,invalidData:n.value})});return{done:n.done,value:i.value}}})}:{issues:[{message:`Expect AsyncIteratorObject`,path:[]}]}}}}}var Ce=class e{"~orpc";constructor(e){this[`~orpc`]=e}static[Symbol.hasInstance](t){return this===e?he(t)===e||M(t)&&M(t[`~orpc`])&&M(t[`~orpc`].meta)&&(t[`~orpc`].metaPlugins===void 0||Array.isArray(t[`~orpc`].metaPlugins))&&typeof t[`~orpc`].loader==`function`:Function.prototype[Symbol.hasInstance].call(this,t)}};function we(e){return e instanceof Ce?e[`~orpc`].loader():Promise.resolve({default:e})}var Te=class e{"~orpc";constructor(e){this[`~orpc`]=e}static[Symbol.hasInstance](t){return this===e?he(t)===e||t instanceof _e&&Array.isArray(t[`~orpc`].orderedMiddlewares)&&typeof t[`~orpc`].handler==`function`:Function.prototype[Symbol.hasInstance].call(this,t)}};function Ee(e,t){if(e instanceof Ce){let[n,r]=P(t.meta,t.metaPlugins,e[`~orpc`].metaPlugins);return new Ce({meta:n,metaPlugins:r,async loader(){let{default:n}=await we(e);return we(Ee(n,t))}})}if(e instanceof Te){let[n,r]=P(t.meta,t.metaPlugins,e[`~orpc`].metaPlugins);return new Te({...ge(t,[`middlewares`,`errorMap`,`meta`,`metaPlugins`]),...e[`~orpc`],meta:n,metaPlugins:r,errorMap:N(t.errorMap,e[`~orpc`].errorMap),orderedMiddlewares:[...t.middlewares.map(e=>({middleware:e,inputSchemasLengthAtUse:0,outputSchemasLengthAtUse:0})),...e[`~orpc`].orderedMiddlewares]})}if(!M(e))return e;let n={};for(let[r,i]of Object.entries(e))n[r]=Ee(i,t);return n}function De({onRequest:e,onSseError:t,onSseEvent:n,responseTransformer:r,responseValidator:i,sseDefaultRetryDelay:a,sseMaxRetryAttempts:o,sseMaxRetryDelay:s,sseSleepFn:c,url:l,...u}){let d,f=c??(e=>new Promise(t=>setTimeout(t,e)));return{stream:async function*(){let c=a??3e3,p=0,m=u.signal??new AbortController().signal;for(;!m.aborted;){p++;let a=u.headers instanceof Headers?u.headers:new Headers(u.headers);d!==void 0&&a.set(`Last-Event-ID`,d);try{let t={redirect:`follow`,...u,body:u.serializedBody,headers:a,signal:m},o=new Request(l,t);e&&(o=await e(l,t));let s=await(u.fetch??globalThis.fetch)(o);if(!s.ok)throw Error(`SSE failed: ${s.status} ${s.statusText}`);if(!s.body)throw Error(`No body in SSE response`);let f=s.body.pipeThrough(new TextDecoderStream).getReader(),p=``,h=()=>{try{f.cancel().catch(()=>{})}catch{}};m.addEventListener(`abort`,h);try{for(;;){let{done:e,value:t}=await f.read();if(e)break;p+=t,p=p.replace(/\r\n?/g,`
|
|
44
3
|
`);let a=p.split(`
|
|
45
4
|
|
|
46
5
|
`);p=a.pop()??``;for(let e of a){let t=e.split(`
|
|
47
6
|
`),a=[],o;for(let e of t)if(e.startsWith(`data:`))a.push(e.replace(/^data:\s*/,``));else if(e.startsWith(`event:`))o=e.replace(/^event:\s*/,``);else if(e.startsWith(`id:`))d=e.replace(/^id:\s*/,``);else if(e.startsWith(`retry:`)){let t=Number.parseInt(e.replace(/^retry:\s*/,``),10);Number.isNaN(t)||(c=t)}let s,l=!1;if(a.length){let e=a.join(`
|
|
48
|
-
`);try{s=JSON.parse(e),l=!0}catch{s=e}}l&&(i&&await i(s),r&&(s=await r(s))),n?.({data:s,event:o,id:d,retry:c}),a.length&&(yield s)}}}finally{m.removeEventListener(`abort`,h),f.releaseLock()}break}catch(e){if(t?.(e),o!==void 0&&p>=o)break;let n=Math.min(c*2**(p-1),s??3e4);await f(n)}}}()}}var K=((e={})=>{let t=pr(br(),e),n=()=>({...t}),r=e=>(t=pr(t,e),n()),i=_r(),a=async e=>{let n={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:hr(t.headers,e.headers),serializedBody:void 0};n.security&&await dr(n),n.requestValidator&&await n.requestValidator(n),n.body!==void 0&&n.bodySerializer&&(n.serializedBody=n.bodySerializer(n.body)),(n.body===void 0||n.serializedBody===``)&&n.headers.delete(`Content-Type`);let r=n;return{opts:r,url:fr(r)}},o=async e=>{let n=e.throwOnError??t.throwOnError,r=e.responseStyle??t.responseStyle,o,s;try{let{opts:t,url:n}=await a(e),r={redirect:`follow`,...t,body:ar(t)};o=new Request(n,r);for(let e of i.request.fns)e&&(o=await e(o,t));let c=t.fetch;s=await c(o);for(let e of i.response.fns)e&&(s=await e(s,o,t));let l={request:o,response:s};if(s.ok){let e=(t.parseAs===`auto`?lr(s.headers.get(`Content-Type`)):t.parseAs)??`json`;if(s.status===204||s.headers.get(`Content-Length`)===`0`){let n;switch(e){case`arrayBuffer`:case`blob`:case`text`:n=await s[e]();break;case`formData`:n=new FormData;break;case`stream`:n=s.body;break;default:n={}}return t.responseStyle===`data`?n:{data:n,...l}}let n;switch(e){case`arrayBuffer`:case`blob`:case`formData`:case`text`:n=await s[e]();break;case`json`:{let e=await s.text();n=e?JSON.parse(e):{};break}case`stream`:return t.responseStyle===`data`?s.body:{data:s.body,...l}}return e===`json`&&(t.responseValidator&&await t.responseValidator(n),t.responseTransformer&&(n=await t.responseTransformer(n))),t.responseStyle===`data`?n:{data:n,...l}}let u=await s.text(),d;try{d=JSON.parse(u)}catch{}throw d??u}catch(t){let a=t;for(let t of i.error.fns)t&&(a=await t(a,s,o,e));if(a||={},n)throw a;return r===`data`?void 0:{error:a,request:o,response:s}}},s=e=>t=>o({...t,method:e}),c=e=>async t=>{let{opts:n,url:r}=await a(t);return xr({...n,body:n.body,method:e,onRequest:async(e,t)=>{let r=new Request(e,t);for(let e of i.request.fns)e&&(r=await e(r,n));return r},serializedBody:ar(n),url:r})};return{buildUrl:e=>fr({...t,...e}),connect:s(`CONNECT`),delete:s(`DELETE`),get:s(`GET`),getConfig:n,head:s(`HEAD`),interceptors:i,options:s(`OPTIONS`),patch:s(`PATCH`),post:s(`POST`),put:s(`PUT`),request:o,setConfig:r,sse:{connect:c(`CONNECT`),delete:c(`DELETE`),get:c(`GET`),head:c(`HEAD`),options:c(`OPTIONS`),patch:c(`PATCH`),post:c(`POST`),put:c(`PUT`),trace:c(`TRACE`)},trace:s(`TRACE`)}})(br({baseUrl:`https://tailorkit.dev/api/platform`})),Sr=e=>(e.client??K).get({url:`/apps`,...e}),Cr=e=>(e.client??K).post({url:`/apps`,...e,headers:{"Content-Type":`application/json`,...e.headers}}),wr=e=>(e.client??K).delete({url:`/apps/{appId}`,...e}),Tr=e=>(e.client??K).get({url:`/apps/{appId}`,...e}),Er=e=>(e.client??K).put({url:`/apps/{appId}`,...e,headers:{"Content-Type":`application/json`,...e.headers}}),Dr=e=>(e.client??K).post({url:`/apps/{appId}/deploy`,...e,headers:{"Content-Type":`application/json`,...e.headers}}),Or=e=>(e.client??K).post({url:`/cli-auth/approve`,...e,headers:{"Content-Type":`application/json`,...e.headers}}),kr=e=>(e.client??K).post({url:`/cli-auth/deny`,...e,headers:{"Content-Type":`application/json`,...e.headers}}),Ar=e=>(e.client??K).post({url:`/cli-auth/poll`,...e,headers:{"Content-Type":`application/json`,...e.headers}}),jr=e=>(e.client??K).post({url:`/cli-auth/start`,...e,headers:{"Content-Type":`application/json`,...e.headers}}),Mr=e=>(e.client??K).post({url:`/cli-auth/verify-token`,...e,headers:{"Content-Type":`application/json`,...e.headers}}),Nr=e=>(e.client??K).get({url:`/deployments`,...e}),Pr=e=>(e.client??K).post({url:`/deployments`,...e,headers:{"Content-Type":`application/json`,...e.headers}}),Fr=e=>(e.client??K).get({url:`/deployments/{deploymentId}`,...e}),Ir=e=>(e.client??K).post({url:`/deployments/{deploymentId}`,...e,headers:{"Content-Type":`application/json`,...e.headers}});Object.entries({$body_:`body`,$headers_:`headers`,$path_:`path`,$query_:`query`});var Lr={initialInputValidationIndex:0,initialOutputValidationIndex:0,dedupeLeadingMiddlewares:!0};function q(e,t){return t===void 0?Lr[e]:t}function Rr(e){let t=((...t)=>e(...t));return t.mapInput=t=>Rr((n,r,...i)=>e(n,t(r),...i)),t.concat=(t,n)=>{let r=n?Rr(t).mapInput(n):t;return Rr((t,n,i,...a)=>e({...t,next:(...[e])=>r({...t,context:{...t.context,...e?.context},next:(...[n])=>t.next({context:{...e?.context,...n?.context}})},n,i,...a)},n,i,...a))},t}function zr(e){return async t=>{try{return[null,await e(t)]}catch(e){if(e instanceof Error&&`digest`in e&&typeof e.digest==`string`&&e.digest.startsWith(`NEXT_`)||e instanceof Response&&`options`in e&&$e(e.options)||$e(e)&&e.isNotFound===!0)throw e;return[mt(e).toJSON(),void 0]}}}var Br=class e extends Rn{errors(t){return new e({...this[`~orpc`],errorMap:vn(this[`~orpc`].errorMap,t)})}meta(t){return new e({...this[`~orpc`],meta:Sn(this[`~orpc`].meta,t)})}route(t){return new e({...this[`~orpc`],route:Cn(this[`~orpc`].route,t)})}use(t,n){let r=n?Rr(t).mapInput(n):t;return new e({...this[`~orpc`],middlewares:Ln(this[`~orpc`].middlewares,r)})}callable(...e){let t=Un(this,...e);return new Proxy(t,{get:(e,t)=>Reflect.has(this,t)?Reflect.get(this,t):Reflect.get(e,t),has:(e,t)=>Reflect.has(this,t)||Reflect.has(e,t)})}actionable(...e){let t=zr(Un(this,...e));return new Proxy(t,{get:(e,t)=>Reflect.has(this,t)?Reflect.get(this,t):Reflect.get(e,t),has:(e,t)=>Reflect.has(this,t)||Reflect.has(e,t)})}},Vr=new class e{"~orpc";constructor(e){this[`~orpc`]=e}$config(t){let n=this[`~orpc`].inputValidationIndex-q(`initialInputValidationIndex`,this[`~orpc`].config.initialInputValidationIndex),r=this[`~orpc`].outputValidationIndex-q(`initialOutputValidationIndex`,this[`~orpc`].config.initialOutputValidationIndex);return new e({...this[`~orpc`],config:t,dedupeLeadingMiddlewares:q(`dedupeLeadingMiddlewares`,t.dedupeLeadingMiddlewares),inputValidationIndex:q(`initialInputValidationIndex`,t.initialInputValidationIndex)+n,outputValidationIndex:q(`initialOutputValidationIndex`,t.initialOutputValidationIndex)+r})}$context(){return new e({...this[`~orpc`],middlewares:[],inputValidationIndex:q(`initialInputValidationIndex`,this[`~orpc`].config.initialInputValidationIndex),outputValidationIndex:q(`initialOutputValidationIndex`,this[`~orpc`].config.initialOutputValidationIndex)})}$meta(t){return new e({...this[`~orpc`],meta:t})}$route(t){return new e({...this[`~orpc`],route:t})}$input(t){return new e({...this[`~orpc`],inputSchema:t})}middleware(e){return Rr(e)}errors(t){return new e({...this[`~orpc`],errorMap:vn(this[`~orpc`].errorMap,t)})}use(t,n){let r=n?Rr(t).mapInput(n):t;return new e({...this[`~orpc`],middlewares:Ln(this[`~orpc`].middlewares,r)})}meta(t){return new e({...this[`~orpc`],meta:Sn(this[`~orpc`].meta,t)})}route(t){return new e({...this[`~orpc`],route:Cn(this[`~orpc`].route,t)})}input(t){return new e({...this[`~orpc`],inputSchema:t,inputValidationIndex:q(`initialInputValidationIndex`,this[`~orpc`].config.initialInputValidationIndex)+this[`~orpc`].middlewares.length})}output(t){return new e({...this[`~orpc`],outputSchema:t,outputValidationIndex:q(`initialOutputValidationIndex`,this[`~orpc`].config.initialOutputValidationIndex)+this[`~orpc`].middlewares.length})}handler(e){return new Br({...this[`~orpc`],handler:e})}prefix(t){return new e({...this[`~orpc`],prefix:En(this[`~orpc`].prefix,t)})}tag(...t){return new e({...this[`~orpc`],tags:Dn(this[`~orpc`].tags,t)})}router(e){return Yn(e,this[`~orpc`])}lazy(e){return Yn(jn(e),this[`~orpc`])}}({config:{},route:{},meta:{},errorMap:{},inputValidationIndex:q(`initialInputValidationIndex`),outputValidationIndex:q(`initialOutputValidationIndex`),middlewares:[],dedupeLeadingMiddlewares:!0});function Hr(e){return Yt(new gn({async fetch(t,n){let r=await(typeof e.headers==`function`?e.headers():e.headers),i=new Headers(r);return new Headers(n?.headers).forEach((e,t)=>{i.set(t,e)}),(e.fetch??fetch)(t,{...n,headers:i})},method:`POST`,url:e.url}))}var J=Vr.$context();function Ur(e){if(!e.tailorkit)throw new W(`UNAUTHORIZED`,{message:`Unauthorized.`});return e.tailorkit}function Y(e){return Ur(e).scopeId}function Wr(e){let[t,n]=e.headers.get(`authorization`)?.split(` `)??[];if(t!==`Bearer`||!n)throw new W(`UNAUTHORIZED`,{message:`Missing CLI deploy token.`});return n}var X=J.middleware(async({context:e,next:t})=>{let n=await Mr({body:{deployToken:Wr(e.request)},client:e.platform,headers:e.platformHeaders}),r=`data`in n?n.data:n;if(!r?.scopeId)throw new W(`UNAUTHORIZED`,{message:`Invalid CLI deploy token.`});return t({context:{tailorkit:{scopeId:r.scopeId}}})}),Gr=J.middleware(async({context:e,next:t})=>{let n=await e.authenticate({request:e.request});if(!n)throw new W(`UNAUTHORIZED`,{message:`Unauthorized.`});return t({context:{tailorkit:n}})}),Kr=async(e,t)=>{if(e===void 0)return t;let n=await e[`~standard`].validate(t);if(`issues`in n)throw new W(`BAD_REQUEST`,{message:`Invalid TailorKit payload`});return n.value};J.use(Gr).input(w.object({input:w.unknown().optional(),path:w.string()})).handler(async({context:e,input:t})=>{let n=e.actions.get(t.path);if(n===void 0)throw new W(`NOT_FOUND`,{message:`Action not found`});let r=await Kr(n.definition.input,t.input),i=await n.handler({context:Ur(e).actionContext,input:r});return Kr(n.definition.output,i)});var qr=w.object({page:w.number().int().min(1).optional(),pageSize:w.number().int().min(1).max(100).optional()}),Jr=w.object({description:w.string().nullable(),name:w.string()});J.use(X).input(Jr).handler(async({context:e,input:t})=>await Cr({body:{...t,scopeId:Y(e)},client:e.platform,headers:e.platformHeaders})),J.use(X).input(w.object({appId:w.string()})).handler(async({context:e,input:t})=>await wr({client:e.platform,headers:e.platformHeaders,path:{appId:t.appId},query:{scopeId:Y(e)}})),J.use(X).input(w.object({appId:w.string(),deploymentId:w.string()})).handler(async({context:e,input:t})=>await Dr({body:{deploymentId:t.deploymentId},client:e.platform,headers:e.platformHeaders,path:{appId:t.appId},query:{scopeId:Y(e)}})),J.use(X).input(w.object({appId:w.string()})).handler(async({context:e,input:t})=>await Tr({client:e.platform,headers:e.platformHeaders,path:{appId:t.appId},query:{scopeId:Y(e)}})),J.use(X).input(qr.optional()).handler(async({context:e,input:t})=>await Sr({client:e.platform,headers:e.platformHeaders,query:{page:t?.page,pageSize:t?.pageSize,scopeId:Y(e)}})),J.use(X).input(w.object({appId:w.string()}).extend(Jr.shape)).handler(async({context:e,input:t})=>await Er({body:{description:t.description,name:t.name},client:e.platform,headers:e.platformHeaders,path:{appId:t.appId},query:{scopeId:Y(e)}}));var Yr=async e=>{try{return await e}catch(e){throw typeof e==`string`&&e.toLowerCase()===`unauthorized`?new W(`UNAUTHORIZED`,{message:`TailorKit platform rejected the host project key. Check TAILORKIT_PROJECT_KEY.`}):e}};J.use(Gr).input(w.object({userCode:w.string().min(1)})).handler(async({context:e,input:t})=>await Yr(Or({body:{scopeId:Y(e),userCode:t.userCode},client:e.platform,headers:e.platformHeaders}))),J.use(Gr).input(w.object({userCode:w.string().min(1)})).handler(async({context:e,input:t})=>await Yr(kr({body:{userCode:t.userCode},client:e.platform,headers:e.platformHeaders}))),J.input(w.object({deviceCode:w.string().min(1)})).handler(async({context:e,input:t})=>await Yr(Ar({body:{deviceCode:t.deviceCode},client:e.platform,headers:e.platformHeaders}))),J.input(w.object({})).handler(async({context:e})=>await Yr(jr({body:{},client:e.platform,headers:e.platformHeaders}))),J.input(w.object({})).use(X).handler(({context:e})=>({scopeId:Y(e)}));var Xr=w.object({page:w.number().int().min(1).optional(),pageSize:w.number().int().min(1).max(100).optional()}),Zr=w.object({checksum:w.string(),contentLength:w.number().int().min(1),contentType:w.literal(`application/javascript`),encoding:w.literal(`utf-8`),objectKey:w.literal(`client.js`)}),Qr=e=>{if(e instanceof Error)return e.message;if(typeof e==`string`)return e;if(e&&typeof e==`object`&&`message`in e){let t=e.message;return typeof t==`string`?t:void 0}},$r=e=>Qr(e)?.toLowerCase().includes(`not found`)??!1,ei=e=>{throw $r(e)?new W(`NOT_FOUND`,{message:`App not found.`}):e};J.use(X).input(w.object({appId:w.string(),assets:w.tuple([Zr])})).handler(async({context:e,input:t})=>{try{return await Pr({body:{appId:t.appId,assets:t.assets,scopeId:Y(e)},client:e.platform,headers:e.platformHeaders})}catch(e){ei(e)}}),J.use(X).input(w.object({deploymentId:w.string()})).handler(async({context:e,input:t})=>await Fr({client:e.platform,headers:e.platformHeaders,path:{deploymentId:t.deploymentId},query:{scopeId:Y(e)}})),J.use(X).input(w.object({appId:w.string()}).merge(Xr)).handler(async({context:e,input:t})=>await Nr({client:e.platform,headers:e.platformHeaders,query:{appId:t.appId,page:t.page,pageSize:t.pageSize,scopeId:Y(e)}})),J.use(X).input(w.object({deploymentId:w.string(),rollout:w.boolean().optional()})).handler(async({context:e,input:t})=>await Ir({body:{scopeId:Y(e),rollout:t.rollout},client:e.platform,headers:e.platformHeaders,path:{deploymentId:t.deploymentId}}));var ti=e=>{let t=new URL(e);return t.hash=``,t.search=``,t.pathname=t.pathname.replace(/\/+$/u,``),t.toString().replace(/\/$/u,``)},ni=C.join(x(),`.tailorkit`,`auth.json`),ri=18e5,ii=2e3,ai=w.object({deployToken:w.string().min(1),scopeId:w.string().min(1).optional()}),oi=w.object({hosts:w.record(w.string(),ai).optional()}).passthrough(),si=e=>new Promise(t=>setTimeout(t,e)),ci=e=>{if(e&&typeof e==`object`&&`error`in e&&e.error!==void 0)throw e.error},li=async()=>{try{return oi.parse(JSON.parse(await _(ni,`utf-8`)))}catch(e){if(e&&typeof e==`object`&&`code`in e&&e.code===`ENOENT`)return{};throw e}},ui=async e=>{await g(C.dirname(ni),{recursive:!0}),await b(ni,`${JSON.stringify(e,null,2)}\n`,{encoding:`utf-8`,mode:384}),await h(ni,384)},di=async e=>{let t=await Me(e.configPath,e.cwd);if(t.config.host)return ti(t.config.host);throw Error(`Missing TailorKit host URL. Set host in tailorkit.config.ts.`)},fi=(e,t)=>{let n=new URL(e);return n.pathname=`${n.pathname.replace(/\/+$/u,``)}/cli-auth/approve`,n.search=``,n.searchParams.set(`code`,t),n.hash=``,n.toString()},pi=e=>Error(`Not logged in for ${e}. Run tailorkit login after checking host in tailorkit.config.ts.`),mi=async(e,t)=>{let n=await li();await ui({...n,hosts:{...n.hosts,[e]:t}})},hi=async e=>{let t=await li();if(!t.hosts?.[e])return!1;let{[e]:n,...r}=t.hosts,i={...t,hosts:r};return Object.keys(r).length===0?(await v(ni,{force:!0}),!0):(await ui(i),!0)},gi=async e=>(await li()).hosts?.[e],_i=async(e,t)=>{let n=await di(e),r=Hr({url:n}),i=await r.cliAuth.start({});ci(i);let a=`data`in i?i.data:i,o=new Date(a.expiresAt),s=Date.now()+(e.timeout??ri);for(t({expiresAt:o,hostUrl:n,userCode:a.userCode});Date.now()<s&&Date.now()<o.getTime();){await si(ii);let e=await r.cliAuth.poll({deviceCode:a.deviceCode});ci(e);let t=`data`in e?e.data:e;switch(t.status){case`pending`:continue;case`denied`:throw Error(`CLI login was denied.`);case`expired`:throw Error(`CLI login expired.`);case`approved`:return await mi(n,{deployToken:t.deployToken,scopeId:t.scopeId}),{hostUrl:n,scopeId:t.scopeId};default:throw Error(`Unexpected CLI login status.`)}}throw Error(`Timed out waiting for CLI login approval.`)},vi=async e=>{let t=await di(e),n=await gi(t);if(!n?.deployToken)throw pi(t);let r=Hr({headers:{authorization:`Bearer ${n.deployToken}`},url:t}),i;try{let e=await r.cliAuth.verifyToken({});ci(e),i=`data`in e?e.data:e}catch{throw pi(t)}return await mi(t,{deployToken:n.deployToken,scopeId:i.scopeId}),{hostUrl:t,scopeId:i.scopeId}},yi=async e=>{let t=await di(e);return{hostUrl:t,removed:await hi(t)}},bi=1048576,xi=re(ie),Si=e=>{if(e&&typeof e==`object`&&`error`in e&&e.error!==void 0)throw e.error;let t=e&&typeof e==`object`&&`data`in e?e.data:e;return t&&typeof t==`object`&&`body`in t?t.body:t},Ci=e=>{if(e instanceof Error)return e.message;if(typeof e==`string`)return e;if(e&&typeof e==`object`&&`message`in e){let t=e.message;return typeof t==`string`?t:void 0}},wi=e=>Ci(e)?.toLowerCase().includes(`not found`)??!1,Ti=async(e,t)=>{let n=C.join(e,`tailorkit-upload.json`);return t.parse(JSON.parse(await _(n,`utf-8`)))},Ei=e=>te(`sha256`).update(e).digest(`hex`),Di=async e=>{try{let t=JSON.parse(await _(C.join(e,`package.json`),`utf-8`));if(typeof t.name==`string`&&t.name.trim())return t.name.trim()}catch{}return C.basename(e)},Oi=async(e,t)=>{let n=await _(e,`utf-8`),r=` appId: ${JSON.stringify(t)},`;if(/^\s*appId\s*:/mu.test(n)){await b(e,n.replace(/^(\s*)appId\s*:\s*(['"]).*?\2\s*,?/mu,`$1appId: ${JSON.stringify(t)},`),`utf-8`);return}let i=/(export\s+default\s+\{)(\r?\n)/u;if(i.test(n)){await b(e,n.replace(i,`$1$2${r}$2`),`utf-8`);return}let a=/(export\s+default\s+(?:defineTailorKitConfig|defineConfig)\(\s*\{)(\r?\n)/u;if(a.test(n)){await b(e,n.replace(a,`$1$2${r}$2`),`utf-8`);return}throw Error(`Could not write appId to ${e}. Add appId: ${JSON.stringify(t)} manually.`)},ki=async(e,t)=>{if(t.byteLength>bi)throw Error(`Deployment asset exceeds ${bi} bytes.`);let n=new Headers(e.headers);n.has(`content-type`)||n.set(`content-type`,`application/javascript`);let r=await fetch(e.uploadUrl,{body:new Uint8Array(t),headers:n,method:`PUT`});if(!r.ok)throw Error(`Asset upload failed with ${r.status} ${r.statusText}.`)},Ai=e=>{for(let t of[`tsconfig.json`,`jsconfig.json`]){let n=C.join(e,t);if(ne(n))return n}},ji=e=>{let t=r(C.join(e,`package.json`));try{return t(`typescript`)}catch{return}},Mi=(e,t,n)=>t.map(t=>{let r=t,i=e.flattenDiagnosticMessageText(r.messageText,`
|
|
49
|
-
`);if(r.file===void 0||r.start===void 0)return`TS${r.code}: ${i}`;let a=e.getLineAndCharacterOfPosition(r.file,r.start);return`${C.relative(n,r.file.fileName)}(${a.line+1},${a.character+1}): error TS${r.code}: ${i}`}).join(`
|
|
50
|
-
`),Ni=(e,t)=>{let n=ji(e.root),r=Ai(e.root);if(n===void 0||r===void 0)return;let i=t.entry??e.config.client?.entry??`./src/client.ts`,a=C.resolve(e.root,i),o=n.readConfigFile(r,n.sys.readFile);if(o.error!==void 0)return{command:`tsc --noEmit ${C.relative(e.root,a)}`,exitCode:1,output:Mi(n,[o.error],e.root)};let s=n.parseJsonConfigFileContent(o.config,n.sys,e.root,{noEmit:!0},r);if(s.errors.length>0)return{command:`tsc --noEmit ${C.relative(e.root,a)}`,exitCode:1,output:Mi(n,s.errors,e.root)};let c=n.createCompilerHost(s.options),l=n.createProgram({host:c,options:s.options,rootNames:[a]}),u=[...n.getPreEmitDiagnostics(l),...l.emit().diagnostics];if(u.length!==0)return{command:`tsc --noEmit ${C.relative(e.root,a)}`,exitCode:1,output:Mi(n,u,e.root)}},Pi=async e=>{let t=await Me(e.configPath,e.cwd),n=t.config.appId,r=!1,i=await vi(e),a=await gi(i.hostUrl);if(!a?.deployToken)throw Error(`Not logged in for ${i.hostUrl}. Run tailorkit login after checking host in tailorkit.config.ts.`);let{buildApp:o,tailorkitUploadManifestSchema:s}=await import(`./assets/builder-wgJqHM_A.js`),[c,l]=await Promise.allSettled([o(e),Ni(t,e)]);if(c.status===`rejected`)throw c.reason;if(l.status===`rejected`)throw l.reason;if(l.value!==void 0&&!await e.onTypecheckFailed?.(l.value))throw Error(`Deployment cancelled because type check failed.`);let u=C.resolve(t.root,e.outDir??t.config.build?.outDir??`.tailorkit`),d=await Ti(u,s),f=C.join(u,d.assets.client),p=await _(f),m=await xi(p),h=Hr({headers:{authorization:`Bearer ${a.deployToken}`},url:i.hostUrl}),g=async a=>{let o=await Di(t.root);if(!await e.onMissingAppId?.({appName:o,configPath:t.filepath,hostUrl:i.hostUrl,reason:a}))throw Error(`Deployment cancelled.`);return n=Si(await h.apps.create({description:null,name:o})).id,r=!0,await Oi(t.filepath,n),n};n||=await g(`missing`);let v=async e=>Si(await h.deployments.create({appId:e,assets:[{checksum:Ei(p),contentLength:p.byteLength,contentType:`application/javascript`,encoding:`utf-8`,objectKey:d.assets.client}]})),y;try{y=await v(n)}catch(e){if(!wi(e))throw e;n=await g(`not-found`),y=await v(n)}await ki(y.assets[0],p);let b=Si(await h.deployments.publish({deploymentId:y.deployment.id,rollout:!0}));return{appId:n,createdApp:r,deploymentId:b.id,hostUrl:i.hostUrl,status:b.status,uploadedFiles:[{gzipSize:m.byteLength,path:d.assets.client,size:p.byteLength}]}},Fi=`/* eslint-disable */
|
|
7
|
+
`);try{s=JSON.parse(e),l=!0}catch{s=e}}l&&(i&&await i(s),r&&(s=await r(s))),n?.({data:s,event:o,id:d,retry:c}),a.length&&(yield s)}}}finally{m.removeEventListener(`abort`,h),f.releaseLock()}break}catch(e){if(t?.(e),o!==void 0&&p>=o)break;let n=Math.min(c*2**(p-1),s??3e4);await f(n)}}}()}}var Oe=e=>{switch(e){case`label`:return`.`;case`matrix`:return`;`;case`simple`:return`,`;default:return`&`}},ke=e=>{switch(e){case`form`:return`,`;case`pipeDelimited`:return`|`;case`spaceDelimited`:return`%20`;default:return`,`}},Ae=e=>{switch(e){case`label`:return`.`;case`matrix`:return`;`;case`simple`:return`,`;default:return`&`}},je=({allowReserved:e,explode:t,name:n,style:r,value:i})=>{if(!t){let t=(e?i:i.map(e=>encodeURIComponent(e))).join(ke(r));switch(r){case`label`:return`.${t}`;case`matrix`:return`;${n}=${t}`;case`simple`:return t;default:return`${n}=${t}`}}let a=Oe(r),o=i.map(t=>r===`label`||r===`simple`?e?t:encodeURIComponent(t):Me({allowReserved:e,name:n,value:t})).join(a);return r===`label`||r===`matrix`?a+o:o},Me=({allowReserved:e,name:t,value:n})=>{if(n==null)return``;if(typeof n==`object`)throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${t}=${e?n:encodeURIComponent(n)}`},Ne=({allowReserved:e,explode:t,name:n,style:r,value:i,valueOnly:a})=>{if(i instanceof Date)return a?i.toISOString():`${n}=${i.toISOString()}`;if(r!==`deepObject`&&!t){let t=[];Object.entries(i).forEach(([n,r])=>{t=[...t,n,e?r:encodeURIComponent(r)]});let a=t.join(`,`);switch(r){case`form`:return`${n}=${a}`;case`label`:return`.${a}`;case`matrix`:return`;${n}=${a}`;default:return a}}let o=Ae(r),s=Object.entries(i).map(([t,i])=>Me({allowReserved:e,name:r===`deepObject`?`${n}[${t}]`:t,value:i})).join(o);return r===`label`||r===`matrix`?o+s:s},Pe=/\{[^{}]+\}/g,Fe=({path:e,url:t})=>{let n=t,r=t.match(Pe);if(r)for(let t of r){let r=!1,i=t.substring(1,t.length-1),a=`simple`;i.endsWith(`*`)&&(r=!0,i=i.substring(0,i.length-1)),i.startsWith(`.`)?(i=i.substring(1),a=`label`):i.startsWith(`;`)&&(i=i.substring(1),a=`matrix`);let o=e[i];if(o==null)continue;if(Array.isArray(o)){n=n.replace(t,je({explode:r,name:i,style:a,value:o}));continue}if(typeof o==`object`){n=n.replace(t,Ne({explode:r,name:i,style:a,value:o,valueOnly:!0}));continue}if(a===`matrix`){n=n.replace(t,`;${Me({name:i,value:o})}`);continue}let s=encodeURIComponent(a===`label`?`.${o}`:o);n=n.replace(t,s)}return n},Ie=({baseUrl:e,path:t,query:n,querySerializer:r,url:i})=>{let a=i.startsWith(`/`)?i:`/${i}`,o=(e??``)+a;t&&(o=Fe({path:t,url:o}));let s=n?r(n):``;return s.startsWith(`?`)&&(s=s.substring(1)),s&&(o+=`?${s}`),o};function Le(e){let t=e.body!==void 0;if(t&&e.bodySerializer)return`serializedBody`in e?e.serializedBody!==void 0&&e.serializedBody!==``?e.serializedBody:null:e.body===``?null:e.body;if(t)return e.body}var Re=async(e,t)=>{let n=typeof t==`function`?await t(e):t;if(n)return e.scheme===`bearer`?`Bearer ${n}`:e.scheme===`basic`?`Basic ${btoa(n)}`:n},ze={bodySerializer:e=>JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t)},Be=({parameters:e={},...t}={})=>n=>{let r=[];if(n&&typeof n==`object`)for(let i in n){let a=n[i];if(a==null)continue;let o=e[i]||t;if(Array.isArray(a)){let e=je({allowReserved:o.allowReserved,explode:!0,name:i,style:`form`,value:a,...o.array});e&&r.push(e)}else if(typeof a==`object`){let e=Ne({allowReserved:o.allowReserved,explode:!0,name:i,style:`deepObject`,value:a,...o.object});e&&r.push(e)}else{let e=Me({allowReserved:o.allowReserved,name:i,value:a});e&&r.push(e)}}return r.join(`&`)},Ve=e=>{if(!e)return`stream`;let t=e.split(`;`)[0]?.trim();if(t){if(t.startsWith(`application/json`)||t.endsWith(`+json`))return`json`;if(t===`multipart/form-data`)return`formData`;if([`application/`,`audio/`,`image/`,`video/`].some(e=>t.startsWith(e)))return`blob`;if(t.startsWith(`text/`))return`text`}},He=(e,t)=>t?!!(e.headers.has(t)||e.query?.[t]||e.headers.get(`Cookie`)?.includes(`${t}=`)):!1;async function Ue(e){for(let t of e.security??[]){if(He(e,t.name))continue;let n=await Re(t,e.auth);if(!n)continue;let r=t.name??`Authorization`;switch(t.in){case`query`:e.query||={},e.query[r]=n;break;case`cookie`:e.headers.append(`Cookie`,`${r}=${n}`);break;default:e.headers.set(r,n)}}}var We=e=>Ie({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:typeof e.querySerializer==`function`?e.querySerializer:Be(e.querySerializer),url:e.url}),Ge=(e,t)=>{let n={...e,...t};return n.baseUrl?.endsWith(`/`)&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=qe(e.headers,t.headers),n},Ke=e=>{let t=[];return e.forEach((e,n)=>{t.push([n,e])}),t},qe=(...e)=>{let t=new Headers;for(let n of e){if(!n)continue;let e=n instanceof Headers?Ke(n):Object.entries(n);for(let[n,r]of e)if(r===null)t.delete(n);else if(Array.isArray(r))for(let e of r)t.append(n,e);else r!==void 0&&t.set(n,typeof r==`object`?JSON.stringify(r):r)}return t},Je=class{fns=[];clear(){this.fns=[]}eject(e){let t=this.getInterceptorIndex(e);this.fns[t]&&(this.fns[t]=null)}exists(e){let t=this.getInterceptorIndex(e);return!!this.fns[t]}getInterceptorIndex(e){return typeof e==`number`?this.fns[e]?e:-1:this.fns.indexOf(e)}update(e,t){let n=this.getInterceptorIndex(e);return this.fns[n]?(this.fns[n]=t,e):!1}use(e){return this.fns.push(e),this.fns.length-1}},Ye=()=>({error:new Je,request:new Je,response:new Je}),Xe=Be({allowReserved:!1,array:{explode:!0,style:`form`},object:{explode:!0,style:`deepObject`}}),Ze={"Content-Type":`application/json`},Qe=(e={})=>({...ze,headers:Ze,parseAs:`auto`,querySerializer:Xe,...e}),I=((e={})=>{let t=Ge(Qe(),e),n=()=>({...t}),r=e=>(t=Ge(t,e),n()),i=Ye(),a=async e=>{let n={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:qe(t.headers,e.headers),serializedBody:void 0};n.security&&await Ue(n),n.requestValidator&&await n.requestValidator(n),n.body!==void 0&&n.bodySerializer&&(n.serializedBody=n.bodySerializer(n.body)),(n.body===void 0||n.serializedBody===``)&&n.headers.delete(`Content-Type`);let r=n;return{opts:r,url:We(r)}},o=async e=>{let n=e.throwOnError??t.throwOnError,r=e.responseStyle??t.responseStyle,o,s;try{let{opts:t,url:n}=await a(e),r={redirect:`follow`,...t,body:Le(t)};o=new Request(n,r);for(let e of i.request.fns)e&&(o=await e(o,t));let c=t.fetch;s=await c(o);for(let e of i.response.fns)e&&(s=await e(s,o,t));let l={request:o,response:s};if(s.ok){let e=(t.parseAs===`auto`?Ve(s.headers.get(`Content-Type`)):t.parseAs)??`json`;if(s.status===204||s.headers.get(`Content-Length`)===`0`){let n;switch(e){case`arrayBuffer`:case`blob`:case`text`:n=await s[e]();break;case`formData`:n=new FormData;break;case`stream`:n=s.body;break;default:n={}}return t.responseStyle===`data`?n:{data:n,...l}}let n;switch(e){case`arrayBuffer`:case`blob`:case`formData`:case`text`:n=await s[e]();break;case`json`:{let e=await s.text();n=e?JSON.parse(e):{};break}case`stream`:return t.responseStyle===`data`?s.body:{data:s.body,...l}}return e===`json`&&(t.responseValidator&&await t.responseValidator(n),t.responseTransformer&&(n=await t.responseTransformer(n))),t.responseStyle===`data`?n:{data:n,...l}}let u=await s.text(),d;try{d=JSON.parse(u)}catch{}throw d??u}catch(t){let a=t;for(let t of i.error.fns)t&&(a=await t(a,s,o,e));if(a||={},n)throw a;return r===`data`?void 0:{error:a,request:o,response:s}}},s=e=>t=>o({...t,method:e}),c=e=>async t=>{let{opts:n,url:r}=await a(t);return De({...n,body:n.body,method:e,onRequest:async(e,t)=>{let r=new Request(e,t);for(let e of i.request.fns)e&&(r=await e(r,n));return r},serializedBody:Le(n),url:r})};return{buildUrl:e=>We({...t,...e}),connect:s(`CONNECT`),delete:s(`DELETE`),get:s(`GET`),getConfig:n,head:s(`HEAD`),interceptors:i,options:s(`OPTIONS`),patch:s(`PATCH`),post:s(`POST`),put:s(`PUT`),request:o,setConfig:r,sse:{connect:c(`CONNECT`),delete:c(`DELETE`),get:c(`GET`),head:c(`HEAD`),options:c(`OPTIONS`),patch:c(`PATCH`),post:c(`POST`),put:c(`PUT`),trace:c(`TRACE`)},trace:s(`TRACE`)}})(Qe({baseUrl:`https://tailorkit.dev/api/platform`})),$e=e=>(e.client??I).sse.post({url:`/app-agent/chat`,...e,headers:{"Content-Type":`application/json`,...e.headers}}),et=e=>(e.client??I).post({url:`/apps/list`,...e,headers:{"Content-Type":`application/json`,...e.headers}}),tt=e=>(e.client??I).post({url:`/apps/{appId}/lookup`,...e,headers:{"Content-Type":`application/json`,...e.headers}}),nt=e=>(e.client??I).post({url:`/apps`,...e,headers:{"Content-Type":`application/json`,...e.headers}}),rt=e=>(e.client??I).delete({url:`/apps/{appId}`,...e,headers:{"Content-Type":`application/json`,...e.headers}}),it=e=>(e.client??I).put({url:`/apps/{appId}`,...e,headers:{"Content-Type":`application/json`,...e.headers}}),at=e=>(e.client??I).post({url:`/apps/{appId}/deploy`,...e,headers:{"Content-Type":`application/json`,...e.headers}}),ot=e=>(e.client??I).post({url:`/cli-auth/approve`,...e,headers:{"Content-Type":`application/json`,...e.headers}}),st=e=>(e.client??I).post({url:`/cli-auth/deny`,...e,headers:{"Content-Type":`application/json`,...e.headers}}),ct=e=>(e.client??I).post({url:`/cli-auth/poll`,...e,headers:{"Content-Type":`application/json`,...e.headers}}),lt=e=>(e.client??I).post({url:`/cli-auth/start`,...e,headers:{"Content-Type":`application/json`,...e.headers}}),ut=e=>(e.client??I).post({url:`/cli-auth/verify-token`,...e,headers:{"Content-Type":`application/json`,...e.headers}}),dt=e=>(e.client??I).post({url:`/deployments/list`,...e,headers:{"Content-Type":`application/json`,...e.headers}}),ft=e=>(e.client??I).post({url:`/deployments/{deploymentId}/lookup`,...e,headers:{"Content-Type":`application/json`,...e.headers}}),pt=e=>(e.client??I).post({url:`/deployments`,...e,headers:{"Content-Type":`application/json`,...e.headers}}),mt=e=>(e.client??I).post({url:`/deployments/{deploymentId}`,...e,headers:{"Content-Type":`application/json`,...e.headers}}),ht=e=>(e.client??I).post({url:`/preview/start`,...e,headers:{"Content-Type":`application/json`,...e.headers}}),gt=e=>(e.client??I).post({url:`/preview/{sessionId}/stop`,...e,headers:{"Content-Type":`application/json`,...e.headers}});Object.entries({$body_:`body`,$headers_:`headers`,$path_:`path`,$query_:`query`});var _t=class e extends Te{meta(...t){let[n,r]=P(this[`~orpc`].meta,this[`~orpc`].metaPlugins,t);return new e({...this[`~orpc`],meta:n,metaPlugins:r})}errors(t){let n=new e({...this[`~orpc`],errorMap:N(this[`~orpc`].errorMap,t)}),r=F(t);return r&&(n=n.meta(...r)),n}use(t){let n=new e({...this[`~orpc`],errorMap:N(t[`~orpc`]?.errorMap,this[`~orpc`].errorMap),orderedMiddlewares:[...this[`~orpc`].orderedMiddlewares,{middleware:t,inputSchemasLengthAtUse:this[`~orpc`].inputSchemas?.length,outputSchemasLengthAtUse:this[`~orpc`].outputSchemas?.length}]});return t[`~orpc`]?.metaPlugins&&(n=n.meta(...t[`~orpc`]?.metaPlugins)),n}};function vt(e){let t=((...t)=>e(...t));return t[`~orpc`]=e[`~orpc`],Object.defineProperty(t,"name",{value:e.name}),t.adaptInput=t=>{let n=vt((n,r,...i)=>e(n,t(r),...i));return n[`~orpc`]=e[`~orpc`],Object.defineProperty(n,"name",{value:e.name}),n},t.errors=e=>{let n=vt(t);return n[`~orpc`]={...t[`~orpc`],errorMap:N(t[`~orpc`]?.errorMap,e)},n},t.use=n=>{let r=vt((t,...r)=>e({...t,async next(e){let i=await n({...t,context:{...t.context,...e?.context},next(n,...r){return t.next({...t,context:{...e?.context,...n?.context}},...r)}},...r);return{...i,context:{...e?.context,...i.context}}}},...r));return r[`~orpc`]={...t[`~orpc`],errorMap:N(n[`~orpc`]?.errorMap,t[`~orpc`]?.errorMap),metaPlugins:[...j(e[`~orpc`]?.metaPlugins),...j(n[`~orpc`]?.metaPlugins)]},Object.defineProperty(r,"name",{value:`${e.name} + ${n.name}`}),r},t}var yt=class e{"~orpc";constructor(e){this[`~orpc`]=e}static create(){return new e({errorMap:{},meta:{},orderedMiddlewares:[]})}$context(){return this}$config(t){return new e({...this[`~orpc`],...t})}meta(...t){let[n,r]=P(this[`~orpc`].meta,this[`~orpc`].metaPlugins,t);return new e({...this[`~orpc`],meta:n,metaPlugins:r})}errors(t){let n=new e({...this[`~orpc`],errorMap:N(this[`~orpc`].errorMap,t)}),r=F(t);return r&&(n=n.meta(...r)),n}use(t){let n=new e({...this[`~orpc`],errorMap:N(t[`~orpc`]?.errorMap??{},this[`~orpc`].errorMap),orderedMiddlewares:[...this[`~orpc`].orderedMiddlewares,{middleware:t,inputSchemasLengthAtUse:this[`~orpc`].inputSchemas?.length,outputSchemasLengthAtUse:this[`~orpc`].outputSchemas?.length}]});return t[`~orpc`]?.metaPlugins&&(n=n.meta(...t[`~orpc`]?.metaPlugins)),n}middleware(e){let t=[...this[`~orpc`].orderedMiddlewares.map(({middleware:e})=>e),e],n=vt(t.shift());for(let e of t)n=n.use(e);return n[`~orpc`]={...n[`~orpc`],errorMap:this[`~orpc`].errorMap,metaPlugins:[...j(this[`~orpc`].metaPlugins),...j(e[`~orpc`]?.metaPlugins)]},n}input(t){let n=new e({...this[`~orpc`],inputSchemas:[...j(this[`~orpc`].inputSchemas),t]}),r=F(t);return r&&(n=n.meta(...r)),n}output(t){let n=new e({...this[`~orpc`],outputSchemas:[...j(this[`~orpc`].outputSchemas),t]}),r=F(t);return r&&(n=n.meta(...r)),n}handler(e){let t=new _t({...this[`~orpc`],handler:e}),n=F(e);return n&&(t=t.meta(...n)),t}router(e){return Ee(e,{...this[`~orpc`],middlewares:this[`~orpc`].orderedMiddlewares.map(({middleware:e})=>e)})}lazy(e){return new Ce({loader:async()=>{let{default:t}=await e();return{default:this.router(t)}},meta:this[`~orpc`].meta,metaPlugins:this[`~orpc`].metaPlugins})}}.create(),bt=A(ie),xt=k.custom(async e=>(await bt.validate?.(e))?.success===!0).describe(`An AI SDK UIMessageChunk. Fields depend on the chunk type.`),St=k.array(k.object({id:k.string().min(1),role:k.enum([`user`,`assistant`]),parts:k.array(k.looseObject({type:k.string()})).min(1),metadata:k.unknown().optional()})).min(1),Ct=k.object({appId:k.string().min(1),messages:St}),wt=k.string().regex(/^[A-Za-z0-9_-]{1,128}$/u),Tt=k.string().max(349528).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u),Et=e=>[...e].some(e=>(e.codePointAt(0)??0)<32),Dt=k.object({path:k.string().min(1).max(1024).refine(e=>new TextEncoder().encode(e).byteLength<=1024,{message:`Preview path exceeds 1024 UTF-8 bytes`}),contentType:k.string().min(1).max(255).refine(e=>!/[\r\n]/u.test(e),{message:`Invalid preview content type`}),size:k.number().int().min(0).max(1048576),chunks:k.number().int().min(0).max(4),sha256:k.string().regex(/^[a-f0-9]{64}$/u)}),Ot=k.object({files:k.array(Dt).max(100),views:k.array(k.object({slot:k.string().min(1).max(255),path:k.string().startsWith(`/`).max(1024),instances:k.literal(!0).optional(),disabled:k.literal(!0).optional()})).max(1e3).optional()}).superRefine((e,t)=>{let n=new Set,r=0;for(let[i,a]of e.files.entries())(a.path.startsWith(`/`)||a.path.includes(`\\`)||a.path.split(`/`).some(e=>!e||e===`.`||e===`..`)||Et(a.path)||n.has(a.path))&&t.addIssue({code:`custom`,message:`Invalid or duplicate preview path`,path:[`files`,i,`path`]}),a.chunks!==Math.ceil(a.size/262144)&&t.addIssue({code:`custom`,message:`Invalid preview chunk count`,path:[`files`,i,`chunks`]}),n.add(a.path),r+=a.size;n.has(`client.js`)||t.addIssue({code:`custom`,message:`Missing client.js`}),r>10485760&&t.addIssue({code:`custom`,message:`Preview build exceeds 10 MiB`})}),kt=k.discriminatedUnion(`type`,[k.object({type:k.literal(`begin`),buildId:wt,revision:k.number().int().positive(),manifest:Ot}),k.object({type:k.literal(`chunk`),revision:k.number().int().positive(),fileIndex:k.number().int().min(0).max(99),chunkIndex:k.number().int().min(0).max(3),base64:Tt}),k.object({type:k.literal(`complete`),revision:k.number().int().positive()}),k.object({type:k.literal(`ended`)})]);k.object({sessionId:k.uuid(),expiresAt:k.string().min(1),websocketUrl:k.url(),token:k.string().min(1)});var At=k.object({manifest:Ot}),jt=k.object({buildId:wt,fileIndex:k.number().int().min(0).max(99),chunkIndex:k.number().int().min(0).max(3),base64:Tt}),Mt=k.object({buildId:wt}),Nt=k.object({accepted:k.literal(!0)}),Pt=k.object({revision:k.number().int().positive()});function Ft(e){let t=te(new ae({connect:()=>e}));return{beginBuild:async e=>Mt.parse(await t.beginBuild(At.parse(e))),uploadChunk:async e=>Nt.parse(await t.uploadChunk(jt.parse(e))),commitBuild:async e=>Pt.parse(await t.commitBuild({buildId:wt.parse(e.buildId)})),heartbeat:async()=>Nt.parse(await t.heartbeat()),subscribe:async()=>{let e=await t.subscribe();return(async function*(){for await(let t of e)yield kt.parse(t)})()}}}function L(e){let t=URL.canParse(e.url)?new URL(e.url):void 0,n=new re({origin:t?.origin,async fetch(t,n){let r=await(typeof e.headers==`function`?e.headers():e.headers),i=new Headers(r);return new Headers(n.headers).forEach((e,t)=>{i.set(t,e)}),(e.fetch??fetch)(t,{...n,headers:i})},url:t?`${t.pathname}${t.search}${t.hash}`:e.url});return te(n)}var It=32,Lt=64,Rt=255,zt=16,Bt=100,Vt=16384,Ht=512,Ut=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/u;function Wt(e){if(!Ut.test(e))throw TypeError(`TailorKit scope names must start with a letter and contain only letters, numbers, "_", or "-".`);return e}function Gt(e){if(!Xt(e))throw TypeError(`TailorKit scope values must be nonempty plain JSON objects.`);let t=0,n=Jt(e,0,!0,new Set,()=>{if(t+=1,t>Ht)throw TypeError(`TailorKit scope values may contain at most ${Ht} JSON values.`)}),r=JSON.stringify(n);if(r===void 0||new TextEncoder().encode(r).byteLength>Vt)throw TypeError(`TailorKit scope values may not exceed ${Vt} bytes of JSON.`);return n}function Kt(e){if(!Xt(e))throw TypeError(`TailorKit scope identity must contain a name and value.`);if(Yt(e,`TailorKit scope identity must contain data properties.`).length!==2||!Object.hasOwn(e,`name`)||!Object.hasOwn(e,`value`))throw TypeError(`TailorKit scope identity must contain only a name and value.`);let t=Object.getOwnPropertyDescriptor(e,`name`)?.value,n=Object.getOwnPropertyDescriptor(e,`value`)?.value;if(typeof t!=`string`)throw TypeError(`TailorKit scope identity must contain a name and value.`);return Wt(t),{name:t,value:Gt(n)}}function qt(e,t){let n=t??Object.keys(e);if(n.length===0)throw TypeError(`At least one TailorKit scope must be selected.`);let r=[],i=new Set;for(let t of n){if(Wt(t),i.has(t))continue;if(i.add(t),!Object.hasOwn(e,t))throw TypeError(`TailorKit scope "${t}" is not available for this request.`);let n=e[t];if(!n)throw TypeError(`TailorKit scope "${t}" is not available for this request.`);r.push({name:t,value:n})}if(r.length===0)throw TypeError(`At least one TailorKit scope must be selected.`);return r}function Jt(e,t,n,r,i){if(i(),e===null||typeof e==`boolean`||typeof e==`string`){if(typeof e==`string`&&e.length>Rt)throw TypeError(`TailorKit scope strings may not exceed ${Rt} characters.`);return e}if(typeof e==`number`){if(!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e))throw TypeError(`TailorKit scope numbers must be finite and safe when integral.`);if(Object.is(e,-0))throw TypeError(`TailorKit scope numbers may not be negative zero.`);return e}if(typeof e!=`object`)throw TypeError(`TailorKit scope values must contain only JSON values.`);if(t>zt)throw TypeError(`TailorKit scope values may be nested at most ${zt} levels deep.`);if(r.has(e))throw TypeError(`TailorKit scope values may not contain cycles.`);if(r.add(e),Array.isArray(e)){if(Object.getPrototypeOf(e)!==Array.prototype)throw TypeError(`TailorKit scope arrays must be standard arrays.`);if(e.length>Bt)throw TypeError(`TailorKit scope arrays may contain at most ${Bt} items.`);let n=Reflect.ownKeys(e);if(n.length!==e.length+1||!n.includes(`length`)||n.some(e=>typeof e!=`string`))throw TypeError(`TailorKit scope arrays must be dense and have no extra properties.`);let a=[];for(let n=0;n<e.length;n+=1){let o=Object.getOwnPropertyDescriptor(e,String(n));if(!o?.enumerable||!(`value`in o))throw TypeError(`TailorKit scope arrays must contain enumerable data items.`);a.push(Jt(o.value,t+1,!1,r,i))}return r.delete(e),Object.freeze(a)}if(!Xt(e))throw TypeError(`TailorKit scope objects must be plain JSON objects.`);let a=Yt(e,`TailorKit scope objects must contain data properties.`);if(n&&a.length===0)throw TypeError(`TailorKit scope values must be nonempty plain JSON objects.`);if(a.length>It)throw TypeError(`TailorKit scope objects may contain at most ${It} properties.`);let o=Object.fromEntries(a.sort(([e],[t])=>Zt(e,t)).map(([e,n])=>[e,Jt(n,t+1,!1,r,i)]));return r.delete(e),Object.freeze(o)}function Yt(e,t){let n=Reflect.ownKeys(e);if(n.some(e=>typeof e!=`string`))throw TypeError(t);let r=[];for(let i of n){if(i===`__proto__`)throw TypeError(`TailorKit scope property names may not be "__proto__".`);if(i.length===0||i.length>Lt)throw TypeError(`TailorKit scope property names must be 1 to ${Lt} characters.`);let n=Object.getOwnPropertyDescriptor(e,i);if(!n?.enumerable||!(`value`in n))throw TypeError(t);r.push([i,n.value])}return r}function Xt(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Zt(e,t){return e<t?-1:+(e>t)}var Qt=k.string().regex(/^[A-Za-z0-9_-]{43}$/u);k.array(Qt).max(20),k.enum([`accept`,`cancel`]);var R=yt.$context();function $t(e){if(!e.tailorkit)throw new O(`UNAUTHORIZED`,{message:`Unauthorized.`});return e.tailorkit}function z(e,t){let n=$t(e).scopes,r=t===void 0?Object.keys(n):[t];if(r.length!==1)throw new O(`BAD_REQUEST`,{message:`Choose one TailorKit scope for this operation.`});try{return qt(n,r)[0]}catch(e){throw new O(`BAD_REQUEST`,{message:e instanceof Error?e.message:`Invalid TailorKit scope selection.`})}}function B(e,t){try{return qt($t(e).scopes,t)}catch(e){throw new O(`BAD_REQUEST`,{message:e instanceof Error?e.message:`Invalid TailorKit scope selection.`})}}function V(e){let[t,n]=e.headers.get(`authorization`)?.split(` `)??[];if(t!==`Bearer`||!n)throw new O(`UNAUTHORIZED`,{message:`Missing CLI deploy token.`});return n}var H=R.middleware(async({context:e,next:t})=>{let n=await ut({body:{deployToken:V(e.request)},client:e.platform,headers:e.platformHeaders}),r=`data`in n?n.data:n;if(!r?.scope)throw new O(`UNAUTHORIZED`,{message:`Invalid CLI deploy token.`});let i;try{let t=Kt(r.scope);if(!Object.hasOwn(e.scopeSchemas,t.name))throw TypeError(`CLI token uses an undeclared scope.`);i=Object.freeze({[t.name]:t.value})}catch{throw new O(`UNAUTHORIZED`,{message:`Invalid CLI deploy token.`})}return t({context:{tailorkit:{scopes:i}}})}),en=R.middleware(async({context:e,next:t})=>{let n=await e.authenticate({request:e.request});if(!n)throw new O(`UNAUTHORIZED`,{message:`Unauthorized.`});return t({context:{tailorkit:n}})});R.use(H).input(Ct).output(Se(xt)).handler(async function*({context:e,input:t,signal:n}){let r=new AbortController,i=n?AbortSignal.any([n,r.signal]):r.signal;try{let n,r=!1,{stream:a}=await $e({body:{...t,deployToken:V(e.request)},client:e.platform,headers:e.platformHeaders,signal:i,sseMaxRetryAttempts:1,onSseError:e=>{n=e}});for await(let e of a){let t=await xt.parseAsync(e);(t.type===`finish`||t.type===`error`)&&(r=!0),yield t}if(i?.throwIfAborted(),n)throw new O(`BAD_GATEWAY`,{message:`The app agent stream failed. Try again.`});if(!r)throw new O(`BAD_GATEWAY`,{message:`The agent stream ended unexpectedly. Try again.`})}finally{r.abort()}});var tn=async(e,t)=>{if(e===void 0)return t;let n=await e[`~standard`].validate(t);if(`issues`in n)throw new O(`BAD_REQUEST`,{message:`Invalid TailorKit payload`});return n.value};R.use(en).input(k.object({input:k.unknown().optional(),path:k.string()})).handler(async({context:e,input:t})=>{let n=e.actions.get(t.path);if(n===void 0)throw new O(`NOT_FOUND`,{message:`Action not found`});let r=await tn(n.definition.input,t.input),i=await n.handler({context:$t(e).actionContext,input:r});return tn(n.definition.output,i)});var nn=k.object({page:k.number().int().min(1).optional(),pageSize:k.number().int().min(1).max(100).optional()}),rn=k.object({description:k.string().nullable(),name:k.string()});R.use(H).input(rn).handler(async({context:e,input:t})=>{let{data:n}=await nt({responseStyle:`fields`,throwOnError:!0,body:{...t,scope:z(e)},client:e.platform,headers:e.platformHeaders});return n}),R.use(H).input(k.object({appId:k.string()})).handler(async({context:e,input:t})=>await rt({body:{scope:z(e)},client:e.platform,headers:e.platformHeaders,path:{appId:t.appId}})),R.use(H).input(k.object({appId:k.string(),deploymentId:k.string()})).handler(async({context:e,input:t})=>await at({body:{deploymentId:t.deploymentId,scope:z(e)},client:e.platform,headers:e.platformHeaders,path:{appId:t.appId}})),R.use(H).input(k.object({appId:k.string(),scopes:k.array(k.string()).optional()})).handler(async({context:e,input:t})=>await tt({body:{scopes:B(e,t.scopes)},client:e.platform,headers:e.platformHeaders,path:{appId:t.appId}})),R.use(H).input(nn.extend({scopes:k.array(k.string()).optional()}).optional()).handler(async({context:e,input:t})=>{let{data:n}=await et({responseStyle:`fields`,throwOnError:!0,client:e.platform,headers:e.platformHeaders,body:{page:t?.page,pageSize:t?.pageSize,scopes:B(e,t?.scopes)}});return n}),R.use(H).input(k.object({appId:k.string()}).extend(rn.shape)).handler(async({context:e,input:t})=>await it({body:{description:t.description,name:t.name,scope:z(e)},client:e.platform,headers:e.platformHeaders,path:{appId:t.appId}}));var an=async e=>{try{return await e}catch(e){throw typeof e==`string`&&e.toLowerCase()===`unauthorized`?new O(`UNAUTHORIZED`,{message:`TailorKit platform rejected the host project key. Check TAILORKIT_PROJECT_KEY.`}):e}};R.use(en).input(k.object({scope:k.string().min(1),userCode:k.string().min(1)})).handler(async({context:e,input:t})=>await an(ot({body:{scope:z(e,t.scope),userCode:t.userCode},client:e.platform,headers:e.platformHeaders}))),R.use(en).input(k.object({userCode:k.string().min(1)})).handler(async({context:e,input:t})=>await an(st({body:{userCode:t.userCode},client:e.platform,headers:e.platformHeaders}))),R.input(k.object({deviceCode:k.string().min(1)})).handler(async({context:e,input:t})=>await an(ct({body:{deviceCode:t.deviceCode},client:e.platform,headers:e.platformHeaders}))),R.input(k.object({})).handler(async({context:e})=>await an(lt({body:{},client:e.platform,headers:e.platformHeaders}))),R.input(k.object({})).use(H).handler(({context:e})=>({scope:z(e)}));var on=k.object({page:k.number().int().min(1).optional(),pageSize:k.number().int().min(1).max(100).optional()}),sn=k.object({checksum:k.string(),contentLength:k.number().int().min(1),contentType:k.literal(`application/javascript`),encoding:k.enum([`utf-8`,`gzip`]),objectKey:k.literal(`client.js`)}),cn=sn.extend({objectKey:k.literal(`server.js`)}),ln=k.object({checksum:k.string(),contentLength:k.number().int().min(1).max(262144),contentType:k.enum([`image/svg+xml`,`image/png`,`image/webp`])}),un=k.tuple([sn]),dn=k.object({dark:ln.optional(),light:ln.optional()}).optional(),fn=e=>{if(e instanceof Error)return e.message;if(typeof e==`string`)return e;if(e&&typeof e==`object`&&`message`in e){let t=e.message;return typeof t==`string`?t:void 0}},pn=e=>fn(e)?.toLowerCase().includes(`not found`)??!1,mn=e=>{throw pn(e)?new O(`NOT_FOUND`,{message:`App not found.`}):e};R.use(H).input(k.object({appId:k.string(),assets:un,views:k.array(k.object({slot:k.string().min(1).max(255),path:k.string().startsWith(`/`).max(1024),instances:k.literal(!0).optional(),disabled:k.literal(!0).optional()})).max(1e3).optional(),server:cn.optional(),logos:dn})).handler(async({context:e,input:t})=>{try{return await pt({body:{appId:t.appId,assets:t.assets,views:t.views,server:t.server,logos:t.logos,scope:z(e)},client:e.platform,headers:e.platformHeaders})}catch(e){mn(e)}}),R.use(H).input(k.object({deploymentId:k.string(),scopes:k.array(k.string()).optional()})).handler(async({context:e,input:t})=>await ft({body:{scopes:B(e,t.scopes)},client:e.platform,headers:e.platformHeaders,path:{deploymentId:t.deploymentId}})),R.use(H).input(k.object({appId:k.string(),scopes:k.array(k.string()).optional()}).merge(on)).handler(async({context:e,input:t})=>await dt({client:e.platform,headers:e.platformHeaders,body:{appId:t.appId,page:t.page,pageSize:t.pageSize,scopes:B(e,t.scopes)}})),R.use(H).input(k.object({deploymentId:k.string(),rollout:k.boolean().optional()})).handler(async({context:e,input:t})=>await mt({body:{scope:z(e),rollout:t.rollout},client:e.platform,headers:e.platformHeaders,path:{deploymentId:t.deploymentId}}));function hn(e){if(!e||typeof e!=`object`)return!1;if(`data`in e&&e.data&&typeof e.data==`object`&&`reason`in e.data&&e.data.reason===`ACTIVE_PREVIEW_EXISTS`)return!0;let t=`message`in e&&typeof e.message==`string`?e.message:``;return/active preview already exists|preview is already running/iu.test(t)?!0:`error`in e&&hn(e.error)||`cause`in e&&hn(e.cause)}R.use(H).input(k.object({appId:k.string().min(1),replaceActive:k.boolean().optional()})).handler(async({context:e,input:t})=>{try{return await ht({body:{appId:t.appId,deployToken:V(e.request),replaceActive:t.replaceActive},client:e.platform,headers:e.platformHeaders})}catch(e){throw hn(e)?new O(`CONFLICT`,{message:"A preview is already running for this app. Run `pnpm tailorkit preview --replace` to end it and start a new one."}):e}}),R.use(H).input(k.object({sessionId:k.uuid()})).handler(async({context:e,input:t})=>await gt({body:{deployToken:V(e.request)},client:e.platform,headers:e.platformHeaders,path:{sessionId:t.sessionId}}));var gn=e=>{let t=new URL(e);return t.hash=``,t.search=``,t.pathname=t.pathname.replace(/\/+$/u,``),t.toString().replace(/\/$/u,``)},_n=k.object({name:k.string().min(1),value:k.record(k.string(),k.unknown())}),vn=k.record(k.string(),k.string()),yn=k.preprocess(e=>typeof e==`object`&&e&&!Array.isArray(e)&&!Object.hasOwn(e,`value`)&&vn.safeParse(e).success?void 0:e,_n.optional()),U=E.join(w(),`.tailorkit`,`auth.json`),bn=18e5,xn=2e3,Sn=k.object({deployToken:k.string().min(1),scope:yn}),Cn=k.object({deployToken:k.string().min(1),scope:_n}),wn=k.object({scope:_n}),Tn=k.object({hosts:k.record(k.string(),Sn).optional()}).passthrough(),En=e=>new Promise(t=>setTimeout(t,e)),Dn=e=>{if(e&&typeof e==`object`&&`error`in e&&e.error!==void 0)throw e.error},On=async()=>{try{return Tn.parse(JSON.parse(await v(U,`utf-8`)))}catch(e){if(e&&typeof e==`object`&&`code`in e&&e.code===`ENOENT`)return{};throw e}},kn=async e=>{await g(E.dirname(U),{recursive:!0}),await C(U,`${JSON.stringify(e,null,2)}\n`,{encoding:`utf-8`,mode:384}),await h(U,384)},An=async e=>{let t=await ee(e.configPath,e.cwd);if(t.config.host)return gn(t.config.host);throw Error(`Missing TailorKit host URL. Set host in tailorkit.config.ts.`)},jn=(e,t)=>{let n=new URL(e);return n.pathname=`${n.pathname.replace(/\/+$/u,``)}/cli-auth/approve`,n.search=``,n.searchParams.set(`code`,t),n.hash=``,n.toString()},Mn=class extends Error{constructor(e){super(`Not logged in for ${e}. Run tailorkit login after checking host in tailorkit.config.ts.`),this.name=`NotLoggedInError`}},Nn=async(e,t)=>{let n=await On();await kn({...n,hosts:{...n.hosts,[e]:t}})},Pn=async e=>{let t=await On();if(!t.hosts?.[e])return!1;let{[e]:n,...r}=t.hosts,i={...t,hosts:r};return Object.keys(r).length===0?(await x(U,{force:!0}),!0):(await kn(i),!0)},Fn=async e=>(await On()).hosts?.[e],In=async(e,t)=>{let n=await An(e),r=L({url:n}),i=await r.cliAuth.start({});Dn(i);let a=`data`in i?i.data:i,o=new Date(a.expiresAt),s=Date.now()+(e.timeout??bn);for(t({expiresAt:o,hostUrl:n,userCode:a.userCode});Date.now()<s&&Date.now()<o.getTime();){await En(xn);let e=await r.cliAuth.poll({deviceCode:a.deviceCode});Dn(e);let t=`data`in e?e.data:e;switch(t.status){case`pending`:continue;case`denied`:throw Error(`CLI login was denied.`);case`expired`:throw Error(`CLI login expired.`);case`approved`:{let e=Cn.parse(t);return await Nn(n,{deployToken:e.deployToken,scope:e.scope}),{hostUrl:n,scope:e.scope}}default:throw Error(`Unexpected CLI login status.`)}}throw Error(`Timed out waiting for CLI login approval.`)},Ln=async e=>{let t=await An(e),n=await Fn(t);if(!n?.deployToken)throw new Mn(t);let r=L({headers:{authorization:`Bearer ${n.deployToken}`},url:t}),i;try{let e=await r.cliAuth.verifyToken({});Dn(e),i=wn.parse(`data`in e?e.data:e)}catch(e){throw typeof e==`object`&&e&&`code`in e&&e.code===`UNAUTHORIZED`?new Mn(t):e}return await Nn(t,{deployToken:n.deployToken,scope:i.scope}),{hostUrl:t,scope:i.scope}},Rn=async e=>{let t=await An(e);return{hostUrl:t,removed:await Pn(t)}},zn=async e=>{try{let t=JSON.parse(await v(E.join(e,`package.json`),`utf-8`));if(typeof t.name==`string`&&t.name.trim())return t.name.trim()}catch{}return E.basename(e)},Bn=async(e,t)=>{let n=await v(e,`utf-8`),{parseSync:r}=await import(`vite`),{program:i}=r(e,n),a=i.body.find(e=>e.type===`ExportDefaultDeclaration`)?.declaration;if(a?.type===`Identifier`){let e=a.name;a=i.body.filter(e=>e.type===`VariableDeclaration`).flatMap(e=>e.declarations).find(t=>t.id.type===`Identifier`&&t.id.name===e)?.init??void 0}for(;a?.type===`TSSatisfiesExpression`||a?.type===`TSAsExpression`;)a=a.expression;if(a?.type===`CallExpression`&&a.callee.type===`Identifier`&&[`defineTailorKitConfig`,`defineConfig`].includes(a.callee.name)){let e=a.arguments[0];a=e?.type===`SpreadElement`?void 0:e}if(a?.type!==`ObjectExpression`)throw Error(`Could not write appId to ${e}. Add appId: ${JSON.stringify(t)} manually.`);let o=a.properties.find(e=>e.type===`Property`&&!e.computed&&(e.key.type===`Identifier`&&e.key.name===`appId`||e.key.type===`Literal`&&e.key.value===`appId`));if(o?.type===`Property`){await C(e,n.slice(0,o.start)+`appId: ${JSON.stringify(t)}`+n.slice(o.end),`utf-8`);return}let s=a.start+1,c=n.slice(s),l=/^(\r?\n)([ \t]*)/u.exec(c),u=l?`${l[1]}${l[2]||` `}appId: ${JSON.stringify(t)},`:` appId: ${JSON.stringify(t)},`;await C(e,n.slice(0,s)+u+c,`utf-8`)},W=3145728,Vn=ue(de),Hn={png:`image/png`,svg:`image/svg+xml`,webp:`image/webp`},Un=e=>{if(e&&typeof e==`object`&&`error`in e&&e.error!==void 0)throw e.error;let t=e&&typeof e==`object`&&`data`in e?e.data:e;return t&&typeof t==`object`&&`body`in t?t.body:t},Wn=e=>{if(e instanceof Error)return e.message;if(typeof e==`string`)return e;if(e&&typeof e==`object`&&`message`in e){let t=e.message;return typeof t==`string`?t:void 0}},Gn=e=>Wn(e)?.toLowerCase().includes(`not found`)??!1,Kn=async(e,t)=>{let n=E.join(e,`tailorkit-upload.json`);return t.parse(JSON.parse(await v(n,`utf-8`)))},qn=e=>oe(`sha256`).update(e).digest(`hex`),Jn=async(e,t,n)=>{if(!e.uploadUrl)return;if(t.byteLength>W)throw Error(`Deployment asset exceeds ${W} bytes.`);let r=new Headers(e.headers);r.has(`content-type`)||r.set(`content-type`,`application/javascript`),n&&r.set(`content-encoding`,n);let i=await fetch(e.uploadUrl,{body:new Uint8Array(t),headers:r,method:`PUT`});if(!i.ok)throw Error(`Asset upload failed with ${i.status} ${i.statusText}.`)},Yn=e=>{for(let t of[`tsconfig.json`,`jsconfig.json`]){let n=E.join(e,t);if(le(n))return n}},Xn=async e=>{let t=Yn(e.root);if(!t)return;let n=r(E.join(e.root,`package.json`)),i;try{i=E.join(E.dirname(n.resolve(`typescript/package.json`)),`bin/tsc`)}catch{return}let a=E.resolve(e.root,e.config.client?.entry??`src/client.ts`),o=await _(E.join(e.root,`.tailorkit-typecheck-`));try{let n=E.join(o,`tsconfig.json`);await C(n,JSON.stringify({extends:t,compilerOptions:{noEmit:!0,incremental:!1,composite:!1},files:[a,...e.config.server?[E.resolve(e.root,e.config.server.entry??`src/server.ts`)]:[]],include:[]})),await ue(se)(process.execPath,[i,`--noEmit`,`--project`,n,`--pretty`,`false`],{cwd:e.root,maxBuffer:4194304})}catch(t){let n=t;return{command:`tsc --noEmit ${E.relative(e.root,a)}`,exitCode:typeof n.code==`number`?n.code:null,output:`${n.stdout??``}${n.stderr??``}`.trim()||n.message||String(t)}}finally{await x(o,{recursive:!0,force:!0})}},Zn=async e=>{let t=await ee(e.configPath,e.cwd),n=t.config.appId,r=!1,i=await Ln(e).catch(t=>{if(t instanceof Mn&&e.onLoginRequired)return e.onLoginRequired();throw t}),a=await Fn(i.hostUrl);if(!a?.deployToken)throw Error(`Not logged in for ${i.hostUrl}. Run tailorkit login after checking host in tailorkit.config.ts.`);let{buildApp:o,tailorkitUploadManifestSchema:s}=await import(`@tailorkit/app/builder`),[c,l]=await Promise.allSettled([o(e),Xn(t)]);if(c.status===`rejected`)throw c.reason;if(l.status===`rejected`)throw l.reason;if(l.value!==void 0&&!await e.onTypecheckFailed?.(l.value))throw Error(`Deployment cancelled because type check failed.`);let u=E.resolve(t.root,e.outDir??t.config.build?.outDir??`.tailorkit`),d=await Kn(u,s),f=E.join(u,d.assets.client),p=await v(f),m=await Vn(p),h=d.assets.server?await v(E.join(u,d.assets.server)):void 0,g=h?await Vn(h):void 0,_=Object.entries(d.assets.logos??{}),y=await Promise.all(_.map(async([e,t])=>{let n=await v(E.join(u,t)),r=Hn[E.extname(t).slice(1)];if(!r)throw Error(`Unsupported ${e} logo format.`);return{content:n,contentType:r,filename:t,variant:e}}));if(p.byteLength>W)throw Error(`Combined client assets are ${p.byteLength} bytes and cannot exceed ${W} bytes.`);if(h&&h.byteLength>W)throw Error(`Server asset exceeds ${W} bytes.`);if(m.byteLength>W||g&&g.byteLength>W)throw Error(`Compressed deployment asset exceeds ${W} bytes.`);let b=L({headers:{authorization:`Bearer ${a.deployToken}`},url:i.hostUrl}),x=async a=>{let o=await zn(t.root);if(!await e.onMissingAppId?.({appName:o,configPath:t.filepath,hostUrl:i.hostUrl,reason:a}))throw Error(`Deployment cancelled.`);return n=Un(await b.apps.create({description:null,name:o})).id,r=!0,await Bn(t.filepath,n),n};n||=await x(`missing`);let S=async e=>Un(await b.deployments.create({appId:e,views:d.views,assets:[{checksum:qn(m),contentLength:m.byteLength,contentType:`application/javascript`,encoding:`gzip`,objectKey:`client.js`}],server:g?{checksum:qn(g),contentLength:g.byteLength,contentType:`application/javascript`,encoding:`gzip`,objectKey:`server.js`}:void 0,logos:y.length>0?Object.fromEntries(y.map(e=>[e.variant,{checksum:qn(e.content),contentLength:e.content.byteLength,contentType:e.contentType}])):void 0})),C;try{C=await S(n)}catch(e){if(!Gn(e))throw e;n=await x(`not-found`),C=await S(n)}if(C.assets.length!==1||!C.assets[0])throw Error(`Deployment did not return an upload URL for the client asset.`);if(h&&!C.server)throw Error(`Deployment did not return an upload URL for the server asset.`);await Promise.all([...g&&C.server?[Jn(C.server,g,`gzip`)]:[],Jn(C.assets[0],m,`gzip`),...y.map(e=>{let t=C.logos?.[e.variant];if(!t)throw Error(`Deployment did not return an upload URL for the ${e.variant} logo.`);return Jn(t,e.content)})]);let w=Un(await b.deployments.publish({deploymentId:C.deployment.id,rollout:!0})),T=await Promise.all(y.map(async e=>({gzipSize:(await Vn(e.content)).byteLength,path:e.filename,size:e.content.byteLength}))),D=[];return h&&g&&d.assets.server&&D.push({gzipSize:g.byteLength,path:d.assets.server,size:h.byteLength}),{appId:n,createdApp:r,deploymentId:w.id,hostUrl:i.hostUrl,status:w.status,uploadedFiles:[{gzipSize:m.byteLength,path:d.assets.client,size:p.byteLength},...D,...T]}};function Qn(e,t){return e===`/`||e===t||t.startsWith(`${e}/`)}var $n=k.enum([`object`,`array`,`string`,`number`,`integer`,`boolean`,`null`]),G=k.object({$schema:k.enum([`https://json-schema.org/draft/2020-12/schema`]).optional(),type:k.union([$n,k.array(k.string())]).optional(),properties:k.lazy(()=>k.record(k.string(),G)).optional(),required:k.array(k.string()).optional(),additionalProperties:k.union([k.boolean(),k.lazy(()=>G)]).optional(),enum:k.array(k.unknown()).optional(),const:k.unknown().optional(),items:k.union([k.boolean(),k.lazy(()=>G)]).optional(),prefixItems:k.lazy(()=>k.array(G)).optional(),minItems:k.number().int().nonnegative().optional(),maxItems:k.number().int().nonnegative().optional(),propertyNames:k.lazy(()=>G).optional(),minimum:k.number().optional(),maximum:k.number().optional(),anyOf:k.lazy(()=>k.array(G)).optional(),oneOf:k.lazy(()=>k.array(G)).optional(),allOf:k.lazy(()=>k.array(G)).optional(),not:k.lazy(()=>G).optional()}).strict(),er=k.object({async:k.boolean().optional(),input:G.optional(),output:G.optional()}),tr=k.object({fields:G.optional(),callbacks:k.record(k.string(),er),children:k.boolean()}),nr=k.record(k.string(),tr),rr=k.string().regex(/^\/.*$/u,{message:`View keys must start with "/".`}),ir=k.object({context:G.optional(),contextOptional:k.boolean().optional()}).strict(),ar=k.record(rr,ir),or=k.object({input:k.record(k.string(),k.unknown()).optional(),output:k.record(k.string(),k.unknown()).optional()}),sr=k.lazy(()=>k.record(k.string(),k.union([or,sr])));k.object({version:k.literal(1),slots:k.record(k.string().min(1),k.object({views:k.array(k.string().startsWith(`/`)),multiple:k.boolean().optional()})).default({}),actions:sr.default({}),components:nr,views:ar.default({})}).superRefine((e,t)=>{for(let[n,r]of Object.entries(e.slots))r.views.forEach((r,i)=>{Object.hasOwn(e.views,r)||t.addIssue({code:`custom`,path:[`slots`,n,`views`,i],message:`Unknown view "${r}".`})})});var cr=`/* eslint-disable */
|
|
51
8
|
|
|
52
9
|
// This file was automatically generated by TailorKit.
|
|
53
10
|
// Documentation: https://tailorkit.dev/docs
|
|
@@ -55,26 +12,27 @@ data: `)}
|
|
|
55
12
|
// Do not make changes to this file directly, as it will be overwritten.
|
|
56
13
|
// Exclude this file from linting and formatting to avoid checking generated code.
|
|
57
14
|
|
|
58
|
-
import { createRemoteComponent } from "
|
|
59
|
-
`,
|
|
60
|
-
`)},
|
|
61
|
-
`)},
|
|
62
|
-
`);t.push(` ${
|
|
63
|
-
`)},
|
|
64
|
-
`)}
|
|
65
|
-
`);i.push(`${r}${
|
|
66
|
-
`)},
|
|
67
|
-
`);n.push(` ${
|
|
68
|
-
`)},
|
|
69
|
-
interface
|
|
15
|
+
import { createRemoteComponent } from "tailorkit/client";
|
|
16
|
+
`,lr=`Record<string, never>`,ur=new Set([`Box`,`Flex`,`Grid`,`Inline`]),K=e=>JSON.stringify(e),q=e=>/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)?e:K(e),dr=e=>typeof e==`string`?K(e):typeof e==`number`||typeof e==`boolean`||e===null?JSON.stringify(e):`unknown`,J=(e,t=0)=>{if(e===void 0)return`unknown`;if(pr(e))return`never`;if(e.const!==void 0)return dr(e.const);if(e.enum!==void 0&&e.enum.length>0)return e.enum.map(dr).join(` | `);if(e.allOf!==void 0&&e.allOf.length>0){let n=e.allOf.map(e=>J(e,t));return[...new Set(n)].map(e=>e.includes(` | `)?`(${e})`:e).join(` & `)}let n=e.anyOf??e.oneOf;if(n!==void 0&&n.length>0){let e=n.filter(e=>!pr(e)).map(e=>J(e,t)).filter(e=>e!==`never`);return e.length===0?`never`:[...new Set(e)].join(` | `)}if(Array.isArray(e.type)){let n=e.type.map(n=>J({...e,type:n},t));return[...new Set(n)].join(` | `)||`never`}let r=e.type;if(r===`null`)return`null`;if(r===`string`)return`string`;if(r===`number`||r===`integer`)return`number`;if(r===`boolean`)return`boolean`;if(r===`array`){let n=typeof e.items==`object`?e.items:void 0;if(e.prefixItems!==void 0){let r=e.prefixItems.map((n,r)=>{let i=J(n,t);return r<(e.minItems??0)?i:`(${i})?`}),i=(e.minItems??0)-e.prefixItems.length;if(i>0&&e.items===!1)return`never`;for(let e=0;e<i;e+=1)r.push(J(n,t));return e.items!==!1&&r.push(`...${fr(J(n,t))}`),`[${r.join(`, `)}]`}return fr(e.items===!1?`never`:J(n,t))}return r===`object`?hr(e,t):`unknown`},fr=e=>`${e.includes(` | `)||e.includes(` & `)?`(${e})`:e}[]`,pr=e=>e.not!==void 0&&Object.keys(e.not).length===0,mr=e=>{let t=e.properties??{},n=Object.values(t);return(Array.isArray(e.type)?e.type.includes(`object`):e.type===`object`)&&n.length>0&&n.every(pr)},hr=(e,t)=>{let n=e.properties??{},r=Object.entries(n);if(mr(e))return`never`;let i=new Set(e.required),a=J(e.additionalProperties===!0?void 0:e.additionalProperties||void 0,t),o=[a];if(a!==`unknown`)for(let[e,n]of r)o.push(J(n,t)),i.has(e)||o.push(`undefined`);let s=e.additionalProperties===!1||e.additionalProperties===void 0?void 0:`Record<string, ${[...new Set(o)].join(` | `)}>`;if(r.length===0)return s??lr;let c=` `.repeat(t),l=` `.repeat(t+2),u=[`{`];for(let[e,n]of r){let r=i.has(e)?``:`?`;u.push(`${l}${q(e)}${r}: ${J(n,t+2)};`)}u.push(`${c}}`);let d=u.join(`
|
|
17
|
+
`);return s===void 0?d:`${d} & ${s}`},gr=e=>{let t=e.replaceAll(/[^A-Za-z0-9_$]/gu,`_`);return/^[A-Za-z_$]/u.test(t)?t:`_${t}`},_r=e=>`${gr(e)}Props`,vr=e=>{let t=gr(e);return`${t.charAt(0).toUpperCase()}${t.slice(1)}`},yr=e=>{if(e.fields?.properties!==void 0)return e.fields.properties;let t={};for(let n of e.fieldKeys??[])t[n]={};return t},br=(e,t)=>{if(e?.anyOf===void 0||e.anyOf.length!==2)return;let[n,r]=e.anyOf.filter(e=>!pr(e));if(n===void 0||r===void 0)return;let i,a;if(n.type===`object`?(i=r,a=n):r.type===`object`&&(i=n,a=r),i===void 0||a===void 0)return;let o=J(i,t);if(o===`never`)return`never`;let s=Object.values(a.properties??{});if(s.length!==0&&!s.map(e=>J(e,t)).some(e=>e!==o&&e!==`never`))return`Responsive<${o}>`},xr=(e,t)=>br(e,t)??J(e,t),Sr=e=>{let t={},n=new Map,r=new Set;for(let[i,a]of Object.entries(e))if(ur.has(i))for(let[e,i]of Object.entries(yr(a))){let a=vr(e),o=xr(i,0),s=n.get(a);if(s===void 0){n.set(a,o),t[e]=a;continue}s!==o&&r.add(a)}return Object.fromEntries(Object.entries(t).filter(([,e])=>!r.has(e)))},Cr=(e,t)=>{let n=[`export type Breakpoint = "base" | "sm" | "md" | "lg" | "xl" | "2xl";`,`export type Responsive<TValue> = TValue | Partial<Record<Breakpoint, TValue>>;`],r=new Set;for(let[i,a]of Object.entries(e))if(ur.has(i))for(let[e,i]of Object.entries(yr(a))){let a=t[e];a===void 0||r.has(a)||(r.add(a),n.push(`export type ${a} = ${xr(i,0)};`))}return n.join(`
|
|
18
|
+
`)},wr=e=>{let t=[`export interface ViewPropsByPath {`];for(let n of Object.keys(e)){let r=Object.entries(e).filter(([e])=>Qn(e,n)).filter(([,e])=>e.context!==void 0).map(([,e])=>{let t=J(e.context,4);return e.contextOptional?`Partial<${t}>`:t}).filter(e=>e!==`Record<string, never>`),i=(r.length>1?r.map(e=>`(${e})`).join(` & `):r[0]??`Record<string, never>`).split(`
|
|
19
|
+
`);t.push(` ${K(n)}: {`),t.push(` context: ${i[0]}`);for(let e of i.slice(1,-1))t.push(e);let a=i.at(-1);a!==void 0&&i.length>1?t.push(`${a};`):t[t.length-1]=`${t.at(-1)};`,t.push(` };`)}return t.push(`}`),t.join(`
|
|
20
|
+
`)},Tr=(e,t,n)=>{let r=_r(e),i=yr(t),a=t.callbacks??{},o=[`export interface ${r} {`];for(let[e,t]of Object.entries(i))o.push(` ${q(e)}?: ${n[e]??xr(t,2)};`);for(let[e,t]of Object.entries(a)){let n=t.input===void 0?``:`input: ${J(t.input,2)}`;o.push(` ${q(e)}?: (${n}) => void;`)}o.push(`}`),o.push(``);let s=Object.entries(a).map(([e,t])=>`${K(e)}: ${t.input===void 0?0:1}`),c=s.length>0?`,\n callbacks: { ${s.join(`, `)} }`:``;return o.push(`export const ${gr(e)} = /* @__PURE__ */ createRemoteComponent<${r}, ${t.children===!0}>(${K(e)}, {`),o.push(` children: ${t.children===!0}${c},`),o.push(`});`),o.join(`
|
|
21
|
+
`)},Er=e=>`input`in e||`output`in e,Dr=(e,t=0)=>{let n=` `.repeat(t),r=` `.repeat(t+2),i=[`{`];for(let[n,a]of Object.entries(e))if(Er(a)){let e=J(a.input,t+2),o=J(a.output,t+2);i.push(`${r}${q(n)}: (input: ${e}) => Promise<${o}>;`)}else{let e=Dr(a,t+2).split(`
|
|
22
|
+
`);i.push(`${r}${q(n)}: ${e[0]}`),i.push(...e.slice(1,-1)),i.push(`${e.at(-1)};`)}return i.push(`${n}}`),i.join(`
|
|
23
|
+
`)},Or=(e,t=[])=>{let n=[`{`];for(let[r,i]of Object.entries(e)){let e=[...t,r];if(Er(i))n.push(` ${q(r)}: async (input: unknown) => {`),n.push(` const response = await fetch(${K(`/api/tailorkit/actions/${e.join(`.`)}`)}, {`),n.push(` body: JSON.stringify(input),`),n.push(` headers: { "content-type": "application/json" },`),n.push(` method: "POST",`),n.push(` });`),n.push(` if (!response.ok) throw new Error(await response.text());`),n.push(` return response.json();`),n.push(` },`);else{let t=Or(i,e).split(`
|
|
24
|
+
`);n.push(` ${q(r)}: ${t[0]}`),n.push(...t.slice(1).map(e=>` ${e}`)),n.push(`,`)}}return n.push(`}`),n.join(`
|
|
25
|
+
`)},kr=(e,t={})=>{let n=Dr(e.actions??{}),r=e.components??{},i=Sr(r),a=[cr,wr(e.views??{}),`declare module "tailorkit/client" {
|
|
26
|
+
interface TailorKitViews extends ViewPropsByPath {}
|
|
27
|
+
interface TailorKitSlots { ${Object.entries(e.slots??{}).map(([e,t])=>`${K(e)}: { views: ${t.views.map(K).join(` | `)||`never`}; multiple: ${t.multiple===!0} };`).join(` `)} }
|
|
70
28
|
}
|
|
71
29
|
|
|
72
|
-
export type
|
|
73
|
-
export type
|
|
74
|
-
export type TailorKitActions = ${
|
|
75
|
-
export const actions = ${
|
|
30
|
+
export type ViewPath = keyof ViewPropsByPath & string;
|
|
31
|
+
export type ViewProps<TPath extends ViewPath> = ViewPropsByPath[TPath];
|
|
32
|
+
export type TailorKitActions = ${n};
|
|
33
|
+
export const actions = ${Or(e.actions??{})} as TailorKitActions;`,Cr(r,i)];t.serverModule&&a.splice(1,0,`import { createApi } from "tailorkit/client";\nimport type app from ${K(t.serverModule)};\ntype AppServerFunctions = typeof app.functions;\ndeclare module "tailorkit/client" {\n interface TailorKitServerFunctions extends AppServerFunctions {}\n}\n\nexport const api = createApi<typeof app.functions>();`);for(let[e,t]of Object.entries(r)){let{children:n}=tr.parse(t);a.push(Tr(e,{...t,children:n},i))}return`${a.join(`
|
|
76
34
|
|
|
77
|
-
`)}\n`},
|
|
35
|
+
`)}\n`},Ar=(e,t)=>{let n=new URL(e);return n.pathname=`${n.pathname.replace(/\/$/u,``)}/${t.replace(/^\//u,``)}`,n.toString()},jr=async e=>{let t=Ar(e,`schema`),n=await fetch(t);if(!n.ok)throw Error(`Unable to fetch TailorKit schema from ${t}: ${n.statusText}`);return await n.json()},Mr=async(e={})=>{let t=E.resolve(e.cwd??`.`),n=E.resolve(t,e.outFile??E.join(`src`,`tailorkit.gen.ts`)),r=await ee(e.configPath,t),i=e.schema??await jr(r.config.host),a=E.resolve(r.root,r.config.server?.entry??`src/server.ts`),o=await S(a).then(e=>e.isFile()).catch(e=>{let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return!1;throw e}),s;if(o){let e=E.relative(E.dirname(n),a).replaceAll(E.sep,`/`).replace(/\.tsx?$/u,``);s=e.startsWith(`.`)?e:`./${e}`}let c=kr(i,{serverModule:s});return await g(E.dirname(n),{recursive:!0}),await C(n,c,`utf-8`),n},Nr=`1.0.0-rc.4-5d5b77c`,Pr=`https://registry.npmjs.org`,Fr=5e3,Y={oxfmt:{fallback:`^0.46.0`,matcher:`^0`,packageName:`oxfmt`},oxlint:{fallback:`^1.61.0`,matcher:`^1`,packageName:`oxlint`},preact:{fallback:`^10.29.1`,matcher:`^10`,packageName:`preact`},tailorkit:{fallback:`latest`,matcher:`^0`,packageName:`tailorkit`},typescript:{fallback:`^6.0.3`,matcher:`^6`,packageName:`typescript`},zod:{fallback:`^4.0.0`,matcher:`^4`,packageName:`zod`}},Ir=e=>{let t=/^(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)$/u.exec(e);if(!t?.groups)return;let{major:n,minor:r,patch:i}=t.groups;if(n&&r&&i)return{major:Number.parseInt(n,10),minor:Number.parseInt(r,10),patch:Number.parseInt(i,10),raw:e}},Lr=(e,t)=>e.major===t.major?e.minor===t.minor?e.patch-t.patch:e.minor-t.minor:e.major-t.major,Rr=(e,t)=>{let n=/^\^(?<major>\d+)(?:\.(?<minor>\d+))?/u.exec(t);if(!n?.groups?.major)return!1;let r=Number.parseInt(n.groups.major,10),i=Number.parseInt(n.groups.minor??`0`,10);return e.major===r&&e.minor>=i},X=async({fallback:e,matcher:t,packageName:n})=>{try{let r=await fetch(`${Pr}/${encodeURIComponent(n)}`,{signal:AbortSignal.timeout(Fr)});if(!r.ok)return e;let i=await r.json(),a=Object.keys(i.versions??{}).map(Ir).filter(e=>e!==void 0).filter(e=>Rr(e,t)).toSorted(Lr).at(-1);return a?`^${a.raw}`:e}catch{return e}},zr=async()=>{let[e,t,n,r,i,a]=await Promise.all([X(Y.oxfmt),X(Y.oxlint),X(Y.preact),X(Y.tailorkit),X(Y.typescript),X(Y.zod)]);return{drizzleKit:Nr,drizzleOrm:Nr,oxfmt:e,oxlint:t,preact:n,tailorkit:r,typescript:i,zod:a}},Br=`{
|
|
78
36
|
"name": "{{ packageName }}",
|
|
79
37
|
"description": "A TailorKit.dev app that embeds in a host app to extend what it can do.",
|
|
80
38
|
"private": true,
|
|
@@ -83,6 +41,7 @@ export const actions = ${ta(e.actions??{})} as TailorKitActions;`,Xi(n,r)];for(l
|
|
|
83
41
|
},
|
|
84
42
|
"scripts": {
|
|
85
43
|
"build": "tailorkit build",
|
|
44
|
+
"db:generate": "tailorkit db generate",
|
|
86
45
|
"deploy": "tailorkit deploy",
|
|
87
46
|
"generate": "tailorkit generate"{% if linting %},
|
|
88
47
|
"lint": "oxlint",
|
|
@@ -93,18 +52,20 @@ export const actions = ${ta(e.actions??{})} as TailorKitActions;`,Xi(n,r)];for(l
|
|
|
93
52
|
"fix": "{{ fixScript }}"{% endif %}
|
|
94
53
|
},
|
|
95
54
|
"dependencies": {
|
|
96
|
-
"
|
|
97
|
-
"preact": "{{ preactVersion }}"
|
|
55
|
+
"tailorkit": "{{ tailorkitVersion }}",
|
|
56
|
+
"preact": "{{ preactVersion }}",
|
|
57
|
+
"zod": "{{ zodVersion }}"
|
|
98
58
|
},
|
|
99
59
|
"devDependencies": {
|
|
100
|
-
"
|
|
60
|
+
"drizzle-kit": "{{ drizzleKitVersion }}",
|
|
61
|
+
"drizzle-orm": "{{ drizzleOrmVersion }}",
|
|
62
|
+
"typescript": "{{ typescriptVersion }}"{% if linting %},
|
|
101
63
|
"oxlint": "{{ oxlintVersion }}"{% endif %}{% if formatting %},
|
|
102
|
-
"oxfmt": "{{ oxfmtVersion }}"{% endif %}
|
|
103
|
-
"typescript": "{{ typescriptVersion }}"
|
|
64
|
+
"oxfmt": "{{ oxfmtVersion }}"{% endif %}
|
|
104
65
|
},
|
|
105
66
|
"type": "module"
|
|
106
67
|
}
|
|
107
|
-
`,
|
|
68
|
+
`,Vr=`{
|
|
108
69
|
"compilerOptions": {
|
|
109
70
|
"allowSyntheticDefaultImports": true,
|
|
110
71
|
"esModuleInterop": true,
|
|
@@ -115,130 +76,118 @@ export const actions = ${ta(e.actions??{})} as TailorKitActions;`,Xi(n,r)];for(l
|
|
|
115
76
|
"module": "ESNext",
|
|
116
77
|
"moduleResolution": "bundler",
|
|
117
78
|
"noEmit": true,
|
|
79
|
+
"skipLibCheck": true,
|
|
118
80
|
"strict": true,
|
|
119
81
|
"target": "ESNext",
|
|
120
82
|
"verbatimModuleSyntax": true
|
|
121
83
|
},
|
|
122
84
|
"include": ["src", "tailorkit.config.ts"]
|
|
123
85
|
}
|
|
124
|
-
`,
|
|
86
|
+
`,Hr=`import type { TailorKitConfig } from "tailorkit/app/config";
|
|
125
87
|
|
|
126
88
|
const config = {
|
|
127
89
|
host: "{{ hostUrl }}",
|
|
128
|
-
|
|
129
|
-
|
|
90
|
+
logos: {
|
|
91
|
+
dark: "logo-dark.svg",
|
|
92
|
+
light: "logo-light.svg",
|
|
130
93
|
},
|
|
131
94
|
} satisfies TailorKitConfig;
|
|
132
95
|
|
|
133
96
|
export default config;
|
|
134
|
-
`,
|
|
97
|
+
`,Ur=`# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
|
98
|
+
|
|
99
|
+
# TailorKit
|
|
135
100
|
.tailorkit
|
|
136
101
|
|
|
137
|
-
#
|
|
138
|
-
logs
|
|
139
|
-
*.log
|
|
102
|
+
# debug
|
|
140
103
|
npm-debug.log*
|
|
141
104
|
yarn-debug.log*
|
|
142
105
|
yarn-error.log*
|
|
143
106
|
pnpm-debug.log*
|
|
144
|
-
lerna-debug.log*
|
|
145
107
|
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
108
|
+
# testing
|
|
109
|
+
/coverage
|
|
110
|
+
|
|
111
|
+
# dependencies
|
|
112
|
+
/node_modules
|
|
113
|
+
/.pnp
|
|
114
|
+
.pnp.js
|
|
150
115
|
|
|
151
|
-
#
|
|
116
|
+
# misc
|
|
117
|
+
.DS_Store
|
|
118
|
+
*.pem
|
|
119
|
+
|
|
120
|
+
# local env files
|
|
121
|
+
.env*.local
|
|
152
122
|
.env
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
.claude/settings.local.json
|
|
158
|
-
.claude/plans/
|
|
159
|
-
.claude/todos.json
|
|
160
|
-
.claude/worktrees
|
|
161
|
-
CLAUDE.local.md
|
|
162
|
-
|
|
163
|
-
# Editors
|
|
164
|
-
**/.idea
|
|
165
|
-
**/.#*
|
|
166
|
-
.nvmrc
|
|
167
|
-
`,ua=`import { defineConfig } from "oxlint";
|
|
123
|
+
|
|
124
|
+
# typescript
|
|
125
|
+
*.tsbuildinfo
|
|
126
|
+
`,Wr=`import { defineConfig } from "oxlint";
|
|
168
127
|
|
|
169
128
|
export default defineConfig({
|
|
170
129
|
ignorePatterns: ["src/tailorkit.gen.ts"],
|
|
171
130
|
});
|
|
172
|
-
`,
|
|
131
|
+
`,Gr=`import { defineConfig } from "oxfmt";
|
|
173
132
|
|
|
174
133
|
export default defineConfig({
|
|
175
134
|
ignorePatterns: ["src/tailorkit.gen.ts"],
|
|
176
135
|
});
|
|
177
|
-
`,
|
|
178
|
-
import
|
|
136
|
+
`,Kr=`import { ClientProvider, defineClient } from "tailorkit/client";
|
|
137
|
+
import defaultView from "./views/default";
|
|
179
138
|
|
|
180
139
|
const client = defineClient({
|
|
181
|
-
|
|
182
|
-
|
|
140
|
+
component: ClientProvider,
|
|
141
|
+
slots: {
|
|
142
|
+
{{ slotName }}: { {{ viewPath }}: defaultView },
|
|
183
143
|
},
|
|
184
144
|
});
|
|
185
145
|
|
|
186
146
|
export default client;
|
|
187
|
-
`,
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
147
|
+
`,qr=`import { defineView, useQuery } from "tailorkit/client";
|
|
148
|
+
import { api{% if useBox %}, Box{% endif %} } from "#tailorkit";
|
|
149
|
+
{% if multiple %}import { z } from "zod";
|
|
150
|
+
{% endif %}
|
|
151
|
+
|
|
152
|
+
const view = defineView({
|
|
153
|
+
slot: {{ slotName }},
|
|
154
|
+
view: {{ viewPath }},
|
|
155
|
+
{% if multiple %} instances: {
|
|
156
|
+
dataSchema: z.object({}),
|
|
157
|
+
resolve: () => [{ key: "default", metadata: { title: "Default" }, data: {} }],
|
|
158
|
+
},
|
|
159
|
+
{% endif %}
|
|
160
|
+
component: ViewComponent,
|
|
191
161
|
});
|
|
192
162
|
|
|
193
|
-
function
|
|
194
|
-
const
|
|
163
|
+
function ViewComponent() {
|
|
164
|
+
const greeting = useQuery(api.greeting, { name: "TailorKit" });
|
|
195
165
|
|
|
196
|
-
return <
|
|
166
|
+
return <{% if useBox %}Box{% endif %}>{greeting.isLoading ? "Loading…" : greeting.error?.message ?? greeting.data}</{% if useBox %}Box{% endif %}>;
|
|
197
167
|
}
|
|
198
168
|
|
|
199
|
-
export default
|
|
200
|
-
`,
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
export type ScreenPath = keyof ScreenPropsByPath & string;
|
|
226
|
-
export type ScreenProps<TPath extends ScreenPath> = ScreenPropsByPath[TPath];
|
|
227
|
-
|
|
228
|
-
export interface ButtonProps {
|
|
229
|
-
disabled?: unknown;
|
|
230
|
-
variant?: unknown;
|
|
231
|
-
onClick?: () => void;
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
export const Button = createRemoteComponent<ButtonProps, readonly ["default"]>("Button", {
|
|
235
|
-
slots: ["default"] as const,
|
|
236
|
-
});
|
|
237
|
-
|
|
238
|
-
export interface CardProps {
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
export const Card = createRemoteComponent<CardProps, readonly ["header", "content", "footer"]>("Card", {
|
|
242
|
-
slots: ["header", "content", "footer"] as const,
|
|
243
|
-
});
|
|
244
|
-
`,ha=new oe({strictVariables:!0}),ga=(e,t)=>ha.parseAndRender(e,t),_a=e=>g(e,{recursive:!0}).then(()=>{}),va=async(e,t,n)=>{if(!n&&ne(e))throw Error(`${e} already exists. Use --force to overwrite it.`);await b(e,t,`utf-8`)},ya=async e=>{let{targetDirectory:t,force:n,formatting:r,hostUrl:i,linting:a,packageName:o,packageVersions:s,useWorkspaceDependencies:c}=e,l=c?`workspace:*`:s.tailorkitApp,u=c?`workspace:*`:s.tailorkitCLI,d=[],f=[];a&&(d.push(`pnpm run lint`),f.push(`pnpm run lint:fix`)),r&&(d.push(`pnpm run format`),f.push(`pnpm run format:fix`));let p={checkScript:d.join(` && `),fixScript:f.join(` && `),formatting:r,hostUrl:i,linting:a,oxfmtVersion:s.oxfmt,oxlintVersion:s.oxlint,packageName:o,preactVersion:s.preact,tailorkitAppVersion:l,tailorkitCLIVersion:u,typescriptVersion:s.typescript};await _a(C.join(t,`src`,`screens`));let m=[{template:oa,dest:`package.json`},{template:sa,dest:`tsconfig.json`},{template:ca,dest:`tailorkit.config.ts`},{template:la,dest:`.gitignore`},{template:ua,dest:`oxlint.config.ts`,condition:a},{template:da,dest:`oxfmt.config.ts`,condition:r},{template:fa,dest:C.join(`src`,`client.ts`)},{template:pa,dest:C.join(`src`,`screens`,`default.tsx`)},{template:ma,dest:C.join(`src`,`tailorkit.gen.ts`)}];await Promise.all(m.filter(e=>e.condition!==!1).map(async({template:e,dest:r})=>{let i=await ga(e,p);await va(C.join(t,r),i,n)}))},ba=`https://registry.npmjs.org`,xa=5e3,Sa={oxfmt:{fallback:`^0.46.0`,matcher:`^0`,packageName:`oxfmt`},oxlint:{fallback:`^1.61.0`,matcher:`^1`,packageName:`oxlint`},preact:{fallback:`^10.29.1`,matcher:`^10`,packageName:`preact`},tailorkitCLI:{fallback:`latest`,matcher:`^0`,packageName:`@tailorkit/cli`},tailorkitApp:{fallback:`latest`,matcher:`^0`,packageName:`@tailorkit/app`},typescript:{fallback:`^6.0.3`,matcher:`^6`,packageName:`typescript`}},Ca=e=>{let t=/^(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)$/u.exec(e);if(!t?.groups)return;let{major:n,minor:r,patch:i}=t.groups;if(!(!n||!r||!i))return{major:Number.parseInt(n,10),minor:Number.parseInt(r,10),patch:Number.parseInt(i,10),raw:e}},wa=(e,t)=>e.major===t.major?e.minor===t.minor?e.patch-t.patch:e.minor-t.minor:e.major-t.major,Ta=(e,t)=>{let n=/^\^(?<major>\d+)(?:\.(?<minor>\d+))?/u.exec(t);if(!n?.groups?.major)return!1;let r=Number.parseInt(n.groups.major,10),i=Number.parseInt(n.groups.minor??`0`,10);return e.major===r&&e.minor>=i},Ea=async({fallback:e,matcher:t,packageName:n})=>{try{let r=await fetch(`${ba}/${encodeURIComponent(n)}`,{signal:AbortSignal.timeout(xa)});if(!r.ok)return e;let i=await r.json(),a=Object.keys(i.versions??{}).map(Ca).filter(e=>e!==void 0).filter(e=>Ta(e,t)).toSorted(wa).at(-1);return a?`^${a.raw}`:e}catch{return e}},Da=async()=>{let[e,t,n,r,i,a]=await Promise.all([Ea(Sa.oxfmt),Ea(Sa.oxlint),Ea(Sa.preact),Ea(Sa.tailorkitCLI),Ea(Sa.tailorkitApp),Ea(Sa.typescript)]);return{oxfmt:e,oxlint:t,preact:n,tailorkitCLI:r,tailorkitApp:i,typescript:a}},Oa=[`pnpm`,`yarn`,`npm`,`bun`],ka=e=>Oa.includes(e),Aa=e=>e.trim().toLowerCase().replaceAll(/[^a-z0-9._/-]+/gu,`-`).replaceAll(/^-+|-+$/gu,``),ja=e=>(s(e)&&(i(`Init cancelled.`),process.exit(0)),e),Ma=(e,t)=>C.resolve(t,e??`.`),Na=async(e,t)=>{let n=Aa(C.basename(t))||`tailorkit-app`;return Aa(e===void 0?ja(await f({defaultValue:n,message:`Package name`,placeholder:n,validate:e=>Aa(e??``).length===0?`Enter a package name.`:void 0})):e)},Pa=async e=>{if(e!==void 0){if(ka(e))return e;throw Error(`--package-manager must be one of: ${Oa.join(`, `)}.`)}return ja(await u({initialValue:`pnpm`,message:`Package manager`,options:Oa.map(e=>({label:e,value:e}))}))},Fa=async e=>e===void 0?ja(await a({initialValue:!0,message:`Add linting with oxlint?`})):e,Ia=async e=>e===void 0?ja(await a({initialValue:!0,message:`Add formatting with oxfmt?`})):e,La=e=>{try{ti(e??``);return}catch{return`Enter a valid host URL.`}},Ra=async e=>{if(e!==void 0){let t=La(e);if(t!==void 0)throw Error(t);return ti(e)}let t=`https://example.com/api/tailorkit`;return ti(ja(await f({defaultValue:t,message:`Host URL`,placeholder:t,validate:La})))},za=async e=>e===void 0?ja(await a({initialValue:!0,message:`Install dependencies?`})):e,Ba=async(e,t)=>t||!ne(e)?t:ja(await a({initialValue:!1,message:`${m.cyan(e)} already exists. Overwrite matching files?`})),Va=(e,t,n)=>new Promise((r,i)=>{let a=ae(e,t,{cwd:n,stdio:`inherit`});a.on(`close`,r),a.on(`error`,i)}),Ha=async(e,t)=>{let n=d();n.start(`Installing dependencies with ${t}`);let r=await Va(t,[`install`],e);if(r!==0)throw n.stop(`Install failed.`),Error(`${t} install exited with code ${r}.`);n.stop(`Installed dependencies.`)},Ua=async(e,t)=>{let n=d();n.start(`Formatting project`);let r=await Va(t,[`run`,`format:fix`],e);if(r!==0)throw n.stop(`Formatting failed.`),Error(`${t} run format:fix exited with code ${r}.`);n.stop(`Formatted project.`)},Wa=async e=>{let t=Ma(e.directory,e.cwd),n=await Na(e.name,t),r=C.join(t,n),i=await Ba(r,e.force??!1),a=await Pa(e.packageManager),o=await Ra(e.host),s=await Fa(e.linting),c=await Ia(e.formatting),l=await za(e.install),u=d();u.start(`Resolving package versions`);let f=await Da();return u.stop(`Resolved package versions.`),await g(r,{recursive:!0}),await ya({force:i,formatting:c,hostUrl:o,linting:s,packageName:n,packageVersions:f,targetDirectory:r}),l&&(await Ha(r,a),c&&await Ua(r,a)),r},Ga={".css":`text/css; charset=utf-8`,".html":`text/html; charset=utf-8`,".js":`text/javascript; charset=utf-8`,".json":`application/json; charset=utf-8`,".map":`application/json; charset=utf-8`},Ka=e=>Ga[C.extname(e)]??`application/octet-stream`,qa=e=>{if(e===void 0)return;let t=Number.parseInt(String(e),10);if(!Number.isInteger(t)||t<=0)throw Error(`--port must be a positive integer.`);return t},Ja=e=>({configPath:e.config,cwd:String(e.cwd??`.`),entry:e.entry,host:e.host,mode:e.mode,outDir:e.outDir,port:qa(e.port)}),Ya=(e,t)=>T(async(n,r)=>{try{let i=new URL(n.url??`/`,`http://localhost`);if(i.pathname===`/apps`){r.writeHead(200,{"access-control-allow-origin":`*`,"content-type":`application/json; charset=utf-8`}),r.end(JSON.stringify(t));return}let a=decodeURIComponent(i.pathname),o=a===`/`?`client.js`:a.slice(1),s=C.resolve(e,o),c=C.relative(e,s);if(c.startsWith(`..`)||C.isAbsolute(c)){r.writeHead(403),r.end(`Forbidden`);return}if(!(await y(s).catch(()=>null))?.isFile()){r.writeHead(404),r.end(`Not found`);return}r.writeHead(200,{"access-control-allow-origin":`*`,"content-type":Ka(s)}),r.end(await _(s))}catch(e){r.writeHead(500),r.end(e instanceof Error?e.message:String(e))}}),Xa=async e=>{let t=C.join(e,`package.json`),n=JSON.parse(await _(t,`utf-8`)),r=typeof n.name==`string`?n.name:C.basename(e);return[{clientPath:`/client.js`,description:typeof n.description==`string`?n.description:void 0,id:r,name:typeof n.name==`string`?n.name:void 0}]},Za=async e=>{let t=await Me(e.configPath,e.cwd),n=C.resolve(t.root,e.outDir??t.config.build?.outDir??`.tailorkit`),r=e.host??`127.0.0.1`,i=e.port??4175,{buildApp:a}=await import(`./assets/builder-wgJqHM_A.js`),o=await a({configPath:e.configPath,cwd:e.cwd,entry:e.entry,mode:e.mode,outDir:e.outDir,watch:!0}),s=()=>{o&&typeof o==`object`&&`close`in o&&o.close()},l=Ya(n,await Xa(t.root));await new Promise((e,t)=>{l.once(`error`,t),l.listen(i,r,e)}),l.removeAllListeners(`error`),process.once(`SIGINT`,()=>{s(),l.close(),process.exit(0)}),process.once(`SIGTERM`,()=>{s(),l.close(),process.exit(0)}),c.info(m.green(`Experimental preview running at http://${r}:${i}`)),c.info(m.dim(`Serving built worker assets from ${n}`))},Qa=e=>{let t=S();return t===`darwin`?{args:[e],command:`open`}:t===`win32`?{args:[`/c`,`start`,``,e],command:`cmd`}:{args:[e],command:`xdg-open`}},$a=e=>new Promise(t=>{let{args:n,command:r}=Qa(e),i=ae(r,n,{detached:!0,stdio:`ignore`,windowsHide:!0});i.once(`error`,()=>{t(!1)}),i.once(`spawn`,()=>{i.unref(),t(!0)})}),$=p(`tailorkit`),eo=e=>{if(e<1024)return`${e} B`;let t=[`KB`,`MB`,`GB`],n=e/1024,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;return`${n.toFixed(n>=10?1:2)} ${t[r]}`};$.option(`--cwd <path>`,`Working directory`,{default:`.`}),$.command(`login`,`Authenticate the TailorKit CLI with a host app`).option(`--config <path>`,`Path to tailorkit config`).option(`--open`,`Open the approval URL in the default browser`,{default:!0}).option(`--timeout <seconds>`,`Seconds to wait for approval`,{default:1800}).action(async e=>{o(m.bold(`TailorKit`));let t=d(),n=!1;try{let r=Number.parseInt(String(e.timeout??`1800`),10);if(!Number.isInteger(r)||r<=0)throw Error(`--timeout must be a positive integer.`);await _i({configPath:e.config,cwd:String(e.cwd??`.`),timeout:r*1e3},({expiresAt:r,hostUrl:i,userCode:a})=>{let o=fi(i,a);e.open!==!1&&$a(o),c.info(`Enter this code in the host app: ${m.bold(a)}`),c.info(`Approval URL: ${m.cyan(o)}`),c.info(`Code expires at ${r.toLocaleString()}.`),c.info(`Waiting for approval...`),t.start(`Checking approval status`),n=!0}),n&&t.stop(`Approved.`),l(`Authenticated successfully.`)}catch(e){n&&t.stop(`Approval failed.`),c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.command(`logout`,`Remove stored TailorKit CLI credentials for a host app`).option(`--config <path>`,`Path to tailorkit config`).action(async e=>{o(m.bold(`TailorKit`));try{let t=await yi({configPath:e.config,cwd:String(e.cwd??`.`)});l(t.removed?`Logged out of ${m.cyan(t.hostUrl)}.`:`No stored credentials found for ${m.cyan(t.hostUrl)}.`)}catch(e){c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.command(`whoami`,`Show the current TailorKit CLI authentication scope`).option(`--config <path>`,`Path to tailorkit config`).action(async e=>{o(m.bold(`TailorKit`));try{let t=await vi({configPath:e.config,cwd:String(e.cwd??`.`)});c.info(`Host: ${m.cyan(t.hostUrl)}`),c.info(`Scope: ${m.cyan(t.scopeId)}`),l(`Authenticated.`)}catch(e){c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.command(`deploy`,`Build and deploy the TailorKit app`).option(`--config <path>`,`Path to tailorkit config`).option(`--entry <path>`,`Client entry file`).option(`--out-dir <path>`,`Build output directory`).option(`--mode <mode>`,`Vite mode`).action(async e=>{o(m.bold(`TailorKit`));let t=d();try{t.start(`Building and deploying app`);let n=await Pi({configPath:e.config,cwd:String(e.cwd??`.`),entry:e.entry,mode:e.mode,onMissingAppId:async({appName:e,configPath:n,hostUrl:r,reason:i})=>{t.stop(`App not linked.`),c.info(i===`missing`?`No appId found in ${m.cyan(n)}.`:`The appId in ${m.cyan(n)} does not exist.`),c.info(`Host: ${m.cyan(r)}`);let o=await a({initialValue:!0,message:i===`missing`?`Create a TailorKit app named ${e}?`:`Create a new TailorKit app named ${e} and update the config?`});return!s(o)&&(o&&t.start(`Creating app and deploying`),o)},onTypecheckFailed:async({command:e,output:n})=>{t.stop(`Type check failed.`),c.error(`Type check failed while running ${m.cyan(e)}.`),n&&c.error(n);let r=await a({initialValue:!1,message:`Type check failed, but the app built successfully. Upload anyway?`});return!s(r)&&(r&&t.start(`Uploading app`),r)},outDir:e.outDir});t.stop(`Deployed app.`),n.createdApp&&c.info(`Created app and updated tailorkit.config.ts with ${m.cyan(n.appId)}.`),c.info(`Host: ${m.cyan(n.hostUrl)}`),c.info(`App: ${m.cyan(n.appId)}`),c.info(`Deployment: ${m.cyan(n.deploymentId)}`),c.info(`Uploaded files:`);for(let e of n.uploadedFiles)c.info(` ${m.cyan(e.path)} ${m.dim(`${eo(e.size)} raw, ${eo(e.gzipSize)} gzip`)}`);n.status&&c.info(`Status: ${m.cyan(n.status)}`),l(`Deployment published.`)}catch(e){t.stop(`Deployment failed.`),c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.command(`build`,`Build the TailorKit app`).option(`--config <path>`,`Path to tailorkit config`).option(`--entry <path>`,`Client entry file`).option(`--out-dir <path>`,`Build output directory`).option(`--mode <mode>`,`Vite mode`).action(async e=>{o(m.bold(`TailorKit`));try{let{buildApp:t}=await import(`./assets/builder-wgJqHM_A.js`);await t({configPath:e.config,cwd:String(e.cwd??`.`),entry:e.entry,mode:e.mode,outDir:e.outDir}),l(`Built app.`)}catch(e){c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.command(`experimental-preview`,`Build and preview the TailorKit worker`).option(`--config <path>`,`Path to tailorkit config`).option(`--entry <path>`,`Client entry file`).option(`--out-dir <path>`,`Build output directory`).option(`--host <host>`,`Preview host`).option(`--port <port>`,`Preview port`).option(`--mode <mode>`,`Vite mode`).action(async e=>{o(m.bold(`TailorKit`));try{await Za(Ja(e))}catch(e){c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.command(`generate`,`Generate TailorKit app bindings`).option(`--config <path>`,`Path to tailorkit config`).option(`--out <path>`,`Generated TypeScript output file`).action(async e=>{o(m.bold(`TailorKit`));try{let t=await aa({configPath:e.config,cwd:String(e.cwd??`.`),outFile:e.out});l(`Generated ${m.cyan(t)}.`)}catch(e){c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.command(`init [directory]`,`Create a new TailorKit app`).option(`--name <name>`,`Package name`).option(`--host <url>`,`TailorKit host URL`).option(`--package-manager <pm>`,`Package manager: bun, yarn, pnpm, or npm`).option(`--lint`,`Add oxlint (use --no-lint to skip)`).option(`--format`,`Add oxfmt (use --no-format to skip)`).option(`--install`,`Install dependencies after scaffolding (use --no-install to skip)`).option(`--force`,`Overwrite existing files`).action(async(e,t)=>{o(m.bold(`TailorKit`));try{let n=await Wa({cwd:String(t.cwd??`.`),directory:e,force:t.force,formatting:t.format,host:t.host,install:t.install,linting:t.lint,name:t.name,packageManager:t.packageManager});l(`Created app at ${m.cyan(n)}.`)}catch(e){c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.help(),$.version(`0.1.0-beta.2`),$.parse();export{Me as t};
|
|
169
|
+
export default view;
|
|
170
|
+
`,Jr=`import { defineServer } from "tailorkit/server";
|
|
171
|
+
import * as functions from "./functions/greeting";
|
|
172
|
+
|
|
173
|
+
const app = defineServer(functions);
|
|
174
|
+
|
|
175
|
+
export default app;
|
|
176
|
+
`,Yr=`// Define your SQLite tables here using table(), text(), boolean(), etc.
|
|
177
|
+
// Run pnpm db:generate and commit migrations/ when adding or changing tables.
|
|
178
|
+
export {};
|
|
179
|
+
`,Xr=`import { tk } from "tailorkit/server";
|
|
180
|
+
import { z } from "zod";
|
|
181
|
+
|
|
182
|
+
export const greeting = tk.query
|
|
183
|
+
.input(z.object({ name: z.string() }))
|
|
184
|
+
.handler(({ input }) => \`Hello, \${input.name}!\`);
|
|
185
|
+
`,Zr=`<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2" viewBox="0 0 24 24">
|
|
186
|
+
<path d="M3 6h6v6H3z" style="fill:#f5f5f5" transform="matrix(1.5 0 0 1.5 10.5 -9)"/>
|
|
187
|
+
<path d="M2 6v12h12v-6H8V6z" style="fill:#f5f5f5" transform="matrix(1.5 0 0 1.5 -3 -3)"/>
|
|
188
|
+
</svg>
|
|
189
|
+
`,Qr=`<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2" viewBox="0 0 24 24">
|
|
190
|
+
<path d="M3 6h6v6H3z" style="fill:#262626" transform="matrix(1.5 0 0 1.5 10.5 -9)"/>
|
|
191
|
+
<path d="M2 6v12h12v-6H8V6z" style="fill:#262626" transform="matrix(1.5 0 0 1.5 -3 -3)"/>
|
|
192
|
+
</svg>
|
|
193
|
+
`,$r=new fe({strictVariables:!0}),ei=(e,t)=>$r.parseAndRender(e,t),ti=e=>g(e,{recursive:!0}).then(()=>{}),ni=async(e,t,n)=>{if(!n&&le(e))throw Error(`${e} already exists. Use --force to overwrite it.`);await C(e,t,`utf-8`)},ri=async e=>{let{targetDirectory:t,force:n,formatting:r,hostUrl:i,schema:a,linting:o,packageName:s,packageVersions:c,useWorkspaceDependencies:l}=e,u=Object.keys(a.slots??{}).sort(),d=Object.keys(a.views??{}).sort().find(e=>u.some(t=>a.slots?.[t]?.views.includes(e)));if(d===void 0)throw Error(`The host schema has no views supported by a slot. Add a view and slot before running tailorkit init.`);let f=u.find(e=>a.slots?.[e]?.views.includes(d)),p=a.components?.Box,m=p?.children===!0&&!p.fields?.required?.length,h=E.join(t,`src`,`tailorkit.gen.ts`);if(!n&&le(h))throw Error(`${h} already exists. Use --force to overwrite it.`);let g=l?`workspace:*`:c.tailorkit,_=[],v=[];o&&(_.push(`pnpm run lint`),v.push(`pnpm run lint:fix`)),r&&(_.push(`pnpm run format`),v.push(`pnpm run format:fix`));let y={viewPath:JSON.stringify(d),slotName:JSON.stringify(f),multiple:a.slots?.[f]?.multiple===!0,useBox:m,checkScript:_.join(` && `),fixScript:v.join(` && `),formatting:r,hostUrl:i,linting:o,oxfmtVersion:c.oxfmt,oxlintVersion:c.oxlint,packageName:s,preactVersion:c.preact,tailorkitVersion:g,typescriptVersion:c.typescript,zodVersion:c.zod??`^4.0.0`,drizzleKitVersion:c.drizzleKit??`1.0.0-rc.4-5d5b77c`,drizzleOrmVersion:c.drizzleOrm??`1.0.0-rc.4-5d5b77c`};await ti(E.join(t,`src`,`views`)),await ti(E.join(t,`src`,`functions`));let b=[{template:Br,dest:`package.json`},{template:Vr,dest:`tsconfig.json`},{template:Hr,dest:`tailorkit.config.ts`},{template:Zr,dest:`logo-dark.svg`},{template:Qr,dest:`logo-light.svg`},{template:Ur,dest:`.gitignore`},{template:Wr,dest:`oxlint.config.ts`,condition:o},{template:Gr,dest:`oxfmt.config.ts`,condition:r},{template:Kr,dest:E.join(`src`,`client.ts`)},{template:qr,dest:E.join(`src`,`views`,`default.tsx`)},{template:Jr,dest:E.join(`src`,`server.ts`)},{template:Yr,dest:E.join(`src`,`schema.ts`)},{template:Xr,dest:E.join(`src`,`functions`,`greeting.ts`)}];await Promise.all(b.filter(e=>e.condition!==!1).map(async({template:e,dest:r})=>{let i=await ei(e,y);await ni(E.join(t,r),i,n)})),await Mr({cwd:t,schema:a})},ii=[`pnpm`,`yarn`,`npm`,`bun`],ai=e=>ii.includes(e),oi=e=>e.trim().toLowerCase().replaceAll(/[^a-z0-9._/-]+/gu,`-`).replaceAll(/^-+|-+$/gu,``),Z=e=>(s(e)&&(i(`Init cancelled.`),process.exit(0)),e),si=(e,t)=>E.resolve(t,e??`.`),ci=async(e,t)=>{let n=oi(E.basename(t))||`tailorkit-app`;return oi(e===void 0?Z(await f({defaultValue:n,message:`Package name`,placeholder:n,validate:e=>oi(e??``).length===0?`Enter a package name.`:void 0})):e)},li=async e=>{if(e!==void 0){if(ai(e))return e;throw Error(`--package-manager must be one of: ${ii.join(`, `)}.`)}return Z(await u({initialValue:`pnpm`,message:`Package manager`,options:ii.map(e=>({label:e,value:e}))}))},ui=async e=>e===void 0?Z(await a({initialValue:!0,message:`Add linting with oxlint?`})):e,di=async e=>e===void 0?Z(await a({initialValue:!0,message:`Add formatting with oxfmt?`})):e,fi=e=>{try{gn(e??``);return}catch{return`Enter a valid host URL.`}},pi=async e=>{if(e!==void 0){let t=fi(e);if(t!==void 0)throw Error(t);return gn(e)}let t=`https://example.com/api/tailorkit`;return gn(Z(await f({defaultValue:t,message:`Host URL`,placeholder:t,validate:fi})))},mi=async e=>e===void 0?Z(await a({initialValue:!0,message:`Install dependencies?`})):e,hi=async(e,t)=>t||!le(e)?t:Z(await a({initialValue:!1,message:`${m.cyan(e)} already exists. Overwrite matching files?`})),gi=(e,t,n)=>new Promise((r,i)=>{let a=ce(e,t,{cwd:n,stdio:`inherit`});a.on(`close`,r),a.on(`error`,i)}),_i=async(e,t)=>{let n=d();n.start(`Installing dependencies with ${t}`);let r=await gi(t,[`install`],e);if(r!==0)throw n.stop(`Install failed.`),Error(`${t} install exited with code ${r}.`);n.stop(`Installed dependencies.`)},vi=async(e,t)=>{let n=d();n.start(`Formatting project`);let r=await gi(t,[`run`,`format:fix`],e);if(r!==0)throw n.stop(`Formatting failed.`),Error(`${t} run format:fix exited with code ${r}.`);n.stop(`Formatted project.`)},yi=async e=>{let t=si(e.directory,e.cwd),n=await ci(e.name,t),r=E.join(t,n),i=await hi(r,e.force??!1),a=await li(e.packageManager),o=await pi(e.host),s=await ui(e.linting),c=await di(e.formatting),l=await mi(e.install),u=d();u.start(`Fetching host schema`);let f;try{f=await jr(o),u.stop(`Fetched host schema.`)}catch(e){throw u.stop(`Unable to fetch host schema.`),e}u.start(`Resolving package versions`);let p=await zr();return u.stop(`Resolved package versions.`),await g(r,{recursive:!0}),await ri({force:i,formatting:c,hostUrl:o,linting:s,packageName:n,packageVersions:p,schema:f,targetDirectory:r}),l&&(await _i(r,a),c&&await vi(r,a)),r},bi=262144,xi={".css":`text/css; charset=utf-8`,".html":`text/html; charset=utf-8`,".js":`text/javascript; charset=utf-8`,".json":`application/json; charset=utf-8`,".map":`application/json; charset=utf-8`},Q=e=>e instanceof Error?e.message:String(e),Si=e=>typeof e==`object`&&!!e&&`code`in e&&e.code===`UNAUTHORIZED`&&`message`in e&&typeof e.message==`string`&&/Preview session is unavailable|Preview developer reconnect grace expired|Preview CLI token is unavailable/u.test(e.message);async function Ci(e){let t=await b(e),n=(await y(t,{recursive:!0,withFileTypes:!0})).filter(e=>e.isFile()).toSorted((e,t)=>E.join(e.parentPath,e.name).localeCompare(E.join(t.parentPath,t.name)));if(n.length>100)throw Error(`Preview build exceeds 100 files.`);let r=[],i={files:[]},a=0;for(let e of n){let n=await b(E.join(e.parentPath,e.name)),o=E.relative(t,n).replaceAll(E.sep,`/`);if(!o||o.startsWith(`../`)||E.isAbsolute(o))throw Error(`Preview file escapes the build output.`);let s=await v(n);if(s.length>1048576)throw Error(`Preview file ${o} exceeds 1 MiB.`);if(a+=s.length,a>10485760)throw Error(`Preview build exceeds 10 MiB.`);o===`views.json`&&(i.views=Ot.shape.views.unwrap().parse(JSON.parse(s.toString(`utf8`)))),r.push(s),i.files.push({path:o,contentType:xi[E.extname(o)]??`application/octet-stream`,size:s.length,chunks:Math.ceil(s.length/bi),sha256:oe(`sha256`).update(s).digest(`hex`)})}if(!i.files.some(e=>e.path===`client.js`))throw Error(`Preview build is missing client.js.`);return{files:r,manifest:i,fingerprint:oe(`sha256`).update(JSON.stringify(i)).digest(`hex`)}}function wi(e,t,n){let r=0;return async()=>{let i=++r;try{let n=await e();i===r&&t(n)}catch(e){i===r&&n(e)}}}async function Ti(e,t){let{buildId:n}=await e.beginBuild({manifest:t.manifest});for(let[r,i]of t.files.entries())for(let a=0;a<(t.manifest.files[r]?.chunks??0);a++)await e.uploadChunk({buildId:n,fileIndex:r,chunkIndex:a,base64:i.subarray(a*bi,(a+1)*bi).toString(`base64`)});await e.commitBuild({buildId:n})}var Ei=k.object({config:k.string().optional(),cwd:k.string().default(`.`),mode:k.string().optional(),outDir:k.string().optional(),replace:k.boolean().optional()}),Di=e=>{let t=Ei.parse(e);return{configPath:t.config,cwd:t.cwd,mode:t.mode,outDir:t.outDir,replace:t.replace}};async function Oi(e){let t=await ee(e.configPath,e.cwd);if(!t.config.appId)throw Error(`Missing appId. Deploy once before starting a remote preview.`);let n=await Ln(e),r=await Fn(n.hostUrl);if(!r?.deployToken)throw Error(`Not logged in. Run tailorkit login first.`);let{buildApp:i}=await import(`@tailorkit/app/builder`),a=await i({...e,watch:!0}),o=async()=>{a&&typeof a==`object`&&`close`in a&&await a.close()},s=await L({headers:{authorization:`Bearer ${r.deployToken}`},url:n.hostUrl}).preview.start({appId:t.config.appId,replaceActive:e.replace}).catch(async e=>{throw await o(),e}),l=`data`in s?s.data:s;if(!l)throw await o(),Error(`Unable to start preview session.`);let u=L({fetch:(e,t)=>fetch(e,{...t,signal:AbortSignal.timeout(5e3)}),headers:{authorization:`Bearer ${r.deployToken}`},url:n.hostUrl}),d=async()=>{try{await u.preview.stop({sessionId:l.sessionId})}catch(e){c.warn(`Unable to end preview session: ${Q(e)}`)}},f=E.resolve(t.root,e.outDir??t.config.build?.outDir??`.tailorkit`),p,h;try{p=await b(E.join(f,`client`)),h=await Ci(p)}catch(e){try{await o()}catch(e){c.warn(`Unable to close preview watcher: ${Q(e)}`)}throw await d(),e}let g,_,v,y=!1,x=!1,S,C,w,T=0,D=1e3,O=0,te=()=>{y||(y=!0,process.off(`SIGINT`,A),process.off(`SIGTERM`,A),S&&clearTimeout(S),C&&clearTimeout(C),w&&clearInterval(w),v?.close(),o().catch(e=>{c.warn(`Unable to close preview watcher: ${Q(e)}`)}),c.warn(`Preview session ended. Start a new preview to continue.`))},ne=()=>{y||!_||x||(S&&clearTimeout(S),S=setTimeout(()=>{if(S=void 0,!_||h.fingerprint===g)return;let e=h,t=_,n=O;x=!0,T=Date.now(),Ti(t,e).then(()=>{n===O&&(g=e.fingerprint)}).catch(e=>{y||c.warn(`Preview upload interrupted: ${Q(e)}`)}).finally(()=>{n===O&&(x=!1,h.fingerprint!==g&&ne())})},Math.max(500,500-(Date.now()-T))))},re=wi(()=>Ci(p),e=>{y||(h=e,ne())},e=>{y||c.warn(`Keeping the last successful preview: ${Q(e)}`)});a&&typeof a==`object`&&`on`in a&&a.on(`event`,e=>{e.code===`BUNDLE_END`&&re()});let k=()=>{if(y)return;let e=new URL(l.tunnelUrl);e.searchParams.set(`role`,`uploader`);let t=new WebSocket(e,l.tunnelToken);v=t,t.addEventListener(`open`,()=>{O+=1,D=1e3,_=Ft(t);let e=()=>void _?.heartbeat().catch(e=>{v!==t||y||(Si(e)?te():t.close())});e(),w=setInterval(e,2e4),ne()}),t.addEventListener(`close`,()=>{O+=1,x=!1,w&&clearInterval(w),v===t&&(v=void 0,_=void 0),y||(C=setTimeout(k,D),D=Math.min(D*2,3e4))}),t.addEventListener(`error`,()=>t.close())};k();let A=()=>{y||(y=!0,process.off(`SIGINT`,A),process.off(`SIGTERM`,A),o().catch(e=>{c.warn(`Unable to close preview watcher: ${Q(e)}`)}),S&&clearTimeout(S),C&&clearTimeout(C),w&&clearInterval(w),v?.close(),d().finally(()=>process.exit(0)))};process.once(`SIGINT`,A),process.once(`SIGTERM`,A);let ie=new URL(n.hostUrl);ie.pathname=`${ie.pathname.replace(/\/+$/u,``)}/preview/${l.shareId}`,c.info(m.green(`Host preview: ${ie.href}`)),c.info(m.dim(`Uploading built app assets from ${p}`))}var ki=e=>{let t=T();return t===`darwin`?{args:[e],command:`open`}:t===`win32`?{args:[`/c`,`start`,``,e],command:`cmd`}:{args:[e],command:`xdg-open`}},Ai=e=>new Promise(t=>{let{args:n,command:r}=ki(e),i=ce(r,n,{detached:!0,stdio:`ignore`,windowsHide:!0});i.once(`error`,()=>{t(!1)}),i.once(`spawn`,()=>{i.unref(),t(!0)})}),$=p(`tailorkit`),ji=e=>{if(e<1024)return`${e} B`;let t=[`KB`,`MB`,`GB`],n=e/1024,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;return`${n.toFixed(n>=10?1:2)} ${t[r]}`},Mi=async(e,t=!0)=>{let n=d(),r=!1;try{let i=await In(e,({expiresAt:e,hostUrl:i,userCode:a})=>{let o=jn(i,a);t&&Ai(o),c.info(`Enter this code in the host app: ${m.bold(a)}`),c.info(`Approval URL: ${m.cyan(o)}`),c.info(`Code expires at ${e.toLocaleString()}.`),c.info(`Waiting for approval...`),n.start(`Checking approval status`),r=!0});return r&&n.stop(`Approved.`),i}catch(e){throw r&&n.stop(`Approval failed.`),e}};$.option(`--cwd <path>`,`Working directory`,{default:`.`}),$.command(`preview`,`Preview the app inside a host app`).option(`--config <path>`,`Path to tailorkit config`).option(`--out-dir <path>`,`Build output directory`).option(`--mode <mode>`,`Vite mode`).option(`--replace`,`End the active preview for this app and start a new one`).action(async e=>{o(m.bold(`TailorKit`));try{await Oi(Di(e))}catch(e){c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.command(`login`,`Authenticate the TailorKit CLI with a host app`).option(`--config <path>`,`Path to tailorkit config`).option(`--open`,`Open the approval URL in the default browser`,{default:!0}).option(`--timeout <seconds>`,`Seconds to wait for approval`,{default:1800}).action(async e=>{o(m.bold(`TailorKit`));try{let t=Number.parseInt(String(e.timeout??`1800`),10);if(!Number.isInteger(t)||t<=0)throw Error(`--timeout must be a positive integer.`);await Mi({configPath:e.config,cwd:String(e.cwd??`.`),timeout:t*1e3},e.open!==!1),l(`Authenticated successfully.`)}catch(e){c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.command(`logout`,`Remove stored TailorKit CLI credentials for a host app`).option(`--config <path>`,`Path to tailorkit config`).action(async e=>{o(m.bold(`TailorKit`));try{let t=await Rn({configPath:e.config,cwd:String(e.cwd??`.`)});l(t.removed?`Logged out of ${m.cyan(t.hostUrl)}.`:`No stored credentials found for ${m.cyan(t.hostUrl)}.`)}catch(e){c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.command(`whoami`,`Show the current TailorKit CLI authentication scope`).option(`--config <path>`,`Path to tailorkit config`).action(async e=>{o(m.bold(`TailorKit`));try{let t=await Ln({configPath:e.config,cwd:String(e.cwd??`.`)});c.info(`Host: ${m.cyan(t.hostUrl)}`),c.info(`Scope: ${m.cyan(JSON.stringify(t.scope))}`),l(`Authenticated.`)}catch(e){c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.command(`deploy`,`Build and deploy the TailorKit app`).option(`--config <path>`,`Path to tailorkit config`).option(`--out-dir <path>`,`Build output directory`).option(`--mode <mode>`,`Vite mode`).action(async e=>{o(m.bold(`TailorKit`));let t=d();try{t.start(`Building and deploying app`);let n=await Zn({configPath:e.config,cwd:String(e.cwd??`.`),mode:e.mode,onLoginRequired:async()=>{t.stop(`Authentication required.`);let n=await Mi({configPath:e.config,cwd:String(e.cwd??`.`)});return t.start(`Building and deploying app`),n},onMissingAppId:async({appName:e,configPath:n,hostUrl:r,reason:i})=>{t.stop(`App not linked.`),c.info(i===`missing`?`No appId found in ${m.cyan(n)}.`:`The appId in ${m.cyan(n)} does not exist.`),c.info(`Host: ${m.cyan(r)}`);let o=await a({initialValue:!0,message:i===`missing`?`Create a TailorKit app named ${e}?`:`Create a new TailorKit app named ${e} and update the config?`});return!s(o)&&(o&&t.start(`Creating app and deploying`),o===!0)},onTypecheckFailed:async({command:e,output:n})=>{t.stop(`Type check failed.`),c.error(`Type check failed while running ${m.cyan(e)}.`),n&&c.error(n);let r=await a({initialValue:!1,message:`Type check failed, but the app built successfully. Upload anyway?`});return!s(r)&&(r&&t.start(`Uploading app`),r===!0)},outDir:e.outDir});t.stop(`Deployed app.`),n.createdApp&&c.info(`Created app and updated tailorkit.config.ts with ${m.cyan(n.appId)}.`),c.info(`Host: ${m.cyan(n.hostUrl)}`),c.info(`App: ${m.cyan(n.appId)}`),c.info(`Deployment: ${m.cyan(n.deploymentId)}`),c.info(`Uploaded files:`);for(let e of n.uploadedFiles)c.info(` ${m.cyan(e.path)} ${m.dim(`${ji(e.size)} raw, ${ji(e.gzipSize)} gzip`)}`);n.status&&c.info(`Status: ${m.cyan(n.status)}`),l(`Deployment published.`)}catch(e){t.stop(`Deployment failed.`),c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.command(`build`,`Build the TailorKit app`).option(`--config <path>`,`Path to tailorkit config`).option(`--out-dir <path>`,`Build output directory`).option(`--mode <mode>`,`Vite mode`).action(async e=>{o(m.bold(`TailorKit`));try{let{buildApp:t}=await import(`@tailorkit/app/builder`);await t({configPath:e.config,cwd:String(e.cwd??`.`),mode:e.mode,outDir:e.outDir}),l(`Built app.`)}catch(e){c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.command(`db <command>`,`Generate database migrations with db generate`).option(`--config <path>`,`Path to tailorkit config`).option(`--name <name>`,`Migration name`).action(async(e,t)=>{o(m.bold(`TailorKit`));try{if(e!==`generate`)throw Error(`Unknown database command: ${e}. Use tailorkit db generate.`);let{generateAppMigrations:n}=await import(`@tailorkit/app/builder`),r=await n({configPath:t.config,cwd:String(t.cwd??`.`),name:t.name});l(`Migrations are up to date in ${m.cyan(r)}.`)}catch(e){c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.command(`generate`,`Generate TailorKit app bindings`).option(`--config <path>`,`Path to tailorkit config`).option(`--out <path>`,`Generated TypeScript output file`).action(async e=>{o(m.bold(`TailorKit`));try{let t=await Mr({configPath:e.config,cwd:String(e.cwd??`.`),outFile:e.out});l(`Generated ${m.cyan(t)}.`)}catch(e){c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.command(`init [directory]`,`Create a new TailorKit app`).option(`--name <name>`,`Package name`).option(`--host <url>`,`TailorKit host URL`).option(`--package-manager <pm>`,`Package manager: bun, yarn, pnpm, or npm`).option(`--lint`,`Add oxlint (use --no-lint to skip)`).option(`--format`,`Add oxfmt (use --no-format to skip)`).option(`--install`,`Install dependencies after scaffolding (use --no-install to skip)`).option(`--force`,`Overwrite existing files`).action(async(e,t)=>{o(m.bold(`TailorKit`));try{let n=await yi({cwd:String(t.cwd??`.`),directory:e,force:t.force,formatting:t.format,host:t.host,install:t.install,linting:t.lint,name:t.name,packageManager:t.packageManager});l(`Created app at ${m.cyan(n)}.`)}catch(e){c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.command(`agent`,`Chat with the TailorKit app agent`).option(`--app <id>`,`App ID (uses config appId, or prompts to select or create an app)`).option(`--config <path>`,`Path to tailorkit config`).action(async e=>{try{let{runAgentCommand:t}=await import(`./assets/agent-BSIUE6vC.js`);await t({appId:e.app,configPath:e.config,cwd:String(e.cwd??`.`),onLoginRequired:()=>Mi({configPath:e.config,cwd:String(e.cwd??`.`)})})}catch(e){c.error(e instanceof Error?e.message:String(e)),process.exitCode=1}}),$.help(),$.version(`0.1.0-beta.20`),$.parse();export{An as a,Fn as i,Bn as n,Ln as o,Mn as r,L as s,zn as t};
|