kuriko 0.3.2 → 0.5.0
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/kuriko.mjs +331 -244
- package/module/main.tf +13 -1
- package/module/outputs.tf +10 -0
- package/package.json +1 -1
package/kuriko.mjs
CHANGED
|
@@ -1,153 +1,153 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __kurikoRequire } from "node:module"; const require = __kurikoRequire(import.meta.url);
|
|
3
|
-
var
|
|
4
|
-
`)}};
|
|
5
|
-
`)?
|
|
3
|
+
var kf=Object.create;var jo=Object.defineProperty;var $f=Object.getOwnPropertyDescriptor;var Sf=Object.getOwnPropertyNames;var vf=Object.getPrototypeOf,Af=Object.prototype.hasOwnProperty;var jn=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var Ef=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(s){throw n=[s],s}};var E=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}};var _f=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Sf(e))!Af.call(t,r)&&r!==n&&jo(t,r,{get:()=>e[r],enumerable:!(s=$f(e,r))||s.enumerable});return t};var Cf=(t,e,n)=>(n=t!=null?kf(vf(t)):{},_f(e||!t||!t.__esModule?jo(n,"default",{value:t,enumerable:!0}):n,t));var w,p=Ef(()=>{w={version:"0.5.0"}});var B=E(Z=>{"use strict";p();var kr=Symbol.for("yaml.alias"),Ho=Symbol.for("yaml.document"),Dn=Symbol.for("yaml.map"),Qo=Symbol.for("yaml.pair"),$r=Symbol.for("yaml.scalar"),Bn=Symbol.for("yaml.seq"),ve=Symbol.for("yaml.node.type"),Xf=t=>!!t&&typeof t=="object"&&t[ve]===kr,ed=t=>!!t&&typeof t=="object"&&t[ve]===Ho,td=t=>!!t&&typeof t=="object"&&t[ve]===Dn,nd=t=>!!t&&typeof t=="object"&&t[ve]===Qo,Zo=t=>!!t&&typeof t=="object"&&t[ve]===$r,sd=t=>!!t&&typeof t=="object"&&t[ve]===Bn;function Xo(t){if(t&&typeof t=="object")switch(t[ve]){case Dn:case Bn:return!0}return!1}function rd(t){if(t&&typeof t=="object")switch(t[ve]){case kr:case Dn:case $r:case Bn:return!0}return!1}var id=t=>(Zo(t)||Xo(t))&&!!t.anchor;Z.ALIAS=kr;Z.DOC=Ho;Z.MAP=Dn;Z.NODE_TYPE=ve;Z.PAIR=Qo;Z.SCALAR=$r;Z.SEQ=Bn;Z.hasAnchor=id;Z.isAlias=Xf;Z.isCollection=Xo;Z.isDocument=ed;Z.isMap=td;Z.isNode=rd;Z.isPair=nd;Z.isScalar=Zo;Z.isSeq=sd});var Dt=E(Sr=>{"use strict";p();var J=B(),re=Symbol("break visit"),ea=Symbol("skip children"),ye=Symbol("remove node");function Un(t,e){let n=ta(e);J.isDocument(t)?lt(null,t.contents,n,Object.freeze([t]))===ye&&(t.contents=null):lt(null,t,n,Object.freeze([]))}Un.BREAK=re;Un.SKIP=ea;Un.REMOVE=ye;function lt(t,e,n,s){let r=na(t,e,n,s);if(J.isNode(r)||J.isPair(r))return sa(t,s,r),lt(t,r,n,s);if(typeof r!="symbol"){if(J.isCollection(e)){s=Object.freeze(s.concat(e));for(let i=0;i<e.items.length;++i){let o=lt(i,e.items[i],n,s);if(typeof o=="number")i=o-1;else{if(o===re)return re;o===ye&&(e.items.splice(i,1),i-=1)}}}else if(J.isPair(e)){s=Object.freeze(s.concat(e));let i=lt("key",e.key,n,s);if(i===re)return re;i===ye&&(e.key=null);let o=lt("value",e.value,n,s);if(o===re)return re;o===ye&&(e.value=null)}}return r}async function Gn(t,e){let n=ta(e);J.isDocument(t)?await ut(null,t.contents,n,Object.freeze([t]))===ye&&(t.contents=null):await ut(null,t,n,Object.freeze([]))}Gn.BREAK=re;Gn.SKIP=ea;Gn.REMOVE=ye;async function ut(t,e,n,s){let r=await na(t,e,n,s);if(J.isNode(r)||J.isPair(r))return sa(t,s,r),ut(t,r,n,s);if(typeof r!="symbol"){if(J.isCollection(e)){s=Object.freeze(s.concat(e));for(let i=0;i<e.items.length;++i){let o=await ut(i,e.items[i],n,s);if(typeof o=="number")i=o-1;else{if(o===re)return re;o===ye&&(e.items.splice(i,1),i-=1)}}}else if(J.isPair(e)){s=Object.freeze(s.concat(e));let i=await ut("key",e.key,n,s);if(i===re)return re;i===ye&&(e.key=null);let o=await ut("value",e.value,n,s);if(o===re)return re;o===ye&&(e.value=null)}}return r}function ta(t){return typeof t=="object"&&(t.Collection||t.Node||t.Value)?Object.assign({Alias:t.Node,Map:t.Node,Scalar:t.Node,Seq:t.Node},t.Value&&{Map:t.Value,Scalar:t.Value,Seq:t.Value},t.Collection&&{Map:t.Collection,Seq:t.Collection},t):t}function na(t,e,n,s){if(typeof n=="function")return n(t,e,s);if(J.isMap(e))return n.Map?.(t,e,s);if(J.isSeq(e))return n.Seq?.(t,e,s);if(J.isPair(e))return n.Pair?.(t,e,s);if(J.isScalar(e))return n.Scalar?.(t,e,s);if(J.isAlias(e))return n.Alias?.(t,e,s)}function sa(t,e,n){let s=e[e.length-1];if(J.isCollection(s))s.items[t]=n;else if(J.isPair(s))t==="key"?s.key=n:s.value=n;else if(J.isDocument(s))s.contents=n;else{let r=J.isAlias(s)?"alias":"scalar";throw new Error(`Cannot replace node with ${r} parent`)}}Sr.visit=Un;Sr.visitAsync=Gn});var vr=E(ia=>{"use strict";p();var ra=B(),od=Dt(),ad={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},cd=t=>t.replace(/[!,[\]{}]/g,e=>ad[e]),Bt=class t{constructor(e,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,n)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,n){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let s=e.trim().split(/[ \t]+/),r=s.shift();switch(r){case"%TAG":{if(s.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),s.length<2))return!1;let[i,o]=s;return this.tags[i]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,s.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[i]=s;if(i==="1.1"||i==="1.2")return this.yaml.version=i,!0;{let o=/^\d+\.\d+$/.test(i);return n(6,`Unsupported YAML version ${i}`,o),!1}}default:return n(0,`Unknown directive ${r}`,!0),!1}}tagName(e,n){if(e==="!")return"!";if(e[0]!=="!")return n(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(n(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&n("Verbatim tags must end with a >"),o)}let[,s,r]=e.match(/^(.*!)([^!]*)$/s);r||n(`The ${e} tag has no suffix`);let i=this.tags[s];if(i)try{return i+decodeURIComponent(r)}catch(o){return n(String(o)),null}return s==="!"?e:(n(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[n,s]of Object.entries(this.tags))if(e.startsWith(s))return n+cd(e.substring(s.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],s=Object.entries(this.tags),r;if(e&&s.length>0&&ra.isNode(e.contents)){let i={};od.visit(e.contents,(o,a)=>{ra.isNode(a)&&a.tag&&(i[a.tag]=!0)}),r=Object.keys(i)}else r=[];for(let[i,o]of s)i==="!!"&&o==="tag:yaml.org,2002:"||(!e||r.some(a=>a.startsWith(o)))&&n.push(`%TAG ${i} ${o}`);return n.join(`
|
|
4
|
+
`)}};Bt.defaultYaml={explicit:!1,version:"1.2"};Bt.defaultTags={"!!":"tag:yaml.org,2002:"};ia.Directives=Bt});var Fn=E(Ut=>{"use strict";p();var oa=B(),ld=Dt();function ud(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(n)}return!0}function aa(t){let e=new Set;return ld.visit(t,{Value(n,s){s.anchor&&e.add(s.anchor)}}),e}function ca(t,e){for(let n=1;;++n){let s=`${t}${n}`;if(!e.has(s))return s}}function fd(t,e){let n=[],s=new Map,r=null;return{onAnchor:i=>{n.push(i),r??(r=aa(t));let o=ca(e,r);return r.add(o),o},setAnchors:()=>{for(let i of n){let o=s.get(i);if(typeof o=="object"&&o.anchor&&(oa.isScalar(o.node)||oa.isCollection(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=i,a}}},sourceObjects:s}}Ut.anchorIsValid=ud;Ut.anchorNames=aa;Ut.createNodeAnchors=fd;Ut.findNewAnchor=ca});var Ar=E(la=>{"use strict";p();function Gt(t,e,n,s){if(s&&typeof s=="object")if(Array.isArray(s))for(let r=0,i=s.length;r<i;++r){let o=s[r],a=Gt(t,s,String(r),o);a===void 0?delete s[r]:a!==o&&(s[r]=a)}else if(s instanceof Map)for(let r of Array.from(s.keys())){let i=s.get(r),o=Gt(t,s,r,i);o===void 0?s.delete(r):o!==i&&s.set(r,o)}else if(s instanceof Set)for(let r of Array.from(s)){let i=Gt(t,s,r,r);i===void 0?s.delete(r):i!==r&&(s.delete(r),s.add(i))}else for(let[r,i]of Object.entries(s)){let o=Gt(t,s,r,i);o===void 0?delete s[r]:o!==i&&(s[r]=o)}return t.call(e,n,s)}la.applyReviver=Gt});var Pe=E(fa=>{"use strict";p();var dd=B();function ua(t,e,n){if(Array.isArray(t))return t.map((s,r)=>ua(s,String(r),n));if(t&&typeof t.toJSON=="function"){if(!n||!dd.hasAnchor(t))return t.toJSON(e,n);let s={aliasCount:0,count:1,res:void 0};n.anchors.set(t,s),n.onCreate=i=>{s.res=i,delete n.onCreate};let r=t.toJSON(e,n);return n.onCreate&&n.onCreate(r),r}return typeof t=="bigint"&&!n?.keep?Number(t):t}fa.toJS=ua});var Wn=E(pa=>{"use strict";p();var pd=Ar(),da=B(),hd=Pe(),Er=class{constructor(e){Object.defineProperty(this,da.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:n,maxAliasCount:s,onAnchor:r,reviver:i}={}){if(!da.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof s=="number"?s:100},a=hd.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:l}of o.anchors.values())r(l,c);return typeof i=="function"?pd.applyReviver(i,{"":a},"",a):a}};pa.NodeBase=Er});var Ft=E(ha=>{"use strict";p();var gd=Fn(),md=Dt(),ft=B(),yd=Wn(),wd=Pe(),_r=class extends yd.NodeBase{constructor(e){super(ft.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,n){let s;n?.aliasResolveCache?s=n.aliasResolveCache:(s=[],md.visit(e,{Node:(i,o)=>{(ft.isAlias(o)||ft.hasAnchor(o))&&s.push(o)}}),n&&(n.aliasResolveCache=s));let r;for(let i of s){if(i===this)break;i.anchor===this.source&&(r=i)}return r}toJSON(e,n){if(!n)return{source:this.source};let{anchors:s,doc:r,maxAliasCount:i}=n,o=this.resolve(r,n);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=s.get(o);if(a||(wd.toJS(o,null,n),a=s.get(o)),!a||a.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(i>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Yn(r,o,s)),a.count*a.aliasCount>i)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,n,s){let r=`*${this.source}`;if(e){if(gd.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(i)}if(e.implicitKey)return`${r} `}return r}};function Yn(t,e,n){if(ft.isAlias(e)){let s=e.resolve(t),r=n&&s&&n.get(s);return r?r.count*r.aliasCount:0}else if(ft.isCollection(e)){let s=0;for(let r of e.items){let i=Yn(t,r,n);i>s&&(s=i)}return s}else if(ft.isPair(e)){let s=Yn(t,e.key,n),r=Yn(t,e.value,n);return Math.max(s,r)}return 1}ha.Alias=_r});var Y=E(Cr=>{"use strict";p();var bd=B(),kd=Wn(),$d=Pe(),Sd=t=>!t||typeof t!="function"&&typeof t!="object",je=class extends kd.NodeBase{constructor(e){super(bd.SCALAR),this.value=e}toJSON(e,n){return n?.keep?this.value:$d.toJS(this.value,e,n)}toString(){return String(this.value)}};je.BLOCK_FOLDED="BLOCK_FOLDED";je.BLOCK_LITERAL="BLOCK_LITERAL";je.PLAIN="PLAIN";je.QUOTE_DOUBLE="QUOTE_DOUBLE";je.QUOTE_SINGLE="QUOTE_SINGLE";Cr.Scalar=je;Cr.isScalarValue=Sd});var Wt=E(ma=>{"use strict";p();var vd=Ft(),Qe=B(),ga=Y(),Ad="tag:yaml.org,2002:";function Ed(t,e,n){if(e){let s=n.filter(i=>i.tag===e),r=s.find(i=>!i.format)??s[0];if(!r)throw new Error(`Tag ${e} not found`);return r}return n.find(s=>s.identify?.(t)&&!s.format)}function _d(t,e,n){if(Qe.isDocument(t)&&(t=t.contents),Qe.isNode(t))return t;if(Qe.isPair(t)){let u=n.schema[Qe.MAP].createNode?.(n.schema,null,n);return u.items.push(t),u}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:s,onAnchor:r,onTagObj:i,schema:o,sourceObjects:a}=n,c;if(s&&t&&typeof t=="object"){if(c=a.get(t),c)return c.anchor??(c.anchor=r(t)),new vd.Alias(c.anchor);c={anchor:null,node:null},a.set(t,c)}e?.startsWith("!!")&&(e=Ad+e.slice(2));let l=Ed(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let u=new ga.Scalar(t);return c&&(c.node=u),u}l=t instanceof Map?o[Qe.MAP]:Symbol.iterator in Object(t)?o[Qe.SEQ]:o[Qe.MAP]}i&&(i(l),delete n.onTagObj);let h=l?.createNode?l.createNode(n.schema,t,n):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(n.schema,t,n):new ga.Scalar(t);return e?h.tag=e:l.default||(h.tag=l.tag),c&&(c.node=h),h}ma.createNode=_d});var Jn=E(Vn=>{"use strict";p();var Cd=Wt(),we=B(),Nd=Wn();function Nr(t,e,n){let s=n;for(let r=e.length-1;r>=0;--r){let i=e[r];if(typeof i=="number"&&Number.isInteger(i)&&i>=0){let o=[];o[i]=s,s=o}else s=new Map([[i,s]])}return Cd.createNode(s,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var ya=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,Tr=class extends Nd.NodeBase{constructor(e,n){super(e),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(e){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(n.schema=e),n.items=n.items.map(s=>we.isNode(s)||we.isPair(s)?s.clone(e):s),this.range&&(n.range=this.range.slice()),n}addIn(e,n){if(ya(e))this.add(n);else{let[s,...r]=e,i=this.get(s,!0);if(we.isCollection(i))i.addIn(r,n);else if(i===void 0&&this.schema)this.set(s,Nr(this.schema,r,n));else throw new Error(`Expected YAML collection at ${s}. Remaining path: ${r}`)}}deleteIn(e){let[n,...s]=e;if(s.length===0)return this.delete(n);let r=this.get(n,!0);if(we.isCollection(r))return r.deleteIn(s);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}getIn(e,n){let[s,...r]=e,i=this.get(s,!0);return r.length===0?!n&&we.isScalar(i)?i.value:i:we.isCollection(i)?i.getIn(r,n):void 0}hasAllNullValues(e){return this.items.every(n=>{if(!we.isPair(n))return!1;let s=n.value;return s==null||e&&we.isScalar(s)&&s.value==null&&!s.commentBefore&&!s.comment&&!s.tag})}hasIn(e){let[n,...s]=e;if(s.length===0)return this.has(n);let r=this.get(n,!0);return we.isCollection(r)?r.hasIn(s):!1}setIn(e,n){let[s,...r]=e;if(r.length===0)this.set(s,n);else{let i=this.get(s,!0);if(we.isCollection(i))i.setIn(r,n);else if(i===void 0&&this.schema)this.set(s,Nr(this.schema,r,n));else throw new Error(`Expected YAML collection at ${s}. Remaining path: ${r}`)}}};Vn.Collection=Tr;Vn.collectionFromPath=Nr;Vn.isEmptyPath=ya});var Yt=E(zn=>{"use strict";p();var Td=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function Or(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var Od=(t,e,n)=>t.endsWith(`
|
|
5
|
+
`)?Or(n,e):n.includes(`
|
|
6
6
|
`)?`
|
|
7
|
-
`+
|
|
8
|
-
`)
|
|
9
|
-
`&&
|
|
10
|
-
|
|
11
|
-
${e}${
|
|
12
|
-
${e}${
|
|
13
|
-
`);s=e,r=e+1,i=
|
|
14
|
-
`){if(i-o>s)return!0;if(o=i+1,r-o<=s)return!1}return!0}function
|
|
7
|
+
`+Or(n,e):(t.endsWith(" ")?"":" ")+n;zn.indentComment=Or;zn.lineComment=Od;zn.stringifyComment=Td});var ba=E(Vt=>{"use strict";p();var Id="flow",Ir="block",Hn="quoted";function Pd(t,e,n="flow",{indentAtStart:s,lineWidth:r=80,minContentWidth:i=20,onFold:o,onOverflow:a}={}){if(!r||r<0)return t;r<i&&(i=0);let c=Math.max(1+i,1+r-e.length);if(t.length<=c)return t;let l=[],h={},u=r-e.length;typeof s=="number"&&(s>r-Math.max(2,i)?l.push(0):u=r-s);let f,d,m=!1,g=-1,y=-1,S=-1;n===Ir&&(g=wa(t,g,e.length),g!==-1&&(u=g+c));for(let O;O=t[g+=1];){if(n===Hn&&O==="\\"){switch(y=g,t[g+1]){case"x":g+=3;break;case"u":g+=5;break;case"U":g+=9;break;default:g+=1}S=g}if(O===`
|
|
8
|
+
`)n===Ir&&(g=wa(t,g,e.length)),u=g+e.length+c,f=void 0;else{if(O===" "&&d&&d!==" "&&d!==`
|
|
9
|
+
`&&d!==" "){let $=t[g+1];$&&$!==" "&&$!==`
|
|
10
|
+
`&&$!==" "&&(f=g)}if(g>=u)if(f)l.push(f),u=f+c,f=void 0;else if(n===Hn){for(;d===" "||d===" ";)d=O,O=t[g+=1],m=!0;let $=g>S+1?g-2:y-1;if(h[$])return t;l.push($),h[$]=!0,u=$+c,f=void 0}else m=!0}d=O}if(m&&a&&a(),l.length===0)return t;o&&o();let C=t.slice(0,l[0]);for(let O=0;O<l.length;++O){let $=l[O],T=l[O+1]||t.length;$===0?C=`
|
|
11
|
+
${e}${t.slice(0,T)}`:(n===Hn&&h[$]&&(C+=`${t[$]}\\`),C+=`
|
|
12
|
+
${e}${t.slice($+1,T)}`)}return C}function wa(t,e,n){let s=e,r=e+1,i=t[r];for(;i===" "||i===" ";)if(e<r+n)i=t[++e];else{do i=t[++e];while(i&&i!==`
|
|
13
|
+
`);s=e,r=e+1,i=t[r]}return s}Vt.FOLD_BLOCK=Ir;Vt.FOLD_FLOW=Id;Vt.FOLD_QUOTED=Hn;Vt.foldFlowLines=Pd});var zt=E(ka=>{"use strict";p();var fe=Y(),Re=ba(),Zn=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),Xn=t=>/^(%|---|\.\.\.)/m.test(t);function jd(t,e,n){if(!e||e<0)return!1;let s=e-n,r=t.length;if(r<=s)return!1;for(let i=0,o=0;i<r;++i)if(t[i]===`
|
|
14
|
+
`){if(i-o>s)return!0;if(o=i+1,r-o<=s)return!1}return!0}function Jt(t,e){let n=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return n;let{implicitKey:s}=e,r=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(Xn(t)?" ":""),o="",a=0;for(let c=0,l=n[c];l;l=n[++c])if(l===" "&&n[c+1]==="\\"&&n[c+2]==="n"&&(o+=n.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(n[c+1]){case"u":{o+=n.slice(a,c);let h=n.substr(c+2,4);switch(h){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:h.substr(0,2)==="00"?o+="\\x"+h.substr(2):o+=n.substr(c,6)}c+=5,a=c+1}break;case"n":if(s||n[c+2]==='"'||n.length<r)c+=1;else{for(o+=n.slice(a,c)+`
|
|
15
15
|
|
|
16
|
-
`;
|
|
17
|
-
`,c+=2;o+=i,
|
|
18
|
-
`)||/[ \t]\n|\n[ \t]/.test(
|
|
19
|
-
${
|
|
16
|
+
`;n[c+2]==="\\"&&n[c+3]==="n"&&n[c+4]!=='"';)o+=`
|
|
17
|
+
`,c+=2;o+=i,n[c+2]===" "&&(o+="\\"),c+=1,a=c+1}break;default:c+=1}return o=a?o+n.slice(a):n,s?o:Re.foldFlowLines(o,i,Re.FOLD_QUOTED,Zn(e,!1))}function Pr(t,e){if(e.options.singleQuote===!1||e.implicitKey&&t.includes(`
|
|
18
|
+
`)||/[ \t]\n|\n[ \t]/.test(t))return Jt(t,e);let n=e.indent||(Xn(t)?" ":""),s="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
19
|
+
${n}`)+"'";return e.implicitKey?s:Re.foldFlowLines(s,n,Re.FOLD_FLOW,Zn(e,!1))}function dt(t,e){let{singleQuote:n}=e.options,s;if(n===!1)s=Jt;else{let r=t.includes('"'),i=t.includes("'");r&&!i?s=Pr:i&&!r?s=Jt:s=n?Pr:Jt}return s(t,e)}var jr;try{jr=new RegExp(`(^|(?<!
|
|
20
20
|
))
|
|
21
21
|
+(?!
|
|
22
|
-
|$)`,"g")}catch{
|
|
22
|
+
|$)`,"g")}catch{jr=/\n+(?!\n|$)/g}function Qn({comment:t,type:e,value:n},s,r,i){let{blockQuote:o,commentString:a,lineWidth:c}=s.options;if(!o||/\n[\t ]+$/.test(n))return dt(n,s);let l=s.indent||(s.forceBlockIndent||Xn(n)?" ":""),h=o==="literal"?!0:o==="folded"||e===fe.Scalar.BLOCK_FOLDED?!1:e===fe.Scalar.BLOCK_LITERAL?!0:!jd(n,c,l.length);if(!n)return h?`|
|
|
23
23
|
`:`>
|
|
24
|
-
`;let u,f;for(f=
|
|
25
|
-
`&&
|
|
26
|
-
`);
|
|
27
|
-
`&&(
|
|
28
|
-
`)
|
|
29
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),
|
|
30
|
-
${l}${
|
|
31
|
-
${l}${
|
|
32
|
-
`)||
|
|
33
|
-
`)?
|
|
34
|
-
`))return
|
|
35
|
-
${c}`);if(o){let f=
|
|
36
|
-
${e.indent}${a}`:a}
|
|
37
|
-
${a}:`):(
|
|
38
|
-
`:""
|
|
39
|
-
${
|
|
40
|
-
`&&(
|
|
24
|
+
`;let u,f;for(f=n.length;f>0;--f){let T=n[f-1];if(T!==`
|
|
25
|
+
`&&T!==" "&&T!==" ")break}let d=n.substring(f),m=d.indexOf(`
|
|
26
|
+
`);m===-1?u="-":n===d||m!==d.length-1?(u="+",i&&i()):u="",d&&(n=n.slice(0,-d.length),d[d.length-1]===`
|
|
27
|
+
`&&(d=d.slice(0,-1)),d=d.replace(jr,`$&${l}`));let g=!1,y,S=-1;for(y=0;y<n.length;++y){let T=n[y];if(T===" ")g=!0;else if(T===`
|
|
28
|
+
`)S=y;else break}let C=n.substring(0,S<y?S+1:y);C&&(n=n.substring(C.length),C=C.replace(/\n+/g,`$&${l}`));let $=(g?l?"2":"1":"")+u;if(t&&($+=" "+a(t.replace(/ ?[\r\n]+/g," ")),r&&r()),!h){let T=n.replace(/\n+/g,`
|
|
29
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),j=!1,b=Zn(s,!0);o!=="folded"&&e!==fe.Scalar.BLOCK_FOLDED&&(b.onOverflow=()=>{j=!0});let v=Re.foldFlowLines(`${C}${T}${d}`,l,Re.FOLD_BLOCK,b);if(!j)return`>${$}
|
|
30
|
+
${l}${v}`}return n=n.replace(/\n+/g,`$&${l}`),`|${$}
|
|
31
|
+
${l}${C}${n}${d}`}function Rd(t,e,n,s){let{type:r,value:i}=t,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:h}=e;if(a&&i.includes(`
|
|
32
|
+
`)||h&&/[[\]{},]/.test(i))return dt(i,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||h||!i.includes(`
|
|
33
|
+
`)?dt(i,e):Qn(t,e,n,s);if(!a&&!h&&r!==fe.Scalar.PLAIN&&i.includes(`
|
|
34
|
+
`))return Qn(t,e,n,s);if(Xn(i)){if(c==="")return e.forceBlockIndent=!0,Qn(t,e,n,s);if(a&&c===l)return dt(i,e)}let u=i.replace(/\n+/g,`$&
|
|
35
|
+
${c}`);if(o){let f=g=>g.default&&g.tag!=="tag:yaml.org,2002:str"&&g.test?.test(u),{compat:d,tags:m}=e.doc.schema;if(m.some(f)||d?.some(f))return dt(i,e)}return a?u:Re.foldFlowLines(u,c,Re.FOLD_FLOW,Zn(e,!1))}function Ld(t,e,n,s){let{implicitKey:r,inFlow:i}=e,o=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:a}=t;a!==fe.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=fe.Scalar.QUOTE_DOUBLE);let c=h=>{switch(h){case fe.Scalar.BLOCK_FOLDED:case fe.Scalar.BLOCK_LITERAL:return r||i?dt(o.value,e):Qn(o,e,n,s);case fe.Scalar.QUOTE_DOUBLE:return Jt(o.value,e);case fe.Scalar.QUOTE_SINGLE:return Pr(o.value,e);case fe.Scalar.PLAIN:return Rd(o,e,n,s);default:return null}},l=c(a);if(l===null){let{defaultKeyType:h,defaultStringType:u}=e.options,f=r&&h||u;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}ka.stringifyString=Ld});var Ht=E(Rr=>{"use strict";p();var xd=Fn(),Le=B(),qd=Yt(),Md=zt();function Kd(t,e){let n=Object.assign({blockQuote:!0,commentString:qd.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trueStr:"true",verifyAliasOrder:!0},t.schema.toStringOptions,e),s;switch(n.collectionStyle){case"block":s=!1;break;case"flow":s=!0;break;default:s=null}return{anchors:new Set,doc:t,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:s,options:n}}function Dd(t,e){if(e.tag){let r=t.filter(i=>i.tag===e.tag);if(r.length>0)return r.find(i=>i.format===e.format)??r[0]}let n,s;if(Le.isScalar(e)){s=e.value;let r=t.filter(i=>i.identify?.(s));if(r.length>1){let i=r.filter(o=>o.test);i.length>0&&(r=i)}n=r.find(i=>i.format===e.format)??r.find(i=>!i.format)}else s=e,n=t.find(r=>r.nodeClass&&s instanceof r.nodeClass);if(!n){let r=s?.constructor?.name??(s===null?"null":typeof s);throw new Error(`Tag not resolved for ${r} value`)}return n}function Bd(t,e,{anchors:n,doc:s}){if(!s.directives)return"";let r=[],i=(Le.isScalar(t)||Le.isCollection(t))&&t.anchor;i&&xd.anchorIsValid(i)&&(n.add(i),r.push(`&${i}`));let o=t.tag??(e.default?null:e.tag);return o&&r.push(s.directives.tagString(o)),r.join(" ")}function Ud(t,e,n,s){if(Le.isPair(t))return t.toString(e,n,s);if(Le.isAlias(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let r,i=Le.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>r=c});r??(r=Dd(e.doc.schema.tags,i));let o=Bd(i,r,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let a=typeof r.stringify=="function"?r.stringify(i,e,n,s):Le.isScalar(i)?Md.stringifyString(i,e,n,s):i.toString(e,n,s);return o?Le.isScalar(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
|
|
36
|
+
${e.indent}${a}`:a}Rr.createStringifyContext=Kd;Rr.stringify=Ud});var Aa=E(va=>{"use strict";p();var Ae=B(),$a=Y(),Sa=Ht(),Qt=Yt();function Gd({key:t,value:e},n,s,r){let{allNullValues:i,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:h,simpleKeys:u}}=n,f=Ae.isNode(t)&&t.comment||null;if(u){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(Ae.isCollection(t)||!Ae.isNode(t)&&typeof t=="object"){let b="With simple keys, collection cannot be used as a key value";throw new Error(b)}}let d=!u&&(!t||f&&e==null&&!n.inFlow||Ae.isCollection(t)||(Ae.isScalar(t)?t.type===$a.Scalar.BLOCK_FOLDED||t.type===$a.Scalar.BLOCK_LITERAL:typeof t=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!d&&(u||!i),indent:a+c});let m=!1,g=!1,y=Sa.stringify(t,n,()=>m=!0,()=>g=!0);if(!d&&!n.inFlow&&y.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");d=!0}if(n.inFlow){if(i||e==null)return m&&s&&s(),y===""?"?":d?`? ${y}`:y}else if(i&&!u||e==null&&d)return y=`? ${y}`,f&&!m?y+=Qt.lineComment(y,n.indent,l(f)):g&&r&&r(),y;m&&(f=null),d?(f&&(y+=Qt.lineComment(y,n.indent,l(f))),y=`? ${y}
|
|
37
|
+
${a}:`):(y=`${y}:`,f&&(y+=Qt.lineComment(y,n.indent,l(f))));let S,C,O;Ae.isNode(e)?(S=!!e.spaceBefore,C=e.commentBefore,O=e.comment):(S=!1,C=null,O=null,e&&typeof e=="object"&&(e=o.createNode(e))),n.implicitKey=!1,!d&&!f&&Ae.isScalar(e)&&(n.indentAtStart=y.length+1),g=!1,!h&&c.length>=2&&!n.inFlow&&!d&&Ae.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(n.indent=n.indent.substring(2));let $=!1,T=Sa.stringify(e,n,()=>$=!0,()=>g=!0),j=" ";if(f||S||C){if(j=S?`
|
|
38
|
+
`:"",C){let b=l(C);j+=`
|
|
39
|
+
${Qt.indentComment(b,n.indent)}`}T===""&&!n.inFlow?j===`
|
|
40
|
+
`&&(j=`
|
|
41
41
|
|
|
42
|
-
`):
|
|
43
|
-
${
|
|
44
|
-
`),
|
|
45
|
-
${
|
|
46
|
-
`)&&(
|
|
47
|
-
${c}${
|
|
48
|
-
`}}return
|
|
49
|
-
`+
|
|
50
|
-
`))&&(l=!0),u.push(
|
|
51
|
-
${i}${r}${
|
|
52
|
-
`;return`${
|
|
53
|
-
${r}${
|
|
54
|
-
`:" ")}return
|
|
42
|
+
`):j+=`
|
|
43
|
+
${n.indent}`}else if(!d&&Ae.isCollection(e)){let b=T[0],v=T.indexOf(`
|
|
44
|
+
`),K=v!==-1,I=n.inFlow??e.flow??e.items.length===0;if(K||!I){let R=!1;if(K&&(b==="&"||b==="!")){let q=T.indexOf(" ");b==="&"&&q!==-1&&q<v&&T[q+1]==="!"&&(q=T.indexOf(" ",q+1)),(q===-1||v<q)&&(R=!0)}R||(j=`
|
|
45
|
+
${n.indent}`)}}else(T===""||T[0]===`
|
|
46
|
+
`)&&(j="");return y+=j+T,n.inFlow?$&&s&&s():O&&!$?y+=Qt.lineComment(y,n.indent,l(O)):g&&r&&r(),y}va.stringifyPair=Gd});var xr=E(Lr=>{"use strict";p();var Ea=jn("process");function Fd(t,...e){t==="debug"&&console.log(...e)}function Wd(t,e){(t==="debug"||t==="warn")&&(typeof Ea.emitWarning=="function"?Ea.emitWarning(e):console.warn(e))}Lr.debug=Fd;Lr.warn=Wd});var ss=E(ns=>{"use strict";p();var Zt=B(),_a=Y(),es="<<",ts={identify:t=>t===es||typeof t=="symbol"&&t.description===es,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new _a.Scalar(Symbol(es)),{addToJSMap:Ca}),stringify:()=>es},Yd=(t,e)=>(ts.identify(e)||Zt.isScalar(e)&&(!e.type||e.type===_a.Scalar.PLAIN)&&ts.identify(e.value))&&t?.doc.schema.tags.some(n=>n.tag===ts.tag&&n.default);function Ca(t,e,n){if(n=t&&Zt.isAlias(n)?n.resolve(t.doc):n,Zt.isSeq(n))for(let s of n.items)qr(t,e,s);else if(Array.isArray(n))for(let s of n)qr(t,e,s);else qr(t,e,n)}function qr(t,e,n){let s=t&&Zt.isAlias(n)?n.resolve(t.doc):n;if(!Zt.isMap(s))throw new Error("Merge sources must be maps or map aliases");let r=s.toJSON(null,t,Map);for(let[i,o]of r)e instanceof Map?e.has(i)||e.set(i,o):e instanceof Set?e.add(i):Object.prototype.hasOwnProperty.call(e,i)||Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}ns.addMergeToJSMap=Ca;ns.isMergeKey=Yd;ns.merge=ts});var Kr=E(Oa=>{"use strict";p();var Vd=xr(),Na=ss(),Jd=Ht(),Ta=B(),Mr=Pe();function zd(t,e,{key:n,value:s}){if(Ta.isNode(n)&&n.addToJSMap)n.addToJSMap(t,e,s);else if(Na.isMergeKey(t,n))Na.addMergeToJSMap(t,e,s);else{let r=Mr.toJS(n,"",t);if(e instanceof Map)e.set(r,Mr.toJS(s,r,t));else if(e instanceof Set)e.add(r);else{let i=Hd(n,r,t),o=Mr.toJS(s,i,t);i in e?Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[i]=o}}return e}function Hd(t,e,n){if(e===null)return"";if(typeof e!="object")return String(e);if(Ta.isNode(t)&&n?.doc){let s=Jd.createStringifyContext(n.doc,{});s.anchors=new Set;for(let i of n.anchors.keys())s.anchors.add(i.anchor);s.inFlow=!0,s.inStringifyKey=!0;let r=t.toString(s);if(!n.mapKeyWarned){let i=JSON.stringify(r);i.length>40&&(i=i.substring(0,36)+'..."'),Vd.warn(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${i}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(e)}Oa.addPairToJSMap=zd});var xe=E(Dr=>{"use strict";p();var Ia=Wt(),Qd=Aa(),Zd=Kr(),rs=B();function Xd(t,e,n){let s=Ia.createNode(t,void 0,n),r=Ia.createNode(e,void 0,n);return new is(s,r)}var is=class t{constructor(e,n=null){Object.defineProperty(this,rs.NODE_TYPE,{value:rs.PAIR}),this.key=e,this.value=n}clone(e){let{key:n,value:s}=this;return rs.isNode(n)&&(n=n.clone(e)),rs.isNode(s)&&(s=s.clone(e)),new t(n,s)}toJSON(e,n){let s=n?.mapAsMap?new Map:{};return Zd.addPairToJSMap(n,s,this)}toString(e,n,s){return e?.doc?Qd.stringifyPair(this,e,n,s):JSON.stringify(this)}};Dr.Pair=is;Dr.createPair=Xd});var Br=E(ja=>{"use strict";p();var Ze=B(),Pa=Ht(),os=Yt();function ep(t,e,n){return(e.inFlow??t.flow?np:tp)(t,e,n)}function tp({comment:t,items:e},n,{blockItemPrefix:s,flowChars:r,itemIndent:i,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=n,h=Object.assign({},n,{indent:i,type:null}),u=!1,f=[];for(let m=0;m<e.length;++m){let g=e[m],y=null;if(Ze.isNode(g))!u&&g.spaceBefore&&f.push(""),as(n,f,g.commentBefore,u),g.comment&&(y=g.comment);else if(Ze.isPair(g)){let C=Ze.isNode(g.key)?g.key:null;C&&(!u&&C.spaceBefore&&f.push(""),as(n,f,C.commentBefore,u))}u=!1;let S=Pa.stringify(g,h,()=>y=null,()=>u=!0);y&&(S+=os.lineComment(S,i,l(y))),u&&y&&(u=!1),f.push(s+S)}let d;if(f.length===0)d=r.start+r.end;else{d=f[0];for(let m=1;m<f.length;++m){let g=f[m];d+=g?`
|
|
47
|
+
${c}${g}`:`
|
|
48
|
+
`}}return t?(d+=`
|
|
49
|
+
`+os.indentComment(l(t),c),a&&a()):u&&o&&o(),d}function np({items:t},e,{flowChars:n,itemIndent:s}){let{indent:r,indentStep:i,flowCollectionPadding:o,options:{commentString:a}}=e;s+=i;let c=Object.assign({},e,{indent:s,inFlow:!0,type:null}),l=!1,h=0,u=[];for(let m=0;m<t.length;++m){let g=t[m],y=null;if(Ze.isNode(g))g.spaceBefore&&u.push(""),as(e,u,g.commentBefore,!1),g.comment&&(y=g.comment);else if(Ze.isPair(g)){let C=Ze.isNode(g.key)?g.key:null;C&&(C.spaceBefore&&u.push(""),as(e,u,C.commentBefore,!1),C.comment&&(l=!0));let O=Ze.isNode(g.value)?g.value:null;O?(O.comment&&(y=O.comment),O.commentBefore&&(l=!0)):g.value==null&&C?.comment&&(y=C.comment)}y&&(l=!0);let S=Pa.stringify(g,c,()=>y=null);m<t.length-1&&(S+=","),y&&(S+=os.lineComment(S,s,a(y))),!l&&(u.length>h||S.includes(`
|
|
50
|
+
`))&&(l=!0),u.push(S),h=u.length}let{start:f,end:d}=n;if(u.length===0)return f+d;if(!l){let m=u.reduce((g,y)=>g+y.length+2,2);l=e.options.lineWidth>0&&m>e.options.lineWidth}if(l){let m=f;for(let g of u)m+=g?`
|
|
51
|
+
${i}${r}${g}`:`
|
|
52
|
+
`;return`${m}
|
|
53
|
+
${r}${d}`}else return`${f}${o}${u.join(" ")}${o}${d}`}function as({indent:t,options:{commentString:e}},n,s,r){if(s&&r&&(s=s.replace(/^\n+/,"")),s){let i=os.indentComment(e(s),t);n.push(i.trimStart())}}ja.stringifyCollection=ep});var Me=E(Gr=>{"use strict";p();var sp=Br(),rp=Kr(),ip=Jn(),qe=B(),cs=xe(),op=Y();function Xt(t,e){let n=qe.isScalar(e)?e.value:e;for(let s of t)if(qe.isPair(s)&&(s.key===e||s.key===n||qe.isScalar(s.key)&&s.key.value===n))return s}var Ur=class extends ip.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(qe.MAP,e),this.items=[]}static from(e,n,s){let{keepUndefined:r,replacer:i}=s,o=new this(e),a=(c,l)=>{if(typeof i=="function")l=i.call(n,c,l);else if(Array.isArray(i)&&!i.includes(c))return;(l!==void 0||r)&&o.items.push(cs.createPair(c,l,s))};if(n instanceof Map)for(let[c,l]of n)a(c,l);else if(n&&typeof n=="object")for(let c of Object.keys(n))a(c,n[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,n){let s;qe.isPair(e)?s=e:!e||typeof e!="object"||!("key"in e)?s=new cs.Pair(e,e?.value):s=new cs.Pair(e.key,e.value);let r=Xt(this.items,s.key),i=this.schema?.sortMapEntries;if(r){if(!n)throw new Error(`Key ${s.key} already set`);qe.isScalar(r.value)&&op.isScalarValue(s.value)?r.value.value=s.value:r.value=s.value}else if(i){let o=this.items.findIndex(a=>i(s,a)<0);o===-1?this.items.push(s):this.items.splice(o,0,s)}else this.items.push(s)}delete(e){let n=Xt(this.items,e);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(e,n){let r=Xt(this.items,e)?.value;return(!n&&qe.isScalar(r)?r.value:r)??void 0}has(e){return!!Xt(this.items,e)}set(e,n){this.add(new cs.Pair(e,n),!0)}toJSON(e,n,s){let r=s?new s:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(r);for(let i of this.items)rp.addPairToJSMap(n,r,i);return r}toString(e,n,s){if(!e)return JSON.stringify(this);for(let r of this.items)if(!qe.isPair(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),sp.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:s,onComment:n})}};Gr.YAMLMap=Ur;Gr.findPair=Xt});var pt=E(La=>{"use strict";p();var ap=B(),Ra=Me(),cp={collection:"map",default:!0,nodeClass:Ra.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return ap.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,n)=>Ra.YAMLMap.from(t,e,n)};La.map=cp});var Ke=E(xa=>{"use strict";p();var lp=Wt(),up=Br(),fp=Jn(),us=B(),dp=Y(),pp=Pe(),Fr=class extends fp.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(us.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let n=ls(e);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(e,n){let s=ls(e);if(typeof s!="number")return;let r=this.items[s];return!n&&us.isScalar(r)?r.value:r}has(e){let n=ls(e);return typeof n=="number"&&n<this.items.length}set(e,n){let s=ls(e);if(typeof s!="number")throw new Error(`Expected a valid index, not ${e}.`);let r=this.items[s];us.isScalar(r)&&dp.isScalarValue(n)?r.value=n:this.items[s]=n}toJSON(e,n){let s=[];n?.onCreate&&n.onCreate(s);let r=0;for(let i of this.items)s.push(pp.toJS(i,String(r++),n));return s}toString(e,n,s){return e?up.stringifyCollection(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:s,onComment:n}):JSON.stringify(this)}static from(e,n,s){let{replacer:r}=s,i=new this(e);if(n&&Symbol.iterator in Object(n)){let o=0;for(let a of n){if(typeof r=="function"){let c=n instanceof Set?a:String(o++);a=r.call(n,c,a)}i.items.push(lp.createNode(a,void 0,s))}}return i}};function ls(t){let e=us.isScalar(t)?t.value:t;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}xa.YAMLSeq=Fr});var ht=E(Ma=>{"use strict";p();var hp=B(),qa=Ke(),gp={collection:"seq",default:!0,nodeClass:qa.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return hp.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,n)=>qa.YAMLSeq.from(t,e,n)};Ma.seq=gp});var en=E(Ka=>{"use strict";p();var mp=zt(),yp={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,n,s){return e=Object.assign({actualString:!0},e),mp.stringifyString(t,e,n,s)}};Ka.string=yp});var fs=E(Ua=>{"use strict";p();var Da=Y(),Ba={identify:t=>t==null,createNode:()=>new Da.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Da.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&Ba.test.test(t)?t:e.options.nullStr};Ua.nullTag=Ba});var Wr=E(Fa=>{"use strict";p();var wp=Y(),Ga={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new wp.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},n){if(t&&Ga.test.test(t)){let s=t[0]==="t"||t[0]==="T";if(e===s)return t}return e?n.options.trueStr:n.options.falseStr}};Fa.boolTag=Ga});var gt=E(Wa=>{"use strict";p();function bp({format:t,minFractionDigits:e,tag:n,value:s}){if(typeof s=="bigint")return String(s);let r=typeof s=="number"?s:Number(s);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let i=JSON.stringify(s);if(!t&&e&&(!n||n==="tag:yaml.org,2002:float")&&/^\d/.test(i)){let o=i.indexOf(".");o<0&&(o=i.length,i+=".");let a=e-(i.length-o-1);for(;a-- >0;)i+="0"}return i}Wa.stringifyNumber=bp});var Vr=E(ds=>{"use strict";p();var kp=Y(),Yr=gt(),$p={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Yr.stringifyNumber},Sp={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():Yr.stringifyNumber(t)}},vp={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new kp.Scalar(parseFloat(t)),n=t.indexOf(".");return n!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-n-1),e},stringify:Yr.stringifyNumber};ds.float=vp;ds.floatExp=Sp;ds.floatNaN=$p});var zr=E(hs=>{"use strict";p();var Ya=gt(),ps=t=>typeof t=="bigint"||Number.isInteger(t),Jr=(t,e,n,{intAsBigInt:s})=>s?BigInt(t):parseInt(t.substring(e),n);function Va(t,e,n){let{value:s}=t;return ps(s)&&s>=0?n+s.toString(e):Ya.stringifyNumber(t)}var Ap={identify:t=>ps(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,n)=>Jr(t,2,8,n),stringify:t=>Va(t,8,"0o")},Ep={identify:ps,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,n)=>Jr(t,0,10,n),stringify:Ya.stringifyNumber},_p={identify:t=>ps(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,n)=>Jr(t,2,16,n),stringify:t=>Va(t,16,"0x")};hs.int=Ep;hs.intHex=_p;hs.intOct=Ap});var za=E(Ja=>{"use strict";p();var Cp=pt(),Np=fs(),Tp=ht(),Op=en(),Ip=Wr(),Hr=Vr(),Qr=zr(),Pp=[Cp.map,Tp.seq,Op.string,Np.nullTag,Ip.boolTag,Qr.intOct,Qr.int,Qr.intHex,Hr.floatNaN,Hr.floatExp,Hr.float];Ja.schema=Pp});var Za=E(Qa=>{"use strict";p();var jp=Y(),Rp=pt(),Lp=ht();function Ha(t){return typeof t=="bigint"||Number.isInteger(t)}var gs=({value:t})=>JSON.stringify(t),xp=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:gs},{identify:t=>t==null,createNode:()=>new jp.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:gs},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:gs},{identify:Ha,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:n})=>n?BigInt(t):parseInt(t,10),stringify:({value:t})=>Ha(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:gs}],qp={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},Mp=[Rp.map,Lp.seq].concat(xp,qp);Qa.schema=Mp});var Xr=E(Xa=>{"use strict";p();var tn=jn("buffer"),Zr=Y(),Kp=zt(),Dp={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof tn.Buffer=="function")return tn.Buffer.from(t,"base64");if(typeof atob=="function"){let n=atob(t.replace(/[\n\r]/g,"")),s=new Uint8Array(n.length);for(let r=0;r<n.length;++r)s[r]=n.charCodeAt(r);return s}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),t},stringify({comment:t,type:e,value:n},s,r,i){if(!n)return"";let o=n,a;if(typeof tn.Buffer=="function")a=o instanceof tn.Buffer?o.toString("base64"):tn.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[l]);a=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=Zr.Scalar.BLOCK_LITERAL),e!==Zr.Scalar.QUOTE_DOUBLE){let c=Math.max(s.options.lineWidth-s.indent.length,s.options.minContentWidth),l=Math.ceil(a.length/c),h=new Array(l);for(let u=0,f=0;u<l;++u,f+=c)h[u]=a.substr(f,c);a=h.join(e===Zr.Scalar.BLOCK_LITERAL?`
|
|
54
|
+
`:" ")}return Kp.stringifyString({comment:t,type:e,value:a},s,r,i)}};Xa.binary=Dp});var ws=E(ys=>{"use strict";p();var ms=B(),ei=xe(),Bp=Y(),Up=Ke();function ec(t,e){if(ms.isSeq(t))for(let n=0;n<t.items.length;++n){let s=t.items[n];if(!ms.isPair(s)){if(ms.isMap(s)){s.items.length>1&&e("Each pair must have its own sequence indicator");let r=s.items[0]||new ei.Pair(new Bp.Scalar(null));if(s.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${s.commentBefore}
|
|
55
55
|
${r.key.commentBefore}`:s.commentBefore),s.comment){let i=r.value??r.key;i.comment=i.comment?`${s.comment}
|
|
56
|
-
${i.comment}`:s.comment}s=r}n.items[t]=ss.isPair(s)?s:new Gr.Pair(s)}}else e("Expected a sequence for this tag");return n}function Oa(n,e,t){let{replacer:s}=t,r=new Dd.YAMLSeq(n);r.tag="tag:yaml.org,2002:pairs";let i=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof s=="function"&&(o=s.call(e,String(i++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;r.items.push(Gr.createPair(a,c,t))}return r}var Kd={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Ta,createNode:Oa};rs.createPairs=Oa;rs.pairs=Kd;rs.resolvePairs=Ta});var Yr=S(Fr=>{"use strict";p();var Pa=x(),Ur=_e(),zt=Le(),Bd=qe(),ja=is(),Je=class n extends Bd.YAMLSeq{constructor(){super(),this.add=zt.YAMLMap.prototype.add.bind(this),this.delete=zt.YAMLMap.prototype.delete.bind(this),this.get=zt.YAMLMap.prototype.get.bind(this),this.has=zt.YAMLMap.prototype.has.bind(this),this.set=zt.YAMLMap.prototype.set.bind(this),this.tag=n.tag}toJSON(e,t){if(!t)return super.toJSON(e);let s=new Map;t?.onCreate&&t.onCreate(s);for(let r of this.items){let i,o;if(Pa.isPair(r)?(i=Ur.toJS(r.key,"",t),o=Ur.toJS(r.value,i,t)):i=Ur.toJS(r,"",t),s.has(i))throw new Error("Ordered maps must not include duplicate keys");s.set(i,o)}return s}static from(e,t,s){let r=ja.createPairs(e,t,s),i=new this;return i.items=r.items,i}};Je.tag="tag:yaml.org,2002:omap";var Gd={collection:"seq",identify:n=>n instanceof Map,nodeClass:Je,default:!1,tag:"tag:yaml.org,2002:omap",resolve(n,e){let t=ja.resolvePairs(n,e),s=[];for(let{key:r}of t.items)Pa.isScalar(r)&&(s.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):s.push(r.value));return Object.assign(new Je,t)},createNode:(n,e,t)=>Je.from(n,e,t)};Fr.YAMLOMap=Je;Fr.omap=Gd});var Ma=S(Vr=>{"use strict";p();var La=Y();function qa({value:n,source:e},t){return e&&(n?Ra:xa).test.test(e)?e:n?t.options.trueStr:t.options.falseStr}var Ra={identify:n=>n===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new La.Scalar(!0),stringify:qa},xa={identify:n=>n===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new La.Scalar(!1),stringify:qa};Vr.falseTag=xa;Vr.trueTag=Ra});var Da=S(os=>{"use strict";p();var Ud=Y(),Jr=ft(),Fd={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:n=>n.slice(-3).toLowerCase()==="nan"?NaN:n[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Jr.stringifyNumber},Yd={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:n=>parseFloat(n.replace(/_/g,"")),stringify(n){let e=Number(n.value);return isFinite(e)?e.toExponential():Jr.stringifyNumber(n)}},Vd={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(n){let e=new Ud.Scalar(parseFloat(n.replace(/_/g,""))),t=n.indexOf(".");if(t!==-1){let s=n.substring(t+1).replace(/_/g,"");s[s.length-1]==="0"&&(e.minFractionDigits=s.length)}return e},stringify:Jr.stringifyNumber};os.float=Vd;os.floatExp=Yd;os.floatNaN=Fd});var Ba=S(Qt=>{"use strict";p();var Ka=ft(),Ht=n=>typeof n=="bigint"||Number.isInteger(n);function as(n,e,t,{intAsBigInt:s}){let r=n[0];if((r==="-"||r==="+")&&(e+=1),n=n.substring(e).replace(/_/g,""),s){switch(t){case 2:n=`0b${n}`;break;case 8:n=`0o${n}`;break;case 16:n=`0x${n}`;break}let o=BigInt(n);return r==="-"?BigInt(-1)*o:o}let i=parseInt(n,t);return r==="-"?-1*i:i}function Wr(n,e,t){let{value:s}=n;if(Ht(s)){let r=s.toString(e);return s<0?"-"+t+r.substr(1):t+r}return Ka.stringifyNumber(n)}var Jd={identify:Ht,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(n,e,t)=>as(n,2,2,t),stringify:n=>Wr(n,2,"0b")},Wd={identify:Ht,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(n,e,t)=>as(n,1,8,t),stringify:n=>Wr(n,8,"0")},zd={identify:Ht,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(n,e,t)=>as(n,0,10,t),stringify:Ka.stringifyNumber},Hd={identify:Ht,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(n,e,t)=>as(n,2,16,t),stringify:n=>Wr(n,16,"0x")};Qt.int=zd;Qt.intBin=Jd;Qt.intHex=Hd;Qt.intOct=Wd});var Hr=S(zr=>{"use strict";p();var us=x(),cs=Pe(),ls=Le(),We=class n extends ls.YAMLMap{constructor(e){super(e),this.tag=n.tag}add(e){let t;us.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new cs.Pair(e.key,null):t=new cs.Pair(e,null),ls.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let s=ls.findPair(this.items,e);return!t&&us.isPair(s)?us.isScalar(s.key)?s.key.value:s.key:s}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let s=ls.findPair(this.items,e);s&&!t?this.items.splice(this.items.indexOf(s),1):!s&&t&&this.items.push(new cs.Pair(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,s){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,s);throw new Error("Set items must all have null values")}static from(e,t,s){let{replacer:r}=s,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof r=="function"&&(o=r.call(t,o,o)),i.items.push(cs.createPair(o,null,s));return i}};We.tag="tag:yaml.org,2002:set";var Qd={collection:"map",identify:n=>n instanceof Set,nodeClass:We,default:!1,tag:"tag:yaml.org,2002:set",createNode:(n,e,t)=>We.from(n,e,t),resolve(n,e){if(us.isMap(n)){if(n.hasAllNullValues(!0))return Object.assign(new We,n);e("Set items must all have null values")}else e("Expected a mapping for this tag");return n}};zr.YAMLSet=We;zr.set=Qd});var Xr=S(fs=>{"use strict";p();var Xd=ft();function Qr(n,e){let t=n[0],s=t==="-"||t==="+"?n.substring(1):n,r=o=>e?BigInt(o):Number(o),i=s.replace(/_/g,"").split(":").reduce((o,a)=>o*r(60)+r(a),r(0));return t==="-"?r(-1)*i:i}function Ga(n){let{value:e}=n,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Xd.stringifyNumber(n);let s="";e<0&&(s="-",e*=t(-1));let r=t(60),i=[e%r];return e<60?i.unshift(0):(e=(e-i[0])/r,i.unshift(e%r),e>=60&&(e=(e-i[0])/r,i.unshift(e))),s+i.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Zd={identify:n=>typeof n=="bigint"||Number.isInteger(n),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(n,e,{intAsBigInt:t})=>Qr(n,t),stringify:Ga},ep={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:n=>Qr(n,!1),stringify:Ga},Ua={identify:n=>n instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(n){let e=n.match(Ua.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,s,r,i,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(t,s-1,r,i||0,o||0,a||0,c),d=e[8];if(d&&d!=="Z"){let u=Qr(d,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:n})=>n?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};fs.floatTime=ep;fs.intTime=Zd;fs.timestamp=Ua});var Va=S(Ya=>{"use strict";p();var tp=lt(),np=Xn(),sp=ut(),rp=Jt(),ip=Br(),Fa=Ma(),Zr=Da(),ds=Ba(),op=Fn(),ap=Yr(),cp=is(),lp=Hr(),ei=Xr(),up=[tp.map,sp.seq,rp.string,np.nullTag,Fa.trueTag,Fa.falseTag,ds.intBin,ds.intOct,ds.int,ds.intHex,Zr.floatNaN,Zr.floatExp,Zr.float,ip.binary,op.merge,ap.omap,cp.pairs,lp.set,ei.intTime,ei.floatTime,ei.timestamp];Ya.schema=up});var nc=S(si=>{"use strict";p();var Ha=lt(),fp=Xn(),Qa=ut(),dp=Jt(),pp=jr(),ti=qr(),ni=xr(),hp=Ea(),mp=_a(),Xa=Br(),Xt=Fn(),Za=Yr(),ec=is(),Ja=Va(),tc=Hr(),ps=Xr(),Wa=new Map([["core",hp.schema],["failsafe",[Ha.map,Qa.seq,dp.string]],["json",mp.schema],["yaml11",Ja.schema],["yaml-1.1",Ja.schema]]),za={binary:Xa.binary,bool:pp.boolTag,float:ti.float,floatExp:ti.floatExp,floatNaN:ti.floatNaN,floatTime:ps.floatTime,int:ni.int,intHex:ni.intHex,intOct:ni.intOct,intTime:ps.intTime,map:Ha.map,merge:Xt.merge,null:fp.nullTag,omap:Za.omap,pairs:ec.pairs,seq:Qa.seq,set:tc.set,timestamp:ps.timestamp},gp={"tag:yaml.org,2002:binary":Xa.binary,"tag:yaml.org,2002:merge":Xt.merge,"tag:yaml.org,2002:omap":Za.omap,"tag:yaml.org,2002:pairs":ec.pairs,"tag:yaml.org,2002:set":tc.set,"tag:yaml.org,2002:timestamp":ps.timestamp};function yp(n,e,t){let s=Wa.get(e);if(s&&!n)return t&&!s.includes(Xt.merge)?s.concat(Xt.merge):s.slice();let r=s;if(!r)if(Array.isArray(n))r=[];else{let i=Array.from(Wa.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${i} or define customTags array`)}if(Array.isArray(n))for(let i of n)r=r.concat(i);else typeof n=="function"&&(r=n(r.slice()));return t&&(r=r.concat(Xt.merge)),r.reduce((i,o)=>{let a=typeof o=="string"?za[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(za).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return i.includes(a)||i.push(a),i},[])}si.coreKnownTags=gp;si.getTags=yp});var oi=S(sc=>{"use strict";p();var ri=x(),wp=lt(),bp=ut(),kp=Jt(),hs=nc(),$p=(n,e)=>n.key<e.key?-1:n.key>e.key?1:0,ii=class n{constructor({compat:e,customTags:t,merge:s,resolveKnownTags:r,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?hs.getTags(e,"compat"):e?hs.getTags(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=r?hs.coreKnownTags:{},this.tags=hs.getTags(t,this.name,s),this.toStringOptions=a??null,Object.defineProperty(this,ri.MAP,{value:wp.map}),Object.defineProperty(this,ri.SCALAR,{value:kp.string}),Object.defineProperty(this,ri.SEQ,{value:bp.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?$p:null}clone(){let e=Object.create(n.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};sc.Schema=ii});var ic=S(rc=>{"use strict";p();var Sp=x(),ai=Ut(),Zt=Dt();function vp(n,e){let t=[],s=e.directives===!0;if(e.directives!==!1&&n.directives){let c=n.directives.toString(n);c?(t.push(c),s=!0):n.directives.docStart&&(s=!0)}s&&t.push("---");let r=ai.createStringifyContext(n,e),{commentString:i}=r.options;if(n.commentBefore){t.length!==1&&t.unshift("");let c=i(n.commentBefore);t.unshift(Zt.indentComment(c,""))}let o=!1,a=null;if(n.contents){if(Sp.isNode(n.contents)){if(n.contents.spaceBefore&&s&&t.push(""),n.contents.commentBefore){let d=i(n.contents.commentBefore);t.push(Zt.indentComment(d,""))}r.forceBlockIndent=!!n.comment,a=n.contents.comment}let c=a?void 0:()=>o=!0,l=ai.stringify(n.contents,r,()=>a=null,c);a&&(l+=Zt.lineComment(l,"",i(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(ai.stringify(n.contents,r));if(n.directives?.docEnd)if(n.comment){let c=i(n.comment);c.includes(`
|
|
57
|
-
`)?(
|
|
56
|
+
${i.comment}`:s.comment}s=r}t.items[n]=ms.isPair(s)?s:new ei.Pair(s)}}else e("Expected a sequence for this tag");return t}function tc(t,e,n){let{replacer:s}=n,r=new Up.YAMLSeq(t);r.tag="tag:yaml.org,2002:pairs";let i=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof s=="function"&&(o=s.call(e,String(i++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;r.items.push(ei.createPair(a,c,n))}return r}var Gp={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:ec,createNode:tc};ys.createPairs=tc;ys.pairs=Gp;ys.resolvePairs=ec});var si=E(ni=>{"use strict";p();var nc=B(),ti=Pe(),nn=Me(),Fp=Ke(),sc=ws(),Xe=class t extends Fp.YAMLSeq{constructor(){super(),this.add=nn.YAMLMap.prototype.add.bind(this),this.delete=nn.YAMLMap.prototype.delete.bind(this),this.get=nn.YAMLMap.prototype.get.bind(this),this.has=nn.YAMLMap.prototype.has.bind(this),this.set=nn.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,n){if(!n)return super.toJSON(e);let s=new Map;n?.onCreate&&n.onCreate(s);for(let r of this.items){let i,o;if(nc.isPair(r)?(i=ti.toJS(r.key,"",n),o=ti.toJS(r.value,i,n)):i=ti.toJS(r,"",n),s.has(i))throw new Error("Ordered maps must not include duplicate keys");s.set(i,o)}return s}static from(e,n,s){let r=sc.createPairs(e,n,s),i=new this;return i.items=r.items,i}};Xe.tag="tag:yaml.org,2002:omap";var Wp={collection:"seq",identify:t=>t instanceof Map,nodeClass:Xe,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let n=sc.resolvePairs(t,e),s=[];for(let{key:r}of n.items)nc.isScalar(r)&&(s.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):s.push(r.value));return Object.assign(new Xe,n)},createNode:(t,e,n)=>Xe.from(t,e,n)};ni.YAMLOMap=Xe;ni.omap=Wp});var cc=E(ri=>{"use strict";p();var rc=Y();function ic({value:t,source:e},n){return e&&(t?oc:ac).test.test(e)?e:t?n.options.trueStr:n.options.falseStr}var oc={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new rc.Scalar(!0),stringify:ic},ac={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new rc.Scalar(!1),stringify:ic};ri.falseTag=ac;ri.trueTag=oc});var lc=E(bs=>{"use strict";p();var Yp=Y(),ii=gt(),Vp={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:ii.stringifyNumber},Jp={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():ii.stringifyNumber(t)}},zp={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new Yp.Scalar(parseFloat(t.replace(/_/g,""))),n=t.indexOf(".");if(n!==-1){let s=t.substring(n+1).replace(/_/g,"");s[s.length-1]==="0"&&(e.minFractionDigits=s.length)}return e},stringify:ii.stringifyNumber};bs.float=zp;bs.floatExp=Jp;bs.floatNaN=Vp});var fc=E(rn=>{"use strict";p();var uc=gt(),sn=t=>typeof t=="bigint"||Number.isInteger(t);function ks(t,e,n,{intAsBigInt:s}){let r=t[0];if((r==="-"||r==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),s){switch(n){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let o=BigInt(t);return r==="-"?BigInt(-1)*o:o}let i=parseInt(t,n);return r==="-"?-1*i:i}function oi(t,e,n){let{value:s}=t;if(sn(s)){let r=s.toString(e);return s<0?"-"+n+r.substr(1):n+r}return uc.stringifyNumber(t)}var Hp={identify:sn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,n)=>ks(t,2,2,n),stringify:t=>oi(t,2,"0b")},Qp={identify:sn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,n)=>ks(t,1,8,n),stringify:t=>oi(t,8,"0")},Zp={identify:sn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,n)=>ks(t,0,10,n),stringify:uc.stringifyNumber},Xp={identify:sn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,n)=>ks(t,2,16,n),stringify:t=>oi(t,16,"0x")};rn.int=Zp;rn.intBin=Hp;rn.intHex=Xp;rn.intOct=Qp});var ci=E(ai=>{"use strict";p();var vs=B(),$s=xe(),Ss=Me(),et=class t extends Ss.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let n;vs.isPair(e)?n=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?n=new $s.Pair(e.key,null):n=new $s.Pair(e,null),Ss.findPair(this.items,n.key)||this.items.push(n)}get(e,n){let s=Ss.findPair(this.items,e);return!n&&vs.isPair(s)?vs.isScalar(s.key)?s.key.value:s.key:s}set(e,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let s=Ss.findPair(this.items,e);s&&!n?this.items.splice(this.items.indexOf(s),1):!s&&n&&this.items.push(new $s.Pair(e))}toJSON(e,n){return super.toJSON(e,n,Set)}toString(e,n,s){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),n,s);throw new Error("Set items must all have null values")}static from(e,n,s){let{replacer:r}=s,i=new this(e);if(n&&Symbol.iterator in Object(n))for(let o of n)typeof r=="function"&&(o=r.call(n,o,o)),i.items.push($s.createPair(o,null,s));return i}};et.tag="tag:yaml.org,2002:set";var eh={collection:"map",identify:t=>t instanceof Set,nodeClass:et,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,n)=>et.from(t,e,n),resolve(t,e){if(vs.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new et,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};ai.YAMLSet=et;ai.set=eh});var ui=E(As=>{"use strict";p();var th=gt();function li(t,e){let n=t[0],s=n==="-"||n==="+"?t.substring(1):t,r=o=>e?BigInt(o):Number(o),i=s.replace(/_/g,"").split(":").reduce((o,a)=>o*r(60)+r(a),r(0));return n==="-"?r(-1)*i:i}function dc(t){let{value:e}=t,n=o=>o;if(typeof e=="bigint")n=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return th.stringifyNumber(t);let s="";e<0&&(s="-",e*=n(-1));let r=n(60),i=[e%r];return e<60?i.unshift(0):(e=(e-i[0])/r,i.unshift(e%r),e>=60&&(e=(e-i[0])/r,i.unshift(e))),s+i.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var nh={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:n})=>li(t,n),stringify:dc},sh={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>li(t,!1),stringify:dc},pc={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){let e=t.match(pc.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,s,r,i,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(n,s-1,r,i||0,o||0,a||0,c),h=e[8];if(h&&h!=="Z"){let u=li(h,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};As.floatTime=sh;As.intTime=nh;As.timestamp=pc});var mc=E(gc=>{"use strict";p();var rh=pt(),ih=fs(),oh=ht(),ah=en(),ch=Xr(),hc=cc(),fi=lc(),Es=fc(),lh=ss(),uh=si(),fh=ws(),dh=ci(),di=ui(),ph=[rh.map,oh.seq,ah.string,ih.nullTag,hc.trueTag,hc.falseTag,Es.intBin,Es.intOct,Es.int,Es.intHex,fi.floatNaN,fi.floatExp,fi.float,ch.binary,lh.merge,uh.omap,fh.pairs,dh.set,di.intTime,di.floatTime,di.timestamp];gc.schema=ph});var _c=E(gi=>{"use strict";p();var kc=pt(),hh=fs(),$c=ht(),gh=en(),mh=Wr(),pi=Vr(),hi=zr(),yh=za(),wh=Za(),Sc=Xr(),on=ss(),vc=si(),Ac=ws(),yc=mc(),Ec=ci(),_s=ui(),wc=new Map([["core",yh.schema],["failsafe",[kc.map,$c.seq,gh.string]],["json",wh.schema],["yaml11",yc.schema],["yaml-1.1",yc.schema]]),bc={binary:Sc.binary,bool:mh.boolTag,float:pi.float,floatExp:pi.floatExp,floatNaN:pi.floatNaN,floatTime:_s.floatTime,int:hi.int,intHex:hi.intHex,intOct:hi.intOct,intTime:_s.intTime,map:kc.map,merge:on.merge,null:hh.nullTag,omap:vc.omap,pairs:Ac.pairs,seq:$c.seq,set:Ec.set,timestamp:_s.timestamp},bh={"tag:yaml.org,2002:binary":Sc.binary,"tag:yaml.org,2002:merge":on.merge,"tag:yaml.org,2002:omap":vc.omap,"tag:yaml.org,2002:pairs":Ac.pairs,"tag:yaml.org,2002:set":Ec.set,"tag:yaml.org,2002:timestamp":_s.timestamp};function kh(t,e,n){let s=wc.get(e);if(s&&!t)return n&&!s.includes(on.merge)?s.concat(on.merge):s.slice();let r=s;if(!r)if(Array.isArray(t))r=[];else{let i=Array.from(wc.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${i} or define customTags array`)}if(Array.isArray(t))for(let i of t)r=r.concat(i);else typeof t=="function"&&(r=t(r.slice()));return n&&(r=r.concat(on.merge)),r.reduce((i,o)=>{let a=typeof o=="string"?bc[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(bc).map(h=>JSON.stringify(h)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return i.includes(a)||i.push(a),i},[])}gi.coreKnownTags=bh;gi.getTags=kh});var wi=E(Cc=>{"use strict";p();var mi=B(),$h=pt(),Sh=ht(),vh=en(),Cs=_c(),Ah=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,yi=class t{constructor({compat:e,customTags:n,merge:s,resolveKnownTags:r,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Cs.getTags(e,"compat"):e?Cs.getTags(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=r?Cs.coreKnownTags:{},this.tags=Cs.getTags(n,this.name,s),this.toStringOptions=a??null,Object.defineProperty(this,mi.MAP,{value:$h.map}),Object.defineProperty(this,mi.SCALAR,{value:vh.string}),Object.defineProperty(this,mi.SEQ,{value:Sh.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Ah:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Cc.Schema=yi});var Tc=E(Nc=>{"use strict";p();var Eh=B(),bi=Ht(),an=Yt();function _h(t,e){let n=[],s=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(n.push(c),s=!0):t.directives.docStart&&(s=!0)}s&&n.push("---");let r=bi.createStringifyContext(t,e),{commentString:i}=r.options;if(t.commentBefore){n.length!==1&&n.unshift("");let c=i(t.commentBefore);n.unshift(an.indentComment(c,""))}let o=!1,a=null;if(t.contents){if(Eh.isNode(t.contents)){if(t.contents.spaceBefore&&s&&n.push(""),t.contents.commentBefore){let h=i(t.contents.commentBefore);n.push(an.indentComment(h,""))}r.forceBlockIndent=!!t.comment,a=t.contents.comment}let c=a?void 0:()=>o=!0,l=bi.stringify(t.contents,r,()=>a=null,c);a&&(l+=an.lineComment(l,"",i(a))),(l[0]==="|"||l[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${l}`:n.push(l)}else n.push(bi.stringify(t.contents,r));if(t.directives?.docEnd)if(t.comment){let c=i(t.comment);c.includes(`
|
|
57
|
+
`)?(n.push("..."),n.push(an.indentComment(c,""))):n.push(`... ${c}`)}else n.push("...");else{let c=t.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||a)&&n[n.length-1]!==""&&n.push(""),n.push(an.indentComment(i(c),"")))}return n.join(`
|
|
58
58
|
`)+`
|
|
59
|
-
`}
|
|
60
|
-
`),o=a+o}if(/[^ ]/.test(o)){let a=1,c=
|
|
59
|
+
`}Nc.stringifyDocument=_h});var cn=E(Oc=>{"use strict";p();var Ch=Ft(),mt=Jn(),ce=B(),Nh=xe(),Th=Pe(),Oh=wi(),Ih=Tc(),ki=Fn(),Ph=Ar(),jh=Wt(),$i=vr(),Si=class t{constructor(e,n,s){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ce.NODE_TYPE,{value:ce.DOC});let r=null;typeof n=="function"||Array.isArray(n)?r=n:s===void 0&&n&&(s=n,n=void 0);let i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},s);this.options=i;let{version:o}=i;s?._directives?(this.directives=s._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new $i.Directives({version:o}),this.setSchema(o,s),this.contents=e===void 0?null:this.createNode(e,r,s)}clone(){let e=Object.create(t.prototype,{[ce.NODE_TYPE]:{value:ce.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=ce.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){yt(this.contents)&&this.contents.add(e)}addIn(e,n){yt(this.contents)&&this.contents.addIn(e,n)}createAlias(e,n){if(!e.anchor){let s=ki.anchorNames(this);e.anchor=!n||s.has(n)?ki.findNewAnchor(n||"a",s):n}return new Ch.Alias(e.anchor)}createNode(e,n,s){let r;if(typeof n=="function")e=n.call({"":e},"",e),r=n;else if(Array.isArray(n)){let y=C=>typeof C=="number"||C instanceof String||C instanceof Number,S=n.filter(y).map(String);S.length>0&&(n=n.concat(S)),r=n}else s===void 0&&n&&(s=n,n=void 0);let{aliasDuplicateObjects:i,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:h}=s??{},{onAnchor:u,setAnchors:f,sourceObjects:d}=ki.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:i??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:r,schema:this.schema,sourceObjects:d},g=jh.createNode(e,h,m);return a&&ce.isCollection(g)&&(g.flow=!0),f(),g}createPair(e,n,s={}){let r=this.createNode(e,null,s),i=this.createNode(n,null,s);return new Nh.Pair(r,i)}delete(e){return yt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return mt.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):yt(this.contents)?this.contents.deleteIn(e):!1}get(e,n){return ce.isCollection(this.contents)?this.contents.get(e,n):void 0}getIn(e,n){return mt.isEmptyPath(e)?!n&&ce.isScalar(this.contents)?this.contents.value:this.contents:ce.isCollection(this.contents)?this.contents.getIn(e,n):void 0}has(e){return ce.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return mt.isEmptyPath(e)?this.contents!==void 0:ce.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,n){this.contents==null?this.contents=mt.collectionFromPath(this.schema,[e],n):yt(this.contents)&&this.contents.set(e,n)}setIn(e,n){mt.isEmptyPath(e)?this.contents=n:this.contents==null?this.contents=mt.collectionFromPath(this.schema,Array.from(e),n):yt(this.contents)&&this.contents.setIn(e,n)}setSchema(e,n={}){typeof e=="number"&&(e=String(e));let s;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new $i.Directives({version:"1.1"}),s={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new $i.Directives({version:e}),s={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,s=null;break;default:{let r=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(n.schema instanceof Object)this.schema=n.schema;else if(s)this.schema=new Oh.Schema(Object.assign(s,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:n,mapAsMap:s,maxAliasCount:r,onAnchor:i,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:s===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},c=Th.toJS(this.contents,n??"",a);if(typeof i=="function")for(let{count:l,res:h}of a.anchors.values())i(h,l);return typeof o=="function"?Ph.applyReviver(o,{"":c},"",c):c}toJSON(e,n){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:n})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let n=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return Ih.stringifyDocument(this,e)}};function yt(t){if(ce.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}Oc.Document=Si});var fn=E(un=>{"use strict";p();var ln=class extends Error{constructor(e,n,s,r){super(),this.name=e,this.code=s,this.message=r,this.pos=n}},vi=class extends ln{constructor(e,n,s){super("YAMLParseError",e,n,s)}},Ai=class extends ln{constructor(e,n,s){super("YAMLWarning",e,n,s)}},Rh=(t,e)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(a=>e.linePos(a));let{line:s,col:r}=n.linePos[0];n.message+=` at line ${s}, column ${r}`;let i=r-1,o=t.substring(e.lineStarts[s-1],e.lineStarts[s]).replace(/[\n\r]+$/,"");if(i>=60&&o.length>80){let a=Math.min(i-39,o.length-79);o="\u2026"+o.substring(a),i-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),s>1&&/^ *$/.test(o.substring(0,i))){let a=t.substring(e.lineStarts[s-2],e.lineStarts[s-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
|
|
60
|
+
`),o=a+o}if(/[^ ]/.test(o)){let a=1,c=n.linePos[1];c&&c.line===s&&c.col>r&&(a=Math.max(1,Math.min(c.col-r,80-i)));let l=" ".repeat(i)+"^".repeat(a);n.message+=`:
|
|
61
61
|
|
|
62
62
|
${o}
|
|
63
63
|
${l}
|
|
64
|
-
`}};
|
|
65
|
-
`))return!0;if(
|
|
66
|
-
`+
|
|
67
|
-
`+
|
|
68
|
-
`+
|
|
69
|
-
`+
|
|
70
|
-
`+
|
|
71
|
-
`+
|
|
72
|
-
`.repeat(Math.max(1,o.length-1)):"",
|
|
73
|
-
`;for(let
|
|
74
|
-
`):
|
|
75
|
-
`:!
|
|
64
|
+
`}};un.YAMLError=ln;un.YAMLParseError=vi;un.YAMLWarning=Ai;un.prettifyError=Rh});var dn=E(Ic=>{"use strict";p();function Lh(t,{flow:e,indicator:n,next:s,offset:r,onError:i,parentIndent:o,startOnNewline:a}){let c=!1,l=a,h=a,u="",f="",d=!1,m=!1,g=null,y=null,S=null,C=null,O=null,$=null,T=null;for(let v of t)switch(m&&(v.type!=="space"&&v.type!=="newline"&&v.type!=="comma"&&i(v.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),g&&(l&&v.type!=="comment"&&v.type!=="newline"&&i(g,"TAB_AS_INDENT","Tabs are not allowed as indentation"),g=null),v.type){case"space":!e&&(n!=="doc-start"||s?.type!=="flow-collection")&&v.source.includes(" ")&&(g=v),h=!0;break;case"comment":{h||i(v,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let K=v.source.substring(1)||" ";u?u+=f+K:u=K,f="",l=!1;break}case"newline":l?u?u+=v.source:(!$||n!=="seq-item-ind")&&(c=!0):f+=v.source,l=!0,d=!0,(y||S)&&(C=v),h=!0;break;case"anchor":y&&i(v,"MULTIPLE_ANCHORS","A node can have at most one anchor"),v.source.endsWith(":")&&i(v.offset+v.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=v,T??(T=v.offset),l=!1,h=!1,m=!0;break;case"tag":{S&&i(v,"MULTIPLE_TAGS","A node can have at most one tag"),S=v,T??(T=v.offset),l=!1,h=!1,m=!0;break}case n:(y||S)&&i(v,"BAD_PROP_ORDER",`Anchors and tags must be after the ${v.source} indicator`),$&&i(v,"UNEXPECTED_TOKEN",`Unexpected ${v.source} in ${e??"collection"}`),$=v,l=n==="seq-item-ind"||n==="explicit-key-ind",h=!1;break;case"comma":if(e){O&&i(v,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),O=v,l=!1,h=!1;break}default:i(v,"UNEXPECTED_TOKEN",`Unexpected ${v.type} token`),l=!1,h=!1}let j=t[t.length-1],b=j?j.offset+j.source.length:r;return m&&s&&s.type!=="space"&&s.type!=="newline"&&s.type!=="comma"&&(s.type!=="scalar"||s.source!=="")&&i(s.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),g&&(l&&g.indent<=o||s?.type==="block-map"||s?.type==="block-seq")&&i(g,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:O,found:$,spaceBefore:c,comment:u,hasNewline:d,anchor:y,tag:S,newlineAfterProp:C,end:b,start:T??b}}Ic.resolveProps=Lh});var Ns=E(Pc=>{"use strict";p();function Ei(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(`
|
|
65
|
+
`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let n of e.start)if(n.type==="newline")return!0;if(e.sep){for(let n of e.sep)if(n.type==="newline")return!0}if(Ei(e.key)||Ei(e.value))return!0}return!1;default:return!0}}Pc.containsNewline=Ei});var _i=E(jc=>{"use strict";p();var xh=Ns();function qh(t,e,n){if(e?.type==="flow-collection"){let s=e.end[0];s.indent===t&&(s.source==="]"||s.source==="}")&&xh.containsNewline(e)&&n(s,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}jc.flowIndentCheck=qh});var Ci=E(Lc=>{"use strict";p();var Rc=B();function Mh(t,e,n){let{uniqueKeys:s}=t.options;if(s===!1)return!1;let r=typeof s=="function"?s:(i,o)=>i===o||Rc.isScalar(i)&&Rc.isScalar(o)&&i.value===o.value;return e.some(i=>r(i.key,n))}Lc.mapIncludes=Mh});var Bc=E(Dc=>{"use strict";p();var xc=xe(),Kh=Me(),qc=dn(),Dh=Ns(),Mc=_i(),Bh=Ci(),Kc="All mapping items must start at the same column";function Uh({composeNode:t,composeEmptyNode:e},n,s,r,i){let o=i?.nodeClass??Kh.YAMLMap,a=new o(n.schema);n.atRoot&&(n.atRoot=!1);let c=s.offset,l=null;for(let h of s.items){let{start:u,key:f,sep:d,value:m}=h,g=qc.resolveProps(u,{indicator:"explicit-key-ind",next:f??d?.[0],offset:c,onError:r,parentIndent:s.indent,startOnNewline:!0}),y=!g.found;if(y){if(f&&(f.type==="block-seq"?r(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==s.indent&&r(c,"BAD_INDENT",Kc)),!g.anchor&&!g.tag&&!d){l=g.end,g.comment&&(a.comment?a.comment+=`
|
|
66
|
+
`+g.comment:a.comment=g.comment);continue}(g.newlineAfterProp||Dh.containsNewline(f))&&r(f??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else g.found?.indent!==s.indent&&r(c,"BAD_INDENT",Kc);n.atKey=!0;let S=g.end,C=f?t(n,f,g,r):e(n,S,u,null,g,r);n.schema.compat&&Mc.flowIndentCheck(s.indent,f,r),n.atKey=!1,Bh.mapIncludes(n,a.items,C)&&r(S,"DUPLICATE_KEY","Map keys must be unique");let O=qc.resolveProps(d??[],{indicator:"map-value-ind",next:m,offset:C.range[2],onError:r,parentIndent:s.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=O.end,O.found){y&&(m?.type==="block-map"&&!O.hasNewline&&r(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&g.start<O.found.offset-1024&&r(C.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let $=m?t(n,m,O,r):e(n,c,d,null,O,r);n.schema.compat&&Mc.flowIndentCheck(s.indent,m,r),c=$.range[2];let T=new xc.Pair(C,$);n.options.keepSourceTokens&&(T.srcToken=h),a.items.push(T)}else{y&&r(C.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),O.comment&&(C.comment?C.comment+=`
|
|
67
|
+
`+O.comment:C.comment=O.comment);let $=new xc.Pair(C);n.options.keepSourceTokens&&($.srcToken=h),a.items.push($)}}return l&&l<c&&r(l,"IMPOSSIBLE","Map comment with trailing content"),a.range=[s.offset,c,l??c],a}Dc.resolveBlockMap=Uh});var Gc=E(Uc=>{"use strict";p();var Gh=Ke(),Fh=dn(),Wh=_i();function Yh({composeNode:t,composeEmptyNode:e},n,s,r,i){let o=i?.nodeClass??Gh.YAMLSeq,a=new o(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let c=s.offset,l=null;for(let{start:h,value:u}of s.items){let f=Fh.resolveProps(h,{indicator:"seq-item-ind",next:u,offset:c,onError:r,parentIndent:s.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||u)u&&u.type==="block-seq"?r(f.end,"BAD_INDENT","All sequence items must start at the same column"):r(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(a.comment=f.comment);continue}let d=u?t(n,u,f,r):e(n,f.end,h,null,f,r);n.schema.compat&&Wh.flowIndentCheck(s.indent,u,r),c=d.range[2],a.items.push(d)}return a.range=[s.offset,c,l??c],a}Uc.resolveBlockSeq=Yh});var wt=E(Fc=>{"use strict";p();function Vh(t,e,n,s){let r="";if(t){let i=!1,o="";for(let a of t){let{source:c,type:l}=a;switch(l){case"space":i=!0;break;case"comment":{n&&!i&&s(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let h=c.substring(1)||" ";r?r+=o+h:r=h,o="";break}case"newline":r&&(o+=c),i=!0;break;default:s(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:r,offset:e}}Fc.resolveEnd=Vh});var Jc=E(Vc=>{"use strict";p();var Jh=B(),zh=xe(),Wc=Me(),Hh=Ke(),Qh=wt(),Yc=dn(),Zh=Ns(),Xh=Ci(),Ni="Block collections are not allowed within flow collections",Ti=t=>t&&(t.type==="block-map"||t.type==="block-seq");function eg({composeNode:t,composeEmptyNode:e},n,s,r,i){let o=s.start.source==="{",a=o?"flow map":"flow sequence",c=i?.nodeClass??(o?Wc.YAMLMap:Hh.YAMLSeq),l=new c(n.schema);l.flow=!0;let h=n.atRoot;h&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let u=s.offset+s.start.source.length;for(let y=0;y<s.items.length;++y){let S=s.items[y],{start:C,key:O,sep:$,value:T}=S,j=Yc.resolveProps(C,{flow:a,indicator:"explicit-key-ind",next:O??$?.[0],offset:u,onError:r,parentIndent:s.indent,startOnNewline:!1});if(!j.found){if(!j.anchor&&!j.tag&&!$&&!T){y===0&&j.comma?r(j.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):y<s.items.length-1&&r(j.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),j.comment&&(l.comment?l.comment+=`
|
|
68
|
+
`+j.comment:l.comment=j.comment),u=j.end;continue}!o&&n.options.strict&&Zh.containsNewline(O)&&r(O,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(y===0)j.comma&&r(j.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(j.comma||r(j.start,"MISSING_CHAR",`Missing , between ${a} items`),j.comment){let b="";e:for(let v of C)switch(v.type){case"comma":case"space":break;case"comment":b=v.source.substring(1);break e;default:break e}if(b){let v=l.items[l.items.length-1];Jh.isPair(v)&&(v=v.value??v.key),v.comment?v.comment+=`
|
|
69
|
+
`+b:v.comment=b,j.comment=j.comment.substring(b.length+1)}}if(!o&&!$&&!j.found){let b=T?t(n,T,j,r):e(n,j.end,$,null,j,r);l.items.push(b),u=b.range[2],Ti(T)&&r(b.range,"BLOCK_IN_FLOW",Ni)}else{n.atKey=!0;let b=j.end,v=O?t(n,O,j,r):e(n,b,C,null,j,r);Ti(O)&&r(v.range,"BLOCK_IN_FLOW",Ni),n.atKey=!1;let K=Yc.resolveProps($??[],{flow:a,indicator:"map-value-ind",next:T,offset:v.range[2],onError:r,parentIndent:s.indent,startOnNewline:!1});if(K.found){if(!o&&!j.found&&n.options.strict){if($)for(let q of $){if(q===K.found)break;if(q.type==="newline"){r(q,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}j.start<K.found.offset-1024&&r(K.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else T&&("source"in T&&T.source&&T.source[0]===":"?r(T,"MISSING_CHAR",`Missing space after : in ${a}`):r(K.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let I=T?t(n,T,K,r):K.found?e(n,K.end,$,null,K,r):null;I?Ti(T)&&r(I.range,"BLOCK_IN_FLOW",Ni):K.comment&&(v.comment?v.comment+=`
|
|
70
|
+
`+K.comment:v.comment=K.comment);let R=new zh.Pair(v,I);if(n.options.keepSourceTokens&&(R.srcToken=S),o){let q=l;Xh.mapIncludes(n,q.items,v)&&r(b,"DUPLICATE_KEY","Map keys must be unique"),q.items.push(R)}else{let q=new Wc.YAMLMap(n.schema);q.flow=!0,q.items.push(R);let F=(I??v).range;q.range=[v.range[0],F[1],F[2]],l.items.push(q)}u=I?I.range[2]:K.end}}let f=o?"}":"]",[d,...m]=s.end,g=u;if(d&&d.source===f)g=d.offset+d.source.length;else{let y=a[0].toUpperCase()+a.substring(1),S=h?`${y} must end with a ${f}`:`${y} in block collection must be sufficiently indented and end with a ${f}`;r(u,h?"MISSING_CHAR":"BAD_INDENT",S),d&&d.source.length!==1&&m.unshift(d)}if(m.length>0){let y=Qh.resolveEnd(m,g,n.options.strict,r);y.comment&&(l.comment?l.comment+=`
|
|
71
|
+
`+y.comment:l.comment=y.comment),l.range=[s.offset,g,y.offset]}else l.range=[s.offset,g,g];return l}Vc.resolveFlowCollection=eg});var Hc=E(zc=>{"use strict";p();var tg=B(),ng=Y(),sg=Me(),rg=Ke(),ig=Bc(),og=Gc(),ag=Jc();function Oi(t,e,n,s,r,i){let o=n.type==="block-map"?ig.resolveBlockMap(t,e,n,s,i):n.type==="block-seq"?og.resolveBlockSeq(t,e,n,s,i):ag.resolveFlowCollection(t,e,n,s,i),a=o.constructor;return r==="!"||r===a.tagName?(o.tag=a.tagName,o):(r&&(o.tag=r),o)}function cg(t,e,n,s,r){let i=s.tag,o=i?e.directives.tagName(i.source,f=>r(i,"TAG_RESOLVE_FAILED",f)):null;if(n.type==="block-seq"){let{anchor:f,newlineAfterProp:d}=s,m=f&&i?f.offset>i.offset?f:i:f??i;m&&(!d||d.offset<m.offset)&&r(m,"MISSING_CHAR","Missing newline after block sequence props")}let a=n.type==="block-map"?"map":n.type==="block-seq"?"seq":n.start.source==="{"?"map":"seq";if(!i||!o||o==="!"||o===sg.YAMLMap.tagName&&a==="map"||o===rg.YAMLSeq.tagName&&a==="seq")return Oi(t,e,n,r,o);let c=e.schema.tags.find(f=>f.tag===o&&f.collection===a);if(!c){let f=e.schema.knownTags[o];if(f&&f.collection===a)e.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?r(i,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Oi(t,e,n,r,o)}let l=Oi(t,e,n,r,o,c),h=c.resolve?.(l,f=>r(i,"TAG_RESOLVE_FAILED",f),e.options)??l,u=tg.isNode(h)?h:new ng.Scalar(h);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}zc.composeCollection=cg});var Pi=E(Qc=>{"use strict";p();var Ii=Y();function lg(t,e,n){let s=e.offset,r=ug(e,t.options.strict,n);if(!r)return{value:"",type:null,comment:"",range:[s,s,s]};let i=r.mode===">"?Ii.Scalar.BLOCK_FOLDED:Ii.Scalar.BLOCK_LITERAL,o=e.source?fg(e.source):[],a=o.length;for(let g=o.length-1;g>=0;--g){let y=o[g][1];if(y===""||y==="\r")a=g;else break}if(a===0){let g=r.chomp==="+"&&o.length>0?`
|
|
72
|
+
`.repeat(Math.max(1,o.length-1)):"",y=s+r.length;return e.source&&(y+=e.source.length),{value:g,type:i,comment:r.comment,range:[s,y,y]}}let c=e.indent+r.indent,l=e.offset+r.length,h=0;for(let g=0;g<a;++g){let[y,S]=o[g];if(S===""||S==="\r")r.indent===0&&y.length>c&&(c=y.length);else{y.length<c&&n(l+y.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),r.indent===0&&(c=y.length),h=g,c===0&&!t.atRoot&&n(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=y.length+S.length+1}for(let g=o.length-1;g>=a;--g)o[g][0].length>c&&(a=g+1);let u="",f="",d=!1;for(let g=0;g<h;++g)u+=o[g][0].slice(c)+`
|
|
73
|
+
`;for(let g=h;g<a;++g){let[y,S]=o[g];l+=y.length+S.length+1;let C=S[S.length-1]==="\r";if(C&&(S=S.slice(0,-1)),S&&y.length<c){let $=`Block scalar lines must not be less indented than their ${r.indent?"explicit indentation indicator":"first line"}`;n(l-S.length-(C?2:1),"BAD_INDENT",$),y=""}i===Ii.Scalar.BLOCK_LITERAL?(u+=f+y.slice(c)+S,f=`
|
|
74
|
+
`):y.length>c||S[0]===" "?(f===" "?f=`
|
|
75
|
+
`:!d&&f===`
|
|
76
76
|
`&&(f=`
|
|
77
77
|
|
|
78
|
-
`),u+=f+
|
|
79
|
-
`,
|
|
78
|
+
`),u+=f+y.slice(c)+S,f=`
|
|
79
|
+
`,d=!0):S===""?f===`
|
|
80
80
|
`?u+=`
|
|
81
81
|
`:f=`
|
|
82
|
-
`:(u+=f+
|
|
83
|
-
`+o[
|
|
82
|
+
`:(u+=f+S,f=" ",d=!1)}switch(r.chomp){case"-":break;case"+":for(let g=a;g<o.length;++g)u+=`
|
|
83
|
+
`+o[g][0].slice(c);u[u.length-1]!==`
|
|
84
84
|
`&&(u+=`
|
|
85
85
|
`);break;default:u+=`
|
|
86
|
-
`}let
|
|
87
|
-
`,"sy"),
|
|
88
|
-
`,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,
|
|
86
|
+
`}let m=s+r.length+e.source.length;return{value:u,type:i,comment:r.comment,range:[s,m,m]}}function ug({offset:t,props:e},n,s){if(e[0].type!=="block-scalar-header")return s(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:r}=e[0],i=r[0],o=0,a="",c=-1;for(let f=1;f<r.length;++f){let d=r[f];if(!a&&(d==="-"||d==="+"))a=d;else{let m=Number(d);!o&&m?o=m:c===-1&&(c=t+f)}}c!==-1&&s(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${r}`);let l=!1,h="",u=r.length;for(let f=1;f<e.length;++f){let d=e[f];switch(d.type){case"space":l=!0;case"newline":u+=d.source.length;break;case"comment":n&&!l&&s(d,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),u+=d.source.length,h=d.source.substring(1);break;case"error":s(d,"UNEXPECTED_TOKEN",d.message),u+=d.source.length;break;default:{let m=`Unexpected token in block scalar header: ${d.type}`;s(d,"UNEXPECTED_TOKEN",m);let g=d.source;g&&typeof g=="string"&&(u+=g.length)}}}return{mode:i,indent:o,chomp:a,comment:h,length:u}}function fg(t){let e=t.split(/\n( *)/),n=e[0],s=n.match(/^( *)/),i=[s?.[1]?[s[1],n.slice(s[1].length)]:["",n]];for(let o=1;o<e.length;o+=2)i.push([e[o],e[o+1]]);return i}Qc.resolveBlockScalar=lg});var Ri=E(Xc=>{"use strict";p();var ji=Y(),dg=wt();function pg(t,e,n){let{offset:s,type:r,source:i,end:o}=t,a,c,l=(f,d,m)=>n(s+f,d,m);switch(r){case"scalar":a=ji.Scalar.PLAIN,c=hg(i,l);break;case"single-quoted-scalar":a=ji.Scalar.QUOTE_SINGLE,c=gg(i,l);break;case"double-quoted-scalar":a=ji.Scalar.QUOTE_DOUBLE,c=mg(i,l);break;default:return n(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[s,s+i.length,s+i.length]}}let h=s+i.length,u=dg.resolveEnd(o,h,e,n);return{value:c,type:a,comment:u.comment,range:[s,h,u.offset]}}function hg(t,e){let n="";switch(t[0]){case" ":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${t[0]}`;break}case"@":case"`":{n=`reserved character ${t[0]}`;break}}return n&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),Zc(t)}function gg(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),Zc(t.slice(1,-1)).replace(/''/g,"'")}function Zc(t){let e,n;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
87
|
+
`,"sy"),n=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
88
|
+
`,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,n=/[ \t]*(.*?)[ \t]*\r?\n/sy}let s=e.exec(t);if(!s)return t;let r=s[1],i=" ",o=e.lastIndex;for(n.lastIndex=o;s=n.exec(t);)s[1]===""?i===`
|
|
89
89
|
`?r+=i:i=`
|
|
90
|
-
`:(r+=i+s[1],i=" "),o=
|
|
90
|
+
`:(r+=i+s[1],i=" "),o=n.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=o,s=a.exec(t),r+i+(s?.[1]??"")}function mg(t,e){let n="";for(let s=1;s<t.length-1;++s){let r=t[s];if(!(r==="\r"&&t[s+1]===`
|
|
91
91
|
`))if(r===`
|
|
92
|
-
`){let{fold:i,offset:o}=
|
|
93
|
-
`)for(i=
|
|
94
|
-
`)for(i=
|
|
95
|
-
`&&!(o==="\r"&&
|
|
96
|
-
`)&&(
|
|
97
|
-
`||s==="\r")&&!(s==="\r"&&
|
|
92
|
+
`){let{fold:i,offset:o}=yg(t,s);n+=i,s=o}else if(r==="\\"){let i=t[++s],o=wg[i];if(o)n+=o;else if(i===`
|
|
93
|
+
`)for(i=t[s+1];i===" "||i===" ";)i=t[++s+1];else if(i==="\r"&&t[s+1]===`
|
|
94
|
+
`)for(i=t[++s+1];i===" "||i===" ";)i=t[++s+1];else if(i==="x"||i==="u"||i==="U"){let a={x:2,u:4,U:8}[i];n+=bg(t,s+1,a,e),s+=a}else{let a=t.substr(s-1,2);e(s-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),n+=a}}else if(r===" "||r===" "){let i=s,o=t[s+1];for(;o===" "||o===" ";)o=t[++s+1];o!==`
|
|
95
|
+
`&&!(o==="\r"&&t[s+2]===`
|
|
96
|
+
`)&&(n+=s>i?t.slice(i,s+1):r)}else n+=r}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),n}function yg(t,e){let n="",s=t[e+1];for(;(s===" "||s===" "||s===`
|
|
97
|
+
`||s==="\r")&&!(s==="\r"&&t[e+2]!==`
|
|
98
98
|
`);)s===`
|
|
99
|
-
`&&(
|
|
100
|
-
`),e+=1,s=
|
|
101
|
-
`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function
|
|
99
|
+
`&&(n+=`
|
|
100
|
+
`),e+=1,s=t[e+1];return n||(n=" "),{fold:n,offset:e}}var wg={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
101
|
+
`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function bg(t,e,n,s){let r=t.substr(e,n),o=r.length===n&&/^[0-9a-fA-F]+$/.test(r)?parseInt(r,16):NaN;if(isNaN(o)){let a=t.substr(e-2,n+2);return s(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}return String.fromCodePoint(o)}Xc.resolveFlowScalar=pg});var nl=E(tl=>{"use strict";p();var tt=B(),el=Y(),kg=Pi(),$g=Ri();function Sg(t,e,n,s){let{value:r,type:i,comment:o,range:a}=e.type==="block-scalar"?kg.resolveBlockScalar(t,e,s):$g.resolveFlowScalar(e,t.options.strict,s),c=n?t.directives.tagName(n.source,u=>s(n,"TAG_RESOLVE_FAILED",u)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[tt.SCALAR]:c?l=vg(t.schema,r,c,n,s):e.type==="scalar"?l=Ag(t,r,e,s):l=t.schema[tt.SCALAR];let h;try{let u=l.resolve(r,f=>s(n??e,"TAG_RESOLVE_FAILED",f),t.options);h=tt.isScalar(u)?u:new el.Scalar(u)}catch(u){let f=u instanceof Error?u.message:String(u);s(n??e,"TAG_RESOLVE_FAILED",f),h=new el.Scalar(r)}return h.range=a,h.source=r,i&&(h.type=i),c&&(h.tag=c),l.format&&(h.format=l.format),o&&(h.comment=o),h}function vg(t,e,n,s,r){if(n==="!")return t[tt.SCALAR];let i=[];for(let a of t.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)i.push(a);else return a;for(let a of i)if(a.test?.test(e))return a;let o=t.knownTags[n];return o&&!o.collection?(t.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(r(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),t[tt.SCALAR])}function Ag({atKey:t,directives:e,schema:n},s,r,i){let o=n.tags.find(a=>(a.default===!0||t&&a.default==="key")&&a.test?.test(s))||n[tt.SCALAR];if(n.compat){let a=n.compat.find(c=>c.default&&c.test?.test(s))??n[tt.SCALAR];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),h=`Value may be parsed as either ${c} or ${l}`;i(r,"TAG_RESOLVE_FAILED",h,!0)}}return o}tl.composeScalar=Sg});var rl=E(sl=>{"use strict";p();function Eg(t,e,n){if(e){n??(n=e.length);for(let s=n-1;s>=0;--s){let r=e[s];switch(r.type){case"space":case"comment":case"newline":t-=r.source.length;continue}for(r=e[++s];r?.type==="space";)t+=r.source.length,r=e[++s];break}}return t}sl.emptyScalarPosition=Eg});var al=E(xi=>{"use strict";p();var _g=Ft(),Cg=B(),Ng=Hc(),il=nl(),Tg=wt(),Og=rl(),Ig={composeNode:ol,composeEmptyNode:Li};function ol(t,e,n,s){let r=t.atKey,{spaceBefore:i,comment:o,anchor:a,tag:c}=n,l,h=!0;switch(e.type){case"alias":l=Pg(t,e,s),(a||c)&&s(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=il.composeScalar(t,e,c,s),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":l=Ng.composeCollection(Ig,t,e,n,s),a&&(l.anchor=a.source.substring(1));break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;s(e,"UNEXPECTED_TOKEN",u),l=Li(t,e.offset,void 0,null,n,s),h=!1}}return a&&l.anchor===""&&s(a,"BAD_ALIAS","Anchor cannot be an empty string"),r&&t.options.stringKeys&&(!Cg.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&s(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),i&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),t.options.keepSourceTokens&&h&&(l.srcToken=e),l}function Li(t,e,n,s,{spaceBefore:r,comment:i,anchor:o,tag:a,end:c},l){let h={type:"scalar",offset:Og.emptyScalarPosition(e,n,s),indent:-1,source:""},u=il.composeScalar(t,h,a,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(u.spaceBefore=!0),i&&(u.comment=i,u.range[2]=c),u}function Pg({options:t},{offset:e,source:n,end:s},r){let i=new _g.Alias(n.substring(1));i.source===""&&r(e,"BAD_ALIAS","Alias cannot be an empty string"),i.source.endsWith(":")&&r(e+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+n.length,a=Tg.resolveEnd(s,o,t.strict,r);return i.range=[e,o,a.offset],a.comment&&(i.comment=a.comment),i}xi.composeEmptyNode=Li;xi.composeNode=ol});var ul=E(ll=>{"use strict";p();var jg=cn(),cl=al(),Rg=wt(),Lg=dn();function xg(t,e,{offset:n,start:s,value:r,end:i},o){let a=Object.assign({_directives:e},t),c=new jg.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},h=Lg.resolveProps(s,{indicator:"doc-start",next:r??i?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});h.found&&(c.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!h.hasNewline&&o(h.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=r?cl.composeNode(l,r,h,o):cl.composeEmptyNode(l,h.end,s,null,h,o);let u=c.contents.range[2],f=Rg.resolveEnd(i,u,!1,o);return f.comment&&(c.comment=f.comment),c.range=[n,u,f.offset],c}ll.composeDoc=xg});var Mi=E(pl=>{"use strict";p();var qg=jn("process"),Mg=vr(),Kg=cn(),pn=fn(),fl=B(),Dg=ul(),Bg=wt();function hn(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:n}=t;return[e,e+(typeof n=="string"?n.length:1)]}function dl(t){let e="",n=!1,s=!1;for(let r=0;r<t.length;++r){let i=t[r];switch(i[0]){case"#":e+=(e===""?"":s?`
|
|
102
102
|
|
|
103
103
|
`:`
|
|
104
|
-
`)+(i.substring(1)||" "),
|
|
105
|
-
${s}`:s;else if(r||e.directives.docStart||!i)e.commentBefore=s;else if(
|
|
104
|
+
`)+(i.substring(1)||" "),n=!0,s=!1;break;case"%":t[r+1]?.[0]!=="#"&&(r+=1),n=!1;break;default:n||(s=!0),n=!1}}return{comment:e,afterEmptyLine:s}}var qi=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,s,r,i)=>{let o=hn(n);i?this.warnings.push(new pn.YAMLWarning(o,s,r)):this.errors.push(new pn.YAMLParseError(o,s,r))},this.directives=new Mg.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,n){let{comment:s,afterEmptyLine:r}=dl(this.prelude);if(s){let i=e.contents;if(n)e.comment=e.comment?`${e.comment}
|
|
105
|
+
${s}`:s;else if(r||e.directives.docStart||!i)e.commentBefore=s;else if(fl.isCollection(i)&&!i.flow&&i.items.length>0){let o=i.items[0];fl.isPair(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${s}
|
|
106
106
|
${a}`:s}else{let o=i.commentBefore;i.commentBefore=o?`${s}
|
|
107
|
-
${o}`:s}}
|
|
108
|
-
${
|
|
107
|
+
${o}`:s}}n?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:dl(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,n=!1,s=-1){for(let r of e)yield*this.next(r);yield*this.end(n,s)}*next(e){switch(qg.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(n,s,r)=>{let i=hn(e);i[0]+=n,this.onError(i,"BAD_DIRECTIVE",s,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let n=Dg.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let n=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,s=new pn.YAMLParseError(hn(e),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(s):this.doc.errors.push(s);break}case"doc-end":{if(!this.doc){let s="Unexpected doc-end without preceding document";this.errors.push(new pn.YAMLParseError(hn(e),"UNEXPECTED_TOKEN",s));break}this.doc.directives.docEnd=!0;let n=Bg.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),n.comment){let s=this.doc.comment;this.doc.comment=s?`${s}
|
|
108
|
+
${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new pn.YAMLParseError(hn(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let s=Object.assign({_directives:this.directives},this.options),r=new Kg.Document(void 0,s);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,n,n],this.decorate(r,!1),yield r}}};pl.Composer=qi});var ml=E(Ts=>{"use strict";p();var Ug=Pi(),Gg=Ri(),Fg=fn(),hl=zt();function Wg(t,e=!0,n){if(t){let s=(r,i,o)=>{let a=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(n)n(a,i,o);else throw new Fg.YAMLParseError([a,a+1],i,o)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Gg.resolveFlowScalar(t,e,s);case"block-scalar":return Ug.resolveBlockScalar({options:{strict:e}},t,s)}}return null}function Yg(t,e){let{implicitKey:n=!1,indent:s,inFlow:r=!1,offset:i=-1,type:o="PLAIN"}=e,a=hl.stringifyString({type:o,value:t},{implicitKey:n,indent:s>0?" ".repeat(s):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:s,source:`
|
|
109
109
|
`}];switch(a[0]){case"|":case">":{let l=a.indexOf(`
|
|
110
|
-
`),
|
|
111
|
-
`,f=[{type:"block-scalar-header",offset:i,indent:s,source:
|
|
112
|
-
`}),{type:"block-scalar",offset:i,indent:s,props:f,source:u}}case'"':return{type:"double-quoted-scalar",offset:i,indent:s,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:i,indent:s,source:a,end:c};default:return{type:"scalar",offset:i,indent:s,source:a,end:c}}}function
|
|
113
|
-
`),s=e.substring(0,
|
|
114
|
-
`;if(
|
|
115
|
-
`});for(let c of Object.keys(
|
|
116
|
-
`};delete
|
|
110
|
+
`),h=a.substring(0,l),u=a.substring(l+1)+`
|
|
111
|
+
`,f=[{type:"block-scalar-header",offset:i,indent:s,source:h}];return gl(f,c)||f.push({type:"newline",offset:-1,indent:s,source:`
|
|
112
|
+
`}),{type:"block-scalar",offset:i,indent:s,props:f,source:u}}case'"':return{type:"double-quoted-scalar",offset:i,indent:s,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:i,indent:s,source:a,end:c};default:return{type:"scalar",offset:i,indent:s,source:a,end:c}}}function Vg(t,e,n={}){let{afterKey:s=!1,implicitKey:r=!1,inFlow:i=!1,type:o}=n,a="indent"in t?t.indent:null;if(s&&typeof a=="number"&&(a+=2),!o)switch(t.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=t.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=hl.stringifyString({type:o,value:e},{implicitKey:r||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Jg(t,c);break;case'"':Ki(t,c,"double-quoted-scalar");break;case"'":Ki(t,c,"single-quoted-scalar");break;default:Ki(t,c,"scalar")}}function Jg(t,e){let n=e.indexOf(`
|
|
113
|
+
`),s=e.substring(0,n),r=e.substring(n+1)+`
|
|
114
|
+
`;if(t.type==="block-scalar"){let i=t.props[0];if(i.type!=="block-scalar-header")throw new Error("Invalid block scalar header");i.source=s,t.source=r}else{let{offset:i}=t,o="indent"in t?t.indent:-1,a=[{type:"block-scalar-header",offset:i,indent:o,source:s}];gl(a,"end"in t?t.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
|
|
115
|
+
`});for(let c of Object.keys(t))c!=="type"&&c!=="offset"&&delete t[c];Object.assign(t,{type:"block-scalar",indent:o,props:a,source:r})}}function gl(t,e){if(e)for(let n of e)switch(n.type){case"space":case"comment":t.push(n);break;case"newline":return t.push(n),!0}return!1}function Ki(t,e,n){switch(t.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":t.type=n,t.source=e;break;case"block-scalar":{let s=t.props.slice(1),r=e.length;t.props[0].type==="block-scalar-header"&&(r-=t.props[0].source.length);for(let i of s)i.offset+=r;delete t.props,Object.assign(t,{type:n,source:e,end:s});break}case"block-map":case"block-seq":{let r={type:"newline",offset:t.offset+e.length,indent:t.indent,source:`
|
|
116
|
+
`};delete t.items,Object.assign(t,{type:n,source:e,end:[r]});break}default:{let s="indent"in t?t.indent:-1,r="end"in t&&Array.isArray(t.end)?t.end.filter(i=>i.type==="space"||i.type==="comment"||i.type==="newline"):[];for(let i of Object.keys(t))i!=="type"&&i!=="offset"&&delete t[i];Object.assign(t,{type:n,indent:s,source:e,end:r})}}}Ts.createScalarToken=Yg;Ts.resolveAsScalar=Wg;Ts.setScalarValue=Vg});var wl=E(yl=>{"use strict";p();var zg=t=>"type"in t?Is(t):Os(t);function Is(t){switch(t.type){case"block-scalar":{let e="";for(let n of t.props)e+=Is(n);return e+t.source}case"block-map":case"block-seq":{let e="";for(let n of t.items)e+=Os(n);return e}case"flow-collection":{let e=t.start.source;for(let n of t.items)e+=Os(n);for(let n of t.end)e+=n.source;return e}case"document":{let e=Os(t);if(t.end)for(let n of t.end)e+=n.source;return e}default:{let e=t.source;if("end"in t&&t.end)for(let n of t.end)e+=n.source;return e}}}function Os({start:t,key:e,sep:n,value:s}){let r="";for(let i of t)r+=i.source;if(e&&(r+=Is(e)),n)for(let i of n)r+=i.source;return s&&(r+=Is(s)),r}yl.stringify=zg});var Sl=E($l=>{"use strict";p();var Di=Symbol("break visit"),Hg=Symbol("skip children"),bl=Symbol("remove item");function nt(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),kl(Object.freeze([]),t,e)}nt.BREAK=Di;nt.SKIP=Hg;nt.REMOVE=bl;nt.itemAtPath=(t,e)=>{let n=t;for(let[s,r]of e){let i=n?.[s];if(i&&"items"in i)n=i.items[r];else return}return n};nt.parentCollection=(t,e)=>{let n=nt.itemAtPath(t,e.slice(0,-1)),s=e[e.length-1][0],r=n?.[s];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function kl(t,e,n){let s=n(e,t);if(typeof s=="symbol")return s;for(let r of["key","value"]){let i=e[r];if(i&&"items"in i){for(let o=0;o<i.items.length;++o){let a=kl(Object.freeze(t.concat([[r,o]])),i.items[o],n);if(typeof a=="number")o=a-1;else{if(a===Di)return Di;a===bl&&(i.items.splice(o,1),o-=1)}}typeof s=="function"&&r==="key"&&(s=s(e,t))}}return typeof s=="function"?s(e,t):s}$l.visit=nt});var Ps=E(ie=>{"use strict";p();var Bi=ml(),Qg=wl(),Zg=Sl(),Ui="\uFEFF",Gi="",Fi="",Wi="",Xg=t=>!!t&&"items"in t,em=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function tm(t){switch(t){case Ui:return"<BOM>";case Gi:return"<DOC>";case Fi:return"<FLOW_END>";case Wi:return"<SCALAR>";default:return JSON.stringify(t)}}function nm(t){switch(t){case Ui:return"byte-order-mark";case Gi:return"doc-mode";case Fi:return"flow-error-end";case Wi:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
117
117
|
`:case`\r
|
|
118
|
-
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(
|
|
119
|
-
`:case"\r":case" ":return!0;default:return!1}}var
|
|
120
|
-
\r `),
|
|
121
|
-
`?!0:
|
|
122
|
-
`:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let
|
|
123
|
-
`||!r&&!this.atEnd)return e+s+1}return
|
|
124
|
-
`||s>=this.indentNext||!
|
|
125
|
-
`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===
|
|
118
|
+
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(t[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}ie.createScalarToken=Bi.createScalarToken;ie.resolveAsScalar=Bi.resolveAsScalar;ie.setScalarValue=Bi.setScalarValue;ie.stringify=Qg.stringify;ie.visit=Zg.visit;ie.BOM=Ui;ie.DOCUMENT=Gi;ie.FLOW_END=Fi;ie.SCALAR=Wi;ie.isCollection=Xg;ie.isScalar=em;ie.prettyToken=tm;ie.tokenType=nm});var Ji=E(Al=>{"use strict";p();var gn=Ps();function de(t){switch(t){case void 0:case" ":case`
|
|
119
|
+
`:case"\r":case" ":return!0;default:return!1}}var vl=new Set("0123456789ABCDEFabcdef"),sm=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),js=new Set(",[]{}"),rm=new Set(` ,[]{}
|
|
120
|
+
\r `),Yi=t=>!t||rm.has(t),Vi=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,n=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!n;let s=this.next??"stream";for(;s&&(n||this.hasChars(1));)s=yield*this.parseNext(s)}atLineEnd(){let e=this.pos,n=this.buffer[e];for(;n===" "||n===" ";)n=this.buffer[++e];return!n||n==="#"||n===`
|
|
121
|
+
`?!0:n==="\r"?this.buffer[e+1]===`
|
|
122
|
+
`:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let n=this.buffer[e];if(this.indentNext>0){let s=0;for(;n===" ";)n=this.buffer[++s+e];if(n==="\r"){let r=this.buffer[s+e+1];if(r===`
|
|
123
|
+
`||!r&&!this.atEnd)return e+s+1}return n===`
|
|
124
|
+
`||s>=this.indentNext||!n&&!this.atEnd?e+s:-1}if(n==="-"||n==="."){let s=this.buffer.substr(e,3);if((s==="---"||s==="...")&&de(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
|
|
125
|
+
`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===gn.BOM&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let n=e.length,s=e.indexOf("#");for(;s!==-1;){let i=e[s-1];if(i===" "||i===" "){n=s-1;break}else s=e.indexOf("#",s+1)}for(;;){let i=e[n-1];if(i===" "||i===" ")n-=1;else break}let r=(yield*this.pushCount(n))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-r),this.pushNewline(),"stream"}if(this.atLineEnd()){let n=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-n),yield*this.pushNewline(),"stream"}return yield gn.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let n=this.peek(3);if((n==="---"||n==="...")&&de(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,n==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!de(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,n]=this.peek(2);if(!n&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&de(n)){let s=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=s,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let n=yield*this.pushIndicators();switch(e[n]){case"#":yield*this.pushCount(e.length-n);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Yi),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return n+=yield*this.parseBlockScalarHeader(),n+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-n),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,n,s=-1;do e=yield*this.pushNewline(),e>0?(n=yield*this.pushSpaces(!1),this.indentValue=s=n):n=0,n+=yield*this.pushSpaces(!0);while(e+n>0);let r=this.getLine();if(r===null)return this.setNext("flow");if((s!==-1&&s<this.indentNext&&r[0]!=="#"||s===0&&(r.startsWith("---")||r.startsWith("..."))&&de(r[3]))&&!(s===this.indentNext-1&&this.flowLevel===1&&(r[0]==="]"||r[0]==="}")))return this.flowLevel=0,yield gn.FLOW_END,yield*this.parseLineStart();let i=0;for(;r[i]===",";)i+=yield*this.pushCount(1),i+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(i+=yield*this.pushIndicators(),r[i]){case void 0:return"flow";case"#":return yield*this.pushCount(r.length-i),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(Yi),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||de(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),n=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;n!==-1&&this.buffer[n+1]==="'";)n=this.buffer.indexOf("'",n+2);else for(;n!==-1;){let i=0;for(;this.buffer[n-1-i]==="\\";)i+=1;if(i%2===0)break;n=this.buffer.indexOf('"',n+1)}let s=this.buffer.substring(0,n),r=s.indexOf(`
|
|
126
126
|
`,this.pos);if(r!==-1){for(;r!==-1;){let i=this.continueScalar(r+1);if(i===-1)break;r=s.indexOf(`
|
|
127
|
-
`,i)}r!==-1&&(
|
|
128
|
-
`:e=i,
|
|
129
|
-
`)break}default:break e}if(!s&&!this.atEnd)return this.setNext("block-scalar");if(
|
|
127
|
+
`,i)}r!==-1&&(n=r-(s[r-1]==="\r"?2:1))}if(n===-1){if(!this.atEnd)return this.setNext("quoted-scalar");n=this.buffer.length}return yield*this.pushToIndex(n+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let n=this.buffer[++e];if(n==="+")this.blockScalarKeep=!0;else if(n>"0"&&n<="9")this.blockScalarIndent=Number(n)-1;else if(n!=="-")break}return yield*this.pushUntil(n=>de(n)||n==="#")}*parseBlockScalar(){let e=this.pos-1,n=0,s;e:for(let i=this.pos;s=this.buffer[i];++i)switch(s){case" ":n+=1;break;case`
|
|
128
|
+
`:e=i,n=0;break;case"\r":{let o=this.buffer[i+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
|
|
129
|
+
`)break}default:break e}if(!s&&!this.atEnd)return this.setNext("block-scalar");if(n>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=n:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let i=this.continueScalar(e+1);if(i===-1)break;e=this.buffer.indexOf(`
|
|
130
130
|
`,i)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let r=e+1;for(s=this.buffer[r];s===" ";)s=this.buffer[++r];if(s===" "){for(;s===" "||s===" "||s==="\r"||s===`
|
|
131
131
|
`;)s=this.buffer[++r];e=r-1}else if(!this.blockScalarKeep)do{let i=e-1,o=this.buffer[i];o==="\r"&&(o=this.buffer[--i]);let a=i;for(;o===" ";)o=this.buffer[--i];if(o===`
|
|
132
|
-
`&&i>=this.pos&&i+1+
|
|
132
|
+
`&&i>=this.pos&&i+1+n>a)e=i;else break}while(!0);return yield gn.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,n=this.pos-1,s=this.pos-1,r;for(;r=this.buffer[++s];)if(r===":"){let i=this.buffer[s+1];if(de(i)||e&&js.has(i))break;n=s}else if(de(r)){let i=this.buffer[s+1];if(r==="\r"&&(i===`
|
|
133
133
|
`?(s+=1,r=`
|
|
134
|
-
`,i=this.buffer[s+1]):
|
|
135
|
-
`){let o=this.continueScalar(s+1);if(o===-1)break;s=Math.max(s,o-2)}}else{if(e&&
|
|
134
|
+
`,i=this.buffer[s+1]):n=s),i==="#"||e&&js.has(i))break;if(r===`
|
|
135
|
+
`){let o=this.continueScalar(s+1);if(o===-1)break;s=Math.max(s,o-2)}}else{if(e&&js.has(r))break;n=s}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield gn.SCALAR,yield*this.pushToIndex(n+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,n){let s=this.buffer.slice(this.pos,e);return s?(yield s,this.pos+=s.length,s.length):(n&&(yield""),0)}*pushIndicators(){switch(this.charAt(0)){case"!":return(yield*this.pushTag())+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"&":return(yield*this.pushUntil(Yi))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{let e=this.flowLevel>0,n=this.charAt(1);if(de(n)||e&&js.has(n))return e?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,(yield*this.pushCount(1))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators())}}return 0}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,n=this.buffer[e];for(;!de(n)&&n!==">";)n=this.buffer[++e];return yield*this.pushToIndex(n===">"?e+1:e,!1)}else{let e=this.pos+1,n=this.buffer[e];for(;n;)if(sm.has(n))n=this.buffer[++e];else if(n==="%"&&vl.has(this.buffer[e+1])&&vl.has(this.buffer[e+2]))n=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
|
|
136
136
|
`?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
|
|
137
|
-
`?yield*this.pushCount(2):0}*pushSpaces(e){let
|
|
138
|
-
`)+1;for(;
|
|
139
|
-
`,
|
|
140
|
-
`)+1;for(;
|
|
141
|
-
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=$s(e),s=mt(t);return s.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=$s(e),s=mt(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(s=>s.type==="newline"||s.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};ol.Parser=Di});var fl=S(un=>{"use strict";p();var al=Ni(),rm=en(),ln=sn(),im=Ar(),om=x(),am=Mi(),cl=Ki();function ll(n){let e=n.prettyErrors!==!1;return{lineCounter:n.lineCounter||e&&new am.LineCounter||null,prettyErrors:e}}function cm(n,e={}){let{lineCounter:t,prettyErrors:s}=ll(e),r=new cl.Parser(t?.addNewLine),i=new al.Composer(e),o=Array.from(i.compose(r.parse(n)));if(s&&t)for(let a of o)a.errors.forEach(ln.prettifyError(n,t)),a.warnings.forEach(ln.prettifyError(n,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}function ul(n,e={}){let{lineCounter:t,prettyErrors:s}=ll(e),r=new cl.Parser(t?.addNewLine),i=new al.Composer(e),o=null;for(let a of i.compose(r.parse(n),!0,n.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new ln.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return s&&t&&(o.errors.forEach(ln.prettifyError(n,t)),o.warnings.forEach(ln.prettifyError(n,t))),o}function lm(n,e,t){let s;typeof e=="function"?s=e:t===void 0&&e&&typeof e=="object"&&(t=e);let r=ul(n,t);if(!r)return null;if(r.warnings.forEach(i=>im.warn(r.options.logLevel,i)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:s},t))}function um(n,e,t){let s=null;if(typeof e=="function"||Array.isArray(e)?s=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){let r=Math.round(t);t=r<1?void 0:r>8?{indent:8}:{indent:r}}if(n===void 0){let{keepUndefined:r}=t??e??{};if(!r)return}return om.isDocument(n)&&!s?n.toString(t):new rm.Document(n,s,t).toString(t)}un.parse=lm;un.parseAllDocuments=cm;un.parseDocument=ul;un.stringify=um});var pl=S(K=>{"use strict";p();var fm=Ni(),dm=en(),pm=oi(),Bi=sn(),hm=xt(),xe=x(),mm=Pe(),gm=Y(),ym=Le(),wm=qe(),bm=bs(),km=Ri(),$m=Mi(),Sm=Ki(),Ss=fl(),dl=jt();K.Composer=fm.Composer;K.Document=dm.Document;K.Schema=pm.Schema;K.YAMLError=Bi.YAMLError;K.YAMLParseError=Bi.YAMLParseError;K.YAMLWarning=Bi.YAMLWarning;K.Alias=hm.Alias;K.isAlias=xe.isAlias;K.isCollection=xe.isCollection;K.isDocument=xe.isDocument;K.isMap=xe.isMap;K.isNode=xe.isNode;K.isPair=xe.isPair;K.isScalar=xe.isScalar;K.isSeq=xe.isSeq;K.Pair=mm.Pair;K.Scalar=gm.Scalar;K.YAMLMap=ym.YAMLMap;K.YAMLSeq=wm.YAMLSeq;K.CST=bm;K.Lexer=km.Lexer;K.LineCounter=$m.LineCounter;K.Parser=Sm.Parser;K.parse=Ss.parse;K.parseAllDocuments=Ss.parseAllDocuments;K.parseDocument=Ss.parseDocument;K.stringify=Ss.stringify;K.visit=dl.visit;K.visitAsync=dl.visitAsync});p();import{parseArgs as Ig}from"node:util";p();import{existsSync as Hm,readFileSync as Qm}from"node:fs";import{join as Xm}from"node:path";p();p();p();function go(n,e,t=s=>s.length>0&&s.length<=100){let s=[];if(typeof n!="object"||n===null||Array.isArray(n))return{rule:null,problems:[`${e}: rows should map a field to a value, e.g. rows: { rep_email: $me }.`]};let r=Object.entries(n);r.length||s.push(`${e}: rows is empty. Leave it out to grant every row.`);let i={},o=a=>typeof a=="string"||typeof a=="number"||typeof a=="boolean";for(let[a,c]of r)t(a)||s.push(`${e}: "${a}" isn't a field name rows can use.`),Array.isArray(c)?!c.length||!c.every(o)?s.push(`${e}.${a}: give one value, or a list of values, e.g. [won, lost].`):i[a]=[...new Set(c.map(l=>typeof l=="string"?l.trim():l))].sort((l,d)=>String(l).localeCompare(String(d))):o(c)?i[a]=typeof c=="string"?c.trim():c:s.push(`${e}.${a}: give a value (text, a number, true/false or $me), or a list of them.`);return{rule:s.length?null:i,problems:s}}var An="*";p();p();var ue=[{id:"claude-code",name:"Claude Code",where:"terminal and IDEs",documents:["https://claude.ai/oauth/claude-code-client-metadata"]},{id:"claude",name:"Claude",where:"claude.ai, desktop and mobile apps",documents:["https://claude.ai/oauth/mcp-oauth-client-metadata"]},{id:"codex",name:"Codex",where:"OpenAI's CLI and IDE extension",documents:["https://chatgpt.com/oauth/codex/client.json","https://chatgpt.com/oauth/codex/*/client.json"]},{id:"chatgpt",name:"ChatGPT",where:"chatgpt.com and its apps, including Codex there",documents:["https://chatgpt.com/oauth/client.json"]},{id:"vscode",name:"VS Code",where:"GitHub Copilot's agent mode",documents:["https://vscode.dev/oauth/client-metadata.json"]},{id:"cursor",name:"Cursor",where:"Cursor's editor and cloud agents",documents:["https://cursor.com/oauth/mcp-client.json"]},{id:"lovable",name:"Lovable",where:"Lovable's workspace connectors",documents:["https://api.lovable.dev/.well-known/oauth-client"]},{id:"replit",name:"Replit",where:"Replit Agent's MCP servers",documents:[],notYet:"signs in without a metadata document"},{id:"bolt",name:"Bolt",where:"Bolt's connectors",documents:[],notYet:"signs in without a metadata document"},{id:"v0",name:"v0",where:"Vercel's v0",documents:[],notYet:"custom MCP sign-in unconfirmed"}],yo=ue.filter(n=>!n.notYet),Ce=["claude-code","claude"],wo=new Map(ue.map(n=>[n.id,n])),En=n=>wo.get(n);function bo(n){let e;try{e=new URL(n)}catch{return!1}return e.protocol==="https:"&&e.pathname.length>1&&!e.hash&&!e.username&&!e.password&&e.href===n}var It=n=>wo.get(n)?.name??n;var Mu="*",rt=class extends Error{name="PolicyFileError";problems;constructor(e){super(`policy.yaml has ${e.length===1?"a problem":`${e.length} problems`}:
|
|
142
|
-
${e.map(
|
|
143
|
-
`)}`),this.problems=e}},Du=new Set(["Viewer","Builder","Admin"]),ko=new Set(["notion","postgres"]),$o=/^[A-Za-z_][A-Za-z0-9_]{0,62}$/,Ku=/^[a-z][a-z0-9-]{1,30}$/,Bu=/^[a-z][a-z0-9_-]{0,40}$/,Gu=/^(?:projects\/[a-z][a-z0-9-]{4,28}[a-z0-9]\/secrets\/)?[A-Za-z0-9_-]{1,255}$/,Uu=n=>/^(ntn_|secret_|sk-|sk_live_|sk_test_|rk_live_|ghp_|gho_|github_pat_|xox[abpr]-|AKIA|ASIA|AIza|ya29\.)/.test(n)||n.length>=32&&/[A-Z]/.test(n)&&/[a-z]/.test(n)&&/[0-9]/.test(n)&&!/[-_].*[-_]/.test(n),Fu=n=>{let e=n.split("/").pop();return e.startsWith("kuriko-")&&!e.startsWith("kuriko-connector-")},Yu=new Set(["roles","connectors","access","clients"]);function So(n){let e=n.trim();return e.toLowerCase()==="everyone"?An:e.includes("@")?e.toLowerCase():e}var Ot=n=>n===An?"everyone":n,st=n=>typeof n=="object"&&n!==null&&!Array.isArray(n),Tt=n=>[...new Set(n)].sort();function vo(n,e){let t=[],s={roles:[],connectors:[],grants:[],clients:[]};if(n==null&&(n={}),!st(n))throw new rt(["The file should be a map with roles, connectors, access and clients."]);for(let d of Object.keys(n))Yu.has(d)||t.push(`Unknown section "${d}" (expected roles, connectors, access, clients).`);let r=n.roles??{};if(!st(r))t.push("roles should map a group to Admin, Builder or Viewer.");else for(let[d,u]of Object.entries(r)){let f=So(d);f===An?t.push("roles: everyone can't be given a role (roles need a real group)."):typeof u!="string"||!Du.has(u)?t.push(`roles: ${d} should be Admin, Builder or Viewer, not ${JSON.stringify(u)}.`):s.roles.some(h=>h.group===f)?t.push(`roles: ${d} is listed twice.`):s.roles.push({group:f,role:u})}let i=n.connectors??{},o=new Map,a=new Set;if(!st(i))t.push("connectors should map an id (e.g. notion) to its settings.");else for(let[d,u]of Object.entries(i)){let f=`connectors.${d}`;if(Ku.test(d)||t.push(`${f}: the id should be lowercase letters, digits and dashes.`),!st(u)){t.push(`${f} should have a name and a kind.`);continue}let h=typeof u.kind=="string"&&ko.has(u.kind)?u.kind:null;h||t.push(`${f}: kind should be one of ${[...ko].join(", ")}.`);let y=u.credentials==="per-person";u.credentials!==void 0&&u.credentials!=="shared"&&!y&&t.push(`${f}: credentials should be shared or per-person.`),y&&h!=="notion"&&t.push(`${f}: only notion can be per-person so far.`);let m=new Set(h==="notion"?["name","kind","secret","resources","credentials",...y?["oauth_client_id"]:[]]:h==="postgres"?["name","kind","secret","schema","credentials"]:["name","kind"]);for(let E of Object.keys(u))m.has(E)||t.push(`${f}: unknown setting "${E}".`);let w=typeof u.name=="string"&&u.name.trim()?u.name.trim():null;w||t.push(`${f}: needs a name.`);let A=null;if(h==="notion"||h==="postgres"){let E=y?"the OAuth client secret":h==="postgres"?"the connection URL":"the integration token";typeof u.secret!="string"||!Gu.test(u.secret)?t.push(`${f}: secret should name the secret in Secret Manager holding ${E} (e.g. warehouse-readonly, or projects/<project>/secrets/<name>), never the secret itself.`):Uu(u.secret.split("/").pop())?t.push(`${f}: secret looks like a credential itself. Put it in Secret Manager and name the secret here instead (then rotate it: it's been in this file).`):Fu(u.secret)?t.push(`${f}: ${u.secret} is one of Kuriko's own secrets; a data source needs its own credential.`):A=u.secret}let $={};if(h==="notion"){let E=u.resources??{};if(!st(E))t.push(`${f}.resources should map a name tools use to a Notion data source ID.`);else{for(let[N,g]of Object.entries(E))Bu.test(N)||t.push(`${f}.resources: "${N}" should be lowercase letters, digits, - and _.`),(typeof g!="string"||g.trim().length<8)&&t.push(`${f}.resources.${N} should be a Notion data source ID.`);$={resources:Object.fromEntries(Object.entries(E).map(([N,g])=>[N,String(g).trim()]).sort(([N],[g])=>N.localeCompare(g)))},o.set(d,new Set(Object.keys(E)))}y&&(typeof u.oauth_client_id!="string"||!/^[A-Za-z0-9-]{8,100}$/.test(u.oauth_client_id)?t.push(`${f}: oauth_client_id should be the OAuth client ID of your Notion public integration.`):$.oauthClientId=u.oauth_client_id)}else h==="postgres"&&(u.schema!==void 0&&(typeof u.schema!="string"||!u.schema)&&t.push(`${f}.schema should be a schema name.`),$={schema:typeof u.schema=="string"&&u.schema?u.schema:"public"},o.set(d,null),a.add(d));w&&h&&A&&s.connectors.push({id:d,name:w,kind:h,config:$,mode:y?"delegated":"service",secretRef:e(A)})}let c=n.access??[];Array.isArray(c)?c.forEach((d,u)=>{let f=`access[${u+1}]`;if(!st(d))return void t.push(`${f} should have group, connector, resources and access.`);for(let g of Object.keys(d))["group","connector","resources","access","mask","rows"].includes(g)||t.push(`${f}: unknown setting "${g}".`);let h=typeof d.group=="string"&&d.group.trim()?So(d.group):null;h||t.push(`${f}: needs a group (a group email, or everyone).`);let y=typeof d.connector=="string"?d.connector:"";o.has(y)||t.push(`${f}: there's no connector "${y}" in connectors.`);let m=Array.isArray(d.resources)?d.resources.filter(g=>typeof g=="string"):typeof d.resources=="string"?[d.resources]:[];(!m.length||Array.isArray(d.resources)&&m.length!==d.resources.length)&&t.push(`${f}: resources should list what's granted, e.g. [interviews].`);let w=o.get(y);if(w)for(let g of m)w.has(g)||t.push(`${f}: ${y} has no resource "${g}" (it has: ${[...w].join(", ")||"none"}).`);if(w===null)for(let g of m)g!==Mu&&!$o.test(g)&&t.push(`${f}: "${g}" isn't a table name (or "*" for every table).`);a.has(y)&&d.access==="write"&&t.push(`${f}: ${y} is read-only in Kuriko; use access: read.`),d.access!=="read"&&d.access!=="write"&&t.push(`${f}: access should be read or write (write includes read).`);let A=d.mask===void 0?[]:Array.isArray(d.mask)&&d.mask.every(g=>typeof g=="string")?d.mask:null;A||t.push(`${f}: mask should be a list of field names.`);let $=d.rows===void 0||d.rows===null?{rule:void 0,problems:[]}:go(d.rows,`${f}.rows`,w===null?g=>$o.test(g):void 0);if(t.push(...$.problems),!h||!y||!m.length||!A||$.rule===null||d.access!=="read"&&d.access!=="write")return;let E=s.grants.filter(g=>g.group===h&&g.connector===y&&g.access===d.access),N=m.filter(g=>E.some(O=>O.resources.includes(g)));if(N.length)return void t.push(`${f}: ${Ot(h)} already has ${d.access} on ${y}: ${N.join(", ")}. A table can be in one ${d.access} grant per group.`);if(E.some(g=>JSON.stringify(g.rows??null)===JSON.stringify($.rule??null)))return void t.push(`${f}: ${Ot(h)} already has ${d.access} on ${y}${$.rule?" with the same rows":""}; put the resources in one grant.`);s.grants.push({group:h,connector:y,resources:Tt(m),access:d.access,mask:Tt(A),...$.rule?{rows:$.rule}:{}})}):t.push("access should be a list of grants.");let l=n.clients===void 0||n.clients===null?[...Ce]:n.clients;if(Array.isArray(l)?l.forEach((d,u)=>{let f=`clients[${u+1}]`;if(typeof d!="string"||!d.trim())return void t.push(`${f} should be a client's name or its metadata document URL.`);let h=d.trim(),y=En(h);if(y?.notYet)return void t.push(`${f}: ${y.name} can't connect to Kuriko yet (${y.notYet}). Leave it commented out for now.`);if(!y&&!bo(h))return void t.push(/^https?:/.test(h)?`${f}: ${h} isn't a client metadata document URL (https, with a path).`:`${f}: Kuriko doesn't know a client called "${h}". Use one of ${yo.map(m=>m.id).join(", ")}, or the client's metadata document URL.`);if(s.clients.includes(h))return void t.push(`${f}: ${h} is listed twice.`);s.clients.push(h)}):t.push("clients should be a list, e.g. [claude-code, codex]."),t.length)throw new rt(t);return ar(s)}var Pt=n=>Array.isArray(n)?n.map(Pt):n&&typeof n=="object"?Object.fromEntries(Object.keys(n).sort().map(e=>[e,Pt(n[e])])):n;function ar(n){let e=t=>(s,r)=>t(s).localeCompare(t(r));return{roles:n.roles.map(({group:t,role:s})=>({group:t,role:s})).sort(e(t=>t.group)),connectors:n.connectors.map(({id:t,name:s,kind:r,mode:i,secretRef:o,config:a})=>({id:t,name:s,kind:r,mode:i,secretRef:o,config:Pt(a)})).sort(e(t=>t.id)),grants:n.grants.map(({group:t,connector:s,resources:r,access:i,mask:o,rows:a})=>({group:t,connector:s,resources:Tt(r),access:i,mask:Tt(o),...a?{rows:Pt(a)}:{}})).sort(e(Vu)),clients:Tt(n.clients??[...Ce])}}var Vu=n=>`${n.connector}\0${n.group}\0${n.access}\0${JSON.stringify(n.rows?Pt(n.rows):null)}`;function Ao(n,e){let t=[],s=a=>typeof a=="string"?a:JSON.stringify(a);for(let a of["name","kind","mode","secretRef"])n[a]!==e[a]&&t.push(`${a} ${s(n[a])} \u2192 ${s(e[a])}`);let r=(a,c="")=>Object.entries(a).flatMap(([l,d])=>d&&typeof d=="object"&&!Array.isArray(d)?r(d,`${c}${l}.`):[[`${c}${l}`,d]]),i=new Map(r(n.config)),o=new Map(r(e.config));for(let a of new Set([...i.keys(),...o.keys()]))JSON.stringify(i.get(a))!==JSON.stringify(o.get(a))&&t.push(`${a} ${i.has(a)?s(i.get(a)):"(none)"} \u2192 ${o.has(a)?s(o.get(a)):"(none)"}`);return t.length?t:["(settings differ only in form)"]}var Ue=(n,e)=>{let t=/^projects\/([^/]+)\/secrets\/(.+)$/.exec(n);return t&&(!e||t[1]===e)?t[2]:n};function Nn(n){switch(n.kind){case"role":return n.op==="add"?`${n.group} becomes ${n.to}`:n.op==="change"?`${n.group}: ${n.from} \u2192 ${n.to}`:`${n.group} is no longer ${n.from}`;case"connector":return`data source ${n.id}: ${n.summary}`;case"grant":return`${Ot(n.group)}: ${n.summary}`;case"client":return n.op==="add"?`people can connect with ${It(n.client)}`:`people can no longer connect with ${It(n.client)}`}}p();import{spawn as Ju}from"node:child_process";import{stripVTControlCharacters as Wu}from"node:util";var Q=class extends Error{command;code;stderr;constructor(e,t,s){let r=Wu(s);super(`${e} failed (exit ${t})${r.trim()?`:
|
|
137
|
+
`?yield*this.pushCount(2):0}*pushSpaces(e){let n=this.pos-1,s;do s=this.buffer[++n];while(s===" "||e&&s===" ");let r=n-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=n),r}*pushUntil(e){let n=this.pos,s=this.buffer[n];for(;!e(s);)s=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};Al.Lexer=Vi});var Hi=E(El=>{"use strict";p();var zi=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let n=0,s=this.lineStarts.length;for(;n<s;){let i=n+s>>1;this.lineStarts[i]<e?n=i+1:s=i}if(this.lineStarts[n]===e)return{line:n+1,col:1};if(n===0)return{line:0,col:e};let r=this.lineStarts[n-1];return{line:n,col:e-r+1}}}};El.LineCounter=zi});var Zi=E(Ol=>{"use strict";p();var im=jn("process"),_l=Ps(),om=Ji();function De(t,e){for(let n=0;n<t.length;++n)if(t[n].type===e)return!0;return!1}function Cl(t){for(let e=0;e<t.length;++e)switch(t[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}function Tl(t){switch(t?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Rs(t){switch(t.type){case"document":return t.start;case"block-map":{let e=t.items[t.items.length-1];return e.sep??e.start}case"block-seq":return t.items[t.items.length-1].start;default:return[]}}function bt(t){if(t.length===0)return[];let e=t.length;e:for(;--e>=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function Nl(t){if(t.start.type==="flow-seq-start")for(let e of t.items)e.sep&&!e.value&&!De(e.start,"explicit-key-ind")&&!De(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,Tl(e.value)?e.value.end?Array.prototype.push.apply(e.value.end,e.sep):e.value.end=e.sep:Array.prototype.push.apply(e.start,e.sep),delete e.sep)}var Qi=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new om.Lexer,this.onNewLine=e}*parse(e,n=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let s of this.lexer.lex(e,n))yield*this.next(s);n||(yield*this.end())}*next(e){if(this.source=e,im.env.LOG_TOKENS&&console.log("|",_l.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let n=_l.tokenType(e);if(n)if(n==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=n,yield*this.step(),n){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{let s=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:s,source:e}),this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&(!e||e.type!=="doc-end")){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let n=e??this.stack.pop();if(!n)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield n;else{let s=this.peek(1);switch(n.type==="block-scalar"?n.indent="indent"in s?s.indent:0:n.type==="flow-collection"&&s.type==="document"&&(n.indent=0),n.type==="flow-collection"&&Nl(n),s.type){case"document":s.value=n;break;case"block-scalar":s.props.push(n);break;case"block-map":{let r=s.items[s.items.length-1];if(r.value){s.items.push({start:[],key:n,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=n;else{Object.assign(r,{key:n,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{let r=s.items[s.items.length-1];r.value?s.items.push({start:[],value:n}):r.value=n;break}case"flow-collection":{let r=s.items[s.items.length-1];!r||r.value?s.items.push({start:[],key:n,sep:[]}):r.sep?r.value=n:Object.assign(r,{key:n,sep:[]});return}default:yield*this.pop(),yield*this.pop(n)}if((s.type==="document"||s.type==="block-map"||s.type==="block-seq")&&(n.type==="block-map"||n.type==="block-seq")){let r=n.items[n.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&Cl(r.start)===-1&&(n.indent===0||r.start.every(i=>i.type!=="comment"||i.indent<n.indent))&&(s.type==="document"?s.end=r.start:s.items.push({start:r.start}),n.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{Cl(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){let n=Rs(this.peek(2)),s=bt(n),r;e.end?(r=e.end,r.push(this.sourceToken),delete e.end):r=[this.sourceToken];let i={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let n=this.source.indexOf(`
|
|
138
|
+
`)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`
|
|
139
|
+
`,n)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let n=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,n.value){let s="end"in n.value?n.value.end:void 0;(Array.isArray(s)?s[s.length-1]:void 0)?.type==="comment"?s?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)e.items.push({start:[this.sourceToken]});else if(n.sep)n.sep.push(this.sourceToken);else{if(this.atIndentedComment(n.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Array.prototype.push.apply(r,n.start),r.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let s=!this.onKeyLine&&this.indent===e.indent,r=s&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",i=[];if(r&&n.sep&&!n.value){let o=[];for(let a=0;a<n.sep.length;++a){let c=n.sep[a];switch(c.type){case"newline":o.push(a);break;case"space":break;case"comment":c.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(i=n.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":r||n.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"explicit-key-ind":!n.sep&&!n.explicitKey?(n.start.push(this.sourceToken),n.explicitKey=!0):r||n.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(n.explicitKey)if(n.sep)if(n.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(De(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(Tl(n.key)&&!De(n.sep,"newline")){let o=bt(n.start),a=n.key,c=n.sep;c.push(this.sourceToken),delete n.key,delete n.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else i.length>0?n.sep=n.sep.concat(i,this.sourceToken):n.sep.push(this.sourceToken);else if(De(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let o=bt(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):De(n.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);r||n.value?(e.items.push({start:i,key:o,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(o):(Object.assign(n,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!n.explicitKey&&n.sep&&!De(n.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else s&&e.items.push({start:i});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let n=e.items[e.items.length-1];switch(this.type){case"newline":if(n.value){let s="end"in n.value?n.value.end:void 0;(Array.isArray(s)?s[s.length-1]:void 0)?.type==="comment"?s?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Array.prototype.push.apply(r,n.start),r.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=e.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;n.value||De(n.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>e.indent){let s=this.startBlockValue(e);if(s){this.stack.push(s);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let n=e.items[e.items.length-1];if(this.type==="flow-error-end"){let s;do yield*this.pop(),s=this.peek(1);while(s&&s.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!n||n.value?e.items.push({start:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let r=this.flowScalar(this.type);!n||n.value?e.items.push({start:[],key:r,sep:[]}):n.sep?this.stack.push(r):Object.assign(n,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let s=this.startBlockValue(e);s?this.stack.push(s):(yield*this.pop(),yield*this.step())}else{let s=this.peek(2);if(s.type==="block-map"&&(this.type==="map-value-ind"&&s.indent===e.indent||this.type==="newline"&&!s.items[s.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&s.type!=="flow-collection"){let r=Rs(s),i=bt(r);Nl(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:i,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let n=this.source.indexOf(`
|
|
140
|
+
`)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`
|
|
141
|
+
`,n)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=Rs(e),s=bt(n);return s.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=Rs(e),s=bt(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,n){return this.type!=="comment"||this.indent<=n?!1:e.every(s=>s.type==="newline"||s.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Ol.Parser=Qi});var Ll=E(yn=>{"use strict";p();var Il=Mi(),am=cn(),mn=fn(),cm=xr(),lm=B(),um=Hi(),Pl=Zi();function jl(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new um.LineCounter||null,prettyErrors:e}}function fm(t,e={}){let{lineCounter:n,prettyErrors:s}=jl(e),r=new Pl.Parser(n?.addNewLine),i=new Il.Composer(e),o=Array.from(i.compose(r.parse(t)));if(s&&n)for(let a of o)a.errors.forEach(mn.prettifyError(t,n)),a.warnings.forEach(mn.prettifyError(t,n));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}function Rl(t,e={}){let{lineCounter:n,prettyErrors:s}=jl(e),r=new Pl.Parser(n?.addNewLine),i=new Il.Composer(e),o=null;for(let a of i.compose(r.parse(t),!0,t.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new mn.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return s&&n&&(o.errors.forEach(mn.prettifyError(t,n)),o.warnings.forEach(mn.prettifyError(t,n))),o}function dm(t,e,n){let s;typeof e=="function"?s=e:n===void 0&&e&&typeof e=="object"&&(n=e);let r=Rl(t,n);if(!r)return null;if(r.warnings.forEach(i=>cm.warn(r.options.logLevel,i)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:s},n))}function pm(t,e,n){let s=null;if(typeof e=="function"||Array.isArray(e)?s=e:n===void 0&&e&&(n=e),typeof n=="string"&&(n=n.length),typeof n=="number"){let r=Math.round(n);n=r<1?void 0:r>8?{indent:8}:{indent:r}}if(t===void 0){let{keepUndefined:r}=n??e??{};if(!r)return}return lm.isDocument(t)&&!s?t.toString(n):new am.Document(t,s,n).toString(n)}yn.parse=dm;yn.parseAllDocuments=fm;yn.parseDocument=Rl;yn.stringify=pm});var ql=E(G=>{"use strict";p();var hm=Mi(),gm=cn(),mm=wi(),Xi=fn(),ym=Ft(),Be=B(),wm=xe(),bm=Y(),km=Me(),$m=Ke(),Sm=Ps(),vm=Ji(),Am=Hi(),Em=Zi(),Ls=Ll(),xl=Dt();G.Composer=hm.Composer;G.Document=gm.Document;G.Schema=mm.Schema;G.YAMLError=Xi.YAMLError;G.YAMLParseError=Xi.YAMLParseError;G.YAMLWarning=Xi.YAMLWarning;G.Alias=ym.Alias;G.isAlias=Be.isAlias;G.isCollection=Be.isCollection;G.isDocument=Be.isDocument;G.isMap=Be.isMap;G.isNode=Be.isNode;G.isPair=Be.isPair;G.isScalar=Be.isScalar;G.isSeq=Be.isSeq;G.Pair=wm.Pair;G.Scalar=bm.Scalar;G.YAMLMap=km.YAMLMap;G.YAMLSeq=$m.YAMLSeq;G.CST=Sm;G.Lexer=vm.Lexer;G.LineCounter=Am.LineCounter;G.Parser=Em.Parser;G.parse=Ls.parse;G.parseAllDocuments=Ls.parseAllDocuments;G.parseDocument=Ls.parseDocument;G.stringify=Ls.stringify;G.visit=xl.visit;G.visitAsync=xl.visitAsync});p();import{parseArgs as Zy}from"node:util";p();import{existsSync as gy,readFileSync as my}from"node:fs";import{join as yy}from"node:path";p();p();p();function Ro(t,e,n=s=>s.length>0&&s.length<=100){let s=[];if(typeof t!="object"||t===null||Array.isArray(t))return{rule:null,problems:[`${e}: rows should map a field to a value, e.g. rows: { rep_email: $me }.`]};let r=Object.entries(t);r.length||s.push(`${e}: rows is empty. Leave it out to grant every row.`);let i={},o=a=>typeof a=="string"||typeof a=="number"||typeof a=="boolean";for(let[a,c]of r)n(a)||s.push(`${e}: "${a}" isn't a field name rows can use.`),Array.isArray(c)?!c.length||!c.every(o)?s.push(`${e}.${a}: give one value, or a list of values, e.g. [won, lost].`):i[a]=[...new Set(c.map(l=>typeof l=="string"?l.trim():l))].sort((l,h)=>String(l).localeCompare(String(h))):o(c)?i[a]=typeof c=="string"?c.trim():c:s.push(`${e}.${a}: give a value (text, a number, true/false or $me), or a list of them.`);return{rule:s.length?null:i,problems:s}}var Rn="*";p();p();var Of=/^[a-z][a-z0-9_-]{0,40}$/,Lo=/^[A-Za-z0-9-]{1,64}$/,If=new Set(["authorization","proxy-authorization","cookie","host","content-length","content-type","transfer-encoding","connection","user-agent"]),Ln=/^[A-Za-z0-9_$@-]+(\.[A-Za-z0-9_$@-]+)*$/,qo=/^[A-Za-z0-9_.[\]-]{1,64}$/,Mo=2e4;function xo(t){let e;try{e=new URL(t)}catch{return"isn't a URL"}if(e.protocol!=="https:")return"should start with https://";if(e.username||e.password)return"shouldn't have a user or password in it";let n=e.hostname.toLowerCase();return/^\[|^[0-9.]+$/.test(n)?"should be a hostname, not an IP address":!n.includes(".")||/(^|\.)(localhost|internal|local|localdomain|home\.arpa)$/.test(n)?"should be a public hostname":null}function Pf(t,e){let n=new URL(t+e);return jf(t,n)?n:null}function jf(t,e){let n=new URL(t),s=n.pathname.replace(/\/$/,"");return e.protocol==="https:"&&e.origin===n.origin&&!e.username&&!e.password&&(e.pathname===s||e.pathname.startsWith(s+"/")||!s)}var ge=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function Ko(t,e,n){let s=[],r={base_url:"",resources:{}},i=typeof t.base_url=="string"?xo(t.base_url.trim()):"is missing";if(i)s.push(`${e}: base_url ${i} (e.g. https://api.hubapi.com).`);else{let c=new URL(t.base_url.trim());(c.search||c.hash)&&s.push(`${e}: base_url shouldn't have a ? or # part; put query settings in each resource's path.`),r.base_url=`${c.origin}${c.pathname.replace(/\/+$/,"")}`}if(n)t.auth!==void 0&&s.push(`${e}: a per-person source signs in with each person's own token; leave auth out.`);else if(t.auth!==void 0){let c=typeof t.auth=="string"?t.auth.trim():"",l=/^header\s+(\S+)$/i.exec(c)?.[1];c==="bearer"||c==="basic"?r.auth=c:l&&Lo.test(l)&&!["cookie","host"].includes(l.toLowerCase())?r.auth=`header ${l}`:s.push(`${e}: auth should be bearer, basic, or header <Name> (e.g. header X-Api-Key).`)}if(t.headers!==void 0)if(!ge(t.headers))s.push(`${e}.headers should map a header name to its value.`);else{let c={};for(let[l,h]of Object.entries(t.headers)){let u=typeof h=="number"?String(h):h;Lo.test(l)?If.has(l.toLowerCase())?s.push(`${e}.headers: Kuriko sets ${l} itself${/auth/i.test(l)?" (the credential goes in Secret Manager: name it in secret)":""}.`):typeof u!="string"||/[\r\n]/.test(u)||u.length>500?s.push(`${e}.headers.${l} should be one line of text.`):xn(u)||/key|token|secret|auth/i.test(l)?s.push(`${e}.headers.${l} looks like it carries a credential. Put it in Secret Manager and use auth: header ${l}.`):c[l]=u:s.push(`${e}.headers: "${l}" isn't a header name.`)}Object.keys(c).length&&(r.headers=c)}let o=t.resources;if(!ge(o)||!Object.keys(o).length)s.push(`${e}.resources should map a name tools use to the API path that lists it.`);else for(let[c,l]of Object.entries(o)){let h=`${e}.resources.${c}`;Of.test(c)||s.push(`${e}.resources: "${c}" should be lowercase letters, digits, - and _.`);let u=typeof l=="string"?{path:l}:l;if(!ge(u)){s.push(`${h} should be a path (e.g. /v1/contacts), or settings with a path.`);continue}for(let m of Object.keys(u))["path","method","body","rows","next","add"].includes(m)||s.push(`${h}: unknown setting "${m}".`);let f={path:""},d=Do(u.path,r.base_url,h,"/crm/v3/objects/contacts?limit=100",s);if(d&&(f.path=d),u.method!==void 0){let m=typeof u.method=="string"?u.method.toUpperCase():"";m!=="GET"&&m!=="POST"?s.push(`${h}: method should be GET or POST (POST for search or GraphQL endpoints). It's how the resource is listed; adding rows goes under add.`):m==="POST"&&(f.method="POST")}if(u.body!==void 0&&(f.method!=="POST"?s.push(`${h}: a body needs method: POST.`):ge(u.body)?JSON.stringify(u.body).length>Mo?s.push(`${h}.body is too long.`):f.body=u.body:s.push(`${h}.body should be the JSON object sent.`)),u.rows!==void 0&&(typeof u.rows!="string"||!Ln.test(u.rows)?s.push(`${h}: rows should say where the list is in the answer, e.g. results or data.items.`):f.rows=u.rows),u.next!==void 0){let m=Mf(u.next,`${h}.next`,f.method==="POST",s);m&&(f.next=m)}if(u.add!==void 0){let m=qf(u.add,`${h}.add`,r.base_url,s);m&&(f.add=m)}r.resources[c]=f}if(n){let c=t.oauth;if(!ge(c))s.push(`${e}: a per-person source needs oauth (authorize_url, token_url, client_id, scopes).`);else{for(let f of Object.keys(c))["authorize_url","token_url","client_id","scopes","scope_separator","authorize_params","client_auth","account"].includes(f)||s.push(`${e}.oauth: unknown setting "${f}".`);let l={};for(let f of["authorize_url","token_url"]){let d=typeof c[f]=="string"?xo(c[f].trim()):"is missing";d?s.push(`${e}.oauth: ${f} ${d}.`):l[f]=c[f].trim()}let h=Rf(c.client_id,e,s);h&&(l.client_id=h);let u=Lf(c.scopes,e,s);if(u&&(l.scopes=u),c.scope_separator!==void 0&&(c.scope_separator!==" "&&c.scope_separator!==","?s.push(`${e}.oauth: scope_separator should be " " or ",".`):c.scope_separator===","&&(l.scope_separator=",")),c.authorize_params!==void 0){let f=new Set(["client_id","redirect_uri","state","response_type","scope"]);!ge(c.authorize_params)||!Object.entries(c.authorize_params).every(([d,m])=>qo.test(d)&&!f.has(d)&&typeof m=="string"&&m.length<=200)?s.push(`${e}.oauth: authorize_params should map extra settings to text (not client_id, redirect_uri, state, response_type or scope).`):Object.keys(c.authorize_params).length&&(l.authorize_params=c.authorize_params)}c.client_auth!==void 0&&(c.client_auth!=="body"&&c.client_auth!=="basic"?s.push(`${e}.oauth: client_auth should be body or basic.`):c.client_auth==="basic"&&(l.client_auth="basic")),c.account!==void 0&&(typeof c.account!="string"||!Ln.test(c.account)?s.push(`${e}.oauth: account should say where the account's email or name is in the token answer, e.g. user.email.`):l.account=c.account),l.authorize_url&&l.token_url&&l.client_id&&(r.oauth=l)}}else t.oauth!==void 0&&s.push(`${e}: oauth is for per-person sources (credentials: per-person).`);let a=Object.keys(r.resources);return{config:r,resources:a,writable:a.filter(c=>r.resources[c].add),problems:s}}function Rf(t,e,n){return typeof t!="string"||!/^[A-Za-z0-9._~:@-]{4,200}$/.test(t.trim())?(n.push(`${e}.oauth: client_id should be your OAuth app's client ID.`),null):xn(t.trim())&&/secret/i.test(t)?(n.push(`${e}.oauth: client_id looks like a client secret; that goes in Secret Manager.`),null):t.trim()}function Lf(t,e,n){if(t===void 0)return null;let s=Array.isArray(t)?t:typeof t=="string"?t.split(/\s+/).filter(Boolean):null;return!s||!s.every(r=>typeof r=="string"&&/^[\x21-\x7e]{1,200}$/.test(r)&&!r.includes(","))?(n.push(`${e}.oauth: scopes should be a list, e.g. [crm.objects.contacts.read].`),null):s.length?s:null}function Do(t,e,n,s,r){let i=typeof t=="string"?t.trim():"";return!/^\/(?!\/)[^\s#\\]*$/.test(i)||i.length>1e3||/(^|\/)\.\.?(\/|\?|$)/.test(i)||/%2e|%2f/i.test(i)?(r.push(`${n}: path should be the API path under base_url, starting with / (e.g. ${s}).`),null):e&&!Pf(e,i)?(r.push(`${n}: path leaves base_url.`),null):i}var wr=t=>t===xf?1:Array.isArray(t)?t.reduce((e,n)=>e+wr(n),0):ge(t)?Object.values(t).reduce((e,n)=>e+wr(n),0):0,xf="$row";function qf(t,e,n,s){let r=typeof t=="string"?{path:t}:t;if(!ge(r))return s.push(`${e} should be a path (e.g. /v1/contacts), or settings with a path.`),null;for(let a of Object.keys(r))["path","body","row"].includes(a)||s.push(a==="method"?`${e}: new rows are always sent with POST; leave method out.`:`${e}: unknown setting "${a}" (add takes path, body and row).`);let i={path:""},o=Do(r.path,n,e,"/crm/v3/objects/contacts",s);return o&&(i.path=o),r.body!==void 0&&(ge(r.body)?JSON.stringify(r.body).length>Mo?s.push(`${e}.body is too long.`):wr(r.body)!==1?s.push(`${e}.body should have $row exactly once, where the tool's values go (e.g. { properties: $row }).`):i.body=r.body:s.push(`${e}.body should be the JSON object sent, with $row where the tool's values go, e.g. { properties: $row }.`)),r.row!==void 0&&r.row!==""&&(typeof r.row!="string"||!Ln.test(r.row)?s.push(`${e}: row should say where the new row is in the answer, e.g. data.issueCreate.issue (or leave it out if the answer is the row).`):i.row=r.row),o?i:null}function Mf(t,e,n,s){let r=c=>(s.push(`${e}: ${c}`),null);if(t==="link")return"link";if(!ge(t))return r("should be link, or { cursor, param }, { cursor, body }, { url }, { page } or { offset }.");let i=Object.keys(t),o=c=>typeof t[c]=="string"&&Ln.test(t[c]),a=c=>typeof t[c]=="string"&&qo.test(t[c]);return"cursor"in t?i.some(c=>!["cursor","param","body","more"].includes(c))?r("a cursor takes cursor, param or body, and more."):o("cursor")?"param"in t=="body"in t?r("say where the cursor goes: param (a query parameter) or body (a field in a POST's body)."):"param"in t&&!a("param")?r("param should be a query parameter name, e.g. after."):"body"in t&&(!n||!o("body"))?r(n?"body should be the field it goes in, e.g. variables.after.":"body needs method: POST."):"more"in t&&!o("more")?r("more should say where the has-more flag is, e.g. has_more."):{cursor:t.cursor,..."param"in t?{param:t.param}:{body:t.body},..."more"in t?{more:t.more}:{}}:r("cursor should say where the next cursor is in the answer, e.g. paging.next.after."):"url"in t?i.length===1&&o("url")?{url:t.url}:r("url should say where the next page's URL is in the answer, e.g. links.next."):"page"in t?i.some(c=>c!=="page"&&c!=="start")||!a("page")?r("page should be the page-number parameter, e.g. page."):"start"in t&&(typeof t.start!="number"||!Number.isInteger(t.start)||t.start<0)?r("start should be the first page's number (0 or 1)."):{page:t.page,...t.start!==void 0&&t.start!==1?{start:t.start}:{}}:"offset"in t?i.length===1&&a("offset")?{offset:t.offset}:r("offset should be the offset parameter, e.g. offset."):r("should be link, or { cursor, param }, { cursor, body }, { url }, { page } or { offset }.")}p();var me=[{id:"claude-code",name:"Claude Code",where:"terminal and IDEs",documents:["https://claude.ai/oauth/claude-code-client-metadata"]},{id:"claude",name:"Claude",where:"claude.ai, desktop and mobile apps",documents:["https://claude.ai/oauth/mcp-oauth-client-metadata"]},{id:"codex",name:"Codex",where:"OpenAI's CLI and IDE extension",documents:["https://chatgpt.com/oauth/codex/client.json","https://chatgpt.com/oauth/codex/*/client.json"]},{id:"chatgpt",name:"ChatGPT",where:"chatgpt.com and its apps, including Codex there",documents:["https://chatgpt.com/oauth/client.json"]},{id:"vscode",name:"VS Code",where:"GitHub Copilot's agent mode",documents:["https://vscode.dev/oauth/client-metadata.json"]},{id:"cursor",name:"Cursor",where:"Cursor's editor and cloud agents",documents:["https://cursor.com/oauth/mcp-client.json"]},{id:"lovable",name:"Lovable",where:"Lovable's workspace connectors",documents:["https://api.lovable.dev/.well-known/oauth-client"]},{id:"replit",name:"Replit",where:"Replit Agent's MCP servers",documents:[],notYet:"signs in without a metadata document"},{id:"bolt",name:"Bolt",where:"Bolt's connectors",documents:[],notYet:"signs in without a metadata document"},{id:"v0",name:"v0",where:"Vercel's v0",documents:[],notYet:"custom MCP sign-in unconfirmed"}],Bo=me.filter(t=>!t.notYet),Ie=["claude-code","claude"],Uo=new Map(me.map(t=>[t.id,t])),qn=t=>Uo.get(t);function Go(t){let e;try{e=new URL(t)}catch{return!1}return e.protocol==="https:"&&e.pathname.length>1&&!e.hash&&!e.username&&!e.password&&e.href===t}var Lt=t=>Uo.get(t)?.name??t;var Kf="*",ct=class extends Error{name="PolicyFileError";problems;constructor(e){super(`policy.yaml has ${e.length===1?"a problem":`${e.length} problems`}:
|
|
142
|
+
${e.map(n=>` - ${n}`).join(`
|
|
143
|
+
`)}`),this.problems=e}},Df=new Set(["Viewer","Builder","Admin"]),Fo=new Set(["postgres","bigquery","snowflake","api"]);var Bf=/^[A-Za-z_][A-Za-z0-9_]{0,62}$/,Wo=/^[A-Za-z_][A-Za-z0-9_]{0,254}$/,Uf=/^[a-z][a-z0-9-]{4,28}[a-z0-9]$/,Gf=/^(?:([a-z][a-z0-9-]{4,28}[a-z0-9])[.:])?([A-Za-z0-9_]{1,1024})$/,Ff=/^[A-Za-z0-9][A-Za-z0-9_.-]{1,254}$/,Wf=/^[A-Za-z0-9_.@$-]{1,255}$/,Mn=/^[A-Za-z_][A-Za-z0-9_$]{0,254}$/,Yf=/^[a-z][a-z0-9-]{1,30}$/;var Vf=/^(?:projects\/[a-z][a-z0-9-]{4,28}[a-z0-9]\/secrets\/)?[A-Za-z0-9_-]{1,255}$/,xn=t=>/^(ntn_|secret_|sk-|sk_live_|sk_test_|rk_live_|ghp_|gho_|github_pat_|xox[abpr]-|AKIA|ASIA|AIza|ya29\.)/.test(t)||t.length>=32&&/[A-Z]/.test(t)&&/[a-z]/.test(t)&&/[0-9]/.test(t)&&!/[-_].*[-_]/.test(t),Jf=t=>{let e=t.split("/").pop();return e.startsWith("kuriko-")&&!e.startsWith("kuriko-connector-")},zf=new Set(["roles","connectors","access","clients"]);function Yo(t){let e=t.trim();return e.toLowerCase()==="everyone"?Rn:e.includes("@")?e.toLowerCase():e}var Mt=t=>t===Rn?"everyone":t,xt=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),qt=t=>[...new Set(t)].sort();function Vo(t,e){let n=[],s={roles:[],connectors:[],grants:[],clients:[]};if(t==null&&(t={}),!xt(t))throw new ct(["The file should be a map with roles, connectors, access and clients."]);for(let u of Object.keys(t))zf.has(u)||n.push(`Unknown section "${u}" (expected roles, connectors, access, clients).`);let r=t.roles??{};if(!xt(r))n.push("roles should map a group to Admin, Builder or Viewer.");else for(let[u,f]of Object.entries(r)){let d=Yo(u);d===Rn?n.push("roles: everyone can't be given a role (roles need a real group)."):typeof f!="string"||!Df.has(f)?n.push(`roles: ${u} should be Admin, Builder or Viewer, not ${JSON.stringify(f)}.`):s.roles.some(m=>m.group===d)?n.push(`roles: ${u} is listed twice.`):s.roles.push({group:d,role:f})}let i=t.connectors??{},o=new Map,a=new Map,c=new Map;if(!xt(i))n.push("connectors should map an id (e.g. hubspot) to its settings.");else for(let[u,f]of Object.entries(i)){let d=`connectors.${u}`;if(Yf.test(u)||n.push(`${d}: the id should be lowercase letters, digits and dashes.`),!xt(f)){n.push(`${d} should have a name and a kind.`);continue}let m=typeof f.kind=="string"&&Fo.has(f.kind)?f.kind:null;m||n.push(`${d}: kind should be one of ${[...Fo].join(", ")}.`);let g=f.credentials==="per-person";f.credentials!==void 0&&f.credentials!=="shared"&&!g&&n.push(`${d}: credentials should be shared or per-person.`),g&&m&&m!=="api"&&n.push(`${d}: only api sources can be per-person so far.`);let y=new Set(m==="postgres"?["name","kind","secret","schema","credentials"]:m==="bigquery"?["name","kind","dataset","project","credentials"]:m==="snowflake"?["name","kind","secret","account","user","warehouse","database","schema","role","credentials"]:m==="api"?["name","kind","secret","credentials","base_url","auth","headers","resources","oauth"]:["name","kind"]);for(let $ of Object.keys(f))y.has($)||n.push($==="secret"&&m==="bigquery"?`${d}: BigQuery needs no secret: Kuriko's own identity is given access to the dataset.`:`${d}: unknown setting "${$}".`);let S=typeof f.name=="string"&&f.name.trim()?f.name.trim():null;S||n.push(`${d}: needs a name.`);let C=null;if(m==="postgres"||m==="snowflake"||m==="api"){let $=g?"the OAuth client secret":m==="postgres"?"the connection URL":m==="snowflake"?"the private key Kuriko signs in with":"the API key or token";typeof f.secret!="string"||!Vf.test(f.secret)?n.push(`${d}: secret should name the secret in Secret Manager holding ${$} (e.g. warehouse-readonly, or projects/<project>/secrets/<name>), never the secret itself.`):xn(f.secret.split("/").pop())?n.push(`${d}: secret looks like a credential itself. Put it in Secret Manager and name the secret here instead (then rotate it: it's been in this file).`):Jf(f.secret)?n.push(`${d}: ${f.secret} is one of Kuriko's own secrets; a data source needs its own credential.`):C=f.secret}let O={};if(m==="postgres")f.schema!==void 0&&(typeof f.schema!="string"||!f.schema)&&n.push(`${d}.schema should be a schema name.`),O={schema:typeof f.schema=="string"&&f.schema?f.schema:"public"},o.set(u,null);else if(m==="bigquery"){let $=typeof f.dataset=="string"?Gf.exec(f.dataset.trim()):null;if(!$)n.push(`${d}: dataset should be a BigQuery dataset, e.g. analytics (in this project) or other-project.analytics.`);else if(f.project!==void 0&&(typeof f.project!="string"||!Uf.test(f.project)))n.push(`${d}: project should be the Google Cloud project the dataset is in, e.g. acme-data.`);else if($[1]&&f.project!==void 0&&$[1]!==f.project)n.push(`${d}: dataset says project ${$[1]} but project says ${f.project}; keep one.`);else{let T=$[1]??f.project;O={dataset:$[2],...T?{project:T}:{}}}o.set(u,null),a.set(u,Wo)}else if(m==="snowflake"){let $=(T,j,b,v)=>{let K=f[T]??v;typeof K!="string"||!j.test(K.trim())?n.push(`${d}: ${T} should be ${b}.`):O[T]=K.trim()};$("account",Ff,"your Snowflake account identifier, e.g. acme-analytics (orgname-accountname)"),$("user",Wf,"the Snowflake user Kuriko signs in as, e.g. KURIKO_READER"),$("warehouse",Mn,"the warehouse queries run on, e.g. COMPUTE_WH"),$("database",Mn,"the database tools read, e.g. ANALYTICS"),$("schema",Mn,"a schema in that database, e.g. PUBLIC","PUBLIC"),f.role!==void 0&&$("role",Mn,"a Snowflake role the user has, e.g. KURIKO_READ"),o.set(u,null),a.set(u,Wo)}else if(m==="api"){let $=Ko(f,d,g);n.push(...$.problems),O=$.config,o.set(u,new Set($.resources)),c.set(u,new Set($.writable))}S&&m==="bigquery"?s.connectors.push({id:u,name:S,kind:m,config:O,mode:"identity",secretRef:null}):S&&m&&C&&s.connectors.push({id:u,name:S,kind:m,config:O,mode:g?"delegated":"service",secretRef:e(C)})}let l=t.access??[];Array.isArray(l)?l.forEach((u,f)=>{let d=`access[${f+1}]`;if(!xt(u))return void n.push(`${d} should have group, connector, resources and access.`);for(let b of Object.keys(u))["group","connector","resources","access","mask","rows"].includes(b)||n.push(`${d}: unknown setting "${b}".`);let m=typeof u.group=="string"&&u.group.trim()?Yo(u.group):null;m||n.push(`${d}: needs a group (a group email, or everyone).`);let g=typeof u.connector=="string"?u.connector:"";o.has(g)||n.push(`${d}: there's no connector "${g}" in connectors.`);let y=Array.isArray(u.resources)?u.resources.filter(b=>typeof b=="string"):typeof u.resources=="string"?[u.resources]:[];(!y.length||Array.isArray(u.resources)&&y.length!==u.resources.length)&&n.push(`${d}: resources should list what's granted, e.g. [interviews].`);let S=o.get(g);if(S)for(let b of y)S.has(b)||n.push(`${d}: ${g} has no resource "${b}" (it has: ${[...S].join(", ")||"none"}).`);let C=a.get(g)??Bf;if(S===null)for(let b of y)b!==Kf&&!C.test(b)&&n.push(`${d}: "${b}" isn't a table name (or "*" for every table).`);if(u.access==="write"&&o.has(g)){let b=c.get(g)??new Set,v=y.filter(K=>(S?S.has(K):!0)&&!b.has(K));v.length&&n.push(S?`${d}: ${g} can't take new rows in ${v.join(", ")} (read-only: no add in its connector). Use access: read, or describe how to add rows under the resource's add.`:`${d}: ${g} is read-only in Kuriko; use access: read.`)}u.access!=="read"&&u.access!=="write"&&n.push(`${d}: access should be read or write (write includes read).`);let O=u.mask===void 0?[]:Array.isArray(u.mask)&&u.mask.every(b=>typeof b=="string")?u.mask:null;O||n.push(`${d}: mask should be a list of field names.`);let $=u.rows===void 0||u.rows===null?{rule:void 0,problems:[]}:Ro(u.rows,`${d}.rows`,S===null?b=>C.test(b):void 0);if(n.push(...$.problems),!m||!g||!y.length||!O||$.rule===null||u.access!=="read"&&u.access!=="write")return;let T=s.grants.filter(b=>b.group===m&&b.connector===g&&b.access===u.access),j=y.filter(b=>T.some(v=>v.resources.includes(b)));if(j.length)return void n.push(`${d}: ${Mt(m)} already has ${u.access} on ${g}: ${j.join(", ")}. A table can be in one ${u.access} grant per group.`);if(T.some(b=>JSON.stringify(b.rows??null)===JSON.stringify($.rule??null)))return void n.push(`${d}: ${Mt(m)} already has ${u.access} on ${g}${$.rule?" with the same rows":""}; put the resources in one grant.`);s.grants.push({group:m,connector:g,resources:qt(y),access:u.access,mask:qt(O),...$.rule?{rows:$.rule}:{}})}):n.push("access should be a list of grants.");let h=t.clients===void 0||t.clients===null?[...Ie]:t.clients;if(Array.isArray(h)?h.forEach((u,f)=>{let d=`clients[${f+1}]`;if(typeof u!="string"||!u.trim())return void n.push(`${d} should be a client's name or its metadata document URL.`);let m=u.trim(),g=qn(m);if(g?.notYet)return void n.push(`${d}: ${g.name} can't connect to Kuriko yet (${g.notYet}). Leave it commented out for now.`);if(!g&&!Go(m))return void n.push(/^https?:/.test(m)?`${d}: ${m} isn't a client metadata document URL (https, with a path).`:`${d}: Kuriko doesn't know a client called "${m}". Use one of ${Bo.map(y=>y.id).join(", ")}, or the client's metadata document URL.`);if(s.clients.includes(m))return void n.push(`${d}: ${m} is listed twice.`);s.clients.push(m)}):n.push("clients should be a list, e.g. [claude-code, codex]."),n.length)throw new ct(n);return br(s)}var Kt=t=>Array.isArray(t)?t.map(Kt):t&&typeof t=="object"?Object.fromEntries(Object.keys(t).sort().map(e=>[e,Kt(t[e])])):t;function br(t){let e=n=>(s,r)=>n(s).localeCompare(n(r));return{roles:t.roles.map(({group:n,role:s})=>({group:n,role:s})).sort(e(n=>n.group)),connectors:t.connectors.map(({id:n,name:s,kind:r,mode:i,secretRef:o,config:a})=>({id:n,name:s,kind:r,mode:i,secretRef:o,config:Kt(a)})).sort(e(n=>n.id)),grants:t.grants.map(({group:n,connector:s,resources:r,access:i,mask:o,rows:a})=>({group:n,connector:s,resources:qt(r),access:i,mask:qt(o),...a?{rows:Kt(a)}:{}})).sort(e(Hf)),clients:qt(t.clients??[...Ie])}}var Hf=t=>`${t.connector}\0${t.group}\0${t.access}\0${JSON.stringify(t.rows?Kt(t.rows):null)}`;function Jo(t,e){let n=[],s=a=>typeof a=="string"?a:JSON.stringify(a);for(let a of["name","kind","mode","secretRef"])t[a]!==e[a]&&n.push(`${a} ${s(t[a])} \u2192 ${s(e[a])}`);let r=(a,c="")=>Object.entries(a).flatMap(([l,h])=>h&&typeof h=="object"&&!Array.isArray(h)?r(h,`${c}${l}.`):[[`${c}${l}`,h]]),i=new Map(r(t.config)),o=new Map(r(e.config));for(let a of new Set([...i.keys(),...o.keys()]))JSON.stringify(i.get(a))!==JSON.stringify(o.get(a))&&n.push(`${a} ${i.has(a)?s(i.get(a)):"(none)"} \u2192 ${o.has(a)?s(o.get(a)):"(none)"}`);return n.length?n:["(settings differ only in form)"]}var ze=(t,e)=>{let n=/^projects\/([^/]+)\/secrets\/(.+)$/.exec(t);return n&&(!e||n[1]===e)?n[2]:t};function Kn(t){switch(t.kind){case"role":return t.op==="add"?`${t.group} becomes ${t.to}`:t.op==="change"?`${t.group}: ${t.from} \u2192 ${t.to}`:`${t.group} is no longer ${t.from}`;case"connector":return`data source ${t.id}: ${t.summary}`;case"grant":return`${Mt(t.group)}: ${t.summary}`;case"client":return t.op==="add"?`people can connect with ${Lt(t.client)}`:`people can no longer connect with ${Lt(t.client)}`}}p();import{spawn as Qf}from"node:child_process";import{stripVTControlCharacters as Zf}from"node:util";var ee=class extends Error{command;code;stderr;constructor(e,n,s){let r=Zf(s);super(`${e} failed (exit ${n})${r.trim()?`:
|
|
144
144
|
${r.trim().split(`
|
|
145
145
|
`).slice(-15).join(`
|
|
146
|
-
`)}`:""}`),this.command=e,this.code=
|
|
147
|
-
`).map(
|
|
146
|
+
`)}`:""}`),this.command=e,this.code=n,this.stderr=r}get reason(){let e=this.stderr.split(`
|
|
147
|
+
`).map(n=>n.replace(/^[│╷╵\s]+/,"").trim()).filter(Boolean);return e.find(n=>/^error\b/i.test(n))?.replace(/^error:?\s*/i,"")??e[0]??`exit ${this.code}`}},zo=t=>/invalid_rapt|reauth related error|invalid_grant|Reauthentication (is )?(required|failed)/i.test(t);function L(t,e,n={}){return new Promise((s,r)=>{let i=t==="gcloud"&&!n.inherit?{CLOUDSDK_CORE_DISABLE_PROMPTS:"1"}:{},o=Qf(t,e,{cwd:n.cwd,env:{...process.env,...i,...n.env},stdio:n.inherit?"inherit":[n.input===void 0?"ignore":"pipe","pipe","pipe"]});n.input!==void 0&&o.stdin?.end(n.input);let a="",c="";o.stdout?.on("data",l=>(a+=l,n.tee&&process.stdout.write(l))),o.stderr?.on("data",l=>(c+=l,n.tee&&process.stderr.write(l))),o.on("error",l=>r(new ee(t,null,l.message))),o.on("close",l=>l===0?s(a):r(new ee(`${t} ${e[0]??""}`.trim(),l,c)))})}async function Q(t,e,n={}){return JSON.parse(await L(t,e,n))}async function He(t,e="--version"){try{return await L(t,[e]),!0}catch{return!1}}p();var pr=Cf(ql(),1);import{existsSync as Eo,readFileSync as _o,writeFileSync as Qu}from"node:fs";import{join as Co}from"node:path";p();var bn="kuriko-idp-client-secret",wn={ring:"kuriko",key:"user-tokens"};var Ml=["serviceusage.googleapis.com","cloudresourcemanager.googleapis.com","run.googleapis.com","sqladmin.googleapis.com","secretmanager.googleapis.com","cloudkms.googleapis.com","artifactregistry.googleapis.com","iam.googleapis.com","cloudidentity.googleapis.com","storage.googleapis.com","cloudbuild.googleapis.com","pubsub.googleapis.com"],Kl=["module.kuriko.google_project_service.apis","module.kuriko.google_artifact_registry_repository.kuriko","module.kuriko.google_service_account.gateway","module.kuriko.google_service_account.web","module.kuriko.google_service_account.tools"],_m=/^[a-z][a-z0-9-]{4,28}[a-z0-9]$/,eo=t=>_m.test(t),Dl=t=>/^[a-z]+-[a-z]+\d+$/.test(t),Bl=t=>/^\d+-[a-z0-9]+\.apps\.googleusercontent\.com$/.test(t),xs=t=>/^[^\s@'"\\]+@[^\s@'"\\]+\.[^\s@'"\\]+$/.test(t);function Ul(t){let e=new Set(t);for(let n=0;;n++){let s=n===0?"kuriko":`kuriko-${n}`;if(!e.has(s))return s}}function Gl(t){let e=/^(.*?)-(\d+)$/.exec(t);return e?`${e[1]}-${Number(e[2])+1}`:`${t}-1`}function Fl(t){return/(failed to create instance|google_sql_database_instance)[\s\S]{0,400}(instanceAlreadyExists|already exists|reuse the name)/i.test(t)}function Wl(t){return/IAM_PERMISSION_DENIED|SERVICE_DISABLED|has not been used in project|it is disabled|API .* not enabled|Permission '.*' denied/i.test(t)}var st=(t,e)=>{let n=`https://kuriko-web-${e}.${t.region}.run.app`;return{web:n,mcp:`https://kuriko-gateway-${e}.${t.region}.run.app/mcp`,redirect:`${n}/api/auth/sso/callback/idp`,newClient:`https://console.cloud.google.com/auth/clients/create?project=${t.project}`,registry:`${t.region}-docker.pkg.dev/${t.project}/kuriko`,webServiceAccount:`kuriko-web@${t.project}.iam.gserviceaccount.com`}},X=t=>JSON.stringify(t);function Yl(t,e,n,s=null,r=!!s){let i=s&&r?`${t.region}-docker.pkg.dev/${t.project}/kuriko-releases/${s.owner}`:`${t.region}-docker.pkg.dev/${t.project}/kuriko`;return`# Kuriko install for ${t.domain}, written by \`kuriko install\`. Holds no secrets.
|
|
148
148
|
terraform {
|
|
149
149
|
backend "gcs" {
|
|
150
|
-
bucket = ${
|
|
150
|
+
bucket = ${X(n)}
|
|
151
151
|
prefix = "kuriko"
|
|
152
152
|
}
|
|
153
153
|
}
|
|
@@ -163,13 +163,13 @@ variable "deletion_protection" {
|
|
|
163
163
|
}
|
|
164
164
|
|
|
165
165
|
locals {
|
|
166
|
-
repo = ${
|
|
166
|
+
repo = ${X(i)}
|
|
167
167
|
}
|
|
168
168
|
|
|
169
169
|
module "kuriko" {
|
|
170
|
-
source = ${
|
|
171
|
-
project_id = ${
|
|
172
|
-
region = ${
|
|
170
|
+
source = ${X(e)}
|
|
171
|
+
project_id = ${X(t.project)}
|
|
172
|
+
region = ${X(t.region)}
|
|
173
173
|
db_instance_name = var.db_instance_name
|
|
174
174
|
deletion_protection = var.deletion_protection
|
|
175
175
|
images = {
|
|
@@ -180,13 +180,13 @@ module "kuriko" {
|
|
|
180
180
|
idp = {
|
|
181
181
|
issuer = "https://accounts.google.com"
|
|
182
182
|
client_id = var.idp_client_id
|
|
183
|
-
domain = ${
|
|
183
|
+
domain = ${X(t.domain)}
|
|
184
184
|
groups_source = "google-workspace"
|
|
185
185
|
}${s?`
|
|
186
186
|
release_registry = {
|
|
187
|
-
upstream = ${
|
|
188
|
-
username = ${
|
|
189
|
-
token_secret_name = ${
|
|
187
|
+
upstream = ${X(s.upstream)}
|
|
188
|
+
username = ${X(s.username)}
|
|
189
|
+
token_secret_name = ${X(s.tokenSecret)}
|
|
190
190
|
token_version = var.release_token_version
|
|
191
191
|
}`:""}
|
|
192
192
|
}
|
|
@@ -196,102 +196,178 @@ output "mcp_url" { value = module.kuriko.mcp_url }
|
|
|
196
196
|
output "idp_redirect_uri" { value = module.kuriko.idp_redirect_uri }
|
|
197
197
|
output "web_service_account" { value = module.kuriko.web_service_account }
|
|
198
198
|
output "migrate_job" { value = module.kuriko.migrate_job }
|
|
199
|
-
|
|
200
|
-
`
|
|
199
|
+
output "gateway_member" { value = module.kuriko.gateway_member }
|
|
200
|
+
`}function Vl(t,e,n=null){return[`version_tag = ${X(e)}`,`idp_client_id = ${X(t.idpClientId??"")}`,`db_instance_name = ${X(t.dbInstanceName)}`,...n?[`release_token_version = ${X(n.tokenVersion)}`]:[],""].join(`
|
|
201
|
+
`)}var qs="module.kuriko.google_sql_database_instance.kuriko",kn={gateway:"kuriko-gateway",web:"kuriko-web",builder:"kuriko-builder",tools:"kuriko-tools",events:"kuriko-events"};function Jl(t,e){let n=`projects/${t.project}/locations/${t.region}/keyRings/${wn.ring}`;return["# Written by `kuriko install`: things already in the project that this install takes over.",...e.ring?[`import {
|
|
201
202
|
to = module.kuriko.google_kms_key_ring.kuriko
|
|
202
|
-
id = ${
|
|
203
|
+
id = ${X(n)}
|
|
203
204
|
}`]:[],...e.key?[`import {
|
|
204
205
|
to = module.kuriko.google_kms_crypto_key.user_tokens
|
|
205
|
-
id = ${
|
|
206
|
+
id = ${X(`${n}/cryptoKeys/${wn.key}`)}
|
|
206
207
|
}`]:[],...e.sqlInstance?[`import {
|
|
207
|
-
to = ${
|
|
208
|
-
id = ${
|
|
209
|
-
}`]:[]].
|
|
208
|
+
to = ${qs}
|
|
209
|
+
id = ${X(`projects/${t.project}/instances/${e.sqlInstance}`)}
|
|
210
|
+
}`]:[],...(e.accounts??[]).map(r=>`import {
|
|
211
|
+
to = module.kuriko.google_service_account.${r}
|
|
212
|
+
id = ${X(`projects/${t.project}/serviceAccounts/${kn[r]}@${t.project}.iam.gserviceaccount.com`)}
|
|
213
|
+
}`)].join(`
|
|
210
214
|
|
|
211
215
|
`)+`
|
|
212
|
-
`}function
|
|
213
|
-
${
|
|
214
|
-
`),i.trim()}finally{s.close()}}async function
|
|
215
|
-
`)},l=f=>{let
|
|
216
|
-
`),s(e[o].value)},u=(f,
|
|
217
|
-
`),process.kill(process.pid,"SIGINT");return}
|
|
218
|
-
`),c(!0),
|
|
219
|
-
`)},f=()=>{i.off("keypress",
|
|
220
|
-
`),r(
|
|
221
|
-
`),process.kill(process.pid,"SIGINT");return}if(
|
|
222
|
-
`),u(!0),
|
|
223
|
-
${
|
|
224
|
-
${e.map(
|
|
225
|
-
`)}`)}var
|
|
226
|
-
gcloud ${l.join(" ")}`)}}async function
|
|
227
|
-
|
|
216
|
+
`}function Ms(t){let e=[];for(let n of t.resource_changes??[]){let s=n.change.actions,r=s.includes("delete")&&s.includes("create")?"replace":s[0]==="create"||s[0]==="update"||s[0]==="delete"?s[0]:null;r&&e.push({address:n.address.replace(/^module\.kuriko\./,""),action:r})}return e}var Ks=new Set(["module.kuriko.google_project_iam_member.gateway_connector_secrets"]);function zl(t){return(t.resource_changes??[]).filter(e=>e.change.actions.includes("delete")&&!(Ks.has(e.address)&&e.change.actions.length===1)).map(e=>e.address)}var Cm={admins:["platform","infra","sre","devops","it","ops","security","secops","admin","admins","cloud","engineering-leads"],builders:["eng","engineering","engineers","dev","developers","product","builders","ops","operations","data","analytics","tech"]};function Hl(t,e,n=6){let s=Cm[e],r=i=>{let o=`${i.email.split("@")[0]} ${i.name}`.toLowerCase().split(/[^a-z0-9]+/),a=s.findIndex(c=>o.includes(c));return a<0?1/0:a};return t.map(i=>({g:i,s:r(i)})).filter(i=>i.s!==1/0).sort((i,o)=>i.s-o.s||i.g.email.localeCompare(o.g.email)).slice(0,n).map(i=>i.g)}var Ql=(t,e)=>{let n=e.trim().toLowerCase();return t.filter(s=>s.email.includes(n)||s.name.toLowerCase().includes(n))};p();p();import{emitKeypressEvents as Xl}from"node:readline";import{createInterface as eu}from"node:readline/promises";import{Writable as Nm}from"node:stream";import{stripVTControlCharacters as Zl,styleText as vt}from"node:util";var _=t=>vt("bold",t),A=t=>vt("dim",t),be=t=>vt("red",t),Ue=t=>vt("green",t),rt=t=>vt("yellow",t),$t=t=>vt("cyan",t),tu="\u280B\u2819\u2839\u2838\u283C\u2834\u2826\u2827\u2807\u280F",kt=null,no=null,to=null,so=0,ro=!1,io=!1,oo=()=>process.stdout.isTTY===!0;function Ds(t){let e=Math.floor((Date.now()-t)/1e3);return e<60?`${e}s`:`${Math.floor(e/60)}m ${String(e%60).padStart(2,"0")}s`}function Tm(){let t=[kt&&`${kt.text} ${A(Ds(kt.start))}`,no?.()&&A(no())].filter(s=>!!s);if(!t.length)return null;let e=(process.stdout.columns||80)-1,n=`${$t(tu[so])} ${t.join(A(" \xB7 "))}`;return Zl(n).length<=e?n:Zl(n).slice(0,e)}function Bs(){oo()&&io&&process.stdout.write("\r\x1B[2K"),io=!1}function St(){if(!oo()||ro)return;Bs();let t=Tm();t&&(process.stdout.write(t),io=!0)}function nu(){to||!oo()||(to=setInterval(()=>{so=(so+1)%tu.length,St()},100),to.unref())}function $n(t){Bs(),console.log(t),St()}async function P(t,e){let n=kt;kt={text:t,start:Date.now()},nu(),St();try{return await e()}finally{kt=n,Bs(),St()}}function ao(t){no=t,nu(),St()}async function At(t){ro=!0,Bs();try{return await t()}finally{ro=!1,St()}}var k=(t="")=>$n(t),M=t=>$n(`
|
|
217
|
+
${_("\u2192")} ${t}`),N=t=>$n(` ${Ue("\u2713")} ${t}`),x=t=>$n(` ${rt("!")} ${t}`);function Us(){if(!process.stdin.isTTY)throw new Error("This needs answers typed at a terminal; run it in your own terminal, not through a pipe.")}async function V(t,e){return Us(),At(async()=>{let n=eu({input:process.stdin,output:process.stdout});try{return(await n.question(e?`${t} ${A(`[${e}]`)} `:`${t} `)).trim()||e||""}finally{n.close()}})}async function z(t,e=!1){let n=(await V(`${t} ${A(e?"[Y/n]":"[y/N]")}`)).toLowerCase();return n?n==="y"||n==="yes":e}async function Gs(t){return Us(),At(()=>Om(t))}async function Om(t){let e=!1,n=new Nm({write(r,i,o){e||process.stdout.write(r),o()}}),s=eu({input:process.stdin,output:n,terminal:!0});try{let r=s.question(`${t} `);e=!0;let i=await r;return process.stdout.write(`
|
|
218
|
+
`),i.trim()}finally{s.close()}}async function oe(t,e){Us();let n=e.map((s,r)=>s.disabled?-1:r).filter(s=>s>=0);if(!n.length)throw new Error(`Nothing to choose for: ${t}`);return At(()=>new Promise(s=>{let r=process.stdin,i=r.isRaw,o=n[0],a=(f,d)=>{let m=f.disabled?A(f.label):d===o?_(f.label):f.label;return`${d===o?$t(" \u203A"):" "} ${m}${f.hint?` ${A(f.hint)}`:""}`},c=f=>{f||process.stdout.write(`\x1B[${e.length}A`);for(let[d,m]of e.entries())process.stdout.write(`\r\x1B[2K${a(m,d)}
|
|
219
|
+
`)},l=f=>{let d=n.indexOf(o);o=n[(d+f+n.length)%n.length],c(!1)},h=()=>{r.off("keypress",u),r.setRawMode(i),r.pause(),process.stdout.write(`\x1B[${e.length+1}A\r\x1B[J${t} ${$t(e[o].label)}
|
|
220
|
+
`),s(e[o].value)},u=(f,d={})=>{if(d.ctrl&&d.name==="c"){r.setRawMode(i),process.stdout.write(`
|
|
221
|
+
`),process.kill(process.pid,"SIGINT");return}d.name==="up"||d.name==="k"?l(-1):d.name==="down"||d.name==="j"||d.name==="tab"?l(1):d.name==="return"||d.name==="enter"?h():f&&/^[1-9]$/.test(f)&&n.includes(Number(f)-1)&&(o=Number(f)-1,c(!1))};process.stdout.write(`${t} ${A("(\u2191/\u2193, Enter)")}
|
|
222
|
+
`),c(!0),Xl(r),r.setRawMode(!0),r.resume(),r.on("keypress",u)}))}async function Fs(t,e,n){Us();let s=e.map((r,i)=>r.disabled?-1:i).filter(r=>r>=0);if(!s.length)throw new Error(`Nothing to choose for: ${t}`);return At(()=>new Promise(r=>{let i=process.stdin,o=i.isRaw,a=e.map(m=>!m.disabled&&n(m.value)),c=s[0],l=(m,g)=>m.disabled?` ${A(`\u25CB ${m.label}${m.hint?` ${m.hint}`:""}`)}`:`${g===c?$t(" \u203A"):" "} ${a[g]?Ue("\u25C9"):A("\u25CB")} ${g===c?_(m.label):m.label}${m.hint?` ${A(m.hint)}`:""}`,h=m=>c=s[(s.indexOf(c)+m+s.length)%s.length],u=m=>{m||process.stdout.write(`\x1B[${e.length}A`);for(let[g,y]of e.entries())process.stdout.write(`\r\x1B[2K${l(y,g)}
|
|
223
|
+
`)},f=()=>{i.off("keypress",d),i.setRawMode(o),i.pause();let m=e.filter((g,y)=>a[y]);process.stdout.write(`\x1B[${e.length+1}A\r\x1B[J${t} ${$t(m.map(g=>g.label).join(", ")||"none")}
|
|
224
|
+
`),r(m.map(g=>g.value))},d=(m,g={})=>{if(g.ctrl&&g.name==="c"){i.setRawMode(o),process.stdout.write(`
|
|
225
|
+
`),process.kill(process.pid,"SIGINT");return}if(g.name==="up"||g.name==="k")h(-1);else if(g.name==="down"||g.name==="j"||g.name==="tab")h(1);else if(g.name==="space")a[c]=!a[c];else return g.name==="return"||g.name==="enter"?f():void 0;u(!1)};process.stdout.write(`${t} ${A("(\u2191/\u2193, Space to tick, Enter)")}
|
|
226
|
+
`),u(!0),Xl(i),i.setRawMode(!0),i.resume(),i.on("keypress",d)}))}async function co(t,e){let n=e.filter(s=>!s.disabled);return n.length===1&&e.length===1?(k(`${t} ${$t(n[0].label)}`),n[0].value):oe(t,e)}function Ee(t,e){$n(`
|
|
227
|
+
${_("\u270B")} ${_(t)}
|
|
228
|
+
${e.map(n=>n?` ${n}`:"").join(`
|
|
229
|
+
`)}`)}var Sn=async t=>{try{return await L("gcloud",t),!0}catch(e){if(e instanceof ee&&/NOT_FOUND|not found|does not exist|404/i.test(e.stderr))return!1;throw e}},Et=async()=>(await L("gcloud",["config","get","account"])).trim();async function te(t={}){let e=async n=>{try{return await L("gcloud",n),null}catch(s){return s instanceof ee&&zo(s.stderr)?"expired":"missing"}};for(let n=!1;;n=!0){let[s,r]=await Promise.all([t.terraformOnly?null:e(["auth","print-access-token"]),e(["auth","application-default","print-access-token"])]);if(!s&&!r)return;let i=await Et().catch(()=>""),c=`${[s&&"gcloud",r&&"Terraform"].filter(Boolean).join(" and ")}${s==="expired"||r==="expired"?`'s Google sign-in${s&&r?"s have":" has"} expired`:` ${s&&r?"aren't":"isn't"} signed in to Google`}`,l=s?["auth","login",...i?[i]:[],"--force",...r?["--update-adc"]:[]]:["auth","application-default","login"];if(!n&&process.stdin.isTTY&&(x(`${c}.`),await z(` Sign in${i?` as ${i}`:""} now? (opens your browser)`,!0))){await At(()=>L("gcloud",l,{inherit:!0}));continue}throw new Error(`${c}. Run:
|
|
230
|
+
gcloud ${l.join(" ")}`)}}async function _t(){return(await Q("gcloud",["organizations","list","--format=json"])).map(t=>({id:t.name.split("/")[1],name:t.displayName,customerId:t.owner?.directoryCustomerId??null}))}async function su(){return(await Q("gcloud",["billing","accounts","list","--format=json"])).filter(t=>t.open).map(t=>({id:t.name.split("/")[1],name:t.displayName}))}async function Ge(t){try{let e=await Q("gcloud",["projects","describe",t,"--format=json"]);return{number:e.projectNumber,state:e.lifecycleState}}catch(e){if(e instanceof ee&&/not found|does not exist|permission/i.test(e.stderr))return null;throw e}}var ru=(t,e)=>L("gcloud",["projects","create",t,`--organization=${e}`,"--name=Kuriko"]);async function iu(t){return(await Q("gcloud",["billing","projects","describe",t,"--format=json"])).billingEnabled===!0}var ou=(t,e)=>L("gcloud",["billing","projects","link",t,`--billing-account=${e}`]);async function au(t){try{return(await L("gcloud",["billing","projects","list",`--billing-account=${t}`,"--format=value(projectId)"])).split(`
|
|
231
|
+
`).map(n=>n.trim()).filter(Boolean)}catch{return null}}var cu=t=>t instanceof ee&&/billing quota exceeded|QuotaFailure/i.test(t.stderr),Ys=(t,e)=>L("gcloud",["services","enable",...e,`--project=${t}`]);async function lu(t,e,n){return await Sn(["storage","buckets","describe",`gs://${t}`,"--format=json"])?"exists":(await L("gcloud",["storage","buckets","create",`gs://${t}`,`--project=${e}`,`--location=${n}`,"--uniform-bucket-level-access","--public-access-prevention"]),await L("gcloud",["storage","buckets","update",`gs://${t}`,"--versioning"]),"created")}async function uu(t){return(await Q("gcloud",["sql","instances","list",`--project=${t}`,"--format=json"])).map(e=>({name:e.name,kuriko:e.settings?.userLabels?.["managed-by"]==="kuriko"}))}async function fu(t,e,n,s){let r=[`--location=${e}`,`--project=${t}`,"--format=json"],i=await Sn(["kms","keyrings","describe",n,...r]);return{ring:i,key:i&&await Sn(["kms","keys","describe",s,`--keyring=${n}`,...r])}}async function du(t,e){let n=(await L("gcloud",["iam","service-accounts","list",`--project=${t}`,"--format=value(email)"])).split(`
|
|
232
|
+
`).map(s=>s.trim());return e.filter(s=>n.includes(`${s}@${t}.iam.gserviceaccount.com`))}async function pu(t){return Sn(["artifacts","docker","images","describe",t,"--format=json"])}async function vn(t,e){return await Sn(["secrets","describe",e,`--project=${t}`,"--format=json"])?(await Q("gcloud",["secrets","versions","list",e,`--project=${t}`,"--filter=state:ENABLED","--format=json"])).length>0:null}async function Ct(t,e,n){await vn(t,e)===null?await L("gcloud",["secrets","create",e,`--project=${t}`,"--replication-policy=automatic","--labels=managed-by=kuriko-security-team","--data-file=-"],{input:n}):await L("gcloud",["secrets","versions","add",e,`--project=${t}`,"--data-file=-"],{input:n})}async function hu(t,e,n){try{let r=await(await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:t,client_secret:e,code:"kuriko-install-check",redirect_uri:n,grant_type:"authorization_code"})})).json().catch(()=>({}));return r.error==="invalid_client"||r.error==="unauthorized_client"?!1:r.error==="invalid_grant"?!0:null}catch{return null}}async function Ws(t,e,n){let s=(await L("gcloud",["auth","print-access-token"])).trim(),r=new URL(`https://cloudidentity.googleapis.com/v1/${e}`);for(let[o,a]of Object.entries(n))r.searchParams.set(o,a);let i=await fetch(r,{headers:{authorization:`Bearer ${s}`,"x-goog-user-project":t}});if(i.status===404||i.status===403)return null;if(!i.ok)throw new Error(`Cloud Identity ${i.status}: ${(await i.text()).slice(0,300)}`);return await i.json()}async function gu(t,e,n,s){let r=(await L("gcloud",["auth","print-access-token"])).trim(),i=new URL(`https://cloudidentity.googleapis.com/v1/${e}`);for(let[a,c]of Object.entries(n))i.searchParams.set(a,c);let o=await fetch(i,{method:"POST",headers:{authorization:`Bearer ${r}`,"x-goog-user-project":t,"content-type":"application/json"},body:JSON.stringify(s)});return{status:o.status,text:await o.text()}}async function mu(t,e){let n=await gu(t,"groups",{initialGroupConfig:e.owner?"WITH_INITIAL_OWNER":"EMPTY"},{parent:`customers/${e.customerId}`,groupKey:{id:e.email},displayName:e.name,description:e.description,labels:{"cloudidentity.googleapis.com/groups.discussion_forum":""}});if(n.status===409)return"exists";if(n.status>=300)throw new Error(`Couldn't create ${e.email} (${n.status}): ${n.text.slice(0,300)}`);return"created"}async function Vs(t,e){let n=[],s="";do{let r=await Ws(t,"groups",{parent:`customers/${e}`,view:"BASIC",pageSize:"500",...s?{pageToken:s}:{}});if(!r)return n.length?n:null;for(let i of r.groups??[])i.groupKey?.id&&n.push({email:i.groupKey.id.toLowerCase(),name:i.displayName??"",description:i.description??""});s=r.nextPageToken??""}while(s&&n.length<2e4);return n.sort((r,i)=>r.email.localeCompare(i.email))}async function lo(t,e,n){let s=await Ws(t,"groups:lookup",{"groupKey.id":e});if(!s?.name)throw new Error(`Group ${e} not found`);let r=await gu(t,`${s.name}/memberships`,{},{preferredMemberKey:{id:n},roles:[{name:"MEMBER"}]});if(r.status===409)return"exists";if(r.status>=300)throw new Error(`Couldn't add ${n} to ${e} (${r.status}): ${r.text.slice(0,300)}`);return"added"}async function Js(t,e,n){let s=await Ws(t,"groups:lookup",{"groupKey.id":e});if(!s?.name)return{exists:!1,isMember:!1};let r="";do{let i=await Ws(t,`${s.name}/memberships:searchTransitiveMemberships`,{pageSize:"500",...r?{pageToken:r}:{}});if(i?.memberships?.some(o=>o.preferredMemberKey?.some(a=>a.id?.toLowerCase()===n.toLowerCase())))return{exists:!0,isMember:!0};r=i?.nextPageToken??""}while(r);return{exists:!0,isMember:!1}}async function Nt(t,e,n,s){let r=[`--project=${t}`,`--region=${e}`],o=(await Q("gcloud",["run","jobs","execute",n,...r,"--async","--format=json",...s?[`--args=^;;^${s.join(";;")}`]:[]])).metadata.name;for(;!(await Q("gcloud",["run","jobs","executions","describe",o,...r,"--format=json"])).status?.completionTime;)await new Promise(c=>setTimeout(c,3e3));for(let a=0;a<12;a++){let l=(await Q("gcloud",["logging","read",`resource.type="cloud_run_job" AND labels."run.googleapis.com/execution_name"="${o}"`,`--project=${t}`,"--freshness=1h","--order=asc","--format=json"])).map(u=>u.textPayload??"").filter(Boolean),h=l.map(u=>/Container called exit\((\d+)\)/.exec(u)).find(Boolean);if(h)return{code:Number(h[1]),logs:l.filter(u=>!/Container called exit/.test(u))};await new Promise(u=>setTimeout(u,5e3))}return{code:null,logs:[]}}async function yu(t,e){return(await L("gcloud",["secrets","versions","list",e,`--project=${t}`,"--filter=state:ENABLED","--sort-by=~createTime","--limit=1","--format=value(name)"])).trim().split("/").pop()||null}async function wu(t,e){return(await L("gcloud",["secrets","versions","access","latest",`--secret=${e}`,`--project=${t}`])).trim()}async function uo(t,e,n=18e4){let s=(await L("gcloud",["auth","print-access-token"])).trim(),r=Date.now()+n;for(;;){let i=await fetch(`https://serviceusage.googleapis.com/v1beta1/projects/${t}/services/${e}:generateServiceIdentity`,{method:"POST",headers:{authorization:`Bearer ${s}`,"x-goog-user-project":t}});if(i.ok)return;let o=await i.text();if(i.status!==403||Date.now()>r)throw new Error(`Couldn't set up ${e}'s service account (${i.status}): ${o.slice(0,200)}`);await new Promise(a=>setTimeout(a,1e4))}}async function bu(t,e,n,s,r){try{let i=`${t.owner}/${s}`,o=Buffer.from(`${e}:${n}`).toString("base64"),a=await fetch(`https://${t.host}/token?service=${t.host}&scope=repository:${i}:pull`,{headers:{authorization:`Basic ${o}`}});if(a.status===401||a.status===403)return"denied";if(!a.ok)return"unreachable";let{token:c}=await a.json(),l=await fetch(`https://${t.host}/v2/${i}/manifests/${r}`,{method:"HEAD",headers:{authorization:`Bearer ${c}`,accept:"application/vnd.oci.image.index.v1+json, application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json, application/vnd.docker.distribution.manifest.list.v2+json"}});return l.ok?"ok":l.status===401||l.status===403?"denied":l.status===404?"missing":"unreachable"}catch{return"unreachable"}}var fo="roles/secretmanager.secretAccessor",zs=t=>{let e=/^projects\/([^/]+)\/secrets\/([^/]+)$/.exec(t);if(!e)throw new Error(`Not a secret reference: ${t}`);return[e[1],e[2]]};async function An(t){let[e,n]=zs(t);return L("gcloud",["secrets","describe",n,`--project=${e}`,"--format=value(name)"]).then(()=>!0,()=>!1)}async function En(t,e){let[n,s]=zs(t);return!!(await Q("gcloud",["secrets","get-iam-policy",s,`--project=${n}`,"--format=json"])).bindings?.some(i=>i.role===fo&&!i.condition&&i.members?.includes(e))}async function po(t,e){let[n,s]=zs(t);await L("gcloud",["secrets","add-iam-policy-binding",s,`--project=${n}`,`--member=${e}`,`--role=${fo}`,"--condition=None","--format=none"])}async function ku(t,e){let[n,s]=zs(t);await An(t)&&await En(t,e)&&await L("gcloud",["secrets","remove-iam-policy-binding",s,`--project=${n}`,`--member=${e}`,`--role=${fo}`,"--condition=None","--format=none"])}async function $u(t){let e=(await L("gcloud",["auth","print-access-token"])).trim(),n=await fetch(`https://bigquery.googleapis.com/bigquery/v2/${t}`,{headers:{authorization:`Bearer ${e}`}});return{status:n.status,body:await n.json().catch(()=>({}))}}async function Su(t){let e=await $u(`projects/${t}/datasets?maxResults=1000`).catch(()=>null);return!e||e.status!==200?null:(e.body.datasets??[]).map(n=>({id:n.datasetReference.datasetId,location:n.location}))}var Im=new Set(["READER","WRITER","OWNER","roles/bigquery.dataViewer","roles/bigquery.dataEditor","roles/bigquery.dataOwner","roles/bigquery.admin"]),Pm=new Set(["roles/bigquery.dataViewer","roles/bigquery.dataEditor","roles/bigquery.dataOwner","roles/bigquery.admin","roles/viewer","roles/editor","roles/owner"]);async function vu(t,e,n){let s=`serviceAccount:${n}`,r=await $u(`projects/${t}/datasets/${e}`);if(r.status===404)return"missing";if(r.status===200){let o=r.body.access??[],a=c=>c.userByEmail?.toLowerCase()===n.toLowerCase()||c.iamMember===s||c.specialGroup==="allAuthenticatedUsers"||c.iamMember==="allAuthenticatedUsers"||c.iamMember==="allUsers";if(o.some(c=>a(c)&&Im.has(c.role??"")))return"readable"}let i=await Q("gcloud",["projects","get-iam-policy",t,"--format=json"]).catch(()=>null);return i?.bindings?.some(o=>Pm.has(o.role)&&!o.condition&&o.members?.includes(s))?"readable":r.status===200&&i?"not-readable":"unknown"}p();import{basename as Ou,relative as qm,resolve as Iu}from"node:path";p();import{existsSync as Hs,readdirSync as jm,readFileSync as Qs}from"node:fs";import{homedir as Rm}from"node:os";import{dirname as ho,join as _e,relative as Lm,resolve as _n}from"node:path";import{fileURLToPath as xm}from"node:url";var H=_n(xm(new URL("../../..",import.meta.url))),Ot="kuriko-installs.json";function ne(t=process.cwd(),e=process.env){for(let n=_n(t);;n=ho(n)){if(Hs(_e(n,Ot)))return n;if(ho(n)===n)break}for(let n of[e.KURIKO_INSTALLS,_e(ho(H),"kuriko-installs")])if(n&&Hs(_e(n,Ot)))return _n(n);return null}var Zs=`No installs repo found. Installs live in a git repo you share with whoever runs Kuriko:
|
|
233
|
+
clone yours next to the Kuriko checkout (or cd into it), or start one with: kuriko init <folder>`;function Fe(t=process.cwd(),e){let n=e&&ne(_n(t,e))||ne(t);if(!n)throw new Error(Zs);return n}function Cn(t,e=process.cwd(),n=ne(e)){if(t){let r=[_n(e,t),n&&_e(n,t)].find(i=>!!i&&go(i));if(!r)throw new Error(`No Kuriko install at ${t}. Run kuriko list to see them.`);return r}let s=it(e,n);if(s.length===1)return s[0];throw s.length>1?new Error(`Several installs; choose one with --dir:
|
|
228
234
|
${s.map(r=>` ${r}`).join(`
|
|
229
|
-
`)}`):new Error(
|
|
230
|
-
git -C ${
|
|
231
|
-
Commit this to the installs repo${
|
|
232
|
-
`)
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
`)}
|
|
236
|
-
`).
|
|
237
|
-
`).
|
|
235
|
+
`)}`):new Error(n?"No Kuriko installs yet. Start one with: kuriko install":Zs)}function it(t=process.cwd(),e=ne(t)){return go(t)?[t]:!e||!Hs(e)?[]:jm(e).sort().map(n=>_e(e,n)).filter(go)}function D(t,e=process.cwd()){let n=Lm(e,t);if(n&&!n.startsWith(".."))return n;let s=Rm();return t.startsWith(s)?`~${t.slice(s.length)}`:t}function Au(t){let e=Qs(_e(t,"main.tf"),"utf8"),n=s=>new RegExp(`^\\s*${s}\\s*=\\s*"([^"]+)"`,"m").exec(e)?.[1]??null;return{project:n("project_id"),region:n("region")}}var Eu=t=>/requested project was not found|project .* (was )?not found|has been deleted|DELETE_REQUESTED/i.test(t);function _u(t){let e=t.filter(n=>n&&!/(^|\.)data\./.test(n));return e.includes("module.kuriko.google_cloud_run_v2_service.web")&&e.includes("module.kuriko.google_cloud_run_v2_service.gateway")?"installed":e.length?"partial":"empty"}function go(t){let e=_e(t,"main.tf");return Hs(e)&&/module\s+"kuriko"/.test(Qs(e,"utf8"))}function Cu(t){let e=Qs(_e(t,"main.tf"),"utf8");return/variable\s+"deletion_protection"/.test(e)&&/deletion_protection\s*=\s*var\.deletion_protection/.test(e)}function Nu(t){try{let e=JSON.parse(Qs(_e(t,".terraform","terraform.tfstate"),"utf8"));return e?.backend?.type==="gcs"?`gs://${e.backend.config.bucket}/${e.backend.config.prefix??""}`:null}catch{return null}}function Tu(t){let e=t.values?.root_module;return[...e?.resources??[],...(e?.child_modules??[]).flatMap(n=>n.resources??[])]}var le=(t,e)=>L("git",["-C",t,...e]);async function Pu(t){try{return(await le(t,["rev-parse","--show-toplevel"])).trim()}catch{return null}}async function Mm(t){return(await le(t,["rev-parse","--abbrev-ref","HEAD"]).catch(()=>"HEAD")).trim()}async function ju(t){try{return(await le(t,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"])).trim()}catch{return null}}async function ke(t){let e=await Pu(t);if(!e)return;let n=await ju(e);if(!n)return;await P("Checking the installs repo is up to date",()=>le(e,["fetch","--quiet"]));let s=Number((await le(e,["rev-list","--count","HEAD..@{u}"])).trim());if(s>0)throw new Error(`The installs repo is ${s} commit${s===1?"":"s"} behind ${n}. Pull first:
|
|
236
|
+
git -C ${D(e)} pull`)}async function We(t,e,n={}){let s=await Pu(t[0]);if(!s){let l=ne(t[0])??t[0];x(`${D(l)} isn't in a git repo, so this change has no history and nobody else can see it.`),k(` Make it one and add a private remote: ${_(`git -C ${D(l)} init`)}, then ${_("git remote add origin <url>")} and push.`);return}let r=ne(t[0]),i=!!r&&Iu(r)!==Iu(s),o=t.map(l=>qm(s,l)||".");if(await le(s,n.remove?["rm","-r","-q","--ignore-unmatch","--",...o]:["add","-A","--",...o]),!(await le(s,["diff","--cached","--name-only","--",...o])).trim())return;let c=i?null:await ju(s);if(!process.stdin.isTTY){x(`Left uncommitted in ${D(s)} (no terminal to ask). Commit it so others running Kuriko see the change:`),k(` ${_(`git -C ${D(s)} commit -m ${JSON.stringify(e)} -- ${o.join(" ")}`)}${c?` && git -C ${D(s)} push`:""}`);return}if(!await z(`
|
|
237
|
+
Commit this to ${i?`${Ou(s)} (on ${await Mm(s)})`:"the installs repo"}${c?` and push to ${c}`:""}?`,!0)){x(`Left uncommitted in ${D(s)}. Commit it so others running Kuriko see the change.`);return}await le(s,["commit","-q","-m",e,"--",...o]),c?(await P("Pushing",()=>le(s,["push","-q"])),N(`Committed and pushed: ${e}`)):i?(N(`Committed: ${e}`),k(` Push it and open a pull request as you usually would, so it's reviewed with the rest of ${Ou(s)}.`)):(N(`Committed: ${e}`),k(` (no remote to push to; add one so others can pull it: ${_(`git -C ${D(s)} remote add origin <url>`)})`))}async function Ru(t,e,n){let s=i=>i.replace(/-dirty-.*$/,"");if(s(e)===s(n))return"same";let r=async(i,o)=>{try{return await le(t,["merge-base","--is-ancestor",s(i),s(o)]),!0}catch{return!1}};return await r(e,n)?"forward":await r(n,e)?"backward":await mo(t,e,n)?"forward":"unknown"}async function mo(t,e,n){let s=r=>r.replace(/-dirty-.*$/,"");if(e!==s(e))return null;try{let r=(await le(t,["rev-parse",`${s(e)}^{tree}`])).trim(),i=(await le(t,["log","--format=%H %T","-n","1000",s(n)])).split(`
|
|
238
|
+
`).find(o=>o.endsWith(` ${r}`));return i?i.split(" ")[0].slice(0,e.length):null}catch{return null}}p();import{existsSync as Km}from"node:fs";import{basename as Dm,join as Bm}from"node:path";var Xs={installed:{mark:"\u25CF",text:"installed"},partial:{mark:"\u25D0",text:"partly installed"},empty:{mark:"\u25CB",text:"not installed"},gone:{mark:"\u25CB",text:"project deleted"},unknown:{mark:"?",text:"status unknown"}};async function Um(t){let{project:e,region:n}=Au(t),s={dir:t,project:e??Dm(t),region:n??"?",status:"unknown"};if(!Km(Bm(t,".terraform")))return{...s,detail:"Terraform isn't set up here yet (run install to continue)"};try{let[r,i]=await Promise.all([L("terraform",["state","list","-no-color"],{cwd:t}),L("terraform",["output","-json"],{cwd:t}).then(o=>JSON.parse(o))]);s.status=_u(r.split(`
|
|
239
|
+
`)),s.status==="installed"&&(s.web=String(i.web_url?.value??""),s.mcp=String(i.mcp_url?.value??""))}catch(r){let i=r instanceof ee?r.reason:String(r);if(Eu(i))return{...s,status:"gone",detail:`Delete the leftover config when you're done with it: rm -r ${D(t)}`};s.detail=`Couldn't read its state: ${i}`}return s}var Nn=t=>P(`Reading ${t.length} install${t.length===1?"":"s"}`,()=>Promise.all(t.map(Um)));async function Ye(t,e,n,s={}){if(t)return Cn(t);let r=it();if(!r.length)return Cn(void 0);await te({terraformOnly:!0});let i=await Nn(r);if(!i.filter(a=>n.includes(a.status)).length)throw new Error(`None of your installs can be used for this:
|
|
240
|
+
${i.map(a=>` ${a.project}: ${Xs[a.status].text}`).join(`
|
|
241
|
+
`)}`);return i.length===1?i[0].dir:oe(e,i.map(a=>{let c=Xs[a.status],l=n.includes(a.status);return{label:a.project,value:a.dir,disabled:!l,hint:`${a.region} ${c.mark} ${c.text}${!l&&s[a.status]?`: ${s[a.status]}`:""}`}}))}p();import{cpSync as Mu,existsSync as Ku,mkdtempSync as zm,readFileSync as tr,rmSync as Du,writeFileSync as nr}from"node:fs";import{tmpdir as Hm}from"node:os";import{join as Ce}from"node:path";p();import{cpSync as Gm,existsSync as Fm,mkdirSync as Wm,rmSync as Ym}from"node:fs";import{join as wo,relative as Vm}from"node:path";import{fileURLToPath as Jm}from"node:url";var W=typeof w>"u"?null:w,Lu=process.env.KURIKO_REGISTRY_HOST||"registry.kuriko.dev",ae={upstream:`https://${Lu}`,host:Lu,owner:"usekuriko",username:"kuriko"},$e="kuriko-release-token",yo=W?Jm(new URL("./module",import.meta.url)):wo(H,"infra/terraform/gcp"),er=".kuriko/module";function xu(t){if(!W)return Vm(t,yo);let e=wo(t,er);if(Ym(e,{recursive:!0,force:!0}),Wm(e,{recursive:!0}),Gm(yo,e,{recursive:!0,filter:n=>!/[/\\]\.terraform([/\\]|$)/.test(n)}),!Fm(wo(e,"main.tf")))throw new Error(`The Terraform module wasn't found in this package (${yo}).`);return`./${er}`}var ot=t=>/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(t);function qu(t,e){let n=i=>{let[o,a]=i.split("-",2);return{nums:o.split(".").map(Number),pre:a??null}},s=n(t),r=n(e);for(let i=0;i<3;i++)if(s.nums[i]!==r.nums[i])return s.nums[i]-r.nums[i];return s.pre===r.pre?0:s.pre===null?1:r.pre===null||s.pre<r.pre?-1:1}var Ve="kuriko.json";function pe(t,e){nr(Ce(t,Ve),JSON.stringify(e,null,2)+`
|
|
242
|
+
`)}function It(t){try{return JSON.parse(tr(Ce(t,Ve),"utf8"))}catch{throw new Error(`${t} has no ${Ve}, so it wasn't made by kuriko install. Upgrade it by hand (terraform apply).`)}}var bo=null,Tn=t=>bo=t;function Bu(t,e){if(!e.releaseUsername)return null;let n=/^release_token_version\s*=\s*"([^"]+)"/m.exec(tr(Ce(t,"terraform.tfvars"),"utf8"))?.[1];return n?{upstream:ae.upstream,owner:ae.owner,username:e.releaseUsername,tokenSecret:$e,tokenVersion:n}:null}async function sr(t){await P("Setting up deploy events",async()=>{await Ys(t.project,["pubsub.googleapis.com"]),await uo(t.project,"pubsub.googleapis.com")})}function Pt(t,e,n){nr(Ce(t,"terraform.tfvars"),Vl(e,n,bo))}function rr(t,e){nr(Ce(t,"main.tf"),Yl(e,xu(t),`${e.project}-tfstate`,bo,!!W))}function Uu(t){try{return/^version_tag\s*=\s*"([^"]+)"/m.exec(tr(Ce(t,"terraform.tfvars"),"utf8"))?.[1]??null}catch{return null}}async function at(t,e){try{return(await L("terraform",["state","list"],{cwd:t})).split(`
|
|
243
|
+
`).includes(e)}catch{return!1}}async function ir(t){if(W)return W.version;let e=(await L("git",["rev-parse","--short","HEAD"],{cwd:H})).trim();if(!(await L("git",["status","--porcelain"],{cwd:H})).trim())return e;if(!t)throw new Error("The Kuriko checkout has uncommitted changes, so its version isn't a commit. Commit them, or pass --allow-dirty.");return`${e}-dirty-${Date.now().toString(36)}`}async function Gu(t,e){let n=s=>s.replace(/-dirty-.*$/,"");try{return(await L("git",["log","--oneline","--no-decorate",`${n(t)}..${n(e)}`],{cwd:H})).split(`
|
|
244
|
+
`).filter(Boolean)}catch{return[]}}async function ko(t,e,n){let s=`.kuriko-${e}.plan`;await L("terraform",["plan","-input=false",...(n??[]).map(o=>`-target=${o}`),`-out=${s}`],{cwd:t});let r=await Q("terraform",["show","-json",s],{cwd:t}),i=zl(r);if(i.length)throw new Error(`This would delete or replace existing resources, which Kuriko never does on its own:
|
|
238
245
|
${i.map(o=>` ${o}`).join(`
|
|
239
246
|
`)}
|
|
240
|
-
Nothing was changed.`);return{file:s,plan:r}}async function
|
|
247
|
+
Nothing was changed.`);return{file:s,plan:r}}async function or(t,e,n){let{file:s,plan:r}=await ko(t,e,n);Ms(r).length&&await L("terraform",["apply","-input=false",s],{cwd:t})}async function ar(t,e,n){for(let s=1;;s++)try{return await or(t,e,n)}catch(r){if(!(r instanceof ee&&Wl(r.stderr))||s>=8)throw r;await new Promise(i=>setTimeout(i,2e4))}}async function cr(t,e,n,s){let r=await P(`${s}, in the cloud`,()=>Nt(t.project,t.region,e,n));if(r.code!==0)throw new Error(`${s} failed in the cloud:
|
|
241
248
|
${r.logs.slice(-10).map(i=>` ${i}`).join(`
|
|
242
|
-
`)}`);
|
|
243
|
-
Access key (hidden as you type or paste):`)).trim();if(!o)continue;if(!/^kuriko_[0-9a-f]{64}$/.test(o)){
|
|
249
|
+
`)}`);N(s)}var Qm=[["gateway","apps/gateway/Dockerfile",null],["web","apps/web/Dockerfile",null],["web-migrate","apps/web/Dockerfile","migrate"]];async function lr(t,e,n){await L("gcloud",["auth","configure-docker",`${t}-docker.pkg.dev`,"--quiet"]);for(let[s,r,i]of Qm){let o=`${e}/${s}:${n}`;if(await pu(o)){N(`${s} (already pushed)`);continue}await P(`Building and pushing ${s}`,()=>L("docker",["buildx","build","--platform","linux/amd64","-f",r,...i?["--target",i]:[],"-t",o,"--push","."],{cwd:H})),N(s)}}async function ur(t,e){let n=o=>P("Checking access to Kuriko's images",()=>bu(ae,ae.username,o,"gateway",e)),s=await vn(t.project,$e),r=!1;if(s&&t.releaseUsername===ae.username){let o=await n(await wu(t.project,$e));if(o==="ok")r=!0;else{if(o==="missing")throw new Error(`Kuriko ${e} isn't published on ${ae.host} yet. Use an earlier CLI version, or ask your Kuriko contact.`);if(o==="denied")x("This install's access key no longer works: Kuriko has revoked it. Paste the new key Kuriko gave you.");else throw new Error(`Couldn't reach ${ae.host} to check this install's access key. Check your connection and run this again.`)}}else s&&t.releaseUsername&&x(`Kuriko's images now come from ${ae.host}, which takes an access key instead of the registry token this install has.`);if(r)N(`Kuriko's images ${e}: access checked`);else for(Ee("Kuriko access key",["Kuriko's images are private. This install pulls them with an access key that Kuriko gives you,",`one per install. It looks like ${_("kuriko_")} followed by 64 letters and digits.`,"",`It goes straight into this project's Secret Manager (${$e}), where only Artifact`,"Registry can read it. It never goes into a file or the installs repo.","Don't have one? Ask your Kuriko contact."]);;){let o=(await Gs(`
|
|
250
|
+
Access key (hidden as you type or paste):`)).trim();if(!o)continue;if(!/^kuriko_[0-9a-f]{64}$/.test(o)){x("That isn't an access key: they start with kuriko_ and have 64 letters and digits after it. Paste the whole key.");continue}let a=await n(o);if(a==="denied"){x("Kuriko doesn't recognise that key, or it has been revoked. Check you pasted the key for this install, or ask Kuriko for a new one.");continue}if(a==="missing")throw new Error(`The key works, but Kuriko ${e} isn't published on ${ae.host} yet. Use an earlier CLI version, or ask your Kuriko contact.`);if(a==="unreachable"){x(`Couldn't reach ${ae.host} to check the key. Check your connection and try again.`);continue}await P("Storing the access key",()=>Ct(t.project,$e,o)),t.releaseUsername=ae.username,N(`Access key works and is stored in Secret Manager (${$e})`);break}await P("Setting up Artifact Registry's service account",()=>uo(t.project,"artifactregistry.googleapis.com"));let i=await yu(t.project,$e);if(!i)throw new Error(`${$e} has no enabled version.`);return{upstream:ae.upstream,owner:ae.owner,username:t.releaseUsername,tokenSecret:$e,tokenVersion:i}}function Fu(t){let e=["main.tf","terraform.tfvars",Ve].map(i=>Ce(t,i)),n=e.map(i=>Ku(i)?tr(i):null),s=Ce(t,er),r=Ku(s)?zm(Ce(Hm(),"kuriko-module-")):null;return r&&Mu(s,r,{recursive:!0}),()=>{e.forEach((i,o)=>n[o]?nr(i,n[o]):Du(i,{force:!0})),Du(s,{recursive:!0,force:!0}),r&&Mu(r,s,{recursive:!0})}}p();var Zm=t=>`kuriko_reads_${t.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"")}`;function Wu(t,e){return`${t.map(s=>{let[r,i]=s.split(".");return`resource "google_bigquery_dataset_iam_member" "${Zm(s)}" {
|
|
251
|
+
project = "${r}"
|
|
252
|
+
dataset_id = "${i}"
|
|
253
|
+
role = "roles/bigquery.dataViewer"
|
|
254
|
+
member = "serviceAccount:${e}"
|
|
255
|
+
}`}).join(`
|
|
256
|
+
|
|
257
|
+
`)}
|
|
258
|
+
|
|
259
|
+
# If ${t.length===1?"that dataset's":"a dataset's"} Terraform lists access { } blocks on google_bigquery_dataset instead, add this
|
|
260
|
+
# block there (mixing the two makes Terraform remove one or the other):
|
|
261
|
+
#
|
|
262
|
+
# access {
|
|
263
|
+
# role = "READER"
|
|
264
|
+
# user_by_email = "${e}"
|
|
265
|
+
# }`}p();import{createPrivateKey as Yu,createPublicKey as Xm,generateKeyPairSync as ey}from"node:crypto";import{existsSync as ty,readFileSync as ny}from"node:fs";import{homedir as sy}from"node:os";var ry=/^[a-z][a-z0-9-]{1,30}$/,iy=/^[A-Za-z_][A-Za-z0-9_$]{0,254}$/,oy=/^[A-Za-z0-9][A-Za-z0-9_.-]{1,254}$/,ay=/^[A-Za-z0-9_]{1,1024}$/,$o="snowflake-kuriko-key";function So(t){let e=`bq-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}`.slice(0,31).replace(/-$/,"");return ry.test(e)?e:"bq-warehouse"}function Vu(t,e){if(!t||t.kind==="none")return"";if(t.kind==="bigquery"){let n=new Set;return t.datasets.map(s=>{let r=So(s);for(let i=2;n.has(r);i++)r=`${So(s).slice(0,28)}-${i}`;return n.add(r),` ${r}: # BigQuery: no credential; the dataset's owners grant Kuriko read access
|
|
266
|
+
name: ${s} (BigQuery)
|
|
267
|
+
kind: bigquery
|
|
268
|
+
dataset: ${s}${t.project!==e?`
|
|
269
|
+
project: ${t.project}`:""}
|
|
270
|
+
`}).join(`
|
|
271
|
+
`)}return` snowflake: # Snowflake: signs in as ${t.user} with the key in Secret Manager
|
|
272
|
+
name: ${t.database} (Snowflake)
|
|
273
|
+
kind: snowflake
|
|
274
|
+
secret: ${t.secret}
|
|
275
|
+
account: ${t.account}
|
|
276
|
+
user: ${t.user}
|
|
277
|
+
role: ${t.role}
|
|
278
|
+
warehouse: ${t.warehouse}
|
|
279
|
+
database: ${t.database}
|
|
280
|
+
schema: ${t.schema}
|
|
281
|
+
`}function Ju(t){return!t||t.kind==="none"?"":`#
|
|
282
|
+
# Your warehouse is connected above, but nobody can read it until a group is granted here, e.g.:
|
|
283
|
+
#
|
|
284
|
+
# - group: data@example.com
|
|
285
|
+
# connector: ${t.kind==="bigquery"?So(t.datasets[0]):"snowflake"}
|
|
286
|
+
# resources: ["*"] # every table, or name them: [orders, customers]
|
|
287
|
+
# access: read
|
|
288
|
+
`}async function zu(t){M("Connecting a data warehouse (optional)"),k(A(" If your company's data is in a warehouse, Kuriko can connect it now. Nobody can read it until you")),k(A(" grant a group access in policy.yaml. Databases (Postgres) and APIs can be added there any time."));let e=await oe(`
|
|
289
|
+
Is your data in a warehouse?`,[{label:"BigQuery",value:"bigquery",hint:"Kuriko reads it with its own Google identity; no key needed"},{label:"Snowflake",value:"snowflake",hint:"Kuriko signs in with a key it keeps in Secret Manager"},{label:"No warehouse",value:"none",hint:"add data sources later in policy.yaml"}]);return e==="bigquery"?cy(t):e==="snowflake"?ly(t):{kind:"none"}}async function cy(t){for(;;){k(A(" Usually your data team's project, not the one Kuriko runs in."));let e=await V(" Which Google Cloud project is the warehouse in?");if(!/^[a-z][a-z0-9-]{4,28}[a-z0-9]$/.test(e)){x("That isn't a Google Cloud project ID (e.g. acme-data).");continue}let n=await P(`Looking for datasets in ${e}`,()=>Su(e)),s;if(n?.length)k(A(" Pick the datasets tools may reach. Kuriko doesn't change who can read them: at the end of the")),k(A(" install it prints the Terraform whoever manages them adds, to let Kuriko's gateway read just these.")),s=await Fs(`
|
|
290
|
+
Which datasets?`,n.map(r=>({label:r.id,value:r.id,hint:r.location})),()=>!1);else{x(n?`${e} has no datasets you can see.`:`Couldn't list ${e}'s datasets (BigQuery may be off there, or your account can't see them).`),s=(await V(" Dataset names, separated by commas (or Enter to skip):")).split(",").map(o=>o.trim()).filter(Boolean);let i=s.filter(o=>!ay.test(o));if(i.length){x(`${i.join(", ")} ${i.length===1?"isn't a dataset name":"aren't dataset names"} (letters, digits and _).`);continue}}if(!s.length){if(await z(" No datasets picked. Continue without a warehouse?",!0))return{kind:"none"};continue}return N(`BigQuery: ${s.map(r=>`${e}.${r}`).join(", ")}`),{kind:"bigquery",project:e,datasets:s}}}var On=async(t,e)=>{for(;;){let n=await V(t,e);if(iy.test(n))return n;x("Use letters, digits and _ (a name as you'd write it in Snowflake without quotes).")}};async function ly(t){let e;for(;e=(await V(" Snowflake account identifier (orgname-accountname, from Admin \u2192 Accounts):")).replace(/\.snowflakecomputing\.com.*$/,"").replace(/^https?:\/\//,""),!oy.test(e);)x("That doesn't look like an account identifier, e.g. acme-analytics.");let n=await On(" Database tools read:"),s=await On(" Schema:","PUBLIC"),r=await On(" Warehouse queries run on:","COMPUTE_WH"),i=await On(" User Kuriko signs in as:","KURIKO_READER"),o=await On(" Role it reads with:","KURIKO_READ"),a=await oe(`
|
|
291
|
+
Kuriko signs in to Snowflake with a key pair. Which key?`,[{label:"Make a new key now",value:"new",hint:"recommended: the private key goes straight into Secret Manager"},{label:"Use a key file I already have",value:"file",hint:"an unencrypted .p8 file"}]),c;if(a==="new")c=ey("rsa",{modulusLength:2048}).privateKey.export({type:"pkcs8",format:"pem"}).toString();else for(;;){let h=(await V(" Path to the private key file:")).replace(/^~(?=\/)/,sy());if(!ty(h)){x(`There's no file at ${h}.`);continue}c=ny(h,"utf8");try{Yu({key:c,format:"pem"});break}catch{x("That isn't an unencrypted private key. Make one without a passphrase: openssl pkcs8 -topk8 -nocrypt")}}await P("Storing the key in Secret Manager",()=>Ct(t.project,$o,c)),N(`Key stored as ${$o} ${A("(only Kuriko's gateway will be able to read it)")}`);let l=Xm(Yu(c)).export({type:"spki",format:"pem"}).toString().replace(/-----[A-Z ]+-----|\s/g,"");return Ee("Set up Kuriko's user in Snowflake (as an ACCOUNTADMIN, in a worksheet)",["Run this once. It makes a role that can only read this schema, and a user that signs in with Kuriko's key.","",...uy({user:i,role:o,warehouse:r,database:n,schema:s,publicKey:l}).map(h=>` ${_(h)}`),"",a==="file"?"If the user already has this key, the ALTER USER line changes nothing.":"The key above is the public half; the private half is only in Secret Manager."]),await V(" Press Enter when you've run it."),N(`Snowflake: ${e}, ${n}.${s} as ${i}`),{kind:"snowflake",account:e,user:i,warehouse:r,database:n,schema:s,role:o,secret:$o}}function uy(t){let e=`${t.database}.${t.schema}`;return[`CREATE ROLE IF NOT EXISTS ${t.role};`,`GRANT USAGE ON WAREHOUSE ${t.warehouse} TO ROLE ${t.role};`,`GRANT USAGE ON DATABASE ${t.database} TO ROLE ${t.role};`,`GRANT USAGE ON SCHEMA ${e} TO ROLE ${t.role};`,`GRANT SELECT ON ALL TABLES IN SCHEMA ${e} TO ROLE ${t.role};`,`GRANT SELECT ON FUTURE TABLES IN SCHEMA ${e} TO ROLE ${t.role};`,`CREATE USER IF NOT EXISTS ${t.user} TYPE = SERVICE DEFAULT_ROLE = ${t.role} DEFAULT_WAREHOUSE = ${t.warehouse};`,`ALTER USER ${t.user} SET RSA_PUBLIC_KEY = '${t.publicKey}';`,`GRANT ROLE ${t.role} TO USER ${t.user};`]}var U="policy.yaml",vo="KURIKO_RESULT ";function fy(t){let e=Math.max(...me.map(o=>o.id.length)),n=o=>`# ${o.name}: ${o.where}${o.notYet?` (not yet: ${o.notYet})`:""}`,s=o=>t.includes(o.id)&&!o.notYet?` - ${o.id.padEnd(e+2)} ${n(o)}`:` # - ${o.id.padEnd(e)} ${n(o)}`,r=t.filter(o=>!me.some(a=>a.id===o)),i=[...me.map(s),...r.map(o=>` - ${o}`)];return`# AI apps people may connect to Kuriko with, to build and use tools. Which data someone sees never
|
|
244
292
|
# depends on the app: their own access above applies either way. This only decides which apps may
|
|
245
293
|
# act on their behalf. Remove the # to allow one; take an app out and it stops working within an hour.
|
|
246
294
|
# Any other app that signs in with a client metadata document can be listed by that document's URL:
|
|
247
295
|
# - https://example.com/oauth/client-metadata.json
|
|
248
|
-
${
|
|
296
|
+
${t.some(o=>!qn(o)?.notYet)?"clients:":"clients: [] # nobody can connect from an AI app yet"}
|
|
249
297
|
${i.join(`
|
|
250
298
|
`)}
|
|
251
|
-
`}function
|
|
252
|
-
# then run kuriko policy apply
|
|
299
|
+
`}function Zu(t,e=""){let n=Vu(t.warehouse,t.project);return`# Who can do what in Kuriko (${t.project}). This file is the source of truth: change it here,
|
|
300
|
+
# then run kuriko policy apply (it shows the changes and asks first).
|
|
253
301
|
# Credentials never go in this file. They live in Secret Manager; a connector only names its secret.
|
|
254
302
|
|
|
255
303
|
# Google groups -> Kuriko role. Admins manage access and see the audit log; builders make tools.
|
|
256
304
|
# Everyone else who can sign in is a Viewer: they use the tools shared with them.
|
|
257
305
|
roles:
|
|
258
|
-
${
|
|
259
|
-
${
|
|
306
|
+
${t.adminsGroup}: Admin
|
|
307
|
+
${t.buildersGroup}: Builder
|
|
260
308
|
|
|
261
309
|
${e}# Data sources tools can use. Credentials stay in Secret Manager under any name (an existing secret
|
|
262
310
|
# is fine); Kuriko's gateway can read only the ones named here.
|
|
263
311
|
#
|
|
264
|
-
# warehouse: #
|
|
312
|
+
# warehouse: # BigQuery: no credential at all. Whoever manages the dataset grants
|
|
313
|
+
# name: Warehouse # Kuriko read access; kuriko policy plan prints the Terraform for it
|
|
314
|
+
# kind: bigquery
|
|
315
|
+
# dataset: analytics # or other-project.analytics
|
|
316
|
+
#
|
|
317
|
+
# snowflake: # Snowflake: key-pair sign-in, the private key in Secret Manager
|
|
318
|
+
# name: Snowflake
|
|
319
|
+
# kind: snowflake
|
|
320
|
+
# secret: snowflake-kuriko-key
|
|
321
|
+
# account: acme-analytics # orgname-accountname
|
|
322
|
+
# user: KURIKO_READER
|
|
323
|
+
# role: KURIKO_READ
|
|
324
|
+
# warehouse: COMPUTE_WH
|
|
325
|
+
# database: ANALYTICS
|
|
326
|
+
# schema: PUBLIC
|
|
327
|
+
#
|
|
328
|
+
# app-db: # Postgres: a read-only user's connection URL, in Secret Manager
|
|
265
329
|
# name: Warehouse
|
|
266
330
|
# kind: postgres
|
|
267
331
|
# secret: warehouse-readonly
|
|
268
332
|
# schema: public
|
|
269
333
|
#
|
|
270
|
-
#
|
|
271
|
-
# name:
|
|
272
|
-
# kind:
|
|
273
|
-
#
|
|
334
|
+
# hubspot: # Any JSON API, described here instead of coded. The credential
|
|
335
|
+
# name: HubSpot # only ever goes to base_url.
|
|
336
|
+
# kind: api
|
|
337
|
+
# base_url: https://api.hubapi.com
|
|
338
|
+
# secret: hubspot-private-app-token
|
|
339
|
+
# auth: bearer # or basic (the secret is user:password), or header X-Api-Key
|
|
274
340
|
# resources:
|
|
275
|
-
#
|
|
341
|
+
# contacts:
|
|
342
|
+
# path: /crm/v3/objects/contacts?limit=100&properties=email,firstname,lastname
|
|
343
|
+
# rows: results # where the list is in the answer
|
|
344
|
+
# next: { cursor: paging.next.after, param: after } # or link, { url: ... }, { page: page }
|
|
345
|
+
# add: { path: /crm/v3/objects/contacts, body: { properties: $row } } # optional: lets tools add rows
|
|
276
346
|
#
|
|
277
|
-
#
|
|
278
|
-
# name:
|
|
279
|
-
# kind:
|
|
347
|
+
# hubspot-personal: # The same, each person signing in with their own HubSpot account
|
|
348
|
+
# name: HubSpot (yours)
|
|
349
|
+
# kind: api
|
|
280
350
|
# credentials: per-person
|
|
281
|
-
#
|
|
282
|
-
# secret:
|
|
351
|
+
# base_url: https://api.hubapi.com
|
|
352
|
+
# secret: hubspot-oauth-client-secret # the OAuth app's client secret
|
|
353
|
+
# oauth:
|
|
354
|
+
# authorize_url: https://app.hubspot.com/oauth/authorize
|
|
355
|
+
# token_url: https://api.hubapi.com/oauth/v1/token
|
|
356
|
+
# client_id: 1a2b3c4d-...
|
|
357
|
+
# scopes: [crm.objects.contacts.read]
|
|
283
358
|
# resources:
|
|
284
|
-
#
|
|
285
|
-
connectors:
|
|
286
|
-
|
|
359
|
+
# contacts: { path: /crm/v3/objects/contacts, rows: results, next: { cursor: paging.next.after, param: after } }
|
|
360
|
+
${n?`connectors:
|
|
361
|
+
${n}`:`connectors: {}
|
|
362
|
+
`}
|
|
287
363
|
# Who may use which data. group is a Google group email, or everyone. write includes read.
|
|
288
364
|
# A tool only ever gets what its viewer is granted here AND what the tool declared it needs.
|
|
289
365
|
# For a per-person source, this says who may use it at all; the source decides what each person sees.
|
|
290
366
|
#
|
|
291
367
|
# - group: everyone
|
|
292
|
-
# connector:
|
|
293
|
-
# resources: [
|
|
294
|
-
# access: write
|
|
368
|
+
# connector: hubspot
|
|
369
|
+
# resources: [contacts] # for a database or warehouse: table names, or ["*"] for every table
|
|
370
|
+
# access: write # only on resources that take new rows (add)
|
|
295
371
|
# mask: [] # fields that come back hidden
|
|
296
372
|
#
|
|
297
373
|
# rows limits a grant to some rows: every field must match, a list means any of these, and $me is
|
|
@@ -310,65 +386,38 @@ connectors: {}
|
|
|
310
386
|
# rows:
|
|
311
387
|
# stage: [won, lost] # finance sees closed deals,
|
|
312
388
|
# mask: [rep_email] # without who closed them
|
|
313
|
-
access: []
|
|
389
|
+
${Ju(t.warehouse)}access: []
|
|
314
390
|
|
|
315
|
-
${
|
|
316
|
-
`)[0]}`]):s}return
|
|
391
|
+
${fy(t.clients??Ie)}`}function Ne(t,e){let n;try{n=(0,pr.parse)(t,{prettyErrors:!0,uniqueKeys:!0})}catch(s){throw s instanceof pr.YAMLParseError?new ct([`It isn't valid YAML: ${s.message.split(`
|
|
392
|
+
`)[0]}`]):s}return Vo(n,s=>s.startsWith("projects/")?s:`projects/${e}/secrets/${s}`)}var Ao={add:Ue("+"),change:rt("~"),remove:be("-")};function dy(t){for(let e of t)k(` ${Ao[e.op]} ${e.op==="remove"?be(Kn(e)):Kn(e)}`)}async function fr(t,e,n){let s=await P(e,()=>Nt(t.project,t.region,"kuriko-migrate",["scripts/admin.ts",...n])),r=s.logs.find(o=>o.startsWith(vo));if(s.code===0&&r)return JSON.parse(r.slice(vo.length));if(s.logs.some(o=>o.includes("Unknown task")))throw new Error(`${t.project} is on a Kuriko version without policy files. Upgrade it first: kuriko upgrade`);let i=s.logs.filter(o=>!o.startsWith(vo)).slice(-8);throw new Error(`${e} failed in the cloud${i.length?`:
|
|
317
393
|
${i.map(o=>` ${o}`).join(`
|
|
318
|
-
`)}`:" (no logs yet; try again)"}`)}async function
|
|
319
|
-
Add any data sources and access this install already has (the plan would remove them otherwise), then run this again.`);
|
|
320
|
-
read -s TOKEN && printf '%s' "$TOKEN" | gcloud secrets create ${
|
|
321
|
-
${
|
|
322
|
-
Apply ${
|
|
394
|
+
`)}`:" (no logs yet; try again)"}`)}async function Xu(t,e){M("Checking this machine"),await ke(Fe(process.cwd(),e.dir)),await te();let n=await Ye(e.dir,"Which install's policy?",["installed"],{partial:"finish it with kuriko install"}),s=It(n);if(!await at(n,"module.kuriko.google_cloud_run_v2_job.migrate"))throw new Error(`${s.project} isn't fully installed yet. Finish it with kuriko install`);N(`Install ${_(s.project)} ${A(`(${D(n)})`)}`);let r=Co(n,U);if(!Eo(r))throw Qu(r,Zu(s)),new Error(`${s.project} had no ${U}, so one was started at ${D(r)} with just the two roles.
|
|
395
|
+
Add any data sources and access this install already has (the plan would remove them otherwise), then run this again.`);M(`Reading ${U}`);let i=Ne(_o(r,"utf8"),s.project),o=(b,v)=>`${b} ${v}${b===1?"":"s"}`;N(`${o(i.roles.length,"role rule")}, ${o(i.connectors.length,"data source")}, ${o(i.grants.length,"grant")}, ${o(i.clients.length,"AI app")}`),i.clients.length||x("clients is empty: nobody can connect to Kuriko from an AI app (Claude Code, Codex, \u2026).");let a=dr(i),c=[];if(await P("Checking the secrets it names exist",async()=>{for(let b of a)await An(b)||c.push(b)}),c.length){let[b,v]=c[0].split("/").filter((K,I)=>I%2===1);throw new Error(`Secret Manager has no ${c.map(K=>ze(K,s.project)).join(", ")} (or your account can't see ${c.length>1?"them":"it"}). Whoever manages credentials creates it, e.g.:
|
|
396
|
+
read -s TOKEN && printf '%s' "$TOKEN" | gcloud secrets create ${v} --project ${b} --data-file=- && unset TOKEN`)}a.length&&N(`Secrets exist: ${a.map(b=>ze(b,s.project)).join(", ")}`),M("What changes");let l=Buffer.from(JSON.stringify(i)).toString("base64"),h=await fr(s,"Comparing with the install, in the cloud",["policy-plan",l]);h.changes=h.changes.filter(b=>{if(b.kind!=="connector"||b.op!=="change")return!0;let v=h.connectors.find(q=>q.id===b.id),K=i.connectors.find(q=>q.id===b.id);if(!v||!K)return!0;let I=q=>br({roles:[],grants:[],clients:[],connectors:[q]}).connectors[0],R=Jo(I(v),I(K));return R[0]==="(settings differ only in form)"?!1:(b.summary=`${K.name}: ${R.join("; ")}`,!0)});let u={roles:[],grants:[],clients:[],connectors:h.connectors},f=await P("Checking which secrets the gateway can read",()=>ef(s,u,i)),d=await P("Checking which BigQuery datasets the gateway can read",()=>tf(s,u,i));h.lastApply?k(A(` Last applied ${new Date(h.lastApply.at).toLocaleString()} by ${h.lastApply.appliedBy}`)):k(A(" This would be the first apply. After it, access changes go through this file; admin tools in Claude point here."));let m=!h.changes.length&&!f.allow.length&&!f.disallow.length;if(m&&(N(`${s.project} already matches ${U}.`),t==="plan"||h.lastApply))return;dy(h.changes);for(let b of f.allow)k(` ${Ao.add} the gateway can read secret ${ze(b,s.project)}`);for(let b of f.disallow)k(` ${Ao.remove} ${be(`the gateway can no longer read secret ${ze(b,s.project)}`)}`);let g=i.connectors.filter(b=>b.mode==="delegated");if(g.length){let b=(await Ge(s.project))?.number;if(b){let v=st(s,b).mcp.replace(/\/mcp$/,"");for(let K of g)k(A(` ${K.id}: set the OAuth redirect URI to ${v}/connect/callback; people connect at ${st(s,b).web}/connect/${K.id}`))}}let y=h.changes.filter(b=>b.op==="remove").length+f.disallow.length,S=h.changes.filter(b=>b.op==="remove"&&(b.kind==="role"||b.kind==="grant")).length,C=h.changes.filter(b=>b.op==="remove"&&b.kind==="connector").length;S&&x(`${S} role${S===1?" or grant is":"s or grants are"} removed: people lose that access on their next request.`),C&&x(`${C} data source${C===1?" is":"s are"} removed: tools using ${C===1?"it":"them"} stop getting its data, and everyone's own connections to ${C===1?"it":"them"} are deleted.`);let O=h.changes.filter(b=>b.kind==="client"&&b.op==="remove");if(O.length&&x(`${O.map(b=>Lt(b.client)).join(", ")} can't sign anyone in any more, and ${O.length===1?"its":"their"} current sessions stop within an hour. People's access is unchanged in the apps that remain.`),f.disallow.length&&x(`Kuriko gives up ${f.disallow.length===1?"a secret":"secrets"} the file no longer names. Nobody loses access; the secret${f.disallow.length===1?" itself is":"s themselves are"} kept.`),nf(s,d),t==="plan"){k(`
|
|
397
|
+
${A("Plan only: nothing was changed. Apply with: kuriko policy apply")}`);return}if(!e.yes&&!await z(`
|
|
398
|
+
Apply ${m?`${U} (no changes; records it as the source of truth)`:"these changes"}?`,!y)){k("Nothing was changed.");return}await sf(s,f);let $=await Et(),T=await fr(s,"Applying, in the cloud",["policy-apply",l,$,h.hash]);await hy(s,f);let j=T.changes.length+f.allow.length+f.disallow.length;N(`${s.project} matches ${U} (${j} change${j===1?"":"s"}, recorded in the audit log as ${$})`),f.allow.length&&k(A(" New secret access can take a minute or two to reach Google's servers.")),await We([r],`Policy for ${s.project}: ${T.changes.length?T.changes.map(Kn).slice(0,3).join("; ")+(T.changes.length>3?"; \u2026":""):"first apply"}`)}var dr=t=>[...new Set(t.connectors.flatMap(e=>e.secretRef?[e.secretRef]:[]))].sort(),No=t=>`kuriko-gateway@${t.project}.iam.gserviceaccount.com`,jt=t=>`serviceAccount:${No(t)}`,Hu=(t,e)=>[...new Set(t.connectors.filter(n=>n.kind==="bigquery").map(n=>`${n.config.project??e}.${n.config.dataset}`))].sort(),py=t=>t.split(".");async function ef(t,e,n){let s=dr(n),r=[];for(let o of s)await En(o,jt(t))||r.push(o);let i=[];for(let o of dr(e))o.startsWith("projects/")&&!s.includes(o)&&await An(o)&&await En(o,jt(t))&&i.push(o);return{allow:r,disallow:i}}async function tf(t,e,n){let s=Hu(n,t.project),r={waiting:[],unknown:[],unused:Hu(e,t.project).filter(i=>!s.includes(i))};for(let i of s){let o=await vu(...py(i),No(t));if(o==="missing")throw new Error(`BigQuery has no dataset ${i} (or your account can't see it). Check the dataset in ${U}.`);o==="not-readable"&&r.waiting.push(i),o==="unknown"&&r.unknown.push(i)}return r}function nf(t,e){let n=[...e.waiting,...e.unknown];e.waiting.length&&x(`Kuriko can't read ${e.waiting.join(", ")} yet. Tools get "no access yet" from ${e.waiting.length===1?"it":"them"} until it's granted.`),e.unknown.length&&x(`Couldn't check who can read ${e.unknown.join(", ")} (your account can't see ${e.unknown.length===1?"its":"their"} access). If reads fail, it needs this grant.`),n.length&&(k(A(` Whoever manages ${n.length===1?"that dataset":"those datasets"} adds this to their Terraform (Kuriko never changes data it doesn't own):
|
|
399
|
+
`)),k(Wu(n,No(t)).split(`
|
|
400
|
+
`).map(s=>` ${s}`).join(`
|
|
401
|
+
`)),k("")),e.unused.length&&k(A(` No longer named here, so their grant to Kuriko can be removed: ${e.unused.join(", ")}`))}async function sf(t,e){e.allow.length&&await P("Letting the gateway read the new secrets",async()=>{for(let n of e.allow)await po(n,jt(t))})}async function hy(t,e){e.disallow.length&&await P("Taking away the gateway's access to secrets no longer used",async()=>{for(let n of e.disallow)await ku(n,jt(t))})}async function rf(t,e){let n=Co(e,U);if(!Eo(n))return[];let s=dr(Ne(_o(n,"utf8"),t.project)),r=[];for(let i of s)await An(i)&&!await En(i,jt(t))&&(await po(i,jt(t)),r.push(i));return r}async function of(t,e,n=""){let s=Co(e,U);Eo(s)||Qu(s,Zu(t,n));let r=Ne(_o(s,"utf8"),t.project),i=Buffer.from(JSON.stringify(r)).toString("base64"),o=await fr(t,"Reading the install's access, in the cloud",["policy-plan",i]);if(o.lastApply)return N(`Access comes from ${U} (change it with kuriko policy apply)`);let a={roles:[],grants:[],clients:[],connectors:o.connectors};await sf(t,await P("Checking which secrets the gateway can read",()=>ef(t,a,r)));let c=await P("Checking which BigQuery datasets the gateway can read",()=>tf(t,a,r));await fr(t,`Applying ${U}, in the cloud`,["policy-apply",i,await Et(),o.hash]),N(`Roles for your two groups${r.connectors.length?`, and ${r.connectors.map(l=>l.name).join(", ")}`:""}, from ${U}`),nf(t,c)}var Te="module.kuriko",wy=[`${Te}.google_sql_database_instance.kuriko`,`${Te}.google_sql_database.kuriko`,`${Te}.google_sql_user.kuriko`,`${Te}.google_cloud_run_v2_service.web`,`${Te}.google_cloud_run_v2_service.gateway`,`${Te}.google_cloud_run_v2_job.migrate`],by=[`${Te}.google_kms_crypto_key.user_tokens`,`${Te}.google_kms_key_ring.kuriko`],ky=new Set(["deletion_protection","deletion_policy"]);function $y(t){let e=Tu(t).filter(u=>u.address.startsWith(`${Te}.`)),n=e.find(u=>u.type==="google_project"&&u.mode==="data")?.values.project_id;if(typeof n!="string")throw new Error("This install has no Kuriko resources in its state (already destroyed, or never installed).");let s=e.filter(u=>u.mode==="managed"),r=u=>s.filter(f=>f.type===u),i=(u,f)=>String(u.values[f]??""),o=i(r("google_cloud_run_v2_service")[0]??r("google_artifact_registry_repository")[0]??{values:{}},"location"),a=[];for(let u of r("google_sql_database_instance"))a.push(`Cloud SQL instance ${_(i(u,"name"))} with all its data and backups: every user, tool, grant and audit record`);for(let u of r("google_cloud_run_v2_service"))a.push(`Cloud Run service ${i(u,"name")}`);for(let u of r("google_cloud_run_v2_job"))a.push(`Cloud Run job ${i(u,"name")}`);for(let u of r("google_secret_manager_secret"))a.push(`Secret ${i(u,"secret_id")} (generated by Kuriko)`);for(let u of r("google_service_account"))a.push(`Service account ${i(u,"email")}`);for(let u of r("google_artifact_registry_repository"))a.push(`Image repository ${i(u,"name")} and every image in it`);s.some(u=>u.type.endsWith("_iam_member"))&&a.push("Every IAM grant Kuriko made");let c=s.filter(u=>by.includes(u.address)).map(u=>u.address),l=r("google_kms_crypto_key").map(u=>`${i(u,"key_ring").split("/").pop()}/${i(u,"name")}`),h=e.find(u=>u.type==="google_secret_manager_secret"&&u.mode==="data");return{project:n,region:o,deletes:a,release:c,keys:l,idpSecret:h?i(h,"secret_id"):null}}function Sy(t){let e=[];for(let n of t.resource_changes??[]){let s=n.change.actions;if(s.length===1&&(s[0]==="no-op"||s[0]==="read"))continue;if(s.length!==1||s[0]!=="update"){e.push(`${n.address} would be ${s.join("/")}`);continue}let r=n.change.before??{},i=n.change.after??{},c=[...new Set([...Object.keys(r),...Object.keys(i),...Object.keys(n.change.after_unknown??{})])].filter(l=>n.change.after_unknown?.[l]===!0||JSON.stringify(r[l]??null)!==JSON.stringify(i[l]??null)).filter(l=>!ky.has(l));c.length&&e.push(`${n.address} would also change ${c.join(", ")}`)}return e}async function af(t){M("Checking this machine");for(let[d,m]of[["terraform","runs the install's Terraform"],["gcloud","finds what Kuriko created outside Terraform"]])if(!await He(d))throw new Error(`${d} isn't installed (${m}).`);await te(),await ke(Fe(process.cwd(),t.dir));let e=await Ye(t.dir,"Which install should be destroyed?",["installed","partial"],{empty:"nothing left to destroy",unknown:"can't read its state"}),n=(d,m=!1)=>L("terraform",d,{cwd:e,inherit:m});if(!Cu(e))throw new Error(`${e}/main.tf must pass deletion protection through to the module, so destroy can turn it off:
|
|
323
402
|
variable "deletion_protection" { type = bool, default = true }
|
|
324
|
-
and in module "kuriko": deletion_protection = var.deletion_protection`);
|
|
325
|
-
${
|
|
326
|
-
${
|
|
327
|
-
${
|
|
328
|
-
Type the project id (${s.project}) to destroy this install: `))!==s.project){
|
|
329
|
-
${f.map(
|
|
403
|
+
and in module "kuriko": deletion_protection = var.deletion_protection`);N(`Install at ${D(e)}`),M("Reading the install");let s=$y(await Q("terraform",["show","-json"],{cwd:e})),r=["--project",s.project,"--format=json"],i=(await Q("gcloud",["run","services","list","--region",s.region,...r])).filter(d=>d.metadata.labels?.["kuriko-tool"]).map(d=>d.metadata.name),o=yy(e,U),a=gy(o)?[...new Set(Ne(my(o,"utf8"),s.project).connectors.flatMap(d=>d.secretRef?[ze(d.secretRef,s.project)]:[]))]:[],c=Nu(e);k(`
|
|
404
|
+
${_(`Destroying Kuriko in ${s.project} (${s.region}) deletes, permanently:`)}`);for(let d of i)k(` ${be("\u2717")} Tool ${d} (Cloud Run service)`);for(let d of s.deletes)k(` ${be("\u2717")} ${d}`);k(`
|
|
405
|
+
${_("It keeps:")}`);let l=[...s.keys.map(d=>`KMS key ${d}. GCP never deletes keys; it costs cents a month and a reinstall here reuses it.`),...s.idpSecret?[`Your IdP client secret ${s.idpSecret}`]:[],...a.map(d=>`Your connector credential ${d}`),...c?[`Terraform state in ${c}`]:[],"The project itself and its enabled APIs"];for(let d of l)k(` ${A("\u2022")} ${d}`);if(t.dryRun){k(`
|
|
406
|
+
${A("Dry run: nothing was changed.")}`);return}if((t.confirm??await V(`
|
|
407
|
+
Type the project id (${s.project}) to destroy this install: `))!==s.project){k("That doesn't match. Nothing was changed.");return}M("Turning off deletion protection");let u=".kuriko-unlock.plan";await n(["plan","-input=false","-var","deletion_protection=false",...wy.map(d=>`-target=${d}`),`-out=${u}`]);let f=Sy(JSON.parse(await n(["show","-json",u])));if(f.length)throw new Error(`The install's config doesn't match what's deployed, so turning off protection would change more than that:
|
|
408
|
+
${f.map(d=>` ${d}`).join(`
|
|
330
409
|
`)}
|
|
331
|
-
Apply the config first (or fix it), then run destroy again.`);if(await
|
|
332
|
-
${
|
|
333
|
-
${
|
|
334
|
-
To remove everything at once: ${
|
|
335
|
-
# Name one in roles or access to give its members something; groups not named here get nothing.`;if(!
|
|
410
|
+
Apply the config first (or fix it), then run destroy again.`);if(await n(["apply","-input=false",u],!0),N("Deletion protection is off"),i.length){M(`Deleting ${i.length} tool${i.length===1?"":"s"}`);for(let d of i)await L("gcloud",["run","services","delete",d,"--region",s.region,"--project",s.project,"--quiet"]),N(d)}s.release.length&&(M("Keeping the KMS key out of the destroy"),await n(["state","rm",...s.release]),N("Terraform no longer manages the key; it stays in the project")),M("Destroying everything else (Cloud SQL takes a few minutes)"),await n(["destroy","-input=false","-auto-approve","-var","deletion_protection=false"],!0),k(`
|
|
411
|
+
${_(`Kuriko is gone from ${s.project}.`)} Still there, by design:`);for(let d of l)k(` ${A("\u2022")} ${d}`);k(`
|
|
412
|
+
${_("Outside Google Cloud")} (yours to remove if you're done with Kuriko):`),k(` ${A("\u2022")} The OAuth client for Kuriko's sign-in, and the Groups Reader role assignment for the deleted kuriko-web account`),k(` ${A("\u2022")} Your kuriko-admins / kuriko-builders groups`),k(`
|
|
413
|
+
To remove everything at once: ${_(`gcloud projects delete ${s.project}`)}`),await We([e],`Destroy ${s.project}`,{remove:!0})}p();import{existsSync as In,mkdirSync as qy,readFileSync as mf,writeFileSync as My}from"node:fs";import{basename as Ky,join as Je}from"node:path";p();import{existsSync as vy,readFileSync as Ay}from"node:fs";import{join as Ey}from"node:path";var _y=40,Cy=t=>t.endsWith(".guest.google")||/^(abuse|postmaster)@/.test(t);async function To(t){let e=await _t().catch(()=>[]),n=(e.find(r=>r.name===t.domain)??e[0])?.customerId;if(!n)return null;let s=await Vs(t.project,n).catch(()=>null);return s&&s.filter(r=>!Cy(r.email))}function cf(t,e){let n=t.filter(a=>a.email!==e.adminsGroup&&a.email!==e.buildersGroup),s=`# Groups in ${e.domain} when this file was made (kuriko groups lists them now).
|
|
414
|
+
# Name one in roles or access to give its members something; groups not named here get nothing.`;if(!n.length)return`${s}
|
|
336
415
|
# (none besides the two above)
|
|
337
|
-
`;let r=
|
|
416
|
+
`;let r=n.slice(0,_y),i=Math.max(...r.map(a=>a.email.length)),o=r.map(a=>`# ${a.name&&a.name.toLowerCase()!==a.email.split("@")[0]?`${a.email.padEnd(i)} ${a.name}`:a.email}`);return n.length>r.length&&o.push(`# \u2026 and ${n.length-r.length} more`),`${s}
|
|
338
417
|
${o.join(`
|
|
339
418
|
`)}
|
|
340
|
-
`}function
|
|
341
|
-
Copy an email into ${
|
|
342
|
-
|
|
343
|
-
This puts Kuriko in your own cloud. Everything runs there, under your control: your people sign
|
|
344
|
-
in with the accounts they already have, and credentials stay in your own secret manager.
|
|
345
|
-
|
|
346
|
-
First a few questions; nothing is created until you've seen the plan and said yes. Then it takes
|
|
347
|
-
about 30 minutes, mostly waiting for the database. A few steps happen in your providers' admin
|
|
348
|
-
pages; this explains each one and checks it before moving on. If anything fails, run it again:
|
|
349
|
-
it picks up where it stopped.`);let e=he();await me(e);let t=n.dir?bn(n.dir):await wg(),s=t&&rr(nt(t,Ge))?JSON.parse(vu(nt(t,Ge),"utf8")):null;s||(v(""),await le("Where should Kuriko run?",[{label:"Google Cloud",value:"gcp",hint:"in a project of yours"},{label:"AWS",value:"aws",hint:"coming soon",disabled:!0},{label:"Azure",value:"azure",hint:"coming soon",disabled:!0},{label:"Managed by Kuriko",value:"managed",hint:"coming soon: we run it for you",disabled:!0}]),await le("Where do your people sign in?",[{label:"Google Workspace",value:"google-workspace"},{label:"Okta",value:"okta",hint:"coming soon",disabled:!0},{label:"Microsoft Entra ID",value:"entra",hint:"coming soon",disabled:!0},{label:"Another OIDC or SAML provider",value:"other",hint:"coming soon",disabled:!0}])),q("Checking this machine");for(let[b,_,M]of[["gcloud","Google Cloud's CLI: https://cloud.google.com/sdk/docs/install","--version"],["terraform","creates the cloud resources: https://developer.hashicorp.com/terraform/install","-version"]])if(!await Fe(b,M))throw new Error(`${b} isn't installed (${_}).`);if(!F){if(!await Fe("git","--version"))throw new Error("git isn't installed (it identifies the Kuriko version).");try{await j("docker",["info","--format","{{.ServerVersion}}"])}catch{throw new Error("Docker isn't running. Start Docker Desktop (it builds Kuriko's images), then run this again.")}}let r=await $t();if(!r)throw new Error("gcloud isn't signed in. Run: gcloud auth login");let i=r.split("@")[1]??"";if(/^(gmail|googlemail)\.com$/.test(i))throw new Error(`gcloud is signed in as ${r}. Sign in with your Google Workspace admin account instead: gcloud auth login`);await X(),T(`Signed in to Google Cloud as ${r}`);let o;if(s){q(`Continuing the install in ${s.project}`);let b=await De(s.project);if(!b||b.state!=="ACTIVE")throw new Error(`Project ${s.project} isn't available (deleted, or your account can't see it).`);o=b.number,T(`Project ${s.project} ${I(`(${t})`)}`)}else{q("Your Google Cloud project"),v(" Kuriko should have a project to itself, so its permissions don't mix with anything else.");let b=await le("New project or existing?",[{label:"Create a new project",value:!0,hint:"recommended"},{label:"Use an existing, empty project",value:!1}]),_="",M=null;if(b){let ie=await P("Finding your organization",()=>St());if(!ie.length)throw new Error(`${r} can't see any Google Cloud organization. Projects for Kuriko should live in your Workspace's organization.`);M=await Hi("Organization:",ie.map(we=>({label:we.name,value:we,hint:we.id}))),_=await sr("Project ID (can't be changed later):",`kuriko-${Math.floor(1e3+Math.random()*9e3)}`,Gi,"6\u201330 characters, starting with a letter: lowercase letters, digits and hyphens.")}else for(;_=await ce("Project ID:"),!await P("Looking it up",()=>De(_));)v(` Can't find ${_}, or ${r} can't see it.`);let G=null;if(b||!await P("Checking billing",()=>Rl(_))){let ie=await P("Finding billing accounts",()=>Ll());if(!ie.length)throw new Error("No open billing account. Create one at https://console.cloud.google.com/billing, then run this again.");G=await Hi("Billing account:",ie.map(we=>({label:we.name,value:we,hint:we.id})))}let D=await yg();q("The plan");let se=(ie,we)=>v(` ${I(ie.padEnd(10))}${we}`);if(se("Runs in",`Google Cloud \xB7 ${b?`new project ${C(_)}${M?` in ${M.name}`:""}`:`existing project ${C(_)}`} \xB7 ${D}`),G&&se("Billing",`${G.name} ${I(G.id)}`),se("Sign-in",`Google Workspace \xB7 people at ${C(i)}`),se("Admins",`kuriko-admins@${i}`),se("Builders",`kuriko-builders@${i}`),se("Cost","about $10\u201315 a month, almost all of it the database; the rest scales to zero when idle"),v(""),!await H("Start?",!0)){v("Nothing was created.");return}if(b){for(;;)try{await P(`Creating project ${_}`,()=>ql(_,M.id));break}catch(ie){if(!(ie instanceof Q&&/already (in use|exists)/i.test(ie.stderr)))throw ie;v(` ${_} is taken (project IDs are unique across all of Google Cloud).`),_=await sr("Another project ID:",void 0,Gi,"6\u201330 characters, starting with a letter: lowercase letters, digits and hyphens.")}T(`Created project ${_}`)}G&&(await P("Linking billing",()=>xl(_,G.id)),T("Billing linked")),o=(await De(_)).number,s={host:"gcp",sso:"google-workspace",project:_,region:D,domain:i,adminEmail:r,adminsGroup:`kuriko-admins@${i}`,buildersGroup:`kuriko-builders@${i}`,dbInstanceName:""},t=nt(e,_),ug(t,{recursive:!0}),ye(t,s)}let a=t,c=Qe(s,o);q("Turning on the Google Cloud services Kuriko uses"),await P("Enabling APIs",()=>Ps(s.project,hl)),await Vs(s),T("Cloud Run, Cloud SQL, Secret Manager, KMS, Artifact Registry, Cloud Build, Pub/Sub, IAM, Cloud Identity"),q("Somewhere to keep Kuriko's Terraform state");let l=`${s.project}-tfstate`,d=await P("Creating the state bucket",()=>Ml(l,s.project,s.region));T(`gs://${l} ${I(`(${d}; versioned, private)`)}`);let u=await Dl(s.project);s.dbInstanceName||(s.dbInstanceName=wl(u.map(b=>b.name)),ye(a,s));let f=await Ws(n.allowDirty);F&&(q(`Kuriko ${f}`),$n(await Zs(s,f)),ye(a,s)),Js(a,s),await P("Preparing Terraform",()=>j("terraform",["init","-input=false"],{cwd:a}));let h={},y=()=>fg(nt(a,"imports.tf"),Al(s,h));await tt(a,"module.kuriko.google_kms_key_ring.kuriko")||(Object.assign(h,await Kl(s.project,s.region,fn.ring,fn.key)),h.ring&&T("Found a KMS key from an earlier install; this one will reuse it")),y(),T(`Install config in ${a}`),q("Kuriko's service accounts and image registry"),Nt(a,s,f),await P("Creating service accounts and the image registry",()=>Hs(a,"bootstrap",ml)),T("kuriko-web, kuriko-gateway and kuriko-tools service accounts; image registry"),q("Kuriko's database");let m={started:Date.now(),state:"creating",note:""},w=Promise.resolve();if(await tt(a,As))m.state="ready",T(`Database ${s.dbInstanceName} ${I("(already created)")}`);else{let b=u.find(_=>_.name===s.dbInstanceName&&_.kuriko);if(b)h.sqlInstance=b.name,y(),T(`Found database ${b.name} from an earlier run; picking it up`);else if(v(" Cloud SQL takes 10\u201315 minutes to create, so it starts now and carries on while you do the next steps."),v(" It's most of Kuriko's cost: about $10\u201315 a month. The rest scales to zero when nobody's using it."),!await H(" Start creating it?",!0))throw new Error("Stopped before creating the database. Run install again to continue.");w=mg(a,s,f,m).then(()=>m.state="ready",_=>(m.state="failed",_)),zi(()=>m.state==="creating"?`database: ${m.note||"creating"} (${Cs(m.started)})`:m.state==="ready"?"database: ready":"database: failed"),T("Started; it'll be ready in about 10\u201315 minutes")}for(F||(q(`Kuriko's images (version ${f})`),v(I(" Built from this checkout (development). Released versions pull Kuriko's published images instead.")),await Xs(s.region,c.registry,f)),Ze("Let people sign in with Google (an OAuth app, in Google Cloud)",["Kuriko signs people in with their Google accounts. Google needs an OAuth app in this project for that.","",`1. Open ${C(c.newClient)}`,` If Google first asks you to set up the app (${C("Get started")}): App name ${C("Kuriko")}, support email: you,`,` Audience: ${C("Internal")} (only people in ${s.domain} can sign in), contact email: you. Agree, ${C("Create")},`," then open the link again. If it goes straight to a form for a new client, skip this.","",`2. Application type: ${C("Web application")}. Name: ${C("Kuriko")}.`,` Under Authorized redirect URIs, ${C("Add URI")} and paste exactly:`,` ${C(c.redirect)}`,` Then ${C("Create")}. A dialog shows the Client ID and Client secret: keep it open.`]);;){let b=await sr(`
|
|
350
|
-
Client ID:`,s.idpClientId,yl,"It looks like 1234567890-abc123.apps.googleusercontent.com."),_=b!==s.idpClientId;if(s.idpClientId=b,ye(a,s),await mn(s.project,dn)&&!_&&!await H(` A client secret is already in Secret Manager (${dn}). Replace it?`)){T("Keeping the stored client secret");break}v(I(` The secret goes straight into Secret Manager as ${dn}. It isn't shown or saved anywhere else.`));let G=await Ts(" Client secret (hidden as you type or paste):");if(!G)continue;let D=await P("Checking them with Google",()=>Gl(b,G,c.redirect));if(D===!1){R("Google doesn't accept that client ID and secret together. Copy both again from the same client.");continue}await P("Storing the secret",()=>js(s.project,dn,G)),T(`Client secret stored in Secret Manager${D?", and Google accepts it":""}`);break}s.groupsChosen||((await Promise.all([s.adminsGroup,s.buildersGroup].map(_=>qs(s.project,_,s.adminEmail).catch(()=>null)))).every(_=>_?.exists)||await bg(s),s.groupsChosen=!0,ye(a,s)),s.clients||(s.clients=await pg(a),ye(a,s)),Ze("Decide who runs Kuriko (Google Groups)",["Kuriko gives roles by Google Group, so access is managed where you already manage people:",` ${C(s.adminsGroup)} Admin: manages who can use which data, sees the audit log.`,` ${C(s.buildersGroup)} Builder: builds tools.`,` Everyone else in ${s.domain} can sign in and use tools shared with them. Groups inside these groups count too.`]);let A=()=>P("Looking for the groups",()=>Promise.all([qs(s.project,s.adminsGroup,s.adminEmail),qs(s.project,s.buildersGroup,s.adminEmail)])),[$,E]=await A(),N=[!$.exists&&s.adminsGroup,!E.exists&&s.buildersGroup].filter(b=>!!b),g=!1;if(N.length&&await H(`
|
|
351
|
-
Create ${N.join(" and ")} now${$.exists?"":`, with you in ${s.adminsGroup}`}?`,!0)){let b=await St(),_=(b.find(M=>M.name===s.domain)??b[0])?.customerId;if(!_)throw new Error("Couldn't find your Workspace's customer ID to create the groups. Create them in the Admin console instead.");for(let[M,G,D,se]of[[s.adminsGroup,"Kuriko admins","Kuriko Admin role: manages who can use which data, sees the audit log.",!0],[s.buildersGroup,"Kuriko builders","Kuriko Builder role: builds tools on Kuriko.",!1]])N.includes(M)&&(await P(`Creating ${M}`,()=>Fl(s.project,{customerId:_,email:M,name:G,description:D,owner:se})),T(`Created ${M}${se?" (you're its owner)":""}`));if(g=!0,!E.exists){let M=(await ce(` Who should build? Their ${s.domain} emails, comma-separated (Enter to add people later):`)).split(/[\s,]+/).filter(Boolean);for(let G of M){if(!vs(G)){R(`Skipped ${G}: not an email address.`);continue}try{await P(`Adding ${G}`,()=>Qi(s.project,s.buildersGroup,G)),T(`Added ${G} to ${s.buildersGroup}`)}catch(D){R(`Couldn't add ${G}: ${D instanceof Error?D.message:String(D)}`)}}}}else N.length&&Ze("Create the groups in the Google Admin console",[`${C("https://admin.google.com/ac/groups")} \u2192 ${C("Create group")}, once for each group email above.`,`Under access settings choose ${C("Restricted")} (only members see the member list) and no external members.`,`Add yourself to ${s.adminsGroup}, and the people who'll build to ${s.buildersGroup}.`]);for(let b=0;;b++){if(b&&([$,E]=await A()),$.exists&&E.exists&&$.isMember){T(`${s.adminsGroup} (you're in it) and ${s.buildersGroup} are ready`);break}if(g&&b<6){await new Promise(M=>setTimeout(M,3e3));continue}if($.exists&&!$.isMember&&await H(` You're not in ${s.adminsGroup}, so you wouldn't be a Kuriko admin. Add you?`,!0)){await P("Adding you",()=>Qi(s.project,s.adminsGroup,s.adminEmail)),g=!0,b=0;continue}let _=[!$.exists&&s.adminsGroup,!E.exists&&s.buildersGroup].filter(Boolean);_.length?R(`Not found yet: ${_.join(", ")} (or ${s.adminEmail} can't see ${_.length>1?"them":"it"}).`):R(`${s.adminEmail} isn't in ${s.adminsGroup}. Add yourself, or you won't be an admin.`),await ce(" Press Enter to check again.")}Ze("Let Kuriko see group membership (Groups Reader role, in the Google Admin console)",["Google doesn't tell apps which groups someone is in when they sign in, so Kuriko asks Google","directly. It needs the Groups Reader admin role for that: it can read group membership and nothing else.","",`1. Open ${C("https://admin.google.com/ac/roles")} and click ${C("Groups Reader")}.`,`2. Open ${C("Admins")} (or "Assign role"), then ${C("Assign service accounts")}.`,`3. Paste ${C(c.webServiceAccount)}, click ${C("Add")}, then ${C("Assign role")}.`,"","It can take a few minutes to take effect. Kuriko checks it at the end."]),await ce(" Press Enter when you've assigned it."),q("Creating Kuriko");let O=await P("Waiting for the database",()=>w);if(zi(null),m.state==="failed")throw O;T(`Database ${s.dbInstanceName} ${I(`(${Cs(m.started)} in all)`)}`),Nt(a,s,f),await P("Creating Kuriko's secrets, key and services",()=>Hs(a,"install",null));for(let b of Object.keys(h))delete h[b];y(),T("Kuriko's secrets, key and services"),q("Setting up Kuriko's database"),await Qs(s,"kuriko-migrate",void 0,"Database schema");let L="";if(!rr(nt(a,B))){let b=await P("Reading your Workspace's groups for policy.yaml",()=>po(s));b&&(L=ku(b,s))}for(await wu(s,a,L),q("Checking Kuriko can see group membership");;){let b=await P("Checking as kuriko-web, in the cloud",()=>vt(s.project,s.region,"kuriko-migrate",["scripts/admin.ts","check-groups",s.adminEmail,s.adminsGroup]));if(b.code===0){T(`Kuriko sees you in ${s.adminsGroup}`);break}for(let _ of b.logs.slice(-3))v(I(` ${_.trim()}`));b.code===3?R(`Kuriko can read groups, but doesn't see ${s.adminEmail} in ${s.adminsGroup}.`):R(`Kuriko can't read group membership yet. Check ${c.webServiceAccount} has Groups Reader (above); it can take a few minutes.`),await ce(" Press Enter to check again.")}v(`
|
|
352
|
-
${C("Kuriko is installed.")}
|
|
353
|
-
|
|
354
|
-
Sign in: ${C(c.web)}
|
|
355
|
-
MCP server: ${C(c.mcp)}
|
|
356
|
-
${hg(s.clients??Ce,c.mcp)}
|
|
357
|
-
|
|
358
|
-
To let someone build: add them to ${s.buildersGroup} and send them the MCP server address.
|
|
359
|
-
Data sources, who may use them, and which AI apps can connect go in ${s.project}/${B};
|
|
360
|
-
apply with kuriko policy apply.
|
|
361
|
-
Their first sign-in is their setup; they never need Google Cloud access.
|
|
362
|
-
|
|
363
|
-
Install config: ${U(a)} ${I("(no secrets in it; state is in gs://"+l+")")}`),await Ke([a],`Install ${s.project} (Kuriko ${f})`)}async function pg(n){q("Choosing which AI apps can connect");let e=nt(n,B);if(rr(e)){let{clients:s}=Ee(vu(e,"utf8"),dg(n));return T(`From ${B}: ${s.length?s.join(", "):"none"}`),s}v(I(" People connect Kuriko to the AI app they build in. Data access is the same whichever app they use;")),v(I(` this only decides which apps may act for them. Change it any time in ${B}.`));let t=await jl(`
|
|
364
|
-
Which AI apps can people connect with?`,ue.map(s=>({label:s.name,value:s.id,hint:s.notYet?"not yet":s.where,disabled:!!s.notYet})),s=>Ce.includes(s));return t.length?T(`AI apps: ${t.map(s=>ue.find(r=>r.id===s).name).join(", ")}`):R(`Nobody will be able to connect from an AI app until you allow one in ${B}.`),t}function hg(n,e){let t={"claude-code":`claude mcp add --transport http kuriko ${e} (then /mcp to sign in)`,claude:"Settings \u2192 Connectors \u2192 Add custom connector, with the MCP server address",codex:`codex mcp add kuriko --url ${e} (then codex mcp login kuriko)`,vscode:"Command Palette \u2192 MCP: Add Server \u2192 HTTP, with the MCP server address",cursor:"Settings \u2192 MCP \u2192 Add new MCP server, with the MCP server address",lovable:"Connectors \u2192 Add custom, with the MCP server address"},s=n.map(r=>` ${`${ue.find(o=>o.id===r)?.name??r}:`.padEnd(14)}${t[r]??"add the MCP server address as a remote MCP server"}`);return s.length?s.join(`
|
|
365
|
-
`):` ${I(`No AI apps can connect yet: allow one in ${B}.`)}`}async function mg(n,e,t,s){for(;;)try{await Hs(n,"database",[As]);return}catch(r){if(!(r instanceof Q&&kl(r.stderr)))throw r;let i=bl(e.dbInstanceName);s.note=`${e.dbInstanceName} was taken, creating ${i}`,e.dbInstanceName=i,ye(n,e),Nt(n,e,t)}}var gg=[["europe-west2","London"],["europe-west1","Belgium"],["europe-west3","Frankfurt"],["us-central1","Iowa"],["us-east1","South Carolina"],["us-west1","Oregon"],["asia-southeast1","Singapore"],["australia-southeast1","Sydney"]];async function yg(){return await le("Region (where Kuriko and its data live):",[...gg.map(([e,t])=>({label:e,value:e,hint:t})),{label:"Another region\u2026",value:""}])||sr("Region:",void 0,gl,"Like europe-west2 or us-central1: https://cloud.google.com/run/docs/locations")}async function wg(){let n=et().filter(t=>rr(nt(t,Ge)));if(!n.length)return null;await X({terraformOnly:!0});let e=await kn(n);return le("Continue an install, or start a new one?",[{label:"Start a new install",value:null},...e.map(t=>{let s=Gs[t.status],r=t.status==="gone";return{label:`Continue ${t.project}`,value:t.dir,disabled:r,hint:`${t.region} ${s.mark} ${s.text}`}})])}async function sr(n,e,t,s){for(;;){let r=await ce(n,e);if(t(r))return r;v(` ${s}`)}}async function bg(n){q("Choosing who runs Kuriko");let e=await St().catch(()=>[]),t=(e.find(r=>r.name===n.domain)??e[0])?.customerId,s=t?await P("Reading your Workspace's groups",()=>Ls(n.project,t)).catch(()=>null):null;s?T(`${s.length} group${s.length===1?"":"s"} in ${n.domain}`):R("Couldn't list your Workspace's groups (your account may not be allowed to). Type the group emails instead."),v(I(" Admins manage who can use which data and see the audit log. Builders make tools and deploy them into this project.")),v(I(" Everyone else who can sign in uses the tools shared with them. More groups can be given roles later, in policy.yaml.")),n.adminsGroup=await Su("admins",s,`kuriko-admins@${n.domain}`),n.buildersGroup=await Su("builders",s?.filter(r=>r.email!==n.adminsGroup)??null,`kuriko-builders@${n.domain}`),n.groupsChosen=!0,T(`Admins: ${C(n.adminsGroup)} Builders: ${C(n.buildersGroup)}`)}async function Su(n,e,t){let s=n==="admins"?`
|
|
366
|
-
Which group are Kuriko's admins?`:`
|
|
367
|
-
Which group can build tools?`,r=async()=>{for(;;){let l=(await ce(e?" Group email, or part of its name:":" Group email:",e?void 0:t)).toLowerCase();if(!e){if(vs(l))return l;R(`${l} isn't an email address.`);continue}let d=e.find(f=>f.email===l);if(d)return d.email;let u=Cl(e,l);if(u.length===1&&await H(` ${u[0].email}${u[0].name?` (${u[0].name})`:""}?`,!0))return u[0].email;if(u.length>1&&u.length<=9){let f=await le(" Which one?",[...u.map(h=>({label:h.email,value:h.email,hint:h.name})),{label:"None of these",value:""}]);if(f)return f}else if(u.length>9)R(`${u.length} groups match "${l}"; type more of it.`);else if(!u.length){if(vs(l)&&await H(` No group ${l} yet. Create it?`,!1))return l;R(`No group matches "${l}".`)}}};if(!e?.length)return r();let i=Nl(e,n),o={label:`Create ${t}`,value:t,hint:"(a new, empty group)"},a=[...i.length?[]:[o],...i.map(l=>({label:l.email,value:l.email,hint:l.name&&l.name.toLowerCase()!==l.email.split("@")[0]?l.name:void 0})),{label:"Another existing group\u2026",value:"?",hint:`(search all ${e.length})`},...i.length?[o]:[]],c=await le(s,a);return c==="?"?r():c}p();async function Eu(){if(!Se()){v(Bs);return}let n=et();if(!n.length){v(`No Kuriko installs yet. Start one with: ${C("kuriko install")}`);return}await X({terraformOnly:!0});let e=await kn(n),t={installed:Me("\u25CF installed"),partial:Xe("\u25D0 partly installed: run install to continue, or destroy"),empty:I("\u25CB not installed (or destroyed)"),gone:I("\u25CB project deleted"),unknown:Xe("? unknown")};for(let s of e)v(`
|
|
368
|
-
${C(s.project)} ${I(s.region)} ${t[s.status]}`),s.web&&v(` web ${s.web}`),s.mcp&&v(` mcp ${s.mcp}`),s.detail&&v(s.status==="gone"?I(` ${s.detail}`):` ${Xe("!")} ${s.detail}`),v(I(` dir ${U(s.dir)}`))}p();import{existsSync as kg}from"node:fs";import{join as $g}from"node:path";var Sg="module.kuriko.google_cloud_run_v2_job.migrate",vg={create:"+",update:"~",replace:"\xB1",delete:"-"};async function Ag(n,e){if(n==="unknown")return"forward";if(At(n)&&At(e)){let t=ou(n,e);return t===0?"same":t<0?"forward":"backward"}return!At(n)&&!At(e)?su(ne,n,e):"switch"}async function Nu(n){q("Checking this machine"),await me(he());for(let f of["gcloud","terraform",...F?[]:["git"]])if(!await Fe(f,f==="terraform"?"-version":"--version"))throw new Error(`${f} isn't installed.`);if(await X(),!F&&!n.dryRun)try{await j("docker",["info","--format","{{.ServerVersion}}"])}catch{throw new Error("Docker isn't running. Start Docker Desktop (it builds Kuriko's images), then run this again.")}let e=await Be(n.dir,"Which install should be upgraded?",["installed"],{partial:"finish it with kuriko install",empty:"nothing to upgrade",unknown:"can't read its state"}),t=Et(e),s=await De(t.project);if(!s||s.state!=="ACTIVE")throw new Error(`Project ${t.project} isn't available (deleted, or your account can't see it).`);if(!await tt(e,"module.kuriko.google_cloud_run_v2_service.web"))throw new Error(`${t.project} isn't fully installed yet. Run install to finish it: kuriko install --dir ${t.project}`);let r=Qe(t,s.number);T(`Install ${C(t.project)} ${I(`(${U(e)})`)}`),q("What changes");let i=fu(e)??"unknown",o=await Ws(n.allowDirty),a=await Ag(i,o);if(a==="backward")throw new Error(F?`${t.project} is on ${i}, newer than this CLI (${o}). Update the CLI first: npm i -g kuriko`:`${t.project} is on ${i}, which is newer than this Kuriko checkout (${o}). Pull the Kuriko repo first: git -C ${U(ne)} pull`);if(a==="unknown")throw new Error(`${t.project} is on ${i}, which this Kuriko checkout doesn't have. Pull the Kuriko repo first: git -C ${U(ne)} pull`);let c=pu(e);F?($n(await Zs(t,o)),ye(e,t)):$n(uu(e,t)),Js(e,t),Nt(e,t,o),await P("Preparing Terraform",()=>j("terraform",["init","-input=false"],{cwd:e}));let{plan:l}=await P("Working out the changes",()=>oo(e,"upgrade",null)),d=Es(l);if(i===o&&!d.length){c(),T(`Already on ${o}. Nothing to do.`);return}v(` Version ${i===o?o:`${I(i)} \u2192 ${C(o)}`}`),a==="switch"&&R(At(o)?`Moves from a development build to release ${o}.`:`Moves from release ${i} to a development build. Use this only for testing.`);let u=a==="forward"&&!F?await du(i,o):[];if(u.length){v(` ${u.length} commit${u.length===1?"":"s"}:`);for(let f of u.slice(0,12))v(I(` ${f}`));u.length>12&&v(I(` \u2026 and ${u.length-12} more`))}v(d.length?" Cloud":" Cloud no resource changes");for(let f of d)v(I(` ${vg[f.action]} ${f.address}${Ns.has(`module.kuriko.${f.address}`)?" (old project-wide secret access; policy.yaml grants each secret instead)":""}`));if(v(I(" No data or service is deleted. The database is migrated first; the web app and gateway switch over after.")),n.dryRun){c(),v(`
|
|
369
|
-
${I("Dry run: nothing was changed.")}`);return}if(!await H(`
|
|
370
|
-
Upgrade?`,!0)){c(),v("Nothing was changed.");return}if(F||(q(`Kuriko's images (version ${o})`),await Xs(t.region,r.registry,o)),await Vs(t),q("Migrating the database"),await P("Updating the migrate job",()=>zs(e,"upgrade-migrate",[Sg,...F?["module.kuriko.google_artifact_registry_repository.releases"]:[]])),await Qs(t,"kuriko-migrate",void 0,"Database schema"),d.some(f=>Ns.has(`module.kuriko.${f.address}`))){kg($g(e,B))||R(`No ${B}: the gateway won't be able to read data source secrets until one names them (kuriko policy apply).`);let f=await P("Giving the gateway the secrets policy.yaml names, one by one",()=>yu(t,e));T(f.length?`The gateway can read ${f.map(h=>h.split("/").pop()).join(", ")}`:"The gateway already reads the secrets policy.yaml names")}q("Switching to the new version"),await P("Updating the web app and gateway",()=>zs(e,"upgrade",null)),T(`${t.project} is on ${C(o)}`),v(`
|
|
371
|
-
${r.web}`),await Ke([e],`Upgrade ${t.project} to Kuriko ${o}${i!=="unknown"&&i!==o?` (from ${i})`:""}`)}p();import{existsSync as Eg,mkdirSync as Ng,writeFileSync as ho}from"node:fs";import{join as ir,resolve as Cg}from"node:path";var _g=`# Kuriko installs
|
|
419
|
+
`}function Ny(t,e){let n=new Map,s=Ey(t,U);if(!vy(s))return n;let r=Ne(Ay(s,"utf8"),e),i=(o,a)=>n.set(o,[...n.get(o)??[],a]);for(let o of r.roles)i(o.group,o.role);for(let o of r.grants)i(o.group,`${o.access} ${o.connector}`);return n}async function lf(t){M("Checking this machine"),await ke(Fe(process.cwd(),t.dir)),await te();let e=await Ye(t.dir,"Which install's groups?",["installed","partial"]),n=It(e);N(`Install ${_(n.project)} ${A(`(${D(e)})`)}`),M(`Google Groups in ${n.domain}`);let s=await P("Reading your Workspace's groups",()=>To(n));if(!s){x("Couldn't list your Workspace's groups: your account may not be allowed to. A Workspace admin can, or find them at admin.google.com \u2192 Directory \u2192 Groups.");return}let r=t.search?.toLowerCase(),i=r?s.filter(l=>`${l.email} ${l.name} ${l.description}`.toLowerCase().includes(r)):s,o=Ny(e,n.project),a=Math.max(10,...i.map(l=>l.email.length));for(let l of i){let h=o.get(l.email);k(` ${l.email.padEnd(a)} ${l.name&&l.name.toLowerCase()!==l.email.split("@")[0]?l.name:""}${h?` ${Ue(`in ${U}: ${h.join(", ")}`)}`:""}`)}N(r?`${i.length} of ${s.length} groups match "${t.search}"`:`${s.length} group${s.length===1?"":"s"}`);let c=[...o.keys()].filter(l=>l!=="*"&&l.includes("@")&&!s.some(h=>h.email===l));for(let l of c)x(`${U} names ${Mt(l)}, which isn't a group in ${n.domain} (a typo, or deleted?). Its rules apply to nobody.`);k(A(`
|
|
420
|
+
Copy an email into ${U} (roles or access), then: kuriko policy apply`))}p();import{existsSync as ff,readdirSync as jy}from"node:fs";import{homedir as Ry}from"node:os";import{basename as Ly,dirname as pf,join as Po,resolve as Oe}from"node:path";p();import{existsSync as Ty,mkdirSync as Oy,writeFileSync as Oo}from"node:fs";import{join as hr,resolve as Iy}from"node:path";var Py=`# Kuriko installs
|
|
372
421
|
|
|
373
422
|
One folder per Kuriko install, named after its cloud project, made and changed by the \`kuriko\` CLI.
|
|
374
423
|
Each holds the install's answers (\`kuriko.json\`) and the Terraform config generated from them. No
|
|
@@ -384,25 +433,63 @@ kuriko upgrade # move one to the Kuriko version you have checked out
|
|
|
384
433
|
\`\`\`
|
|
385
434
|
|
|
386
435
|
Clone it next to your Kuriko checkout, or run \`kuriko\` from inside it.
|
|
387
|
-
`;async function
|
|
388
|
-
`),
|
|
436
|
+
`;async function Io(t){Oy(t,{recursive:!0}),Oo(hr(t,Ot),JSON.stringify({kuriko:"installs",version:1},null,2)+`
|
|
437
|
+
`),Oo(hr(t,".gitignore"),`.terraform/
|
|
389
438
|
.kuriko-*.plan
|
|
390
|
-
`),
|
|
439
|
+
`),Ty(hr(t,"README.md"))||Oo(hr(t,"README.md"),Py);try{return await L("git",["-C",t,"rev-parse","--git-dir"]),{isRepo:!0}}catch{return{isRepo:!1}}}async function uf(t="."){let e=Iy(t);if(ne(e)===e){N(`${D(e)} is already an installs repo`);return}let{isRepo:s}=await Io(e);N(`${D(e)} is now an installs repo`),k(`
|
|
391
440
|
Share it through git: whoever can clone it can see your installs (changing one also needs
|
|
392
|
-
permissions on its cloud project). ${s?"Commit these files and push.":`Make it a git repo: ${
|
|
441
|
+
permissions on its cloud project). ${s?"Commit these files and push.":`Make it a git repo: ${_(`git -C ${D(e)} init`)}, then add a private remote.`}`)}async function df(t){try{return(await L("git",["-C",t,"rev-parse","--show-toplevel"])).trim()}catch{return null}}function xy(t,e,n=H){if(e&&Oe(e)!==Oe(n))return{path:Po(e,"kuriko"),inRepo:!0};let s=e?pf(Oe(n)):Oe(t);return{path:Po(s,"kuriko-installs"),inRepo:!1}}async function hf(t=process.cwd()){M("Where Kuriko keeps its config"),k(" Each install is a folder of plain files: its answers, the Terraform that runs it, and policy.yaml"),k(" (who can use which data). No secrets. Keep it in git so changes are reviewed and nothing is lost.");let e=xy(t,await df(t));for(k(""),k(` ${_("If your team has a Terraform repo, put it there")} (e.g. infra/kuriko): Kuriko's config is then`),k(" reviewed in pull requests, versioned and applied like the rest of your infrastructure."),k(" Otherwise, a folder of its own that you make a private git repo."),e.inRepo&&k(A(`
|
|
442
|
+
You're in ${D(pf(e.path))}, so it's suggested there.`));;){let n=(await V(`
|
|
443
|
+
Folder:`,D(e.path))).replace(/^~(?=\/|$)/,Ry()),s=Oe(t,n);if(Oe(s).startsWith(Oe(H)+"/")||Oe(s)===Oe(H)){x("That's inside the Kuriko checkout. Pick a folder outside it.");continue}if(ff(s)&&!ff(Po(s,Ot))&&jy(s).length){x(`${D(s)} isn't empty. Pick a new folder (Kuriko makes it), or an empty one.`);continue}let{isRepo:r}=await Io(s);return N(`Config goes in ${D(s)}${r?` ${A(`(in the git repo ${Ly(await df(s)??s)})`)}`:""}`),k(A(` Run kuriko from inside it later (or set KURIKO_INSTALLS=${s}), so it finds your installs.`)),s}}async function yf(t){k(`${_("Kuriko install")}
|
|
444
|
+
|
|
445
|
+
This puts Kuriko in your own cloud. Everything runs there, under your control: your people sign
|
|
446
|
+
in with the accounts they already have, and credentials stay in your own secret manager.
|
|
447
|
+
|
|
448
|
+
First a few questions; nothing is created until you've seen the plan and said yes. Then it takes
|
|
449
|
+
about 30 minutes, mostly waiting for the database. A few steps happen in your providers' admin
|
|
450
|
+
pages; this explains each one and checks it before moving on. If anything fails, run it again:
|
|
451
|
+
it picks up where it stopped.`);let e=ne()??await hf();await ke(e);let n=t.dir?Cn(t.dir):await Wy(),s=n&&In(Je(n,Ve))?JSON.parse(mf(Je(n,Ve),"utf8")):null;s||(k(""),await oe("Where should Kuriko run?",[{label:"Google Cloud",value:"gcp",hint:"in a project of yours"},{label:"AWS",value:"aws",hint:"coming soon",disabled:!0},{label:"Azure",value:"azure",hint:"coming soon",disabled:!0},{label:"Managed by Kuriko",value:"managed",hint:"coming soon: we run it for you",disabled:!0}]),await oe("Where do your people sign in?",[{label:"Google Workspace",value:"google-workspace"},{label:"Okta",value:"okta",hint:"coming soon",disabled:!0},{label:"Microsoft Entra ID",value:"entra",hint:"coming soon",disabled:!0},{label:"Another OIDC or SAML provider",value:"other",hint:"coming soon",disabled:!0}])),M("Checking this machine");for(let[I,R,q]of[["gcloud","Google Cloud's CLI: https://cloud.google.com/sdk/docs/install","--version"],["terraform","creates the cloud resources: https://developer.hashicorp.com/terraform/install","-version"]])if(!await He(I,q))throw new Error(`${I} isn't installed (${R}).`);if(!W){if(!await He("git","--version"))throw new Error("git isn't installed (it identifies the Kuriko version).");try{await L("docker",["info","--format","{{.ServerVersion}}"])}catch{throw new Error("Docker isn't running. Start Docker Desktop (it builds Kuriko's images), then run this again.")}}let r=await Et();if(!r)throw new Error("gcloud isn't signed in. Run: gcloud auth login");let i=r.split("@")[1]??"";if(/^(gmail|googlemail)\.com$/.test(i))throw new Error(`gcloud is signed in as ${r}. Sign in with your Google Workspace admin account instead: gcloud auth login`);await te(),N(`Signed in to Google Cloud as ${r}`);let o;if(s){M(`Continuing the install in ${s.project}`);let I=await Ge(s.project);if(!I||I.state!=="ACTIVE")throw new Error(`Project ${s.project} isn't available (deleted, or your account can't see it).`);o=I.number,N(`Project ${s.project} ${A(`(${n})`)}`)}else{M("Your Google Cloud project"),k(" Kuriko should have a project to itself, so its permissions don't mix with anything else.");let I=await oe("New project or existing?",[{label:"Create a new project",value:!0,hint:"recommended"},{label:"Use an existing, empty project",value:!1}]),R="",q=null;if(I){let se=await P("Finding your organization",()=>_t());if(!se.length)throw new Error(`${r} can't see any Google Cloud organization. Projects for Kuriko should live in your Workspace's organization.`);q=await co("Organization:",se.map(he=>({label:he.name,value:he,hint:he.id}))),R=await gr("Project ID (can't be changed later):",`kuriko-${Math.floor(1e3+Math.random()*9e3)}`,eo,"6\u201330 characters, starting with a letter: lowercase letters, digits and hyphens.")}else for(;R=await V("Project ID:"),!await P("Looking it up",()=>Ge(R));)k(` Can't find ${R}, or ${r} can't see it.`);let F=null;if(I||!await P("Checking billing",()=>iu(R))){let se=await P("Finding billing accounts",()=>su());if(!se.length)throw new Error("No open billing account. Create one at https://console.cloud.google.com/billing, then run this again.");F=await co("Billing account:",se.map(yr=>({label:yr.name,value:yr,hint:yr.id})));let he=await P("Checking the billing account has room",()=>au(F.id));if(he&&he.length>=5&&(x(`${F.name} already has ${he.length} projects linked (${he.join(", ")}). New billing accounts are often limited to 5.`),k(A(" If linking fails, unlink a project you don't use (gcloud billing projects unlink <project>), or ask Google")),k(A(" for more: https://support.google.com/code/contact/billing_quota_increase")),!await z(" Try anyway?",!1))){k("Nothing was created.");return}}let ue=await Fy();M("The plan");let Se=(se,he)=>k(` ${A(se.padEnd(10))}${he}`);if(Se("Runs in",`Google Cloud \xB7 ${I?`new project ${_(R)}${q?` in ${q.name}`:""}`:`existing project ${_(R)}`} \xB7 ${ue}`),F&&Se("Billing",`${F.name} ${A(F.id)}`),Se("Sign-in",`Google Workspace \xB7 people at ${_(i)}`),Se("Admins",`kuriko-admins@${i}`),Se("Builders",`kuriko-builders@${i}`),Se("Cost","about $10\u201315 a month, almost all of it the database; the rest scales to zero when idle"),k(""),!await z("Start?",!0)){k("Nothing was created.");return}if(I){for(;;)try{await P(`Creating project ${R}`,()=>ru(R,q.id));break}catch(se){if(!(se instanceof ee&&/already (in use|exists)/i.test(se.stderr)))throw se;k(` ${R} is taken (project IDs are unique across all of Google Cloud).`),R=await gr("Another project ID:",void 0,eo,"6\u201330 characters, starting with a letter: lowercase letters, digits and hyphens.")}N(`Created project ${R}`)}if(F){try{await P("Linking billing",()=>ou(R,F.id))}catch(se){throw cu(se)?new Error(`${F.name} is at Google's limit of linked projects, so billing couldn't be linked to ${R}.
|
|
452
|
+
Free a slot (gcloud billing projects unlink <a project you don't use>) or ask Google for more:
|
|
453
|
+
https://support.google.com/code/contact/billing_quota_increase
|
|
454
|
+
Then run kuriko install again and choose "Use an existing, empty project": ${R}${I?" (already created, so no new project is made)":""}.`):se}N("Billing linked")}o=(await Ge(R)).number,s={host:"gcp",sso:"google-workspace",project:R,region:ue,domain:i,adminEmail:r,adminsGroup:`kuriko-admins@${i}`,buildersGroup:`kuriko-builders@${i}`,dbInstanceName:""},n=Je(e,R),qy(n,{recursive:!0}),pe(n,s)}let a=n,c=st(s,o);M("Turning on the Google Cloud services Kuriko uses"),await P("Enabling APIs",()=>Ys(s.project,Ml)),await sr(s),N("Cloud Run, Cloud SQL, Secret Manager, KMS, Artifact Registry, Cloud Build, Pub/Sub, IAM, Cloud Identity"),M("Somewhere to keep Kuriko's Terraform state");let l=`${s.project}-tfstate`,h=await P("Creating the state bucket",()=>lu(l,s.project,s.region));N(`gs://${l} ${A(`(${h}; versioned, private)`)}`);let u=await uu(s.project);s.dbInstanceName||(s.dbInstanceName=Ul(u.map(I=>I.name)),pe(a,s));let f=await ir(t.allowDirty);W&&(M(`Kuriko ${f}`),Tn(await ur(s,f)),pe(a,s)),rr(a,s),await P("Preparing Terraform",()=>L("terraform",["init","-input=false"],{cwd:a}));let d={},m=()=>My(Je(a,"imports.tf"),Jl(s,d));await at(a,"module.kuriko.google_kms_key_ring.kuriko")||(Object.assign(d,await fu(s.project,s.region,wn.ring,wn.key)),d.ring&&N("Found a KMS key from an earlier install; this one will reuse it"));let g=(await L("terraform",["state","list"],{cwd:a}).catch(()=>"")).split(`
|
|
455
|
+
`),y=Object.keys(kn).filter(I=>!g.includes(`module.kuriko.google_service_account.${I}`));if(y.length){let I=await P("Looking for service accounts from an earlier install",()=>du(s.project,y.map(R=>kn[R])));d.accounts=y.filter(R=>I.includes(kn[R])),d.accounts.length&&N(`Found ${I.join(", ")} from an earlier install; this one takes ${I.length===1?"it":"them"} over`)}m(),N(`Install config in ${a}`),M("Kuriko's service accounts and image registry"),Pt(a,s,f),await P("Creating service accounts and the image registry",()=>ar(a,"bootstrap",Kl)),N("kuriko-web, kuriko-gateway and kuriko-tools service accounts; image registry"),M("Kuriko's database");let S={started:Date.now(),state:"creating",note:""},C=Promise.resolve();if(await at(a,qs))S.state="ready",N(`Database ${s.dbInstanceName} ${A("(already created)")}`);else{let I=u.find(R=>R.name===s.dbInstanceName&&R.kuriko);if(I)d.sqlInstance=I.name,m(),N(`Found database ${I.name} from an earlier run; picking it up`);else if(k(" Cloud SQL takes 10\u201315 minutes to create, so it starts now and carries on while you do the next steps."),k(" It's most of Kuriko's cost: about $10\u201315 a month. The rest scales to zero when nobody's using it."),!await z(" Start creating it?",!0))throw new Error("Stopped before creating the database. Run install again to continue.");C=Uy(a,s,f,S).then(()=>S.state="ready",R=>(S.state="failed",R)),ao(()=>S.state==="creating"?`database: ${S.note||"creating"} (${Ds(S.started)})`:S.state==="ready"?"database: ready":"database: failed"),N("Started; it'll be ready in about 10\u201315 minutes")}for(W||(M(`Kuriko's images (version ${f})`),k(A(" Built from this checkout (development). Released versions pull Kuriko's published images instead.")),await lr(s.region,c.registry,f)),Ee("Let people sign in with Google (an OAuth app, in Google Cloud)",["Kuriko signs people in with their Google accounts. Google needs an OAuth app in this project for that.","",`1. Open ${_(c.newClient)}`,` If Google first asks you to set up the app (${_("Get started")}): App name ${_("Kuriko")}, support email: you,`,` Audience: ${_("Internal")} (only people in ${s.domain} can sign in), contact email: you. Agree, ${_("Create")},`," then open the link again. If it goes straight to a form for a new client, skip this.","",`2. Application type: ${_("Web application")}. Name: ${_("Kuriko")}.`,` Under Authorized redirect URIs, ${_("Add URI")} and paste exactly:`,` ${_(c.redirect)}`,` Then ${_("Create")}. A dialog shows the Client ID and Client secret: keep it open.`]);;){let I=await gr(`
|
|
456
|
+
Client ID:`,s.idpClientId,Bl,"It looks like 1234567890-abc123.apps.googleusercontent.com."),R=I!==s.idpClientId;if(s.idpClientId=I,pe(a,s),await vn(s.project,bn)&&!R&&!await z(` A client secret is already in Secret Manager (${bn}). Replace it?`)){N("Keeping the stored client secret");break}k(A(` The secret goes straight into Secret Manager as ${bn}. It isn't shown or saved anywhere else.`));let F=await Gs(" Client secret (hidden as you type or paste):");if(!F)continue;let ue=await P("Checking them with Google",()=>hu(I,F,c.redirect));if(ue===!1){x("Google doesn't accept that client ID and secret together. Copy both again from the same client.");continue}await P("Storing the secret",()=>Ct(s.project,bn,F)),N(`Client secret stored in Secret Manager${ue?", and Google accepts it":""}`);break}s.groupsChosen||((await Promise.all([s.adminsGroup,s.buildersGroup].map(R=>Js(s.project,R,s.adminEmail).catch(()=>null)))).every(R=>R?.exists)||await Yy(s),s.groupsChosen=!0,pe(a,s)),s.clients||(s.clients=await Dy(a),pe(a,s)),!s.warehouse&&!In(Je(a,U))&&(s.warehouse=await zu(s),pe(a,s)),Ee("Decide who runs Kuriko (Google Groups)",["Kuriko gives roles by Google Group, so access is managed where you already manage people:",` ${_(s.adminsGroup)} Admin: manages who can use which data, sees the audit log.`,` ${_(s.buildersGroup)} Builder: builds tools.`,` Everyone else in ${s.domain} can sign in and use tools shared with them. Groups inside these groups count too.`]);let O=()=>P("Looking for the groups",()=>Promise.all([Js(s.project,s.adminsGroup,s.adminEmail),Js(s.project,s.buildersGroup,s.adminEmail)])),[$,T]=await O(),j=[!$.exists&&s.adminsGroup,!T.exists&&s.buildersGroup].filter(I=>!!I),b=!1;if(j.length&&await z(`
|
|
457
|
+
Create ${j.join(" and ")} now${$.exists?"":`, with you in ${s.adminsGroup}`}?`,!0)){let I=await _t(),R=(I.find(q=>q.name===s.domain)??I[0])?.customerId;if(!R)throw new Error("Couldn't find your Workspace's customer ID to create the groups. Create them in the Admin console instead.");for(let[q,F,ue,Se]of[[s.adminsGroup,"Kuriko admins","Kuriko Admin role: manages who can use which data, sees the audit log.",!0],[s.buildersGroup,"Kuriko builders","Kuriko Builder role: builds tools on Kuriko.",!1]])j.includes(q)&&(await P(`Creating ${q}`,()=>mu(s.project,{customerId:R,email:q,name:F,description:ue,owner:Se})),N(`Created ${q}${Se?" (you're its owner)":""}`));if(b=!0,!T.exists){let q=(await V(` Who should build? Their ${s.domain} emails, comma-separated (Enter to add people later):`)).split(/[\s,]+/).filter(Boolean);for(let F of q){if(!xs(F)){x(`Skipped ${F}: not an email address.`);continue}try{await P(`Adding ${F}`,()=>lo(s.project,s.buildersGroup,F)),N(`Added ${F} to ${s.buildersGroup}`)}catch(ue){x(`Couldn't add ${F}: ${ue instanceof Error?ue.message:String(ue)}`)}}}}else j.length&&Ee("Create the groups in the Google Admin console",[`${_("https://admin.google.com/ac/groups")} \u2192 ${_("Create group")}, once for each group email above.`,`Under access settings choose ${_("Restricted")} (only members see the member list) and no external members.`,`Add yourself to ${s.adminsGroup}, and the people who'll build to ${s.buildersGroup}.`]);for(let I=0;;I++){if(I&&([$,T]=await O()),$.exists&&T.exists&&$.isMember){N(`${s.adminsGroup} (you're in it) and ${s.buildersGroup} are ready`);break}if(b&&I<6){await new Promise(q=>setTimeout(q,3e3));continue}if($.exists&&!$.isMember&&await z(` You're not in ${s.adminsGroup}, so you wouldn't be a Kuriko admin. Add you?`,!0)){await P("Adding you",()=>lo(s.project,s.adminsGroup,s.adminEmail)),b=!0,I=0;continue}let R=[!$.exists&&s.adminsGroup,!T.exists&&s.buildersGroup].filter(Boolean);R.length?x(`Not found yet: ${R.join(", ")} (or ${s.adminEmail} can't see ${R.length>1?"them":"it"}).`):x(`${s.adminEmail} isn't in ${s.adminsGroup}. Add yourself, or you won't be an admin.`),await V(" Press Enter to check again.")}Ee("Let Kuriko see group membership (Groups Reader role, in the Google Admin console)",["Google doesn't tell apps which groups someone is in when they sign in, so Kuriko asks Google","directly. It needs the Groups Reader admin role for that: it can read group membership and nothing else.","",`1. Open ${_("https://admin.google.com/ac/roles")} and click ${_("Groups Reader")}.`,`2. Open ${_("Admins")} (or "Assign role"), then ${_("Assign service accounts")}.`,`3. Paste ${_(c.webServiceAccount)}, click ${_("Add")}, then ${_("Assign role")}.`,"","It can take a few minutes to take effect. Kuriko checks it at the end."]),await V(" Press Enter when you've assigned it."),M("Creating Kuriko");let v=await P("Waiting for the database",()=>C);if(ao(null),S.state==="failed")throw v;N(`Database ${s.dbInstanceName} ${A(`(${Ds(S.started)} in all)`)}`),Pt(a,s,f),await P("Creating Kuriko's secrets, key and services",()=>ar(a,"install",null));for(let I of Object.keys(d))delete d[I];m(),N("Kuriko's secrets, key and services"),M("Setting up Kuriko's database"),await cr(s,"kuriko-migrate",void 0,"Database schema");let K="";if(!In(Je(a,U))){let I=await P("Reading your Workspace's groups for policy.yaml",()=>To(s));I&&(K=cf(I,s))}for(await of(s,a,K),M("Checking Kuriko can see group membership");;){let I=await P("Checking as kuriko-web, in the cloud",()=>Nt(s.project,s.region,"kuriko-migrate",["scripts/admin.ts","check-groups",s.adminEmail,s.adminsGroup]));if(I.code===0){N(`Kuriko sees you in ${s.adminsGroup}`);break}for(let R of I.logs.slice(-3))k(A(` ${R.trim()}`));I.code===3?x(`Kuriko can read groups, but doesn't see ${s.adminEmail} in ${s.adminsGroup}.`):x(`Kuriko can't read group membership yet. Check ${c.webServiceAccount} has Groups Reader (above); it can take a few minutes.`),await V(" Press Enter to check again.")}k(`
|
|
458
|
+
${_("Kuriko is installed.")}
|
|
459
|
+
|
|
460
|
+
Sign in: ${_(c.web)}
|
|
461
|
+
MCP server: ${_(c.mcp)}
|
|
462
|
+
${By(s.clients??Ie,c.mcp)}
|
|
463
|
+
|
|
464
|
+
To let someone build: add them to ${s.buildersGroup} and send them the MCP server address.
|
|
465
|
+
${s.warehouse&&s.warehouse.kind!=="none"?`Your ${s.warehouse.kind==="bigquery"?"BigQuery datasets are":"Snowflake database is"} connected; nobody can read ${s.warehouse.kind==="bigquery"&&s.warehouse.datasets.length>1?"them":"it"} until you grant a group
|
|
466
|
+
access in ${s.project}/${U} (there's an example in it).
|
|
467
|
+
`:""}Data sources, who may use them, and which AI apps can connect go in ${s.project}/${U};
|
|
468
|
+
apply with kuriko policy apply.
|
|
469
|
+
Their first sign-in is their setup; they never need Google Cloud access.
|
|
470
|
+
|
|
471
|
+
Install config: ${D(a)} ${A("(no secrets in it; state is in gs://"+l+")")}`),await We([a],`Install ${s.project} (Kuriko ${f})`)}async function Dy(t){M("Choosing which AI apps can connect");let e=Je(t,U);if(In(e)){let{clients:s}=Ne(mf(e,"utf8"),Ky(t));return N(`From ${U}: ${s.length?s.join(", "):"none"}`),s}k(A(" People connect Kuriko to the AI app they build in. Data access is the same whichever app they use;")),k(A(` this only decides which apps may act for them. Change it any time in ${U}.`));let n=await Fs(`
|
|
472
|
+
Which AI apps can people connect with?`,me.map(s=>({label:s.name,value:s.id,hint:s.notYet?"not yet":s.where,disabled:!!s.notYet})),s=>Ie.includes(s));return n.length?N(`AI apps: ${n.map(s=>me.find(r=>r.id===s).name).join(", ")}`):x(`Nobody will be able to connect from an AI app until you allow one in ${U}.`),n}function By(t,e){let n={"claude-code":`claude mcp add --transport http kuriko ${e} (then /mcp to sign in)`,claude:"Settings \u2192 Connectors \u2192 Add custom connector, with the MCP server address",codex:`codex mcp add kuriko --url ${e} (then codex mcp login kuriko)`,vscode:"Command Palette \u2192 MCP: Add Server \u2192 HTTP, with the MCP server address",cursor:"Settings \u2192 MCP \u2192 Add new MCP server, with the MCP server address",lovable:"Connectors \u2192 Add custom, with the MCP server address"},s=t.map(r=>` ${`${me.find(o=>o.id===r)?.name??r}:`.padEnd(14)}${n[r]??"add the MCP server address as a remote MCP server"}`);return s.length?s.join(`
|
|
473
|
+
`):` ${A(`No AI apps can connect yet: allow one in ${U}.`)}`}async function Uy(t,e,n,s){for(;;)try{await ar(t,"database",[qs]);return}catch(r){if(!(r instanceof ee&&Fl(r.stderr)))throw r;let i=Gl(e.dbInstanceName);s.note=`${e.dbInstanceName} was taken, creating ${i}`,e.dbInstanceName=i,pe(t,e),Pt(t,e,n)}}var Gy=[["europe-west2","London"],["europe-west1","Belgium"],["europe-west3","Frankfurt"],["us-central1","Iowa"],["us-east1","South Carolina"],["us-west1","Oregon"],["asia-southeast1","Singapore"],["australia-southeast1","Sydney"]];async function Fy(){return await oe("Region (where Kuriko and its data live):",[...Gy.map(([e,n])=>({label:e,value:e,hint:n})),{label:"Another region\u2026",value:""}])||gr("Region:",void 0,Dl,"Like europe-west2 or us-central1: https://cloud.google.com/run/docs/locations")}async function Wy(){let t=it().filter(n=>In(Je(n,Ve)));if(!t.length)return null;await te({terraformOnly:!0});let e=await Nn(t);return oe("Continue an install, or start a new one?",[{label:"Start a new install",value:null},...e.map(n=>{let s=Xs[n.status],r=n.status==="gone";return{label:`Continue ${n.project}`,value:n.dir,disabled:r,hint:`${n.region} ${s.mark} ${s.text}`}})])}async function gr(t,e,n,s){for(;;){let r=await V(t,e);if(n(r))return r;k(` ${s}`)}}async function Yy(t){M("Choosing who runs Kuriko");let e=await _t().catch(()=>[]),n=(e.find(r=>r.name===t.domain)??e[0])?.customerId,s=n?await P("Reading your Workspace's groups",()=>Vs(t.project,n)).catch(()=>null):null;s?N(`${s.length} group${s.length===1?"":"s"} in ${t.domain}`):x("Couldn't list your Workspace's groups (your account may not be allowed to). Type the group emails instead."),k(A(" Admins manage who can use which data and see the audit log. Builders make tools and deploy them into this project.")),k(A(" Everyone else who can sign in uses the tools shared with them. More groups can be given roles later, in policy.yaml.")),t.adminsGroup=await gf("admins",s,`kuriko-admins@${t.domain}`),t.buildersGroup=await gf("builders",s?.filter(r=>r.email!==t.adminsGroup)??null,`kuriko-builders@${t.domain}`),t.groupsChosen=!0,N(`Admins: ${_(t.adminsGroup)} Builders: ${_(t.buildersGroup)}`)}async function gf(t,e,n){let s=t==="admins"?`
|
|
474
|
+
Which group are Kuriko's admins?`:`
|
|
475
|
+
Which group can build tools?`,r=async()=>{for(;;){let l=(await V(e?" Group email, or part of its name:":" Group email:",e?void 0:n)).toLowerCase();if(!e){if(xs(l))return l;x(`${l} isn't an email address.`);continue}let h=e.find(f=>f.email===l);if(h)return h.email;let u=Ql(e,l);if(u.length===1&&await z(` ${u[0].email}${u[0].name?` (${u[0].name})`:""}?`,!0))return u[0].email;if(u.length>1&&u.length<=9){let f=await oe(" Which one?",[...u.map(d=>({label:d.email,value:d.email,hint:d.name})),{label:"None of these",value:""}]);if(f)return f}else if(u.length>9)x(`${u.length} groups match "${l}"; type more of it.`);else if(!u.length){if(xs(l)&&await z(` No group ${l} yet. Create it?`,!1))return l;x(`No group matches "${l}".`)}}};if(!e?.length)return r();let i=Hl(e,t),o={label:`Create ${n}`,value:n,hint:"(a new, empty group)"},a=[...i.length?[]:[o],...i.map(l=>({label:l.email,value:l.email,hint:l.name&&l.name.toLowerCase()!==l.email.split("@")[0]?l.name:void 0})),{label:"Another existing group\u2026",value:"?",hint:`(search all ${e.length})`},...i.length?[o]:[]],c=await oe(s,a);return c==="?"?r():c}p();async function wf(){if(!ne()){k(Zs);return}let t=it();if(!t.length){k(`No Kuriko installs yet. Start one with: ${_("kuriko install")}`);return}await te({terraformOnly:!0});let e=await Nn(t),n={installed:Ue("\u25CF installed"),partial:rt("\u25D0 partly installed: run install to continue, or destroy"),empty:A("\u25CB not installed (or destroyed)"),gone:A("\u25CB project deleted"),unknown:rt("? unknown")};for(let s of e)k(`
|
|
476
|
+
${_(s.project)} ${A(s.region)} ${n[s.status]}`),s.web&&k(` web ${s.web}`),s.mcp&&k(` mcp ${s.mcp}`),s.detail&&k(s.status==="gone"?A(` ${s.detail}`):` ${rt("!")} ${s.detail}`),k(A(` dir ${D(s.dir)}`))}p();import{existsSync as Vy}from"node:fs";import{join as Jy}from"node:path";var zy="module.kuriko.google_cloud_run_v2_job.migrate",Hy={create:"+",update:"~",replace:"\xB1",delete:"-"};async function Qy(t,e){if(t==="unknown")return"forward";if(ot(t)&&ot(e)){let n=qu(t,e);return n===0?"same":n<0?"forward":"backward"}return!ot(t)&&!ot(e)?Ru(H,t,e):"switch"}async function bf(t){M("Checking this machine"),await ke(Fe(process.cwd(),t.dir));for(let m of["gcloud","terraform",...W?[]:["git"]])if(!await He(m,m==="terraform"?"-version":"--version"))throw new Error(`${m} isn't installed.`);if(await te(),!W&&!t.dryRun)try{await L("docker",["info","--format","{{.ServerVersion}}"])}catch{throw new Error("Docker isn't running. Start Docker Desktop (it builds Kuriko's images), then run this again.")}let e=await Ye(t.dir,"Which install should be upgraded?",["installed"],{partial:"finish it with kuriko install",empty:"nothing to upgrade",unknown:"can't read its state"}),n=It(e),s=await Ge(n.project);if(!s||s.state!=="ACTIVE")throw new Error(`Project ${n.project} isn't available (deleted, or your account can't see it).`);if(!await at(e,"module.kuriko.google_cloud_run_v2_service.web"))throw new Error(`${n.project} isn't fully installed yet. Finish it with kuriko install`);let r=st(n,s.number);N(`Install ${_(n.project)} ${A(`(${D(e)})`)}`),M("What changes");let i=Uu(e)??"unknown",o=await ir(t.allowDirty),a=await Qy(i,o);if(a==="backward")throw new Error(W?`${n.project} is on ${i}, newer than this CLI (${o}). Update the CLI first: npm i -g kuriko`:`${n.project} is on ${i}, which is newer than this Kuriko checkout (${o}). Pull the Kuriko repo first: git -C ${D(H)} pull`);if(a==="unknown")throw new Error(`${n.project} is on ${i}, which this Kuriko checkout doesn't have. Pull the Kuriko repo first: git -C ${D(H)} pull`);let c=Fu(e);W?(Tn(await ur(n,o)),pe(e,n)):Tn(Bu(e,n)),rr(e,n),Pt(e,n,o),await P("Preparing Terraform",()=>L("terraform",["init","-input=false"],{cwd:e}));let{plan:l}=await P("Working out the changes",()=>ko(e,"upgrade",null)),h=Ms(l);if(i===o&&!h.length){c(),N(`Already on ${o}. Nothing to do.`);return}k(` Version ${i===o?o:`${A(i)} \u2192 ${_(o)}`}`),a==="switch"&&x(ot(o)?`Moves from a development build to release ${o}.`:`Moves from release ${i} to a development build. Use this only for testing.`);let u=!W&&!ot(i)?await mo(H,i,o)??i:i,f=a==="forward"&&!W?await Gu(u,o):[];if(f.length){k(` ${f.length} commit${f.length===1?"":"s"}:`);for(let m of f.slice(0,12))k(A(` ${m}`));f.length>12&&k(A(` \u2026 and ${f.length-12} more`))}k(h.length?" Cloud":" Cloud no resource changes");for(let m of h)k(A(` ${Hy[m.action]} ${m.address}${Ks.has(`module.kuriko.${m.address}`)?" (old project-wide secret access; policy.yaml grants each secret instead)":""}`));if(k(A(" No data or service is deleted. The database is migrated first; the web app and gateway switch over after.")),t.dryRun){c(),k(`
|
|
477
|
+
${A("Dry run: nothing was changed.")}`);return}if(!await z(`
|
|
478
|
+
Upgrade?`,!0).catch(m=>{throw c(),m})){c(),k("Nothing was changed.");return}if(W||(M(`Kuriko's images (version ${o})`),await lr(n.region,r.registry,o)),await sr(n),M("Migrating the database"),await P("Updating the migrate job",()=>or(e,"upgrade-migrate",[zy,...W?["module.kuriko.google_artifact_registry_repository.releases"]:[]])),await cr(n,"kuriko-migrate",void 0,"Database schema"),h.some(m=>Ks.has(`module.kuriko.${m.address}`))){Vy(Jy(e,U))||x(`No ${U}: the gateway won't be able to read data source secrets until one names them (kuriko policy apply).`);let m=await P("Giving the gateway the secrets policy.yaml names, one by one",()=>rf(n,e));N(m.length?`The gateway can read ${m.map(g=>g.split("/").pop()).join(", ")}`:"The gateway already reads the secrets policy.yaml names")}M("Switching to the new version"),await P("Updating the web app and gateway",()=>or(e,"upgrade",null)),N(`${n.project} is on ${_(o)}`),k(`
|
|
479
|
+
${r.web}`),await We([e],`Upgrade ${n.project} to Kuriko ${o}${i!=="unknown"&&i!==o?` (from ${i})`:""}`)}var Pn={install:{usage:"install [--dir <install>] [--allow-dirty]",summary:"Put Kuriko in a Google Cloud project, for a company on Google Workspace",details:["Walks through every step, including the three done in Google's admin pages (an OAuth app,","two Google Groups, and the Groups Reader role), explaining each and checking it before moving on.","Takes about 30 minutes, mostly waiting for the database. Safe to re-run: it continues where it stopped.",""," --dir <install> Continue a specific install, by project ID (default: asks, if there are any)"," --allow-dirty Install from a checkout with uncommitted changes (images get a -dirty tag)"],run:t=>yf({dir:t.dir,allowDirty:t["allow-dirty"]})},list:{usage:"list",summary:"Show your installs, how far each got, and their URLs",details:["Reads each install's Terraform state, so it shows what's actually in the cloud."],run:()=>wf()},upgrade:{usage:"upgrade [--dir <install>] [--dry-run] [--allow-dirty]",summary:"Move an install to the version in this checkout",details:["Shows the version change, the commits in it and what changes in the cloud, then asks.","Builds and pushes the new images, migrates the database with the new version, and only then","switches the web app and gateway over. Never deletes anything; a plan that would is refused.",""," --dir <install> Which install, by project ID (default: asks, if there's more than one)"," --dry-run Show what would change, change nothing (no images built)"," --allow-dirty Upgrade to a checkout with uncommitted changes (images get a -dirty tag)"],run:t=>bf({dir:t.dir,allowDirty:t["allow-dirty"],dryRun:t["dry-run"]})},policy:{usage:"policy plan|apply [--dir <install>] [--yes]",summary:"Change who can do what: roles, data sources and access, from the install's policy.yaml",details:["Each install's access lives in policy.yaml next to its Terraform: which Google groups are admins and","builders, which data sources exist (naming their secrets, never holding them), and who may use what.","plan shows what applying the file would change; apply shows the same, asks, and makes the install match.","Runs inside the cloud; every change is in the audit log. Commit the file so the repo is the record.",""," --dir <install> Which install, by project ID (default: asks, if there's more than one)"," --yes Apply without asking (for CI)"],run:(t,e)=>{if(e[0]!=="plan"&&e[0]!=="apply")throw new Rt('Say "kuriko policy plan" or "kuriko policy apply".');return Xu(e[0],{dir:t.dir,yes:t.yes})}},groups:{usage:"groups [search] [--dir <install>]",summary:"List your Google Groups, to name in policy.yaml, and which ones it already uses",details:["Shows every group in the install's Google Workspace with its name, marks the ones policy.yaml gives a","role or access to, and warns about groups policy.yaml names that don't exist. Membership is never","copied into Kuriko: people's groups are read from Workspace each time they sign in.",""," search Only groups whose email, name or description contains this"," --dir <install> Which install, by project ID (default: asks, if there's more than one)"],run:(t,e)=>lf({dir:t.dir,search:e.join(" ")||void 0})},destroy:{usage:"destroy [--dir <install>] [--dry-run] [--confirm <project-id>]",summary:"Remove an install from its cloud project",details:["Shows what will be deleted (the database and everything in it, services, accounts) and what stays","(the KMS key, your own secrets, the state bucket, the project), then asks for the project ID.",""," --dir <install> Which install, by project ID (default: asks, if there's more than one)"," --dry-run Show what would happen, change nothing"," --confirm <project-id> Give the project ID up front instead of typing it"],run:t=>af({dir:t.dir,dryRun:t["dry-run"],confirm:t.confirm})},init:{usage:"init [folder]",summary:"Make a folder the installs repo you share with whoever runs Kuriko",details:["Installs (answers and Terraform config, no secrets) live in a git repo. Whoever can clone it sees","the installs; changing one also needs permissions on its cloud project. Commands find the repo","from inside it, from $KURIKO_INSTALLS, or as a kuriko-installs checkout next to the Kuriko one."],run:(t,e)=>uf(e[0])},help:{usage:"help [command]",summary:"Show this, or the details of one command",details:[],run:async(t,e)=>mr(e[0])}};function mr(t){if(t){let n=Pn[t];if(!n)throw new Rt(`No command "${t}".`);console.log(`${_(`kuriko ${n.usage}`)}
|
|
393
480
|
|
|
394
|
-
${
|
|
481
|
+
${n.summary}.${n.details.length?`
|
|
395
482
|
|
|
396
|
-
${
|
|
397
|
-
`)}`:""}`);return}let e=Math.max(...Object.keys(
|
|
483
|
+
${n.details.join(`
|
|
484
|
+
`)}`:""}`);return}let e=Math.max(...Object.keys(Pn).map(n=>n.length));console.log(`${_("kuriko")} ${A("\xB7 runs Kuriko in your own cloud")}
|
|
398
485
|
|
|
399
|
-
Usage: kuriko <command> [options] ${
|
|
486
|
+
Usage: kuriko <command> [options] ${A(W?`version ${W.version}`:"development build, from a Kuriko checkout")}
|
|
400
487
|
|
|
401
488
|
Commands:
|
|
402
|
-
${Object.entries(
|
|
489
|
+
${Object.entries(Pn).map(([n,s])=>` ${n.padEnd(e)} ${s.summary}`).join(`
|
|
403
490
|
`)}
|
|
404
491
|
|
|
405
|
-
Run ${
|
|
406
|
-
${
|
|
407
|
-
`),
|
|
408
|
-
${
|
|
492
|
+
Run ${_("kuriko help <command>")} for a command's options.
|
|
493
|
+
${Xy()}`)}function Xy(){let t=ne();return t?`Installs repo: ${D(t)}`:"No installs repo yet: clone yours next to the Kuriko checkout, or run kuriko init <folder>."}var Rt=class extends Error{};try{let{positionals:t,values:e}=Zy({allowPositionals:!0,options:{dir:{type:"string"},"allow-dirty":{type:"boolean"},confirm:{type:"string"},"dry-run":{type:"boolean"},yes:{type:"boolean"},help:{type:"boolean",short:"h"},version:{type:"boolean",short:"v"}}}),[n,...s]=t;if(e.version)console.log(W?W.version:"development build");else if(!n)mr();else if(Pn[n])e.help?mr(n):await Pn[n].run(e,s);else throw new Rt(`No command "${n}".`)}catch(t){let e=t instanceof Error?t.message:String(t),n=/Unknown option '([^']+)'/.exec(e)?.[1],s=n?`No option ${n}.`:e,r=t.code;t instanceof Rt||typeof r=="string"&&r.startsWith("ERR_PARSE_ARGS")?(console.error(`${be("\u2717")} ${s}
|
|
494
|
+
`),mr(),process.exitCode=2):(console.error(`
|
|
495
|
+
${be("\u2717")} ${s}`),process.exitCode=1)}
|