kuriko 0.3.1 → 0.4.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 +340 -238
- package/module/main.tf +13 -1
- package/module/outputs.tf +10 -0
- package/package.json +1 -1
package/kuriko.mjs
CHANGED
|
@@ -1,160 +1,160 @@
|
|
|
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 yf=Object.create;var Po=Object.defineProperty;var wf=Object.getOwnPropertyDescriptor;var bf=Object.getOwnPropertyNames;var kf=Object.getPrototypeOf,$f=Object.prototype.hasOwnProperty;var Os=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,s)=>(typeof require<"u"?require:e)[s]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var Sf=(t,e,s)=>()=>{if(s)throw s[0];try{return t&&(e=t(t=0)),e}catch(n){throw s=[n],n}};var _=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(s){throw e=0,s}};var vf=(t,e,s,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of bf(e))!$f.call(t,r)&&r!==s&&Po(t,r,{get:()=>e[r],enumerable:!(n=wf(e,r))||n.enumerable});return t};var Af=(t,e,s)=>(s=t!=null?yf(kf(t)):{},vf(e||!t||!t.__esModule?Po(s,"default",{value:t,enumerable:!0}):s,t));var w,h=Sf(()=>{w={version:"0.4.0"}});var D=_(Z=>{"use strict";h();var br=Symbol.for("yaml.alias"),Vo=Symbol.for("yaml.document"),qs=Symbol.for("yaml.map"),Jo=Symbol.for("yaml.pair"),kr=Symbol.for("yaml.scalar"),Ms=Symbol.for("yaml.seq"),Se=Symbol.for("yaml.node.type"),Jf=t=>!!t&&typeof t=="object"&&t[Se]===br,zf=t=>!!t&&typeof t=="object"&&t[Se]===Vo,Hf=t=>!!t&&typeof t=="object"&&t[Se]===qs,Qf=t=>!!t&&typeof t=="object"&&t[Se]===Jo,zo=t=>!!t&&typeof t=="object"&&t[Se]===kr,Zf=t=>!!t&&typeof t=="object"&&t[Se]===Ms;function Ho(t){if(t&&typeof t=="object")switch(t[Se]){case qs:case Ms:return!0}return!1}function Xf(t){if(t&&typeof t=="object")switch(t[Se]){case br:case qs:case kr:case Ms:return!0}return!1}var ed=t=>(zo(t)||Ho(t))&&!!t.anchor;Z.ALIAS=br;Z.DOC=Vo;Z.MAP=qs;Z.NODE_TYPE=Se;Z.PAIR=Jo;Z.SCALAR=kr;Z.SEQ=Ms;Z.hasAnchor=ed;Z.isAlias=Jf;Z.isCollection=Ho;Z.isDocument=zf;Z.isMap=Hf;Z.isNode=Xf;Z.isPair=Qf;Z.isScalar=zo;Z.isSeq=Zf});var Dt=_($r=>{"use strict";h();var J=D(),ne=Symbol("break visit"),Qo=Symbol("skip children"),me=Symbol("remove node");function Ks(t,e){let s=Zo(e);J.isDocument(t)?ut(null,t.contents,s,Object.freeze([t]))===me&&(t.contents=null):ut(null,t,s,Object.freeze([]))}Ks.BREAK=ne;Ks.SKIP=Qo;Ks.REMOVE=me;function ut(t,e,s,n){let r=Xo(t,e,s,n);if(J.isNode(r)||J.isPair(r))return ea(t,n,r),ut(t,r,s,n);if(typeof r!="symbol"){if(J.isCollection(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){let o=ut(i,e.items[i],s,n);if(typeof o=="number")i=o-1;else{if(o===ne)return ne;o===me&&(e.items.splice(i,1),i-=1)}}}else if(J.isPair(e)){n=Object.freeze(n.concat(e));let i=ut("key",e.key,s,n);if(i===ne)return ne;i===me&&(e.key=null);let o=ut("value",e.value,s,n);if(o===ne)return ne;o===me&&(e.value=null)}}return r}async function Ds(t,e){let s=Zo(e);J.isDocument(t)?await ft(null,t.contents,s,Object.freeze([t]))===me&&(t.contents=null):await ft(null,t,s,Object.freeze([]))}Ds.BREAK=ne;Ds.SKIP=Qo;Ds.REMOVE=me;async function ft(t,e,s,n){let r=await Xo(t,e,s,n);if(J.isNode(r)||J.isPair(r))return ea(t,n,r),ft(t,r,s,n);if(typeof r!="symbol"){if(J.isCollection(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){let o=await ft(i,e.items[i],s,n);if(typeof o=="number")i=o-1;else{if(o===ne)return ne;o===me&&(e.items.splice(i,1),i-=1)}}}else if(J.isPair(e)){n=Object.freeze(n.concat(e));let i=await ft("key",e.key,s,n);if(i===ne)return ne;i===me&&(e.key=null);let o=await ft("value",e.value,s,n);if(o===ne)return ne;o===me&&(e.value=null)}}return r}function Zo(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 Xo(t,e,s,n){if(typeof s=="function")return s(t,e,n);if(J.isMap(e))return s.Map?.(t,e,n);if(J.isSeq(e))return s.Seq?.(t,e,n);if(J.isPair(e))return s.Pair?.(t,e,n);if(J.isScalar(e))return s.Scalar?.(t,e,n);if(J.isAlias(e))return s.Alias?.(t,e,n)}function ea(t,e,s){let n=e[e.length-1];if(J.isCollection(n))n.items[t]=s;else if(J.isPair(n))t==="key"?n.key=s:n.value=s;else if(J.isDocument(n))n.contents=s;else{let r=J.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${r} parent`)}}$r.visit=Ks;$r.visitAsync=Ds});var Sr=_(sa=>{"use strict";h();var ta=D(),td=Dt(),sd={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},nd=t=>t.replace(/[!,[\]{}]/g,e=>sd[e]),Bt=class t{constructor(e,s){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,s)}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,s){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let n=e.trim().split(/[ \t]+/),r=n.shift();switch(r){case"%TAG":{if(n.length!==2&&(s(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[i,o]=n;return this.tags[i]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return s(0,"%YAML directive should contain exactly one part"),!1;let[i]=n;if(i==="1.1"||i==="1.2")return this.yaml.version=i,!0;{let o=/^\d+\.\d+$/.test(i);return s(6,`Unsupported YAML version ${i}`,o),!1}}default:return s(0,`Unknown directive ${r}`,!0),!1}}tagName(e,s){if(e==="!")return"!";if(e[0]!=="!")return s(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(s(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&s("Verbatim tags must end with a >"),o)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||s(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(o){return s(String(o)),null}return n==="!"?e:(s(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[s,n]of Object.entries(this.tags))if(e.startsWith(n))return s+nd(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let s=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),r;if(e&&n.length>0&&ta.isNode(e.contents)){let i={};td.visit(e.contents,(o,a)=>{ta.isNode(a)&&a.tag&&(i[a.tag]=!0)}),r=Object.keys(i)}else r=[];for(let[i,o]of n)i==="!!"&&o==="tag:yaml.org,2002:"||(!e||r.some(a=>a.startsWith(o)))&&s.push(`%TAG ${i} ${o}`);return s.join(`
|
|
4
|
+
`)}};Bt.defaultYaml={explicit:!1,version:"1.2"};Bt.defaultTags={"!!":"tag:yaml.org,2002:"};sa.Directives=Bt});var Bs=_(Ut=>{"use strict";h();var na=D(),rd=Dt();function id(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let s=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(s)}return!0}function ra(t){let e=new Set;return rd.visit(t,{Value(s,n){n.anchor&&e.add(n.anchor)}}),e}function ia(t,e){for(let s=1;;++s){let n=`${t}${s}`;if(!e.has(n))return n}}function od(t,e){let s=[],n=new Map,r=null;return{onAnchor:i=>{s.push(i),r??(r=ra(t));let o=ia(e,r);return r.add(o),o},setAnchors:()=>{for(let i of s){let o=n.get(i);if(typeof o=="object"&&o.anchor&&(na.isScalar(o.node)||na.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:n}}Ut.anchorIsValid=id;Ut.anchorNames=ra;Ut.createNodeAnchors=od;Ut.findNewAnchor=ia});var vr=_(oa=>{"use strict";h();function Gt(t,e,s,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let r=0,i=n.length;r<i;++r){let o=n[r],a=Gt(t,n,String(r),o);a===void 0?delete n[r]:a!==o&&(n[r]=a)}else if(n instanceof Map)for(let r of Array.from(n.keys())){let i=n.get(r),o=Gt(t,n,r,i);o===void 0?n.delete(r):o!==i&&n.set(r,o)}else if(n instanceof Set)for(let r of Array.from(n)){let i=Gt(t,n,r,r);i===void 0?n.delete(r):i!==r&&(n.delete(r),n.add(i))}else for(let[r,i]of Object.entries(n)){let o=Gt(t,n,r,i);o===void 0?delete n[r]:o!==i&&(n[r]=o)}return t.call(e,s,n)}oa.applyReviver=Gt});var Oe=_(ca=>{"use strict";h();var ad=D();function aa(t,e,s){if(Array.isArray(t))return t.map((n,r)=>aa(n,String(r),s));if(t&&typeof t.toJSON=="function"){if(!s||!ad.hasAnchor(t))return t.toJSON(e,s);let n={aliasCount:0,count:1,res:void 0};s.anchors.set(t,n),s.onCreate=i=>{n.res=i,delete s.onCreate};let r=t.toJSON(e,s);return s.onCreate&&s.onCreate(r),r}return typeof t=="bigint"&&!s?.keep?Number(t):t}ca.toJS=aa});var Us=_(ua=>{"use strict";h();var cd=vr(),la=D(),ld=Oe(),Ar=class{constructor(e){Object.defineProperty(this,la.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:s,maxAliasCount:n,onAnchor:r,reviver:i}={}){if(!la.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:s===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},a=ld.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:l}of o.anchors.values())r(l,c);return typeof i=="function"?cd.applyReviver(i,{"":a},"",a):a}};ua.NodeBase=Ar});var Ft=_(fa=>{"use strict";h();var ud=Bs(),fd=Dt(),dt=D(),dd=Us(),pd=Oe(),Er=class extends dd.NodeBase{constructor(e){super(dt.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,s){let n;s?.aliasResolveCache?n=s.aliasResolveCache:(n=[],fd.visit(e,{Node:(i,o)=>{(dt.isAlias(o)||dt.hasAnchor(o))&&n.push(o)}}),s&&(s.aliasResolveCache=n));let r;for(let i of n){if(i===this)break;i.anchor===this.source&&(r=i)}return r}toJSON(e,s){if(!s)return{source:this.source};let{anchors:n,doc:r,maxAliasCount:i}=s,o=this.resolve(r,s);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=n.get(o);if(a||(pd.toJS(o,null,s),a=n.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=Gs(r,o,n)),a.count*a.aliasCount>i)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,s,n){let r=`*${this.source}`;if(e){if(ud.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 Gs(t,e,s){if(dt.isAlias(e)){let n=e.resolve(t),r=s&&n&&s.get(n);return r?r.count*r.aliasCount:0}else if(dt.isCollection(e)){let n=0;for(let r of e.items){let i=Gs(t,r,s);i>n&&(n=i)}return n}else if(dt.isPair(e)){let n=Gs(t,e.key,s),r=Gs(t,e.value,s);return Math.max(n,r)}return 1}fa.Alias=Er});var Y=_(_r=>{"use strict";h();var hd=D(),gd=Us(),md=Oe(),yd=t=>!t||typeof t!="function"&&typeof t!="object",Pe=class extends gd.NodeBase{constructor(e){super(hd.SCALAR),this.value=e}toJSON(e,s){return s?.keep?this.value:md.toJS(this.value,e,s)}toString(){return String(this.value)}};Pe.BLOCK_FOLDED="BLOCK_FOLDED";Pe.BLOCK_LITERAL="BLOCK_LITERAL";Pe.PLAIN="PLAIN";Pe.QUOTE_DOUBLE="QUOTE_DOUBLE";Pe.QUOTE_SINGLE="QUOTE_SINGLE";_r.Scalar=Pe;_r.isScalarValue=yd});var Wt=_(pa=>{"use strict";h();var wd=Ft(),Qe=D(),da=Y(),bd="tag:yaml.org,2002:";function kd(t,e,s){if(e){let n=s.filter(i=>i.tag===e),r=n.find(i=>!i.format)??n[0];if(!r)throw new Error(`Tag ${e} not found`);return r}return s.find(n=>n.identify?.(t)&&!n.format)}function $d(t,e,s){if(Qe.isDocument(t)&&(t=t.contents),Qe.isNode(t))return t;if(Qe.isPair(t)){let u=s.schema[Qe.MAP].createNode?.(s.schema,null,s);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:n,onAnchor:r,onTagObj:i,schema:o,sourceObjects:a}=s,c;if(n&&t&&typeof t=="object"){if(c=a.get(t),c)return c.anchor??(c.anchor=r(t)),new wd.Alias(c.anchor);c={anchor:null,node:null},a.set(t,c)}e?.startsWith("!!")&&(e=bd+e.slice(2));let l=kd(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let u=new da.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 s.onTagObj);let p=l?.createNode?l.createNode(s.schema,t,s):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(s.schema,t,s):new da.Scalar(t);return e?p.tag=e:l.default||(p.tag=l.tag),c&&(c.node=p),p}pa.createNode=$d});var Ws=_(Fs=>{"use strict";h();var Sd=Wt(),ye=D(),vd=Us();function Cr(t,e,s){let n=s;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]=n,n=o}else n=new Map([[i,n]])}return Sd.createNode(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var ha=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,Nr=class extends vd.NodeBase{constructor(e,s){super(e),Object.defineProperty(this,"schema",{value:s,configurable:!0,enumerable:!1,writable:!0})}clone(e){let s=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(s.schema=e),s.items=s.items.map(n=>ye.isNode(n)||ye.isPair(n)?n.clone(e):n),this.range&&(s.range=this.range.slice()),s}addIn(e,s){if(ha(e))this.add(s);else{let[n,...r]=e,i=this.get(n,!0);if(ye.isCollection(i))i.addIn(r,s);else if(i===void 0&&this.schema)this.set(n,Cr(this.schema,r,s));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}deleteIn(e){let[s,...n]=e;if(n.length===0)return this.delete(s);let r=this.get(s,!0);if(ye.isCollection(r))return r.deleteIn(n);throw new Error(`Expected YAML collection at ${s}. Remaining path: ${n}`)}getIn(e,s){let[n,...r]=e,i=this.get(n,!0);return r.length===0?!s&&ye.isScalar(i)?i.value:i:ye.isCollection(i)?i.getIn(r,s):void 0}hasAllNullValues(e){return this.items.every(s=>{if(!ye.isPair(s))return!1;let n=s.value;return n==null||e&&ye.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[s,...n]=e;if(n.length===0)return this.has(s);let r=this.get(s,!0);return ye.isCollection(r)?r.hasIn(n):!1}setIn(e,s){let[n,...r]=e;if(r.length===0)this.set(n,s);else{let i=this.get(n,!0);if(ye.isCollection(i))i.setIn(r,s);else if(i===void 0&&this.schema)this.set(n,Cr(this.schema,r,s));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}};Fs.Collection=Nr;Fs.collectionFromPath=Cr;Fs.isEmptyPath=ha});var Yt=_(Ys=>{"use strict";h();var Ad=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function Tr(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var Ed=(t,e,s)=>t.endsWith(`
|
|
5
|
+
`)?Tr(s,e):s.includes(`
|
|
6
6
|
`)?`
|
|
7
|
-
`+
|
|
8
|
-
`)
|
|
9
|
-
`&&
|
|
10
|
-
|
|
11
|
-
${e}${
|
|
12
|
-
${e}${
|
|
13
|
-
`);
|
|
14
|
-
`){if(i-o>
|
|
7
|
+
`+Tr(s,e):(t.endsWith(" ")?"":" ")+s;Ys.indentComment=Tr;Ys.lineComment=Ed;Ys.stringifyComment=Ad});var ma=_(Vt=>{"use strict";h();var _d="flow",Ir="block",Vs="quoted";function Cd(t,e,s="flow",{indentAtStart:n,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=[],p={},u=r-e.length;typeof n=="number"&&(n>r-Math.max(2,i)?l.push(0):u=r-n);let f,d,m=!1,g=-1,y=-1,S=-1;s===Ir&&(g=ga(t,g,e.length),g!==-1&&(u=g+c));for(let I;I=t[g+=1];){if(s===Vs&&I==="\\"){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(I===`
|
|
8
|
+
`)s===Ir&&(g=ga(t,g,e.length)),u=g+e.length+c,f=void 0;else{if(I===" "&&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(s===Vs){for(;d===" "||d===" ";)d=I,I=t[g+=1],m=!0;let $=g>S+1?g-2:y-1;if(p[$])return t;l.push($),p[$]=!0,u=$+c,f=void 0}else m=!0}d=I}if(m&&a&&a(),l.length===0)return t;o&&o();let N=t.slice(0,l[0]);for(let I=0;I<l.length;++I){let $=l[I],E=l[I+1]||t.length;$===0?N=`
|
|
11
|
+
${e}${t.slice(0,E)}`:(s===Vs&&p[$]&&(N+=`${t[$]}\\`),N+=`
|
|
12
|
+
${e}${t.slice($+1,E)}`)}return N}function ga(t,e,s){let n=e,r=e+1,i=t[r];for(;i===" "||i===" ";)if(e<r+s)i=t[++e];else{do i=t[++e];while(i&&i!==`
|
|
13
|
+
`);n=e,r=e+1,i=t[r]}return n}Vt.FOLD_BLOCK=Ir;Vt.FOLD_FLOW=_d;Vt.FOLD_QUOTED=Vs;Vt.foldFlowLines=Cd});var zt=_(ya=>{"use strict";h();var fe=Y(),je=ma(),zs=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),Hs=t=>/^(%|---|\.\.\.)/m.test(t);function Nd(t,e,s){if(!e||e<0)return!1;let n=e-s,r=t.length;if(r<=n)return!1;for(let i=0,o=0;i<r;++i)if(t[i]===`
|
|
14
|
+
`){if(i-o>n)return!0;if(o=i+1,r-o<=n)return!1}return!0}function Jt(t,e){let s=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return s;let{implicitKey:n}=e,r=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(Hs(t)?" ":""),o="",a=0;for(let c=0,l=s[c];l;l=s[++c])if(l===" "&&s[c+1]==="\\"&&s[c+2]==="n"&&(o+=s.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(s[c+1]){case"u":{o+=s.slice(a,c);let p=s.substr(c+2,4);switch(p){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:p.substr(0,2)==="00"?o+="\\x"+p.substr(2):o+=s.substr(c,6)}c+=5,a=c+1}break;case"n":if(n||s[c+2]==='"'||s.length<r)c+=1;else{for(o+=s.slice(a,c)+`
|
|
15
15
|
|
|
16
|
-
`;
|
|
17
|
-
`,c+=2;o+=i,
|
|
18
|
-
`)||/[ \t]\n|\n[ \t]/.test(
|
|
19
|
-
${
|
|
16
|
+
`;s[c+2]==="\\"&&s[c+3]==="n"&&s[c+4]!=='"';)o+=`
|
|
17
|
+
`,c+=2;o+=i,s[c+2]===" "&&(o+="\\"),c+=1,a=c+1}break;default:c+=1}return o=a?o+s.slice(a):s,n?o:je.foldFlowLines(o,i,je.FOLD_QUOTED,zs(e,!1))}function Or(t,e){if(e.options.singleQuote===!1||e.implicitKey&&t.includes(`
|
|
18
|
+
`)||/[ \t]\n|\n[ \t]/.test(t))return Jt(t,e);let s=e.indent||(Hs(t)?" ":""),n="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
19
|
+
${s}`)+"'";return e.implicitKey?n:je.foldFlowLines(n,s,je.FOLD_FLOW,zs(e,!1))}function pt(t,e){let{singleQuote:s}=e.options,n;if(s===!1)n=Jt;else{let r=t.includes('"'),i=t.includes("'");r&&!i?n=Or:i&&!r?n=Jt:n=s?Or:Jt}return n(t,e)}var Pr;try{Pr=new RegExp(`(^|(?<!
|
|
20
20
|
))
|
|
21
21
|
+(?!
|
|
22
|
-
|$)`,"g")}catch{
|
|
22
|
+
|$)`,"g")}catch{Pr=/\n+(?!\n|$)/g}function Js({comment:t,type:e,value:s},n,r,i){let{blockQuote:o,commentString:a,lineWidth:c}=n.options;if(!o||/\n[\t ]+$/.test(s))return pt(s,n);let l=n.indent||(n.forceBlockIndent||Hs(s)?" ":""),p=o==="literal"?!0:o==="folded"||e===fe.Scalar.BLOCK_FOLDED?!1:e===fe.Scalar.BLOCK_LITERAL?!0:!Nd(s,c,l.length);if(!s)return p?`|
|
|
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}`),O=!1,
|
|
30
|
-
${l}${
|
|
31
|
-
${l}${
|
|
32
|
-
`)||
|
|
33
|
-
`)?
|
|
34
|
-
`))return
|
|
35
|
-
${c}`);if(o){let f=
|
|
36
|
-
${e.indent}${a}`:a}
|
|
37
|
-
${a}:`):(
|
|
38
|
-
`:""
|
|
39
|
-
${
|
|
24
|
+
`;let u,f;for(f=s.length;f>0;--f){let E=s[f-1];if(E!==`
|
|
25
|
+
`&&E!==" "&&E!==" ")break}let d=s.substring(f),m=d.indexOf(`
|
|
26
|
+
`);m===-1?u="-":s===d||m!==d.length-1?(u="+",i&&i()):u="",d&&(s=s.slice(0,-d.length),d[d.length-1]===`
|
|
27
|
+
`&&(d=d.slice(0,-1)),d=d.replace(Pr,`$&${l}`));let g=!1,y,S=-1;for(y=0;y<s.length;++y){let E=s[y];if(E===" ")g=!0;else if(E===`
|
|
28
|
+
`)S=y;else break}let N=s.substring(0,S<y?S+1:y);N&&(s=s.substring(N.length),N=N.replace(/\n+/g,`$&${l}`));let $=(g?l?"2":"1":"")+u;if(t&&($+=" "+a(t.replace(/ ?[\r\n]+/g," ")),r&&r()),!p){let E=s.replace(/\n+/g,`
|
|
29
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),O=!1,b=zs(n,!0);o!=="folded"&&e!==fe.Scalar.BLOCK_FOLDED&&(b.onOverflow=()=>{O=!0});let A=je.foldFlowLines(`${N}${E}${d}`,l,je.FOLD_BLOCK,b);if(!O)return`>${$}
|
|
30
|
+
${l}${A}`}return s=s.replace(/\n+/g,`$&${l}`),`|${$}
|
|
31
|
+
${l}${N}${s}${d}`}function Td(t,e,s,n){let{type:r,value:i}=t,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:p}=e;if(a&&i.includes(`
|
|
32
|
+
`)||p&&/[[\]{},]/.test(i))return pt(i,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||p||!i.includes(`
|
|
33
|
+
`)?pt(i,e):Js(t,e,s,n);if(!a&&!p&&r!==fe.Scalar.PLAIN&&i.includes(`
|
|
34
|
+
`))return Js(t,e,s,n);if(Hs(i)){if(c==="")return e.forceBlockIndent=!0,Js(t,e,s,n);if(a&&c===l)return pt(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 pt(i,e)}return a?u:je.foldFlowLines(u,c,je.FOLD_FLOW,zs(e,!1))}function Id(t,e,s,n){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=p=>{switch(p){case fe.Scalar.BLOCK_FOLDED:case fe.Scalar.BLOCK_LITERAL:return r||i?pt(o.value,e):Js(o,e,s,n);case fe.Scalar.QUOTE_DOUBLE:return Jt(o.value,e);case fe.Scalar.QUOTE_SINGLE:return Or(o.value,e);case fe.Scalar.PLAIN:return Td(o,e,s,n);default:return null}},l=c(a);if(l===null){let{defaultKeyType:p,defaultStringType:u}=e.options,f=r&&p||u;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}ya.stringifyString=Id});var Ht=_(jr=>{"use strict";h();var Od=Bs(),Re=D(),Pd=Yt(),jd=zt();function Rd(t,e){let s=Object.assign({blockQuote:!0,commentString:Pd.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),n;switch(s.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:t,flowCollectionPadding:s.flowCollectionPadding?" ":"",indent:"",indentStep:typeof s.indent=="number"?" ".repeat(s.indent):" ",inFlow:n,options:s}}function Ld(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 s,n;if(Re.isScalar(e)){n=e.value;let r=t.filter(i=>i.identify?.(n));if(r.length>1){let i=r.filter(o=>o.test);i.length>0&&(r=i)}s=r.find(i=>i.format===e.format)??r.find(i=>!i.format)}else n=e,s=t.find(r=>r.nodeClass&&n instanceof r.nodeClass);if(!s){let r=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${r} value`)}return s}function xd(t,e,{anchors:s,doc:n}){if(!n.directives)return"";let r=[],i=(Re.isScalar(t)||Re.isCollection(t))&&t.anchor;i&&Od.anchorIsValid(i)&&(s.add(i),r.push(`&${i}`));let o=t.tag??(e.default?null:e.tag);return o&&r.push(n.directives.tagString(o)),r.join(" ")}function qd(t,e,s,n){if(Re.isPair(t))return t.toString(e,s,n);if(Re.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=Re.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>r=c});r??(r=Ld(e.doc.schema.tags,i));let o=xd(i,r,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let a=typeof r.stringify=="function"?r.stringify(i,e,s,n):Re.isScalar(i)?jd.stringifyString(i,e,s,n):i.toString(e,s,n);return o?Re.isScalar(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
|
|
36
|
+
${e.indent}${a}`:a}jr.createStringifyContext=Rd;jr.stringify=qd});var $a=_(ka=>{"use strict";h();var ve=D(),wa=Y(),ba=Ht(),Qt=Yt();function Md({key:t,value:e},s,n,r){let{allNullValues:i,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:p,simpleKeys:u}}=s,f=ve.isNode(t)&&t.comment||null;if(u){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(ve.isCollection(t)||!ve.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&&!s.inFlow||ve.isCollection(t)||(ve.isScalar(t)?t.type===wa.Scalar.BLOCK_FOLDED||t.type===wa.Scalar.BLOCK_LITERAL:typeof t=="object"));s=Object.assign({},s,{allNullValues:!1,implicitKey:!d&&(u||!i),indent:a+c});let m=!1,g=!1,y=ba.stringify(t,s,()=>m=!0,()=>g=!0);if(!d&&!s.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(s.inFlow){if(i||e==null)return m&&n&&n(),y===""?"?":d?`? ${y}`:y}else if(i&&!u||e==null&&d)return y=`? ${y}`,f&&!m?y+=Qt.lineComment(y,s.indent,l(f)):g&&r&&r(),y;m&&(f=null),d?(f&&(y+=Qt.lineComment(y,s.indent,l(f))),y=`? ${y}
|
|
37
|
+
${a}:`):(y=`${y}:`,f&&(y+=Qt.lineComment(y,s.indent,l(f))));let S,N,I;ve.isNode(e)?(S=!!e.spaceBefore,N=e.commentBefore,I=e.comment):(S=!1,N=null,I=null,e&&typeof e=="object"&&(e=o.createNode(e))),s.implicitKey=!1,!d&&!f&&ve.isScalar(e)&&(s.indentAtStart=y.length+1),g=!1,!p&&c.length>=2&&!s.inFlow&&!d&&ve.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(s.indent=s.indent.substring(2));let $=!1,E=ba.stringify(e,s,()=>$=!0,()=>g=!0),O=" ";if(f||S||N){if(O=S?`
|
|
38
|
+
`:"",N){let b=l(N);O+=`
|
|
39
|
+
${Qt.indentComment(b,s.indent)}`}E===""&&!s.inFlow?O===`
|
|
40
40
|
`&&(O=`
|
|
41
41
|
|
|
42
42
|
`):O+=`
|
|
43
|
-
${
|
|
44
|
-
`),
|
|
45
|
-
${
|
|
46
|
-
`)&&(O="");return
|
|
47
|
-
${c}${
|
|
48
|
-
`}}return
|
|
49
|
-
`+
|
|
50
|
-
`))&&(l=!0),u.push(
|
|
51
|
-
${i}${r}${
|
|
52
|
-
`;return`${
|
|
53
|
-
${r}${
|
|
54
|
-
`:" ")}return
|
|
55
|
-
${r.key.commentBefore}`:
|
|
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
|
-
`)?(
|
|
43
|
+
${s.indent}`}else if(!d&&ve.isCollection(e)){let b=E[0],A=E.indexOf(`
|
|
44
|
+
`),K=A!==-1,P=s.inFlow??e.flow??e.items.length===0;if(K||!P){let R=!1;if(K&&(b==="&"||b==="!")){let q=E.indexOf(" ");b==="&"&&q!==-1&&q<A&&E[q+1]==="!"&&(q=E.indexOf(" ",q+1)),(q===-1||A<q)&&(R=!0)}R||(O=`
|
|
45
|
+
${s.indent}`)}}else(E===""||E[0]===`
|
|
46
|
+
`)&&(O="");return y+=O+E,s.inFlow?$&&n&&n():I&&!$?y+=Qt.lineComment(y,s.indent,l(I)):g&&r&&r(),y}ka.stringifyPair=Md});var Lr=_(Rr=>{"use strict";h();var Sa=Os("process");function Kd(t,...e){t==="debug"&&console.log(...e)}function Dd(t,e){(t==="debug"||t==="warn")&&(typeof Sa.emitWarning=="function"?Sa.emitWarning(e):console.warn(e))}Rr.debug=Kd;Rr.warn=Dd});var en=_(Xs=>{"use strict";h();var Zt=D(),va=Y(),Qs="<<",Zs={identify:t=>t===Qs||typeof t=="symbol"&&t.description===Qs,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new va.Scalar(Symbol(Qs)),{addToJSMap:Aa}),stringify:()=>Qs},Bd=(t,e)=>(Zs.identify(e)||Zt.isScalar(e)&&(!e.type||e.type===va.Scalar.PLAIN)&&Zs.identify(e.value))&&t?.doc.schema.tags.some(s=>s.tag===Zs.tag&&s.default);function Aa(t,e,s){if(s=t&&Zt.isAlias(s)?s.resolve(t.doc):s,Zt.isSeq(s))for(let n of s.items)xr(t,e,n);else if(Array.isArray(s))for(let n of s)xr(t,e,n);else xr(t,e,s)}function xr(t,e,s){let n=t&&Zt.isAlias(s)?s.resolve(t.doc):s;if(!Zt.isMap(n))throw new Error("Merge sources must be maps or map aliases");let r=n.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}Xs.addMergeToJSMap=Aa;Xs.isMergeKey=Bd;Xs.merge=Zs});var Mr=_(Ca=>{"use strict";h();var Ud=Lr(),Ea=en(),Gd=Ht(),_a=D(),qr=Oe();function Fd(t,e,{key:s,value:n}){if(_a.isNode(s)&&s.addToJSMap)s.addToJSMap(t,e,n);else if(Ea.isMergeKey(t,s))Ea.addMergeToJSMap(t,e,n);else{let r=qr.toJS(s,"",t);if(e instanceof Map)e.set(r,qr.toJS(n,r,t));else if(e instanceof Set)e.add(r);else{let i=Wd(s,r,t),o=qr.toJS(n,i,t);i in e?Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[i]=o}}return e}function Wd(t,e,s){if(e===null)return"";if(typeof e!="object")return String(e);if(_a.isNode(t)&&s?.doc){let n=Gd.createStringifyContext(s.doc,{});n.anchors=new Set;for(let i of s.anchors.keys())n.anchors.add(i.anchor);n.inFlow=!0,n.inStringifyKey=!0;let r=t.toString(n);if(!s.mapKeyWarned){let i=JSON.stringify(r);i.length>40&&(i=i.substring(0,36)+'..."'),Ud.warn(s.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${i}. Set mapAsMap: true to use object keys.`),s.mapKeyWarned=!0}return r}return JSON.stringify(e)}Ca.addPairToJSMap=Fd});var Le=_(Kr=>{"use strict";h();var Na=Wt(),Yd=$a(),Vd=Mr(),tn=D();function Jd(t,e,s){let n=Na.createNode(t,void 0,s),r=Na.createNode(e,void 0,s);return new sn(n,r)}var sn=class t{constructor(e,s=null){Object.defineProperty(this,tn.NODE_TYPE,{value:tn.PAIR}),this.key=e,this.value=s}clone(e){let{key:s,value:n}=this;return tn.isNode(s)&&(s=s.clone(e)),tn.isNode(n)&&(n=n.clone(e)),new t(s,n)}toJSON(e,s){let n=s?.mapAsMap?new Map:{};return Vd.addPairToJSMap(s,n,this)}toString(e,s,n){return e?.doc?Yd.stringifyPair(this,e,s,n):JSON.stringify(this)}};Kr.Pair=sn;Kr.createPair=Jd});var Dr=_(Ia=>{"use strict";h();var Ze=D(),Ta=Ht(),nn=Yt();function zd(t,e,s){return(e.inFlow??t.flow?Qd:Hd)(t,e,s)}function Hd({comment:t,items:e},s,{blockItemPrefix:n,flowChars:r,itemIndent:i,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=s,p=Object.assign({},s,{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(""),rn(s,f,g.commentBefore,u),g.comment&&(y=g.comment);else if(Ze.isPair(g)){let N=Ze.isNode(g.key)?g.key:null;N&&(!u&&N.spaceBefore&&f.push(""),rn(s,f,N.commentBefore,u))}u=!1;let S=Ta.stringify(g,p,()=>y=null,()=>u=!0);y&&(S+=nn.lineComment(S,i,l(y))),u&&y&&(u=!1),f.push(n+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
|
+
`+nn.indentComment(l(t),c),a&&a()):u&&o&&o(),d}function Qd({items:t},e,{flowChars:s,itemIndent:n}){let{indent:r,indentStep:i,flowCollectionPadding:o,options:{commentString:a}}=e;n+=i;let c=Object.assign({},e,{indent:n,inFlow:!0,type:null}),l=!1,p=0,u=[];for(let m=0;m<t.length;++m){let g=t[m],y=null;if(Ze.isNode(g))g.spaceBefore&&u.push(""),rn(e,u,g.commentBefore,!1),g.comment&&(y=g.comment);else if(Ze.isPair(g)){let N=Ze.isNode(g.key)?g.key:null;N&&(N.spaceBefore&&u.push(""),rn(e,u,N.commentBefore,!1),N.comment&&(l=!0));let I=Ze.isNode(g.value)?g.value:null;I?(I.comment&&(y=I.comment),I.commentBefore&&(l=!0)):g.value==null&&N?.comment&&(y=N.comment)}y&&(l=!0);let S=Ta.stringify(g,c,()=>y=null);m<t.length-1&&(S+=","),y&&(S+=nn.lineComment(S,n,a(y))),!l&&(u.length>p||S.includes(`
|
|
50
|
+
`))&&(l=!0),u.push(S),p=u.length}let{start:f,end:d}=s;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 rn({indent:t,options:{commentString:e}},s,n,r){if(n&&r&&(n=n.replace(/^\n+/,"")),n){let i=nn.indentComment(e(n),t);s.push(i.trimStart())}}Ia.stringifyCollection=zd});var qe=_(Ur=>{"use strict";h();var Zd=Dr(),Xd=Mr(),ep=Ws(),xe=D(),on=Le(),tp=Y();function Xt(t,e){let s=xe.isScalar(e)?e.value:e;for(let n of t)if(xe.isPair(n)&&(n.key===e||n.key===s||xe.isScalar(n.key)&&n.key.value===s))return n}var Br=class extends ep.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(xe.MAP,e),this.items=[]}static from(e,s,n){let{keepUndefined:r,replacer:i}=n,o=new this(e),a=(c,l)=>{if(typeof i=="function")l=i.call(s,c,l);else if(Array.isArray(i)&&!i.includes(c))return;(l!==void 0||r)&&o.items.push(on.createPair(c,l,n))};if(s instanceof Map)for(let[c,l]of s)a(c,l);else if(s&&typeof s=="object")for(let c of Object.keys(s))a(c,s[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,s){let n;xe.isPair(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new on.Pair(e,e?.value):n=new on.Pair(e.key,e.value);let r=Xt(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!s)throw new Error(`Key ${n.key} already set`);xe.isScalar(r.value)&&tp.isScalarValue(n.value)?r.value.value=n.value:r.value=n.value}else if(i){let o=this.items.findIndex(a=>i(n,a)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(e){let s=Xt(this.items,e);return s?this.items.splice(this.items.indexOf(s),1).length>0:!1}get(e,s){let r=Xt(this.items,e)?.value;return(!s&&xe.isScalar(r)?r.value:r)??void 0}has(e){return!!Xt(this.items,e)}set(e,s){this.add(new on.Pair(e,s),!0)}toJSON(e,s,n){let r=n?new n:s?.mapAsMap?new Map:{};s?.onCreate&&s.onCreate(r);for(let i of this.items)Xd.addPairToJSMap(s,r,i);return r}toString(e,s,n){if(!e)return JSON.stringify(this);for(let r of this.items)if(!xe.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})),Zd.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:s})}};Ur.YAMLMap=Br;Ur.findPair=Xt});var ht=_(Pa=>{"use strict";h();var sp=D(),Oa=qe(),np={collection:"map",default:!0,nodeClass:Oa.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return sp.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,s)=>Oa.YAMLMap.from(t,e,s)};Pa.map=np});var Me=_(ja=>{"use strict";h();var rp=Wt(),ip=Dr(),op=Ws(),cn=D(),ap=Y(),cp=Oe(),Gr=class extends op.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(cn.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let s=an(e);return typeof s!="number"?!1:this.items.splice(s,1).length>0}get(e,s){let n=an(e);if(typeof n!="number")return;let r=this.items[n];return!s&&cn.isScalar(r)?r.value:r}has(e){let s=an(e);return typeof s=="number"&&s<this.items.length}set(e,s){let n=an(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);let r=this.items[n];cn.isScalar(r)&&ap.isScalarValue(s)?r.value=s:this.items[n]=s}toJSON(e,s){let n=[];s?.onCreate&&s.onCreate(n);let r=0;for(let i of this.items)n.push(cp.toJS(i,String(r++),s));return n}toString(e,s,n){return e?ip.stringifyCollection(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:n,onComment:s}):JSON.stringify(this)}static from(e,s,n){let{replacer:r}=n,i=new this(e);if(s&&Symbol.iterator in Object(s)){let o=0;for(let a of s){if(typeof r=="function"){let c=s instanceof Set?a:String(o++);a=r.call(s,c,a)}i.items.push(rp.createNode(a,void 0,n))}}return i}};function an(t){let e=cn.isScalar(t)?t.value:t;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}ja.YAMLSeq=Gr});var gt=_(La=>{"use strict";h();var lp=D(),Ra=Me(),up={collection:"seq",default:!0,nodeClass:Ra.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return lp.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,s)=>Ra.YAMLSeq.from(t,e,s)};La.seq=up});var es=_(xa=>{"use strict";h();var fp=zt(),dp={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,s,n){return e=Object.assign({actualString:!0},e),fp.stringifyString(t,e,s,n)}};xa.string=dp});var ln=_(Ka=>{"use strict";h();var qa=Y(),Ma={identify:t=>t==null,createNode:()=>new qa.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new qa.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&Ma.test.test(t)?t:e.options.nullStr};Ka.nullTag=Ma});var Fr=_(Ba=>{"use strict";h();var pp=Y(),Da={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new pp.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},s){if(t&&Da.test.test(t)){let n=t[0]==="t"||t[0]==="T";if(e===n)return t}return e?s.options.trueStr:s.options.falseStr}};Ba.boolTag=Da});var mt=_(Ua=>{"use strict";h();function hp({format:t,minFractionDigits:e,tag:s,value:n}){if(typeof n=="bigint")return String(n);let r=typeof n=="number"?n:Number(n);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let i=JSON.stringify(n);if(!t&&e&&(!s||s==="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}Ua.stringifyNumber=hp});var Yr=_(un=>{"use strict";h();var gp=Y(),Wr=mt(),mp={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:Wr.stringifyNumber},yp={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():Wr.stringifyNumber(t)}},wp={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 gp.Scalar(parseFloat(t)),s=t.indexOf(".");return s!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-s-1),e},stringify:Wr.stringifyNumber};un.float=wp;un.floatExp=yp;un.floatNaN=mp});var Jr=_(dn=>{"use strict";h();var Ga=mt(),fn=t=>typeof t=="bigint"||Number.isInteger(t),Vr=(t,e,s,{intAsBigInt:n})=>n?BigInt(t):parseInt(t.substring(e),s);function Fa(t,e,s){let{value:n}=t;return fn(n)&&n>=0?s+n.toString(e):Ga.stringifyNumber(t)}var bp={identify:t=>fn(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,s)=>Vr(t,2,8,s),stringify:t=>Fa(t,8,"0o")},kp={identify:fn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,s)=>Vr(t,0,10,s),stringify:Ga.stringifyNumber},$p={identify:t=>fn(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,s)=>Vr(t,2,16,s),stringify:t=>Fa(t,16,"0x")};dn.int=kp;dn.intHex=$p;dn.intOct=bp});var Ya=_(Wa=>{"use strict";h();var Sp=ht(),vp=ln(),Ap=gt(),Ep=es(),_p=Fr(),zr=Yr(),Hr=Jr(),Cp=[Sp.map,Ap.seq,Ep.string,vp.nullTag,_p.boolTag,Hr.intOct,Hr.int,Hr.intHex,zr.floatNaN,zr.floatExp,zr.float];Wa.schema=Cp});var za=_(Ja=>{"use strict";h();var Np=Y(),Tp=ht(),Ip=gt();function Va(t){return typeof t=="bigint"||Number.isInteger(t)}var pn=({value:t})=>JSON.stringify(t),Op=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:pn},{identify:t=>t==null,createNode:()=>new Np.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:pn},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:pn},{identify:Va,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:s})=>s?BigInt(t):parseInt(t,10),stringify:({value:t})=>Va(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:pn}],Pp={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},jp=[Tp.map,Ip.seq].concat(Op,Pp);Ja.schema=jp});var Zr=_(Ha=>{"use strict";h();var ts=Os("buffer"),Qr=Y(),Rp=zt(),Lp={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof ts.Buffer=="function")return ts.Buffer.from(t,"base64");if(typeof atob=="function"){let s=atob(t.replace(/[\n\r]/g,"")),n=new Uint8Array(s.length);for(let r=0;r<s.length;++r)n[r]=s.charCodeAt(r);return n}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),t},stringify({comment:t,type:e,value:s},n,r,i){if(!s)return"";let o=s,a;if(typeof ts.Buffer=="function")a=o instanceof ts.Buffer?o.toString("base64"):ts.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=Qr.Scalar.BLOCK_LITERAL),e!==Qr.Scalar.QUOTE_DOUBLE){let c=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),l=Math.ceil(a.length/c),p=new Array(l);for(let u=0,f=0;u<l;++u,f+=c)p[u]=a.substr(f,c);a=p.join(e===Qr.Scalar.BLOCK_LITERAL?`
|
|
54
|
+
`:" ")}return Rp.stringifyString({comment:t,type:e,value:a},n,r,i)}};Ha.binary=Lp});var mn=_(gn=>{"use strict";h();var hn=D(),Xr=Le(),xp=Y(),qp=Me();function Qa(t,e){if(hn.isSeq(t))for(let s=0;s<t.items.length;++s){let n=t.items[s];if(!hn.isPair(n)){if(hn.isMap(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");let r=n.items[0]||new Xr.Pair(new xp.Scalar(null));if(n.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${n.commentBefore}
|
|
55
|
+
${r.key.commentBefore}`:n.commentBefore),n.comment){let i=r.value??r.key;i.comment=i.comment?`${n.comment}
|
|
56
|
+
${i.comment}`:n.comment}n=r}t.items[s]=hn.isPair(n)?n:new Xr.Pair(n)}}else e("Expected a sequence for this tag");return t}function Za(t,e,s){let{replacer:n}=s,r=new qp.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 n=="function"&&(o=n.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(Xr.createPair(a,c,s))}return r}var Mp={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Qa,createNode:Za};gn.createPairs=Za;gn.pairs=Mp;gn.resolvePairs=Qa});var si=_(ti=>{"use strict";h();var Xa=D(),ei=Oe(),ss=qe(),Kp=Me(),ec=mn(),Xe=class t extends Kp.YAMLSeq{constructor(){super(),this.add=ss.YAMLMap.prototype.add.bind(this),this.delete=ss.YAMLMap.prototype.delete.bind(this),this.get=ss.YAMLMap.prototype.get.bind(this),this.has=ss.YAMLMap.prototype.has.bind(this),this.set=ss.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,s){if(!s)return super.toJSON(e);let n=new Map;s?.onCreate&&s.onCreate(n);for(let r of this.items){let i,o;if(Xa.isPair(r)?(i=ei.toJS(r.key,"",s),o=ei.toJS(r.value,i,s)):i=ei.toJS(r,"",s),n.has(i))throw new Error("Ordered maps must not include duplicate keys");n.set(i,o)}return n}static from(e,s,n){let r=ec.createPairs(e,s,n),i=new this;return i.items=r.items,i}};Xe.tag="tag:yaml.org,2002:omap";var Dp={collection:"seq",identify:t=>t instanceof Map,nodeClass:Xe,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let s=ec.resolvePairs(t,e),n=[];for(let{key:r}of s.items)Xa.isScalar(r)&&(n.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):n.push(r.value));return Object.assign(new Xe,s)},createNode:(t,e,s)=>Xe.from(t,e,s)};ti.YAMLOMap=Xe;ti.omap=Dp});var ic=_(ni=>{"use strict";h();var tc=Y();function sc({value:t,source:e},s){return e&&(t?nc:rc).test.test(e)?e:t?s.options.trueStr:s.options.falseStr}var nc={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 tc.Scalar(!0),stringify:sc},rc={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 tc.Scalar(!1),stringify:sc};ni.falseTag=rc;ni.trueTag=nc});var oc=_(yn=>{"use strict";h();var Bp=Y(),ri=mt(),Up={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:ri.stringifyNumber},Gp={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():ri.stringifyNumber(t)}},Fp={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 Bp.Scalar(parseFloat(t.replace(/_/g,""))),s=t.indexOf(".");if(s!==-1){let n=t.substring(s+1).replace(/_/g,"");n[n.length-1]==="0"&&(e.minFractionDigits=n.length)}return e},stringify:ri.stringifyNumber};yn.float=Fp;yn.floatExp=Gp;yn.floatNaN=Up});var cc=_(rs=>{"use strict";h();var ac=mt(),ns=t=>typeof t=="bigint"||Number.isInteger(t);function wn(t,e,s,{intAsBigInt:n}){let r=t[0];if((r==="-"||r==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),n){switch(s){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,s);return r==="-"?-1*i:i}function ii(t,e,s){let{value:n}=t;if(ns(n)){let r=n.toString(e);return n<0?"-"+s+r.substr(1):s+r}return ac.stringifyNumber(t)}var Wp={identify:ns,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,s)=>wn(t,2,2,s),stringify:t=>ii(t,2,"0b")},Yp={identify:ns,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,s)=>wn(t,1,8,s),stringify:t=>ii(t,8,"0")},Vp={identify:ns,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,s)=>wn(t,0,10,s),stringify:ac.stringifyNumber},Jp={identify:ns,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,s)=>wn(t,2,16,s),stringify:t=>ii(t,16,"0x")};rs.int=Vp;rs.intBin=Wp;rs.intHex=Jp;rs.intOct=Yp});var ai=_(oi=>{"use strict";h();var $n=D(),bn=Le(),kn=qe(),et=class t extends kn.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let s;$n.isPair(e)?s=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?s=new bn.Pair(e.key,null):s=new bn.Pair(e,null),kn.findPair(this.items,s.key)||this.items.push(s)}get(e,s){let n=kn.findPair(this.items,e);return!s&&$n.isPair(n)?$n.isScalar(n.key)?n.key.value:n.key:n}set(e,s){if(typeof s!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof s}`);let n=kn.findPair(this.items,e);n&&!s?this.items.splice(this.items.indexOf(n),1):!n&&s&&this.items.push(new bn.Pair(e))}toJSON(e,s){return super.toJSON(e,s,Set)}toString(e,s,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),s,n);throw new Error("Set items must all have null values")}static from(e,s,n){let{replacer:r}=n,i=new this(e);if(s&&Symbol.iterator in Object(s))for(let o of s)typeof r=="function"&&(o=r.call(s,o,o)),i.items.push(bn.createPair(o,null,n));return i}};et.tag="tag:yaml.org,2002:set";var zp={collection:"map",identify:t=>t instanceof Set,nodeClass:et,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,s)=>et.from(t,e,s),resolve(t,e){if($n.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}};oi.YAMLSet=et;oi.set=zp});var li=_(Sn=>{"use strict";h();var Hp=mt();function ci(t,e){let s=t[0],n=s==="-"||s==="+"?t.substring(1):t,r=o=>e?BigInt(o):Number(o),i=n.replace(/_/g,"").split(":").reduce((o,a)=>o*r(60)+r(a),r(0));return s==="-"?r(-1)*i:i}function lc(t){let{value:e}=t,s=o=>o;if(typeof e=="bigint")s=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Hp.stringifyNumber(t);let n="";e<0&&(n="-",e*=s(-1));let r=s(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))),n+i.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Qp={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:s})=>ci(t,s),stringify:lc},Zp={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=>ci(t,!1),stringify:lc},uc={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(uc.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,s,n,r,i,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(s,n-1,r,i||0,o||0,a||0,c),p=e[8];if(p&&p!=="Z"){let u=ci(p,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Sn.floatTime=Zp;Sn.intTime=Qp;Sn.timestamp=uc});var pc=_(dc=>{"use strict";h();var Xp=ht(),eh=ln(),th=gt(),sh=es(),nh=Zr(),fc=ic(),ui=oc(),vn=cc(),rh=en(),ih=si(),oh=mn(),ah=ai(),fi=li(),ch=[Xp.map,th.seq,sh.string,eh.nullTag,fc.trueTag,fc.falseTag,vn.intBin,vn.intOct,vn.int,vn.intHex,ui.floatNaN,ui.floatExp,ui.float,nh.binary,rh.merge,ih.omap,oh.pairs,ah.set,fi.intTime,fi.floatTime,fi.timestamp];dc.schema=ch});var vc=_(hi=>{"use strict";h();var yc=ht(),lh=ln(),wc=gt(),uh=es(),fh=Fr(),di=Yr(),pi=Jr(),dh=Ya(),ph=za(),bc=Zr(),is=en(),kc=si(),$c=mn(),hc=pc(),Sc=ai(),An=li(),gc=new Map([["core",dh.schema],["failsafe",[yc.map,wc.seq,uh.string]],["json",ph.schema],["yaml11",hc.schema],["yaml-1.1",hc.schema]]),mc={binary:bc.binary,bool:fh.boolTag,float:di.float,floatExp:di.floatExp,floatNaN:di.floatNaN,floatTime:An.floatTime,int:pi.int,intHex:pi.intHex,intOct:pi.intOct,intTime:An.intTime,map:yc.map,merge:is.merge,null:lh.nullTag,omap:kc.omap,pairs:$c.pairs,seq:wc.seq,set:Sc.set,timestamp:An.timestamp},hh={"tag:yaml.org,2002:binary":bc.binary,"tag:yaml.org,2002:merge":is.merge,"tag:yaml.org,2002:omap":kc.omap,"tag:yaml.org,2002:pairs":$c.pairs,"tag:yaml.org,2002:set":Sc.set,"tag:yaml.org,2002:timestamp":An.timestamp};function gh(t,e,s){let n=gc.get(e);if(n&&!t)return s&&!n.includes(is.merge)?n.concat(is.merge):n.slice();let r=n;if(!r)if(Array.isArray(t))r=[];else{let i=Array.from(gc.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 s&&(r=r.concat(is.merge)),r.reduce((i,o)=>{let a=typeof o=="string"?mc[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(mc).map(p=>JSON.stringify(p)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return i.includes(a)||i.push(a),i},[])}hi.coreKnownTags=hh;hi.getTags=gh});var yi=_(Ac=>{"use strict";h();var gi=D(),mh=ht(),yh=gt(),wh=es(),En=vc(),bh=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,mi=class t{constructor({compat:e,customTags:s,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?En.getTags(e,"compat"):e?En.getTags(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=r?En.coreKnownTags:{},this.tags=En.getTags(s,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,gi.MAP,{value:mh.map}),Object.defineProperty(this,gi.SCALAR,{value:wh.string}),Object.defineProperty(this,gi.SEQ,{value:yh.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?bh:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Ac.Schema=mi});var _c=_(Ec=>{"use strict";h();var kh=D(),wi=Ht(),os=Yt();function $h(t,e){let s=[],n=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(s.push(c),n=!0):t.directives.docStart&&(n=!0)}n&&s.push("---");let r=wi.createStringifyContext(t,e),{commentString:i}=r.options;if(t.commentBefore){s.length!==1&&s.unshift("");let c=i(t.commentBefore);s.unshift(os.indentComment(c,""))}let o=!1,a=null;if(t.contents){if(kh.isNode(t.contents)){if(t.contents.spaceBefore&&n&&s.push(""),t.contents.commentBefore){let p=i(t.contents.commentBefore);s.push(os.indentComment(p,""))}r.forceBlockIndent=!!t.comment,a=t.contents.comment}let c=a?void 0:()=>o=!0,l=wi.stringify(t.contents,r,()=>a=null,c);a&&(l+=os.lineComment(l,"",i(a))),(l[0]==="|"||l[0]===">")&&s[s.length-1]==="---"?s[s.length-1]=`--- ${l}`:s.push(l)}else s.push(wi.stringify(t.contents,r));if(t.directives?.docEnd)if(t.comment){let c=i(t.comment);c.includes(`
|
|
57
|
+
`)?(s.push("..."),s.push(os.indentComment(c,""))):s.push(`... ${c}`)}else s.push("...");else{let c=t.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||a)&&s[s.length-1]!==""&&s.push(""),s.push(os.indentComment(i(c),"")))}return s.join(`
|
|
58
58
|
`)+`
|
|
59
|
-
`}
|
|
60
|
-
`),o=a+o}if(/[^ ]/.test(o)){let a=1,c=
|
|
59
|
+
`}Ec.stringifyDocument=$h});var as=_(Cc=>{"use strict";h();var Sh=Ft(),yt=Ws(),ce=D(),vh=Le(),Ah=Oe(),Eh=yi(),_h=_c(),bi=Bs(),Ch=vr(),Nh=Wt(),ki=Sr(),$i=class t{constructor(e,s,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ce.NODE_TYPE,{value:ce.DOC});let r=null;typeof s=="function"||Array.isArray(s)?r=s:n===void 0&&s&&(n=s,s=void 0);let i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=i;let{version:o}=i;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new ki.Directives({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,r,n)}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){wt(this.contents)&&this.contents.add(e)}addIn(e,s){wt(this.contents)&&this.contents.addIn(e,s)}createAlias(e,s){if(!e.anchor){let n=bi.anchorNames(this);e.anchor=!s||n.has(s)?bi.findNewAnchor(s||"a",n):s}return new Sh.Alias(e.anchor)}createNode(e,s,n){let r;if(typeof s=="function")e=s.call({"":e},"",e),r=s;else if(Array.isArray(s)){let y=N=>typeof N=="number"||N instanceof String||N instanceof Number,S=s.filter(y).map(String);S.length>0&&(s=s.concat(S)),r=s}else n===void 0&&s&&(n=s,s=void 0);let{aliasDuplicateObjects:i,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:p}=n??{},{onAnchor:u,setAnchors:f,sourceObjects:d}=bi.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:i??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:r,schema:this.schema,sourceObjects:d},g=Nh.createNode(e,p,m);return a&&ce.isCollection(g)&&(g.flow=!0),f(),g}createPair(e,s,n={}){let r=this.createNode(e,null,n),i=this.createNode(s,null,n);return new vh.Pair(r,i)}delete(e){return wt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return yt.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):wt(this.contents)?this.contents.deleteIn(e):!1}get(e,s){return ce.isCollection(this.contents)?this.contents.get(e,s):void 0}getIn(e,s){return yt.isEmptyPath(e)?!s&&ce.isScalar(this.contents)?this.contents.value:this.contents:ce.isCollection(this.contents)?this.contents.getIn(e,s):void 0}has(e){return ce.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return yt.isEmptyPath(e)?this.contents!==void 0:ce.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,s){this.contents==null?this.contents=yt.collectionFromPath(this.schema,[e],s):wt(this.contents)&&this.contents.set(e,s)}setIn(e,s){yt.isEmptyPath(e)?this.contents=s:this.contents==null?this.contents=yt.collectionFromPath(this.schema,Array.from(e),s):wt(this.contents)&&this.contents.setIn(e,s)}setSchema(e,s={}){typeof e=="number"&&(e=String(e));let n;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new ki.Directives({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new ki.Directives({version:e}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=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(s.schema instanceof Object)this.schema=s.schema;else if(n)this.schema=new Eh.Schema(Object.assign(n,s));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:s,mapAsMap:n,maxAliasCount:r,onAnchor:i,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},c=Ah.toJS(this.contents,s??"",a);if(typeof i=="function")for(let{count:l,res:p}of a.anchors.values())i(p,l);return typeof o=="function"?Ch.applyReviver(o,{"":c},"",c):c}toJSON(e,s){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:s})}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 s=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${s}`)}return _h.stringifyDocument(this,e)}};function wt(t){if(ce.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}Cc.Document=$i});var us=_(ls=>{"use strict";h();var cs=class extends Error{constructor(e,s,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=s}},Si=class extends cs{constructor(e,s,n){super("YAMLParseError",e,s,n)}},vi=class extends cs{constructor(e,s,n){super("YAMLWarning",e,s,n)}},Th=(t,e)=>s=>{if(s.pos[0]===-1)return;s.linePos=s.pos.map(a=>e.linePos(a));let{line:n,col:r}=s.linePos[0];s.message+=` at line ${n}, column ${r}`;let i=r-1,o=t.substring(e.lineStarts[n-1],e.lineStarts[n]).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"),n>1&&/^ *$/.test(o.substring(0,i))){let a=t.substring(e.lineStarts[n-2],e.lineStarts[n-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
|
|
60
|
+
`),o=a+o}if(/[^ ]/.test(o)){let a=1,c=s.linePos[1];c&&c.line===n&&c.col>r&&(a=Math.max(1,Math.min(c.col-r,80-i)));let l=" ".repeat(i)+"^".repeat(a);s.message+=`:
|
|
61
61
|
|
|
62
62
|
${o}
|
|
63
63
|
${l}
|
|
64
|
-
`}};
|
|
65
|
-
`))return!0;if(
|
|
66
|
-
`+
|
|
67
|
-
`+
|
|
68
|
-
`+O.comment:l.comment=O.comment),u=O.end;continue}!o&&
|
|
69
|
-
`+
|
|
70
|
-
`+
|
|
71
|
-
`+
|
|
72
|
-
`.repeat(Math.max(1,o.length-1)):"",
|
|
73
|
-
`;for(let
|
|
74
|
-
`):
|
|
75
|
-
`:!
|
|
64
|
+
`}};ls.YAMLError=cs;ls.YAMLParseError=Si;ls.YAMLWarning=vi;ls.prettifyError=Th});var fs=_(Nc=>{"use strict";h();function Ih(t,{flow:e,indicator:s,next:n,offset:r,onError:i,parentIndent:o,startOnNewline:a}){let c=!1,l=a,p=a,u="",f="",d=!1,m=!1,g=null,y=null,S=null,N=null,I=null,$=null,E=null;for(let A of t)switch(m&&(A.type!=="space"&&A.type!=="newline"&&A.type!=="comma"&&i(A.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),g&&(l&&A.type!=="comment"&&A.type!=="newline"&&i(g,"TAB_AS_INDENT","Tabs are not allowed as indentation"),g=null),A.type){case"space":!e&&(s!=="doc-start"||n?.type!=="flow-collection")&&A.source.includes(" ")&&(g=A),p=!0;break;case"comment":{p||i(A,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let K=A.source.substring(1)||" ";u?u+=f+K:u=K,f="",l=!1;break}case"newline":l?u?u+=A.source:(!$||s!=="seq-item-ind")&&(c=!0):f+=A.source,l=!0,d=!0,(y||S)&&(N=A),p=!0;break;case"anchor":y&&i(A,"MULTIPLE_ANCHORS","A node can have at most one anchor"),A.source.endsWith(":")&&i(A.offset+A.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=A,E??(E=A.offset),l=!1,p=!1,m=!0;break;case"tag":{S&&i(A,"MULTIPLE_TAGS","A node can have at most one tag"),S=A,E??(E=A.offset),l=!1,p=!1,m=!0;break}case s:(y||S)&&i(A,"BAD_PROP_ORDER",`Anchors and tags must be after the ${A.source} indicator`),$&&i(A,"UNEXPECTED_TOKEN",`Unexpected ${A.source} in ${e??"collection"}`),$=A,l=s==="seq-item-ind"||s==="explicit-key-ind",p=!1;break;case"comma":if(e){I&&i(A,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),I=A,l=!1,p=!1;break}default:i(A,"UNEXPECTED_TOKEN",`Unexpected ${A.type} token`),l=!1,p=!1}let O=t[t.length-1],b=O?O.offset+O.source.length:r;return m&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&i(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),g&&(l&&g.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&i(g,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:I,found:$,spaceBefore:c,comment:u,hasNewline:d,anchor:y,tag:S,newlineAfterProp:N,end:b,start:E??b}}Nc.resolveProps=Ih});var _n=_(Tc=>{"use strict";h();function Ai(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 s of e.start)if(s.type==="newline")return!0;if(e.sep){for(let s of e.sep)if(s.type==="newline")return!0}if(Ai(e.key)||Ai(e.value))return!0}return!1;default:return!0}}Tc.containsNewline=Ai});var Ei=_(Ic=>{"use strict";h();var Oh=_n();function Ph(t,e,s){if(e?.type==="flow-collection"){let n=e.end[0];n.indent===t&&(n.source==="]"||n.source==="}")&&Oh.containsNewline(e)&&s(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Ic.flowIndentCheck=Ph});var _i=_(Pc=>{"use strict";h();var Oc=D();function jh(t,e,s){let{uniqueKeys:n}=t.options;if(n===!1)return!1;let r=typeof n=="function"?n:(i,o)=>i===o||Oc.isScalar(i)&&Oc.isScalar(o)&&i.value===o.value;return e.some(i=>r(i.key,s))}Pc.mapIncludes=jh});var Mc=_(qc=>{"use strict";h();var jc=Le(),Rh=qe(),Rc=fs(),Lh=_n(),Lc=Ei(),xh=_i(),xc="All mapping items must start at the same column";function qh({composeNode:t,composeEmptyNode:e},s,n,r,i){let o=i?.nodeClass??Rh.YAMLMap,a=new o(s.schema);s.atRoot&&(s.atRoot=!1);let c=n.offset,l=null;for(let p of n.items){let{start:u,key:f,sep:d,value:m}=p,g=Rc.resolveProps(u,{indicator:"explicit-key-ind",next:f??d?.[0],offset:c,onError:r,parentIndent:n.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!==n.indent&&r(c,"BAD_INDENT",xc)),!g.anchor&&!g.tag&&!d){l=g.end,g.comment&&(a.comment?a.comment+=`
|
|
66
|
+
`+g.comment:a.comment=g.comment);continue}(g.newlineAfterProp||Lh.containsNewline(f))&&r(f??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else g.found?.indent!==n.indent&&r(c,"BAD_INDENT",xc);s.atKey=!0;let S=g.end,N=f?t(s,f,g,r):e(s,S,u,null,g,r);s.schema.compat&&Lc.flowIndentCheck(n.indent,f,r),s.atKey=!1,xh.mapIncludes(s,a.items,N)&&r(S,"DUPLICATE_KEY","Map keys must be unique");let I=Rc.resolveProps(d??[],{indicator:"map-value-ind",next:m,offset:N.range[2],onError:r,parentIndent:n.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=I.end,I.found){y&&(m?.type==="block-map"&&!I.hasNewline&&r(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),s.options.strict&&g.start<I.found.offset-1024&&r(N.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(s,m,I,r):e(s,c,d,null,I,r);s.schema.compat&&Lc.flowIndentCheck(n.indent,m,r),c=$.range[2];let E=new jc.Pair(N,$);s.options.keepSourceTokens&&(E.srcToken=p),a.items.push(E)}else{y&&r(N.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),I.comment&&(N.comment?N.comment+=`
|
|
67
|
+
`+I.comment:N.comment=I.comment);let $=new jc.Pair(N);s.options.keepSourceTokens&&($.srcToken=p),a.items.push($)}}return l&&l<c&&r(l,"IMPOSSIBLE","Map comment with trailing content"),a.range=[n.offset,c,l??c],a}qc.resolveBlockMap=qh});var Dc=_(Kc=>{"use strict";h();var Mh=Me(),Kh=fs(),Dh=Ei();function Bh({composeNode:t,composeEmptyNode:e},s,n,r,i){let o=i?.nodeClass??Mh.YAMLSeq,a=new o(s.schema);s.atRoot&&(s.atRoot=!1),s.atKey&&(s.atKey=!1);let c=n.offset,l=null;for(let{start:p,value:u}of n.items){let f=Kh.resolveProps(p,{indicator:"seq-item-ind",next:u,offset:c,onError:r,parentIndent:n.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(s,u,f,r):e(s,f.end,p,null,f,r);s.schema.compat&&Dh.flowIndentCheck(n.indent,u,r),c=d.range[2],a.items.push(d)}return a.range=[n.offset,c,l??c],a}Kc.resolveBlockSeq=Bh});var bt=_(Bc=>{"use strict";h();function Uh(t,e,s,n){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":{s&&!i&&n(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let p=c.substring(1)||" ";r?r+=o+p:r=p,o="";break}case"newline":r&&(o+=c),i=!0;break;default:n(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:r,offset:e}}Bc.resolveEnd=Uh});var Wc=_(Fc=>{"use strict";h();var Gh=D(),Fh=Le(),Uc=qe(),Wh=Me(),Yh=bt(),Gc=fs(),Vh=_n(),Jh=_i(),Ci="Block collections are not allowed within flow collections",Ni=t=>t&&(t.type==="block-map"||t.type==="block-seq");function zh({composeNode:t,composeEmptyNode:e},s,n,r,i){let o=n.start.source==="{",a=o?"flow map":"flow sequence",c=i?.nodeClass??(o?Uc.YAMLMap:Wh.YAMLSeq),l=new c(s.schema);l.flow=!0;let p=s.atRoot;p&&(s.atRoot=!1),s.atKey&&(s.atKey=!1);let u=n.offset+n.start.source.length;for(let y=0;y<n.items.length;++y){let S=n.items[y],{start:N,key:I,sep:$,value:E}=S,O=Gc.resolveProps(N,{flow:a,indicator:"explicit-key-ind",next:I??$?.[0],offset:u,onError:r,parentIndent:n.indent,startOnNewline:!1});if(!O.found){if(!O.anchor&&!O.tag&&!$&&!E){y===0&&O.comma?r(O.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):y<n.items.length-1&&r(O.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),O.comment&&(l.comment?l.comment+=`
|
|
68
|
+
`+O.comment:l.comment=O.comment),u=O.end;continue}!o&&s.options.strict&&Vh.containsNewline(I)&&r(I,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(y===0)O.comma&&r(O.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(O.comma||r(O.start,"MISSING_CHAR",`Missing , between ${a} items`),O.comment){let b="";e:for(let A of N)switch(A.type){case"comma":case"space":break;case"comment":b=A.source.substring(1);break e;default:break e}if(b){let A=l.items[l.items.length-1];Gh.isPair(A)&&(A=A.value??A.key),A.comment?A.comment+=`
|
|
69
|
+
`+b:A.comment=b,O.comment=O.comment.substring(b.length+1)}}if(!o&&!$&&!O.found){let b=E?t(s,E,O,r):e(s,O.end,$,null,O,r);l.items.push(b),u=b.range[2],Ni(E)&&r(b.range,"BLOCK_IN_FLOW",Ci)}else{s.atKey=!0;let b=O.end,A=I?t(s,I,O,r):e(s,b,N,null,O,r);Ni(I)&&r(A.range,"BLOCK_IN_FLOW",Ci),s.atKey=!1;let K=Gc.resolveProps($??[],{flow:a,indicator:"map-value-ind",next:E,offset:A.range[2],onError:r,parentIndent:n.indent,startOnNewline:!1});if(K.found){if(!o&&!O.found&&s.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}}O.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 E&&("source"in E&&E.source&&E.source[0]===":"?r(E,"MISSING_CHAR",`Missing space after : in ${a}`):r(K.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let P=E?t(s,E,K,r):K.found?e(s,K.end,$,null,K,r):null;P?Ni(E)&&r(P.range,"BLOCK_IN_FLOW",Ci):K.comment&&(A.comment?A.comment+=`
|
|
70
|
+
`+K.comment:A.comment=K.comment);let R=new Fh.Pair(A,P);if(s.options.keepSourceTokens&&(R.srcToken=S),o){let q=l;Jh.mapIncludes(s,q.items,A)&&r(b,"DUPLICATE_KEY","Map keys must be unique"),q.items.push(R)}else{let q=new Uc.YAMLMap(s.schema);q.flow=!0,q.items.push(R);let F=(P??A).range;q.range=[A.range[0],F[1],F[2]],l.items.push(q)}u=P?P.range[2]:K.end}}let f=o?"}":"]",[d,...m]=n.end,g=u;if(d&&d.source===f)g=d.offset+d.source.length;else{let y=a[0].toUpperCase()+a.substring(1),S=p?`${y} must end with a ${f}`:`${y} in block collection must be sufficiently indented and end with a ${f}`;r(u,p?"MISSING_CHAR":"BAD_INDENT",S),d&&d.source.length!==1&&m.unshift(d)}if(m.length>0){let y=Yh.resolveEnd(m,g,s.options.strict,r);y.comment&&(l.comment?l.comment+=`
|
|
71
|
+
`+y.comment:l.comment=y.comment),l.range=[n.offset,g,y.offset]}else l.range=[n.offset,g,g];return l}Fc.resolveFlowCollection=zh});var Vc=_(Yc=>{"use strict";h();var Hh=D(),Qh=Y(),Zh=qe(),Xh=Me(),eg=Mc(),tg=Dc(),sg=Wc();function Ti(t,e,s,n,r,i){let o=s.type==="block-map"?eg.resolveBlockMap(t,e,s,n,i):s.type==="block-seq"?tg.resolveBlockSeq(t,e,s,n,i):sg.resolveFlowCollection(t,e,s,n,i),a=o.constructor;return r==="!"||r===a.tagName?(o.tag=a.tagName,o):(r&&(o.tag=r),o)}function ng(t,e,s,n,r){let i=n.tag,o=i?e.directives.tagName(i.source,f=>r(i,"TAG_RESOLVE_FAILED",f)):null;if(s.type==="block-seq"){let{anchor:f,newlineAfterProp:d}=n,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=s.type==="block-map"?"map":s.type==="block-seq"?"seq":s.start.source==="{"?"map":"seq";if(!i||!o||o==="!"||o===Zh.YAMLMap.tagName&&a==="map"||o===Xh.YAMLSeq.tagName&&a==="seq")return Ti(t,e,s,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),Ti(t,e,s,r,o)}let l=Ti(t,e,s,r,o,c),p=c.resolve?.(l,f=>r(i,"TAG_RESOLVE_FAILED",f),e.options)??l,u=Hh.isNode(p)?p:new Qh.Scalar(p);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}Yc.composeCollection=ng});var Oi=_(Jc=>{"use strict";h();var Ii=Y();function rg(t,e,s){let n=e.offset,r=ig(e,t.options.strict,s);if(!r)return{value:"",type:null,comment:"",range:[n,n,n]};let i=r.mode===">"?Ii.Scalar.BLOCK_FOLDED:Ii.Scalar.BLOCK_LITERAL,o=e.source?og(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=n+r.length;return e.source&&(y+=e.source.length),{value:g,type:i,comment:r.comment,range:[n,y,y]}}let c=e.indent+r.indent,l=e.offset+r.length,p=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&&s(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),p=g,c===0&&!t.atRoot&&s(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<p;++g)u+=o[g][0].slice(c)+`
|
|
73
|
+
`;for(let g=p;g<a;++g){let[y,S]=o[g];l+=y.length+S.length+1;let N=S[S.length-1]==="\r";if(N&&(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"}`;s(l-S.length-(N?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=n+r.length+e.source.length;return{value:u,type:i,comment:r.comment,range:[n,m,m]}}function ig({offset:t,props:e},s,n){if(e[0].type!=="block-scalar-header")return n(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&&n(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${r}`);let l=!1,p="",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":s&&!l&&n(d,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),u+=d.source.length,p=d.source.substring(1);break;case"error":n(d,"UNEXPECTED_TOKEN",d.message),u+=d.source.length;break;default:{let m=`Unexpected token in block scalar header: ${d.type}`;n(d,"UNEXPECTED_TOKEN",m);let g=d.source;g&&typeof g=="string"&&(u+=g.length)}}}return{mode:i,indent:o,chomp:a,comment:p,length:u}}function og(t){let e=t.split(/\n( *)/),s=e[0],n=s.match(/^( *)/),i=[n?.[1]?[n[1],s.slice(n[1].length)]:["",s]];for(let o=1;o<e.length;o+=2)i.push([e[o],e[o+1]]);return i}Jc.resolveBlockScalar=rg});var ji=_(Hc=>{"use strict";h();var Pi=Y(),ag=bt();function cg(t,e,s){let{offset:n,type:r,source:i,end:o}=t,a,c,l=(f,d,m)=>s(n+f,d,m);switch(r){case"scalar":a=Pi.Scalar.PLAIN,c=lg(i,l);break;case"single-quoted-scalar":a=Pi.Scalar.QUOTE_SINGLE,c=ug(i,l);break;case"double-quoted-scalar":a=Pi.Scalar.QUOTE_DOUBLE,c=fg(i,l);break;default:return s(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[n,n+i.length,n+i.length]}}let p=n+i.length,u=ag.resolveEnd(o,p,e,s);return{value:c,type:a,comment:u.comment,range:[n,p,u.offset]}}function lg(t,e){let s="";switch(t[0]){case" ":s="a tab character";break;case",":s="flow indicator character ,";break;case"%":s="directive indicator character %";break;case"|":case">":{s=`block scalar indicator ${t[0]}`;break}case"@":case"`":{s=`reserved character ${t[0]}`;break}}return s&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${s}`),zc(t)}function ug(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,s;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
87
|
+
`,"sy"),s=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
88
|
+
`,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,s=/[ \t]*(.*?)[ \t]*\r?\n/sy}let n=e.exec(t);if(!n)return t;let r=n[1],i=" ",o=e.lastIndex;for(s.lastIndex=o;n=s.exec(t);)n[1]===""?i===`
|
|
89
89
|
`?r+=i:i=`
|
|
90
|
-
`:(r+=i+
|
|
90
|
+
`:(r+=i+n[1],i=" "),o=s.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=o,n=a.exec(t),r+i+(n?.[1]??"")}function fg(t,e){let s="";for(let n=1;n<t.length-1;++n){let r=t[n];if(!(r==="\r"&&t[n+1]===`
|
|
91
91
|
`))if(r===`
|
|
92
|
-
`){let{fold:i,offset:o}=
|
|
93
|
-
`)for(i=n
|
|
94
|
-
`)for(i=
|
|
95
|
-
`&&!(o==="\r"&&n
|
|
96
|
-
`)&&(
|
|
97
|
-
`||
|
|
98
|
-
`);)
|
|
99
|
-
`&&(
|
|
100
|
-
`),e+=1,
|
|
101
|
-
`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function
|
|
92
|
+
`){let{fold:i,offset:o}=dg(t,n);s+=i,n=o}else if(r==="\\"){let i=t[++n],o=pg[i];if(o)s+=o;else if(i===`
|
|
93
|
+
`)for(i=t[n+1];i===" "||i===" ";)i=t[++n+1];else if(i==="\r"&&t[n+1]===`
|
|
94
|
+
`)for(i=t[++n+1];i===" "||i===" ";)i=t[++n+1];else if(i==="x"||i==="u"||i==="U"){let a={x:2,u:4,U:8}[i];s+=hg(t,n+1,a,e),n+=a}else{let a=t.substr(n-1,2);e(n-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),s+=a}}else if(r===" "||r===" "){let i=n,o=t[n+1];for(;o===" "||o===" ";)o=t[++n+1];o!==`
|
|
95
|
+
`&&!(o==="\r"&&t[n+2]===`
|
|
96
|
+
`)&&(s+=n>i?t.slice(i,n+1):r)}else s+=r}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),s}function dg(t,e){let s="",n=t[e+1];for(;(n===" "||n===" "||n===`
|
|
97
|
+
`||n==="\r")&&!(n==="\r"&&t[e+2]!==`
|
|
98
|
+
`);)n===`
|
|
99
|
+
`&&(s+=`
|
|
100
|
+
`),e+=1,n=t[e+1];return s||(s=" "),{fold:s,offset:e}}var pg={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 hg(t,e,s,n){let r=t.substr(e,s),o=r.length===s&&/^[0-9a-fA-F]+$/.test(r)?parseInt(r,16):NaN;if(isNaN(o)){let a=t.substr(e-2,s+2);return n(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}return String.fromCodePoint(o)}Hc.resolveFlowScalar=cg});var Xc=_(Zc=>{"use strict";h();var tt=D(),Qc=Y(),gg=Oi(),mg=ji();function yg(t,e,s,n){let{value:r,type:i,comment:o,range:a}=e.type==="block-scalar"?gg.resolveBlockScalar(t,e,n):mg.resolveFlowScalar(e,t.options.strict,n),c=s?t.directives.tagName(s.source,u=>n(s,"TAG_RESOLVE_FAILED",u)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[tt.SCALAR]:c?l=wg(t.schema,r,c,s,n):e.type==="scalar"?l=bg(t,r,e,n):l=t.schema[tt.SCALAR];let p;try{let u=l.resolve(r,f=>n(s??e,"TAG_RESOLVE_FAILED",f),t.options);p=tt.isScalar(u)?u:new Qc.Scalar(u)}catch(u){let f=u instanceof Error?u.message:String(u);n(s??e,"TAG_RESOLVE_FAILED",f),p=new Qc.Scalar(r)}return p.range=a,p.source=r,i&&(p.type=i),c&&(p.tag=c),l.format&&(p.format=l.format),o&&(p.comment=o),p}function wg(t,e,s,n,r){if(s==="!")return t[tt.SCALAR];let i=[];for(let a of t.tags)if(!a.collection&&a.tag===s)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[s];return o&&!o.collection?(t.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(r(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${s}`,s!=="tag:yaml.org,2002:str"),t[tt.SCALAR])}function bg({atKey:t,directives:e,schema:s},n,r,i){let o=s.tags.find(a=>(a.default===!0||t&&a.default==="key")&&a.test?.test(n))||s[tt.SCALAR];if(s.compat){let a=s.compat.find(c=>c.default&&c.test?.test(n))??s[tt.SCALAR];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),p=`Value may be parsed as either ${c} or ${l}`;i(r,"TAG_RESOLVE_FAILED",p,!0)}}return o}Zc.composeScalar=yg});var tl=_(el=>{"use strict";h();function kg(t,e,s){if(e){s??(s=e.length);for(let n=s-1;n>=0;--n){let r=e[n];switch(r.type){case"space":case"comment":case"newline":t-=r.source.length;continue}for(r=e[++n];r?.type==="space";)t+=r.source.length,r=e[++n];break}}return t}el.emptyScalarPosition=kg});var rl=_(Li=>{"use strict";h();var $g=Ft(),Sg=D(),vg=Vc(),sl=Xc(),Ag=bt(),Eg=tl(),_g={composeNode:nl,composeEmptyNode:Ri};function nl(t,e,s,n){let r=t.atKey,{spaceBefore:i,comment:o,anchor:a,tag:c}=s,l,p=!0;switch(e.type){case"alias":l=Cg(t,e,n),(a||c)&&n(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=sl.composeScalar(t,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":l=vg.composeCollection(_g,t,e,s,n),a&&(l.anchor=a.source.substring(1));break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",u),l=Ri(t,e.offset,void 0,null,s,n),p=!1}}return a&&l.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),r&&t.options.stringKeys&&(!Sg.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(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&&p&&(l.srcToken=e),l}function Ri(t,e,s,n,{spaceBefore:r,comment:i,anchor:o,tag:a,end:c},l){let p={type:"scalar",offset:Eg.emptyScalarPosition(e,s,n),indent:-1,source:""},u=sl.composeScalar(t,p,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 Cg({options:t},{offset:e,source:s,end:n},r){let i=new $g.Alias(s.substring(1));i.source===""&&r(e,"BAD_ALIAS","Alias cannot be an empty string"),i.source.endsWith(":")&&r(e+s.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+s.length,a=Ag.resolveEnd(n,o,t.strict,r);return i.range=[e,o,a.offset],a.comment&&(i.comment=a.comment),i}Li.composeEmptyNode=Ri;Li.composeNode=nl});var al=_(ol=>{"use strict";h();var Ng=as(),il=rl(),Tg=bt(),Ig=fs();function Og(t,e,{offset:s,start:n,value:r,end:i},o){let a=Object.assign({_directives:e},t),c=new Ng.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},p=Ig.resolveProps(n,{indicator:"doc-start",next:r??i?.[0],offset:s,onError:o,parentIndent:0,startOnNewline:!0});p.found&&(c.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!p.hasNewline&&o(p.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=r?il.composeNode(l,r,p,o):il.composeEmptyNode(l,p.end,n,null,p,o);let u=c.contents.range[2],f=Tg.resolveEnd(i,u,!1,o);return f.comment&&(c.comment=f.comment),c.range=[s,u,f.offset],c}ol.composeDoc=Og});var qi=_(ul=>{"use strict";h();var Pg=Os("process"),jg=Sr(),Rg=as(),ds=us(),cl=D(),Lg=al(),xg=bt();function ps(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:s}=t;return[e,e+(typeof s=="string"?s.length:1)]}function ll(t){let e="",s=!1,n=!1;for(let r=0;r<t.length;++r){let i=t[r];switch(i[0]){case"#":e+=(e===""?"":n?`
|
|
102
102
|
|
|
103
103
|
`:`
|
|
104
|
-
`)+(i.substring(1)||" "),
|
|
105
|
-
${
|
|
106
|
-
${a}`:
|
|
107
|
-
${o}`:
|
|
108
|
-
${
|
|
104
|
+
`)+(i.substring(1)||" "),s=!0,n=!1;break;case"%":t[r+1]?.[0]!=="#"&&(r+=1),s=!1;break;default:s||(n=!0),s=!1}}return{comment:e,afterEmptyLine:n}}var xi=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(s,n,r,i)=>{let o=ps(s);i?this.warnings.push(new ds.YAMLWarning(o,n,r)):this.errors.push(new ds.YAMLParseError(o,n,r))},this.directives=new jg.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,s){let{comment:n,afterEmptyLine:r}=ll(this.prelude);if(n){let i=e.contents;if(s)e.comment=e.comment?`${e.comment}
|
|
105
|
+
${n}`:n;else if(r||e.directives.docStart||!i)e.commentBefore=n;else if(cl.isCollection(i)&&!i.flow&&i.items.length>0){let o=i.items[0];cl.isPair(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${n}
|
|
106
|
+
${a}`:n}else{let o=i.commentBefore;i.commentBefore=o?`${n}
|
|
107
|
+
${o}`:n}}s?(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:ll(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,s=!1,n=-1){for(let r of e)yield*this.next(r);yield*this.end(s,n)}*next(e){switch(Pg.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(s,n,r)=>{let i=ps(e);i[0]+=s,this.onError(i,"BAD_DIRECTIVE",n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let s=Lg.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!s.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(s,!1),this.doc&&(yield this.doc),this.doc=s,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let s=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new ds.YAMLParseError(ps(e),"UNEXPECTED_TOKEN",s);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){let n="Unexpected doc-end without preceding document";this.errors.push(new ds.YAMLParseError(ps(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let s=xg.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),s.comment){let n=this.doc.comment;this.doc.comment=n?`${n}
|
|
108
|
+
${s.comment}`:s.comment}this.doc.range[2]=s.offset;break}default:this.errors.push(new ds.YAMLParseError(ps(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,s=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let n=Object.assign({_directives:this.directives},this.options),r=new Rg.Document(void 0,n);this.atDirectives&&this.onError(s,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,s,s],this.decorate(r,!1),yield r}}};ul.Composer=xi});var pl=_(Cn=>{"use strict";h();var qg=Oi(),Mg=ji(),Kg=us(),fl=zt();function Dg(t,e=!0,s){if(t){let n=(r,i,o)=>{let a=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(s)s(a,i,o);else throw new Kg.YAMLParseError([a,a+1],i,o)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Mg.resolveFlowScalar(t,e,n);case"block-scalar":return qg.resolveBlockScalar({options:{strict:e}},t,n)}}return null}function Bg(t,e){let{implicitKey:s=!1,indent:n,inFlow:r=!1,offset:i=-1,type:o="PLAIN"}=e,a=fl.stringifyString({type:o,value:t},{implicitKey:s,indent:n>0?" ".repeat(n):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:n,source:`
|
|
109
109
|
`}];switch(a[0]){case"|":case">":{let l=a.indexOf(`
|
|
110
|
-
`),
|
|
111
|
-
`,f=[{type:"block-scalar-header",offset:i,indent:
|
|
112
|
-
`}),{type:"block-scalar",offset:i,indent:
|
|
113
|
-
`),
|
|
114
|
-
`;if(
|
|
115
|
-
`});for(let c of Object.keys(
|
|
116
|
-
`};delete
|
|
110
|
+
`),p=a.substring(0,l),u=a.substring(l+1)+`
|
|
111
|
+
`,f=[{type:"block-scalar-header",offset:i,indent:n,source:p}];return dl(f,c)||f.push({type:"newline",offset:-1,indent:n,source:`
|
|
112
|
+
`}),{type:"block-scalar",offset:i,indent:n,props:f,source:u}}case'"':return{type:"double-quoted-scalar",offset:i,indent:n,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:i,indent:n,source:a,end:c};default:return{type:"scalar",offset:i,indent:n,source:a,end:c}}}function Ug(t,e,s={}){let{afterKey:n=!1,implicitKey:r=!1,inFlow:i=!1,type:o}=s,a="indent"in t?t.indent:null;if(n&&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=fl.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">":Gg(t,c);break;case'"':Mi(t,c,"double-quoted-scalar");break;case"'":Mi(t,c,"single-quoted-scalar");break;default:Mi(t,c,"scalar")}}function Gg(t,e){let s=e.indexOf(`
|
|
113
|
+
`),n=e.substring(0,s),r=e.substring(s+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=n,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:n}];dl(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 dl(t,e){if(e)for(let s of e)switch(s.type){case"space":case"comment":t.push(s);break;case"newline":return t.push(s),!0}return!1}function Mi(t,e,s){switch(t.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":t.type=s,t.source=e;break;case"block-scalar":{let n=t.props.slice(1),r=e.length;t.props[0].type==="block-scalar-header"&&(r-=t.props[0].source.length);for(let i of n)i.offset+=r;delete t.props,Object.assign(t,{type:s,source:e,end:n});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:s,source:e,end:[r]});break}default:{let n="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:s,indent:n,source:e,end:r})}}}Cn.createScalarToken=Bg;Cn.resolveAsScalar=Dg;Cn.setScalarValue=Ug});var gl=_(hl=>{"use strict";h();var Fg=t=>"type"in t?Tn(t):Nn(t);function Tn(t){switch(t.type){case"block-scalar":{let e="";for(let s of t.props)e+=Tn(s);return e+t.source}case"block-map":case"block-seq":{let e="";for(let s of t.items)e+=Nn(s);return e}case"flow-collection":{let e=t.start.source;for(let s of t.items)e+=Nn(s);for(let s of t.end)e+=s.source;return e}case"document":{let e=Nn(t);if(t.end)for(let s of t.end)e+=s.source;return e}default:{let e=t.source;if("end"in t&&t.end)for(let s of t.end)e+=s.source;return e}}}function Nn({start:t,key:e,sep:s,value:n}){let r="";for(let i of t)r+=i.source;if(e&&(r+=Tn(e)),s)for(let i of s)r+=i.source;return n&&(r+=Tn(n)),r}hl.stringify=Fg});var bl=_(wl=>{"use strict";h();var Ki=Symbol("break visit"),Wg=Symbol("skip children"),ml=Symbol("remove item");function st(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),yl(Object.freeze([]),t,e)}st.BREAK=Ki;st.SKIP=Wg;st.REMOVE=ml;st.itemAtPath=(t,e)=>{let s=t;for(let[n,r]of e){let i=s?.[n];if(i&&"items"in i)s=i.items[r];else return}return s};st.parentCollection=(t,e)=>{let s=st.itemAtPath(t,e.slice(0,-1)),n=e[e.length-1][0],r=s?.[n];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function yl(t,e,s){let n=s(e,t);if(typeof n=="symbol")return n;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=yl(Object.freeze(t.concat([[r,o]])),i.items[o],s);if(typeof a=="number")o=a-1;else{if(a===Ki)return Ki;a===ml&&(i.items.splice(o,1),o-=1)}}typeof n=="function"&&r==="key"&&(n=n(e,t))}}return typeof n=="function"?n(e,t):n}wl.visit=st});var In=_(re=>{"use strict";h();var Di=pl(),Yg=gl(),Vg=bl(),Bi="\uFEFF",Ui="",Gi="",Fi="",Jg=t=>!!t&&"items"in t,zg=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function Hg(t){switch(t){case Bi:return"<BOM>";case Ui:return"<DOC>";case Gi:return"<FLOW_END>";case Fi:return"<SCALAR>";default:return JSON.stringify(t)}}function Qg(t){switch(t){case Bi:return"byte-order-mark";case Ui:return"doc-mode";case Gi:return"flow-error-end";case Fi: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+
|
|
124
|
-
`||
|
|
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]===
|
|
126
|
-
`,this.pos);if(r!==-1){for(;r!==-1;){let i=this.continueScalar(r+1);if(i===-1)break;r=
|
|
127
|
-
`,i)}r!==-1&&(
|
|
128
|
-
`:e=i,
|
|
129
|
-
`)break}default:break e}if(!
|
|
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(
|
|
131
|
-
`;)
|
|
132
|
-
`&&i>=this.pos&&i+1+
|
|
133
|
-
`?(
|
|
134
|
-
`,i=this.buffer[
|
|
135
|
-
`){let o=this.continueScalar(
|
|
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}re.createScalarToken=Di.createScalarToken;re.resolveAsScalar=Di.resolveAsScalar;re.setScalarValue=Di.setScalarValue;re.stringify=Yg.stringify;re.visit=Vg.visit;re.BOM=Bi;re.DOCUMENT=Ui;re.FLOW_END=Gi;re.SCALAR=Fi;re.isCollection=Jg;re.isScalar=zg;re.prettyToken=Hg;re.tokenType=Qg});var Vi=_($l=>{"use strict";h();var hs=In();function de(t){switch(t){case void 0:case" ":case`
|
|
119
|
+
`:case"\r":case" ":return!0;default:return!1}}var kl=new Set("0123456789ABCDEFabcdef"),Zg=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),On=new Set(",[]{}"),Xg=new Set(` ,[]{}
|
|
120
|
+
\r `),Wi=t=>!t||Xg.has(t),Yi=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,s=!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=!s;let n=this.next??"stream";for(;n&&(s||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,s=this.buffer[e];for(;s===" "||s===" ";)s=this.buffer[++e];return!s||s==="#"||s===`
|
|
121
|
+
`?!0:s==="\r"?this.buffer[e+1]===`
|
|
122
|
+
`:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let s=this.buffer[e];if(this.indentNext>0){let n=0;for(;s===" ";)s=this.buffer[++n+e];if(s==="\r"){let r=this.buffer[n+e+1];if(r===`
|
|
123
|
+
`||!r&&!this.atEnd)return e+n+1}return s===`
|
|
124
|
+
`||n>=this.indentNext||!s&&!this.atEnd?e+n:-1}if(s==="-"||s==="."){let n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&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]===hs.BOM&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let s=e.length,n=e.indexOf("#");for(;n!==-1;){let i=e[n-1];if(i===" "||i===" "){s=n-1;break}else n=e.indexOf("#",n+1)}for(;;){let i=e[s-1];if(i===" "||i===" ")s-=1;else break}let r=(yield*this.pushCount(s))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-r),this.pushNewline(),"stream"}if(this.atLineEnd()){let s=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-s),yield*this.pushNewline(),"stream"}return yield hs.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 s=this.peek(3);if((s==="---"||s==="...")&&de(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,s==="---"?"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,s]=this.peek(2);if(!s&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&de(s)){let n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let s=yield*this.pushIndicators();switch(e[s]){case"#":yield*this.pushCount(e.length-s);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(Wi),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return s+=yield*this.parseBlockScalarHeader(),s+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-s),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,s,n=-1;do e=yield*this.pushNewline(),e>0?(s=yield*this.pushSpaces(!1),this.indentValue=n=s):s=0,s+=yield*this.pushSpaces(!0);while(e+s>0);let r=this.getLine();if(r===null)return this.setNext("flow");if((n!==-1&&n<this.indentNext&&r[0]!=="#"||n===0&&(r.startsWith("---")||r.startsWith("..."))&&de(r[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(r[0]==="]"||r[0]==="}")))return this.flowLevel=0,yield hs.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(Wi),"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),s=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;s!==-1&&this.buffer[s+1]==="'";)s=this.buffer.indexOf("'",s+2);else for(;s!==-1;){let i=0;for(;this.buffer[s-1-i]==="\\";)i+=1;if(i%2===0)break;s=this.buffer.indexOf('"',s+1)}let n=this.buffer.substring(0,s),r=n.indexOf(`
|
|
126
|
+
`,this.pos);if(r!==-1){for(;r!==-1;){let i=this.continueScalar(r+1);if(i===-1)break;r=n.indexOf(`
|
|
127
|
+
`,i)}r!==-1&&(s=r-(n[r-1]==="\r"?2:1))}if(s===-1){if(!this.atEnd)return this.setNext("quoted-scalar");s=this.buffer.length}return yield*this.pushToIndex(s+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let s=this.buffer[++e];if(s==="+")this.blockScalarKeep=!0;else if(s>"0"&&s<="9")this.blockScalarIndent=Number(s)-1;else if(s!=="-")break}return yield*this.pushUntil(s=>de(s)||s==="#")}*parseBlockScalar(){let e=this.pos-1,s=0,n;e:for(let i=this.pos;n=this.buffer[i];++i)switch(n){case" ":s+=1;break;case`
|
|
128
|
+
`:e=i,s=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(!n&&!this.atEnd)return this.setNext("block-scalar");if(s>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=s: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
|
+
`,i)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let r=e+1;for(n=this.buffer[r];n===" ";)n=this.buffer[++r];if(n===" "){for(;n===" "||n===" "||n==="\r"||n===`
|
|
131
|
+
`;)n=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+s>a)e=i;else break}while(!0);return yield hs.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,s=this.pos-1,n=this.pos-1,r;for(;r=this.buffer[++n];)if(r===":"){let i=this.buffer[n+1];if(de(i)||e&&On.has(i))break;s=n}else if(de(r)){let i=this.buffer[n+1];if(r==="\r"&&(i===`
|
|
133
|
+
`?(n+=1,r=`
|
|
134
|
+
`,i=this.buffer[n+1]):s=n),i==="#"||e&&On.has(i))break;if(r===`
|
|
135
|
+
`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&On.has(r))break;s=n}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield hs.SCALAR,yield*this.pushToIndex(s+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,s){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(s&&(yield""),0)}*pushIndicators(){switch(this.charAt(0)){case"!":return(yield*this.pushTag())+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"&":return(yield*this.pushUntil(Wi))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{let e=this.flowLevel>0,s=this.charAt(1);if(de(s)||e&&On.has(s))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,s=this.buffer[e];for(;!de(s)&&s!==">";)s=this.buffer[++e];return yield*this.pushToIndex(s===">"?e+1:e,!1)}else{let e=this.pos+1,s=this.buffer[e];for(;s;)if(Zg.has(s))s=this.buffer[++e];else if(s==="%"&&kl.has(this.buffer[e+1])&&kl.has(this.buffer[e+2]))s=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:"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:"chatgpt",name:"ChatGPT",where:"chatgpt.com connectors",documents:[],notYet:"signs in without a metadata document"},{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 s=this.pos-1,n;do n=this.buffer[++s];while(n===" "||e&&n===" ");let r=s-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=s),r}*pushUntil(e){let s=this.pos,n=this.buffer[s];for(;!e(n);)n=this.buffer[++s];return yield*this.pushToIndex(s,!1)}};$l.Lexer=Yi});var zi=_(Sl=>{"use strict";h();var Ji=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let s=0,n=this.lineStarts.length;for(;s<n;){let i=s+n>>1;this.lineStarts[i]<e?s=i+1:n=i}if(this.lineStarts[s]===e)return{line:s+1,col:1};if(s===0)return{line:0,col:e};let r=this.lineStarts[s-1];return{line:s,col:e-r+1}}}};Sl.LineCounter=Ji});var Qi=_(Cl=>{"use strict";h();var em=Os("process"),vl=In(),tm=Vi();function Ke(t,e){for(let s=0;s<t.length;++s)if(t[s].type===e)return!0;return!1}function Al(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 _l(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 Pn(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 kt(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 El(t){if(t.start.type==="flow-seq-start")for(let e of t.items)e.sep&&!e.value&&!Ke(e.start,"explicit-key-ind")&&!Ke(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,_l(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 Hi=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 tm.Lexer,this.onNewLine=e}*parse(e,s=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(e,s))yield*this.next(n);s||(yield*this.end())}*next(e){if(this.source=e,em.env.LOG_TOKENS&&console.log("|",vl.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let s=vl.tokenType(e);if(s)if(s==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=s,yield*this.step(),s){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 n=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:n,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 s=e??this.stack.pop();if(!s)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield s;else{let n=this.peek(1);switch(s.type==="block-scalar"?s.indent="indent"in n?n.indent:0:s.type==="flow-collection"&&n.type==="document"&&(s.indent=0),s.type==="flow-collection"&&El(s),n.type){case"document":n.value=s;break;case"block-scalar":n.props.push(s);break;case"block-map":{let r=n.items[n.items.length-1];if(r.value){n.items.push({start:[],key:s,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=s;else{Object.assign(r,{key:s,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{let r=n.items[n.items.length-1];r.value?n.items.push({start:[],value:s}):r.value=s;break}case"flow-collection":{let r=n.items[n.items.length-1];!r||r.value?n.items.push({start:[],key:s,sep:[]}):r.sep?r.value=s:Object.assign(r,{key:s,sep:[]});return}default:yield*this.pop(),yield*this.pop(s)}if((n.type==="document"||n.type==="block-map"||n.type==="block-seq")&&(s.type==="block-map"||s.type==="block-seq")){let r=s.items[s.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&Al(r.start)===-1&&(s.indent===0||r.start.every(i=>i.type!=="comment"||i.indent<s.indent))&&(n.type==="document"?n.end=r.start:n.items.push({start:r.start}),s.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":{Al(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 s=this.startBlockValue(e);s?this.stack.push(s):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 s=Pn(this.peek(2)),n=kt(s),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:n,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 s=this.source.indexOf(`
|
|
138
|
+
`)+1;for(;s!==0;)this.onNewLine(this.offset+s),s=this.source.indexOf(`
|
|
139
|
+
`,s)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let s=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,s.value){let n="end"in s.value?s.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else s.sep?s.sep.push(this.sourceToken):s.start.push(this.sourceToken);return;case"space":case"comment":if(s.value)e.items.push({start:[this.sourceToken]});else if(s.sep)s.sep.push(this.sourceToken);else{if(this.atIndentedComment(s.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Array.prototype.push.apply(r,s.start),r.push(this.sourceToken),e.items.pop();return}}s.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,r=n&&(s.sep||s.explicitKey)&&this.type!=="seq-item-ind",i=[];if(r&&s.sep&&!s.value){let o=[];for(let a=0;a<s.sep.length;++a){let c=s.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=s.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":r||s.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):s.sep?s.sep.push(this.sourceToken):s.start.push(this.sourceToken);return;case"explicit-key-ind":!s.sep&&!s.explicitKey?(s.start.push(this.sourceToken),s.explicitKey=!0):r||s.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(s.explicitKey)if(s.sep)if(s.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Ke(s.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(_l(s.key)&&!Ke(s.sep,"newline")){let o=kt(s.start),a=s.key,c=s.sep;c.push(this.sourceToken),delete s.key,delete s.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else i.length>0?s.sep=s.sep.concat(i,this.sourceToken):s.sep.push(this.sourceToken);else if(Ke(s.start,"newline"))Object.assign(s,{key:null,sep:[this.sourceToken]});else{let o=kt(s.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else s.sep?s.value||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):Ke(s.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):s.sep.push(this.sourceToken):Object.assign(s,{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||s.value?(e.items.push({start:i,key:o,sep:[]}),this.onKeyLine=!0):s.sep?this.stack.push(o):(Object.assign(s,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!s.explicitKey&&s.sep&&!Ke(s.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 n&&e.items.push({start:i});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let s=e.items[e.items.length-1];switch(this.type){case"newline":if(s.value){let n="end"in s.value?s.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else s.start.push(this.sourceToken);return;case"space":case"comment":if(s.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(s.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Array.prototype.push.apply(r,s.start),r.push(this.sourceToken),e.items.pop();return}}s.start.push(this.sourceToken)}return;case"anchor":case"tag":if(s.value||this.indent<=e.indent)break;s.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;s.value||Ke(s.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):s.start.push(this.sourceToken);return}if(this.indent>e.indent){let n=this.startBlockValue(e);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let s=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n&&n.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!s||s.sep?e.items.push({start:[this.sourceToken]}):s.start.push(this.sourceToken);return;case"map-value-ind":!s||s.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):s.sep?s.sep.push(this.sourceToken):Object.assign(s,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!s||s.value?e.items.push({start:[this.sourceToken]}):s.sep?s.sep.push(this.sourceToken):s.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let r=this.flowScalar(this.type);!s||s.value?e.items.push({start:[],key:r,sep:[]}):s.sep?this.stack.push(r):Object.assign(s,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===e.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){let r=Pn(n),i=kt(r);El(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 s=this.source.indexOf(`
|
|
140
|
+
`)+1;for(;s!==0;)this.onNewLine(this.offset+s),s=this.source.indexOf(`
|
|
141
|
+
`,s)+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 s=Pn(e),n=kt(s);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let s=Pn(e),n=kt(s);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,s){return this.type!=="comment"||this.indent<=s?!1:e.every(n=>n.type==="newline"||n.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())}}};Cl.Parser=Hi});var Pl=_(ms=>{"use strict";h();var Nl=qi(),sm=as(),gs=us(),nm=Lr(),rm=D(),im=zi(),Tl=Qi();function Il(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new im.LineCounter||null,prettyErrors:e}}function om(t,e={}){let{lineCounter:s,prettyErrors:n}=Il(e),r=new Tl.Parser(s?.addNewLine),i=new Nl.Composer(e),o=Array.from(i.compose(r.parse(t)));if(n&&s)for(let a of o)a.errors.forEach(gs.prettifyError(t,s)),a.warnings.forEach(gs.prettifyError(t,s));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}function Ol(t,e={}){let{lineCounter:s,prettyErrors:n}=Il(e),r=new Tl.Parser(s?.addNewLine),i=new Nl.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 gs.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&s&&(o.errors.forEach(gs.prettifyError(t,s)),o.warnings.forEach(gs.prettifyError(t,s))),o}function am(t,e,s){let n;typeof e=="function"?n=e:s===void 0&&e&&typeof e=="object"&&(s=e);let r=Ol(t,s);if(!r)return null;if(r.warnings.forEach(i=>nm.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:n},s))}function cm(t,e,s){let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:s===void 0&&e&&(s=e),typeof s=="string"&&(s=s.length),typeof s=="number"){let r=Math.round(s);s=r<1?void 0:r>8?{indent:8}:{indent:r}}if(t===void 0){let{keepUndefined:r}=s??e??{};if(!r)return}return rm.isDocument(t)&&!n?t.toString(s):new sm.Document(t,n,s).toString(s)}ms.parse=am;ms.parseAllDocuments=om;ms.parseDocument=Ol;ms.stringify=cm});var Rl=_(G=>{"use strict";h();var lm=qi(),um=as(),fm=yi(),Zi=us(),dm=Ft(),De=D(),pm=Le(),hm=Y(),gm=qe(),mm=Me(),ym=In(),wm=Vi(),bm=zi(),km=Qi(),jn=Pl(),jl=Dt();G.Composer=lm.Composer;G.Document=um.Document;G.Schema=fm.Schema;G.YAMLError=Zi.YAMLError;G.YAMLParseError=Zi.YAMLParseError;G.YAMLWarning=Zi.YAMLWarning;G.Alias=dm.Alias;G.isAlias=De.isAlias;G.isCollection=De.isCollection;G.isDocument=De.isDocument;G.isMap=De.isMap;G.isNode=De.isNode;G.isPair=De.isPair;G.isScalar=De.isScalar;G.isSeq=De.isSeq;G.Pair=pm.Pair;G.Scalar=hm.Scalar;G.YAMLMap=gm.YAMLMap;G.YAMLSeq=mm.YAMLSeq;G.CST=ym;G.Lexer=wm.Lexer;G.LineCounter=bm.LineCounter;G.Parser=km.Parser;G.parse=jn.parse;G.parseAllDocuments=jn.parseAllDocuments;G.parseDocument=jn.parseDocument;G.stringify=jn.stringify;G.visit=jl.visit;G.visitAsync=jl.visitAsync});h();import{parseArgs as Vy}from"node:util";h();import{existsSync as uy,readFileSync as fy}from"node:fs";import{join as dy}from"node:path";h();h();h();function jo(t,e,s=n=>n.length>0&&n.length<=100){let n=[];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||n.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)s(a)||n.push(`${e}: "${a}" isn't a field name rows can use.`),Array.isArray(c)?!c.length||!c.every(o)?n.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,p)=>String(l).localeCompare(String(p))):o(c)?i[a]=typeof c=="string"?c.trim():c:n.push(`${e}.${a}: give a value (text, a number, true/false or $me), or a list of them.`);return{rule:n.length?null:i,problems:n}}var Ps="*";h();h();var Cf=/^[a-z][a-z0-9_-]{0,40}$/,Ro=/^[A-Za-z0-9-]{1,64}$/,Nf=new Set(["authorization","proxy-authorization","cookie","host","content-length","content-type","transfer-encoding","connection","user-agent"]),yr=/^[A-Za-z0-9_$@-]+(\.[A-Za-z0-9_$@-]+)*$/,xo=/^[A-Za-z0-9_.[\]-]{1,64}$/,Tf=2e4;function Lo(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 s=e.hostname.toLowerCase();return/^\[|^[0-9.]+$/.test(s)?"should be a hostname, not an IP address":!s.includes(".")||/(^|\.)(localhost|internal|local|localdomain|home\.arpa)$/.test(s)?"should be a public hostname":null}function If(t,e){let s=new URL(t+e);return Of(t,s)?s:null}function Of(t,e){let s=new URL(t),n=s.pathname.replace(/\/$/,"");return e.protocol==="https:"&&e.origin===s.origin&&!e.username&&!e.password&&(e.pathname===n||e.pathname.startsWith(n+"/")||!n)}var Je=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function qo(t,e,s){let n=[],r={base_url:"",resources:{}},i=typeof t.base_url=="string"?Lo(t.base_url.trim()):"is missing";if(i)n.push(`${e}: base_url ${i} (e.g. https://api.hubapi.com).`);else{let a=new URL(t.base_url.trim());(a.search||a.hash)&&n.push(`${e}: base_url shouldn't have a ? or # part; put query settings in each resource's path.`),r.base_url=`${a.origin}${a.pathname.replace(/\/+$/,"")}`}if(s)t.auth!==void 0&&n.push(`${e}: a per-person source signs in with each person's own token; leave auth out.`);else if(t.auth!==void 0){let a=typeof t.auth=="string"?t.auth.trim():"",c=/^header\s+(\S+)$/i.exec(a)?.[1];a==="bearer"||a==="basic"?r.auth=a:c&&Ro.test(c)&&!["cookie","host"].includes(c.toLowerCase())?r.auth=`header ${c}`:n.push(`${e}: auth should be bearer, basic, or header <Name> (e.g. header X-Api-Key).`)}if(t.headers!==void 0)if(!Je(t.headers))n.push(`${e}.headers should map a header name to its value.`);else{let a={};for(let[c,l]of Object.entries(t.headers)){let p=typeof l=="number"?String(l):l;Ro.test(c)?Nf.has(c.toLowerCase())?n.push(`${e}.headers: Kuriko sets ${c} itself${/auth/i.test(c)?" (the credential goes in Secret Manager: name it in secret)":""}.`):typeof p!="string"||/[\r\n]/.test(p)||p.length>500?n.push(`${e}.headers.${c} should be one line of text.`):js(p)||/key|token|secret|auth/i.test(c)?n.push(`${e}.headers.${c} looks like it carries a credential. Put it in Secret Manager and use auth: header ${c}.`):a[c]=p:n.push(`${e}.headers: "${c}" isn't a header name.`)}Object.keys(a).length&&(r.headers=a)}let o=t.resources;if(!Je(o)||!Object.keys(o).length)n.push(`${e}.resources should map a name tools use to the API path that lists it.`);else for(let[a,c]of Object.entries(o)){let l=`${e}.resources.${a}`;Cf.test(a)||n.push(`${e}.resources: "${a}" should be lowercase letters, digits, - and _.`);let p=typeof c=="string"?{path:c}:c;if(!Je(p)){n.push(`${l} should be a path (e.g. /v1/contacts), or settings with a path.`);continue}for(let d of Object.keys(p))["path","method","body","rows","next"].includes(d)||n.push(`${l}: unknown setting "${d}".`);let u={path:""},f=typeof p.path=="string"?p.path.trim():"";if(!/^\/(?!\/)[^\s#\\]*$/.test(f)||f.length>1e3||/(^|\/)\.\.?(\/|\?|$)/.test(f)||/%2e|%2f/i.test(f)?n.push(`${l}: path should be the API path under base_url, starting with / (e.g. /crm/v3/objects/contacts?limit=100).`):r.base_url&&!If(r.base_url,f)?n.push(`${l}: path leaves base_url.`):u.path=f,p.method!==void 0){let d=typeof p.method=="string"?p.method.toUpperCase():"";d!=="GET"&&d!=="POST"?n.push(`${l}: method should be GET or POST (POST for search or GraphQL endpoints; Kuriko only reads).`):d==="POST"&&(u.method="POST")}if(p.body!==void 0&&(u.method!=="POST"?n.push(`${l}: a body needs method: POST.`):Je(p.body)?JSON.stringify(p.body).length>Tf?n.push(`${l}.body is too long.`):u.body=p.body:n.push(`${l}.body should be the JSON object sent.`)),p.rows!==void 0&&(typeof p.rows!="string"||!yr.test(p.rows)?n.push(`${l}: rows should say where the list is in the answer, e.g. results or data.items.`):u.rows=p.rows),p.next!==void 0){let d=Pf(p.next,`${l}.next`,u.method==="POST",n);d&&(u.next=d)}r.resources[a]=u}if(s){let a=t.oauth;if(!Je(a))n.push(`${e}: a per-person source needs oauth (authorize_url, token_url, client_id, scopes).`);else{for(let l of Object.keys(a))["authorize_url","token_url","client_id","scopes","scope_separator","authorize_params","client_auth","account"].includes(l)||n.push(`${e}.oauth: unknown setting "${l}".`);let c={};for(let l of["authorize_url","token_url"]){let p=typeof a[l]=="string"?Lo(a[l].trim()):"is missing";p?n.push(`${e}.oauth: ${l} ${p}.`):c[l]=a[l].trim()}if(typeof a.client_id!="string"||!/^[A-Za-z0-9._~:@-]{4,200}$/.test(a.client_id.trim())?n.push(`${e}.oauth: client_id should be your OAuth app's client ID.`):js(a.client_id.trim())&&/secret/i.test(a.client_id)?n.push(`${e}.oauth: client_id looks like a client secret; that goes in Secret Manager.`):c.client_id=a.client_id.trim(),a.scopes!==void 0){let l=Array.isArray(a.scopes)?a.scopes:typeof a.scopes=="string"?a.scopes.split(/\s+/).filter(Boolean):null;!l||!l.every(p=>typeof p=="string"&&/^[\x21-\x7e]{1,200}$/.test(p)&&!p.includes(","))?n.push(`${e}.oauth: scopes should be a list, e.g. [crm.objects.contacts.read].`):l.length&&(c.scopes=l)}if(a.scope_separator!==void 0&&(a.scope_separator!==" "&&a.scope_separator!==","?n.push(`${e}.oauth: scope_separator should be " " or ",".`):a.scope_separator===","&&(c.scope_separator=",")),a.authorize_params!==void 0){let l=new Set(["client_id","redirect_uri","state","response_type","scope"]);!Je(a.authorize_params)||!Object.entries(a.authorize_params).every(([p,u])=>xo.test(p)&&!l.has(p)&&typeof u=="string"&&u.length<=200)?n.push(`${e}.oauth: authorize_params should map extra settings to text (not client_id, redirect_uri, state, response_type or scope).`):Object.keys(a.authorize_params).length&&(c.authorize_params=a.authorize_params)}a.client_auth!==void 0&&(a.client_auth!=="body"&&a.client_auth!=="basic"?n.push(`${e}.oauth: client_auth should be body or basic.`):a.client_auth==="basic"&&(c.client_auth="basic")),a.account!==void 0&&(typeof a.account!="string"||!yr.test(a.account)?n.push(`${e}.oauth: account should say where the account's email or name is in the token answer, e.g. user.email.`):c.account=a.account),c.authorize_url&&c.token_url&&c.client_id&&(r.oauth=c)}}else t.oauth!==void 0&&n.push(`${e}: oauth is for per-person sources (credentials: per-person).`);return{config:r,problems:n}}function Pf(t,e,s,n){let r=c=>(n.push(`${e}: ${c}`),null);if(t==="link")return"link";if(!Je(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"&&yr.test(t[c]),a=c=>typeof t[c]=="string"&&xo.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&&(!s||!o("body"))?r(s?"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 }.")}h();var ge=[{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"}],Mo=ge.filter(t=>!t.notYet),Ie=["claude-code","claude"],Ko=new Map(ge.map(t=>[t.id,t])),Rs=t=>Ko.get(t);function Do(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 xt=t=>Ko.get(t)?.name??t;var jf="*",lt=class extends Error{name="PolicyFileError";problems;constructor(e){super(`policy.yaml has ${e.length===1?"a problem":`${e.length} problems`}:
|
|
142
|
+
${e.map(s=>` - ${s}`).join(`
|
|
143
|
+
`)}`),this.problems=e}},Rf=new Set(["Viewer","Builder","Admin"]),Bo=new Set(["notion","postgres","bigquery","snowflake","api"]);var Lf=/^[A-Za-z_][A-Za-z0-9_]{0,62}$/,Uo=/^[A-Za-z_][A-Za-z0-9_]{0,254}$/,xf=/^[a-z][a-z0-9-]{4,28}[a-z0-9]$/,qf=/^(?:([a-z][a-z0-9-]{4,28}[a-z0-9])[.:])?([A-Za-z0-9_]{1,1024})$/,Mf=/^[A-Za-z0-9][A-Za-z0-9_.-]{1,254}$/,Kf=/^[A-Za-z0-9_.@$-]{1,255}$/,Ls=/^[A-Za-z_][A-Za-z0-9_$]{0,254}$/,Df=/^[a-z][a-z0-9-]{1,30}$/,Bf=/^[a-z][a-z0-9_-]{0,40}$/,Uf=/^(?:projects\/[a-z][a-z0-9-]{4,28}[a-z0-9]\/secrets\/)?[A-Za-z0-9_-]{1,255}$/,js=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),Gf=t=>{let e=t.split("/").pop();return e.startsWith("kuriko-")&&!e.startsWith("kuriko-connector-")},Ff=new Set(["roles","connectors","access","clients"]);function Go(t){let e=t.trim();return e.toLowerCase()==="everyone"?Ps:e.includes("@")?e.toLowerCase():e}var Mt=t=>t===Ps?"everyone":t,ct=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),qt=t=>[...new Set(t)].sort();function Fo(t,e){let s=[],n={roles:[],connectors:[],grants:[],clients:[]};if(t==null&&(t={}),!ct(t))throw new lt(["The file should be a map with roles, connectors, access and clients."]);for(let u of Object.keys(t))Ff.has(u)||s.push(`Unknown section "${u}" (expected roles, connectors, access, clients).`);let r=t.roles??{};if(!ct(r))s.push("roles should map a group to Admin, Builder or Viewer.");else for(let[u,f]of Object.entries(r)){let d=Go(u);d===Ps?s.push("roles: everyone can't be given a role (roles need a real group)."):typeof f!="string"||!Rf.has(f)?s.push(`roles: ${u} should be Admin, Builder or Viewer, not ${JSON.stringify(f)}.`):n.roles.some(m=>m.group===d)?s.push(`roles: ${u} is listed twice.`):n.roles.push({group:d,role:f})}let i=t.connectors??{},o=new Map,a=new Map,c=new Set;if(!ct(i))s.push("connectors should map an id (e.g. notion) to its settings.");else for(let[u,f]of Object.entries(i)){let d=`connectors.${u}`;if(Df.test(u)||s.push(`${d}: the id should be lowercase letters, digits and dashes.`),!ct(f)){s.push(`${d} should have a name and a kind.`);continue}let m=typeof f.kind=="string"&&Bo.has(f.kind)?f.kind:null;m||s.push(`${d}: kind should be one of ${[...Bo].join(", ")}.`);let g=f.credentials==="per-person";f.credentials!==void 0&&f.credentials!=="shared"&&!g&&s.push(`${d}: credentials should be shared or per-person.`),g&&m!=="notion"&&m!=="api"&&s.push(`${d}: only notion and api sources can be per-person so far.`);let y=new Set(m==="notion"?["name","kind","secret","resources","credentials",...g?["oauth_client_id"]:[]]: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($)||s.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||s.push(`${d}: needs a name.`);let N=null;if(m==="notion"||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":m==="api"?"the API key or token":"the integration token";typeof f.secret!="string"||!Uf.test(f.secret)?s.push(`${d}: secret should name the secret in Secret Manager holding ${$} (e.g. warehouse-readonly, or projects/<project>/secrets/<name>), never the secret itself.`):js(f.secret.split("/").pop())?s.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).`):Gf(f.secret)?s.push(`${d}: ${f.secret} is one of Kuriko's own secrets; a data source needs its own credential.`):N=f.secret}let I={};if(m==="notion"){let $=f.resources??{};if(!ct($))s.push(`${d}.resources should map a name tools use to a Notion data source ID.`);else{for(let[E,O]of Object.entries($))Bf.test(E)||s.push(`${d}.resources: "${E}" should be lowercase letters, digits, - and _.`),(typeof O!="string"||O.trim().length<8)&&s.push(`${d}.resources.${E} should be a Notion data source ID.`);I={resources:Object.fromEntries(Object.entries($).map(([E,O])=>[E,String(O).trim()]).sort(([E],[O])=>E.localeCompare(O)))},o.set(u,new Set(Object.keys($)))}g&&(typeof f.oauth_client_id!="string"||!/^[A-Za-z0-9-]{8,100}$/.test(f.oauth_client_id)?s.push(`${d}: oauth_client_id should be the OAuth client ID of your Notion public integration.`):I.oauthClientId=f.oauth_client_id)}else if(m==="postgres")f.schema!==void 0&&(typeof f.schema!="string"||!f.schema)&&s.push(`${d}.schema should be a schema name.`),I={schema:typeof f.schema=="string"&&f.schema?f.schema:"public"},o.set(u,null),c.add(u);else if(m==="bigquery"){let $=typeof f.dataset=="string"?qf.exec(f.dataset.trim()):null;if(!$)s.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"||!xf.test(f.project)))s.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)s.push(`${d}: dataset says project ${$[1]} but project says ${f.project}; keep one.`);else{let E=$[1]??f.project;I={dataset:$[2],...E?{project:E}:{}}}o.set(u,null),a.set(u,Uo),c.add(u)}else if(m==="snowflake"){let $=(E,O,b,A)=>{let K=f[E]??A;typeof K!="string"||!O.test(K.trim())?s.push(`${d}: ${E} should be ${b}.`):I[E]=K.trim()};$("account",Mf,"your Snowflake account identifier, e.g. acme-analytics (orgname-accountname)"),$("user",Kf,"the Snowflake user Kuriko signs in as, e.g. KURIKO_READER"),$("warehouse",Ls,"the warehouse queries run on, e.g. COMPUTE_WH"),$("database",Ls,"the database tools read, e.g. ANALYTICS"),$("schema",Ls,"a schema in that database, e.g. PUBLIC","PUBLIC"),f.role!==void 0&&$("role",Ls,"a Snowflake role the user has, e.g. KURIKO_READ"),o.set(u,null),a.set(u,Uo),c.add(u)}else if(m==="api"){let $=qo(f,d,g);s.push(...$.problems),I=$.config,o.set(u,new Set(Object.keys($.config.resources))),c.add(u)}S&&m==="bigquery"?n.connectors.push({id:u,name:S,kind:m,config:I,mode:"identity",secretRef:null}):S&&m&&N&&n.connectors.push({id:u,name:S,kind:m,config:I,mode:g?"delegated":"service",secretRef:e(N)})}let l=t.access??[];Array.isArray(l)?l.forEach((u,f)=>{let d=`access[${f+1}]`;if(!ct(u))return void s.push(`${d} should have group, connector, resources and access.`);for(let b of Object.keys(u))["group","connector","resources","access","mask","rows"].includes(b)||s.push(`${d}: unknown setting "${b}".`);let m=typeof u.group=="string"&&u.group.trim()?Go(u.group):null;m||s.push(`${d}: needs a group (a group email, or everyone).`);let g=typeof u.connector=="string"?u.connector:"";o.has(g)||s.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)&&s.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)||s.push(`${d}: ${g} has no resource "${b}" (it has: ${[...S].join(", ")||"none"}).`);let N=a.get(g)??Lf;if(S===null)for(let b of y)b!==jf&&!N.test(b)&&s.push(`${d}: "${b}" isn't a table name (or "*" for every table).`);c.has(g)&&u.access==="write"&&s.push(`${d}: ${g} is read-only in Kuriko; use access: read.`),u.access!=="read"&&u.access!=="write"&&s.push(`${d}: access should be read or write (write includes read).`);let I=u.mask===void 0?[]:Array.isArray(u.mask)&&u.mask.every(b=>typeof b=="string")?u.mask:null;I||s.push(`${d}: mask should be a list of field names.`);let $=u.rows===void 0||u.rows===null?{rule:void 0,problems:[]}:jo(u.rows,`${d}.rows`,S===null?b=>N.test(b):void 0);if(s.push(...$.problems),!m||!g||!y.length||!I||$.rule===null||u.access!=="read"&&u.access!=="write")return;let E=n.grants.filter(b=>b.group===m&&b.connector===g&&b.access===u.access),O=y.filter(b=>E.some(A=>A.resources.includes(b)));if(O.length)return void s.push(`${d}: ${Mt(m)} already has ${u.access} on ${g}: ${O.join(", ")}. A table can be in one ${u.access} grant per group.`);if(E.some(b=>JSON.stringify(b.rows??null)===JSON.stringify($.rule??null)))return void s.push(`${d}: ${Mt(m)} already has ${u.access} on ${g}${$.rule?" with the same rows":""}; put the resources in one grant.`);n.grants.push({group:m,connector:g,resources:qt(y),access:u.access,mask:qt(I),...$.rule?{rows:$.rule}:{}})}):s.push("access should be a list of grants.");let p=t.clients===void 0||t.clients===null?[...Ie]:t.clients;if(Array.isArray(p)?p.forEach((u,f)=>{let d=`clients[${f+1}]`;if(typeof u!="string"||!u.trim())return void s.push(`${d} should be a client's name or its metadata document URL.`);let m=u.trim(),g=Rs(m);if(g?.notYet)return void s.push(`${d}: ${g.name} can't connect to Kuriko yet (${g.notYet}). Leave it commented out for now.`);if(!g&&!Do(m))return void s.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 ${Mo.map(y=>y.id).join(", ")}, or the client's metadata document URL.`);if(n.clients.includes(m))return void s.push(`${d}: ${m} is listed twice.`);n.clients.push(m)}):s.push("clients should be a list, e.g. [claude-code, codex]."),s.length)throw new lt(s);return wr(n)}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 wr(t){let e=s=>(n,r)=>s(n).localeCompare(s(r));return{roles:t.roles.map(({group:s,role:n})=>({group:s,role:n})).sort(e(s=>s.group)),connectors:t.connectors.map(({id:s,name:n,kind:r,mode:i,secretRef:o,config:a})=>({id:s,name:n,kind:r,mode:i,secretRef:o,config:Kt(a)})).sort(e(s=>s.id)),grants:t.grants.map(({group:s,connector:n,resources:r,access:i,mask:o,rows:a})=>({group:s,connector:n,resources:qt(r),access:i,mask:qt(o),...a?{rows:Kt(a)}:{}})).sort(e(Wf)),clients:qt(t.clients??[...Ie])}}var Wf=t=>`${t.connector}\0${t.group}\0${t.access}\0${JSON.stringify(t.rows?Kt(t.rows):null)}`;function Wo(t,e){let s=[],n=a=>typeof a=="string"?a:JSON.stringify(a);for(let a of["name","kind","mode","secretRef"])t[a]!==e[a]&&s.push(`${a} ${n(t[a])} \u2192 ${n(e[a])}`);let r=(a,c="")=>Object.entries(a).flatMap(([l,p])=>p&&typeof p=="object"&&!Array.isArray(p)?r(p,`${c}${l}.`):[[`${c}${l}`,p]]),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))&&s.push(`${a} ${i.has(a)?n(i.get(a)):"(none)"} \u2192 ${o.has(a)?n(o.get(a)):"(none)"}`);return s.length?s:["(settings differ only in form)"]}var ze=(t,e)=>{let s=/^projects\/([^/]+)\/secrets\/(.+)$/.exec(t);return s&&(!e||s[1]===e)?s[2]:t};function xs(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 ${xt(t.client)}`:`people can no longer connect with ${xt(t.client)}`}}h();import{spawn as Yf}from"node:child_process";import{stripVTControlCharacters as Vf}from"node:util";var ee=class extends Error{command;code;stderr;constructor(e,s,n){let r=Vf(n);super(`${e} failed (exit ${s})${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=s,this.stderr=r}get reason(){let e=this.stderr.split(`
|
|
147
|
+
`).map(s=>s.replace(/^[│╷╵\s]+/,"").trim()).filter(Boolean);return e.find(s=>/^error\b/i.test(s))?.replace(/^error:?\s*/i,"")??e[0]??`exit ${this.code}`}},Yo=t=>/invalid_rapt|reauth related error|invalid_grant|Reauthentication (is )?(required|failed)/i.test(t);function L(t,e,s={}){return new Promise((n,r)=>{let i=t==="gcloud"&&!s.inherit?{CLOUDSDK_CORE_DISABLE_PROMPTS:"1"}:{},o=Yf(t,e,{cwd:s.cwd,env:{...process.env,...i,...s.env},stdio:s.inherit?"inherit":[s.input===void 0?"ignore":"pipe","pipe","pipe"]});s.input!==void 0&&o.stdin?.end(s.input);let a="",c="";o.stdout?.on("data",l=>(a+=l,s.tee&&process.stdout.write(l))),o.stderr?.on("data",l=>(c+=l,s.tee&&process.stderr.write(l))),o.on("error",l=>r(new ee(t,null,l.message))),o.on("close",l=>l===0?n(a):r(new ee(`${t} ${e[0]??""}`.trim(),l,c)))})}async function Q(t,e,s={}){return JSON.parse(await L(t,e,s))}async function He(t,e="--version"){try{return await L(t,[e]),!0}catch{return!1}}h();var dr=Af(Rl(),1);import{existsSync as Ao,readFileSync as Eo,writeFileSync as Ju}from"node:fs";import{join as _o}from"node:path";h();var ws="kuriko-idp-client-secret",ys={ring:"kuriko",key:"user-tokens"};var Ll=["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"],xl=["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]$/,Xi=t=>$m.test(t),ql=t=>/^[a-z]+-[a-z]+\d+$/.test(t),Ml=t=>/^\d+-[a-z0-9]+\.apps\.googleusercontent\.com$/.test(t),Rn=t=>/^[^\s@'"\\]+@[^\s@'"\\]+\.[^\s@'"\\]+$/.test(t);function Kl(t){let e=new Set(t);for(let s=0;;s++){let n=s===0?"kuriko":`kuriko-${s}`;if(!e.has(n))return n}}function Dl(t){let e=/^(.*?)-(\d+)$/.exec(t);return e?`${e[1]}-${Number(e[2])+1}`:`${t}-1`}function Bl(t){return/(failed to create instance|google_sql_database_instance)[\s\S]{0,400}(instanceAlreadyExists|already exists|reuse the name)/i.test(t)}function Ul(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 nt=(t,e)=>{let s=`https://kuriko-web-${e}.${t.region}.run.app`;return{web:s,mcp:`https://kuriko-gateway-${e}.${t.region}.run.app/mcp`,redirect:`${s}/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 Gl(t,e,s,n=null,r=!!n){let i=n&&r?`${t.region}-docker.pkg.dev/${t.project}/kuriko-releases/${n.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(s)}
|
|
151
151
|
prefix = "kuriko"
|
|
152
152
|
}
|
|
153
153
|
}
|
|
154
154
|
|
|
155
155
|
variable "version_tag" { type = string }
|
|
156
156
|
variable "idp_client_id" { type = string }
|
|
157
|
-
variable "db_instance_name" { type = string }${
|
|
157
|
+
variable "db_instance_name" { type = string }${n?`
|
|
158
158
|
variable "release_token_version" { type = string }`:""}
|
|
159
159
|
# Only \`kuriko destroy\` turns this off, for the one apply just before it deletes everything.
|
|
160
160
|
variable "deletion_protection" {
|
|
@@ -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
|
+
}${n?`
|
|
186
186
|
release_registry = {
|
|
187
|
-
upstream = ${
|
|
188
|
-
username = ${
|
|
189
|
-
token_secret_name = ${
|
|
187
|
+
upstream = ${X(n.upstream)}
|
|
188
|
+
username = ${X(n.username)}
|
|
189
|
+
token_secret_name = ${X(n.tokenSecret)}
|
|
190
190
|
token_version = var.release_token_version
|
|
191
191
|
}`:""}
|
|
192
192
|
}
|
|
@@ -196,72 +196,136 @@ 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 Fl(t,e,s=null){return[`version_tag = ${X(e)}`,`idp_client_id = ${X(t.idpClientId??"")}`,`db_instance_name = ${X(t.dbInstanceName)}`,...s?[`release_token_version = ${X(s.tokenVersion)}`]:[],""].join(`
|
|
201
|
+
`)}var Ln="module.kuriko.google_sql_database_instance.kuriko",bs={gateway:"kuriko-gateway",web:"kuriko-web",builder:"kuriko-builder",tools:"kuriko-tools",events:"kuriko-events"};function Wl(t,e){let s=`projects/${t.project}/locations/${t.region}/keyRings/${ys.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(s)}
|
|
203
204
|
}`]:[],...e.key?[`import {
|
|
204
205
|
to = module.kuriko.google_kms_crypto_key.user_tokens
|
|
205
|
-
id = ${
|
|
206
|
+
id = ${X(`${s}/cryptoKeys/${ys.key}`)}
|
|
206
207
|
}`]:[],...e.sqlInstance?[`import {
|
|
207
|
-
to = ${
|
|
208
|
-
id = ${
|
|
209
|
-
}`]:[]].
|
|
208
|
+
to = ${Ln}
|
|
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/${bs[r]}@${t.project}.iam.gserviceaccount.com`)}
|
|
213
|
+
}`)].join(`
|
|
210
214
|
|
|
211
215
|
`)+`
|
|
212
|
-
`}function
|
|
213
|
-
${C("\u2192")} ${
|
|
214
|
-
`),i.trim()}finally{
|
|
215
|
-
`)},l=f=>{let
|
|
216
|
-
`),
|
|
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
|
-
${C("\u270B")} ${C(
|
|
224
|
-
${e.map(
|
|
225
|
-
`)}`)}var
|
|
226
|
-
gcloud ${l.join(" ")}`)}}async function
|
|
227
|
-
|
|
228
|
-
${s.map(r
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
`)
|
|
233
|
-
${i.
|
|
234
|
-
`)}`);return i
|
|
235
|
-
`)
|
|
236
|
-
|
|
237
|
-
`)
|
|
216
|
+
`}function xn(t){let e=[];for(let s of t.resource_changes??[]){let n=s.change.actions,r=n.includes("delete")&&n.includes("create")?"replace":n[0]==="create"||n[0]==="update"||n[0]==="delete"?n[0]:null;r&&e.push({address:s.address.replace(/^module\.kuriko\./,""),action:r})}return e}var qn=new Set(["module.kuriko.google_project_iam_member.gateway_connector_secrets"]);function Yl(t){return(t.resource_changes??[]).filter(e=>e.change.actions.includes("delete")&&!(qn.has(e.address)&&e.change.actions.length===1)).map(e=>e.address)}var Sm={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 Vl(t,e,s=6){let n=Sm[e],r=i=>{let o=`${i.email.split("@")[0]} ${i.name}`.toLowerCase().split(/[^a-z0-9]+/),a=n.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,s).map(i=>i.g)}var Jl=(t,e)=>{let s=e.trim().toLowerCase();return t.filter(n=>n.email.includes(s)||n.name.toLowerCase().includes(s))};h();h();import{emitKeypressEvents as Hl}from"node:readline";import{createInterface as Ql}from"node:readline/promises";import{Writable as vm}from"node:stream";import{stripVTControlCharacters as zl,styleText as At}from"node:util";var C=t=>At("bold",t),v=t=>At("dim",t),we=t=>At("red",t),Be=t=>At("green",t),rt=t=>At("yellow",t),St=t=>At("cyan",t),Zl="\u280B\u2819\u2839\u2838\u283C\u2834\u2826\u2827\u2807\u280F",$t=null,to=null,eo=null,so=0,no=!1,ro=!1,io=()=>process.stdout.isTTY===!0;function Mn(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 Am(){let t=[$t&&`${$t.text} ${v(Mn($t.start))}`,to?.()&&v(to())].filter(n=>!!n);if(!t.length)return null;let e=(process.stdout.columns||80)-1,s=`${St(Zl[so])} ${t.join(v(" \xB7 "))}`;return zl(s).length<=e?s:zl(s).slice(0,e)}function Kn(){io()&&ro&&process.stdout.write("\r\x1B[2K"),ro=!1}function vt(){if(!io()||no)return;Kn();let t=Am();t&&(process.stdout.write(t),ro=!0)}function Xl(){eo||!io()||(eo=setInterval(()=>{so=(so+1)%Zl.length,vt()},100),eo.unref())}function ks(t){Kn(),console.log(t),vt()}async function j(t,e){let s=$t;$t={text:t,start:Date.now()},Xl(),vt();try{return await e()}finally{$t=s,Kn(),vt()}}function oo(t){to=t,Xl(),vt()}async function Et(t){no=!0,Kn();try{return await t()}finally{no=!1,vt()}}var k=(t="")=>ks(t),M=t=>ks(`
|
|
217
|
+
${C("\u2192")} ${t}`),T=t=>ks(` ${Be("\u2713")} ${t}`),x=t=>ks(` ${rt("!")} ${t}`);function Dn(){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 Dn(),Et(async()=>{let s=Ql({input:process.stdin,output:process.stdout});try{return(await s.question(e?`${t} ${v(`[${e}]`)} `:`${t} `)).trim()||e||""}finally{s.close()}})}async function z(t,e=!1){let s=(await V(`${t} ${v(e?"[Y/n]":"[y/N]")}`)).toLowerCase();return s?s==="y"||s==="yes":e}async function Bn(t){return Dn(),Et(()=>Em(t))}async function Em(t){let e=!1,s=new vm({write(r,i,o){e||process.stdout.write(r),o()}}),n=Ql({input:process.stdin,output:s,terminal:!0});try{let r=n.question(`${t} `);e=!0;let i=await r;return process.stdout.write(`
|
|
218
|
+
`),i.trim()}finally{n.close()}}async function ie(t,e){Dn();let s=e.map((n,r)=>n.disabled?-1:r).filter(n=>n>=0);if(!s.length)throw new Error(`Nothing to choose for: ${t}`);return Et(()=>new Promise(n=>{let r=process.stdin,i=r.isRaw,o=s[0],a=(f,d)=>{let m=f.disabled?v(f.label):d===o?C(f.label):f.label;return`${d===o?St(" \u203A"):" "} ${m}${f.hint?` ${v(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=s.indexOf(o);o=s[(d+f+s.length)%s.length],c(!1)},p=()=>{r.off("keypress",u),r.setRawMode(i),r.pause(),process.stdout.write(`\x1B[${e.length+1}A\r\x1B[J${t} ${St(e[o].label)}
|
|
220
|
+
`),n(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"?p():f&&/^[1-9]$/.test(f)&&s.includes(Number(f)-1)&&(o=Number(f)-1,c(!1))};process.stdout.write(`${t} ${v("(\u2191/\u2193, Enter)")}
|
|
222
|
+
`),c(!0),Hl(r),r.setRawMode(!0),r.resume(),r.on("keypress",u)}))}async function Un(t,e,s){Dn();let n=e.map((r,i)=>r.disabled?-1:i).filter(r=>r>=0);if(!n.length)throw new Error(`Nothing to choose for: ${t}`);return Et(()=>new Promise(r=>{let i=process.stdin,o=i.isRaw,a=e.map(m=>!m.disabled&&s(m.value)),c=n[0],l=(m,g)=>m.disabled?` ${v(`\u25CB ${m.label}${m.hint?` ${m.hint}`:""}`)}`:`${g===c?St(" \u203A"):" "} ${a[g]?Be("\u25C9"):v("\u25CB")} ${g===c?C(m.label):m.label}${m.hint?` ${v(m.hint)}`:""}`,p=m=>c=n[(n.indexOf(c)+m+n.length)%n.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} ${St(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")p(-1);else if(g.name==="down"||g.name==="j"||g.name==="tab")p(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} ${v("(\u2191/\u2193, Space to tick, Enter)")}
|
|
226
|
+
`),u(!0),Hl(i),i.setRawMode(!0),i.resume(),i.on("keypress",d)}))}async function ao(t,e){let s=e.filter(n=>!n.disabled);return s.length===1&&e.length===1?(k(`${t} ${St(s[0].label)}`),s[0].value):ie(t,e)}function Ae(t,e){ks(`
|
|
227
|
+
${C("\u270B")} ${C(t)}
|
|
228
|
+
${e.map(s=>s?` ${s}`:"").join(`
|
|
229
|
+
`)}`)}var $s=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}},_t=async()=>(await L("gcloud",["config","get","account"])).trim();async function te(t={}){let e=async s=>{try{return await L("gcloud",s),null}catch(n){return n instanceof ee&&Yo(n.stderr)?"expired":"missing"}};for(let s=!1;;s=!0){let[n,r]=await Promise.all([t.terraformOnly?null:e(["auth","print-access-token"]),e(["auth","application-default","print-access-token"])]);if(!n&&!r)return;let i=await _t().catch(()=>""),c=`${[n&&"gcloud",r&&"Terraform"].filter(Boolean).join(" and ")}${n==="expired"||r==="expired"?`'s Google sign-in${n&&r?"s have":" has"} expired`:` ${n&&r?"aren't":"isn't"} signed in to Google`}`,l=n?["auth","login",...i?[i]:[],"--force",...r?["--update-adc"]:[]]:["auth","application-default","login"];if(!s&&process.stdin.isTTY&&(x(`${c}.`),await z(` Sign in${i?` as ${i}`:""} now? (opens your browser)`,!0))){await Et(()=>L("gcloud",l,{inherit:!0}));continue}throw new Error(`${c}. Run:
|
|
230
|
+
gcloud ${l.join(" ")}`)}}async function Ct(){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 eu(){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 Ue(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 tu=(t,e)=>L("gcloud",["projects","create",t,`--organization=${e}`,"--name=Kuriko"]);async function su(t){return(await Q("gcloud",["billing","projects","describe",t,"--format=json"])).billingEnabled===!0}var nu=(t,e)=>L("gcloud",["billing","projects","link",t,`--billing-account=${e}`]);async function ru(t){try{return(await L("gcloud",["billing","projects","list",`--billing-account=${t}`,"--format=value(projectId)"])).split(`
|
|
231
|
+
`).map(s=>s.trim()).filter(Boolean)}catch{return null}}var iu=t=>t instanceof ee&&/billing quota exceeded|QuotaFailure/i.test(t.stderr),Fn=(t,e)=>L("gcloud",["services","enable",...e,`--project=${t}`]);async function ou(t,e,s){return await $s(["storage","buckets","describe",`gs://${t}`,"--format=json"])?"exists":(await L("gcloud",["storage","buckets","create",`gs://${t}`,`--project=${e}`,`--location=${s}`,"--uniform-bucket-level-access","--public-access-prevention"]),await L("gcloud",["storage","buckets","update",`gs://${t}`,"--versioning"]),"created")}async function au(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 cu(t,e,s,n){let r=[`--location=${e}`,`--project=${t}`,"--format=json"],i=await $s(["kms","keyrings","describe",s,...r]);return{ring:i,key:i&&await $s(["kms","keys","describe",n,`--keyring=${s}`,...r])}}async function lu(t,e){let s=(await L("gcloud",["iam","service-accounts","list",`--project=${t}`,"--format=value(email)"])).split(`
|
|
232
|
+
`).map(n=>n.trim());return e.filter(n=>s.includes(`${n}@${t}.iam.gserviceaccount.com`))}async function uu(t){return $s(["artifacts","docker","images","describe",t,"--format=json"])}async function Ss(t,e){return await $s(["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 Nt(t,e,s){await Ss(t,e)===null?await L("gcloud",["secrets","create",e,`--project=${t}`,"--replication-policy=automatic","--labels=managed-by=kuriko-security-team","--data-file=-"],{input:s}):await L("gcloud",["secrets","versions","add",e,`--project=${t}`,"--data-file=-"],{input:s})}async function fu(t,e,s){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:s,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 Gn(t,e,s){let n=(await L("gcloud",["auth","print-access-token"])).trim(),r=new URL(`https://cloudidentity.googleapis.com/v1/${e}`);for(let[o,a]of Object.entries(s))r.searchParams.set(o,a);let i=await fetch(r,{headers:{authorization:`Bearer ${n}`,"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 du(t,e,s,n){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(s))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(n)});return{status:o.status,text:await o.text()}}async function pu(t,e){let s=await du(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(s.status===409)return"exists";if(s.status>=300)throw new Error(`Couldn't create ${e.email} (${s.status}): ${s.text.slice(0,300)}`);return"created"}async function Wn(t,e){let s=[],n="";do{let r=await Gn(t,"groups",{parent:`customers/${e}`,view:"BASIC",pageSize:"500",...n?{pageToken:n}:{}});if(!r)return s.length?s:null;for(let i of r.groups??[])i.groupKey?.id&&s.push({email:i.groupKey.id.toLowerCase(),name:i.displayName??"",description:i.description??""});n=r.nextPageToken??""}while(n&&s.length<2e4);return s.sort((r,i)=>r.email.localeCompare(i.email))}async function co(t,e,s){let n=await Gn(t,"groups:lookup",{"groupKey.id":e});if(!n?.name)throw new Error(`Group ${e} not found`);let r=await du(t,`${n.name}/memberships`,{},{preferredMemberKey:{id:s},roles:[{name:"MEMBER"}]});if(r.status===409)return"exists";if(r.status>=300)throw new Error(`Couldn't add ${s} to ${e} (${r.status}): ${r.text.slice(0,300)}`);return"added"}async function Yn(t,e,s){let n=await Gn(t,"groups:lookup",{"groupKey.id":e});if(!n?.name)return{exists:!1,isMember:!1};let r="";do{let i=await Gn(t,`${n.name}/memberships:searchTransitiveMemberships`,{pageSize:"500",...r?{pageToken:r}:{}});if(i?.memberships?.some(o=>o.preferredMemberKey?.some(a=>a.id?.toLowerCase()===s.toLowerCase())))return{exists:!0,isMember:!0};r=i?.nextPageToken??""}while(r);return{exists:!0,isMember:!1}}async function Tt(t,e,s,n){let r=[`--project=${t}`,`--region=${e}`],o=(await Q("gcloud",["run","jobs","execute",s,...r,"--async","--format=json",...n?[`--args=^;;^${n.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),p=l.map(u=>/Container called exit\((\d+)\)/.exec(u)).find(Boolean);if(p)return{code:Number(p[1]),logs:l.filter(u=>!/Container called exit/.test(u))};await new Promise(u=>setTimeout(u,5e3))}return{code:null,logs:[]}}async function hu(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 gu(t,e){return(await L("gcloud",["secrets","versions","access","latest",`--secret=${e}`,`--project=${t}`])).trim()}async function lo(t,e,s=18e4){let n=(await L("gcloud",["auth","print-access-token"])).trim(),r=Date.now()+s;for(;;){let i=await fetch(`https://serviceusage.googleapis.com/v1beta1/projects/${t}/services/${e}:generateServiceIdentity`,{method:"POST",headers:{authorization:`Bearer ${n}`,"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 mu(t,e,s,n,r){try{let i=`${t.owner}/${n}`,o=Buffer.from(`${e}:${s}`).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 uo="roles/secretmanager.secretAccessor",Vn=t=>{let e=/^projects\/([^/]+)\/secrets\/([^/]+)$/.exec(t);if(!e)throw new Error(`Not a secret reference: ${t}`);return[e[1],e[2]]};async function vs(t){let[e,s]=Vn(t);return L("gcloud",["secrets","describe",s,`--project=${e}`,"--format=value(name)"]).then(()=>!0,()=>!1)}async function As(t,e){let[s,n]=Vn(t);return!!(await Q("gcloud",["secrets","get-iam-policy",n,`--project=${s}`,"--format=json"])).bindings?.some(i=>i.role===uo&&!i.condition&&i.members?.includes(e))}async function fo(t,e){let[s,n]=Vn(t);await L("gcloud",["secrets","add-iam-policy-binding",n,`--project=${s}`,`--member=${e}`,`--role=${uo}`,"--condition=None","--format=none"])}async function yu(t,e){let[s,n]=Vn(t);await vs(t)&&await As(t,e)&&await L("gcloud",["secrets","remove-iam-policy-binding",n,`--project=${s}`,`--member=${e}`,`--role=${uo}`,"--condition=None","--format=none"])}async function wu(t){let e=(await L("gcloud",["auth","print-access-token"])).trim(),s=await fetch(`https://bigquery.googleapis.com/bigquery/v2/${t}`,{headers:{authorization:`Bearer ${e}`}});return{status:s.status,body:await s.json().catch(()=>({}))}}async function bu(t){let e=await wu(`projects/${t}/datasets?maxResults=1000`).catch(()=>null);return!e||e.status!==200?null:(e.body.datasets??[]).map(s=>({id:s.datasetReference.datasetId,location:s.location}))}var _m=new Set(["READER","WRITER","OWNER","roles/bigquery.dataViewer","roles/bigquery.dataEditor","roles/bigquery.dataOwner","roles/bigquery.admin"]),Cm=new Set(["roles/bigquery.dataViewer","roles/bigquery.dataEditor","roles/bigquery.dataOwner","roles/bigquery.admin","roles/viewer","roles/editor","roles/owner"]);async function ku(t,e,s){let n=`serviceAccount:${s}`,r=await wu(`projects/${t}/datasets/${e}`);if(r.status===404)return"missing";if(r.status===200){let o=r.body.access??[],a=c=>c.userByEmail?.toLowerCase()===s.toLowerCase()||c.iamMember===n||c.specialGroup==="allAuthenticatedUsers"||c.iamMember==="allAuthenticatedUsers"||c.iamMember==="allUsers";if(o.some(c=>a(c)&&_m.has(c.role??"")))return"readable"}let i=await Q("gcloud",["projects","get-iam-policy",t,"--format=json"]).catch(()=>null);return i?.bindings?.some(o=>Cm.has(o.role)&&!o.condition&&o.members?.includes(n))?"readable":r.status===200&&i?"not-readable":"unknown"}h();import{basename as Cu,relative as Pm,resolve as Nu}from"node:path";h();import{existsSync as Jn,readdirSync as Nm,readFileSync as Hn}from"node:fs";import{homedir as Tm}from"node:os";import{dirname as po,join as Ee,relative as Im,resolve as zn}from"node:path";import{fileURLToPath as Om}from"node:url";var H=zn(Om(new URL("../../..",import.meta.url))),Ot="kuriko-installs.json";function oe(t=process.cwd(),e=process.env){for(let s=zn(t);;s=po(s)){if(Jn(Ee(s,Ot)))return s;if(po(s)===s)break}for(let s of[e.KURIKO_INSTALLS,Ee(po(H),"kuriko-installs")])if(s&&Jn(Ee(s,Ot)))return zn(s);return null}var Qn=`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 Ge(t=process.cwd()){let e=oe(t);if(!e)throw new Error(Qn);return e}function Es(t,e=process.cwd(),s=oe(e)){if(t){let r=[zn(e,t),s&&Ee(s,t)].find(i=>!!i&&ho(i));if(!r)throw new Error(`No Kuriko install at ${t}. Run kuriko list to see them.`);return r}let n=it(e,s);if(n.length===1)return n[0];throw n.length>1?new Error(`Several installs; choose one with --dir:
|
|
234
|
+
${n.map(r=>` ${r}`).join(`
|
|
235
|
+
`)}`):new Error(s?"No Kuriko installs yet. Start one with: kuriko install":Qn)}function it(t=process.cwd(),e=oe(t)){return ho(t)?[t]:!e||!Jn(e)?[]:Nm(e).sort().map(s=>Ee(e,s)).filter(ho)}function B(t,e=process.cwd()){let s=Im(e,t);if(s&&!s.startsWith(".."))return s;let n=Tm();return t.startsWith(n)?`~${t.slice(n.length)}`:t}function $u(t){let e=Hn(Ee(t,"main.tf"),"utf8"),s=n=>new RegExp(`^\\s*${n}\\s*=\\s*"([^"]+)"`,"m").exec(e)?.[1]??null;return{project:s("project_id"),region:s("region")}}var Su=t=>/requested project was not found|project .* (was )?not found|has been deleted|DELETE_REQUESTED/i.test(t);function vu(t){let e=t.filter(s=>s&&!/(^|\.)data\./.test(s));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 ho(t){let e=Ee(t,"main.tf");return Jn(e)&&/module\s+"kuriko"/.test(Hn(e,"utf8"))}function Au(t){let e=Hn(Ee(t,"main.tf"),"utf8");return/variable\s+"deletion_protection"/.test(e)&&/deletion_protection\s*=\s*var\.deletion_protection/.test(e)}function Eu(t){try{let e=JSON.parse(Hn(Ee(t,".terraform","terraform.tfstate"),"utf8"));return e?.backend?.type==="gcs"?`gs://${e.backend.config.bucket}/${e.backend.config.prefix??""}`:null}catch{return null}}function _u(t){let e=t.values?.root_module;return[...e?.resources??[],...(e?.child_modules??[]).flatMap(s=>s.resources??[])]}var le=(t,e)=>L("git",["-C",t,...e]);async function Tu(t){try{return(await le(t,["rev-parse","--show-toplevel"])).trim()}catch{return null}}async function jm(t){return(await le(t,["rev-parse","--abbrev-ref","HEAD"]).catch(()=>"HEAD")).trim()}async function Iu(t){try{return(await le(t,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"])).trim()}catch{return null}}async function be(t){let e=await Tu(t);if(!e)return;let s=await Iu(e);if(!s)return;await j("Checking the installs repo is up to date",()=>le(e,["fetch","--quiet"]));let n=Number((await le(e,["rev-list","--count","HEAD..@{u}"])).trim());if(n>0)throw new Error(`The installs repo is ${n} commit${n===1?"":"s"} behind ${s}. Pull first:
|
|
236
|
+
git -C ${B(e)} pull`)}async function Fe(t,e,s={}){let n=await Tu(t[0]);if(!n){let l=oe(t[0])??t[0];x(`${B(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: ${C(`git -C ${B(l)} init`)}, then ${C("git remote add origin <url>")} and push.`);return}let r=oe(t[0]),i=!!r&&Nu(r)!==Nu(n),o=t.map(l=>Pm(n,l)||".");if(await le(n,s.remove?["rm","-r","-q","--ignore-unmatch","--",...o]:["add","-A","--",...o]),!(await le(n,["diff","--cached","--name-only","--",...o])).trim())return;let c=i?null:await Iu(n);if(!await z(`
|
|
237
|
+
Commit this to ${i?`${Cu(n)} (on ${await jm(n)})`:"the installs repo"}${c?` and push to ${c}`:""}?`,!0)){x(`Left uncommitted in ${B(n)}. Commit it so others running Kuriko see the change.`);return}await le(n,["commit","-q","-m",e,"--",...o]),c?(await j("Pushing",()=>le(n,["push","-q"])),T(`Committed and pushed: ${e}`)):i?(T(`Committed: ${e}`),k(` Push it and open a pull request as you usually would, so it's reviewed with the rest of ${Cu(n)}.`)):(T(`Committed: ${e}`),k(` (no remote to push to; add one so others can pull it: ${C(`git -C ${B(n)} remote add origin <url>`)})`))}async function Ou(t,e,s){let n=i=>i.replace(/-dirty-.*$/,"");if(n(e)===n(s))return"same";let r=async(i,o)=>{try{return await le(t,["merge-base","--is-ancestor",n(i),n(o)]),!0}catch{return!1}};return await r(e,s)?"forward":await r(s,e)?"backward":await go(t,e,s)?"forward":"unknown"}async function go(t,e,s){let n=r=>r.replace(/-dirty-.*$/,"");if(e!==n(e))return null;try{let r=(await le(t,["rev-parse",`${n(e)}^{tree}`])).trim(),i=(await le(t,["log","--format=%H %T","-n","1000",n(s)])).split(`
|
|
238
|
+
`).find(o=>o.endsWith(` ${r}`));return i?i.split(" ")[0].slice(0,e.length):null}catch{return null}}h();import{existsSync as Rm}from"node:fs";import{basename as Lm,join as xm}from"node:path";var Zn={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 qm(t){let{project:e,region:s}=$u(t),n={dir:t,project:e??Lm(t),region:s??"?",status:"unknown"};if(!Rm(xm(t,".terraform")))return{...n,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))]);n.status=vu(r.split(`
|
|
239
|
+
`)),n.status==="installed"&&(n.web=String(i.web_url?.value??""),n.mcp=String(i.mcp_url?.value??""))}catch(r){let i=r instanceof ee?r.reason:String(r);if(Su(i))return{...n,status:"gone",detail:`Delete the leftover config when you're done with it: rm -r ${B(t)}`};n.detail=`Couldn't read its state: ${i}`}return n}var _s=t=>j(`Reading ${t.length} install${t.length===1?"":"s"}`,()=>Promise.all(t.map(qm)));async function We(t,e,s,n={}){if(t)return Es(t);let r=it();if(!r.length)return Es(void 0);await te({terraformOnly:!0});let i=await _s(r);if(!i.filter(a=>s.includes(a.status)).length)throw new Error(`None of your installs can be used for this:
|
|
240
|
+
${i.map(a=>` ${a.project}: ${Zn[a.status].text}`).join(`
|
|
241
|
+
`)}`);return i.length===1?i[0].dir:ie(e,i.map(a=>{let c=Zn[a.status],l=s.includes(a.status);return{label:a.project,value:a.dir,disabled:!l,hint:`${a.region} ${c.mark} ${c.text}${!l&&n[a.status]?`: ${n[a.status]}`:""}`}}))}h();import{cpSync as Lu,existsSync as xu,mkdtempSync as Fm,readFileSync as er,rmSync as qu,writeFileSync as tr}from"node:fs";import{tmpdir as Wm}from"node:os";import{join as _e}from"node:path";h();import{cpSync as Mm,existsSync as Km,mkdirSync as Dm,rmSync as Bm}from"node:fs";import{join as yo,relative as Um}from"node:path";import{fileURLToPath as Gm}from"node:url";var W=typeof w>"u"?null:w,Pu=process.env.KURIKO_REGISTRY_HOST||"registry.kuriko.dev",ae={upstream:`https://${Pu}`,host:Pu,owner:"usekuriko",username:"kuriko"},ke="kuriko-release-token",mo=W?Gm(new URL("./module",import.meta.url)):yo(H,"infra/terraform/gcp"),Xn=".kuriko/module";function ju(t){if(!W)return Um(t,mo);let e=yo(t,Xn);if(Bm(e,{recursive:!0,force:!0}),Dm(e,{recursive:!0}),Mm(mo,e,{recursive:!0,filter:s=>!/[/\\]\.terraform([/\\]|$)/.test(s)}),!Km(yo(e,"main.tf")))throw new Error(`The Terraform module wasn't found in this package (${mo}).`);return`./${Xn}`}var ot=t=>/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(t);function Ru(t,e){let s=i=>{let[o,a]=i.split("-",2);return{nums:o.split(".").map(Number),pre:a??null}},n=s(t),r=s(e);for(let i=0;i<3;i++)if(n.nums[i]!==r.nums[i])return n.nums[i]-r.nums[i];return n.pre===r.pre?0:n.pre===null?1:r.pre===null||n.pre<r.pre?-1:1}var Ye="kuriko.json";function pe(t,e){tr(_e(t,Ye),JSON.stringify(e,null,2)+`
|
|
242
|
+
`)}function Pt(t){try{return JSON.parse(er(_e(t,Ye),"utf8"))}catch{throw new Error(`${t} has no ${Ye}, so it wasn't made by kuriko install. Upgrade it by hand (terraform apply).`)}}var wo=null,Cs=t=>wo=t;function Mu(t,e){if(!e.releaseUsername)return null;let s=/^release_token_version\s*=\s*"([^"]+)"/m.exec(er(_e(t,"terraform.tfvars"),"utf8"))?.[1];return s?{upstream:ae.upstream,owner:ae.owner,username:e.releaseUsername,tokenSecret:ke,tokenVersion:s}:null}async function sr(t){await j("Setting up deploy events",async()=>{await Fn(t.project,["pubsub.googleapis.com"]),await lo(t.project,"pubsub.googleapis.com")})}function jt(t,e,s){tr(_e(t,"terraform.tfvars"),Fl(e,s,wo))}function nr(t,e){tr(_e(t,"main.tf"),Gl(e,ju(t),`${e.project}-tfstate`,wo,!!W))}function Ku(t){try{return/^version_tag\s*=\s*"([^"]+)"/m.exec(er(_e(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 rr(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 Du(t,e){let s=n=>n.replace(/-dirty-.*$/,"");try{return(await L("git",["log","--oneline","--no-decorate",`${s(t)}..${s(e)}`],{cwd:H})).split(`
|
|
244
|
+
`).filter(Boolean)}catch{return[]}}async function bo(t,e,s){let n=`.kuriko-${e}.plan`;await L("terraform",["plan","-input=false",...(s??[]).map(o=>`-target=${o}`),`-out=${n}`],{cwd:t});let r=await Q("terraform",["show","-json",n],{cwd:t}),i=Yl(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:
|
|
247
|
+
Nothing was changed.`);return{file:n,plan:r}}async function ir(t,e,s){let{file:n,plan:r}=await bo(t,e,s);xn(r).length&&await L("terraform",["apply","-input=false",n],{cwd:t})}async function or(t,e,s){for(let n=1;;n++)try{return await ir(t,e,s)}catch(r){if(!(r instanceof ee&&Ul(r.stderr))||n>=8)throw r;await new Promise(i=>setTimeout(i,2e4))}}async function ar(t,e,s,n){let r=await j(`${n}, in the cloud`,()=>Tt(t.project,t.region,e,s));if(r.code!==0)throw new Error(`${n} failed in the cloud:
|
|
241
248
|
${r.logs.slice(-10).map(i=>` ${i}`).join(`
|
|
242
|
-
`)}`);T(
|
|
243
|
-
Access key (hidden as you type or paste):`)).trim();if(!o)continue;if(!/^kuriko_[0-9a-f]{64}$/.test(o)){
|
|
249
|
+
`)}`);T(n)}var Ym=[["gateway","apps/gateway/Dockerfile",null],["web","apps/web/Dockerfile",null],["web-migrate","apps/web/Dockerfile","migrate"]];async function cr(t,e,s){await L("gcloud",["auth","configure-docker",`${t}-docker.pkg.dev`,"--quiet"]);for(let[n,r,i]of Ym){let o=`${e}/${n}:${s}`;if(await uu(o)){T(`${n} (already pushed)`);continue}await j(`Building and pushing ${n}`,()=>L("docker",["buildx","build","--platform","linux/amd64","-f",r,...i?["--target",i]:[],"-t",o,"--push","."],{cwd:H})),T(n)}}async function lr(t,e){let s=o=>j("Checking access to Kuriko's images",()=>mu(ae,ae.username,o,"gateway",e)),n=await Ss(t.project,ke),r=!1;if(n&&t.releaseUsername===ae.username){let o=await s(await gu(t.project,ke));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 n&&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)T(`Kuriko's images ${e}: access checked`);else for(Ae("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 ${C("kuriko_")} followed by 64 letters and digits.`,"",`It goes straight into this project's Secret Manager (${ke}), 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 Bn(`
|
|
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 s(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 j("Storing the access key",()=>Nt(t.project,ke,o)),t.releaseUsername=ae.username,T(`Access key works and is stored in Secret Manager (${ke})`);break}await j("Setting up Artifact Registry's service account",()=>lo(t.project,"artifactregistry.googleapis.com"));let i=await hu(t.project,ke);if(!i)throw new Error(`${ke} has no enabled version.`);return{upstream:ae.upstream,owner:ae.owner,username:t.releaseUsername,tokenSecret:ke,tokenVersion:i}}function Bu(t){let e=["main.tf","terraform.tfvars",Ye].map(i=>_e(t,i)),s=e.map(i=>xu(i)?er(i):null),n=_e(t,Xn),r=xu(n)?Fm(_e(Wm(),"kuriko-module-")):null;return r&&Lu(n,r,{recursive:!0}),()=>{e.forEach((i,o)=>s[o]?tr(i,s[o]):qu(i,{force:!0})),qu(n,{recursive:!0,force:!0}),r&&Lu(r,n,{recursive:!0})}}h();var Vm=t=>`kuriko_reads_${t.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"")}`;function Uu(t,e){return`${t.map(n=>{let[r,i]=n.split(".");return`resource "google_bigquery_dataset_iam_member" "${Vm(n)}" {
|
|
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
|
+
# }`}h();import{createPrivateKey as Gu,createPublicKey as Jm,generateKeyPairSync as zm}from"node:crypto";import{existsSync as Hm,readFileSync as Qm}from"node:fs";import{homedir as Zm}from"node:os";var Xm=/^[a-z][a-z0-9-]{1,30}$/,ey=/^[A-Za-z_][A-Za-z0-9_$]{0,254}$/,ty=/^[A-Za-z0-9][A-Za-z0-9_.-]{1,254}$/,sy=/^[A-Za-z0-9_]{1,1024}$/,ko="snowflake-kuriko-key";function $o(t){let e=`bq-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}`.slice(0,31).replace(/-$/,"");return Xm.test(e)?e:"bq-warehouse"}function Fu(t,e){if(!t||t.kind==="none")return"";if(t.kind==="bigquery"){let s=new Set;return t.datasets.map(n=>{let r=$o(n);for(let i=2;s.has(r);i++)r=`${$o(n).slice(0,28)}-${i}`;return s.add(r),` ${r}: # BigQuery: no credential; the dataset's owners grant Kuriko read access
|
|
266
|
+
name: ${n} (BigQuery)
|
|
267
|
+
kind: bigquery
|
|
268
|
+
dataset: ${n}${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 Wu(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"?$o(t.datasets[0]):"snowflake"}
|
|
286
|
+
# resources: ["*"] # every table, or name them: [orders, customers]
|
|
287
|
+
# access: read
|
|
288
|
+
`}async function Yu(t){M("Connecting a data warehouse (optional)"),k(v(" If your company's data is in a warehouse, Kuriko can connect it now. Nobody can read it until you")),k(v(" grant a group access in policy.yaml. Databases (Postgres) and Notion can be added there any time."));let e=await ie(`
|
|
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"?ny(t):e==="snowflake"?ry(t):{kind:"none"}}async function ny(t){for(;;){k(v(" 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 s=await j(`Looking for datasets in ${e}`,()=>bu(e)),n;if(s?.length)k(v(" Pick the datasets tools may reach. Kuriko doesn't change who can read them: at the end of the")),k(v(" install it prints the Terraform whoever manages them adds, to let Kuriko's gateway read just these.")),n=await Un(`
|
|
290
|
+
Which datasets?`,s.map(r=>({label:r.id,value:r.id,hint:r.location})),()=>!1);else{x(s?`${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).`),n=(await V(" Dataset names, separated by commas (or Enter to skip):")).split(",").map(o=>o.trim()).filter(Boolean);let i=n.filter(o=>!sy.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(!n.length){if(await z(" No datasets picked. Continue without a warehouse?",!0))return{kind:"none"};continue}return T(`BigQuery: ${n.map(r=>`${e}.${r}`).join(", ")}`),{kind:"bigquery",project:e,datasets:n}}}var Ns=async(t,e)=>{for(;;){let s=await V(t,e);if(ey.test(s))return s;x("Use letters, digits and _ (a name as you'd write it in Snowflake without quotes).")}};async function ry(t){let e;for(;e=(await V(" Snowflake account identifier (orgname-accountname, from Admin \u2192 Accounts):")).replace(/\.snowflakecomputing\.com.*$/,"").replace(/^https?:\/\//,""),!ty.test(e);)x("That doesn't look like an account identifier, e.g. acme-analytics.");let s=await Ns(" Database tools read:"),n=await Ns(" Schema:","PUBLIC"),r=await Ns(" Warehouse queries run on:","COMPUTE_WH"),i=await Ns(" User Kuriko signs in as:","KURIKO_READER"),o=await Ns(" Role it reads with:","KURIKO_READ"),a=await ie(`
|
|
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=zm("rsa",{modulusLength:2048}).privateKey.export({type:"pkcs8",format:"pem"}).toString();else for(;;){let p=(await V(" Path to the private key file:")).replace(/^~(?=\/)/,Zm());if(!Hm(p)){x(`There's no file at ${p}.`);continue}c=Qm(p,"utf8");try{Gu({key:c,format:"pem"});break}catch{x("That isn't an unencrypted private key. Make one without a passphrase: openssl pkcs8 -topk8 -nocrypt")}}await j("Storing the key in Secret Manager",()=>Nt(t.project,ko,c)),T(`Key stored as ${ko} ${v("(only Kuriko's gateway will be able to read it)")}`);let l=Jm(Gu(c)).export({type:"spki",format:"pem"}).toString().replace(/-----[A-Z ]+-----|\s/g,"");return Ae("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.","",...iy({user:i,role:o,warehouse:r,database:s,schema:n,publicKey:l}).map(p=>` ${C(p)}`),"",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."),T(`Snowflake: ${e}, ${s}.${n} as ${i}`),{kind:"snowflake",account:e,user:i,warehouse:r,database:s,schema:n,role:o,secret:ko}}function iy(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",So="KURIKO_RESULT ";function oy(t){let e=Math.max(...ge.map(o=>o.id.length)),s=o=>`# ${o.name}: ${o.where}${o.notYet?` (not yet: ${o.notYet})`:""}`,n=o=>t.includes(o.id)&&!o.notYet?` - ${o.id.padEnd(e+2)} ${s(o)}`:` # - ${o.id.padEnd(e)} ${s(o)}`,r=t.filter(o=>!ge.some(a=>a.id===o)),i=[...ge.map(n),...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=>!Rs(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 s=Fu(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
|
|
@@ -282,15 +346,42 @@ ${e}# Data sources tools can use. Credentials stay in Secret Manager under any n
|
|
|
282
346
|
# secret: notion-oauth-client-secret # its OAuth client secret
|
|
283
347
|
# resources:
|
|
284
348
|
# interviews: 6643d20a-7cdb-4154-a1eb-7994499dd58b
|
|
285
|
-
|
|
286
|
-
|
|
349
|
+
#
|
|
350
|
+
# hubspot: # Any JSON API, described here instead of coded (read-only). The
|
|
351
|
+
# name: HubSpot # credential only ever goes to base_url.
|
|
352
|
+
# kind: api
|
|
353
|
+
# base_url: https://api.hubapi.com
|
|
354
|
+
# secret: hubspot-private-app-token
|
|
355
|
+
# auth: bearer # or basic (the secret is user:password), or header X-Api-Key
|
|
356
|
+
# resources:
|
|
357
|
+
# contacts:
|
|
358
|
+
# path: /crm/v3/objects/contacts?limit=100&properties=email,firstname,lastname
|
|
359
|
+
# rows: results # where the list is in the answer
|
|
360
|
+
# next: { cursor: paging.next.after, param: after } # or link, { url: ... }, { page: page }
|
|
361
|
+
#
|
|
362
|
+
# hubspot-personal: # The same, each person signing in with their own HubSpot account
|
|
363
|
+
# name: HubSpot (yours)
|
|
364
|
+
# kind: api
|
|
365
|
+
# credentials: per-person
|
|
366
|
+
# base_url: https://api.hubapi.com
|
|
367
|
+
# secret: hubspot-oauth-client-secret # the OAuth app's client secret
|
|
368
|
+
# oauth:
|
|
369
|
+
# authorize_url: https://app.hubspot.com/oauth/authorize
|
|
370
|
+
# token_url: https://api.hubapi.com/oauth/v1/token
|
|
371
|
+
# client_id: 1a2b3c4d-...
|
|
372
|
+
# scopes: [crm.objects.contacts.read]
|
|
373
|
+
# resources:
|
|
374
|
+
# contacts: { path: /crm/v3/objects/contacts, rows: results, next: { cursor: paging.next.after, param: after } }
|
|
375
|
+
${s?`connectors:
|
|
376
|
+
${s}`:`connectors: {}
|
|
377
|
+
`}
|
|
287
378
|
# Who may use which data. group is a Google group email, or everyone. write includes read.
|
|
288
379
|
# A tool only ever gets what its viewer is granted here AND what the tool declared it needs.
|
|
289
380
|
# For a per-person source, this says who may use it at all; the source decides what each person sees.
|
|
290
381
|
#
|
|
291
382
|
# - group: everyone
|
|
292
383
|
# connector: notion
|
|
293
|
-
# resources: [interviews] # for a database: table names, or ["*"] for every table
|
|
384
|
+
# resources: [interviews] # for a database or warehouse: table names, or ["*"] for every table
|
|
294
385
|
# access: write
|
|
295
386
|
# mask: [] # fields that come back hidden
|
|
296
387
|
#
|
|
@@ -310,65 +401,38 @@ connectors: {}
|
|
|
310
401
|
# rows:
|
|
311
402
|
# stage: [won, lost] # finance sees closed deals,
|
|
312
403
|
# mask: [rep_email] # without who closed them
|
|
313
|
-
access: []
|
|
404
|
+
${Wu(t.warehouse)}access: []
|
|
314
405
|
|
|
315
|
-
${
|
|
316
|
-
`)[0]}`]):
|
|
406
|
+
${oy(t.clients??Ie)}`}function Ce(t,e){let s;try{s=(0,dr.parse)(t,{prettyErrors:!0,uniqueKeys:!0})}catch(n){throw n instanceof dr.YAMLParseError?new lt([`It isn't valid YAML: ${n.message.split(`
|
|
407
|
+
`)[0]}`]):n}return Fo(s,n=>n.startsWith("projects/")?n:`projects/${e}/secrets/${n}`)}var vo={add:Be("+"),change:rt("~"),remove:we("-")};function ay(t){for(let e of t)k(` ${vo[e.op]} ${e.op==="remove"?we(xs(e)):xs(e)}`)}async function ur(t,e,s){let n=await j(e,()=>Tt(t.project,t.region,"kuriko-migrate",["scripts/admin.ts",...s])),r=n.logs.find(o=>o.startsWith(So));if(n.code===0&&r)return JSON.parse(r.slice(So.length));if(n.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=n.logs.filter(o=>!o.startsWith(So)).slice(-8);throw new Error(`${e} failed in the cloud${i.length?`:
|
|
317
408
|
${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 ${
|
|
409
|
+
`)}`:" (no logs yet; try again)"}`)}async function Hu(t,e){M("Checking this machine"),await be(Ge()),await te();let s=await We(e.dir,"Which install's policy?",["installed"],{partial:"finish it with kuriko install"}),n=Pt(s);if(!await at(s,"module.kuriko.google_cloud_run_v2_job.migrate"))throw new Error(`${n.project} isn't fully installed yet. Finish it with kuriko install`);T(`Install ${C(n.project)} ${v(`(${B(s)})`)}`);let r=_o(s,U);if(!Ao(r))throw Ju(r,zu(n)),new Error(`${n.project} had no ${U}, so one was started at ${B(r)} with just the two roles.
|
|
410
|
+
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=Ce(Eo(r,"utf8"),n.project),o=(b,A)=>`${b} ${A}${b===1?"":"s"}`;T(`${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=fr(i),c=[];if(await j("Checking the secrets it names exist",async()=>{for(let b of a)await vs(b)||c.push(b)}),c.length){let[b,A]=c[0].split("/").filter((K,P)=>P%2===1);throw new Error(`Secret Manager has no ${c.map(K=>ze(K,n.project)).join(", ")} (or your account can't see ${c.length>1?"them":"it"}). Whoever manages credentials creates it, e.g.:
|
|
411
|
+
read -s TOKEN && printf '%s' "$TOKEN" | gcloud secrets create ${A} --project ${b} --data-file=- && unset TOKEN`)}a.length&&T(`Secrets exist: ${a.map(b=>ze(b,n.project)).join(", ")}`),M("What changes");let l=Buffer.from(JSON.stringify(i)).toString("base64"),p=await ur(n,"Comparing with the install, in the cloud",["policy-plan",l]);p.changes=p.changes.filter(b=>{if(b.kind!=="connector"||b.op!=="change")return!0;let A=p.connectors.find(q=>q.id===b.id),K=i.connectors.find(q=>q.id===b.id);if(!A||!K)return!0;let P=q=>wr({roles:[],grants:[],clients:[],connectors:[q]}).connectors[0],R=Wo(P(A),P(K));return R[0]==="(settings differ only in form)"?!1:(b.summary=`${K.name}: ${R.join("; ")}`,!0)});let u={roles:[],grants:[],clients:[],connectors:p.connectors},f=await j("Checking which secrets the gateway can read",()=>Qu(n,u,i)),d=await j("Checking which BigQuery datasets the gateway can read",()=>Zu(n,u,i));p.lastApply?k(v(` Last applied ${new Date(p.lastApply.at).toLocaleString()} by ${p.lastApply.appliedBy}`)):k(v(" This would be the first apply. After it, access changes go through this file; admin tools in Claude point here."));let m=!p.changes.length&&!f.allow.length&&!f.disallow.length;if(m&&(T(`${n.project} already matches ${U}.`),t==="plan"||p.lastApply))return;ay(p.changes);for(let b of f.allow)k(` ${vo.add} the gateway can read secret ${ze(b,n.project)}`);for(let b of f.disallow)k(` ${vo.remove} ${we(`the gateway can no longer read secret ${ze(b,n.project)}`)}`);let g=i.connectors.filter(b=>b.mode==="delegated");if(g.length){let b=(await Ue(n.project))?.number;if(b){let A=nt(n,b).mcp.replace(/\/mcp$/,"");for(let K of g)k(v(` ${K.id}: set the OAuth redirect URI to ${A}/connect/callback; people connect at ${nt(n,b).web}/connect/${K.id}`))}}let y=p.changes.filter(b=>b.op==="remove").length+f.disallow.length,S=p.changes.filter(b=>b.op==="remove"&&(b.kind==="role"||b.kind==="grant")).length,N=p.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.`),N&&x(`${N} data source${N===1?" is":"s are"} removed: tools using ${N===1?"it":"them"} stop getting its data, and everyone's own connections to ${N===1?"it":"them"} are deleted.`);let I=p.changes.filter(b=>b.kind==="client"&&b.op==="remove");if(I.length&&x(`${I.map(b=>xt(b.client)).join(", ")} can't sign anyone in any more, and ${I.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.`),Xu(n,d),t==="plan"){k(`
|
|
412
|
+
${v("Plan only: nothing was changed. Apply with: kuriko policy apply")}`);return}if(!e.yes&&!await z(`
|
|
413
|
+
Apply ${m?`${U} (no changes; records it as the source of truth)`:"these changes"}?`,!y)){k("Nothing was changed.");return}await ef(n,f);let $=await _t(),E=await ur(n,"Applying, in the cloud",["policy-apply",l,$,p.hash]);await ly(n,f);let O=E.changes.length+f.allow.length+f.disallow.length;T(`${n.project} matches ${U} (${O} change${O===1?"":"s"}, recorded in the audit log as ${$})`),f.allow.length&&k(v(" New secret access can take a minute or two to reach Google's servers.")),await Fe([r],`Policy for ${n.project}: ${E.changes.length?E.changes.map(xs).slice(0,3).join("; ")+(E.changes.length>3?"; \u2026":""):"first apply"}`)}var fr=t=>[...new Set(t.connectors.flatMap(e=>e.secretRef?[e.secretRef]:[]))].sort(),Co=t=>`kuriko-gateway@${t.project}.iam.gserviceaccount.com`,Rt=t=>`serviceAccount:${Co(t)}`,Vu=(t,e)=>[...new Set(t.connectors.filter(s=>s.kind==="bigquery").map(s=>`${s.config.project??e}.${s.config.dataset}`))].sort(),cy=t=>t.split(".");async function Qu(t,e,s){let n=fr(s),r=[];for(let o of n)await As(o,Rt(t))||r.push(o);let i=[];for(let o of fr(e))o.startsWith("projects/")&&!n.includes(o)&&await vs(o)&&await As(o,Rt(t))&&i.push(o);return{allow:r,disallow:i}}async function Zu(t,e,s){let n=Vu(s,t.project),r={waiting:[],unknown:[],unused:Vu(e,t.project).filter(i=>!n.includes(i))};for(let i of n){let o=await ku(...cy(i),Co(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 Xu(t,e){let s=[...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.`),s.length&&(k(v(` Whoever manages ${s.length===1?"that dataset":"those datasets"} adds this to their Terraform (Kuriko never changes data it doesn't own):
|
|
414
|
+
`)),k(Uu(s,Co(t)).split(`
|
|
415
|
+
`).map(n=>` ${n}`).join(`
|
|
416
|
+
`)),k("")),e.unused.length&&k(v(` No longer named here, so their grant to Kuriko can be removed: ${e.unused.join(", ")}`))}async function ef(t,e){e.allow.length&&await j("Letting the gateway read the new secrets",async()=>{for(let s of e.allow)await fo(s,Rt(t))})}async function ly(t,e){e.disallow.length&&await j("Taking away the gateway's access to secrets no longer used",async()=>{for(let s of e.disallow)await yu(s,Rt(t))})}async function tf(t,e){let s=_o(e,U);if(!Ao(s))return[];let n=fr(Ce(Eo(s,"utf8"),t.project)),r=[];for(let i of n)await vs(i)&&!await As(i,Rt(t))&&(await fo(i,Rt(t)),r.push(i));return r}async function sf(t,e,s=""){let n=_o(e,U);Ao(n)||Ju(n,zu(t,s));let r=Ce(Eo(n,"utf8"),t.project),i=Buffer.from(JSON.stringify(r)).toString("base64"),o=await ur(t,"Reading the install's access, in the cloud",["policy-plan",i]);if(o.lastApply)return T(`Access comes from ${U} (change it with kuriko policy apply)`);let a={roles:[],grants:[],clients:[],connectors:o.connectors};await ef(t,await j("Checking which secrets the gateway can read",()=>Qu(t,a,r)));let c=await j("Checking which BigQuery datasets the gateway can read",()=>Zu(t,a,r));await ur(t,`Applying ${U}, in the cloud`,["policy-apply",i,await _t(),o.hash]),T(`Roles for your two groups${r.connectors.length?`, and ${r.connectors.map(l=>l.name).join(", ")}`:""}, from ${U}`),Xu(t,c)}var Ne="module.kuriko",py=[`${Ne}.google_sql_database_instance.kuriko`,`${Ne}.google_sql_database.kuriko`,`${Ne}.google_sql_user.kuriko`,`${Ne}.google_cloud_run_v2_service.web`,`${Ne}.google_cloud_run_v2_service.gateway`,`${Ne}.google_cloud_run_v2_job.migrate`],hy=[`${Ne}.google_kms_crypto_key.user_tokens`,`${Ne}.google_kms_key_ring.kuriko`],gy=new Set(["deletion_protection","deletion_policy"]);function my(t){let e=_u(t).filter(u=>u.address.startsWith(`${Ne}.`)),s=e.find(u=>u.type==="google_project"&&u.mode==="data")?.values.project_id;if(typeof s!="string")throw new Error("This install has no Kuriko resources in its state (already destroyed, or never installed).");let n=e.filter(u=>u.mode==="managed"),r=u=>n.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 ${C(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`);n.some(u=>u.type.endsWith("_iam_member"))&&a.push("Every IAM grant Kuriko made");let c=n.filter(u=>hy.includes(u.address)).map(u=>u.address),l=r("google_kms_crypto_key").map(u=>`${i(u,"key_ring").split("/").pop()}/${i(u,"name")}`),p=e.find(u=>u.type==="google_secret_manager_secret"&&u.mode==="data");return{project:s,region:o,deletes:a,release:c,keys:l,idpSecret:p?i(p,"secret_id"):null}}function yy(t){let e=[];for(let s of t.resource_changes??[]){let n=s.change.actions;if(n.length===1&&(n[0]==="no-op"||n[0]==="read"))continue;if(n.length!==1||n[0]!=="update"){e.push(`${s.address} would be ${n.join("/")}`);continue}let r=s.change.before??{},i=s.change.after??{},c=[...new Set([...Object.keys(r),...Object.keys(i),...Object.keys(s.change.after_unknown??{})])].filter(l=>s.change.after_unknown?.[l]===!0||JSON.stringify(r[l]??null)!==JSON.stringify(i[l]??null)).filter(l=>!gy.has(l));c.length&&e.push(`${s.address} would also change ${c.join(", ")}`)}return e}async function nf(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 be(Ge());let e=await We(t.dir,"Which install should be destroyed?",["installed","partial"],{empty:"nothing left to destroy",unknown:"can't read its state"}),s=(d,m=!1)=>L("terraform",d,{cwd:e,inherit:m});if(!Au(e))throw new Error(`${e}/main.tf must pass deletion protection through to the module, so destroy can turn it off:
|
|
323
417
|
variable "deletion_protection" { type = bool, default = true }
|
|
324
|
-
and in module "kuriko": deletion_protection = var.deletion_protection`);T(`Install at ${
|
|
325
|
-
${C(`Destroying Kuriko in ${
|
|
326
|
-
${C("It keeps:")}`);let l=[...
|
|
327
|
-
${
|
|
328
|
-
Type the project id (${
|
|
329
|
-
${f.map(
|
|
418
|
+
and in module "kuriko": deletion_protection = var.deletion_protection`);T(`Install at ${B(e)}`),M("Reading the install");let n=my(await Q("terraform",["show","-json"],{cwd:e})),r=["--project",n.project,"--format=json"],i=(await Q("gcloud",["run","services","list","--region",n.region,...r])).filter(d=>d.metadata.labels?.["kuriko-tool"]).map(d=>d.metadata.name),o=dy(e,U),a=uy(o)?[...new Set(Ce(fy(o,"utf8"),n.project).connectors.flatMap(d=>d.secretRef?[ze(d.secretRef,n.project)]:[]))]:[],c=Eu(e);k(`
|
|
419
|
+
${C(`Destroying Kuriko in ${n.project} (${n.region}) deletes, permanently:`)}`);for(let d of i)k(` ${we("\u2717")} Tool ${d} (Cloud Run service)`);for(let d of n.deletes)k(` ${we("\u2717")} ${d}`);k(`
|
|
420
|
+
${C("It keeps:")}`);let l=[...n.keys.map(d=>`KMS key ${d}. GCP never deletes keys; it costs cents a month and a reinstall here reuses it.`),...n.idpSecret?[`Your IdP client secret ${n.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(` ${v("\u2022")} ${d}`);if(t.dryRun){k(`
|
|
421
|
+
${v("Dry run: nothing was changed.")}`);return}if((t.confirm??await V(`
|
|
422
|
+
Type the project id (${n.project}) to destroy this install: `))!==n.project){k("That doesn't match. Nothing was changed.");return}M("Turning off deletion protection");let u=".kuriko-unlock.plan";await s(["plan","-input=false","-var","deletion_protection=false",...py.map(d=>`-target=${d}`),`-out=${u}`]);let f=yy(JSON.parse(await s(["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:
|
|
423
|
+
${f.map(d=>` ${d}`).join(`
|
|
330
424
|
`)}
|
|
331
|
-
Apply the config first (or fix it), then run destroy again.`);if(await
|
|
332
|
-
${C(`Kuriko is gone from ${
|
|
333
|
-
${C("Outside Google Cloud")} (yours to remove if you're done with Kuriko):`),
|
|
334
|
-
To remove everything at once: ${C(`gcloud projects delete ${
|
|
335
|
-
# Name one in roles or access to give its members something; groups not named here get nothing.`;if(!
|
|
425
|
+
Apply the config first (or fix it), then run destroy again.`);if(await s(["apply","-input=false",u],!0),T("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",n.region,"--project",n.project,"--quiet"]),T(d)}n.release.length&&(M("Keeping the KMS key out of the destroy"),await s(["state","rm",...n.release]),T("Terraform no longer manages the key; it stays in the project")),M("Destroying everything else (Cloud SQL takes a few minutes)"),await s(["destroy","-input=false","-auto-approve","-var","deletion_protection=false"],!0),k(`
|
|
426
|
+
${C(`Kuriko is gone from ${n.project}.`)} Still there, by design:`);for(let d of l)k(` ${v("\u2022")} ${d}`);k(`
|
|
427
|
+
${C("Outside Google Cloud")} (yours to remove if you're done with Kuriko):`),k(` ${v("\u2022")} The OAuth client for Kuriko's sign-in, and the Groups Reader role assignment for the deleted kuriko-web account`),k(` ${v("\u2022")} Your kuriko-admins / kuriko-builders groups`),k(`
|
|
428
|
+
To remove everything at once: ${C(`gcloud projects delete ${n.project}`)}`),await Fe([e],`Destroy ${n.project}`,{remove:!0})}h();import{existsSync as Ts,mkdirSync as Py,readFileSync as pf,writeFileSync as jy}from"node:fs";import{basename as Ry,join as Ve}from"node:path";h();import{existsSync as wy,readFileSync as by}from"node:fs";import{join as ky}from"node:path";var $y=40,Sy=t=>t.endsWith(".guest.google")||/^(abuse|postmaster)@/.test(t);async function No(t){let e=await Ct().catch(()=>[]),s=(e.find(r=>r.name===t.domain)??e[0])?.customerId;if(!s)return null;let n=await Wn(t.project,s).catch(()=>null);return n&&n.filter(r=>!Sy(r.email))}function rf(t,e){let s=t.filter(a=>a.email!==e.adminsGroup&&a.email!==e.buildersGroup),n=`# Groups in ${e.domain} when this file was made (kuriko groups lists them now).
|
|
429
|
+
# Name one in roles or access to give its members something; groups not named here get nothing.`;if(!s.length)return`${n}
|
|
336
430
|
# (none besides the two above)
|
|
337
|
-
`;let r=
|
|
431
|
+
`;let r=s.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 s.length>r.length&&o.push(`# \u2026 and ${s.length-r.length} more`),`${n}
|
|
338
432
|
${o.join(`
|
|
339
433
|
`)}
|
|
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
|
|
434
|
+
`}function vy(t,e){let s=new Map,n=ky(t,U);if(!wy(n))return s;let r=Ce(by(n,"utf8"),e),i=(o,a)=>s.set(o,[...s.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 s}async function of(t){M("Checking this machine"),await be(Ge()),await te();let e=await We(t.dir,"Which install's groups?",["installed","partial"]),s=Pt(e);T(`Install ${C(s.project)} ${v(`(${B(e)})`)}`),M(`Google Groups in ${s.domain}`);let n=await j("Reading your Workspace's groups",()=>No(s));if(!n){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?n.filter(l=>`${l.email} ${l.name} ${l.description}`.toLowerCase().includes(r)):n,o=vy(e,s.project),a=Math.max(10,...i.map(l=>l.email.length));for(let l of i){let p=o.get(l.email);k(` ${l.email.padEnd(a)} ${l.name&&l.name.toLowerCase()!==l.email.split("@")[0]?l.name:""}${p?` ${Be(`in ${U}: ${p.join(", ")}`)}`:""}`)}T(r?`${i.length} of ${n.length} groups match "${t.search}"`:`${n.length} group${n.length===1?"":"s"}`);let c=[...o.keys()].filter(l=>l!=="*"&&l.includes("@")&&!n.some(p=>p.email===l));for(let l of c)x(`${U} names ${Mt(l)}, which isn't a group in ${s.domain} (a typo, or deleted?). Its rules apply to nobody.`);k(v(`
|
|
435
|
+
Copy an email into ${U} (roles or access), then: kuriko policy apply`))}h();import{existsSync as cf,readdirSync as Ny}from"node:fs";import{homedir as Ty}from"node:os";import{basename as Iy,dirname as uf,join as Oo,resolve as Te}from"node:path";h();import{existsSync as Ay,mkdirSync as Ey,writeFileSync as To}from"node:fs";import{join as pr,resolve as _y}from"node:path";var Cy=`# Kuriko installs
|
|
372
436
|
|
|
373
437
|
One folder per Kuriko install, named after its cloud project, made and changed by the \`kuriko\` CLI.
|
|
374
438
|
Each holds the install's answers (\`kuriko.json\`) and the Terraform config generated from them. No
|
|
@@ -384,25 +448,63 @@ kuriko upgrade # move one to the Kuriko version you have checked out
|
|
|
384
448
|
\`\`\`
|
|
385
449
|
|
|
386
450
|
Clone it next to your Kuriko checkout, or run \`kuriko\` from inside it.
|
|
387
|
-
`;async function
|
|
388
|
-
`),
|
|
451
|
+
`;async function Io(t){Ey(t,{recursive:!0}),To(pr(t,Ot),JSON.stringify({kuriko:"installs",version:1},null,2)+`
|
|
452
|
+
`),To(pr(t,".gitignore"),`.terraform/
|
|
389
453
|
.kuriko-*.plan
|
|
390
|
-
`),
|
|
454
|
+
`),Ay(pr(t,"README.md"))||To(pr(t,"README.md"),Cy);try{return await L("git",["-C",t,"rev-parse","--git-dir"]),{isRepo:!0}}catch{return{isRepo:!1}}}async function af(t="."){let e=_y(t);if(oe(e)===e){T(`${B(e)} is already an installs repo`);return}let{isRepo:n}=await Io(e);T(`${B(e)} is now an installs repo`),k(`
|
|
391
455
|
Share it through git: whoever can clone it can see your installs (changing one also needs
|
|
392
|
-
permissions on its cloud project). ${
|
|
456
|
+
permissions on its cloud project). ${n?"Commit these files and push.":`Make it a git repo: ${C(`git -C ${B(e)} init`)}, then add a private remote.`}`)}async function lf(t){try{return(await L("git",["-C",t,"rev-parse","--show-toplevel"])).trim()}catch{return null}}function Oy(t,e,s=H){if(e&&Te(e)!==Te(s))return{path:Oo(e,"kuriko"),inRepo:!0};let n=e?uf(Te(s)):Te(t);return{path:Oo(n,"kuriko-installs"),inRepo:!1}}async function ff(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=Oy(t,await lf(t));for(k(""),k(` ${C("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(v(`
|
|
457
|
+
You're in ${B(uf(e.path))}, so it's suggested there.`));;){let s=(await V(`
|
|
458
|
+
Folder:`,B(e.path))).replace(/^~(?=\/|$)/,Ty()),n=Te(t,s);if(Te(n).startsWith(Te(H)+"/")||Te(n)===Te(H)){x("That's inside the Kuriko checkout. Pick a folder outside it.");continue}if(cf(n)&&!cf(Oo(n,Ot))&&Ny(n).length){x(`${B(n)} isn't empty. Pick a new folder (Kuriko makes it), or an empty one.`);continue}let{isRepo:r}=await Io(n);return T(`Config goes in ${B(n)}${r?` ${v(`(in the git repo ${Iy(await lf(n)??n)})`)}`:""}`),k(v(` Run kuriko from inside it later (or set KURIKO_INSTALLS=${n}), so it finds your installs.`)),n}}async function hf(t){k(`${C("Kuriko install")}
|
|
459
|
+
|
|
460
|
+
This puts Kuriko in your own cloud. Everything runs there, under your control: your people sign
|
|
461
|
+
in with the accounts they already have, and credentials stay in your own secret manager.
|
|
462
|
+
|
|
463
|
+
First a few questions; nothing is created until you've seen the plan and said yes. Then it takes
|
|
464
|
+
about 30 minutes, mostly waiting for the database. A few steps happen in your providers' admin
|
|
465
|
+
pages; this explains each one and checks it before moving on. If anything fails, run it again:
|
|
466
|
+
it picks up where it stopped.`);let e=oe()??await ff();await be(e);let s=t.dir?Es(t.dir):await Dy(),n=s&&Ts(Ve(s,Ye))?JSON.parse(pf(Ve(s,Ye),"utf8")):null;n||(k(""),await ie("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 ie("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[P,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(P,q))throw new Error(`${P} 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 _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 te(),T(`Signed in to Google Cloud as ${r}`);let o;if(n){M(`Continuing the install in ${n.project}`);let P=await Ue(n.project);if(!P||P.state!=="ACTIVE")throw new Error(`Project ${n.project} isn't available (deleted, or your account can't see it).`);o=P.number,T(`Project ${n.project} ${v(`(${s})`)}`)}else{M("Your Google Cloud project"),k(" Kuriko should have a project to itself, so its permissions don't mix with anything else.");let P=await ie("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(P){let se=await j("Finding your organization",()=>Ct());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 ao("Organization:",se.map(he=>({label:he.name,value:he,hint:he.id}))),R=await hr("Project ID (can't be changed later):",`kuriko-${Math.floor(1e3+Math.random()*9e3)}`,Xi,"6\u201330 characters, starting with a letter: lowercase letters, digits and hyphens.")}else for(;R=await V("Project ID:"),!await j("Looking it up",()=>Ue(R));)k(` Can't find ${R}, or ${r} can't see it.`);let F=null;if(P||!await j("Checking billing",()=>su(R))){let se=await j("Finding billing accounts",()=>eu());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 ao("Billing account:",se.map(mr=>({label:mr.name,value:mr,hint:mr.id})));let he=await j("Checking the billing account has room",()=>ru(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(v(" If linking fails, unlink a project you don't use (gcloud billing projects unlink <project>), or ask Google")),k(v(" for more: https://support.google.com/code/contact/billing_quota_increase")),!await z(" Try anyway?",!1))){k("Nothing was created.");return}}let ue=await Ky();M("The plan");let $e=(se,he)=>k(` ${v(se.padEnd(10))}${he}`);if($e("Runs in",`Google Cloud \xB7 ${P?`new project ${C(R)}${q?` in ${q.name}`:""}`:`existing project ${C(R)}`} \xB7 ${ue}`),F&&$e("Billing",`${F.name} ${v(F.id)}`),$e("Sign-in",`Google Workspace \xB7 people at ${C(i)}`),$e("Admins",`kuriko-admins@${i}`),$e("Builders",`kuriko-builders@${i}`),$e("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(P){for(;;)try{await j(`Creating project ${R}`,()=>tu(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 hr("Another project ID:",void 0,Xi,"6\u201330 characters, starting with a letter: lowercase letters, digits and hyphens.")}T(`Created project ${R}`)}if(F){try{await j("Linking billing",()=>nu(R,F.id))}catch(se){throw iu(se)?new Error(`${F.name} is at Google's limit of linked projects, so billing couldn't be linked to ${R}.
|
|
467
|
+
Free a slot (gcloud billing projects unlink <a project you don't use>) or ask Google for more:
|
|
468
|
+
https://support.google.com/code/contact/billing_quota_increase
|
|
469
|
+
Then run kuriko install again and choose "Use an existing, empty project": ${R}${P?" (already created, so no new project is made)":""}.`):se}T("Billing linked")}o=(await Ue(R)).number,n={host:"gcp",sso:"google-workspace",project:R,region:ue,domain:i,adminEmail:r,adminsGroup:`kuriko-admins@${i}`,buildersGroup:`kuriko-builders@${i}`,dbInstanceName:""},s=Ve(e,R),Py(s,{recursive:!0}),pe(s,n)}let a=s,c=nt(n,o);M("Turning on the Google Cloud services Kuriko uses"),await j("Enabling APIs",()=>Fn(n.project,Ll)),await sr(n),T("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=`${n.project}-tfstate`,p=await j("Creating the state bucket",()=>ou(l,n.project,n.region));T(`gs://${l} ${v(`(${p}; versioned, private)`)}`);let u=await au(n.project);n.dbInstanceName||(n.dbInstanceName=Kl(u.map(P=>P.name)),pe(a,n));let f=await rr(t.allowDirty);W&&(M(`Kuriko ${f}`),Cs(await lr(n,f)),pe(a,n)),nr(a,n),await j("Preparing Terraform",()=>L("terraform",["init","-input=false"],{cwd:a}));let d={},m=()=>jy(Ve(a,"imports.tf"),Wl(n,d));await at(a,"module.kuriko.google_kms_key_ring.kuriko")||(Object.assign(d,await cu(n.project,n.region,ys.ring,ys.key)),d.ring&&T("Found a KMS key from an earlier install; this one will reuse it"));let g=(await L("terraform",["state","list"],{cwd:a}).catch(()=>"")).split(`
|
|
470
|
+
`),y=Object.keys(bs).filter(P=>!g.includes(`module.kuriko.google_service_account.${P}`));if(y.length){let P=await j("Looking for service accounts from an earlier install",()=>lu(n.project,y.map(R=>bs[R])));d.accounts=y.filter(R=>P.includes(bs[R])),d.accounts.length&&T(`Found ${P.join(", ")} from an earlier install; this one takes ${P.length===1?"it":"them"} over`)}m(),T(`Install config in ${a}`),M("Kuriko's service accounts and image registry"),jt(a,n,f),await j("Creating service accounts and the image registry",()=>or(a,"bootstrap",xl)),T("kuriko-web, kuriko-gateway and kuriko-tools service accounts; image registry"),M("Kuriko's database");let S={started:Date.now(),state:"creating",note:""},N=Promise.resolve();if(await at(a,Ln))S.state="ready",T(`Database ${n.dbInstanceName} ${v("(already created)")}`);else{let P=u.find(R=>R.name===n.dbInstanceName&&R.kuriko);if(P)d.sqlInstance=P.name,m(),T(`Found database ${P.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.");N=qy(a,n,f,S).then(()=>S.state="ready",R=>(S.state="failed",R)),oo(()=>S.state==="creating"?`database: ${S.note||"creating"} (${Mn(S.started)})`:S.state==="ready"?"database: ready":"database: failed"),T("Started; it'll be ready in about 10\u201315 minutes")}for(W||(M(`Kuriko's images (version ${f})`),k(v(" Built from this checkout (development). Released versions pull Kuriko's published images instead.")),await cr(n.region,c.registry,f)),Ae("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 ${n.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 P=await hr(`
|
|
471
|
+
Client ID:`,n.idpClientId,Ml,"It looks like 1234567890-abc123.apps.googleusercontent.com."),R=P!==n.idpClientId;if(n.idpClientId=P,pe(a,n),await Ss(n.project,ws)&&!R&&!await z(` A client secret is already in Secret Manager (${ws}). Replace it?`)){T("Keeping the stored client secret");break}k(v(` The secret goes straight into Secret Manager as ${ws}. It isn't shown or saved anywhere else.`));let F=await Bn(" Client secret (hidden as you type or paste):");if(!F)continue;let ue=await j("Checking them with Google",()=>fu(P,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 j("Storing the secret",()=>Nt(n.project,ws,F)),T(`Client secret stored in Secret Manager${ue?", and Google accepts it":""}`);break}n.groupsChosen||((await Promise.all([n.adminsGroup,n.buildersGroup].map(R=>Yn(n.project,R,n.adminEmail).catch(()=>null)))).every(R=>R?.exists)||await By(n),n.groupsChosen=!0,pe(a,n)),n.clients||(n.clients=await Ly(a),pe(a,n)),!n.warehouse&&!Ts(Ve(a,U))&&(n.warehouse=await Yu(n),pe(a,n)),Ae("Decide who runs Kuriko (Google Groups)",["Kuriko gives roles by Google Group, so access is managed where you already manage people:",` ${C(n.adminsGroup)} Admin: manages who can use which data, sees the audit log.`,` ${C(n.buildersGroup)} Builder: builds tools.`,` Everyone else in ${n.domain} can sign in and use tools shared with them. Groups inside these groups count too.`]);let I=()=>j("Looking for the groups",()=>Promise.all([Yn(n.project,n.adminsGroup,n.adminEmail),Yn(n.project,n.buildersGroup,n.adminEmail)])),[$,E]=await I(),O=[!$.exists&&n.adminsGroup,!E.exists&&n.buildersGroup].filter(P=>!!P),b=!1;if(O.length&&await z(`
|
|
472
|
+
Create ${O.join(" and ")} now${$.exists?"":`, with you in ${n.adminsGroup}`}?`,!0)){let P=await Ct(),R=(P.find(q=>q.name===n.domain)??P[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,$e]of[[n.adminsGroup,"Kuriko admins","Kuriko Admin role: manages who can use which data, sees the audit log.",!0],[n.buildersGroup,"Kuriko builders","Kuriko Builder role: builds tools on Kuriko.",!1]])O.includes(q)&&(await j(`Creating ${q}`,()=>pu(n.project,{customerId:R,email:q,name:F,description:ue,owner:$e})),T(`Created ${q}${$e?" (you're its owner)":""}`));if(b=!0,!E.exists){let q=(await V(` Who should build? Their ${n.domain} emails, comma-separated (Enter to add people later):`)).split(/[\s,]+/).filter(Boolean);for(let F of q){if(!Rn(F)){x(`Skipped ${F}: not an email address.`);continue}try{await j(`Adding ${F}`,()=>co(n.project,n.buildersGroup,F)),T(`Added ${F} to ${n.buildersGroup}`)}catch(ue){x(`Couldn't add ${F}: ${ue instanceof Error?ue.message:String(ue)}`)}}}}else O.length&&Ae("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 ${n.adminsGroup}, and the people who'll build to ${n.buildersGroup}.`]);for(let P=0;;P++){if(P&&([$,E]=await I()),$.exists&&E.exists&&$.isMember){T(`${n.adminsGroup} (you're in it) and ${n.buildersGroup} are ready`);break}if(b&&P<6){await new Promise(q=>setTimeout(q,3e3));continue}if($.exists&&!$.isMember&&await z(` You're not in ${n.adminsGroup}, so you wouldn't be a Kuriko admin. Add you?`,!0)){await j("Adding you",()=>co(n.project,n.adminsGroup,n.adminEmail)),b=!0,P=0;continue}let R=[!$.exists&&n.adminsGroup,!E.exists&&n.buildersGroup].filter(Boolean);R.length?x(`Not found yet: ${R.join(", ")} (or ${n.adminEmail} can't see ${R.length>1?"them":"it"}).`):x(`${n.adminEmail} isn't in ${n.adminsGroup}. Add yourself, or you won't be an admin.`),await V(" Press Enter to check again.")}Ae("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 V(" Press Enter when you've assigned it."),M("Creating Kuriko");let A=await j("Waiting for the database",()=>N);if(oo(null),S.state==="failed")throw A;T(`Database ${n.dbInstanceName} ${v(`(${Mn(S.started)} in all)`)}`),jt(a,n,f),await j("Creating Kuriko's secrets, key and services",()=>or(a,"install",null));for(let P of Object.keys(d))delete d[P];m(),T("Kuriko's secrets, key and services"),M("Setting up Kuriko's database"),await ar(n,"kuriko-migrate",void 0,"Database schema");let K="";if(!Ts(Ve(a,U))){let P=await j("Reading your Workspace's groups for policy.yaml",()=>No(n));P&&(K=rf(P,n))}for(await sf(n,a,K),M("Checking Kuriko can see group membership");;){let P=await j("Checking as kuriko-web, in the cloud",()=>Tt(n.project,n.region,"kuriko-migrate",["scripts/admin.ts","check-groups",n.adminEmail,n.adminsGroup]));if(P.code===0){T(`Kuriko sees you in ${n.adminsGroup}`);break}for(let R of P.logs.slice(-3))k(v(` ${R.trim()}`));P.code===3?x(`Kuriko can read groups, but doesn't see ${n.adminEmail} in ${n.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(`
|
|
473
|
+
${C("Kuriko is installed.")}
|
|
474
|
+
|
|
475
|
+
Sign in: ${C(c.web)}
|
|
476
|
+
MCP server: ${C(c.mcp)}
|
|
477
|
+
${xy(n.clients??Ie,c.mcp)}
|
|
478
|
+
|
|
479
|
+
To let someone build: add them to ${n.buildersGroup} and send them the MCP server address.
|
|
480
|
+
${n.warehouse&&n.warehouse.kind!=="none"?`Your ${n.warehouse.kind==="bigquery"?"BigQuery datasets are":"Snowflake database is"} connected; nobody can read ${n.warehouse.kind==="bigquery"&&n.warehouse.datasets.length>1?"them":"it"} until you grant a group
|
|
481
|
+
access in ${n.project}/${U} (there's an example in it).
|
|
482
|
+
`:""}Data sources, who may use them, and which AI apps can connect go in ${n.project}/${U};
|
|
483
|
+
apply with kuriko policy apply.
|
|
484
|
+
Their first sign-in is their setup; they never need Google Cloud access.
|
|
485
|
+
|
|
486
|
+
Install config: ${B(a)} ${v("(no secrets in it; state is in gs://"+l+")")}`),await Fe([a],`Install ${n.project} (Kuriko ${f})`)}async function Ly(t){M("Choosing which AI apps can connect");let e=Ve(t,U);if(Ts(e)){let{clients:n}=Ce(pf(e,"utf8"),Ry(t));return T(`From ${U}: ${n.length?n.join(", "):"none"}`),n}k(v(" People connect Kuriko to the AI app they build in. Data access is the same whichever app they use;")),k(v(` this only decides which apps may act for them. Change it any time in ${U}.`));let s=await Un(`
|
|
487
|
+
Which AI apps can people connect with?`,ge.map(n=>({label:n.name,value:n.id,hint:n.notYet?"not yet":n.where,disabled:!!n.notYet})),n=>Ie.includes(n));return s.length?T(`AI apps: ${s.map(n=>ge.find(r=>r.id===n).name).join(", ")}`):x(`Nobody will be able to connect from an AI app until you allow one in ${U}.`),s}function xy(t,e){let s={"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"},n=t.map(r=>` ${`${ge.find(o=>o.id===r)?.name??r}:`.padEnd(14)}${s[r]??"add the MCP server address as a remote MCP server"}`);return n.length?n.join(`
|
|
488
|
+
`):` ${v(`No AI apps can connect yet: allow one in ${U}.`)}`}async function qy(t,e,s,n){for(;;)try{await or(t,"database",[Ln]);return}catch(r){if(!(r instanceof ee&&Bl(r.stderr)))throw r;let i=Dl(e.dbInstanceName);n.note=`${e.dbInstanceName} was taken, creating ${i}`,e.dbInstanceName=i,pe(t,e),jt(t,e,s)}}var My=[["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 Ky(){return await ie("Region (where Kuriko and its data live):",[...My.map(([e,s])=>({label:e,value:e,hint:s})),{label:"Another region\u2026",value:""}])||hr("Region:",void 0,ql,"Like europe-west2 or us-central1: https://cloud.google.com/run/docs/locations")}async function Dy(){let t=it().filter(s=>Ts(Ve(s,Ye)));if(!t.length)return null;await te({terraformOnly:!0});let e=await _s(t);return ie("Continue an install, or start a new one?",[{label:"Start a new install",value:null},...e.map(s=>{let n=Zn[s.status],r=s.status==="gone";return{label:`Continue ${s.project}`,value:s.dir,disabled:r,hint:`${s.region} ${n.mark} ${n.text}`}})])}async function hr(t,e,s,n){for(;;){let r=await V(t,e);if(s(r))return r;k(` ${n}`)}}async function By(t){M("Choosing who runs Kuriko");let e=await Ct().catch(()=>[]),s=(e.find(r=>r.name===t.domain)??e[0])?.customerId,n=s?await j("Reading your Workspace's groups",()=>Wn(t.project,s)).catch(()=>null):null;n?T(`${n.length} group${n.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(v(" Admins manage who can use which data and see the audit log. Builders make tools and deploy them into this project.")),k(v(" 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 df("admins",n,`kuriko-admins@${t.domain}`),t.buildersGroup=await df("builders",n?.filter(r=>r.email!==t.adminsGroup)??null,`kuriko-builders@${t.domain}`),t.groupsChosen=!0,T(`Admins: ${C(t.adminsGroup)} Builders: ${C(t.buildersGroup)}`)}async function df(t,e,s){let n=t==="admins"?`
|
|
489
|
+
Which group are Kuriko's admins?`:`
|
|
490
|
+
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:s)).toLowerCase();if(!e){if(Rn(l))return l;x(`${l} isn't an email address.`);continue}let p=e.find(f=>f.email===l);if(p)return p.email;let u=Jl(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 ie(" 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(Rn(l)&&await z(` No group ${l} yet. Create it?`,!1))return l;x(`No group matches "${l}".`)}}};if(!e?.length)return r();let i=Vl(e,t),o={label:`Create ${s}`,value:s,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 ie(n,a);return c==="?"?r():c}h();async function gf(){if(!oe()){k(Qn);return}let t=it();if(!t.length){k(`No Kuriko installs yet. Start one with: ${C("kuriko install")}`);return}await te({terraformOnly:!0});let e=await _s(t),s={installed:Be("\u25CF installed"),partial:rt("\u25D0 partly installed: run install to continue, or destroy"),empty:v("\u25CB not installed (or destroyed)"),gone:v("\u25CB project deleted"),unknown:rt("? unknown")};for(let n of e)k(`
|
|
491
|
+
${C(n.project)} ${v(n.region)} ${s[n.status]}`),n.web&&k(` web ${n.web}`),n.mcp&&k(` mcp ${n.mcp}`),n.detail&&k(n.status==="gone"?v(` ${n.detail}`):` ${rt("!")} ${n.detail}`),k(v(` dir ${B(n.dir)}`))}h();import{existsSync as Uy}from"node:fs";import{join as Gy}from"node:path";var Fy="module.kuriko.google_cloud_run_v2_job.migrate",Wy={create:"+",update:"~",replace:"\xB1",delete:"-"};async function Yy(t,e){if(t==="unknown")return"forward";if(ot(t)&&ot(e)){let s=Ru(t,e);return s===0?"same":s<0?"forward":"backward"}return!ot(t)&&!ot(e)?Ou(H,t,e):"switch"}async function mf(t){M("Checking this machine"),await be(Ge());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 We(t.dir,"Which install should be upgraded?",["installed"],{partial:"finish it with kuriko install",empty:"nothing to upgrade",unknown:"can't read its state"}),s=Pt(e),n=await Ue(s.project);if(!n||n.state!=="ACTIVE")throw new Error(`Project ${s.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(`${s.project} isn't fully installed yet. Finish it with kuriko install`);let r=nt(s,n.number);T(`Install ${C(s.project)} ${v(`(${B(e)})`)}`),M("What changes");let i=Ku(e)??"unknown",o=await rr(t.allowDirty),a=await Yy(i,o);if(a==="backward")throw new Error(W?`${s.project} is on ${i}, newer than this CLI (${o}). Update the CLI first: npm i -g kuriko`:`${s.project} is on ${i}, which is newer than this Kuriko checkout (${o}). Pull the Kuriko repo first: git -C ${B(H)} pull`);if(a==="unknown")throw new Error(`${s.project} is on ${i}, which this Kuriko checkout doesn't have. Pull the Kuriko repo first: git -C ${B(H)} pull`);let c=Bu(e);W?(Cs(await lr(s,o)),pe(e,s)):Cs(Mu(e,s)),nr(e,s),jt(e,s,o),await j("Preparing Terraform",()=>L("terraform",["init","-input=false"],{cwd:e}));let{plan:l}=await j("Working out the changes",()=>bo(e,"upgrade",null)),p=xn(l);if(i===o&&!p.length){c(),T(`Already on ${o}. Nothing to do.`);return}k(` Version ${i===o?o:`${v(i)} \u2192 ${C(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 go(H,i,o)??i:i,f=a==="forward"&&!W?await Du(u,o):[];if(f.length){k(` ${f.length} commit${f.length===1?"":"s"}:`);for(let m of f.slice(0,12))k(v(` ${m}`));f.length>12&&k(v(` \u2026 and ${f.length-12} more`))}k(p.length?" Cloud":" Cloud no resource changes");for(let m of p)k(v(` ${Wy[m.action]} ${m.address}${qn.has(`module.kuriko.${m.address}`)?" (old project-wide secret access; policy.yaml grants each secret instead)":""}`));if(k(v(" No data or service is deleted. The database is migrated first; the web app and gateway switch over after.")),t.dryRun){c(),k(`
|
|
492
|
+
${v("Dry run: nothing was changed.")}`);return}if(!await z(`
|
|
493
|
+
Upgrade?`,!0).catch(m=>{throw c(),m})){c(),k("Nothing was changed.");return}if(W||(M(`Kuriko's images (version ${o})`),await cr(s.region,r.registry,o)),await sr(s),M("Migrating the database"),await j("Updating the migrate job",()=>ir(e,"upgrade-migrate",[Fy,...W?["module.kuriko.google_artifact_registry_repository.releases"]:[]])),await ar(s,"kuriko-migrate",void 0,"Database schema"),p.some(m=>qn.has(`module.kuriko.${m.address}`))){Uy(Gy(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 j("Giving the gateway the secrets policy.yaml names, one by one",()=>tf(s,e));T(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 j("Updating the web app and gateway",()=>ir(e,"upgrade",null)),T(`${s.project} is on ${C(o)}`),k(`
|
|
494
|
+
${r.web}`),await Fe([e],`Upgrade ${s.project} to Kuriko ${o}${i!=="unknown"&&i!==o?` (from ${i})`:""}`)}var Is={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=>hf({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:()=>gf()},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=>mf({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 Lt('Say "kuriko policy plan" or "kuriko policy apply".');return Hu(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)=>of({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=>nf({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)=>af(e[0])},help:{usage:"help [command]",summary:"Show this, or the details of one command",details:[],run:async(t,e)=>gr(e[0])}};function gr(t){if(t){let s=Is[t];if(!s)throw new Lt(`No command "${t}".`);console.log(`${C(`kuriko ${s.usage}`)}
|
|
393
495
|
|
|
394
|
-
${
|
|
496
|
+
${s.summary}.${s.details.length?`
|
|
395
497
|
|
|
396
|
-
${
|
|
397
|
-
`)}`:""}`);return}let e=Math.max(...Object.keys(
|
|
498
|
+
${s.details.join(`
|
|
499
|
+
`)}`:""}`);return}let e=Math.max(...Object.keys(Is).map(s=>s.length));console.log(`${C("kuriko")} ${v("\xB7 runs Kuriko in your own cloud")}
|
|
398
500
|
|
|
399
|
-
Usage: kuriko <command> [options] ${
|
|
501
|
+
Usage: kuriko <command> [options] ${v(W?`version ${W.version}`:"development build, from a Kuriko checkout")}
|
|
400
502
|
|
|
401
503
|
Commands:
|
|
402
|
-
${Object.entries(
|
|
504
|
+
${Object.entries(Is).map(([s,n])=>` ${s.padEnd(e)} ${n.summary}`).join(`
|
|
403
505
|
`)}
|
|
404
506
|
|
|
405
507
|
Run ${C("kuriko help <command>")} for a command's options.
|
|
406
|
-
${
|
|
407
|
-
`),
|
|
408
|
-
${
|
|
508
|
+
${Jy()}`)}function Jy(){let t=oe();return t?`Installs repo: ${B(t)}`:"No installs repo yet: clone yours next to the Kuriko checkout, or run kuriko init <folder>."}var Lt=class extends Error{};try{let{positionals:t,values:e}=Vy({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"}}}),[s,...n]=t;if(e.version)console.log(W?W.version:"development build");else if(!s)gr();else if(Is[s])e.help?gr(s):await Is[s].run(e,n);else throw new Lt(`No command "${s}".`)}catch(t){let e=t instanceof Error?t.message:String(t),s=/Unknown option '([^']+)'/.exec(e)?.[1],n=s?`No option ${s}.`:e,r=t.code;t instanceof Lt||typeof r=="string"&&r.startsWith("ERR_PARSE_ARGS")?(console.error(`${we("\u2717")} ${n}
|
|
509
|
+
`),gr(),process.exitCode=2):(console.error(`
|
|
510
|
+
${we("\u2717")} ${n}`),process.exitCode=1)}
|