kuriko 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/kuriko.mjs +231 -246
  2. package/package.json +1 -1
package/kuriko.mjs CHANGED
@@ -1,76 +1,76 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __kurikoRequire } from "node:module"; const require = __kurikoRequire(import.meta.url);
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(`
3
+ var kf=Object.create;var jo=Object.defineProperty;var $f=Object.getOwnPropertyDescriptor;var Sf=Object.getOwnPropertyNames;var vf=Object.getPrototypeOf,Af=Object.prototype.hasOwnProperty;var jn=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var Ef=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(s){throw n=[s],s}};var E=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}};var _f=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Sf(e))!Af.call(t,r)&&r!==n&&jo(t,r,{get:()=>e[r],enumerable:!(s=$f(e,r))||s.enumerable});return t};var Cf=(t,e,n)=>(n=t!=null?kf(vf(t)):{},_f(e||!t||!t.__esModule?jo(n,"default",{value:t,enumerable:!0}):n,t));var w,p=Ef(()=>{w={version:"0.5.0"}});var B=E(Z=>{"use strict";p();var kr=Symbol.for("yaml.alias"),Ho=Symbol.for("yaml.document"),Dn=Symbol.for("yaml.map"),Qo=Symbol.for("yaml.pair"),$r=Symbol.for("yaml.scalar"),Bn=Symbol.for("yaml.seq"),ve=Symbol.for("yaml.node.type"),Xf=t=>!!t&&typeof t=="object"&&t[ve]===kr,ed=t=>!!t&&typeof t=="object"&&t[ve]===Ho,td=t=>!!t&&typeof t=="object"&&t[ve]===Dn,nd=t=>!!t&&typeof t=="object"&&t[ve]===Qo,Zo=t=>!!t&&typeof t=="object"&&t[ve]===$r,sd=t=>!!t&&typeof t=="object"&&t[ve]===Bn;function Xo(t){if(t&&typeof t=="object")switch(t[ve]){case Dn:case Bn:return!0}return!1}function rd(t){if(t&&typeof t=="object")switch(t[ve]){case kr:case Dn:case $r:case Bn:return!0}return!1}var id=t=>(Zo(t)||Xo(t))&&!!t.anchor;Z.ALIAS=kr;Z.DOC=Ho;Z.MAP=Dn;Z.NODE_TYPE=ve;Z.PAIR=Qo;Z.SCALAR=$r;Z.SEQ=Bn;Z.hasAnchor=id;Z.isAlias=Xf;Z.isCollection=Xo;Z.isDocument=ed;Z.isMap=td;Z.isNode=rd;Z.isPair=nd;Z.isScalar=Zo;Z.isSeq=sd});var Dt=E(Sr=>{"use strict";p();var J=B(),re=Symbol("break visit"),ea=Symbol("skip children"),ye=Symbol("remove node");function Un(t,e){let n=ta(e);J.isDocument(t)?lt(null,t.contents,n,Object.freeze([t]))===ye&&(t.contents=null):lt(null,t,n,Object.freeze([]))}Un.BREAK=re;Un.SKIP=ea;Un.REMOVE=ye;function lt(t,e,n,s){let r=na(t,e,n,s);if(J.isNode(r)||J.isPair(r))return sa(t,s,r),lt(t,r,n,s);if(typeof r!="symbol"){if(J.isCollection(e)){s=Object.freeze(s.concat(e));for(let i=0;i<e.items.length;++i){let o=lt(i,e.items[i],n,s);if(typeof o=="number")i=o-1;else{if(o===re)return re;o===ye&&(e.items.splice(i,1),i-=1)}}}else if(J.isPair(e)){s=Object.freeze(s.concat(e));let i=lt("key",e.key,n,s);if(i===re)return re;i===ye&&(e.key=null);let o=lt("value",e.value,n,s);if(o===re)return re;o===ye&&(e.value=null)}}return r}async function Gn(t,e){let n=ta(e);J.isDocument(t)?await ut(null,t.contents,n,Object.freeze([t]))===ye&&(t.contents=null):await ut(null,t,n,Object.freeze([]))}Gn.BREAK=re;Gn.SKIP=ea;Gn.REMOVE=ye;async function ut(t,e,n,s){let r=await na(t,e,n,s);if(J.isNode(r)||J.isPair(r))return sa(t,s,r),ut(t,r,n,s);if(typeof r!="symbol"){if(J.isCollection(e)){s=Object.freeze(s.concat(e));for(let i=0;i<e.items.length;++i){let o=await ut(i,e.items[i],n,s);if(typeof o=="number")i=o-1;else{if(o===re)return re;o===ye&&(e.items.splice(i,1),i-=1)}}}else if(J.isPair(e)){s=Object.freeze(s.concat(e));let i=await ut("key",e.key,n,s);if(i===re)return re;i===ye&&(e.key=null);let o=await ut("value",e.value,n,s);if(o===re)return re;o===ye&&(e.value=null)}}return r}function ta(t){return typeof t=="object"&&(t.Collection||t.Node||t.Value)?Object.assign({Alias:t.Node,Map:t.Node,Scalar:t.Node,Seq:t.Node},t.Value&&{Map:t.Value,Scalar:t.Value,Seq:t.Value},t.Collection&&{Map:t.Collection,Seq:t.Collection},t):t}function na(t,e,n,s){if(typeof n=="function")return n(t,e,s);if(J.isMap(e))return n.Map?.(t,e,s);if(J.isSeq(e))return n.Seq?.(t,e,s);if(J.isPair(e))return n.Pair?.(t,e,s);if(J.isScalar(e))return n.Scalar?.(t,e,s);if(J.isAlias(e))return n.Alias?.(t,e,s)}function sa(t,e,n){let s=e[e.length-1];if(J.isCollection(s))s.items[t]=n;else if(J.isPair(s))t==="key"?s.key=n:s.value=n;else if(J.isDocument(s))s.contents=n;else{let r=J.isAlias(s)?"alias":"scalar";throw new Error(`Cannot replace node with ${r} parent`)}}Sr.visit=Un;Sr.visitAsync=Gn});var vr=E(ia=>{"use strict";p();var ra=B(),od=Dt(),ad={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},cd=t=>t.replace(/[!,[\]{}]/g,e=>ad[e]),Bt=class t{constructor(e,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,n)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,n){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let s=e.trim().split(/[ \t]+/),r=s.shift();switch(r){case"%TAG":{if(s.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),s.length<2))return!1;let[i,o]=s;return this.tags[i]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,s.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[i]=s;if(i==="1.1"||i==="1.2")return this.yaml.version=i,!0;{let o=/^\d+\.\d+$/.test(i);return n(6,`Unsupported YAML version ${i}`,o),!1}}default:return n(0,`Unknown directive ${r}`,!0),!1}}tagName(e,n){if(e==="!")return"!";if(e[0]!=="!")return n(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(n(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&n("Verbatim tags must end with a >"),o)}let[,s,r]=e.match(/^(.*!)([^!]*)$/s);r||n(`The ${e} tag has no suffix`);let i=this.tags[s];if(i)try{return i+decodeURIComponent(r)}catch(o){return n(String(o)),null}return s==="!"?e:(n(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[n,s]of Object.entries(this.tags))if(e.startsWith(s))return n+cd(e.substring(s.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],s=Object.entries(this.tags),r;if(e&&s.length>0&&ra.isNode(e.contents)){let i={};od.visit(e.contents,(o,a)=>{ra.isNode(a)&&a.tag&&(i[a.tag]=!0)}),r=Object.keys(i)}else r=[];for(let[i,o]of s)i==="!!"&&o==="tag:yaml.org,2002:"||(!e||r.some(a=>a.startsWith(o)))&&n.push(`%TAG ${i} ${o}`);return n.join(`
4
+ `)}};Bt.defaultYaml={explicit:!1,version:"1.2"};Bt.defaultTags={"!!":"tag:yaml.org,2002:"};ia.Directives=Bt});var Fn=E(Ut=>{"use strict";p();var oa=B(),ld=Dt();function ud(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(n)}return!0}function aa(t){let e=new Set;return ld.visit(t,{Value(n,s){s.anchor&&e.add(s.anchor)}}),e}function ca(t,e){for(let n=1;;++n){let s=`${t}${n}`;if(!e.has(s))return s}}function fd(t,e){let n=[],s=new Map,r=null;return{onAnchor:i=>{n.push(i),r??(r=aa(t));let o=ca(e,r);return r.add(o),o},setAnchors:()=>{for(let i of n){let o=s.get(i);if(typeof o=="object"&&o.anchor&&(oa.isScalar(o.node)||oa.isCollection(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=i,a}}},sourceObjects:s}}Ut.anchorIsValid=ud;Ut.anchorNames=aa;Ut.createNodeAnchors=fd;Ut.findNewAnchor=ca});var Ar=E(la=>{"use strict";p();function Gt(t,e,n,s){if(s&&typeof s=="object")if(Array.isArray(s))for(let r=0,i=s.length;r<i;++r){let o=s[r],a=Gt(t,s,String(r),o);a===void 0?delete s[r]:a!==o&&(s[r]=a)}else if(s instanceof Map)for(let r of Array.from(s.keys())){let i=s.get(r),o=Gt(t,s,r,i);o===void 0?s.delete(r):o!==i&&s.set(r,o)}else if(s instanceof Set)for(let r of Array.from(s)){let i=Gt(t,s,r,r);i===void 0?s.delete(r):i!==r&&(s.delete(r),s.add(i))}else for(let[r,i]of Object.entries(s)){let o=Gt(t,s,r,i);o===void 0?delete s[r]:o!==i&&(s[r]=o)}return t.call(e,n,s)}la.applyReviver=Gt});var Pe=E(fa=>{"use strict";p();var dd=B();function ua(t,e,n){if(Array.isArray(t))return t.map((s,r)=>ua(s,String(r),n));if(t&&typeof t.toJSON=="function"){if(!n||!dd.hasAnchor(t))return t.toJSON(e,n);let s={aliasCount:0,count:1,res:void 0};n.anchors.set(t,s),n.onCreate=i=>{s.res=i,delete n.onCreate};let r=t.toJSON(e,n);return n.onCreate&&n.onCreate(r),r}return typeof t=="bigint"&&!n?.keep?Number(t):t}fa.toJS=ua});var Wn=E(pa=>{"use strict";p();var pd=Ar(),da=B(),hd=Pe(),Er=class{constructor(e){Object.defineProperty(this,da.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:n,maxAliasCount:s,onAnchor:r,reviver:i}={}){if(!da.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof s=="number"?s:100},a=hd.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:l}of o.anchors.values())r(l,c);return typeof i=="function"?pd.applyReviver(i,{"":a},"",a):a}};pa.NodeBase=Er});var Ft=E(ha=>{"use strict";p();var gd=Fn(),md=Dt(),ft=B(),yd=Wn(),wd=Pe(),_r=class extends yd.NodeBase{constructor(e){super(ft.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,n){let s;n?.aliasResolveCache?s=n.aliasResolveCache:(s=[],md.visit(e,{Node:(i,o)=>{(ft.isAlias(o)||ft.hasAnchor(o))&&s.push(o)}}),n&&(n.aliasResolveCache=s));let r;for(let i of s){if(i===this)break;i.anchor===this.source&&(r=i)}return r}toJSON(e,n){if(!n)return{source:this.source};let{anchors:s,doc:r,maxAliasCount:i}=n,o=this.resolve(r,n);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=s.get(o);if(a||(wd.toJS(o,null,n),a=s.get(o)),!a||a.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(i>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Yn(r,o,s)),a.count*a.aliasCount>i)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,n,s){let r=`*${this.source}`;if(e){if(gd.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(i)}if(e.implicitKey)return`${r} `}return r}};function Yn(t,e,n){if(ft.isAlias(e)){let s=e.resolve(t),r=n&&s&&n.get(s);return r?r.count*r.aliasCount:0}else if(ft.isCollection(e)){let s=0;for(let r of e.items){let i=Yn(t,r,n);i>s&&(s=i)}return s}else if(ft.isPair(e)){let s=Yn(t,e.key,n),r=Yn(t,e.value,n);return Math.max(s,r)}return 1}ha.Alias=_r});var Y=E(Cr=>{"use strict";p();var bd=B(),kd=Wn(),$d=Pe(),Sd=t=>!t||typeof t!="function"&&typeof t!="object",je=class extends kd.NodeBase{constructor(e){super(bd.SCALAR),this.value=e}toJSON(e,n){return n?.keep?this.value:$d.toJS(this.value,e,n)}toString(){return String(this.value)}};je.BLOCK_FOLDED="BLOCK_FOLDED";je.BLOCK_LITERAL="BLOCK_LITERAL";je.PLAIN="PLAIN";je.QUOTE_DOUBLE="QUOTE_DOUBLE";je.QUOTE_SINGLE="QUOTE_SINGLE";Cr.Scalar=je;Cr.isScalarValue=Sd});var Wt=E(ma=>{"use strict";p();var vd=Ft(),Qe=B(),ga=Y(),Ad="tag:yaml.org,2002:";function Ed(t,e,n){if(e){let s=n.filter(i=>i.tag===e),r=s.find(i=>!i.format)??s[0];if(!r)throw new Error(`Tag ${e} not found`);return r}return n.find(s=>s.identify?.(t)&&!s.format)}function _d(t,e,n){if(Qe.isDocument(t)&&(t=t.contents),Qe.isNode(t))return t;if(Qe.isPair(t)){let u=n.schema[Qe.MAP].createNode?.(n.schema,null,n);return u.items.push(t),u}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:s,onAnchor:r,onTagObj:i,schema:o,sourceObjects:a}=n,c;if(s&&t&&typeof t=="object"){if(c=a.get(t),c)return c.anchor??(c.anchor=r(t)),new vd.Alias(c.anchor);c={anchor:null,node:null},a.set(t,c)}e?.startsWith("!!")&&(e=Ad+e.slice(2));let l=Ed(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let u=new ga.Scalar(t);return c&&(c.node=u),u}l=t instanceof Map?o[Qe.MAP]:Symbol.iterator in Object(t)?o[Qe.SEQ]:o[Qe.MAP]}i&&(i(l),delete n.onTagObj);let h=l?.createNode?l.createNode(n.schema,t,n):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(n.schema,t,n):new ga.Scalar(t);return e?h.tag=e:l.default||(h.tag=l.tag),c&&(c.node=h),h}ma.createNode=_d});var Jn=E(Vn=>{"use strict";p();var Cd=Wt(),we=B(),Nd=Wn();function Nr(t,e,n){let s=n;for(let r=e.length-1;r>=0;--r){let i=e[r];if(typeof i=="number"&&Number.isInteger(i)&&i>=0){let o=[];o[i]=s,s=o}else s=new Map([[i,s]])}return Cd.createNode(s,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var ya=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,Tr=class extends Nd.NodeBase{constructor(e,n){super(e),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(e){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(n.schema=e),n.items=n.items.map(s=>we.isNode(s)||we.isPair(s)?s.clone(e):s),this.range&&(n.range=this.range.slice()),n}addIn(e,n){if(ya(e))this.add(n);else{let[s,...r]=e,i=this.get(s,!0);if(we.isCollection(i))i.addIn(r,n);else if(i===void 0&&this.schema)this.set(s,Nr(this.schema,r,n));else throw new Error(`Expected YAML collection at ${s}. Remaining path: ${r}`)}}deleteIn(e){let[n,...s]=e;if(s.length===0)return this.delete(n);let r=this.get(n,!0);if(we.isCollection(r))return r.deleteIn(s);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}getIn(e,n){let[s,...r]=e,i=this.get(s,!0);return r.length===0?!n&&we.isScalar(i)?i.value:i:we.isCollection(i)?i.getIn(r,n):void 0}hasAllNullValues(e){return this.items.every(n=>{if(!we.isPair(n))return!1;let s=n.value;return s==null||e&&we.isScalar(s)&&s.value==null&&!s.commentBefore&&!s.comment&&!s.tag})}hasIn(e){let[n,...s]=e;if(s.length===0)return this.has(n);let r=this.get(n,!0);return we.isCollection(r)?r.hasIn(s):!1}setIn(e,n){let[s,...r]=e;if(r.length===0)this.set(s,n);else{let i=this.get(s,!0);if(we.isCollection(i))i.setIn(r,n);else if(i===void 0&&this.schema)this.set(s,Nr(this.schema,r,n));else throw new Error(`Expected YAML collection at ${s}. Remaining path: ${r}`)}}};Vn.Collection=Tr;Vn.collectionFromPath=Nr;Vn.isEmptyPath=ya});var Yt=E(zn=>{"use strict";p();var Td=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function Or(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var Od=(t,e,n)=>t.endsWith(`
5
+ `)?Or(n,e):n.includes(`
6
6
  `)?`
7
- `+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!==`
7
+ `+Or(n,e):(t.endsWith(" ")?"":" ")+n;zn.indentComment=Or;zn.lineComment=Od;zn.stringifyComment=Td});var ba=E(Vt=>{"use strict";p();var Id="flow",Ir="block",Hn="quoted";function Pd(t,e,n="flow",{indentAtStart:s,lineWidth:r=80,minContentWidth:i=20,onFold:o,onOverflow:a}={}){if(!r||r<0)return t;r<i&&(i=0);let c=Math.max(1+i,1+r-e.length);if(t.length<=c)return t;let l=[],h={},u=r-e.length;typeof s=="number"&&(s>r-Math.max(2,i)?l.push(0):u=r-s);let f,d,m=!1,g=-1,y=-1,S=-1;n===Ir&&(g=wa(t,g,e.length),g!==-1&&(u=g+c));for(let O;O=t[g+=1];){if(n===Hn&&O==="\\"){switch(y=g,t[g+1]){case"x":g+=3;break;case"u":g+=5;break;case"U":g+=9;break;default:g+=1}S=g}if(O===`
8
+ `)n===Ir&&(g=wa(t,g,e.length)),u=g+e.length+c,f=void 0;else{if(O===" "&&d&&d!==" "&&d!==`
9
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)+`
10
+ `&&$!==" "&&(f=g)}if(g>=u)if(f)l.push(f),u=f+c,f=void 0;else if(n===Hn){for(;d===" "||d===" ";)d=O,O=t[g+=1],m=!0;let $=g>S+1?g-2:y-1;if(h[$])return t;l.push($),h[$]=!0,u=$+c,f=void 0}else m=!0}d=O}if(m&&a&&a(),l.length===0)return t;o&&o();let C=t.slice(0,l[0]);for(let O=0;O<l.length;++O){let $=l[O],T=l[O+1]||t.length;$===0?C=`
11
+ ${e}${t.slice(0,T)}`:(n===Hn&&h[$]&&(C+=`${t[$]}\\`),C+=`
12
+ ${e}${t.slice($+1,T)}`)}return C}function wa(t,e,n){let s=e,r=e+1,i=t[r];for(;i===" "||i===" ";)if(e<r+n)i=t[++e];else{do i=t[++e];while(i&&i!==`
13
+ `);s=e,r=e+1,i=t[r]}return s}Vt.FOLD_BLOCK=Ir;Vt.FOLD_FLOW=Id;Vt.FOLD_QUOTED=Hn;Vt.foldFlowLines=Pd});var zt=E(ka=>{"use strict";p();var fe=Y(),Re=ba(),Zn=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),Xn=t=>/^(%|---|\.\.\.)/m.test(t);function jd(t,e,n){if(!e||e<0)return!1;let s=e-n,r=t.length;if(r<=s)return!1;for(let i=0,o=0;i<r;++i)if(t[i]===`
14
+ `){if(i-o>s)return!0;if(o=i+1,r-o<=s)return!1}return!0}function Jt(t,e){let n=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return n;let{implicitKey:s}=e,r=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(Xn(t)?" ":""),o="",a=0;for(let c=0,l=n[c];l;l=n[++c])if(l===" "&&n[c+1]==="\\"&&n[c+2]==="n"&&(o+=n.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(n[c+1]){case"u":{o+=n.slice(a,c);let h=n.substr(c+2,4);switch(h){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:h.substr(0,2)==="00"?o+="\\x"+h.substr(2):o+=n.substr(c,6)}c+=5,a=c+1}break;case"n":if(s||n[c+2]==='"'||n.length<r)c+=1;else{for(o+=n.slice(a,c)+`
15
15
 
16
- `;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(`(^|(?<!
16
+ `;n[c+2]==="\\"&&n[c+3]==="n"&&n[c+4]!=='"';)o+=`
17
+ `,c+=2;o+=i,n[c+2]===" "&&(o+="\\"),c+=1,a=c+1}break;default:c+=1}return o=a?o+n.slice(a):n,s?o:Re.foldFlowLines(o,i,Re.FOLD_QUOTED,Zn(e,!1))}function Pr(t,e){if(e.options.singleQuote===!1||e.implicitKey&&t.includes(`
18
+ `)||/[ \t]\n|\n[ \t]/.test(t))return Jt(t,e);let n=e.indent||(Xn(t)?" ":""),s="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&
19
+ ${n}`)+"'";return e.implicitKey?s:Re.foldFlowLines(s,n,Re.FOLD_FLOW,Zn(e,!1))}function dt(t,e){let{singleQuote:n}=e.options,s;if(n===!1)s=Jt;else{let r=t.includes('"'),i=t.includes("'");r&&!i?s=Pr:i&&!r?s=Jt:s=n?Pr:Jt}return s(t,e)}var jr;try{jr=new RegExp(`(^|(?<!
20
20
  ))
21
21
  +(?!
22
- |$)`,"g")}catch{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?`|
22
+ |$)`,"g")}catch{jr=/\n+(?!\n|$)/g}function Qn({comment:t,type:e,value:n},s,r,i){let{blockQuote:o,commentString:a,lineWidth:c}=s.options;if(!o||/\n[\t ]+$/.test(n))return dt(n,s);let l=s.indent||(s.forceBlockIndent||Xn(n)?" ":""),h=o==="literal"?!0:o==="folded"||e===fe.Scalar.BLOCK_FOLDED?!1:e===fe.Scalar.BLOCK_LITERAL?!0:!jd(n,c,l.length);if(!n)return h?`|
23
23
  `:`>
24
- `;let u,f;for(f=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
- `&&(O=`
24
+ `;let u,f;for(f=n.length;f>0;--f){let T=n[f-1];if(T!==`
25
+ `&&T!==" "&&T!==" ")break}let d=n.substring(f),m=d.indexOf(`
26
+ `);m===-1?u="-":n===d||m!==d.length-1?(u="+",i&&i()):u="",d&&(n=n.slice(0,-d.length),d[d.length-1]===`
27
+ `&&(d=d.slice(0,-1)),d=d.replace(jr,`$&${l}`));let g=!1,y,S=-1;for(y=0;y<n.length;++y){let T=n[y];if(T===" ")g=!0;else if(T===`
28
+ `)S=y;else break}let C=n.substring(0,S<y?S+1:y);C&&(n=n.substring(C.length),C=C.replace(/\n+/g,`$&${l}`));let $=(g?l?"2":"1":"")+u;if(t&&($+=" "+a(t.replace(/ ?[\r\n]+/g," ")),r&&r()),!h){let T=n.replace(/\n+/g,`
29
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),j=!1,b=Zn(s,!0);o!=="folded"&&e!==fe.Scalar.BLOCK_FOLDED&&(b.onOverflow=()=>{j=!0});let v=Re.foldFlowLines(`${C}${T}${d}`,l,Re.FOLD_BLOCK,b);if(!j)return`>${$}
30
+ ${l}${v}`}return n=n.replace(/\n+/g,`$&${l}`),`|${$}
31
+ ${l}${C}${n}${d}`}function Rd(t,e,n,s){let{type:r,value:i}=t,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:h}=e;if(a&&i.includes(`
32
+ `)||h&&/[[\]{},]/.test(i))return dt(i,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||h||!i.includes(`
33
+ `)?dt(i,e):Qn(t,e,n,s);if(!a&&!h&&r!==fe.Scalar.PLAIN&&i.includes(`
34
+ `))return Qn(t,e,n,s);if(Xn(i)){if(c==="")return e.forceBlockIndent=!0,Qn(t,e,n,s);if(a&&c===l)return dt(i,e)}let u=i.replace(/\n+/g,`$&
35
+ ${c}`);if(o){let f=g=>g.default&&g.tag!=="tag:yaml.org,2002:str"&&g.test?.test(u),{compat:d,tags:m}=e.doc.schema;if(m.some(f)||d?.some(f))return dt(i,e)}return a?u:Re.foldFlowLines(u,c,Re.FOLD_FLOW,Zn(e,!1))}function Ld(t,e,n,s){let{implicitKey:r,inFlow:i}=e,o=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:a}=t;a!==fe.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=fe.Scalar.QUOTE_DOUBLE);let c=h=>{switch(h){case fe.Scalar.BLOCK_FOLDED:case fe.Scalar.BLOCK_LITERAL:return r||i?dt(o.value,e):Qn(o,e,n,s);case fe.Scalar.QUOTE_DOUBLE:return Jt(o.value,e);case fe.Scalar.QUOTE_SINGLE:return Pr(o.value,e);case fe.Scalar.PLAIN:return Rd(o,e,n,s);default:return null}},l=c(a);if(l===null){let{defaultKeyType:h,defaultStringType:u}=e.options,f=r&&h||u;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}ka.stringifyString=Ld});var Ht=E(Rr=>{"use strict";p();var xd=Fn(),Le=B(),qd=Yt(),Md=zt();function Kd(t,e){let n=Object.assign({blockQuote:!0,commentString:qd.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trueStr:"true",verifyAliasOrder:!0},t.schema.toStringOptions,e),s;switch(n.collectionStyle){case"block":s=!1;break;case"flow":s=!0;break;default:s=null}return{anchors:new Set,doc:t,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:s,options:n}}function Dd(t,e){if(e.tag){let r=t.filter(i=>i.tag===e.tag);if(r.length>0)return r.find(i=>i.format===e.format)??r[0]}let n,s;if(Le.isScalar(e)){s=e.value;let r=t.filter(i=>i.identify?.(s));if(r.length>1){let i=r.filter(o=>o.test);i.length>0&&(r=i)}n=r.find(i=>i.format===e.format)??r.find(i=>!i.format)}else s=e,n=t.find(r=>r.nodeClass&&s instanceof r.nodeClass);if(!n){let r=s?.constructor?.name??(s===null?"null":typeof s);throw new Error(`Tag not resolved for ${r} value`)}return n}function Bd(t,e,{anchors:n,doc:s}){if(!s.directives)return"";let r=[],i=(Le.isScalar(t)||Le.isCollection(t))&&t.anchor;i&&xd.anchorIsValid(i)&&(n.add(i),r.push(`&${i}`));let o=t.tag??(e.default?null:e.tag);return o&&r.push(s.directives.tagString(o)),r.join(" ")}function Ud(t,e,n,s){if(Le.isPair(t))return t.toString(e,n,s);if(Le.isAlias(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let r,i=Le.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>r=c});r??(r=Dd(e.doc.schema.tags,i));let o=Bd(i,r,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let a=typeof r.stringify=="function"?r.stringify(i,e,n,s):Le.isScalar(i)?Md.stringifyString(i,e,n,s):i.toString(e,n,s);return o?Le.isScalar(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
36
+ ${e.indent}${a}`:a}Rr.createStringifyContext=Kd;Rr.stringify=Ud});var Aa=E(va=>{"use strict";p();var Ae=B(),$a=Y(),Sa=Ht(),Qt=Yt();function Gd({key:t,value:e},n,s,r){let{allNullValues:i,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:h,simpleKeys:u}}=n,f=Ae.isNode(t)&&t.comment||null;if(u){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(Ae.isCollection(t)||!Ae.isNode(t)&&typeof t=="object"){let b="With simple keys, collection cannot be used as a key value";throw new Error(b)}}let d=!u&&(!t||f&&e==null&&!n.inFlow||Ae.isCollection(t)||(Ae.isScalar(t)?t.type===$a.Scalar.BLOCK_FOLDED||t.type===$a.Scalar.BLOCK_LITERAL:typeof t=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!d&&(u||!i),indent:a+c});let m=!1,g=!1,y=Sa.stringify(t,n,()=>m=!0,()=>g=!0);if(!d&&!n.inFlow&&y.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");d=!0}if(n.inFlow){if(i||e==null)return m&&s&&s(),y===""?"?":d?`? ${y}`:y}else if(i&&!u||e==null&&d)return y=`? ${y}`,f&&!m?y+=Qt.lineComment(y,n.indent,l(f)):g&&r&&r(),y;m&&(f=null),d?(f&&(y+=Qt.lineComment(y,n.indent,l(f))),y=`? ${y}
37
+ ${a}:`):(y=`${y}:`,f&&(y+=Qt.lineComment(y,n.indent,l(f))));let S,C,O;Ae.isNode(e)?(S=!!e.spaceBefore,C=e.commentBefore,O=e.comment):(S=!1,C=null,O=null,e&&typeof e=="object"&&(e=o.createNode(e))),n.implicitKey=!1,!d&&!f&&Ae.isScalar(e)&&(n.indentAtStart=y.length+1),g=!1,!h&&c.length>=2&&!n.inFlow&&!d&&Ae.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(n.indent=n.indent.substring(2));let $=!1,T=Sa.stringify(e,n,()=>$=!0,()=>g=!0),j=" ";if(f||S||C){if(j=S?`
38
+ `:"",C){let b=l(C);j+=`
39
+ ${Qt.indentComment(b,n.indent)}`}T===""&&!n.inFlow?j===`
40
+ `&&(j=`
41
41
 
42
- `):O+=`
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?`
42
+ `):j+=`
43
+ ${n.indent}`}else if(!d&&Ae.isCollection(e)){let b=T[0],v=T.indexOf(`
44
+ `),K=v!==-1,I=n.inFlow??e.flow??e.items.length===0;if(K||!I){let R=!1;if(K&&(b==="&"||b==="!")){let q=T.indexOf(" ");b==="&"&&q!==-1&&q<v&&T[q+1]==="!"&&(q=T.indexOf(" ",q+1)),(q===-1||v<q)&&(R=!0)}R||(j=`
45
+ ${n.indent}`)}}else(T===""||T[0]===`
46
+ `)&&(j="");return y+=j+T,n.inFlow?$&&s&&s():O&&!$?y+=Qt.lineComment(y,n.indent,l(O)):g&&r&&r(),y}va.stringifyPair=Gd});var xr=E(Lr=>{"use strict";p();var Ea=jn("process");function Fd(t,...e){t==="debug"&&console.log(...e)}function Wd(t,e){(t==="debug"||t==="warn")&&(typeof Ea.emitWarning=="function"?Ea.emitWarning(e):console.warn(e))}Lr.debug=Fd;Lr.warn=Wd});var ss=E(ns=>{"use strict";p();var Zt=B(),_a=Y(),es="<<",ts={identify:t=>t===es||typeof t=="symbol"&&t.description===es,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new _a.Scalar(Symbol(es)),{addToJSMap:Ca}),stringify:()=>es},Yd=(t,e)=>(ts.identify(e)||Zt.isScalar(e)&&(!e.type||e.type===_a.Scalar.PLAIN)&&ts.identify(e.value))&&t?.doc.schema.tags.some(n=>n.tag===ts.tag&&n.default);function Ca(t,e,n){if(n=t&&Zt.isAlias(n)?n.resolve(t.doc):n,Zt.isSeq(n))for(let s of n.items)qr(t,e,s);else if(Array.isArray(n))for(let s of n)qr(t,e,s);else qr(t,e,n)}function qr(t,e,n){let s=t&&Zt.isAlias(n)?n.resolve(t.doc):n;if(!Zt.isMap(s))throw new Error("Merge sources must be maps or map aliases");let r=s.toJSON(null,t,Map);for(let[i,o]of r)e instanceof Map?e.has(i)||e.set(i,o):e instanceof Set?e.add(i):Object.prototype.hasOwnProperty.call(e,i)||Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}ns.addMergeToJSMap=Ca;ns.isMergeKey=Yd;ns.merge=ts});var Kr=E(Oa=>{"use strict";p();var Vd=xr(),Na=ss(),Jd=Ht(),Ta=B(),Mr=Pe();function zd(t,e,{key:n,value:s}){if(Ta.isNode(n)&&n.addToJSMap)n.addToJSMap(t,e,s);else if(Na.isMergeKey(t,n))Na.addMergeToJSMap(t,e,s);else{let r=Mr.toJS(n,"",t);if(e instanceof Map)e.set(r,Mr.toJS(s,r,t));else if(e instanceof Set)e.add(r);else{let i=Hd(n,r,t),o=Mr.toJS(s,i,t);i in e?Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[i]=o}}return e}function Hd(t,e,n){if(e===null)return"";if(typeof e!="object")return String(e);if(Ta.isNode(t)&&n?.doc){let s=Jd.createStringifyContext(n.doc,{});s.anchors=new Set;for(let i of n.anchors.keys())s.anchors.add(i.anchor);s.inFlow=!0,s.inStringifyKey=!0;let r=t.toString(s);if(!n.mapKeyWarned){let i=JSON.stringify(r);i.length>40&&(i=i.substring(0,36)+'..."'),Vd.warn(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${i}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(e)}Oa.addPairToJSMap=zd});var xe=E(Dr=>{"use strict";p();var Ia=Wt(),Qd=Aa(),Zd=Kr(),rs=B();function Xd(t,e,n){let s=Ia.createNode(t,void 0,n),r=Ia.createNode(e,void 0,n);return new is(s,r)}var is=class t{constructor(e,n=null){Object.defineProperty(this,rs.NODE_TYPE,{value:rs.PAIR}),this.key=e,this.value=n}clone(e){let{key:n,value:s}=this;return rs.isNode(n)&&(n=n.clone(e)),rs.isNode(s)&&(s=s.clone(e)),new t(n,s)}toJSON(e,n){let s=n?.mapAsMap?new Map:{};return Zd.addPairToJSMap(n,s,this)}toString(e,n,s){return e?.doc?Qd.stringifyPair(this,e,n,s):JSON.stringify(this)}};Dr.Pair=is;Dr.createPair=Xd});var Br=E(ja=>{"use strict";p();var Ze=B(),Pa=Ht(),os=Yt();function ep(t,e,n){return(e.inFlow??t.flow?np:tp)(t,e,n)}function tp({comment:t,items:e},n,{blockItemPrefix:s,flowChars:r,itemIndent:i,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=n,h=Object.assign({},n,{indent:i,type:null}),u=!1,f=[];for(let m=0;m<e.length;++m){let g=e[m],y=null;if(Ze.isNode(g))!u&&g.spaceBefore&&f.push(""),as(n,f,g.commentBefore,u),g.comment&&(y=g.comment);else if(Ze.isPair(g)){let C=Ze.isNode(g.key)?g.key:null;C&&(!u&&C.spaceBefore&&f.push(""),as(n,f,C.commentBefore,u))}u=!1;let S=Pa.stringify(g,h,()=>y=null,()=>u=!0);y&&(S+=os.lineComment(S,i,l(y))),u&&y&&(u=!1),f.push(s+S)}let d;if(f.length===0)d=r.start+r.end;else{d=f[0];for(let m=1;m<f.length;++m){let g=f[m];d+=g?`
47
47
  ${c}${g}`:`
48
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?`
49
+ `+os.indentComment(l(t),c),a&&a()):u&&o&&o(),d}function np({items:t},e,{flowChars:n,itemIndent:s}){let{indent:r,indentStep:i,flowCollectionPadding:o,options:{commentString:a}}=e;s+=i;let c=Object.assign({},e,{indent:s,inFlow:!0,type:null}),l=!1,h=0,u=[];for(let m=0;m<t.length;++m){let g=t[m],y=null;if(Ze.isNode(g))g.spaceBefore&&u.push(""),as(e,u,g.commentBefore,!1),g.comment&&(y=g.comment);else if(Ze.isPair(g)){let C=Ze.isNode(g.key)?g.key:null;C&&(C.spaceBefore&&u.push(""),as(e,u,C.commentBefore,!1),C.comment&&(l=!0));let O=Ze.isNode(g.value)?g.value:null;O?(O.comment&&(y=O.comment),O.commentBefore&&(l=!0)):g.value==null&&C?.comment&&(y=C.comment)}y&&(l=!0);let S=Pa.stringify(g,c,()=>y=null);m<t.length-1&&(S+=","),y&&(S+=os.lineComment(S,s,a(y))),!l&&(u.length>h||S.includes(`
50
+ `))&&(l=!0),u.push(S),h=u.length}let{start:f,end:d}=n;if(u.length===0)return f+d;if(!l){let m=u.reduce((g,y)=>g+y.length+2,2);l=e.options.lineWidth>0&&m>e.options.lineWidth}if(l){let m=f;for(let g of u)m+=g?`
51
51
  ${i}${r}${g}`:`
52
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(`
53
+ ${r}${d}`}else return`${f}${o}${u.join(" ")}${o}${d}`}function as({indent:t,options:{commentString:e}},n,s,r){if(s&&r&&(s=s.replace(/^\n+/,"")),s){let i=os.indentComment(e(s),t);n.push(i.trimStart())}}ja.stringifyCollection=ep});var Me=E(Gr=>{"use strict";p();var sp=Br(),rp=Kr(),ip=Jn(),qe=B(),cs=xe(),op=Y();function Xt(t,e){let n=qe.isScalar(e)?e.value:e;for(let s of t)if(qe.isPair(s)&&(s.key===e||s.key===n||qe.isScalar(s.key)&&s.key.value===n))return s}var Ur=class extends ip.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(qe.MAP,e),this.items=[]}static from(e,n,s){let{keepUndefined:r,replacer:i}=s,o=new this(e),a=(c,l)=>{if(typeof i=="function")l=i.call(n,c,l);else if(Array.isArray(i)&&!i.includes(c))return;(l!==void 0||r)&&o.items.push(cs.createPair(c,l,s))};if(n instanceof Map)for(let[c,l]of n)a(c,l);else if(n&&typeof n=="object")for(let c of Object.keys(n))a(c,n[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,n){let s;qe.isPair(e)?s=e:!e||typeof e!="object"||!("key"in e)?s=new cs.Pair(e,e?.value):s=new cs.Pair(e.key,e.value);let r=Xt(this.items,s.key),i=this.schema?.sortMapEntries;if(r){if(!n)throw new Error(`Key ${s.key} already set`);qe.isScalar(r.value)&&op.isScalarValue(s.value)?r.value.value=s.value:r.value=s.value}else if(i){let o=this.items.findIndex(a=>i(s,a)<0);o===-1?this.items.push(s):this.items.splice(o,0,s)}else this.items.push(s)}delete(e){let n=Xt(this.items,e);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(e,n){let r=Xt(this.items,e)?.value;return(!n&&qe.isScalar(r)?r.value:r)??void 0}has(e){return!!Xt(this.items,e)}set(e,n){this.add(new cs.Pair(e,n),!0)}toJSON(e,n,s){let r=s?new s:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(r);for(let i of this.items)rp.addPairToJSMap(n,r,i);return r}toString(e,n,s){if(!e)return JSON.stringify(this);for(let r of this.items)if(!qe.isPair(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),sp.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:s,onComment:n})}};Gr.YAMLMap=Ur;Gr.findPair=Xt});var pt=E(La=>{"use strict";p();var ap=B(),Ra=Me(),cp={collection:"map",default:!0,nodeClass:Ra.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return ap.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,n)=>Ra.YAMLMap.from(t,e,n)};La.map=cp});var Ke=E(xa=>{"use strict";p();var lp=Wt(),up=Br(),fp=Jn(),us=B(),dp=Y(),pp=Pe(),Fr=class extends fp.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(us.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let n=ls(e);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(e,n){let s=ls(e);if(typeof s!="number")return;let r=this.items[s];return!n&&us.isScalar(r)?r.value:r}has(e){let n=ls(e);return typeof n=="number"&&n<this.items.length}set(e,n){let s=ls(e);if(typeof s!="number")throw new Error(`Expected a valid index, not ${e}.`);let r=this.items[s];us.isScalar(r)&&dp.isScalarValue(n)?r.value=n:this.items[s]=n}toJSON(e,n){let s=[];n?.onCreate&&n.onCreate(s);let r=0;for(let i of this.items)s.push(pp.toJS(i,String(r++),n));return s}toString(e,n,s){return e?up.stringifyCollection(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:s,onComment:n}):JSON.stringify(this)}static from(e,n,s){let{replacer:r}=s,i=new this(e);if(n&&Symbol.iterator in Object(n)){let o=0;for(let a of n){if(typeof r=="function"){let c=n instanceof Set?a:String(o++);a=r.call(n,c,a)}i.items.push(lp.createNode(a,void 0,s))}}return i}};function ls(t){let e=us.isScalar(t)?t.value:t;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}xa.YAMLSeq=Fr});var ht=E(Ma=>{"use strict";p();var hp=B(),qa=Ke(),gp={collection:"seq",default:!0,nodeClass:qa.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return hp.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,n)=>qa.YAMLSeq.from(t,e,n)};Ma.seq=gp});var en=E(Ka=>{"use strict";p();var mp=zt(),yp={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,n,s){return e=Object.assign({actualString:!0},e),mp.stringifyString(t,e,n,s)}};Ka.string=yp});var fs=E(Ua=>{"use strict";p();var Da=Y(),Ba={identify:t=>t==null,createNode:()=>new Da.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Da.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&Ba.test.test(t)?t:e.options.nullStr};Ua.nullTag=Ba});var Wr=E(Fa=>{"use strict";p();var wp=Y(),Ga={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new wp.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},n){if(t&&Ga.test.test(t)){let s=t[0]==="t"||t[0]==="T";if(e===s)return t}return e?n.options.trueStr:n.options.falseStr}};Fa.boolTag=Ga});var gt=E(Wa=>{"use strict";p();function bp({format:t,minFractionDigits:e,tag:n,value:s}){if(typeof s=="bigint")return String(s);let r=typeof s=="number"?s:Number(s);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let i=JSON.stringify(s);if(!t&&e&&(!n||n==="tag:yaml.org,2002:float")&&/^\d/.test(i)){let o=i.indexOf(".");o<0&&(o=i.length,i+=".");let a=e-(i.length-o-1);for(;a-- >0;)i+="0"}return i}Wa.stringifyNumber=bp});var Vr=E(ds=>{"use strict";p();var kp=Y(),Yr=gt(),$p={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Yr.stringifyNumber},Sp={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():Yr.stringifyNumber(t)}},vp={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new kp.Scalar(parseFloat(t)),n=t.indexOf(".");return n!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-n-1),e},stringify:Yr.stringifyNumber};ds.float=vp;ds.floatExp=Sp;ds.floatNaN=$p});var zr=E(hs=>{"use strict";p();var Ya=gt(),ps=t=>typeof t=="bigint"||Number.isInteger(t),Jr=(t,e,n,{intAsBigInt:s})=>s?BigInt(t):parseInt(t.substring(e),n);function Va(t,e,n){let{value:s}=t;return ps(s)&&s>=0?n+s.toString(e):Ya.stringifyNumber(t)}var Ap={identify:t=>ps(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,n)=>Jr(t,2,8,n),stringify:t=>Va(t,8,"0o")},Ep={identify:ps,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,n)=>Jr(t,0,10,n),stringify:Ya.stringifyNumber},_p={identify:t=>ps(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,n)=>Jr(t,2,16,n),stringify:t=>Va(t,16,"0x")};hs.int=Ep;hs.intHex=_p;hs.intOct=Ap});var za=E(Ja=>{"use strict";p();var Cp=pt(),Np=fs(),Tp=ht(),Op=en(),Ip=Wr(),Hr=Vr(),Qr=zr(),Pp=[Cp.map,Tp.seq,Op.string,Np.nullTag,Ip.boolTag,Qr.intOct,Qr.int,Qr.intHex,Hr.floatNaN,Hr.floatExp,Hr.float];Ja.schema=Pp});var Za=E(Qa=>{"use strict";p();var jp=Y(),Rp=pt(),Lp=ht();function Ha(t){return typeof t=="bigint"||Number.isInteger(t)}var gs=({value:t})=>JSON.stringify(t),xp=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:gs},{identify:t=>t==null,createNode:()=>new jp.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:gs},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:gs},{identify:Ha,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:n})=>n?BigInt(t):parseInt(t,10),stringify:({value:t})=>Ha(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:gs}],qp={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},Mp=[Rp.map,Lp.seq].concat(xp,qp);Qa.schema=Mp});var Xr=E(Xa=>{"use strict";p();var tn=jn("buffer"),Zr=Y(),Kp=zt(),Dp={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof tn.Buffer=="function")return tn.Buffer.from(t,"base64");if(typeof atob=="function"){let n=atob(t.replace(/[\n\r]/g,"")),s=new Uint8Array(n.length);for(let r=0;r<n.length;++r)s[r]=n.charCodeAt(r);return s}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),t},stringify({comment:t,type:e,value:n},s,r,i){if(!n)return"";let o=n,a;if(typeof tn.Buffer=="function")a=o instanceof tn.Buffer?o.toString("base64"):tn.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[l]);a=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=Zr.Scalar.BLOCK_LITERAL),e!==Zr.Scalar.QUOTE_DOUBLE){let c=Math.max(s.options.lineWidth-s.indent.length,s.options.minContentWidth),l=Math.ceil(a.length/c),h=new Array(l);for(let u=0,f=0;u<l;++u,f+=c)h[u]=a.substr(f,c);a=h.join(e===Zr.Scalar.BLOCK_LITERAL?`
54
+ `:" ")}return Kp.stringifyString({comment:t,type:e,value:a},s,r,i)}};Xa.binary=Dp});var ws=E(ys=>{"use strict";p();var ms=B(),ei=xe(),Bp=Y(),Up=Ke();function ec(t,e){if(ms.isSeq(t))for(let n=0;n<t.items.length;++n){let s=t.items[n];if(!ms.isPair(s)){if(ms.isMap(s)){s.items.length>1&&e("Each pair must have its own sequence indicator");let r=s.items[0]||new ei.Pair(new Bp.Scalar(null));if(s.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${s.commentBefore}
55
+ ${r.key.commentBefore}`:s.commentBefore),s.comment){let i=r.value??r.key;i.comment=i.comment?`${s.comment}
56
+ ${i.comment}`:s.comment}s=r}t.items[n]=ms.isPair(s)?s:new ei.Pair(s)}}else e("Expected a sequence for this tag");return t}function tc(t,e,n){let{replacer:s}=n,r=new Up.YAMLSeq(t);r.tag="tag:yaml.org,2002:pairs";let i=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof s=="function"&&(o=s.call(e,String(i++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;r.items.push(ei.createPair(a,c,n))}return r}var Gp={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:ec,createNode:tc};ys.createPairs=tc;ys.pairs=Gp;ys.resolvePairs=ec});var si=E(ni=>{"use strict";p();var nc=B(),ti=Pe(),nn=Me(),Fp=Ke(),sc=ws(),Xe=class t extends Fp.YAMLSeq{constructor(){super(),this.add=nn.YAMLMap.prototype.add.bind(this),this.delete=nn.YAMLMap.prototype.delete.bind(this),this.get=nn.YAMLMap.prototype.get.bind(this),this.has=nn.YAMLMap.prototype.has.bind(this),this.set=nn.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,n){if(!n)return super.toJSON(e);let s=new Map;n?.onCreate&&n.onCreate(s);for(let r of this.items){let i,o;if(nc.isPair(r)?(i=ti.toJS(r.key,"",n),o=ti.toJS(r.value,i,n)):i=ti.toJS(r,"",n),s.has(i))throw new Error("Ordered maps must not include duplicate keys");s.set(i,o)}return s}static from(e,n,s){let r=sc.createPairs(e,n,s),i=new this;return i.items=r.items,i}};Xe.tag="tag:yaml.org,2002:omap";var Wp={collection:"seq",identify:t=>t instanceof Map,nodeClass:Xe,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let n=sc.resolvePairs(t,e),s=[];for(let{key:r}of n.items)nc.isScalar(r)&&(s.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):s.push(r.value));return Object.assign(new Xe,n)},createNode:(t,e,n)=>Xe.from(t,e,n)};ni.YAMLOMap=Xe;ni.omap=Wp});var cc=E(ri=>{"use strict";p();var rc=Y();function ic({value:t,source:e},n){return e&&(t?oc:ac).test.test(e)?e:t?n.options.trueStr:n.options.falseStr}var oc={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new rc.Scalar(!0),stringify:ic},ac={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new rc.Scalar(!1),stringify:ic};ri.falseTag=ac;ri.trueTag=oc});var lc=E(bs=>{"use strict";p();var Yp=Y(),ii=gt(),Vp={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:ii.stringifyNumber},Jp={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():ii.stringifyNumber(t)}},zp={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new Yp.Scalar(parseFloat(t.replace(/_/g,""))),n=t.indexOf(".");if(n!==-1){let s=t.substring(n+1).replace(/_/g,"");s[s.length-1]==="0"&&(e.minFractionDigits=s.length)}return e},stringify:ii.stringifyNumber};bs.float=zp;bs.floatExp=Jp;bs.floatNaN=Vp});var fc=E(rn=>{"use strict";p();var uc=gt(),sn=t=>typeof t=="bigint"||Number.isInteger(t);function ks(t,e,n,{intAsBigInt:s}){let r=t[0];if((r==="-"||r==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),s){switch(n){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let o=BigInt(t);return r==="-"?BigInt(-1)*o:o}let i=parseInt(t,n);return r==="-"?-1*i:i}function oi(t,e,n){let{value:s}=t;if(sn(s)){let r=s.toString(e);return s<0?"-"+n+r.substr(1):n+r}return uc.stringifyNumber(t)}var Hp={identify:sn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,n)=>ks(t,2,2,n),stringify:t=>oi(t,2,"0b")},Qp={identify:sn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,n)=>ks(t,1,8,n),stringify:t=>oi(t,8,"0")},Zp={identify:sn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,n)=>ks(t,0,10,n),stringify:uc.stringifyNumber},Xp={identify:sn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,n)=>ks(t,2,16,n),stringify:t=>oi(t,16,"0x")};rn.int=Zp;rn.intBin=Hp;rn.intHex=Xp;rn.intOct=Qp});var ci=E(ai=>{"use strict";p();var vs=B(),$s=xe(),Ss=Me(),et=class t extends Ss.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let n;vs.isPair(e)?n=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?n=new $s.Pair(e.key,null):n=new $s.Pair(e,null),Ss.findPair(this.items,n.key)||this.items.push(n)}get(e,n){let s=Ss.findPair(this.items,e);return!n&&vs.isPair(s)?vs.isScalar(s.key)?s.key.value:s.key:s}set(e,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let s=Ss.findPair(this.items,e);s&&!n?this.items.splice(this.items.indexOf(s),1):!s&&n&&this.items.push(new $s.Pair(e))}toJSON(e,n){return super.toJSON(e,n,Set)}toString(e,n,s){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),n,s);throw new Error("Set items must all have null values")}static from(e,n,s){let{replacer:r}=s,i=new this(e);if(n&&Symbol.iterator in Object(n))for(let o of n)typeof r=="function"&&(o=r.call(n,o,o)),i.items.push($s.createPair(o,null,s));return i}};et.tag="tag:yaml.org,2002:set";var eh={collection:"map",identify:t=>t instanceof Set,nodeClass:et,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,n)=>et.from(t,e,n),resolve(t,e){if(vs.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new et,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};ai.YAMLSet=et;ai.set=eh});var ui=E(As=>{"use strict";p();var th=gt();function li(t,e){let n=t[0],s=n==="-"||n==="+"?t.substring(1):t,r=o=>e?BigInt(o):Number(o),i=s.replace(/_/g,"").split(":").reduce((o,a)=>o*r(60)+r(a),r(0));return n==="-"?r(-1)*i:i}function dc(t){let{value:e}=t,n=o=>o;if(typeof e=="bigint")n=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return th.stringifyNumber(t);let s="";e<0&&(s="-",e*=n(-1));let r=n(60),i=[e%r];return e<60?i.unshift(0):(e=(e-i[0])/r,i.unshift(e%r),e>=60&&(e=(e-i[0])/r,i.unshift(e))),s+i.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var nh={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:n})=>li(t,n),stringify:dc},sh={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>li(t,!1),stringify:dc},pc={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){let e=t.match(pc.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,s,r,i,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(n,s-1,r,i||0,o||0,a||0,c),h=e[8];if(h&&h!=="Z"){let u=li(h,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};As.floatTime=sh;As.intTime=nh;As.timestamp=pc});var mc=E(gc=>{"use strict";p();var rh=pt(),ih=fs(),oh=ht(),ah=en(),ch=Xr(),hc=cc(),fi=lc(),Es=fc(),lh=ss(),uh=si(),fh=ws(),dh=ci(),di=ui(),ph=[rh.map,oh.seq,ah.string,ih.nullTag,hc.trueTag,hc.falseTag,Es.intBin,Es.intOct,Es.int,Es.intHex,fi.floatNaN,fi.floatExp,fi.float,ch.binary,lh.merge,uh.omap,fh.pairs,dh.set,di.intTime,di.floatTime,di.timestamp];gc.schema=ph});var _c=E(gi=>{"use strict";p();var kc=pt(),hh=fs(),$c=ht(),gh=en(),mh=Wr(),pi=Vr(),hi=zr(),yh=za(),wh=Za(),Sc=Xr(),on=ss(),vc=si(),Ac=ws(),yc=mc(),Ec=ci(),_s=ui(),wc=new Map([["core",yh.schema],["failsafe",[kc.map,$c.seq,gh.string]],["json",wh.schema],["yaml11",yc.schema],["yaml-1.1",yc.schema]]),bc={binary:Sc.binary,bool:mh.boolTag,float:pi.float,floatExp:pi.floatExp,floatNaN:pi.floatNaN,floatTime:_s.floatTime,int:hi.int,intHex:hi.intHex,intOct:hi.intOct,intTime:_s.intTime,map:kc.map,merge:on.merge,null:hh.nullTag,omap:vc.omap,pairs:Ac.pairs,seq:$c.seq,set:Ec.set,timestamp:_s.timestamp},bh={"tag:yaml.org,2002:binary":Sc.binary,"tag:yaml.org,2002:merge":on.merge,"tag:yaml.org,2002:omap":vc.omap,"tag:yaml.org,2002:pairs":Ac.pairs,"tag:yaml.org,2002:set":Ec.set,"tag:yaml.org,2002:timestamp":_s.timestamp};function kh(t,e,n){let s=wc.get(e);if(s&&!t)return n&&!s.includes(on.merge)?s.concat(on.merge):s.slice();let r=s;if(!r)if(Array.isArray(t))r=[];else{let i=Array.from(wc.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${i} or define customTags array`)}if(Array.isArray(t))for(let i of t)r=r.concat(i);else typeof t=="function"&&(r=t(r.slice()));return n&&(r=r.concat(on.merge)),r.reduce((i,o)=>{let a=typeof o=="string"?bc[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(bc).map(h=>JSON.stringify(h)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return i.includes(a)||i.push(a),i},[])}gi.coreKnownTags=bh;gi.getTags=kh});var wi=E(Cc=>{"use strict";p();var mi=B(),$h=pt(),Sh=ht(),vh=en(),Cs=_c(),Ah=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,yi=class t{constructor({compat:e,customTags:n,merge:s,resolveKnownTags:r,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Cs.getTags(e,"compat"):e?Cs.getTags(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=r?Cs.coreKnownTags:{},this.tags=Cs.getTags(n,this.name,s),this.toStringOptions=a??null,Object.defineProperty(this,mi.MAP,{value:$h.map}),Object.defineProperty(this,mi.SCALAR,{value:vh.string}),Object.defineProperty(this,mi.SEQ,{value:Sh.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Ah:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Cc.Schema=yi});var Tc=E(Nc=>{"use strict";p();var Eh=B(),bi=Ht(),an=Yt();function _h(t,e){let n=[],s=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(n.push(c),s=!0):t.directives.docStart&&(s=!0)}s&&n.push("---");let r=bi.createStringifyContext(t,e),{commentString:i}=r.options;if(t.commentBefore){n.length!==1&&n.unshift("");let c=i(t.commentBefore);n.unshift(an.indentComment(c,""))}let o=!1,a=null;if(t.contents){if(Eh.isNode(t.contents)){if(t.contents.spaceBefore&&s&&n.push(""),t.contents.commentBefore){let h=i(t.contents.commentBefore);n.push(an.indentComment(h,""))}r.forceBlockIndent=!!t.comment,a=t.contents.comment}let c=a?void 0:()=>o=!0,l=bi.stringify(t.contents,r,()=>a=null,c);a&&(l+=an.lineComment(l,"",i(a))),(l[0]==="|"||l[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${l}`:n.push(l)}else n.push(bi.stringify(t.contents,r));if(t.directives?.docEnd)if(t.comment){let c=i(t.comment);c.includes(`
57
+ `)?(n.push("..."),n.push(an.indentComment(c,""))):n.push(`... ${c}`)}else n.push("...");else{let c=t.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||a)&&n[n.length-1]!==""&&n.push(""),n.push(an.indentComment(i(c),"")))}return n.join(`
58
58
  `)+`
59
- `}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+=`:
59
+ `}Nc.stringifyDocument=_h});var cn=E(Oc=>{"use strict";p();var Ch=Ft(),mt=Jn(),ce=B(),Nh=xe(),Th=Pe(),Oh=wi(),Ih=Tc(),ki=Fn(),Ph=Ar(),jh=Wt(),$i=vr(),Si=class t{constructor(e,n,s){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ce.NODE_TYPE,{value:ce.DOC});let r=null;typeof n=="function"||Array.isArray(n)?r=n:s===void 0&&n&&(s=n,n=void 0);let i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},s);this.options=i;let{version:o}=i;s?._directives?(this.directives=s._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new $i.Directives({version:o}),this.setSchema(o,s),this.contents=e===void 0?null:this.createNode(e,r,s)}clone(){let e=Object.create(t.prototype,{[ce.NODE_TYPE]:{value:ce.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=ce.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){yt(this.contents)&&this.contents.add(e)}addIn(e,n){yt(this.contents)&&this.contents.addIn(e,n)}createAlias(e,n){if(!e.anchor){let s=ki.anchorNames(this);e.anchor=!n||s.has(n)?ki.findNewAnchor(n||"a",s):n}return new Ch.Alias(e.anchor)}createNode(e,n,s){let r;if(typeof n=="function")e=n.call({"":e},"",e),r=n;else if(Array.isArray(n)){let y=C=>typeof C=="number"||C instanceof String||C instanceof Number,S=n.filter(y).map(String);S.length>0&&(n=n.concat(S)),r=n}else s===void 0&&n&&(s=n,n=void 0);let{aliasDuplicateObjects:i,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:h}=s??{},{onAnchor:u,setAnchors:f,sourceObjects:d}=ki.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:i??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:r,schema:this.schema,sourceObjects:d},g=jh.createNode(e,h,m);return a&&ce.isCollection(g)&&(g.flow=!0),f(),g}createPair(e,n,s={}){let r=this.createNode(e,null,s),i=this.createNode(n,null,s);return new Nh.Pair(r,i)}delete(e){return yt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return mt.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):yt(this.contents)?this.contents.deleteIn(e):!1}get(e,n){return ce.isCollection(this.contents)?this.contents.get(e,n):void 0}getIn(e,n){return mt.isEmptyPath(e)?!n&&ce.isScalar(this.contents)?this.contents.value:this.contents:ce.isCollection(this.contents)?this.contents.getIn(e,n):void 0}has(e){return ce.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return mt.isEmptyPath(e)?this.contents!==void 0:ce.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,n){this.contents==null?this.contents=mt.collectionFromPath(this.schema,[e],n):yt(this.contents)&&this.contents.set(e,n)}setIn(e,n){mt.isEmptyPath(e)?this.contents=n:this.contents==null?this.contents=mt.collectionFromPath(this.schema,Array.from(e),n):yt(this.contents)&&this.contents.setIn(e,n)}setSchema(e,n={}){typeof e=="number"&&(e=String(e));let s;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new $i.Directives({version:"1.1"}),s={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new $i.Directives({version:e}),s={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,s=null;break;default:{let r=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(n.schema instanceof Object)this.schema=n.schema;else if(s)this.schema=new Oh.Schema(Object.assign(s,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:n,mapAsMap:s,maxAliasCount:r,onAnchor:i,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:s===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},c=Th.toJS(this.contents,n??"",a);if(typeof i=="function")for(let{count:l,res:h}of a.anchors.values())i(h,l);return typeof o=="function"?Ph.applyReviver(o,{"":c},"",c):c}toJSON(e,n){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:n})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let n=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return Ih.stringifyDocument(this,e)}};function yt(t){if(ce.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}Oc.Document=Si});var fn=E(un=>{"use strict";p();var ln=class extends Error{constructor(e,n,s,r){super(),this.name=e,this.code=s,this.message=r,this.pos=n}},vi=class extends ln{constructor(e,n,s){super("YAMLParseError",e,n,s)}},Ai=class extends ln{constructor(e,n,s){super("YAMLWarning",e,n,s)}},Rh=(t,e)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(a=>e.linePos(a));let{line:s,col:r}=n.linePos[0];n.message+=` at line ${s}, column ${r}`;let i=r-1,o=t.substring(e.lineStarts[s-1],e.lineStarts[s]).replace(/[\n\r]+$/,"");if(i>=60&&o.length>80){let a=Math.min(i-39,o.length-79);o="\u2026"+o.substring(a),i-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),s>1&&/^ *$/.test(o.substring(0,i))){let a=t.substring(e.lineStarts[s-2],e.lineStarts[s-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
60
+ `),o=a+o}if(/[^ ]/.test(o)){let a=1,c=n.linePos[1];c&&c.line===s&&c.col>r&&(a=Math.max(1,Math.min(c.col-r,80-i)));let l=" ".repeat(i)+"^".repeat(a);n.message+=`:
61
61
 
62
62
  ${o}
63
63
  ${l}
64
- `}};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=`
64
+ `}};un.YAMLError=ln;un.YAMLParseError=vi;un.YAMLWarning=Ai;un.prettifyError=Rh});var dn=E(Ic=>{"use strict";p();function Lh(t,{flow:e,indicator:n,next:s,offset:r,onError:i,parentIndent:o,startOnNewline:a}){let c=!1,l=a,h=a,u="",f="",d=!1,m=!1,g=null,y=null,S=null,C=null,O=null,$=null,T=null;for(let v of t)switch(m&&(v.type!=="space"&&v.type!=="newline"&&v.type!=="comma"&&i(v.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),g&&(l&&v.type!=="comment"&&v.type!=="newline"&&i(g,"TAB_AS_INDENT","Tabs are not allowed as indentation"),g=null),v.type){case"space":!e&&(n!=="doc-start"||s?.type!=="flow-collection")&&v.source.includes(" ")&&(g=v),h=!0;break;case"comment":{h||i(v,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let K=v.source.substring(1)||" ";u?u+=f+K:u=K,f="",l=!1;break}case"newline":l?u?u+=v.source:(!$||n!=="seq-item-ind")&&(c=!0):f+=v.source,l=!0,d=!0,(y||S)&&(C=v),h=!0;break;case"anchor":y&&i(v,"MULTIPLE_ANCHORS","A node can have at most one anchor"),v.source.endsWith(":")&&i(v.offset+v.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=v,T??(T=v.offset),l=!1,h=!1,m=!0;break;case"tag":{S&&i(v,"MULTIPLE_TAGS","A node can have at most one tag"),S=v,T??(T=v.offset),l=!1,h=!1,m=!0;break}case n:(y||S)&&i(v,"BAD_PROP_ORDER",`Anchors and tags must be after the ${v.source} indicator`),$&&i(v,"UNEXPECTED_TOKEN",`Unexpected ${v.source} in ${e??"collection"}`),$=v,l=n==="seq-item-ind"||n==="explicit-key-ind",h=!1;break;case"comma":if(e){O&&i(v,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),O=v,l=!1,h=!1;break}default:i(v,"UNEXPECTED_TOKEN",`Unexpected ${v.type} token`),l=!1,h=!1}let j=t[t.length-1],b=j?j.offset+j.source.length:r;return m&&s&&s.type!=="space"&&s.type!=="newline"&&s.type!=="comma"&&(s.type!=="scalar"||s.source!=="")&&i(s.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),g&&(l&&g.indent<=o||s?.type==="block-map"||s?.type==="block-seq")&&i(g,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:O,found:$,spaceBefore:c,comment:u,hasNewline:d,anchor:y,tag:S,newlineAfterProp:C,end:b,start:T??b}}Ic.resolveProps=Lh});var Ns=E(Pc=>{"use strict";p();function Ei(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(`
65
+ `))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let n of e.start)if(n.type==="newline")return!0;if(e.sep){for(let n of e.sep)if(n.type==="newline")return!0}if(Ei(e.key)||Ei(e.value))return!0}return!1;default:return!0}}Pc.containsNewline=Ei});var _i=E(jc=>{"use strict";p();var xh=Ns();function qh(t,e,n){if(e?.type==="flow-collection"){let s=e.end[0];s.indent===t&&(s.source==="]"||s.source==="}")&&xh.containsNewline(e)&&n(s,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}jc.flowIndentCheck=qh});var Ci=E(Lc=>{"use strict";p();var Rc=B();function Mh(t,e,n){let{uniqueKeys:s}=t.options;if(s===!1)return!1;let r=typeof s=="function"?s:(i,o)=>i===o||Rc.isScalar(i)&&Rc.isScalar(o)&&i.value===o.value;return e.some(i=>r(i.key,n))}Lc.mapIncludes=Mh});var Bc=E(Dc=>{"use strict";p();var xc=xe(),Kh=Me(),qc=dn(),Dh=Ns(),Mc=_i(),Bh=Ci(),Kc="All mapping items must start at the same column";function Uh({composeNode:t,composeEmptyNode:e},n,s,r,i){let o=i?.nodeClass??Kh.YAMLMap,a=new o(n.schema);n.atRoot&&(n.atRoot=!1);let c=s.offset,l=null;for(let h of s.items){let{start:u,key:f,sep:d,value:m}=h,g=qc.resolveProps(u,{indicator:"explicit-key-ind",next:f??d?.[0],offset:c,onError:r,parentIndent:s.indent,startOnNewline:!0}),y=!g.found;if(y){if(f&&(f.type==="block-seq"?r(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==s.indent&&r(c,"BAD_INDENT",Kc)),!g.anchor&&!g.tag&&!d){l=g.end,g.comment&&(a.comment?a.comment+=`
66
+ `+g.comment:a.comment=g.comment);continue}(g.newlineAfterProp||Dh.containsNewline(f))&&r(f??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else g.found?.indent!==s.indent&&r(c,"BAD_INDENT",Kc);n.atKey=!0;let S=g.end,C=f?t(n,f,g,r):e(n,S,u,null,g,r);n.schema.compat&&Mc.flowIndentCheck(s.indent,f,r),n.atKey=!1,Bh.mapIncludes(n,a.items,C)&&r(S,"DUPLICATE_KEY","Map keys must be unique");let O=qc.resolveProps(d??[],{indicator:"map-value-ind",next:m,offset:C.range[2],onError:r,parentIndent:s.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=O.end,O.found){y&&(m?.type==="block-map"&&!O.hasNewline&&r(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&g.start<O.found.offset-1024&&r(C.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let $=m?t(n,m,O,r):e(n,c,d,null,O,r);n.schema.compat&&Mc.flowIndentCheck(s.indent,m,r),c=$.range[2];let T=new xc.Pair(C,$);n.options.keepSourceTokens&&(T.srcToken=h),a.items.push(T)}else{y&&r(C.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),O.comment&&(C.comment?C.comment+=`
67
+ `+O.comment:C.comment=O.comment);let $=new xc.Pair(C);n.options.keepSourceTokens&&($.srcToken=h),a.items.push($)}}return l&&l<c&&r(l,"IMPOSSIBLE","Map comment with trailing content"),a.range=[s.offset,c,l??c],a}Dc.resolveBlockMap=Uh});var Gc=E(Uc=>{"use strict";p();var Gh=Ke(),Fh=dn(),Wh=_i();function Yh({composeNode:t,composeEmptyNode:e},n,s,r,i){let o=i?.nodeClass??Gh.YAMLSeq,a=new o(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let c=s.offset,l=null;for(let{start:h,value:u}of s.items){let f=Fh.resolveProps(h,{indicator:"seq-item-ind",next:u,offset:c,onError:r,parentIndent:s.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||u)u&&u.type==="block-seq"?r(f.end,"BAD_INDENT","All sequence items must start at the same column"):r(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(a.comment=f.comment);continue}let d=u?t(n,u,f,r):e(n,f.end,h,null,f,r);n.schema.compat&&Wh.flowIndentCheck(s.indent,u,r),c=d.range[2],a.items.push(d)}return a.range=[s.offset,c,l??c],a}Uc.resolveBlockSeq=Yh});var wt=E(Fc=>{"use strict";p();function Vh(t,e,n,s){let r="";if(t){let i=!1,o="";for(let a of t){let{source:c,type:l}=a;switch(l){case"space":i=!0;break;case"comment":{n&&!i&&s(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let h=c.substring(1)||" ";r?r+=o+h:r=h,o="";break}case"newline":r&&(o+=c),i=!0;break;default:s(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:r,offset:e}}Fc.resolveEnd=Vh});var Jc=E(Vc=>{"use strict";p();var Jh=B(),zh=xe(),Wc=Me(),Hh=Ke(),Qh=wt(),Yc=dn(),Zh=Ns(),Xh=Ci(),Ni="Block collections are not allowed within flow collections",Ti=t=>t&&(t.type==="block-map"||t.type==="block-seq");function eg({composeNode:t,composeEmptyNode:e},n,s,r,i){let o=s.start.source==="{",a=o?"flow map":"flow sequence",c=i?.nodeClass??(o?Wc.YAMLMap:Hh.YAMLSeq),l=new c(n.schema);l.flow=!0;let h=n.atRoot;h&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let u=s.offset+s.start.source.length;for(let y=0;y<s.items.length;++y){let S=s.items[y],{start:C,key:O,sep:$,value:T}=S,j=Yc.resolveProps(C,{flow:a,indicator:"explicit-key-ind",next:O??$?.[0],offset:u,onError:r,parentIndent:s.indent,startOnNewline:!1});if(!j.found){if(!j.anchor&&!j.tag&&!$&&!T){y===0&&j.comma?r(j.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):y<s.items.length-1&&r(j.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),j.comment&&(l.comment?l.comment+=`
68
+ `+j.comment:l.comment=j.comment),u=j.end;continue}!o&&n.options.strict&&Zh.containsNewline(O)&&r(O,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(y===0)j.comma&&r(j.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(j.comma||r(j.start,"MISSING_CHAR",`Missing , between ${a} items`),j.comment){let b="";e:for(let v of C)switch(v.type){case"comma":case"space":break;case"comment":b=v.source.substring(1);break e;default:break e}if(b){let v=l.items[l.items.length-1];Jh.isPair(v)&&(v=v.value??v.key),v.comment?v.comment+=`
69
+ `+b:v.comment=b,j.comment=j.comment.substring(b.length+1)}}if(!o&&!$&&!j.found){let b=T?t(n,T,j,r):e(n,j.end,$,null,j,r);l.items.push(b),u=b.range[2],Ti(T)&&r(b.range,"BLOCK_IN_FLOW",Ni)}else{n.atKey=!0;let b=j.end,v=O?t(n,O,j,r):e(n,b,C,null,j,r);Ti(O)&&r(v.range,"BLOCK_IN_FLOW",Ni),n.atKey=!1;let K=Yc.resolveProps($??[],{flow:a,indicator:"map-value-ind",next:T,offset:v.range[2],onError:r,parentIndent:s.indent,startOnNewline:!1});if(K.found){if(!o&&!j.found&&n.options.strict){if($)for(let q of $){if(q===K.found)break;if(q.type==="newline"){r(q,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}j.start<K.found.offset-1024&&r(K.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else T&&("source"in T&&T.source&&T.source[0]===":"?r(T,"MISSING_CHAR",`Missing space after : in ${a}`):r(K.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let I=T?t(n,T,K,r):K.found?e(n,K.end,$,null,K,r):null;I?Ti(T)&&r(I.range,"BLOCK_IN_FLOW",Ni):K.comment&&(v.comment?v.comment+=`
70
+ `+K.comment:v.comment=K.comment);let R=new zh.Pair(v,I);if(n.options.keepSourceTokens&&(R.srcToken=S),o){let q=l;Xh.mapIncludes(n,q.items,v)&&r(b,"DUPLICATE_KEY","Map keys must be unique"),q.items.push(R)}else{let q=new Wc.YAMLMap(n.schema);q.flow=!0,q.items.push(R);let F=(I??v).range;q.range=[v.range[0],F[1],F[2]],l.items.push(q)}u=I?I.range[2]:K.end}}let f=o?"}":"]",[d,...m]=s.end,g=u;if(d&&d.source===f)g=d.offset+d.source.length;else{let y=a[0].toUpperCase()+a.substring(1),S=h?`${y} must end with a ${f}`:`${y} in block collection must be sufficiently indented and end with a ${f}`;r(u,h?"MISSING_CHAR":"BAD_INDENT",S),d&&d.source.length!==1&&m.unshift(d)}if(m.length>0){let y=Qh.resolveEnd(m,g,n.options.strict,r);y.comment&&(l.comment?l.comment+=`
71
+ `+y.comment:l.comment=y.comment),l.range=[s.offset,g,y.offset]}else l.range=[s.offset,g,g];return l}Vc.resolveFlowCollection=eg});var Hc=E(zc=>{"use strict";p();var tg=B(),ng=Y(),sg=Me(),rg=Ke(),ig=Bc(),og=Gc(),ag=Jc();function Oi(t,e,n,s,r,i){let o=n.type==="block-map"?ig.resolveBlockMap(t,e,n,s,i):n.type==="block-seq"?og.resolveBlockSeq(t,e,n,s,i):ag.resolveFlowCollection(t,e,n,s,i),a=o.constructor;return r==="!"||r===a.tagName?(o.tag=a.tagName,o):(r&&(o.tag=r),o)}function cg(t,e,n,s,r){let i=s.tag,o=i?e.directives.tagName(i.source,f=>r(i,"TAG_RESOLVE_FAILED",f)):null;if(n.type==="block-seq"){let{anchor:f,newlineAfterProp:d}=s,m=f&&i?f.offset>i.offset?f:i:f??i;m&&(!d||d.offset<m.offset)&&r(m,"MISSING_CHAR","Missing newline after block sequence props")}let a=n.type==="block-map"?"map":n.type==="block-seq"?"seq":n.start.source==="{"?"map":"seq";if(!i||!o||o==="!"||o===sg.YAMLMap.tagName&&a==="map"||o===rg.YAMLSeq.tagName&&a==="seq")return Oi(t,e,n,r,o);let c=e.schema.tags.find(f=>f.tag===o&&f.collection===a);if(!c){let f=e.schema.knownTags[o];if(f&&f.collection===a)e.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?r(i,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Oi(t,e,n,r,o)}let l=Oi(t,e,n,r,o,c),h=c.resolve?.(l,f=>r(i,"TAG_RESOLVE_FAILED",f),e.options)??l,u=tg.isNode(h)?h:new ng.Scalar(h);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}zc.composeCollection=cg});var Pi=E(Qc=>{"use strict";p();var Ii=Y();function lg(t,e,n){let s=e.offset,r=ug(e,t.options.strict,n);if(!r)return{value:"",type:null,comment:"",range:[s,s,s]};let i=r.mode===">"?Ii.Scalar.BLOCK_FOLDED:Ii.Scalar.BLOCK_LITERAL,o=e.source?fg(e.source):[],a=o.length;for(let g=o.length-1;g>=0;--g){let y=o[g][1];if(y===""||y==="\r")a=g;else break}if(a===0){let g=r.chomp==="+"&&o.length>0?`
72
+ `.repeat(Math.max(1,o.length-1)):"",y=s+r.length;return e.source&&(y+=e.source.length),{value:g,type:i,comment:r.comment,range:[s,y,y]}}let c=e.indent+r.indent,l=e.offset+r.length,h=0;for(let g=0;g<a;++g){let[y,S]=o[g];if(S===""||S==="\r")r.indent===0&&y.length>c&&(c=y.length);else{y.length<c&&n(l+y.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),r.indent===0&&(c=y.length),h=g,c===0&&!t.atRoot&&n(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=y.length+S.length+1}for(let g=o.length-1;g>=a;--g)o[g][0].length>c&&(a=g+1);let u="",f="",d=!1;for(let g=0;g<h;++g)u+=o[g][0].slice(c)+`
73
+ `;for(let g=h;g<a;++g){let[y,S]=o[g];l+=y.length+S.length+1;let C=S[S.length-1]==="\r";if(C&&(S=S.slice(0,-1)),S&&y.length<c){let $=`Block scalar lines must not be less indented than their ${r.indent?"explicit indentation indicator":"first line"}`;n(l-S.length-(C?2:1),"BAD_INDENT",$),y=""}i===Ii.Scalar.BLOCK_LITERAL?(u+=f+y.slice(c)+S,f=`
74
74
  `):y.length>c||S[0]===" "?(f===" "?f=`
75
75
  `:!d&&f===`
76
76
  `&&(f=`
@@ -83,78 +83,78 @@ ${l}
83
83
  `+o[g][0].slice(c);u[u.length-1]!==`
84
84
  `&&(u+=`
85
85
  `);break;default:u+=`
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===`
86
+ `}let m=s+r.length+e.source.length;return{value:u,type:i,comment:r.comment,range:[s,m,m]}}function ug({offset:t,props:e},n,s){if(e[0].type!=="block-scalar-header")return s(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:r}=e[0],i=r[0],o=0,a="",c=-1;for(let f=1;f<r.length;++f){let d=r[f];if(!a&&(d==="-"||d==="+"))a=d;else{let m=Number(d);!o&&m?o=m:c===-1&&(c=t+f)}}c!==-1&&s(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${r}`);let l=!1,h="",u=r.length;for(let f=1;f<e.length;++f){let d=e[f];switch(d.type){case"space":l=!0;case"newline":u+=d.source.length;break;case"comment":n&&!l&&s(d,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),u+=d.source.length,h=d.source.substring(1);break;case"error":s(d,"UNEXPECTED_TOKEN",d.message),u+=d.source.length;break;default:{let m=`Unexpected token in block scalar header: ${d.type}`;s(d,"UNEXPECTED_TOKEN",m);let g=d.source;g&&typeof g=="string"&&(u+=g.length)}}}return{mode:i,indent:o,chomp:a,comment:h,length:u}}function fg(t){let e=t.split(/\n( *)/),n=e[0],s=n.match(/^( *)/),i=[s?.[1]?[s[1],n.slice(s[1].length)]:["",n]];for(let o=1;o<e.length;o+=2)i.push([e[o],e[o+1]]);return i}Qc.resolveBlockScalar=lg});var Ri=E(Xc=>{"use strict";p();var ji=Y(),dg=wt();function pg(t,e,n){let{offset:s,type:r,source:i,end:o}=t,a,c,l=(f,d,m)=>n(s+f,d,m);switch(r){case"scalar":a=ji.Scalar.PLAIN,c=hg(i,l);break;case"single-quoted-scalar":a=ji.Scalar.QUOTE_SINGLE,c=gg(i,l);break;case"double-quoted-scalar":a=ji.Scalar.QUOTE_DOUBLE,c=mg(i,l);break;default:return n(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[s,s+i.length,s+i.length]}}let h=s+i.length,u=dg.resolveEnd(o,h,e,n);return{value:c,type:a,comment:u.comment,range:[s,h,u.offset]}}function hg(t,e){let n="";switch(t[0]){case" ":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${t[0]}`;break}case"@":case"`":{n=`reserved character ${t[0]}`;break}}return n&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),Zc(t)}function gg(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),Zc(t.slice(1,-1)).replace(/''/g,"'")}function Zc(t){let e,n;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
87
+ `,"sy"),n=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
88
+ `,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,n=/[ \t]*(.*?)[ \t]*\r?\n/sy}let s=e.exec(t);if(!s)return t;let r=s[1],i=" ",o=e.lastIndex;for(n.lastIndex=o;s=n.exec(t);)s[1]===""?i===`
89
89
  `?r+=i:i=`
90
- `:(r+=i+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]===`
90
+ `:(r+=i+s[1],i=" "),o=n.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=o,s=a.exec(t),r+i+(s?.[1]??"")}function mg(t,e){let n="";for(let s=1;s<t.length-1;++s){let r=t[s];if(!(r==="\r"&&t[s+1]===`
91
91
  `))if(r===`
92
- `){let{fold:i,offset:o}=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?`
92
+ `){let{fold:i,offset:o}=yg(t,s);n+=i,s=o}else if(r==="\\"){let i=t[++s],o=wg[i];if(o)n+=o;else if(i===`
93
+ `)for(i=t[s+1];i===" "||i===" ";)i=t[++s+1];else if(i==="\r"&&t[s+1]===`
94
+ `)for(i=t[++s+1];i===" "||i===" ";)i=t[++s+1];else if(i==="x"||i==="u"||i==="U"){let a={x:2,u:4,U:8}[i];n+=bg(t,s+1,a,e),s+=a}else{let a=t.substr(s-1,2);e(s-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),n+=a}}else if(r===" "||r===" "){let i=s,o=t[s+1];for(;o===" "||o===" ";)o=t[++s+1];o!==`
95
+ `&&!(o==="\r"&&t[s+2]===`
96
+ `)&&(n+=s>i?t.slice(i,s+1):r)}else n+=r}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),n}function yg(t,e){let n="",s=t[e+1];for(;(s===" "||s===" "||s===`
97
+ `||s==="\r")&&!(s==="\r"&&t[e+2]!==`
98
+ `);)s===`
99
+ `&&(n+=`
100
+ `),e+=1,s=t[e+1];return n||(n=" "),{fold:n,offset:e}}var wg={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
101
+ `,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function bg(t,e,n,s){let r=t.substr(e,n),o=r.length===n&&/^[0-9a-fA-F]+$/.test(r)?parseInt(r,16):NaN;if(isNaN(o)){let a=t.substr(e-2,n+2);return s(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}return String.fromCodePoint(o)}Xc.resolveFlowScalar=pg});var nl=E(tl=>{"use strict";p();var tt=B(),el=Y(),kg=Pi(),$g=Ri();function Sg(t,e,n,s){let{value:r,type:i,comment:o,range:a}=e.type==="block-scalar"?kg.resolveBlockScalar(t,e,s):$g.resolveFlowScalar(e,t.options.strict,s),c=n?t.directives.tagName(n.source,u=>s(n,"TAG_RESOLVE_FAILED",u)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[tt.SCALAR]:c?l=vg(t.schema,r,c,n,s):e.type==="scalar"?l=Ag(t,r,e,s):l=t.schema[tt.SCALAR];let h;try{let u=l.resolve(r,f=>s(n??e,"TAG_RESOLVE_FAILED",f),t.options);h=tt.isScalar(u)?u:new el.Scalar(u)}catch(u){let f=u instanceof Error?u.message:String(u);s(n??e,"TAG_RESOLVE_FAILED",f),h=new el.Scalar(r)}return h.range=a,h.source=r,i&&(h.type=i),c&&(h.tag=c),l.format&&(h.format=l.format),o&&(h.comment=o),h}function vg(t,e,n,s,r){if(n==="!")return t[tt.SCALAR];let i=[];for(let a of t.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)i.push(a);else return a;for(let a of i)if(a.test?.test(e))return a;let o=t.knownTags[n];return o&&!o.collection?(t.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(r(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),t[tt.SCALAR])}function Ag({atKey:t,directives:e,schema:n},s,r,i){let o=n.tags.find(a=>(a.default===!0||t&&a.default==="key")&&a.test?.test(s))||n[tt.SCALAR];if(n.compat){let a=n.compat.find(c=>c.default&&c.test?.test(s))??n[tt.SCALAR];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),h=`Value may be parsed as either ${c} or ${l}`;i(r,"TAG_RESOLVE_FAILED",h,!0)}}return o}tl.composeScalar=Sg});var rl=E(sl=>{"use strict";p();function Eg(t,e,n){if(e){n??(n=e.length);for(let s=n-1;s>=0;--s){let r=e[s];switch(r.type){case"space":case"comment":case"newline":t-=r.source.length;continue}for(r=e[++s];r?.type==="space";)t+=r.source.length,r=e[++s];break}}return t}sl.emptyScalarPosition=Eg});var al=E(xi=>{"use strict";p();var _g=Ft(),Cg=B(),Ng=Hc(),il=nl(),Tg=wt(),Og=rl(),Ig={composeNode:ol,composeEmptyNode:Li};function ol(t,e,n,s){let r=t.atKey,{spaceBefore:i,comment:o,anchor:a,tag:c}=n,l,h=!0;switch(e.type){case"alias":l=Pg(t,e,s),(a||c)&&s(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=il.composeScalar(t,e,c,s),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":l=Ng.composeCollection(Ig,t,e,n,s),a&&(l.anchor=a.source.substring(1));break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;s(e,"UNEXPECTED_TOKEN",u),l=Li(t,e.offset,void 0,null,n,s),h=!1}}return a&&l.anchor===""&&s(a,"BAD_ALIAS","Anchor cannot be an empty string"),r&&t.options.stringKeys&&(!Cg.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&s(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),i&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),t.options.keepSourceTokens&&h&&(l.srcToken=e),l}function Li(t,e,n,s,{spaceBefore:r,comment:i,anchor:o,tag:a,end:c},l){let h={type:"scalar",offset:Og.emptyScalarPosition(e,n,s),indent:-1,source:""},u=il.composeScalar(t,h,a,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(u.spaceBefore=!0),i&&(u.comment=i,u.range[2]=c),u}function Pg({options:t},{offset:e,source:n,end:s},r){let i=new _g.Alias(n.substring(1));i.source===""&&r(e,"BAD_ALIAS","Alias cannot be an empty string"),i.source.endsWith(":")&&r(e+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+n.length,a=Tg.resolveEnd(s,o,t.strict,r);return i.range=[e,o,a.offset],a.comment&&(i.comment=a.comment),i}xi.composeEmptyNode=Li;xi.composeNode=ol});var ul=E(ll=>{"use strict";p();var jg=cn(),cl=al(),Rg=wt(),Lg=dn();function xg(t,e,{offset:n,start:s,value:r,end:i},o){let a=Object.assign({_directives:e},t),c=new jg.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},h=Lg.resolveProps(s,{indicator:"doc-start",next:r??i?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});h.found&&(c.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!h.hasNewline&&o(h.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=r?cl.composeNode(l,r,h,o):cl.composeEmptyNode(l,h.end,s,null,h,o);let u=c.contents.range[2],f=Rg.resolveEnd(i,u,!1,o);return f.comment&&(c.comment=f.comment),c.range=[n,u,f.offset],c}ll.composeDoc=xg});var Mi=E(pl=>{"use strict";p();var qg=jn("process"),Mg=vr(),Kg=cn(),pn=fn(),fl=B(),Dg=ul(),Bg=wt();function hn(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:n}=t;return[e,e+(typeof n=="string"?n.length:1)]}function dl(t){let e="",n=!1,s=!1;for(let r=0;r<t.length;++r){let i=t[r];switch(i[0]){case"#":e+=(e===""?"":s?`
102
102
 
103
103
  `:`
104
- `)+(i.substring(1)||" "),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:`
104
+ `)+(i.substring(1)||" "),n=!0,s=!1;break;case"%":t[r+1]?.[0]!=="#"&&(r+=1),n=!1;break;default:n||(s=!0),n=!1}}return{comment:e,afterEmptyLine:s}}var qi=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,s,r,i)=>{let o=hn(n);i?this.warnings.push(new pn.YAMLWarning(o,s,r)):this.errors.push(new pn.YAMLParseError(o,s,r))},this.directives=new Mg.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,n){let{comment:s,afterEmptyLine:r}=dl(this.prelude);if(s){let i=e.contents;if(n)e.comment=e.comment?`${e.comment}
105
+ ${s}`:s;else if(r||e.directives.docStart||!i)e.commentBefore=s;else if(fl.isCollection(i)&&!i.flow&&i.items.length>0){let o=i.items[0];fl.isPair(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${s}
106
+ ${a}`:s}else{let o=i.commentBefore;i.commentBefore=o?`${s}
107
+ ${o}`:s}}n?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:dl(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,n=!1,s=-1){for(let r of e)yield*this.next(r);yield*this.end(n,s)}*next(e){switch(qg.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(n,s,r)=>{let i=hn(e);i[0]+=n,this.onError(i,"BAD_DIRECTIVE",s,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let n=Dg.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let n=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,s=new pn.YAMLParseError(hn(e),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(s):this.doc.errors.push(s);break}case"doc-end":{if(!this.doc){let s="Unexpected doc-end without preceding document";this.errors.push(new pn.YAMLParseError(hn(e),"UNEXPECTED_TOKEN",s));break}this.doc.directives.docEnd=!0;let n=Bg.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),n.comment){let s=this.doc.comment;this.doc.comment=s?`${s}
108
+ ${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new pn.YAMLParseError(hn(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let s=Object.assign({_directives:this.directives},this.options),r=new Kg.Document(void 0,s);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,n,n],this.decorate(r,!1),yield r}}};pl.Composer=qi});var ml=E(Ts=>{"use strict";p();var Ug=Pi(),Gg=Ri(),Fg=fn(),hl=zt();function Wg(t,e=!0,n){if(t){let s=(r,i,o)=>{let a=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(n)n(a,i,o);else throw new Fg.YAMLParseError([a,a+1],i,o)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Gg.resolveFlowScalar(t,e,s);case"block-scalar":return Ug.resolveBlockScalar({options:{strict:e}},t,s)}}return null}function Yg(t,e){let{implicitKey:n=!1,indent:s,inFlow:r=!1,offset:i=-1,type:o="PLAIN"}=e,a=hl.stringifyString({type:o,value:t},{implicitKey:n,indent:s>0?" ".repeat(s):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:s,source:`
109
109
  `}];switch(a[0]){case"|":case">":{let l=a.indexOf(`
110
- `),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`
110
+ `),h=a.substring(0,l),u=a.substring(l+1)+`
111
+ `,f=[{type:"block-scalar-header",offset:i,indent:s,source:h}];return gl(f,c)||f.push({type:"newline",offset:-1,indent:s,source:`
112
+ `}),{type:"block-scalar",offset:i,indent:s,props:f,source:u}}case'"':return{type:"double-quoted-scalar",offset:i,indent:s,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:i,indent:s,source:a,end:c};default:return{type:"scalar",offset:i,indent:s,source:a,end:c}}}function Vg(t,e,n={}){let{afterKey:s=!1,implicitKey:r=!1,inFlow:i=!1,type:o}=n,a="indent"in t?t.indent:null;if(s&&typeof a=="number"&&(a+=2),!o)switch(t.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=t.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=hl.stringifyString({type:o,value:e},{implicitKey:r||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Jg(t,c);break;case'"':Ki(t,c,"double-quoted-scalar");break;case"'":Ki(t,c,"single-quoted-scalar");break;default:Ki(t,c,"scalar")}}function Jg(t,e){let n=e.indexOf(`
113
+ `),s=e.substring(0,n),r=e.substring(n+1)+`
114
+ `;if(t.type==="block-scalar"){let i=t.props[0];if(i.type!=="block-scalar-header")throw new Error("Invalid block scalar header");i.source=s,t.source=r}else{let{offset:i}=t,o="indent"in t?t.indent:-1,a=[{type:"block-scalar-header",offset:i,indent:o,source:s}];gl(a,"end"in t?t.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
115
+ `});for(let c of Object.keys(t))c!=="type"&&c!=="offset"&&delete t[c];Object.assign(t,{type:"block-scalar",indent:o,props:a,source:r})}}function gl(t,e){if(e)for(let n of e)switch(n.type){case"space":case"comment":t.push(n);break;case"newline":return t.push(n),!0}return!1}function Ki(t,e,n){switch(t.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":t.type=n,t.source=e;break;case"block-scalar":{let s=t.props.slice(1),r=e.length;t.props[0].type==="block-scalar-header"&&(r-=t.props[0].source.length);for(let i of s)i.offset+=r;delete t.props,Object.assign(t,{type:n,source:e,end:s});break}case"block-map":case"block-seq":{let r={type:"newline",offset:t.offset+e.length,indent:t.indent,source:`
116
+ `};delete t.items,Object.assign(t,{type:n,source:e,end:[r]});break}default:{let s="indent"in t?t.indent:-1,r="end"in t&&Array.isArray(t.end)?t.end.filter(i=>i.type==="space"||i.type==="comment"||i.type==="newline"):[];for(let i of Object.keys(t))i!=="type"&&i!=="offset"&&delete t[i];Object.assign(t,{type:n,indent:s,source:e,end:r})}}}Ts.createScalarToken=Yg;Ts.resolveAsScalar=Wg;Ts.setScalarValue=Vg});var wl=E(yl=>{"use strict";p();var zg=t=>"type"in t?Is(t):Os(t);function Is(t){switch(t.type){case"block-scalar":{let e="";for(let n of t.props)e+=Is(n);return e+t.source}case"block-map":case"block-seq":{let e="";for(let n of t.items)e+=Os(n);return e}case"flow-collection":{let e=t.start.source;for(let n of t.items)e+=Os(n);for(let n of t.end)e+=n.source;return e}case"document":{let e=Os(t);if(t.end)for(let n of t.end)e+=n.source;return e}default:{let e=t.source;if("end"in t&&t.end)for(let n of t.end)e+=n.source;return e}}}function Os({start:t,key:e,sep:n,value:s}){let r="";for(let i of t)r+=i.source;if(e&&(r+=Is(e)),n)for(let i of n)r+=i.source;return s&&(r+=Is(s)),r}yl.stringify=zg});var Sl=E($l=>{"use strict";p();var Di=Symbol("break visit"),Hg=Symbol("skip children"),bl=Symbol("remove item");function nt(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),kl(Object.freeze([]),t,e)}nt.BREAK=Di;nt.SKIP=Hg;nt.REMOVE=bl;nt.itemAtPath=(t,e)=>{let n=t;for(let[s,r]of e){let i=n?.[s];if(i&&"items"in i)n=i.items[r];else return}return n};nt.parentCollection=(t,e)=>{let n=nt.itemAtPath(t,e.slice(0,-1)),s=e[e.length-1][0],r=n?.[s];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function kl(t,e,n){let s=n(e,t);if(typeof s=="symbol")return s;for(let r of["key","value"]){let i=e[r];if(i&&"items"in i){for(let o=0;o<i.items.length;++o){let a=kl(Object.freeze(t.concat([[r,o]])),i.items[o],n);if(typeof a=="number")o=a-1;else{if(a===Di)return Di;a===bl&&(i.items.splice(o,1),o-=1)}}typeof s=="function"&&r==="key"&&(s=s(e,t))}}return typeof s=="function"?s(e,t):s}$l.visit=nt});var Ps=E(ie=>{"use strict";p();var Bi=ml(),Qg=wl(),Zg=Sl(),Ui="\uFEFF",Gi="",Fi="",Wi="",Xg=t=>!!t&&"items"in t,em=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function tm(t){switch(t){case Ui:return"<BOM>";case Gi:return"<DOC>";case Fi:return"<FLOW_END>";case Wi:return"<SCALAR>";default:return JSON.stringify(t)}}function nm(t){switch(t){case Ui:return"byte-order-mark";case Gi:return"doc-mode";case Fi:return"flow-error-end";case Wi:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
117
117
  `:case`\r
118
- `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(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===`
118
+ `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(t[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}ie.createScalarToken=Bi.createScalarToken;ie.resolveAsScalar=Bi.resolveAsScalar;ie.setScalarValue=Bi.setScalarValue;ie.stringify=Qg.stringify;ie.visit=Zg.visit;ie.BOM=Ui;ie.DOCUMENT=Gi;ie.FLOW_END=Fi;ie.SCALAR=Wi;ie.isCollection=Xg;ie.isScalar=em;ie.prettyToken=tm;ie.tokenType=nm});var Ji=E(Al=>{"use strict";p();var gn=Ps();function de(t){switch(t){case void 0:case" ":case`
119
+ `:case"\r":case" ":return!0;default:return!1}}var vl=new Set("0123456789ABCDEFabcdef"),sm=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),js=new Set(",[]{}"),rm=new Set(` ,[]{}
120
+ \r `),Yi=t=>!t||rm.has(t),Vi=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,n=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!n;let s=this.next??"stream";for(;s&&(n||this.hasChars(1));)s=yield*this.parseNext(s)}atLineEnd(){let e=this.pos,n=this.buffer[e];for(;n===" "||n===" ";)n=this.buffer[++e];return!n||n==="#"||n===`
121
+ `?!0:n==="\r"?this.buffer[e+1]===`
122
+ `:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let n=this.buffer[e];if(this.indentNext>0){let s=0;for(;n===" ";)n=this.buffer[++s+e];if(n==="\r"){let r=this.buffer[s+e+1];if(r===`
123
+ `||!r&&!this.atEnd)return e+s+1}return n===`
124
+ `||s>=this.indentNext||!n&&!this.atEnd?e+s:-1}if(n==="-"||n==="."){let s=this.buffer.substr(e,3);if((s==="---"||s==="...")&&de(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
125
+ `,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===gn.BOM&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let n=e.length,s=e.indexOf("#");for(;s!==-1;){let i=e[s-1];if(i===" "||i===" "){n=s-1;break}else s=e.indexOf("#",s+1)}for(;;){let i=e[n-1];if(i===" "||i===" ")n-=1;else break}let r=(yield*this.pushCount(n))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-r),this.pushNewline(),"stream"}if(this.atLineEnd()){let n=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-n),yield*this.pushNewline(),"stream"}return yield gn.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let n=this.peek(3);if((n==="---"||n==="...")&&de(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,n==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!de(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,n]=this.peek(2);if(!n&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&de(n)){let s=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=s,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let n=yield*this.pushIndicators();switch(e[n]){case"#":yield*this.pushCount(e.length-n);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Yi),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return n+=yield*this.parseBlockScalarHeader(),n+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-n),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,n,s=-1;do e=yield*this.pushNewline(),e>0?(n=yield*this.pushSpaces(!1),this.indentValue=s=n):n=0,n+=yield*this.pushSpaces(!0);while(e+n>0);let r=this.getLine();if(r===null)return this.setNext("flow");if((s!==-1&&s<this.indentNext&&r[0]!=="#"||s===0&&(r.startsWith("---")||r.startsWith("..."))&&de(r[3]))&&!(s===this.indentNext-1&&this.flowLevel===1&&(r[0]==="]"||r[0]==="}")))return this.flowLevel=0,yield gn.FLOW_END,yield*this.parseLineStart();let i=0;for(;r[i]===",";)i+=yield*this.pushCount(1),i+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(i+=yield*this.pushIndicators(),r[i]){case void 0:return"flow";case"#":return yield*this.pushCount(r.length-i),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(Yi),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||de(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),n=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;n!==-1&&this.buffer[n+1]==="'";)n=this.buffer.indexOf("'",n+2);else for(;n!==-1;){let i=0;for(;this.buffer[n-1-i]==="\\";)i+=1;if(i%2===0)break;n=this.buffer.indexOf('"',n+1)}let s=this.buffer.substring(0,n),r=s.indexOf(`
126
+ `,this.pos);if(r!==-1){for(;r!==-1;){let i=this.continueScalar(r+1);if(i===-1)break;r=s.indexOf(`
127
+ `,i)}r!==-1&&(n=r-(s[r-1]==="\r"?2:1))}if(n===-1){if(!this.atEnd)return this.setNext("quoted-scalar");n=this.buffer.length}return yield*this.pushToIndex(n+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let n=this.buffer[++e];if(n==="+")this.blockScalarKeep=!0;else if(n>"0"&&n<="9")this.blockScalarIndent=Number(n)-1;else if(n!=="-")break}return yield*this.pushUntil(n=>de(n)||n==="#")}*parseBlockScalar(){let e=this.pos-1,n=0,s;e:for(let i=this.pos;s=this.buffer[i];++i)switch(s){case" ":n+=1;break;case`
128
+ `:e=i,n=0;break;case"\r":{let o=this.buffer[i+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
129
+ `)break}default:break e}if(!s&&!this.atEnd)return this.setNext("block-scalar");if(n>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=n:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let i=this.continueScalar(e+1);if(i===-1)break;e=this.buffer.indexOf(`
130
+ `,i)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let r=e+1;for(s=this.buffer[r];s===" ";)s=this.buffer[++r];if(s===" "){for(;s===" "||s===" "||s==="\r"||s===`
131
+ `;)s=this.buffer[++r];e=r-1}else if(!this.blockScalarKeep)do{let i=e-1,o=this.buffer[i];o==="\r"&&(o=this.buffer[--i]);let a=i;for(;o===" ";)o=this.buffer[--i];if(o===`
132
+ `&&i>=this.pos&&i+1+n>a)e=i;else break}while(!0);return yield gn.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,n=this.pos-1,s=this.pos-1,r;for(;r=this.buffer[++s];)if(r===":"){let i=this.buffer[s+1];if(de(i)||e&&js.has(i))break;n=s}else if(de(r)){let i=this.buffer[s+1];if(r==="\r"&&(i===`
133
+ `?(s+=1,r=`
134
+ `,i=this.buffer[s+1]):n=s),i==="#"||e&&js.has(i))break;if(r===`
135
+ `){let o=this.continueScalar(s+1);if(o===-1)break;s=Math.max(s,o-2)}}else{if(e&&js.has(r))break;n=s}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield gn.SCALAR,yield*this.pushToIndex(n+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,n){let s=this.buffer.slice(this.pos,e);return s?(yield s,this.pos+=s.length,s.length):(n&&(yield""),0)}*pushIndicators(){switch(this.charAt(0)){case"!":return(yield*this.pushTag())+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"&":return(yield*this.pushUntil(Yi))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{let e=this.flowLevel>0,n=this.charAt(1);if(de(n)||e&&js.has(n))return e?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,(yield*this.pushCount(1))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators())}}return 0}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,n=this.buffer[e];for(;!de(n)&&n!==">";)n=this.buffer[++e];return yield*this.pushToIndex(n===">"?e+1:e,!1)}else{let e=this.pos+1,n=this.buffer[e];for(;n;)if(sm.has(n))n=this.buffer[++e];else if(n==="%"&&vl.has(this.buffer[e+1])&&vl.has(this.buffer[e+2]))n=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
136
136
  `?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
137
- `?yield*this.pushCount(2):0}*pushSpaces(e){let 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()?`:
137
+ `?yield*this.pushCount(2):0}*pushSpaces(e){let n=this.pos-1,s;do s=this.buffer[++n];while(s===" "||e&&s===" ");let r=n-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=n),r}*pushUntil(e){let n=this.pos,s=this.buffer[n];for(;!e(s);)s=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};Al.Lexer=Vi});var Hi=E(El=>{"use strict";p();var zi=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let n=0,s=this.lineStarts.length;for(;n<s;){let i=n+s>>1;this.lineStarts[i]<e?n=i+1:s=i}if(this.lineStarts[n]===e)return{line:n+1,col:1};if(n===0)return{line:0,col:e};let r=this.lineStarts[n-1];return{line:n,col:e-r+1}}}};El.LineCounter=zi});var Zi=E(Ol=>{"use strict";p();var im=jn("process"),_l=Ps(),om=Ji();function De(t,e){for(let n=0;n<t.length;++n)if(t[n].type===e)return!0;return!1}function Cl(t){for(let e=0;e<t.length;++e)switch(t[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}function Tl(t){switch(t?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Rs(t){switch(t.type){case"document":return t.start;case"block-map":{let e=t.items[t.items.length-1];return e.sep??e.start}case"block-seq":return t.items[t.items.length-1].start;default:return[]}}function bt(t){if(t.length===0)return[];let e=t.length;e:for(;--e>=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function Nl(t){if(t.start.type==="flow-seq-start")for(let e of t.items)e.sep&&!e.value&&!De(e.start,"explicit-key-ind")&&!De(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,Tl(e.value)?e.value.end?Array.prototype.push.apply(e.value.end,e.sep):e.value.end=e.sep:Array.prototype.push.apply(e.start,e.sep),delete e.sep)}var Qi=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new om.Lexer,this.onNewLine=e}*parse(e,n=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let s of this.lexer.lex(e,n))yield*this.next(s);n||(yield*this.end())}*next(e){if(this.source=e,im.env.LOG_TOKENS&&console.log("|",_l.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let n=_l.tokenType(e);if(n)if(n==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=n,yield*this.step(),n){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{let s=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:s,source:e}),this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&(!e||e.type!=="doc-end")){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let n=e??this.stack.pop();if(!n)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield n;else{let s=this.peek(1);switch(n.type==="block-scalar"?n.indent="indent"in s?s.indent:0:n.type==="flow-collection"&&s.type==="document"&&(n.indent=0),n.type==="flow-collection"&&Nl(n),s.type){case"document":s.value=n;break;case"block-scalar":s.props.push(n);break;case"block-map":{let r=s.items[s.items.length-1];if(r.value){s.items.push({start:[],key:n,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=n;else{Object.assign(r,{key:n,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{let r=s.items[s.items.length-1];r.value?s.items.push({start:[],value:n}):r.value=n;break}case"flow-collection":{let r=s.items[s.items.length-1];!r||r.value?s.items.push({start:[],key:n,sep:[]}):r.sep?r.value=n:Object.assign(r,{key:n,sep:[]});return}default:yield*this.pop(),yield*this.pop(n)}if((s.type==="document"||s.type==="block-map"||s.type==="block-seq")&&(n.type==="block-map"||n.type==="block-seq")){let r=n.items[n.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&Cl(r.start)===-1&&(n.indent===0||r.start.every(i=>i.type!=="comment"||i.indent<n.indent))&&(s.type==="document"?s.end=r.start:s.items.push({start:r.start}),n.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{Cl(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){let n=Rs(this.peek(2)),s=bt(n),r;e.end?(r=e.end,r.push(this.sourceToken),delete e.end):r=[this.sourceToken];let i={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let n=this.source.indexOf(`
138
+ `)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`
139
+ `,n)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let n=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,n.value){let s="end"in n.value?n.value.end:void 0;(Array.isArray(s)?s[s.length-1]:void 0)?.type==="comment"?s?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)e.items.push({start:[this.sourceToken]});else if(n.sep)n.sep.push(this.sourceToken);else{if(this.atIndentedComment(n.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Array.prototype.push.apply(r,n.start),r.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let s=!this.onKeyLine&&this.indent===e.indent,r=s&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",i=[];if(r&&n.sep&&!n.value){let o=[];for(let a=0;a<n.sep.length;++a){let c=n.sep[a];switch(c.type){case"newline":o.push(a);break;case"space":break;case"comment":c.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(i=n.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":r||n.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"explicit-key-ind":!n.sep&&!n.explicitKey?(n.start.push(this.sourceToken),n.explicitKey=!0):r||n.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(n.explicitKey)if(n.sep)if(n.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(De(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(Tl(n.key)&&!De(n.sep,"newline")){let o=bt(n.start),a=n.key,c=n.sep;c.push(this.sourceToken),delete n.key,delete n.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else i.length>0?n.sep=n.sep.concat(i,this.sourceToken):n.sep.push(this.sourceToken);else if(De(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let o=bt(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):De(n.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);r||n.value?(e.items.push({start:i,key:o,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(o):(Object.assign(n,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!n.explicitKey&&n.sep&&!De(n.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else s&&e.items.push({start:i});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let n=e.items[e.items.length-1];switch(this.type){case"newline":if(n.value){let s="end"in n.value?n.value.end:void 0;(Array.isArray(s)?s[s.length-1]:void 0)?.type==="comment"?s?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Array.prototype.push.apply(r,n.start),r.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=e.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;n.value||De(n.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>e.indent){let s=this.startBlockValue(e);if(s){this.stack.push(s);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let n=e.items[e.items.length-1];if(this.type==="flow-error-end"){let s;do yield*this.pop(),s=this.peek(1);while(s&&s.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!n||n.value?e.items.push({start:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let r=this.flowScalar(this.type);!n||n.value?e.items.push({start:[],key:r,sep:[]}):n.sep?this.stack.push(r):Object.assign(n,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let s=this.startBlockValue(e);s?this.stack.push(s):(yield*this.pop(),yield*this.step())}else{let s=this.peek(2);if(s.type==="block-map"&&(this.type==="map-value-ind"&&s.indent===e.indent||this.type==="newline"&&!s.items[s.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&s.type!=="flow-collection"){let r=Rs(s),i=bt(r);Nl(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:i,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let n=this.source.indexOf(`
140
+ `)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`
141
+ `,n)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=Rs(e),s=bt(n);return s.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=Rs(e),s=bt(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,n){return this.type!=="comment"||this.indent<=n?!1:e.every(s=>s.type==="newline"||s.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Ol.Parser=Qi});var Ll=E(yn=>{"use strict";p();var Il=Mi(),am=cn(),mn=fn(),cm=xr(),lm=B(),um=Hi(),Pl=Zi();function jl(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new um.LineCounter||null,prettyErrors:e}}function fm(t,e={}){let{lineCounter:n,prettyErrors:s}=jl(e),r=new Pl.Parser(n?.addNewLine),i=new Il.Composer(e),o=Array.from(i.compose(r.parse(t)));if(s&&n)for(let a of o)a.errors.forEach(mn.prettifyError(t,n)),a.warnings.forEach(mn.prettifyError(t,n));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}function Rl(t,e={}){let{lineCounter:n,prettyErrors:s}=jl(e),r=new Pl.Parser(n?.addNewLine),i=new Il.Composer(e),o=null;for(let a of i.compose(r.parse(t),!0,t.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new mn.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return s&&n&&(o.errors.forEach(mn.prettifyError(t,n)),o.warnings.forEach(mn.prettifyError(t,n))),o}function dm(t,e,n){let s;typeof e=="function"?s=e:n===void 0&&e&&typeof e=="object"&&(n=e);let r=Rl(t,n);if(!r)return null;if(r.warnings.forEach(i=>cm.warn(r.options.logLevel,i)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:s},n))}function pm(t,e,n){let s=null;if(typeof e=="function"||Array.isArray(e)?s=e:n===void 0&&e&&(n=e),typeof n=="string"&&(n=n.length),typeof n=="number"){let r=Math.round(n);n=r<1?void 0:r>8?{indent:8}:{indent:r}}if(t===void 0){let{keepUndefined:r}=n??e??{};if(!r)return}return lm.isDocument(t)&&!s?t.toString(n):new am.Document(t,s,n).toString(n)}yn.parse=dm;yn.parseAllDocuments=fm;yn.parseDocument=Rl;yn.stringify=pm});var ql=E(G=>{"use strict";p();var hm=Mi(),gm=cn(),mm=wi(),Xi=fn(),ym=Ft(),Be=B(),wm=xe(),bm=Y(),km=Me(),$m=Ke(),Sm=Ps(),vm=Ji(),Am=Hi(),Em=Zi(),Ls=Ll(),xl=Dt();G.Composer=hm.Composer;G.Document=gm.Document;G.Schema=mm.Schema;G.YAMLError=Xi.YAMLError;G.YAMLParseError=Xi.YAMLParseError;G.YAMLWarning=Xi.YAMLWarning;G.Alias=ym.Alias;G.isAlias=Be.isAlias;G.isCollection=Be.isCollection;G.isDocument=Be.isDocument;G.isMap=Be.isMap;G.isNode=Be.isNode;G.isPair=Be.isPair;G.isScalar=Be.isScalar;G.isSeq=Be.isSeq;G.Pair=wm.Pair;G.Scalar=bm.Scalar;G.YAMLMap=km.YAMLMap;G.YAMLSeq=$m.YAMLSeq;G.CST=Sm;G.Lexer=vm.Lexer;G.LineCounter=Am.LineCounter;G.Parser=Em.Parser;G.parse=Ls.parse;G.parseAllDocuments=Ls.parseAllDocuments;G.parseDocument=Ls.parseDocument;G.stringify=Ls.stringify;G.visit=xl.visit;G.visitAsync=xl.visitAsync});p();import{parseArgs as Zy}from"node:util";p();import{existsSync as gy,readFileSync as my}from"node:fs";import{join as yy}from"node:path";p();p();p();function Ro(t,e,n=s=>s.length>0&&s.length<=100){let s=[];if(typeof t!="object"||t===null||Array.isArray(t))return{rule:null,problems:[`${e}: rows should map a field to a value, e.g. rows: { rep_email: $me }.`]};let r=Object.entries(t);r.length||s.push(`${e}: rows is empty. Leave it out to grant every row.`);let i={},o=a=>typeof a=="string"||typeof a=="number"||typeof a=="boolean";for(let[a,c]of r)n(a)||s.push(`${e}: "${a}" isn't a field name rows can use.`),Array.isArray(c)?!c.length||!c.every(o)?s.push(`${e}.${a}: give one value, or a list of values, e.g. [won, lost].`):i[a]=[...new Set(c.map(l=>typeof l=="string"?l.trim():l))].sort((l,h)=>String(l).localeCompare(String(h))):o(c)?i[a]=typeof c=="string"?c.trim():c:s.push(`${e}.${a}: give a value (text, a number, true/false or $me), or a list of them.`);return{rule:s.length?null:i,problems:s}}var Rn="*";p();p();var Of=/^[a-z][a-z0-9_-]{0,40}$/,Lo=/^[A-Za-z0-9-]{1,64}$/,If=new Set(["authorization","proxy-authorization","cookie","host","content-length","content-type","transfer-encoding","connection","user-agent"]),Ln=/^[A-Za-z0-9_$@-]+(\.[A-Za-z0-9_$@-]+)*$/,qo=/^[A-Za-z0-9_.[\]-]{1,64}$/,Mo=2e4;function xo(t){let e;try{e=new URL(t)}catch{return"isn't a URL"}if(e.protocol!=="https:")return"should start with https://";if(e.username||e.password)return"shouldn't have a user or password in it";let n=e.hostname.toLowerCase();return/^\[|^[0-9.]+$/.test(n)?"should be a hostname, not an IP address":!n.includes(".")||/(^|\.)(localhost|internal|local|localdomain|home\.arpa)$/.test(n)?"should be a public hostname":null}function Pf(t,e){let n=new URL(t+e);return jf(t,n)?n:null}function jf(t,e){let n=new URL(t),s=n.pathname.replace(/\/$/,"");return e.protocol==="https:"&&e.origin===n.origin&&!e.username&&!e.password&&(e.pathname===s||e.pathname.startsWith(s+"/")||!s)}var ge=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function Ko(t,e,n){let s=[],r={base_url:"",resources:{}},i=typeof t.base_url=="string"?xo(t.base_url.trim()):"is missing";if(i)s.push(`${e}: base_url ${i} (e.g. https://api.hubapi.com).`);else{let c=new URL(t.base_url.trim());(c.search||c.hash)&&s.push(`${e}: base_url shouldn't have a ? or # part; put query settings in each resource's path.`),r.base_url=`${c.origin}${c.pathname.replace(/\/+$/,"")}`}if(n)t.auth!==void 0&&s.push(`${e}: a per-person source signs in with each person's own token; leave auth out.`);else if(t.auth!==void 0){let c=typeof t.auth=="string"?t.auth.trim():"",l=/^header\s+(\S+)$/i.exec(c)?.[1];c==="bearer"||c==="basic"?r.auth=c:l&&Lo.test(l)&&!["cookie","host"].includes(l.toLowerCase())?r.auth=`header ${l}`:s.push(`${e}: auth should be bearer, basic, or header <Name> (e.g. header X-Api-Key).`)}if(t.headers!==void 0)if(!ge(t.headers))s.push(`${e}.headers should map a header name to its value.`);else{let c={};for(let[l,h]of Object.entries(t.headers)){let u=typeof h=="number"?String(h):h;Lo.test(l)?If.has(l.toLowerCase())?s.push(`${e}.headers: Kuriko sets ${l} itself${/auth/i.test(l)?" (the credential goes in Secret Manager: name it in secret)":""}.`):typeof u!="string"||/[\r\n]/.test(u)||u.length>500?s.push(`${e}.headers.${l} should be one line of text.`):xn(u)||/key|token|secret|auth/i.test(l)?s.push(`${e}.headers.${l} looks like it carries a credential. Put it in Secret Manager and use auth: header ${l}.`):c[l]=u:s.push(`${e}.headers: "${l}" isn't a header name.`)}Object.keys(c).length&&(r.headers=c)}let o=t.resources;if(!ge(o)||!Object.keys(o).length)s.push(`${e}.resources should map a name tools use to the API path that lists it.`);else for(let[c,l]of Object.entries(o)){let h=`${e}.resources.${c}`;Of.test(c)||s.push(`${e}.resources: "${c}" should be lowercase letters, digits, - and _.`);let u=typeof l=="string"?{path:l}:l;if(!ge(u)){s.push(`${h} should be a path (e.g. /v1/contacts), or settings with a path.`);continue}for(let m of Object.keys(u))["path","method","body","rows","next","add"].includes(m)||s.push(`${h}: unknown setting "${m}".`);let f={path:""},d=Do(u.path,r.base_url,h,"/crm/v3/objects/contacts?limit=100",s);if(d&&(f.path=d),u.method!==void 0){let m=typeof u.method=="string"?u.method.toUpperCase():"";m!=="GET"&&m!=="POST"?s.push(`${h}: method should be GET or POST (POST for search or GraphQL endpoints). It's how the resource is listed; adding rows goes under add.`):m==="POST"&&(f.method="POST")}if(u.body!==void 0&&(f.method!=="POST"?s.push(`${h}: a body needs method: POST.`):ge(u.body)?JSON.stringify(u.body).length>Mo?s.push(`${h}.body is too long.`):f.body=u.body:s.push(`${h}.body should be the JSON object sent.`)),u.rows!==void 0&&(typeof u.rows!="string"||!Ln.test(u.rows)?s.push(`${h}: rows should say where the list is in the answer, e.g. results or data.items.`):f.rows=u.rows),u.next!==void 0){let m=Mf(u.next,`${h}.next`,f.method==="POST",s);m&&(f.next=m)}if(u.add!==void 0){let m=qf(u.add,`${h}.add`,r.base_url,s);m&&(f.add=m)}r.resources[c]=f}if(n){let c=t.oauth;if(!ge(c))s.push(`${e}: a per-person source needs oauth (authorize_url, token_url, client_id, scopes).`);else{for(let f of Object.keys(c))["authorize_url","token_url","client_id","scopes","scope_separator","authorize_params","client_auth","account"].includes(f)||s.push(`${e}.oauth: unknown setting "${f}".`);let l={};for(let f of["authorize_url","token_url"]){let d=typeof c[f]=="string"?xo(c[f].trim()):"is missing";d?s.push(`${e}.oauth: ${f} ${d}.`):l[f]=c[f].trim()}let h=Rf(c.client_id,e,s);h&&(l.client_id=h);let u=Lf(c.scopes,e,s);if(u&&(l.scopes=u),c.scope_separator!==void 0&&(c.scope_separator!==" "&&c.scope_separator!==","?s.push(`${e}.oauth: scope_separator should be " " or ",".`):c.scope_separator===","&&(l.scope_separator=",")),c.authorize_params!==void 0){let f=new Set(["client_id","redirect_uri","state","response_type","scope"]);!ge(c.authorize_params)||!Object.entries(c.authorize_params).every(([d,m])=>qo.test(d)&&!f.has(d)&&typeof m=="string"&&m.length<=200)?s.push(`${e}.oauth: authorize_params should map extra settings to text (not client_id, redirect_uri, state, response_type or scope).`):Object.keys(c.authorize_params).length&&(l.authorize_params=c.authorize_params)}c.client_auth!==void 0&&(c.client_auth!=="body"&&c.client_auth!=="basic"?s.push(`${e}.oauth: client_auth should be body or basic.`):c.client_auth==="basic"&&(l.client_auth="basic")),c.account!==void 0&&(typeof c.account!="string"||!Ln.test(c.account)?s.push(`${e}.oauth: account should say where the account's email or name is in the token answer, e.g. user.email.`):l.account=c.account),l.authorize_url&&l.token_url&&l.client_id&&(r.oauth=l)}}else t.oauth!==void 0&&s.push(`${e}: oauth is for per-person sources (credentials: per-person).`);let a=Object.keys(r.resources);return{config:r,resources:a,writable:a.filter(c=>r.resources[c].add),problems:s}}function Rf(t,e,n){return typeof t!="string"||!/^[A-Za-z0-9._~:@-]{4,200}$/.test(t.trim())?(n.push(`${e}.oauth: client_id should be your OAuth app's client ID.`),null):xn(t.trim())&&/secret/i.test(t)?(n.push(`${e}.oauth: client_id looks like a client secret; that goes in Secret Manager.`),null):t.trim()}function Lf(t,e,n){if(t===void 0)return null;let s=Array.isArray(t)?t:typeof t=="string"?t.split(/\s+/).filter(Boolean):null;return!s||!s.every(r=>typeof r=="string"&&/^[\x21-\x7e]{1,200}$/.test(r)&&!r.includes(","))?(n.push(`${e}.oauth: scopes should be a list, e.g. [crm.objects.contacts.read].`),null):s.length?s:null}function Do(t,e,n,s,r){let i=typeof t=="string"?t.trim():"";return!/^\/(?!\/)[^\s#\\]*$/.test(i)||i.length>1e3||/(^|\/)\.\.?(\/|\?|$)/.test(i)||/%2e|%2f/i.test(i)?(r.push(`${n}: path should be the API path under base_url, starting with / (e.g. ${s}).`),null):e&&!Pf(e,i)?(r.push(`${n}: path leaves base_url.`),null):i}var wr=t=>t===xf?1:Array.isArray(t)?t.reduce((e,n)=>e+wr(n),0):ge(t)?Object.values(t).reduce((e,n)=>e+wr(n),0):0,xf="$row";function qf(t,e,n,s){let r=typeof t=="string"?{path:t}:t;if(!ge(r))return s.push(`${e} should be a path (e.g. /v1/contacts), or settings with a path.`),null;for(let a of Object.keys(r))["path","body","row"].includes(a)||s.push(a==="method"?`${e}: new rows are always sent with POST; leave method out.`:`${e}: unknown setting "${a}" (add takes path, body and row).`);let i={path:""},o=Do(r.path,n,e,"/crm/v3/objects/contacts",s);return o&&(i.path=o),r.body!==void 0&&(ge(r.body)?JSON.stringify(r.body).length>Mo?s.push(`${e}.body is too long.`):wr(r.body)!==1?s.push(`${e}.body should have $row exactly once, where the tool's values go (e.g. { properties: $row }).`):i.body=r.body:s.push(`${e}.body should be the JSON object sent, with $row where the tool's values go, e.g. { properties: $row }.`)),r.row!==void 0&&r.row!==""&&(typeof r.row!="string"||!Ln.test(r.row)?s.push(`${e}: row should say where the new row is in the answer, e.g. data.issueCreate.issue (or leave it out if the answer is the row).`):i.row=r.row),o?i:null}function Mf(t,e,n,s){let r=c=>(s.push(`${e}: ${c}`),null);if(t==="link")return"link";if(!ge(t))return r("should be link, or { cursor, param }, { cursor, body }, { url }, { page } or { offset }.");let i=Object.keys(t),o=c=>typeof t[c]=="string"&&Ln.test(t[c]),a=c=>typeof t[c]=="string"&&qo.test(t[c]);return"cursor"in t?i.some(c=>!["cursor","param","body","more"].includes(c))?r("a cursor takes cursor, param or body, and more."):o("cursor")?"param"in t=="body"in t?r("say where the cursor goes: param (a query parameter) or body (a field in a POST's body)."):"param"in t&&!a("param")?r("param should be a query parameter name, e.g. after."):"body"in t&&(!n||!o("body"))?r(n?"body should be the field it goes in, e.g. variables.after.":"body needs method: POST."):"more"in t&&!o("more")?r("more should say where the has-more flag is, e.g. has_more."):{cursor:t.cursor,..."param"in t?{param:t.param}:{body:t.body},..."more"in t?{more:t.more}:{}}:r("cursor should say where the next cursor is in the answer, e.g. paging.next.after."):"url"in t?i.length===1&&o("url")?{url:t.url}:r("url should say where the next page's URL is in the answer, e.g. links.next."):"page"in t?i.some(c=>c!=="page"&&c!=="start")||!a("page")?r("page should be the page-number parameter, e.g. page."):"start"in t&&(typeof t.start!="number"||!Number.isInteger(t.start)||t.start<0)?r("start should be the first page's number (0 or 1)."):{page:t.page,...t.start!==void 0&&t.start!==1?{start:t.start}:{}}:"offset"in t?i.length===1&&a("offset")?{offset:t.offset}:r("offset should be the offset parameter, e.g. offset."):r("should be link, or { cursor, param }, { cursor, body }, { url }, { page } or { offset }.")}p();var me=[{id:"claude-code",name:"Claude Code",where:"terminal and IDEs",documents:["https://claude.ai/oauth/claude-code-client-metadata"]},{id:"claude",name:"Claude",where:"claude.ai, desktop and mobile apps",documents:["https://claude.ai/oauth/mcp-oauth-client-metadata"]},{id:"codex",name:"Codex",where:"OpenAI's CLI and IDE extension",documents:["https://chatgpt.com/oauth/codex/client.json","https://chatgpt.com/oauth/codex/*/client.json"]},{id:"chatgpt",name:"ChatGPT",where:"chatgpt.com and its apps, including Codex there",documents:["https://chatgpt.com/oauth/client.json"]},{id:"vscode",name:"VS Code",where:"GitHub Copilot's agent mode",documents:["https://vscode.dev/oauth/client-metadata.json"]},{id:"cursor",name:"Cursor",where:"Cursor's editor and cloud agents",documents:["https://cursor.com/oauth/mcp-client.json"]},{id:"lovable",name:"Lovable",where:"Lovable's workspace connectors",documents:["https://api.lovable.dev/.well-known/oauth-client"]},{id:"replit",name:"Replit",where:"Replit Agent's MCP servers",documents:[],notYet:"signs in without a metadata document"},{id:"bolt",name:"Bolt",where:"Bolt's connectors",documents:[],notYet:"signs in without a metadata document"},{id:"v0",name:"v0",where:"Vercel's v0",documents:[],notYet:"custom MCP sign-in unconfirmed"}],Bo=me.filter(t=>!t.notYet),Ie=["claude-code","claude"],Uo=new Map(me.map(t=>[t.id,t])),qn=t=>Uo.get(t);function Go(t){let e;try{e=new URL(t)}catch{return!1}return e.protocol==="https:"&&e.pathname.length>1&&!e.hash&&!e.username&&!e.password&&e.href===t}var Lt=t=>Uo.get(t)?.name??t;var Kf="*",ct=class extends Error{name="PolicyFileError";problems;constructor(e){super(`policy.yaml has ${e.length===1?"a problem":`${e.length} problems`}:
142
+ ${e.map(n=>` - ${n}`).join(`
143
+ `)}`),this.problems=e}},Df=new Set(["Viewer","Builder","Admin"]),Fo=new Set(["postgres","bigquery","snowflake","api"]);var Bf=/^[A-Za-z_][A-Za-z0-9_]{0,62}$/,Wo=/^[A-Za-z_][A-Za-z0-9_]{0,254}$/,Uf=/^[a-z][a-z0-9-]{4,28}[a-z0-9]$/,Gf=/^(?:([a-z][a-z0-9-]{4,28}[a-z0-9])[.:])?([A-Za-z0-9_]{1,1024})$/,Ff=/^[A-Za-z0-9][A-Za-z0-9_.-]{1,254}$/,Wf=/^[A-Za-z0-9_.@$-]{1,255}$/,Mn=/^[A-Za-z_][A-Za-z0-9_$]{0,254}$/,Yf=/^[a-z][a-z0-9-]{1,30}$/;var Vf=/^(?:projects\/[a-z][a-z0-9-]{4,28}[a-z0-9]\/secrets\/)?[A-Za-z0-9_-]{1,255}$/,xn=t=>/^(ntn_|secret_|sk-|sk_live_|sk_test_|rk_live_|ghp_|gho_|github_pat_|xox[abpr]-|AKIA|ASIA|AIza|ya29\.)/.test(t)||t.length>=32&&/[A-Z]/.test(t)&&/[a-z]/.test(t)&&/[0-9]/.test(t)&&!/[-_].*[-_]/.test(t),Jf=t=>{let e=t.split("/").pop();return e.startsWith("kuriko-")&&!e.startsWith("kuriko-connector-")},zf=new Set(["roles","connectors","access","clients"]);function Yo(t){let e=t.trim();return e.toLowerCase()==="everyone"?Rn:e.includes("@")?e.toLowerCase():e}var Mt=t=>t===Rn?"everyone":t,xt=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),qt=t=>[...new Set(t)].sort();function Vo(t,e){let n=[],s={roles:[],connectors:[],grants:[],clients:[]};if(t==null&&(t={}),!xt(t))throw new ct(["The file should be a map with roles, connectors, access and clients."]);for(let u of Object.keys(t))zf.has(u)||n.push(`Unknown section "${u}" (expected roles, connectors, access, clients).`);let r=t.roles??{};if(!xt(r))n.push("roles should map a group to Admin, Builder or Viewer.");else for(let[u,f]of Object.entries(r)){let d=Yo(u);d===Rn?n.push("roles: everyone can't be given a role (roles need a real group)."):typeof f!="string"||!Df.has(f)?n.push(`roles: ${u} should be Admin, Builder or Viewer, not ${JSON.stringify(f)}.`):s.roles.some(m=>m.group===d)?n.push(`roles: ${u} is listed twice.`):s.roles.push({group:d,role:f})}let i=t.connectors??{},o=new Map,a=new Map,c=new Map;if(!xt(i))n.push("connectors should map an id (e.g. hubspot) to its settings.");else for(let[u,f]of Object.entries(i)){let d=`connectors.${u}`;if(Yf.test(u)||n.push(`${d}: the id should be lowercase letters, digits and dashes.`),!xt(f)){n.push(`${d} should have a name and a kind.`);continue}let m=typeof f.kind=="string"&&Fo.has(f.kind)?f.kind:null;m||n.push(`${d}: kind should be one of ${[...Fo].join(", ")}.`);let g=f.credentials==="per-person";f.credentials!==void 0&&f.credentials!=="shared"&&!g&&n.push(`${d}: credentials should be shared or per-person.`),g&&m&&m!=="api"&&n.push(`${d}: only api sources can be per-person so far.`);let y=new Set(m==="postgres"?["name","kind","secret","schema","credentials"]:m==="bigquery"?["name","kind","dataset","project","credentials"]:m==="snowflake"?["name","kind","secret","account","user","warehouse","database","schema","role","credentials"]:m==="api"?["name","kind","secret","credentials","base_url","auth","headers","resources","oauth"]:["name","kind"]);for(let $ of Object.keys(f))y.has($)||n.push($==="secret"&&m==="bigquery"?`${d}: BigQuery needs no secret: Kuriko's own identity is given access to the dataset.`:`${d}: unknown setting "${$}".`);let S=typeof f.name=="string"&&f.name.trim()?f.name.trim():null;S||n.push(`${d}: needs a name.`);let C=null;if(m==="postgres"||m==="snowflake"||m==="api"){let $=g?"the OAuth client secret":m==="postgres"?"the connection URL":m==="snowflake"?"the private key Kuriko signs in with":"the API key or token";typeof f.secret!="string"||!Vf.test(f.secret)?n.push(`${d}: secret should name the secret in Secret Manager holding ${$} (e.g. warehouse-readonly, or projects/<project>/secrets/<name>), never the secret itself.`):xn(f.secret.split("/").pop())?n.push(`${d}: secret looks like a credential itself. Put it in Secret Manager and name the secret here instead (then rotate it: it's been in this file).`):Jf(f.secret)?n.push(`${d}: ${f.secret} is one of Kuriko's own secrets; a data source needs its own credential.`):C=f.secret}let O={};if(m==="postgres")f.schema!==void 0&&(typeof f.schema!="string"||!f.schema)&&n.push(`${d}.schema should be a schema name.`),O={schema:typeof f.schema=="string"&&f.schema?f.schema:"public"},o.set(u,null);else if(m==="bigquery"){let $=typeof f.dataset=="string"?Gf.exec(f.dataset.trim()):null;if(!$)n.push(`${d}: dataset should be a BigQuery dataset, e.g. analytics (in this project) or other-project.analytics.`);else if(f.project!==void 0&&(typeof f.project!="string"||!Uf.test(f.project)))n.push(`${d}: project should be the Google Cloud project the dataset is in, e.g. acme-data.`);else if($[1]&&f.project!==void 0&&$[1]!==f.project)n.push(`${d}: dataset says project ${$[1]} but project says ${f.project}; keep one.`);else{let T=$[1]??f.project;O={dataset:$[2],...T?{project:T}:{}}}o.set(u,null),a.set(u,Wo)}else if(m==="snowflake"){let $=(T,j,b,v)=>{let K=f[T]??v;typeof K!="string"||!j.test(K.trim())?n.push(`${d}: ${T} should be ${b}.`):O[T]=K.trim()};$("account",Ff,"your Snowflake account identifier, e.g. acme-analytics (orgname-accountname)"),$("user",Wf,"the Snowflake user Kuriko signs in as, e.g. KURIKO_READER"),$("warehouse",Mn,"the warehouse queries run on, e.g. COMPUTE_WH"),$("database",Mn,"the database tools read, e.g. ANALYTICS"),$("schema",Mn,"a schema in that database, e.g. PUBLIC","PUBLIC"),f.role!==void 0&&$("role",Mn,"a Snowflake role the user has, e.g. KURIKO_READ"),o.set(u,null),a.set(u,Wo)}else if(m==="api"){let $=Ko(f,d,g);n.push(...$.problems),O=$.config,o.set(u,new Set($.resources)),c.set(u,new Set($.writable))}S&&m==="bigquery"?s.connectors.push({id:u,name:S,kind:m,config:O,mode:"identity",secretRef:null}):S&&m&&C&&s.connectors.push({id:u,name:S,kind:m,config:O,mode:g?"delegated":"service",secretRef:e(C)})}let l=t.access??[];Array.isArray(l)?l.forEach((u,f)=>{let d=`access[${f+1}]`;if(!xt(u))return void n.push(`${d} should have group, connector, resources and access.`);for(let b of Object.keys(u))["group","connector","resources","access","mask","rows"].includes(b)||n.push(`${d}: unknown setting "${b}".`);let m=typeof u.group=="string"&&u.group.trim()?Yo(u.group):null;m||n.push(`${d}: needs a group (a group email, or everyone).`);let g=typeof u.connector=="string"?u.connector:"";o.has(g)||n.push(`${d}: there's no connector "${g}" in connectors.`);let y=Array.isArray(u.resources)?u.resources.filter(b=>typeof b=="string"):typeof u.resources=="string"?[u.resources]:[];(!y.length||Array.isArray(u.resources)&&y.length!==u.resources.length)&&n.push(`${d}: resources should list what's granted, e.g. [interviews].`);let S=o.get(g);if(S)for(let b of y)S.has(b)||n.push(`${d}: ${g} has no resource "${b}" (it has: ${[...S].join(", ")||"none"}).`);let C=a.get(g)??Bf;if(S===null)for(let b of y)b!==Kf&&!C.test(b)&&n.push(`${d}: "${b}" isn't a table name (or "*" for every table).`);if(u.access==="write"&&o.has(g)){let b=c.get(g)??new Set,v=y.filter(K=>(S?S.has(K):!0)&&!b.has(K));v.length&&n.push(S?`${d}: ${g} can't take new rows in ${v.join(", ")} (read-only: no add in its connector). Use access: read, or describe how to add rows under the resource's add.`:`${d}: ${g} is read-only in Kuriko; use access: read.`)}u.access!=="read"&&u.access!=="write"&&n.push(`${d}: access should be read or write (write includes read).`);let O=u.mask===void 0?[]:Array.isArray(u.mask)&&u.mask.every(b=>typeof b=="string")?u.mask:null;O||n.push(`${d}: mask should be a list of field names.`);let $=u.rows===void 0||u.rows===null?{rule:void 0,problems:[]}:Ro(u.rows,`${d}.rows`,S===null?b=>C.test(b):void 0);if(n.push(...$.problems),!m||!g||!y.length||!O||$.rule===null||u.access!=="read"&&u.access!=="write")return;let T=s.grants.filter(b=>b.group===m&&b.connector===g&&b.access===u.access),j=y.filter(b=>T.some(v=>v.resources.includes(b)));if(j.length)return void n.push(`${d}: ${Mt(m)} already has ${u.access} on ${g}: ${j.join(", ")}. A table can be in one ${u.access} grant per group.`);if(T.some(b=>JSON.stringify(b.rows??null)===JSON.stringify($.rule??null)))return void n.push(`${d}: ${Mt(m)} already has ${u.access} on ${g}${$.rule?" with the same rows":""}; put the resources in one grant.`);s.grants.push({group:m,connector:g,resources:qt(y),access:u.access,mask:qt(O),...$.rule?{rows:$.rule}:{}})}):n.push("access should be a list of grants.");let h=t.clients===void 0||t.clients===null?[...Ie]:t.clients;if(Array.isArray(h)?h.forEach((u,f)=>{let d=`clients[${f+1}]`;if(typeof u!="string"||!u.trim())return void n.push(`${d} should be a client's name or its metadata document URL.`);let m=u.trim(),g=qn(m);if(g?.notYet)return void n.push(`${d}: ${g.name} can't connect to Kuriko yet (${g.notYet}). Leave it commented out for now.`);if(!g&&!Go(m))return void n.push(/^https?:/.test(m)?`${d}: ${m} isn't a client metadata document URL (https, with a path).`:`${d}: Kuriko doesn't know a client called "${m}". Use one of ${Bo.map(y=>y.id).join(", ")}, or the client's metadata document URL.`);if(s.clients.includes(m))return void n.push(`${d}: ${m} is listed twice.`);s.clients.push(m)}):n.push("clients should be a list, e.g. [claude-code, codex]."),n.length)throw new ct(n);return br(s)}var Kt=t=>Array.isArray(t)?t.map(Kt):t&&typeof t=="object"?Object.fromEntries(Object.keys(t).sort().map(e=>[e,Kt(t[e])])):t;function br(t){let e=n=>(s,r)=>n(s).localeCompare(n(r));return{roles:t.roles.map(({group:n,role:s})=>({group:n,role:s})).sort(e(n=>n.group)),connectors:t.connectors.map(({id:n,name:s,kind:r,mode:i,secretRef:o,config:a})=>({id:n,name:s,kind:r,mode:i,secretRef:o,config:Kt(a)})).sort(e(n=>n.id)),grants:t.grants.map(({group:n,connector:s,resources:r,access:i,mask:o,rows:a})=>({group:n,connector:s,resources:qt(r),access:i,mask:qt(o),...a?{rows:Kt(a)}:{}})).sort(e(Hf)),clients:qt(t.clients??[...Ie])}}var Hf=t=>`${t.connector}\0${t.group}\0${t.access}\0${JSON.stringify(t.rows?Kt(t.rows):null)}`;function Jo(t,e){let n=[],s=a=>typeof a=="string"?a:JSON.stringify(a);for(let a of["name","kind","mode","secretRef"])t[a]!==e[a]&&n.push(`${a} ${s(t[a])} \u2192 ${s(e[a])}`);let r=(a,c="")=>Object.entries(a).flatMap(([l,h])=>h&&typeof h=="object"&&!Array.isArray(h)?r(h,`${c}${l}.`):[[`${c}${l}`,h]]),i=new Map(r(t.config)),o=new Map(r(e.config));for(let a of new Set([...i.keys(),...o.keys()]))JSON.stringify(i.get(a))!==JSON.stringify(o.get(a))&&n.push(`${a} ${i.has(a)?s(i.get(a)):"(none)"} \u2192 ${o.has(a)?s(o.get(a)):"(none)"}`);return n.length?n:["(settings differ only in form)"]}var ze=(t,e)=>{let n=/^projects\/([^/]+)\/secrets\/(.+)$/.exec(t);return n&&(!e||n[1]===e)?n[2]:t};function Kn(t){switch(t.kind){case"role":return t.op==="add"?`${t.group} becomes ${t.to}`:t.op==="change"?`${t.group}: ${t.from} \u2192 ${t.to}`:`${t.group} is no longer ${t.from}`;case"connector":return`data source ${t.id}: ${t.summary}`;case"grant":return`${Mt(t.group)}: ${t.summary}`;case"client":return t.op==="add"?`people can connect with ${Lt(t.client)}`:`people can no longer connect with ${Lt(t.client)}`}}p();import{spawn as Qf}from"node:child_process";import{stripVTControlCharacters as Zf}from"node:util";var ee=class extends Error{command;code;stderr;constructor(e,n,s){let r=Zf(s);super(`${e} failed (exit ${n})${r.trim()?`:
144
144
  ${r.trim().split(`
145
145
  `).slice(-15).join(`
146
- `)}`:""}`),this.command=e,this.code=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.
146
+ `)}`:""}`),this.command=e,this.code=n,this.stderr=r}get reason(){let e=this.stderr.split(`
147
+ `).map(n=>n.replace(/^[│╷╵\s]+/,"").trim()).filter(Boolean);return e.find(n=>/^error\b/i.test(n))?.replace(/^error:?\s*/i,"")??e[0]??`exit ${this.code}`}},zo=t=>/invalid_rapt|reauth related error|invalid_grant|Reauthentication (is )?(required|failed)/i.test(t);function L(t,e,n={}){return new Promise((s,r)=>{let i=t==="gcloud"&&!n.inherit?{CLOUDSDK_CORE_DISABLE_PROMPTS:"1"}:{},o=Qf(t,e,{cwd:n.cwd,env:{...process.env,...i,...n.env},stdio:n.inherit?"inherit":[n.input===void 0?"ignore":"pipe","pipe","pipe"]});n.input!==void 0&&o.stdin?.end(n.input);let a="",c="";o.stdout?.on("data",l=>(a+=l,n.tee&&process.stdout.write(l))),o.stderr?.on("data",l=>(c+=l,n.tee&&process.stderr.write(l))),o.on("error",l=>r(new ee(t,null,l.message))),o.on("close",l=>l===0?s(a):r(new ee(`${t} ${e[0]??""}`.trim(),l,c)))})}async function Q(t,e,n={}){return JSON.parse(await L(t,e,n))}async function He(t,e="--version"){try{return await L(t,[e]),!0}catch{return!1}}p();var pr=Cf(ql(),1);import{existsSync as Eo,readFileSync as _o,writeFileSync as Qu}from"node:fs";import{join as Co}from"node:path";p();var bn="kuriko-idp-client-secret",wn={ring:"kuriko",key:"user-tokens"};var Ml=["serviceusage.googleapis.com","cloudresourcemanager.googleapis.com","run.googleapis.com","sqladmin.googleapis.com","secretmanager.googleapis.com","cloudkms.googleapis.com","artifactregistry.googleapis.com","iam.googleapis.com","cloudidentity.googleapis.com","storage.googleapis.com","cloudbuild.googleapis.com","pubsub.googleapis.com"],Kl=["module.kuriko.google_project_service.apis","module.kuriko.google_artifact_registry_repository.kuriko","module.kuriko.google_service_account.gateway","module.kuriko.google_service_account.web","module.kuriko.google_service_account.tools"],_m=/^[a-z][a-z0-9-]{4,28}[a-z0-9]$/,eo=t=>_m.test(t),Dl=t=>/^[a-z]+-[a-z]+\d+$/.test(t),Bl=t=>/^\d+-[a-z0-9]+\.apps\.googleusercontent\.com$/.test(t),xs=t=>/^[^\s@'"\\]+@[^\s@'"\\]+\.[^\s@'"\\]+$/.test(t);function Ul(t){let e=new Set(t);for(let n=0;;n++){let s=n===0?"kuriko":`kuriko-${n}`;if(!e.has(s))return s}}function Gl(t){let e=/^(.*?)-(\d+)$/.exec(t);return e?`${e[1]}-${Number(e[2])+1}`:`${t}-1`}function Fl(t){return/(failed to create instance|google_sql_database_instance)[\s\S]{0,400}(instanceAlreadyExists|already exists|reuse the name)/i.test(t)}function Wl(t){return/IAM_PERMISSION_DENIED|SERVICE_DISABLED|has not been used in project|it is disabled|API .* not enabled|Permission '.*' denied/i.test(t)}var st=(t,e)=>{let n=`https://kuriko-web-${e}.${t.region}.run.app`;return{web:n,mcp:`https://kuriko-gateway-${e}.${t.region}.run.app/mcp`,redirect:`${n}/api/auth/sso/callback/idp`,newClient:`https://console.cloud.google.com/auth/clients/create?project=${t.project}`,registry:`${t.region}-docker.pkg.dev/${t.project}/kuriko`,webServiceAccount:`kuriko-web@${t.project}.iam.gserviceaccount.com`}},X=t=>JSON.stringify(t);function Yl(t,e,n,s=null,r=!!s){let i=s&&r?`${t.region}-docker.pkg.dev/${t.project}/kuriko-releases/${s.owner}`:`${t.region}-docker.pkg.dev/${t.project}/kuriko`;return`# Kuriko install for ${t.domain}, written by \`kuriko install\`. Holds no secrets.
148
148
  terraform {
149
149
  backend "gcs" {
150
- bucket = ${X(s)}
150
+ bucket = ${X(n)}
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 }${n?`
157
+ variable "db_instance_name" { type = string }${s?`
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" {
@@ -182,11 +182,11 @@ module "kuriko" {
182
182
  client_id = var.idp_client_id
183
183
  domain = ${X(t.domain)}
184
184
  groups_source = "google-workspace"
185
- }${n?`
185
+ }${s?`
186
186
  release_registry = {
187
- upstream = ${X(n.upstream)}
188
- username = ${X(n.username)}
189
- token_secret_name = ${X(n.tokenSecret)}
187
+ upstream = ${X(s.upstream)}
188
+ username = ${X(s.username)}
189
+ token_secret_name = ${X(s.tokenSecret)}
190
190
  token_version = var.release_token_version
191
191
  }`:""}
192
192
  }
@@ -197,57 +197,57 @@ 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
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 {
200
+ `}function Vl(t,e,n=null){return[`version_tag = ${X(e)}`,`idp_client_id = ${X(t.idpClientId??"")}`,`db_instance_name = ${X(t.dbInstanceName)}`,...n?[`release_token_version = ${X(n.tokenVersion)}`]:[],""].join(`
201
+ `)}var qs="module.kuriko.google_sql_database_instance.kuriko",kn={gateway:"kuriko-gateway",web:"kuriko-web",builder:"kuriko-builder",tools:"kuriko-tools",events:"kuriko-events"};function Jl(t,e){let n=`projects/${t.project}/locations/${t.region}/keyRings/${wn.ring}`;return["# Written by `kuriko install`: things already in the project that this install takes over.",...e.ring?[`import {
202
202
  to = module.kuriko.google_kms_key_ring.kuriko
203
- id = ${X(s)}
203
+ id = ${X(n)}
204
204
  }`]:[],...e.key?[`import {
205
205
  to = module.kuriko.google_kms_crypto_key.user_tokens
206
- id = ${X(`${s}/cryptoKeys/${ys.key}`)}
206
+ id = ${X(`${n}/cryptoKeys/${wn.key}`)}
207
207
  }`]:[],...e.sqlInstance?[`import {
208
- to = ${Ln}
208
+ to = ${qs}
209
209
  id = ${X(`projects/${t.project}/instances/${e.sqlInstance}`)}
210
210
  }`]:[],...(e.accounts??[]).map(r=>`import {
211
211
  to = module.kuriko.google_service_account.${r}
212
- id = ${X(`projects/${t.project}/serviceAccounts/${bs[r]}@${t.project}.iam.gserviceaccount.com`)}
212
+ id = ${X(`projects/${t.project}/serviceAccounts/${kn[r]}@${t.project}.iam.gserviceaccount.com`)}
213
213
  }`)].join(`
214
214
 
215
215
  `)+`
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")}
216
+ `}function Ms(t){let e=[];for(let n of t.resource_changes??[]){let s=n.change.actions,r=s.includes("delete")&&s.includes("create")?"replace":s[0]==="create"||s[0]==="update"||s[0]==="delete"?s[0]:null;r&&e.push({address:n.address.replace(/^module\.kuriko\./,""),action:r})}return e}var Ks=new Set(["module.kuriko.google_project_iam_member.gateway_connector_secrets"]);function zl(t){return(t.resource_changes??[]).filter(e=>e.change.actions.includes("delete")&&!(Ks.has(e.address)&&e.change.actions.length===1)).map(e=>e.address)}var Cm={admins:["platform","infra","sre","devops","it","ops","security","secops","admin","admins","cloud","engineering-leads"],builders:["eng","engineering","engineers","dev","developers","product","builders","ops","operations","data","analytics","tech"]};function Hl(t,e,n=6){let s=Cm[e],r=i=>{let o=`${i.email.split("@")[0]} ${i.name}`.toLowerCase().split(/[^a-z0-9]+/),a=s.findIndex(c=>o.includes(c));return a<0?1/0:a};return t.map(i=>({g:i,s:r(i)})).filter(i=>i.s!==1/0).sort((i,o)=>i.s-o.s||i.g.email.localeCompare(o.g.email)).slice(0,n).map(i=>i.g)}var Ql=(t,e)=>{let n=e.trim().toLowerCase();return t.filter(s=>s.email.includes(n)||s.name.toLowerCase().includes(n))};p();p();import{emitKeypressEvents as Xl}from"node:readline";import{createInterface as eu}from"node:readline/promises";import{Writable as Nm}from"node:stream";import{stripVTControlCharacters as Zl,styleText as vt}from"node:util";var _=t=>vt("bold",t),A=t=>vt("dim",t),be=t=>vt("red",t),Ue=t=>vt("green",t),rt=t=>vt("yellow",t),$t=t=>vt("cyan",t),tu="\u280B\u2819\u2839\u2838\u283C\u2834\u2826\u2827\u2807\u280F",kt=null,no=null,to=null,so=0,ro=!1,io=!1,oo=()=>process.stdout.isTTY===!0;function Ds(t){let e=Math.floor((Date.now()-t)/1e3);return e<60?`${e}s`:`${Math.floor(e/60)}m ${String(e%60).padStart(2,"0")}s`}function Tm(){let t=[kt&&`${kt.text} ${A(Ds(kt.start))}`,no?.()&&A(no())].filter(s=>!!s);if(!t.length)return null;let e=(process.stdout.columns||80)-1,n=`${$t(tu[so])} ${t.join(A(" \xB7 "))}`;return Zl(n).length<=e?n:Zl(n).slice(0,e)}function Bs(){oo()&&io&&process.stdout.write("\r\x1B[2K"),io=!1}function St(){if(!oo()||ro)return;Bs();let t=Tm();t&&(process.stdout.write(t),io=!0)}function nu(){to||!oo()||(to=setInterval(()=>{so=(so+1)%tu.length,St()},100),to.unref())}function $n(t){Bs(),console.log(t),St()}async function P(t,e){let n=kt;kt={text:t,start:Date.now()},nu(),St();try{return await e()}finally{kt=n,Bs(),St()}}function ao(t){no=t,nu(),St()}async function At(t){ro=!0,Bs();try{return await t()}finally{ro=!1,St()}}var k=(t="")=>$n(t),M=t=>$n(`
217
+ ${_("\u2192")} ${t}`),N=t=>$n(` ${Ue("\u2713")} ${t}`),x=t=>$n(` ${rt("!")} ${t}`);function Us(){if(!process.stdin.isTTY)throw new Error("This needs answers typed at a terminal; run it in your own terminal, not through a pipe.")}async function V(t,e){return Us(),At(async()=>{let n=eu({input:process.stdin,output:process.stdout});try{return(await n.question(e?`${t} ${A(`[${e}]`)} `:`${t} `)).trim()||e||""}finally{n.close()}})}async function z(t,e=!1){let n=(await V(`${t} ${A(e?"[Y/n]":"[y/N]")}`)).toLowerCase();return n?n==="y"||n==="yes":e}async function Gs(t){return Us(),At(()=>Om(t))}async function Om(t){let e=!1,n=new Nm({write(r,i,o){e||process.stdout.write(r),o()}}),s=eu({input:process.stdin,output:n,terminal:!0});try{let r=s.question(`${t} `);e=!0;let i=await r;return process.stdout.write(`
218
+ `),i.trim()}finally{s.close()}}async function oe(t,e){Us();let n=e.map((s,r)=>s.disabled?-1:r).filter(s=>s>=0);if(!n.length)throw new Error(`Nothing to choose for: ${t}`);return At(()=>new Promise(s=>{let r=process.stdin,i=r.isRaw,o=n[0],a=(f,d)=>{let m=f.disabled?A(f.label):d===o?_(f.label):f.label;return`${d===o?$t(" \u203A"):" "} ${m}${f.hint?` ${A(f.hint)}`:""}`},c=f=>{f||process.stdout.write(`\x1B[${e.length}A`);for(let[d,m]of e.entries())process.stdout.write(`\r\x1B[2K${a(m,d)}
219
+ `)},l=f=>{let d=n.indexOf(o);o=n[(d+f+n.length)%n.length],c(!1)},h=()=>{r.off("keypress",u),r.setRawMode(i),r.pause(),process.stdout.write(`\x1B[${e.length+1}A\r\x1B[J${t} ${$t(e[o].label)}
220
+ `),s(e[o].value)},u=(f,d={})=>{if(d.ctrl&&d.name==="c"){r.setRawMode(i),process.stdout.write(`
221
+ `),process.kill(process.pid,"SIGINT");return}d.name==="up"||d.name==="k"?l(-1):d.name==="down"||d.name==="j"||d.name==="tab"?l(1):d.name==="return"||d.name==="enter"?h():f&&/^[1-9]$/.test(f)&&n.includes(Number(f)-1)&&(o=Number(f)-1,c(!1))};process.stdout.write(`${t} ${A("(\u2191/\u2193, Enter)")}
222
+ `),c(!0),Xl(r),r.setRawMode(!0),r.resume(),r.on("keypress",u)}))}async function Fs(t,e,n){Us();let s=e.map((r,i)=>r.disabled?-1:i).filter(r=>r>=0);if(!s.length)throw new Error(`Nothing to choose for: ${t}`);return At(()=>new Promise(r=>{let i=process.stdin,o=i.isRaw,a=e.map(m=>!m.disabled&&n(m.value)),c=s[0],l=(m,g)=>m.disabled?` ${A(`\u25CB ${m.label}${m.hint?` ${m.hint}`:""}`)}`:`${g===c?$t(" \u203A"):" "} ${a[g]?Ue("\u25C9"):A("\u25CB")} ${g===c?_(m.label):m.label}${m.hint?` ${A(m.hint)}`:""}`,h=m=>c=s[(s.indexOf(c)+m+s.length)%s.length],u=m=>{m||process.stdout.write(`\x1B[${e.length}A`);for(let[g,y]of e.entries())process.stdout.write(`\r\x1B[2K${l(y,g)}
223
+ `)},f=()=>{i.off("keypress",d),i.setRawMode(o),i.pause();let m=e.filter((g,y)=>a[y]);process.stdout.write(`\x1B[${e.length+1}A\r\x1B[J${t} ${$t(m.map(g=>g.label).join(", ")||"none")}
224
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:
225
+ `),process.kill(process.pid,"SIGINT");return}if(g.name==="up"||g.name==="k")h(-1);else if(g.name==="down"||g.name==="j"||g.name==="tab")h(1);else if(g.name==="space")a[c]=!a[c];else return g.name==="return"||g.name==="enter"?f():void 0;u(!1)};process.stdout.write(`${t} ${A("(\u2191/\u2193, Space to tick, Enter)")}
226
+ `),u(!0),Xl(i),i.setRawMode(!0),i.resume(),i.on("keypress",d)}))}async function co(t,e){let n=e.filter(s=>!s.disabled);return n.length===1&&e.length===1?(k(`${t} ${$t(n[0].label)}`),n[0].value):oe(t,e)}function Ee(t,e){$n(`
227
+ ${_("\u270B")} ${_(t)}
228
+ ${e.map(n=>n?` ${n}`:"").join(`
229
+ `)}`)}var Sn=async t=>{try{return await L("gcloud",t),!0}catch(e){if(e instanceof ee&&/NOT_FOUND|not found|does not exist|404/i.test(e.stderr))return!1;throw e}},Et=async()=>(await L("gcloud",["config","get","account"])).trim();async function te(t={}){let e=async n=>{try{return await L("gcloud",n),null}catch(s){return s instanceof ee&&zo(s.stderr)?"expired":"missing"}};for(let n=!1;;n=!0){let[s,r]=await Promise.all([t.terraformOnly?null:e(["auth","print-access-token"]),e(["auth","application-default","print-access-token"])]);if(!s&&!r)return;let i=await Et().catch(()=>""),c=`${[s&&"gcloud",r&&"Terraform"].filter(Boolean).join(" and ")}${s==="expired"||r==="expired"?`'s Google sign-in${s&&r?"s have":" has"} expired`:` ${s&&r?"aren't":"isn't"} signed in to Google`}`,l=s?["auth","login",...i?[i]:[],"--force",...r?["--update-adc"]:[]]:["auth","application-default","login"];if(!n&&process.stdin.isTTY&&(x(`${c}.`),await z(` Sign in${i?` as ${i}`:""} now? (opens your browser)`,!0))){await At(()=>L("gcloud",l,{inherit:!0}));continue}throw new Error(`${c}. Run:
230
+ gcloud ${l.join(" ")}`)}}async function _t(){return(await Q("gcloud",["organizations","list","--format=json"])).map(t=>({id:t.name.split("/")[1],name:t.displayName,customerId:t.owner?.directoryCustomerId??null}))}async function su(){return(await Q("gcloud",["billing","accounts","list","--format=json"])).filter(t=>t.open).map(t=>({id:t.name.split("/")[1],name:t.displayName}))}async function Ge(t){try{let e=await Q("gcloud",["projects","describe",t,"--format=json"]);return{number:e.projectNumber,state:e.lifecycleState}}catch(e){if(e instanceof ee&&/not found|does not exist|permission/i.test(e.stderr))return null;throw e}}var ru=(t,e)=>L("gcloud",["projects","create",t,`--organization=${e}`,"--name=Kuriko"]);async function iu(t){return(await Q("gcloud",["billing","projects","describe",t,"--format=json"])).billingEnabled===!0}var ou=(t,e)=>L("gcloud",["billing","projects","link",t,`--billing-account=${e}`]);async function au(t){try{return(await L("gcloud",["billing","projects","list",`--billing-account=${t}`,"--format=value(projectId)"])).split(`
231
+ `).map(n=>n.trim()).filter(Boolean)}catch{return null}}var cu=t=>t instanceof ee&&/billing quota exceeded|QuotaFailure/i.test(t.stderr),Ys=(t,e)=>L("gcloud",["services","enable",...e,`--project=${t}`]);async function lu(t,e,n){return await Sn(["storage","buckets","describe",`gs://${t}`,"--format=json"])?"exists":(await L("gcloud",["storage","buckets","create",`gs://${t}`,`--project=${e}`,`--location=${n}`,"--uniform-bucket-level-access","--public-access-prevention"]),await L("gcloud",["storage","buckets","update",`gs://${t}`,"--versioning"]),"created")}async function uu(t){return(await Q("gcloud",["sql","instances","list",`--project=${t}`,"--format=json"])).map(e=>({name:e.name,kuriko:e.settings?.userLabels?.["managed-by"]==="kuriko"}))}async function fu(t,e,n,s){let r=[`--location=${e}`,`--project=${t}`,"--format=json"],i=await Sn(["kms","keyrings","describe",n,...r]);return{ring:i,key:i&&await Sn(["kms","keys","describe",s,`--keyring=${n}`,...r])}}async function du(t,e){let n=(await L("gcloud",["iam","service-accounts","list",`--project=${t}`,"--format=value(email)"])).split(`
232
+ `).map(s=>s.trim());return e.filter(s=>n.includes(`${s}@${t}.iam.gserviceaccount.com`))}async function pu(t){return Sn(["artifacts","docker","images","describe",t,"--format=json"])}async function vn(t,e){return await Sn(["secrets","describe",e,`--project=${t}`,"--format=json"])?(await Q("gcloud",["secrets","versions","list",e,`--project=${t}`,"--filter=state:ENABLED","--format=json"])).length>0:null}async function Ct(t,e,n){await vn(t,e)===null?await L("gcloud",["secrets","create",e,`--project=${t}`,"--replication-policy=automatic","--labels=managed-by=kuriko-security-team","--data-file=-"],{input:n}):await L("gcloud",["secrets","versions","add",e,`--project=${t}`,"--data-file=-"],{input:n})}async function hu(t,e,n){try{let r=await(await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:t,client_secret:e,code:"kuriko-install-check",redirect_uri:n,grant_type:"authorization_code"})})).json().catch(()=>({}));return r.error==="invalid_client"||r.error==="unauthorized_client"?!1:r.error==="invalid_grant"?!0:null}catch{return null}}async function Ws(t,e,n){let s=(await L("gcloud",["auth","print-access-token"])).trim(),r=new URL(`https://cloudidentity.googleapis.com/v1/${e}`);for(let[o,a]of Object.entries(n))r.searchParams.set(o,a);let i=await fetch(r,{headers:{authorization:`Bearer ${s}`,"x-goog-user-project":t}});if(i.status===404||i.status===403)return null;if(!i.ok)throw new Error(`Cloud Identity ${i.status}: ${(await i.text()).slice(0,300)}`);return await i.json()}async function gu(t,e,n,s){let r=(await L("gcloud",["auth","print-access-token"])).trim(),i=new URL(`https://cloudidentity.googleapis.com/v1/${e}`);for(let[a,c]of Object.entries(n))i.searchParams.set(a,c);let o=await fetch(i,{method:"POST",headers:{authorization:`Bearer ${r}`,"x-goog-user-project":t,"content-type":"application/json"},body:JSON.stringify(s)});return{status:o.status,text:await o.text()}}async function mu(t,e){let n=await gu(t,"groups",{initialGroupConfig:e.owner?"WITH_INITIAL_OWNER":"EMPTY"},{parent:`customers/${e.customerId}`,groupKey:{id:e.email},displayName:e.name,description:e.description,labels:{"cloudidentity.googleapis.com/groups.discussion_forum":""}});if(n.status===409)return"exists";if(n.status>=300)throw new Error(`Couldn't create ${e.email} (${n.status}): ${n.text.slice(0,300)}`);return"created"}async function Vs(t,e){let n=[],s="";do{let r=await Ws(t,"groups",{parent:`customers/${e}`,view:"BASIC",pageSize:"500",...s?{pageToken:s}:{}});if(!r)return n.length?n:null;for(let i of r.groups??[])i.groupKey?.id&&n.push({email:i.groupKey.id.toLowerCase(),name:i.displayName??"",description:i.description??""});s=r.nextPageToken??""}while(s&&n.length<2e4);return n.sort((r,i)=>r.email.localeCompare(i.email))}async function lo(t,e,n){let s=await Ws(t,"groups:lookup",{"groupKey.id":e});if(!s?.name)throw new Error(`Group ${e} not found`);let r=await gu(t,`${s.name}/memberships`,{},{preferredMemberKey:{id:n},roles:[{name:"MEMBER"}]});if(r.status===409)return"exists";if(r.status>=300)throw new Error(`Couldn't add ${n} to ${e} (${r.status}): ${r.text.slice(0,300)}`);return"added"}async function Js(t,e,n){let s=await Ws(t,"groups:lookup",{"groupKey.id":e});if(!s?.name)return{exists:!1,isMember:!1};let r="";do{let i=await Ws(t,`${s.name}/memberships:searchTransitiveMemberships`,{pageSize:"500",...r?{pageToken:r}:{}});if(i?.memberships?.some(o=>o.preferredMemberKey?.some(a=>a.id?.toLowerCase()===n.toLowerCase())))return{exists:!0,isMember:!0};r=i?.nextPageToken??""}while(r);return{exists:!0,isMember:!1}}async function Nt(t,e,n,s){let r=[`--project=${t}`,`--region=${e}`],o=(await Q("gcloud",["run","jobs","execute",n,...r,"--async","--format=json",...s?[`--args=^;;^${s.join(";;")}`]:[]])).metadata.name;for(;!(await Q("gcloud",["run","jobs","executions","describe",o,...r,"--format=json"])).status?.completionTime;)await new Promise(c=>setTimeout(c,3e3));for(let a=0;a<12;a++){let l=(await Q("gcloud",["logging","read",`resource.type="cloud_run_job" AND labels."run.googleapis.com/execution_name"="${o}"`,`--project=${t}`,"--freshness=1h","--order=asc","--format=json"])).map(u=>u.textPayload??"").filter(Boolean),h=l.map(u=>/Container called exit\((\d+)\)/.exec(u)).find(Boolean);if(h)return{code:Number(h[1]),logs:l.filter(u=>!/Container called exit/.test(u))};await new Promise(u=>setTimeout(u,5e3))}return{code:null,logs:[]}}async function yu(t,e){return(await L("gcloud",["secrets","versions","list",e,`--project=${t}`,"--filter=state:ENABLED","--sort-by=~createTime","--limit=1","--format=value(name)"])).trim().split("/").pop()||null}async function wu(t,e){return(await L("gcloud",["secrets","versions","access","latest",`--secret=${e}`,`--project=${t}`])).trim()}async function uo(t,e,n=18e4){let s=(await L("gcloud",["auth","print-access-token"])).trim(),r=Date.now()+n;for(;;){let i=await fetch(`https://serviceusage.googleapis.com/v1beta1/projects/${t}/services/${e}:generateServiceIdentity`,{method:"POST",headers:{authorization:`Bearer ${s}`,"x-goog-user-project":t}});if(i.ok)return;let o=await i.text();if(i.status!==403||Date.now()>r)throw new Error(`Couldn't set up ${e}'s service account (${i.status}): ${o.slice(0,200)}`);await new Promise(a=>setTimeout(a,1e4))}}async function bu(t,e,n,s,r){try{let i=`${t.owner}/${s}`,o=Buffer.from(`${e}:${n}`).toString("base64"),a=await fetch(`https://${t.host}/token?service=${t.host}&scope=repository:${i}:pull`,{headers:{authorization:`Basic ${o}`}});if(a.status===401||a.status===403)return"denied";if(!a.ok)return"unreachable";let{token:c}=await a.json(),l=await fetch(`https://${t.host}/v2/${i}/manifests/${r}`,{method:"HEAD",headers:{authorization:`Bearer ${c}`,accept:"application/vnd.oci.image.index.v1+json, application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json, application/vnd.docker.distribution.manifest.list.v2+json"}});return l.ok?"ok":l.status===401||l.status===403?"denied":l.status===404?"missing":"unreachable"}catch{return"unreachable"}}var fo="roles/secretmanager.secretAccessor",zs=t=>{let e=/^projects\/([^/]+)\/secrets\/([^/]+)$/.exec(t);if(!e)throw new Error(`Not a secret reference: ${t}`);return[e[1],e[2]]};async function An(t){let[e,n]=zs(t);return L("gcloud",["secrets","describe",n,`--project=${e}`,"--format=value(name)"]).then(()=>!0,()=>!1)}async function En(t,e){let[n,s]=zs(t);return!!(await Q("gcloud",["secrets","get-iam-policy",s,`--project=${n}`,"--format=json"])).bindings?.some(i=>i.role===fo&&!i.condition&&i.members?.includes(e))}async function po(t,e){let[n,s]=zs(t);await L("gcloud",["secrets","add-iam-policy-binding",s,`--project=${n}`,`--member=${e}`,`--role=${fo}`,"--condition=None","--format=none"])}async function ku(t,e){let[n,s]=zs(t);await An(t)&&await En(t,e)&&await L("gcloud",["secrets","remove-iam-policy-binding",s,`--project=${n}`,`--member=${e}`,`--role=${fo}`,"--condition=None","--format=none"])}async function $u(t){let e=(await L("gcloud",["auth","print-access-token"])).trim(),n=await fetch(`https://bigquery.googleapis.com/bigquery/v2/${t}`,{headers:{authorization:`Bearer ${e}`}});return{status:n.status,body:await n.json().catch(()=>({}))}}async function Su(t){let e=await $u(`projects/${t}/datasets?maxResults=1000`).catch(()=>null);return!e||e.status!==200?null:(e.body.datasets??[]).map(n=>({id:n.datasetReference.datasetId,location:n.location}))}var Im=new Set(["READER","WRITER","OWNER","roles/bigquery.dataViewer","roles/bigquery.dataEditor","roles/bigquery.dataOwner","roles/bigquery.admin"]),Pm=new Set(["roles/bigquery.dataViewer","roles/bigquery.dataEditor","roles/bigquery.dataOwner","roles/bigquery.admin","roles/viewer","roles/editor","roles/owner"]);async function vu(t,e,n){let s=`serviceAccount:${n}`,r=await $u(`projects/${t}/datasets/${e}`);if(r.status===404)return"missing";if(r.status===200){let o=r.body.access??[],a=c=>c.userByEmail?.toLowerCase()===n.toLowerCase()||c.iamMember===s||c.specialGroup==="allAuthenticatedUsers"||c.iamMember==="allAuthenticatedUsers"||c.iamMember==="allUsers";if(o.some(c=>a(c)&&Im.has(c.role??"")))return"readable"}let i=await Q("gcloud",["projects","get-iam-policy",t,"--format=json"]).catch(()=>null);return i?.bindings?.some(o=>Pm.has(o.role)&&!o.condition&&o.members?.includes(s))?"readable":r.status===200&&i?"not-readable":"unknown"}p();import{basename as Ou,relative as qm,resolve as Iu}from"node:path";p();import{existsSync as Hs,readdirSync as jm,readFileSync as Qs}from"node:fs";import{homedir as Rm}from"node:os";import{dirname as ho,join as _e,relative as Lm,resolve as _n}from"node:path";import{fileURLToPath as xm}from"node:url";var H=_n(xm(new URL("../../..",import.meta.url))),Ot="kuriko-installs.json";function ne(t=process.cwd(),e=process.env){for(let n=_n(t);;n=ho(n)){if(Hs(_e(n,Ot)))return n;if(ho(n)===n)break}for(let n of[e.KURIKO_INSTALLS,_e(ho(H),"kuriko-installs")])if(n&&Hs(_e(n,Ot)))return _n(n);return null}var Zs=`No installs repo found. Installs live in a git repo you share with whoever runs Kuriko:
233
+ clone yours next to the Kuriko checkout (or cd into it), or start one with: kuriko init <folder>`;function Fe(t=process.cwd(),e){let n=e&&ne(_n(t,e))||ne(t);if(!n)throw new Error(Zs);return n}function Cn(t,e=process.cwd(),n=ne(e)){if(t){let r=[_n(e,t),n&&_e(n,t)].find(i=>!!i&&go(i));if(!r)throw new Error(`No Kuriko install at ${t}. Run kuriko list to see them.`);return r}let s=it(e,n);if(s.length===1)return s[0];throw s.length>1?new Error(`Several installs; choose one with --dir:
234
+ ${s.map(r=>` ${r}`).join(`
235
+ `)}`):new Error(n?"No Kuriko installs yet. Start one with: kuriko install":Zs)}function it(t=process.cwd(),e=ne(t)){return go(t)?[t]:!e||!Hs(e)?[]:jm(e).sort().map(n=>_e(e,n)).filter(go)}function D(t,e=process.cwd()){let n=Lm(e,t);if(n&&!n.startsWith(".."))return n;let s=Rm();return t.startsWith(s)?`~${t.slice(s.length)}`:t}function Au(t){let e=Qs(_e(t,"main.tf"),"utf8"),n=s=>new RegExp(`^\\s*${s}\\s*=\\s*"([^"]+)"`,"m").exec(e)?.[1]??null;return{project:n("project_id"),region:n("region")}}var Eu=t=>/requested project was not found|project .* (was )?not found|has been deleted|DELETE_REQUESTED/i.test(t);function _u(t){let e=t.filter(n=>n&&!/(^|\.)data\./.test(n));return e.includes("module.kuriko.google_cloud_run_v2_service.web")&&e.includes("module.kuriko.google_cloud_run_v2_service.gateway")?"installed":e.length?"partial":"empty"}function go(t){let e=_e(t,"main.tf");return Hs(e)&&/module\s+"kuriko"/.test(Qs(e,"utf8"))}function Cu(t){let e=Qs(_e(t,"main.tf"),"utf8");return/variable\s+"deletion_protection"/.test(e)&&/deletion_protection\s*=\s*var\.deletion_protection/.test(e)}function Nu(t){try{let e=JSON.parse(Qs(_e(t,".terraform","terraform.tfstate"),"utf8"));return e?.backend?.type==="gcs"?`gs://${e.backend.config.bucket}/${e.backend.config.prefix??""}`:null}catch{return null}}function Tu(t){let e=t.values?.root_module;return[...e?.resources??[],...(e?.child_modules??[]).flatMap(n=>n.resources??[])]}var le=(t,e)=>L("git",["-C",t,...e]);async function Pu(t){try{return(await le(t,["rev-parse","--show-toplevel"])).trim()}catch{return null}}async function Mm(t){return(await le(t,["rev-parse","--abbrev-ref","HEAD"]).catch(()=>"HEAD")).trim()}async function ju(t){try{return(await le(t,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"])).trim()}catch{return null}}async function ke(t){let e=await Pu(t);if(!e)return;let n=await ju(e);if(!n)return;await P("Checking the installs repo is up to date",()=>le(e,["fetch","--quiet"]));let s=Number((await le(e,["rev-list","--count","HEAD..@{u}"])).trim());if(s>0)throw new Error(`The installs repo is ${s} commit${s===1?"":"s"} behind ${n}. Pull first:
236
+ git -C ${D(e)} pull`)}async function We(t,e,n={}){let s=await Pu(t[0]);if(!s){let l=ne(t[0])??t[0];x(`${D(l)} isn't in a git repo, so this change has no history and nobody else can see it.`),k(` Make it one and add a private remote: ${_(`git -C ${D(l)} init`)}, then ${_("git remote add origin <url>")} and push.`);return}let r=ne(t[0]),i=!!r&&Iu(r)!==Iu(s),o=t.map(l=>qm(s,l)||".");if(await le(s,n.remove?["rm","-r","-q","--ignore-unmatch","--",...o]:["add","-A","--",...o]),!(await le(s,["diff","--cached","--name-only","--",...o])).trim())return;let c=i?null:await ju(s);if(!process.stdin.isTTY){x(`Left uncommitted in ${D(s)} (no terminal to ask). Commit it so others running Kuriko see the change:`),k(` ${_(`git -C ${D(s)} commit -m ${JSON.stringify(e)} -- ${o.join(" ")}`)}${c?` && git -C ${D(s)} push`:""}`);return}if(!await z(`
237
+ Commit this to ${i?`${Ou(s)} (on ${await Mm(s)})`:"the installs repo"}${c?` and push to ${c}`:""}?`,!0)){x(`Left uncommitted in ${D(s)}. Commit it so others running Kuriko see the change.`);return}await le(s,["commit","-q","-m",e,"--",...o]),c?(await P("Pushing",()=>le(s,["push","-q"])),N(`Committed and pushed: ${e}`)):i?(N(`Committed: ${e}`),k(` Push it and open a pull request as you usually would, so it's reviewed with the rest of ${Ou(s)}.`)):(N(`Committed: ${e}`),k(` (no remote to push to; add one so others can pull it: ${_(`git -C ${D(s)} remote add origin <url>`)})`))}async function Ru(t,e,n){let s=i=>i.replace(/-dirty-.*$/,"");if(s(e)===s(n))return"same";let r=async(i,o)=>{try{return await le(t,["merge-base","--is-ancestor",s(i),s(o)]),!0}catch{return!1}};return await r(e,n)?"forward":await r(n,e)?"backward":await mo(t,e,n)?"forward":"unknown"}async function mo(t,e,n){let s=r=>r.replace(/-dirty-.*$/,"");if(e!==s(e))return null;try{let r=(await le(t,["rev-parse",`${s(e)}^{tree}`])).trim(),i=(await le(t,["log","--format=%H %T","-n","1000",s(n)])).split(`
238
+ `).find(o=>o.endsWith(` ${r}`));return i?i.split(" ")[0].slice(0,e.length):null}catch{return null}}p();import{existsSync as Km}from"node:fs";import{basename as Dm,join as Bm}from"node:path";var Xs={installed:{mark:"\u25CF",text:"installed"},partial:{mark:"\u25D0",text:"partly installed"},empty:{mark:"\u25CB",text:"not installed"},gone:{mark:"\u25CB",text:"project deleted"},unknown:{mark:"?",text:"status unknown"}};async function Um(t){let{project:e,region:n}=Au(t),s={dir:t,project:e??Dm(t),region:n??"?",status:"unknown"};if(!Km(Bm(t,".terraform")))return{...s,detail:"Terraform isn't set up here yet (run install to continue)"};try{let[r,i]=await Promise.all([L("terraform",["state","list","-no-color"],{cwd:t}),L("terraform",["output","-json"],{cwd:t}).then(o=>JSON.parse(o))]);s.status=_u(r.split(`
239
+ `)),s.status==="installed"&&(s.web=String(i.web_url?.value??""),s.mcp=String(i.mcp_url?.value??""))}catch(r){let i=r instanceof ee?r.reason:String(r);if(Eu(i))return{...s,status:"gone",detail:`Delete the leftover config when you're done with it: rm -r ${D(t)}`};s.detail=`Couldn't read its state: ${i}`}return s}var Nn=t=>P(`Reading ${t.length} install${t.length===1?"":"s"}`,()=>Promise.all(t.map(Um)));async function Ye(t,e,n,s={}){if(t)return Cn(t);let r=it();if(!r.length)return Cn(void 0);await te({terraformOnly:!0});let i=await Nn(r);if(!i.filter(a=>n.includes(a.status)).length)throw new Error(`None of your installs can be used for this:
240
+ ${i.map(a=>` ${a.project}: ${Xs[a.status].text}`).join(`
241
+ `)}`);return i.length===1?i[0].dir:oe(e,i.map(a=>{let c=Xs[a.status],l=n.includes(a.status);return{label:a.project,value:a.dir,disabled:!l,hint:`${a.region} ${c.mark} ${c.text}${!l&&s[a.status]?`: ${s[a.status]}`:""}`}}))}p();import{cpSync as Mu,existsSync as Ku,mkdtempSync as zm,readFileSync as tr,rmSync as Du,writeFileSync as nr}from"node:fs";import{tmpdir as Hm}from"node:os";import{join as Ce}from"node:path";p();import{cpSync as Gm,existsSync as Fm,mkdirSync as Wm,rmSync as Ym}from"node:fs";import{join as wo,relative as Vm}from"node:path";import{fileURLToPath as Jm}from"node:url";var W=typeof w>"u"?null:w,Lu=process.env.KURIKO_REGISTRY_HOST||"registry.kuriko.dev",ae={upstream:`https://${Lu}`,host:Lu,owner:"usekuriko",username:"kuriko"},$e="kuriko-release-token",yo=W?Jm(new URL("./module",import.meta.url)):wo(H,"infra/terraform/gcp"),er=".kuriko/module";function xu(t){if(!W)return Vm(t,yo);let e=wo(t,er);if(Ym(e,{recursive:!0,force:!0}),Wm(e,{recursive:!0}),Gm(yo,e,{recursive:!0,filter:n=>!/[/\\]\.terraform([/\\]|$)/.test(n)}),!Fm(wo(e,"main.tf")))throw new Error(`The Terraform module wasn't found in this package (${yo}).`);return`./${er}`}var ot=t=>/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(t);function qu(t,e){let n=i=>{let[o,a]=i.split("-",2);return{nums:o.split(".").map(Number),pre:a??null}},s=n(t),r=n(e);for(let i=0;i<3;i++)if(s.nums[i]!==r.nums[i])return s.nums[i]-r.nums[i];return s.pre===r.pre?0:s.pre===null?1:r.pre===null||s.pre<r.pre?-1:1}var Ve="kuriko.json";function pe(t,e){nr(Ce(t,Ve),JSON.stringify(e,null,2)+`
242
+ `)}function It(t){try{return JSON.parse(tr(Ce(t,Ve),"utf8"))}catch{throw new Error(`${t} has no ${Ve}, so it wasn't made by kuriko install. Upgrade it by hand (terraform apply).`)}}var bo=null,Tn=t=>bo=t;function Bu(t,e){if(!e.releaseUsername)return null;let n=/^release_token_version\s*=\s*"([^"]+)"/m.exec(tr(Ce(t,"terraform.tfvars"),"utf8"))?.[1];return n?{upstream:ae.upstream,owner:ae.owner,username:e.releaseUsername,tokenSecret:$e,tokenVersion:n}:null}async function sr(t){await P("Setting up deploy events",async()=>{await Ys(t.project,["pubsub.googleapis.com"]),await uo(t.project,"pubsub.googleapis.com")})}function Pt(t,e,n){nr(Ce(t,"terraform.tfvars"),Vl(e,n,bo))}function rr(t,e){nr(Ce(t,"main.tf"),Yl(e,xu(t),`${e.project}-tfstate`,bo,!!W))}function Uu(t){try{return/^version_tag\s*=\s*"([^"]+)"/m.exec(tr(Ce(t,"terraform.tfvars"),"utf8"))?.[1]??null}catch{return null}}async function at(t,e){try{return(await L("terraform",["state","list"],{cwd:t})).split(`
243
+ `).includes(e)}catch{return!1}}async function ir(t){if(W)return W.version;let e=(await L("git",["rev-parse","--short","HEAD"],{cwd:H})).trim();if(!(await L("git",["status","--porcelain"],{cwd:H})).trim())return e;if(!t)throw new Error("The Kuriko checkout has uncommitted changes, so its version isn't a commit. Commit them, or pass --allow-dirty.");return`${e}-dirty-${Date.now().toString(36)}`}async function Gu(t,e){let n=s=>s.replace(/-dirty-.*$/,"");try{return(await L("git",["log","--oneline","--no-decorate",`${n(t)}..${n(e)}`],{cwd:H})).split(`
244
+ `).filter(Boolean)}catch{return[]}}async function ko(t,e,n){let s=`.kuriko-${e}.plan`;await L("terraform",["plan","-input=false",...(n??[]).map(o=>`-target=${o}`),`-out=${s}`],{cwd:t});let r=await Q("terraform",["show","-json",s],{cwd:t}),i=zl(r);if(i.length)throw new Error(`This would delete or replace existing resources, which Kuriko never does on its own:
245
245
  ${i.map(o=>` ${o}`).join(`
246
246
  `)}
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:
247
+ Nothing was changed.`);return{file:s,plan:r}}async function or(t,e,n){let{file:s,plan:r}=await ko(t,e,n);Ms(r).length&&await L("terraform",["apply","-input=false",s],{cwd:t})}async function ar(t,e,n){for(let s=1;;s++)try{return await or(t,e,n)}catch(r){if(!(r instanceof ee&&Wl(r.stderr))||s>=8)throw r;await new Promise(i=>setTimeout(i,2e4))}}async function cr(t,e,n,s){let r=await P(`${s}, in the cloud`,()=>Nt(t.project,t.region,e,n));if(r.code!==0)throw new Error(`${s} failed in the cloud:
248
248
  ${r.logs.slice(-10).map(i=>` ${i}`).join(`
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)}" {
249
+ `)}`);N(s)}var Qm=[["gateway","apps/gateway/Dockerfile",null],["web","apps/web/Dockerfile",null],["web-migrate","apps/web/Dockerfile","migrate"]];async function lr(t,e,n){await L("gcloud",["auth","configure-docker",`${t}-docker.pkg.dev`,"--quiet"]);for(let[s,r,i]of Qm){let o=`${e}/${s}:${n}`;if(await pu(o)){N(`${s} (already pushed)`);continue}await P(`Building and pushing ${s}`,()=>L("docker",["buildx","build","--platform","linux/amd64","-f",r,...i?["--target",i]:[],"-t",o,"--push","."],{cwd:H})),N(s)}}async function ur(t,e){let n=o=>P("Checking access to Kuriko's images",()=>bu(ae,ae.username,o,"gateway",e)),s=await vn(t.project,$e),r=!1;if(s&&t.releaseUsername===ae.username){let o=await n(await wu(t.project,$e));if(o==="ok")r=!0;else{if(o==="missing")throw new Error(`Kuriko ${e} isn't published on ${ae.host} yet. Use an earlier CLI version, or ask your Kuriko contact.`);if(o==="denied")x("This install's access key no longer works: Kuriko has revoked it. Paste the new key Kuriko gave you.");else throw new Error(`Couldn't reach ${ae.host} to check this install's access key. Check your connection and run this again.`)}}else s&&t.releaseUsername&&x(`Kuriko's images now come from ${ae.host}, which takes an access key instead of the registry token this install has.`);if(r)N(`Kuriko's images ${e}: access checked`);else for(Ee("Kuriko access key",["Kuriko's images are private. This install pulls them with an access key that Kuriko gives you,",`one per install. It looks like ${_("kuriko_")} followed by 64 letters and digits.`,"",`It goes straight into this project's Secret Manager (${$e}), where only Artifact`,"Registry can read it. It never goes into a file or the installs repo.","Don't have one? Ask your Kuriko contact."]);;){let o=(await Gs(`
250
+ Access key (hidden as you type or paste):`)).trim();if(!o)continue;if(!/^kuriko_[0-9a-f]{64}$/.test(o)){x("That isn't an access key: they start with kuriko_ and have 64 letters and digits after it. Paste the whole key.");continue}let a=await n(o);if(a==="denied"){x("Kuriko doesn't recognise that key, or it has been revoked. Check you pasted the key for this install, or ask Kuriko for a new one.");continue}if(a==="missing")throw new Error(`The key works, but Kuriko ${e} isn't published on ${ae.host} yet. Use an earlier CLI version, or ask your Kuriko contact.`);if(a==="unreachable"){x(`Couldn't reach ${ae.host} to check the key. Check your connection and try again.`);continue}await P("Storing the access key",()=>Ct(t.project,$e,o)),t.releaseUsername=ae.username,N(`Access key works and is stored in Secret Manager (${$e})`);break}await P("Setting up Artifact Registry's service account",()=>uo(t.project,"artifactregistry.googleapis.com"));let i=await yu(t.project,$e);if(!i)throw new Error(`${$e} has no enabled version.`);return{upstream:ae.upstream,owner:ae.owner,username:t.releaseUsername,tokenSecret:$e,tokenVersion:i}}function Fu(t){let e=["main.tf","terraform.tfvars",Ve].map(i=>Ce(t,i)),n=e.map(i=>Ku(i)?tr(i):null),s=Ce(t,er),r=Ku(s)?zm(Ce(Hm(),"kuriko-module-")):null;return r&&Mu(s,r,{recursive:!0}),()=>{e.forEach((i,o)=>n[o]?nr(i,n[o]):Du(i,{force:!0})),Du(s,{recursive:!0,force:!0}),r&&Mu(r,s,{recursive:!0})}}p();var Zm=t=>`kuriko_reads_${t.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"")}`;function Wu(t,e){return`${t.map(s=>{let[r,i]=s.split(".");return`resource "google_bigquery_dataset_iam_member" "${Zm(s)}" {
251
251
  project = "${r}"
252
252
  dataset_id = "${i}"
253
253
  role = "roles/bigquery.dataViewer"
@@ -262,10 +262,10 @@ ${r.logs.slice(-10).map(i=>` ${i}`).join(`
262
262
  # access {
263
263
  # role = "READER"
264
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)
265
+ # }`}p();import{createPrivateKey as Yu,createPublicKey as Xm,generateKeyPairSync as ey}from"node:crypto";import{existsSync as ty,readFileSync as ny}from"node:fs";import{homedir as sy}from"node:os";var ry=/^[a-z][a-z0-9-]{1,30}$/,iy=/^[A-Za-z_][A-Za-z0-9_$]{0,254}$/,oy=/^[A-Za-z0-9][A-Za-z0-9_.-]{1,254}$/,ay=/^[A-Za-z0-9_]{1,1024}$/,$o="snowflake-kuriko-key";function So(t){let e=`bq-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}`.slice(0,31).replace(/-$/,"");return ry.test(e)?e:"bq-warehouse"}function Vu(t,e){if(!t||t.kind==="none")return"";if(t.kind==="bigquery"){let n=new Set;return t.datasets.map(s=>{let r=So(s);for(let i=2;n.has(r);i++)r=`${So(s).slice(0,28)}-${i}`;return n.add(r),` ${r}: # BigQuery: no credential; the dataset's owners grant Kuriko read access
266
+ name: ${s} (BigQuery)
267
267
  kind: bigquery
268
- dataset: ${n}${t.project!==e?`
268
+ dataset: ${s}${t.project!==e?`
269
269
  project: ${t.project}`:""}
270
270
  `}).join(`
271
271
  `)}return` snowflake: # Snowflake: signs in as ${t.user} with the key in Secret Manager
@@ -278,25 +278,25 @@ ${r.logs.slice(-10).map(i=>` ${i}`).join(`
278
278
  warehouse: ${t.warehouse}
279
279
  database: ${t.database}
280
280
  schema: ${t.schema}
281
- `}function Wu(t){return!t||t.kind==="none"?"":`#
281
+ `}function Ju(t){return!t||t.kind==="none"?"":`#
282
282
  # Your warehouse is connected above, but nobody can read it until a group is granted here, e.g.:
283
283
  #
284
284
  # - group: data@example.com
285
- # connector: ${t.kind==="bigquery"?$o(t.datasets[0]):"snowflake"}
285
+ # connector: ${t.kind==="bigquery"?So(t.datasets[0]):"snowflake"}
286
286
  # resources: ["*"] # every table, or name them: [orders, customers]
287
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
288
+ `}async function zu(t){M("Connecting a data warehouse (optional)"),k(A(" If your company's data is in a warehouse, Kuriko can connect it now. Nobody can read it until you")),k(A(" grant a group access in policy.yaml. Databases (Postgres) and APIs can be added there any time."));let e=await oe(`
289
+ Is your data in a warehouse?`,[{label:"BigQuery",value:"bigquery",hint:"Kuriko reads it with its own Google identity; no key needed"},{label:"Snowflake",value:"snowflake",hint:"Kuriko signs in with a key it keeps in Secret Manager"},{label:"No warehouse",value:"none",hint:"add data sources later in policy.yaml"}]);return e==="bigquery"?cy(t):e==="snowflake"?ly(t):{kind:"none"}}async function cy(t){for(;;){k(A(" Usually your data team's project, not the one Kuriko runs in."));let e=await V(" Which Google Cloud project is the warehouse in?");if(!/^[a-z][a-z0-9-]{4,28}[a-z0-9]$/.test(e)){x("That isn't a Google Cloud project ID (e.g. acme-data).");continue}let n=await P(`Looking for datasets in ${e}`,()=>Su(e)),s;if(n?.length)k(A(" Pick the datasets tools may reach. Kuriko doesn't change who can read them: at the end of the")),k(A(" install it prints the Terraform whoever manages them adds, to let Kuriko's gateway read just these.")),s=await Fs(`
290
+ Which datasets?`,n.map(r=>({label:r.id,value:r.id,hint:r.location})),()=>!1);else{x(n?`${e} has no datasets you can see.`:`Couldn't list ${e}'s datasets (BigQuery may be off there, or your account can't see them).`),s=(await V(" Dataset names, separated by commas (or Enter to skip):")).split(",").map(o=>o.trim()).filter(Boolean);let i=s.filter(o=>!ay.test(o));if(i.length){x(`${i.join(", ")} ${i.length===1?"isn't a dataset name":"aren't dataset names"} (letters, digits and _).`);continue}}if(!s.length){if(await z(" No datasets picked. Continue without a warehouse?",!0))return{kind:"none"};continue}return N(`BigQuery: ${s.map(r=>`${e}.${r}`).join(", ")}`),{kind:"bigquery",project:e,datasets:s}}}var On=async(t,e)=>{for(;;){let n=await V(t,e);if(iy.test(n))return n;x("Use letters, digits and _ (a name as you'd write it in Snowflake without quotes).")}};async function ly(t){let e;for(;e=(await V(" Snowflake account identifier (orgname-accountname, from Admin \u2192 Accounts):")).replace(/\.snowflakecomputing\.com.*$/,"").replace(/^https?:\/\//,""),!oy.test(e);)x("That doesn't look like an account identifier, e.g. acme-analytics.");let n=await On(" Database tools read:"),s=await On(" Schema:","PUBLIC"),r=await On(" Warehouse queries run on:","COMPUTE_WH"),i=await On(" User Kuriko signs in as:","KURIKO_READER"),o=await On(" Role it reads with:","KURIKO_READ"),a=await oe(`
291
+ Kuriko signs in to Snowflake with a key pair. Which key?`,[{label:"Make a new key now",value:"new",hint:"recommended: the private key goes straight into Secret Manager"},{label:"Use a key file I already have",value:"file",hint:"an unencrypted .p8 file"}]),c;if(a==="new")c=ey("rsa",{modulusLength:2048}).privateKey.export({type:"pkcs8",format:"pem"}).toString();else for(;;){let h=(await V(" Path to the private key file:")).replace(/^~(?=\/)/,sy());if(!ty(h)){x(`There's no file at ${h}.`);continue}c=ny(h,"utf8");try{Yu({key:c,format:"pem"});break}catch{x("That isn't an unencrypted private key. Make one without a passphrase: openssl pkcs8 -topk8 -nocrypt")}}await P("Storing the key in Secret Manager",()=>Ct(t.project,$o,c)),N(`Key stored as ${$o} ${A("(only Kuriko's gateway will be able to read it)")}`);let l=Xm(Yu(c)).export({type:"spki",format:"pem"}).toString().replace(/-----[A-Z ]+-----|\s/g,"");return Ee("Set up Kuriko's user in Snowflake (as an ACCOUNTADMIN, in a worksheet)",["Run this once. It makes a role that can only read this schema, and a user that signs in with Kuriko's key.","",...uy({user:i,role:o,warehouse:r,database:n,schema:s,publicKey:l}).map(h=>` ${_(h)}`),"",a==="file"?"If the user already has this key, the ALTER USER line changes nothing.":"The key above is the public half; the private half is only in Secret Manager."]),await V(" Press Enter when you've run it."),N(`Snowflake: ${e}, ${n}.${s} as ${i}`),{kind:"snowflake",account:e,user:i,warehouse:r,database:n,schema:s,role:o,secret:$o}}function uy(t){let e=`${t.database}.${t.schema}`;return[`CREATE ROLE IF NOT EXISTS ${t.role};`,`GRANT USAGE ON WAREHOUSE ${t.warehouse} TO ROLE ${t.role};`,`GRANT USAGE ON DATABASE ${t.database} TO ROLE ${t.role};`,`GRANT USAGE ON SCHEMA ${e} TO ROLE ${t.role};`,`GRANT SELECT ON ALL TABLES IN SCHEMA ${e} TO ROLE ${t.role};`,`GRANT SELECT ON FUTURE TABLES IN SCHEMA ${e} TO ROLE ${t.role};`,`CREATE USER IF NOT EXISTS ${t.user} TYPE = SERVICE DEFAULT_ROLE = ${t.role} DEFAULT_WAREHOUSE = ${t.warehouse};`,`ALTER USER ${t.user} SET RSA_PUBLIC_KEY = '${t.publicKey}';`,`GRANT ROLE ${t.role} TO USER ${t.user};`]}var U="policy.yaml",vo="KURIKO_RESULT ";function fy(t){let e=Math.max(...me.map(o=>o.id.length)),n=o=>`# ${o.name}: ${o.where}${o.notYet?` (not yet: ${o.notYet})`:""}`,s=o=>t.includes(o.id)&&!o.notYet?` - ${o.id.padEnd(e+2)} ${n(o)}`:` # - ${o.id.padEnd(e)} ${n(o)}`,r=t.filter(o=>!me.some(a=>a.id===o)),i=[...me.map(s),...r.map(o=>` - ${o}`)];return`# AI apps people may connect to Kuriko with, to build and use tools. Which data someone sees never
292
292
  # depends on the app: their own access above applies either way. This only decides which apps may
293
293
  # act on their behalf. Remove the # to allow one; take an app out and it stops working within an hour.
294
294
  # Any other app that signs in with a client metadata document can be listed by that document's URL:
295
295
  # - https://example.com/oauth/client-metadata.json
296
- ${t.some(o=>!Rs(o)?.notYet)?"clients:":"clients: [] # nobody can connect from an AI app yet"}
296
+ ${t.some(o=>!qn(o)?.notYet)?"clients:":"clients: [] # nobody can connect from an AI app yet"}
297
297
  ${i.join(`
298
298
  `)}
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,
299
+ `}function Zu(t,e=""){let n=Vu(t.warehouse,t.project);return`# Who can do what in Kuriko (${t.project}). This file is the source of truth: change it here,
300
300
  # then run kuriko policy apply (it shows the changes and asks first).
301
301
  # Credentials never go in this file. They live in Secret Manager; a connector only names its secret.
302
302
 
@@ -331,24 +331,8 @@ ${e}# Data sources tools can use. Credentials stay in Secret Manager under any n
331
331
  # secret: warehouse-readonly
332
332
  # schema: public
333
333
  #
334
- # notion: # Notion, one shared integration (share each database with it in Notion)
335
- # name: Notion
336
- # kind: notion
337
- # secret: notion-integration-token
338
- # resources:
339
- # interviews: 6643d20a-7cdb-4154-a1eb-7994499dd58b # name tools use: the database's data source ID
340
- #
341
- # notion-personal: # Notion, each person connects their own account once: tools see
342
- # name: Notion (yours) # exactly what that person can see in Notion
343
- # kind: notion
344
- # credentials: per-person
345
- # oauth_client_id: 1a2b3c4d-... # your Notion public integration
346
- # secret: notion-oauth-client-secret # its OAuth client secret
347
- # resources:
348
- # interviews: 6643d20a-7cdb-4154-a1eb-7994499dd58b
349
- #
350
- # hubspot: # Any JSON API, described here instead of coded (read-only). The
351
- # name: HubSpot # credential only ever goes to base_url.
334
+ # hubspot: # Any JSON API, described here instead of coded. The credential
335
+ # name: HubSpot # only ever goes to base_url.
352
336
  # kind: api
353
337
  # base_url: https://api.hubapi.com
354
338
  # secret: hubspot-private-app-token
@@ -358,6 +342,7 @@ ${e}# Data sources tools can use. Credentials stay in Secret Manager under any n
358
342
  # path: /crm/v3/objects/contacts?limit=100&properties=email,firstname,lastname
359
343
  # rows: results # where the list is in the answer
360
344
  # next: { cursor: paging.next.after, param: after } # or link, { url: ... }, { page: page }
345
+ # add: { path: /crm/v3/objects/contacts, body: { properties: $row } } # optional: lets tools add rows
361
346
  #
362
347
  # hubspot-personal: # The same, each person signing in with their own HubSpot account
363
348
  # name: HubSpot (yours)
@@ -372,17 +357,17 @@ ${e}# Data sources tools can use. Credentials stay in Secret Manager under any n
372
357
  # scopes: [crm.objects.contacts.read]
373
358
  # resources:
374
359
  # contacts: { path: /crm/v3/objects/contacts, rows: results, next: { cursor: paging.next.after, param: after } }
375
- ${s?`connectors:
376
- ${s}`:`connectors: {}
360
+ ${n?`connectors:
361
+ ${n}`:`connectors: {}
377
362
  `}
378
363
  # Who may use which data. group is a Google group email, or everyone. write includes read.
379
364
  # A tool only ever gets what its viewer is granted here AND what the tool declared it needs.
380
365
  # For a per-person source, this says who may use it at all; the source decides what each person sees.
381
366
  #
382
367
  # - group: everyone
383
- # connector: notion
384
- # resources: [interviews] # for a database or warehouse: table names, or ["*"] for every table
385
- # access: write
368
+ # connector: hubspot
369
+ # resources: [contacts] # for a database or warehouse: table names, or ["*"] for every table
370
+ # access: write # only on resources that take new rows (add)
386
371
  # mask: [] # fields that come back hidden
387
372
  #
388
373
  # rows limits a grant to some rows: every field must match, a list means any of these, and $me is
@@ -401,38 +386,38 @@ ${s}`:`connectors: {}
401
386
  # rows:
402
387
  # stage: [won, lost] # finance sees closed deals,
403
388
  # mask: [rep_email] # without who closed them
404
- ${Wu(t.warehouse)}access: []
389
+ ${Ju(t.warehouse)}access: []
405
390
 
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?`:
391
+ ${fy(t.clients??Ie)}`}function Ne(t,e){let n;try{n=(0,pr.parse)(t,{prettyErrors:!0,uniqueKeys:!0})}catch(s){throw s instanceof pr.YAMLParseError?new ct([`It isn't valid YAML: ${s.message.split(`
392
+ `)[0]}`]):s}return Vo(n,s=>s.startsWith("projects/")?s:`projects/${e}/secrets/${s}`)}var Ao={add:Ue("+"),change:rt("~"),remove:be("-")};function dy(t){for(let e of t)k(` ${Ao[e.op]} ${e.op==="remove"?be(Kn(e)):Kn(e)}`)}async function fr(t,e,n){let s=await P(e,()=>Nt(t.project,t.region,"kuriko-migrate",["scripts/admin.ts",...n])),r=s.logs.find(o=>o.startsWith(vo));if(s.code===0&&r)return JSON.parse(r.slice(vo.length));if(s.logs.some(o=>o.includes("Unknown task")))throw new Error(`${t.project} is on a Kuriko version without policy files. Upgrade it first: kuriko upgrade`);let i=s.logs.filter(o=>!o.startsWith(vo)).slice(-8);throw new Error(`${e} failed in the cloud${i.length?`:
408
393
  ${i.map(o=>` ${o}`).join(`
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:
394
+ `)}`:" (no logs yet; try again)"}`)}async function Xu(t,e){M("Checking this machine"),await ke(Fe(process.cwd(),e.dir)),await te();let n=await Ye(e.dir,"Which install's policy?",["installed"],{partial:"finish it with kuriko install"}),s=It(n);if(!await at(n,"module.kuriko.google_cloud_run_v2_job.migrate"))throw new Error(`${s.project} isn't fully installed yet. Finish it with kuriko install`);N(`Install ${_(s.project)} ${A(`(${D(n)})`)}`);let r=Co(n,U);if(!Eo(r))throw Qu(r,Zu(s)),new Error(`${s.project} had no ${U}, so one was started at ${D(r)} with just the two roles.
395
+ Add any data sources and access this install already has (the plan would remove them otherwise), then run this again.`);M(`Reading ${U}`);let i=Ne(_o(r,"utf8"),s.project),o=(b,v)=>`${b} ${v}${b===1?"":"s"}`;N(`${o(i.roles.length,"role rule")}, ${o(i.connectors.length,"data source")}, ${o(i.grants.length,"grant")}, ${o(i.clients.length,"AI app")}`),i.clients.length||x("clients is empty: nobody can connect to Kuriko from an AI app (Claude Code, Codex, \u2026).");let a=dr(i),c=[];if(await P("Checking the secrets it names exist",async()=>{for(let b of a)await An(b)||c.push(b)}),c.length){let[b,v]=c[0].split("/").filter((K,I)=>I%2===1);throw new Error(`Secret Manager has no ${c.map(K=>ze(K,s.project)).join(", ")} (or your account can't see ${c.length>1?"them":"it"}). Whoever manages credentials creates it, e.g.:
396
+ read -s TOKEN && printf '%s' "$TOKEN" | gcloud secrets create ${v} --project ${b} --data-file=- && unset TOKEN`)}a.length&&N(`Secrets exist: ${a.map(b=>ze(b,s.project)).join(", ")}`),M("What changes");let l=Buffer.from(JSON.stringify(i)).toString("base64"),h=await fr(s,"Comparing with the install, in the cloud",["policy-plan",l]);h.changes=h.changes.filter(b=>{if(b.kind!=="connector"||b.op!=="change")return!0;let v=h.connectors.find(q=>q.id===b.id),K=i.connectors.find(q=>q.id===b.id);if(!v||!K)return!0;let I=q=>br({roles:[],grants:[],clients:[],connectors:[q]}).connectors[0],R=Jo(I(v),I(K));return R[0]==="(settings differ only in form)"?!1:(b.summary=`${K.name}: ${R.join("; ")}`,!0)});let u={roles:[],grants:[],clients:[],connectors:h.connectors},f=await P("Checking which secrets the gateway can read",()=>ef(s,u,i)),d=await P("Checking which BigQuery datasets the gateway can read",()=>tf(s,u,i));h.lastApply?k(A(` Last applied ${new Date(h.lastApply.at).toLocaleString()} by ${h.lastApply.appliedBy}`)):k(A(" This would be the first apply. After it, access changes go through this file; admin tools in Claude point here."));let m=!h.changes.length&&!f.allow.length&&!f.disallow.length;if(m&&(N(`${s.project} already matches ${U}.`),t==="plan"||h.lastApply))return;dy(h.changes);for(let b of f.allow)k(` ${Ao.add} the gateway can read secret ${ze(b,s.project)}`);for(let b of f.disallow)k(` ${Ao.remove} ${be(`the gateway can no longer read secret ${ze(b,s.project)}`)}`);let g=i.connectors.filter(b=>b.mode==="delegated");if(g.length){let b=(await Ge(s.project))?.number;if(b){let v=st(s,b).mcp.replace(/\/mcp$/,"");for(let K of g)k(A(` ${K.id}: set the OAuth redirect URI to ${v}/connect/callback; people connect at ${st(s,b).web}/connect/${K.id}`))}}let y=h.changes.filter(b=>b.op==="remove").length+f.disallow.length,S=h.changes.filter(b=>b.op==="remove"&&(b.kind==="role"||b.kind==="grant")).length,C=h.changes.filter(b=>b.op==="remove"&&b.kind==="connector").length;S&&x(`${S} role${S===1?" or grant is":"s or grants are"} removed: people lose that access on their next request.`),C&&x(`${C} data source${C===1?" is":"s are"} removed: tools using ${C===1?"it":"them"} stop getting its data, and everyone's own connections to ${C===1?"it":"them"} are deleted.`);let O=h.changes.filter(b=>b.kind==="client"&&b.op==="remove");if(O.length&&x(`${O.map(b=>Lt(b.client)).join(", ")} can't sign anyone in any more, and ${O.length===1?"its":"their"} current sessions stop within an hour. People's access is unchanged in the apps that remain.`),f.disallow.length&&x(`Kuriko gives up ${f.disallow.length===1?"a secret":"secrets"} the file no longer names. Nobody loses access; the secret${f.disallow.length===1?" itself is":"s themselves are"} kept.`),nf(s,d),t==="plan"){k(`
397
+ ${A("Plan only: nothing was changed. Apply with: kuriko policy apply")}`);return}if(!e.yes&&!await z(`
398
+ Apply ${m?`${U} (no changes; records it as the source of truth)`:"these changes"}?`,!y)){k("Nothing was changed.");return}await sf(s,f);let $=await Et(),T=await fr(s,"Applying, in the cloud",["policy-apply",l,$,h.hash]);await hy(s,f);let j=T.changes.length+f.allow.length+f.disallow.length;N(`${s.project} matches ${U} (${j} change${j===1?"":"s"}, recorded in the audit log as ${$})`),f.allow.length&&k(A(" New secret access can take a minute or two to reach Google's servers.")),await We([r],`Policy for ${s.project}: ${T.changes.length?T.changes.map(Kn).slice(0,3).join("; ")+(T.changes.length>3?"; \u2026":""):"first apply"}`)}var dr=t=>[...new Set(t.connectors.flatMap(e=>e.secretRef?[e.secretRef]:[]))].sort(),No=t=>`kuriko-gateway@${t.project}.iam.gserviceaccount.com`,jt=t=>`serviceAccount:${No(t)}`,Hu=(t,e)=>[...new Set(t.connectors.filter(n=>n.kind==="bigquery").map(n=>`${n.config.project??e}.${n.config.dataset}`))].sort(),py=t=>t.split(".");async function ef(t,e,n){let s=dr(n),r=[];for(let o of s)await En(o,jt(t))||r.push(o);let i=[];for(let o of dr(e))o.startsWith("projects/")&&!s.includes(o)&&await An(o)&&await En(o,jt(t))&&i.push(o);return{allow:r,disallow:i}}async function tf(t,e,n){let s=Hu(n,t.project),r={waiting:[],unknown:[],unused:Hu(e,t.project).filter(i=>!s.includes(i))};for(let i of s){let o=await vu(...py(i),No(t));if(o==="missing")throw new Error(`BigQuery has no dataset ${i} (or your account can't see it). Check the dataset in ${U}.`);o==="not-readable"&&r.waiting.push(i),o==="unknown"&&r.unknown.push(i)}return r}function nf(t,e){let n=[...e.waiting,...e.unknown];e.waiting.length&&x(`Kuriko can't read ${e.waiting.join(", ")} yet. Tools get "no access yet" from ${e.waiting.length===1?"it":"them"} until it's granted.`),e.unknown.length&&x(`Couldn't check who can read ${e.unknown.join(", ")} (your account can't see ${e.unknown.length===1?"its":"their"} access). If reads fail, it needs this grant.`),n.length&&(k(A(` Whoever manages ${n.length===1?"that dataset":"those datasets"} adds this to their Terraform (Kuriko never changes data it doesn't own):
399
+ `)),k(Wu(n,No(t)).split(`
400
+ `).map(s=>` ${s}`).join(`
401
+ `)),k("")),e.unused.length&&k(A(` No longer named here, so their grant to Kuriko can be removed: ${e.unused.join(", ")}`))}async function sf(t,e){e.allow.length&&await P("Letting the gateway read the new secrets",async()=>{for(let n of e.allow)await po(n,jt(t))})}async function hy(t,e){e.disallow.length&&await P("Taking away the gateway's access to secrets no longer used",async()=>{for(let n of e.disallow)await ku(n,jt(t))})}async function rf(t,e){let n=Co(e,U);if(!Eo(n))return[];let s=dr(Ne(_o(n,"utf8"),t.project)),r=[];for(let i of s)await An(i)&&!await En(i,jt(t))&&(await po(i,jt(t)),r.push(i));return r}async function of(t,e,n=""){let s=Co(e,U);Eo(s)||Qu(s,Zu(t,n));let r=Ne(_o(s,"utf8"),t.project),i=Buffer.from(JSON.stringify(r)).toString("base64"),o=await fr(t,"Reading the install's access, in the cloud",["policy-plan",i]);if(o.lastApply)return N(`Access comes from ${U} (change it with kuriko policy apply)`);let a={roles:[],grants:[],clients:[],connectors:o.connectors};await sf(t,await P("Checking which secrets the gateway can read",()=>ef(t,a,r)));let c=await P("Checking which BigQuery datasets the gateway can read",()=>tf(t,a,r));await fr(t,`Applying ${U}, in the cloud`,["policy-apply",i,await Et(),o.hash]),N(`Roles for your two groups${r.connectors.length?`, and ${r.connectors.map(l=>l.name).join(", ")}`:""}, from ${U}`),nf(t,c)}var Te="module.kuriko",wy=[`${Te}.google_sql_database_instance.kuriko`,`${Te}.google_sql_database.kuriko`,`${Te}.google_sql_user.kuriko`,`${Te}.google_cloud_run_v2_service.web`,`${Te}.google_cloud_run_v2_service.gateway`,`${Te}.google_cloud_run_v2_job.migrate`],by=[`${Te}.google_kms_crypto_key.user_tokens`,`${Te}.google_kms_key_ring.kuriko`],ky=new Set(["deletion_protection","deletion_policy"]);function $y(t){let e=Tu(t).filter(u=>u.address.startsWith(`${Te}.`)),n=e.find(u=>u.type==="google_project"&&u.mode==="data")?.values.project_id;if(typeof n!="string")throw new Error("This install has no Kuriko resources in its state (already destroyed, or never installed).");let s=e.filter(u=>u.mode==="managed"),r=u=>s.filter(f=>f.type===u),i=(u,f)=>String(u.values[f]??""),o=i(r("google_cloud_run_v2_service")[0]??r("google_artifact_registry_repository")[0]??{values:{}},"location"),a=[];for(let u of r("google_sql_database_instance"))a.push(`Cloud SQL instance ${_(i(u,"name"))} with all its data and backups: every user, tool, grant and audit record`);for(let u of r("google_cloud_run_v2_service"))a.push(`Cloud Run service ${i(u,"name")}`);for(let u of r("google_cloud_run_v2_job"))a.push(`Cloud Run job ${i(u,"name")}`);for(let u of r("google_secret_manager_secret"))a.push(`Secret ${i(u,"secret_id")} (generated by Kuriko)`);for(let u of r("google_service_account"))a.push(`Service account ${i(u,"email")}`);for(let u of r("google_artifact_registry_repository"))a.push(`Image repository ${i(u,"name")} and every image in it`);s.some(u=>u.type.endsWith("_iam_member"))&&a.push("Every IAM grant Kuriko made");let c=s.filter(u=>by.includes(u.address)).map(u=>u.address),l=r("google_kms_crypto_key").map(u=>`${i(u,"key_ring").split("/").pop()}/${i(u,"name")}`),h=e.find(u=>u.type==="google_secret_manager_secret"&&u.mode==="data");return{project:n,region:o,deletes:a,release:c,keys:l,idpSecret:h?i(h,"secret_id"):null}}function Sy(t){let e=[];for(let n of t.resource_changes??[]){let s=n.change.actions;if(s.length===1&&(s[0]==="no-op"||s[0]==="read"))continue;if(s.length!==1||s[0]!=="update"){e.push(`${n.address} would be ${s.join("/")}`);continue}let r=n.change.before??{},i=n.change.after??{},c=[...new Set([...Object.keys(r),...Object.keys(i),...Object.keys(n.change.after_unknown??{})])].filter(l=>n.change.after_unknown?.[l]===!0||JSON.stringify(r[l]??null)!==JSON.stringify(i[l]??null)).filter(l=>!ky.has(l));c.length&&e.push(`${n.address} would also change ${c.join(", ")}`)}return e}async function af(t){M("Checking this machine");for(let[d,m]of[["terraform","runs the install's Terraform"],["gcloud","finds what Kuriko created outside Terraform"]])if(!await He(d))throw new Error(`${d} isn't installed (${m}).`);await te(),await ke(Fe(process.cwd(),t.dir));let e=await Ye(t.dir,"Which install should be destroyed?",["installed","partial"],{empty:"nothing left to destroy",unknown:"can't read its state"}),n=(d,m=!1)=>L("terraform",d,{cwd:e,inherit:m});if(!Cu(e))throw new Error(`${e}/main.tf must pass deletion protection through to the module, so destroy can turn it off:
417
402
  variable "deletion_protection" { type = bool, default = true }
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:
403
+ and in module "kuriko": deletion_protection = var.deletion_protection`);N(`Install at ${D(e)}`),M("Reading the install");let s=$y(await Q("terraform",["show","-json"],{cwd:e})),r=["--project",s.project,"--format=json"],i=(await Q("gcloud",["run","services","list","--region",s.region,...r])).filter(d=>d.metadata.labels?.["kuriko-tool"]).map(d=>d.metadata.name),o=yy(e,U),a=gy(o)?[...new Set(Ne(my(o,"utf8"),s.project).connectors.flatMap(d=>d.secretRef?[ze(d.secretRef,s.project)]:[]))]:[],c=Nu(e);k(`
404
+ ${_(`Destroying Kuriko in ${s.project} (${s.region}) deletes, permanently:`)}`);for(let d of i)k(` ${be("\u2717")} Tool ${d} (Cloud Run service)`);for(let d of s.deletes)k(` ${be("\u2717")} ${d}`);k(`
405
+ ${_("It keeps:")}`);let l=[...s.keys.map(d=>`KMS key ${d}. GCP never deletes keys; it costs cents a month and a reinstall here reuses it.`),...s.idpSecret?[`Your IdP client secret ${s.idpSecret}`]:[],...a.map(d=>`Your connector credential ${d}`),...c?[`Terraform state in ${c}`]:[],"The project itself and its enabled APIs"];for(let d of l)k(` ${A("\u2022")} ${d}`);if(t.dryRun){k(`
406
+ ${A("Dry run: nothing was changed.")}`);return}if((t.confirm??await V(`
407
+ Type the project id (${s.project}) to destroy this install: `))!==s.project){k("That doesn't match. Nothing was changed.");return}M("Turning off deletion protection");let u=".kuriko-unlock.plan";await n(["plan","-input=false","-var","deletion_protection=false",...wy.map(d=>`-target=${d}`),`-out=${u}`]);let f=Sy(JSON.parse(await n(["show","-json",u])));if(f.length)throw new Error(`The install's config doesn't match what's deployed, so turning off protection would change more than that:
423
408
  ${f.map(d=>` ${d}`).join(`
424
409
  `)}
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}
410
+ Apply the config first (or fix it), then run destroy again.`);if(await n(["apply","-input=false",u],!0),N("Deletion protection is off"),i.length){M(`Deleting ${i.length} tool${i.length===1?"":"s"}`);for(let d of i)await L("gcloud",["run","services","delete",d,"--region",s.region,"--project",s.project,"--quiet"]),N(d)}s.release.length&&(M("Keeping the KMS key out of the destroy"),await n(["state","rm",...s.release]),N("Terraform no longer manages the key; it stays in the project")),M("Destroying everything else (Cloud SQL takes a few minutes)"),await n(["destroy","-input=false","-auto-approve","-var","deletion_protection=false"],!0),k(`
411
+ ${_(`Kuriko is gone from ${s.project}.`)} Still there, by design:`);for(let d of l)k(` ${A("\u2022")} ${d}`);k(`
412
+ ${_("Outside Google Cloud")} (yours to remove if you're done with Kuriko):`),k(` ${A("\u2022")} The OAuth client for Kuriko's sign-in, and the Groups Reader role assignment for the deleted kuriko-web account`),k(` ${A("\u2022")} Your kuriko-admins / kuriko-builders groups`),k(`
413
+ To remove everything at once: ${_(`gcloud projects delete ${s.project}`)}`),await We([e],`Destroy ${s.project}`,{remove:!0})}p();import{existsSync as In,mkdirSync as qy,readFileSync as mf,writeFileSync as My}from"node:fs";import{basename as Ky,join as Je}from"node:path";p();import{existsSync as vy,readFileSync as Ay}from"node:fs";import{join as Ey}from"node:path";var _y=40,Cy=t=>t.endsWith(".guest.google")||/^(abuse|postmaster)@/.test(t);async function To(t){let e=await _t().catch(()=>[]),n=(e.find(r=>r.name===t.domain)??e[0])?.customerId;if(!n)return null;let s=await Vs(t.project,n).catch(()=>null);return s&&s.filter(r=>!Cy(r.email))}function cf(t,e){let n=t.filter(a=>a.email!==e.adminsGroup&&a.email!==e.buildersGroup),s=`# Groups in ${e.domain} when this file was made (kuriko groups lists them now).
414
+ # Name one in roles or access to give its members something; groups not named here get nothing.`;if(!n.length)return`${s}
430
415
  # (none besides the two above)
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}
416
+ `;let r=n.slice(0,_y),i=Math.max(...r.map(a=>a.email.length)),o=r.map(a=>`# ${a.name&&a.name.toLowerCase()!==a.email.split("@")[0]?`${a.email.padEnd(i)} ${a.name}`:a.email}`);return n.length>r.length&&o.push(`# \u2026 and ${n.length-r.length} more`),`${s}
432
417
  ${o.join(`
433
418
  `)}
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
419
+ `}function Ny(t,e){let n=new Map,s=Ey(t,U);if(!vy(s))return n;let r=Ne(Ay(s,"utf8"),e),i=(o,a)=>n.set(o,[...n.get(o)??[],a]);for(let o of r.roles)i(o.group,o.role);for(let o of r.grants)i(o.group,`${o.access} ${o.connector}`);return n}async function lf(t){M("Checking this machine"),await ke(Fe(process.cwd(),t.dir)),await te();let e=await Ye(t.dir,"Which install's groups?",["installed","partial"]),n=It(e);N(`Install ${_(n.project)} ${A(`(${D(e)})`)}`),M(`Google Groups in ${n.domain}`);let s=await P("Reading your Workspace's groups",()=>To(n));if(!s){x("Couldn't list your Workspace's groups: your account may not be allowed to. A Workspace admin can, or find them at admin.google.com \u2192 Directory \u2192 Groups.");return}let r=t.search?.toLowerCase(),i=r?s.filter(l=>`${l.email} ${l.name} ${l.description}`.toLowerCase().includes(r)):s,o=Ny(e,n.project),a=Math.max(10,...i.map(l=>l.email.length));for(let l of i){let h=o.get(l.email);k(` ${l.email.padEnd(a)} ${l.name&&l.name.toLowerCase()!==l.email.split("@")[0]?l.name:""}${h?` ${Ue(`in ${U}: ${h.join(", ")}`)}`:""}`)}N(r?`${i.length} of ${s.length} groups match "${t.search}"`:`${s.length} group${s.length===1?"":"s"}`);let c=[...o.keys()].filter(l=>l!=="*"&&l.includes("@")&&!s.some(h=>h.email===l));for(let l of c)x(`${U} names ${Mt(l)}, which isn't a group in ${n.domain} (a typo, or deleted?). Its rules apply to nobody.`);k(A(`
420
+ Copy an email into ${U} (roles or access), then: kuriko policy apply`))}p();import{existsSync as ff,readdirSync as jy}from"node:fs";import{homedir as Ry}from"node:os";import{basename as Ly,dirname as pf,join as Po,resolve as Oe}from"node:path";p();import{existsSync as Ty,mkdirSync as Oy,writeFileSync as Oo}from"node:fs";import{join as hr,resolve as Iy}from"node:path";var Py=`# Kuriko installs
436
421
 
437
422
  One folder per Kuriko install, named after its cloud project, made and changed by the \`kuriko\` CLI.
438
423
  Each holds the install's answers (\`kuriko.json\`) and the Terraform config generated from them. No
@@ -448,14 +433,14 @@ kuriko upgrade # move one to the Kuriko version you have checked out
448
433
  \`\`\`
449
434
 
450
435
  Clone it next to your Kuriko checkout, or run \`kuriko\` from inside it.
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/
436
+ `;async function Io(t){Oy(t,{recursive:!0}),Oo(hr(t,Ot),JSON.stringify({kuriko:"installs",version:1},null,2)+`
437
+ `),Oo(hr(t,".gitignore"),`.terraform/
453
438
  .kuriko-*.plan
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(`
439
+ `),Ty(hr(t,"README.md"))||Oo(hr(t,"README.md"),Py);try{return await L("git",["-C",t,"rev-parse","--git-dir"]),{isRepo:!0}}catch{return{isRepo:!1}}}async function uf(t="."){let e=Iy(t);if(ne(e)===e){N(`${D(e)} is already an installs repo`);return}let{isRepo:s}=await Io(e);N(`${D(e)} is now an installs repo`),k(`
455
440
  Share it through git: whoever can clone it can see your installs (changing one also needs
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")}
441
+ permissions on its cloud project). ${s?"Commit these files and push.":`Make it a git repo: ${_(`git -C ${D(e)} init`)}, then add a private remote.`}`)}async function df(t){try{return(await L("git",["-C",t,"rev-parse","--show-toplevel"])).trim()}catch{return null}}function xy(t,e,n=H){if(e&&Oe(e)!==Oe(n))return{path:Po(e,"kuriko"),inRepo:!0};let s=e?pf(Oe(n)):Oe(t);return{path:Po(s,"kuriko-installs"),inRepo:!1}}async function hf(t=process.cwd()){M("Where Kuriko keeps its config"),k(" Each install is a folder of plain files: its answers, the Terraform that runs it, and policy.yaml"),k(" (who can use which data). No secrets. Keep it in git so changes are reviewed and nothing is lost.");let e=xy(t,await df(t));for(k(""),k(` ${_("If your team has a Terraform repo, put it there")} (e.g. infra/kuriko): Kuriko's config is then`),k(" reviewed in pull requests, versioned and applied like the rest of your infrastructure."),k(" Otherwise, a folder of its own that you make a private git repo."),e.inRepo&&k(A(`
442
+ You're in ${D(pf(e.path))}, so it's suggested there.`));;){let n=(await V(`
443
+ Folder:`,D(e.path))).replace(/^~(?=\/|$)/,Ry()),s=Oe(t,n);if(Oe(s).startsWith(Oe(H)+"/")||Oe(s)===Oe(H)){x("That's inside the Kuriko checkout. Pick a folder outside it.");continue}if(ff(s)&&!ff(Po(s,Ot))&&jy(s).length){x(`${D(s)} isn't empty. Pick a new folder (Kuriko makes it), or an empty one.`);continue}let{isRepo:r}=await Io(s);return N(`Config goes in ${D(s)}${r?` ${A(`(in the git repo ${Ly(await df(s)??s)})`)}`:""}`),k(A(` Run kuriko from inside it later (or set KURIKO_INSTALLS=${s}), so it finds your installs.`)),s}}async function yf(t){k(`${_("Kuriko install")}
459
444
 
460
445
  This puts Kuriko in your own cloud. Everything runs there, under your control: your people sign
461
446
  in with the accounts they already have, and credentials stay in your own secret manager.
@@ -463,48 +448,48 @@ in with the accounts they already have, and credentials stay in your own secret
463
448
  First a few questions; nothing is created until you've seen the plan and said yes. Then it takes
464
449
  about 30 minutes, mostly waiting for the database. A few steps happen in your providers' admin
465
450
  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}.
451
+ it picks up where it stopped.`);let e=ne()??await hf();await ke(e);let n=t.dir?Cn(t.dir):await Wy(),s=n&&In(Je(n,Ve))?JSON.parse(mf(Je(n,Ve),"utf8")):null;s||(k(""),await oe("Where should Kuriko run?",[{label:"Google Cloud",value:"gcp",hint:"in a project of yours"},{label:"AWS",value:"aws",hint:"coming soon",disabled:!0},{label:"Azure",value:"azure",hint:"coming soon",disabled:!0},{label:"Managed by Kuriko",value:"managed",hint:"coming soon: we run it for you",disabled:!0}]),await oe("Where do your people sign in?",[{label:"Google Workspace",value:"google-workspace"},{label:"Okta",value:"okta",hint:"coming soon",disabled:!0},{label:"Microsoft Entra ID",value:"entra",hint:"coming soon",disabled:!0},{label:"Another OIDC or SAML provider",value:"other",hint:"coming soon",disabled:!0}])),M("Checking this machine");for(let[I,R,q]of[["gcloud","Google Cloud's CLI: https://cloud.google.com/sdk/docs/install","--version"],["terraform","creates the cloud resources: https://developer.hashicorp.com/terraform/install","-version"]])if(!await He(I,q))throw new Error(`${I} isn't installed (${R}).`);if(!W){if(!await He("git","--version"))throw new Error("git isn't installed (it identifies the Kuriko version).");try{await L("docker",["info","--format","{{.ServerVersion}}"])}catch{throw new Error("Docker isn't running. Start Docker Desktop (it builds Kuriko's images), then run this again.")}}let r=await Et();if(!r)throw new Error("gcloud isn't signed in. Run: gcloud auth login");let i=r.split("@")[1]??"";if(/^(gmail|googlemail)\.com$/.test(i))throw new Error(`gcloud is signed in as ${r}. Sign in with your Google Workspace admin account instead: gcloud auth login`);await te(),N(`Signed in to Google Cloud as ${r}`);let o;if(s){M(`Continuing the install in ${s.project}`);let I=await Ge(s.project);if(!I||I.state!=="ACTIVE")throw new Error(`Project ${s.project} isn't available (deleted, or your account can't see it).`);o=I.number,N(`Project ${s.project} ${A(`(${n})`)}`)}else{M("Your Google Cloud project"),k(" Kuriko should have a project to itself, so its permissions don't mix with anything else.");let I=await oe("New project or existing?",[{label:"Create a new project",value:!0,hint:"recommended"},{label:"Use an existing, empty project",value:!1}]),R="",q=null;if(I){let se=await P("Finding your organization",()=>_t());if(!se.length)throw new Error(`${r} can't see any Google Cloud organization. Projects for Kuriko should live in your Workspace's organization.`);q=await co("Organization:",se.map(he=>({label:he.name,value:he,hint:he.id}))),R=await gr("Project ID (can't be changed later):",`kuriko-${Math.floor(1e3+Math.random()*9e3)}`,eo,"6\u201330 characters, starting with a letter: lowercase letters, digits and hyphens.")}else for(;R=await V("Project ID:"),!await P("Looking it up",()=>Ge(R));)k(` Can't find ${R}, or ${r} can't see it.`);let F=null;if(I||!await P("Checking billing",()=>iu(R))){let se=await P("Finding billing accounts",()=>su());if(!se.length)throw new Error("No open billing account. Create one at https://console.cloud.google.com/billing, then run this again.");F=await co("Billing account:",se.map(yr=>({label:yr.name,value:yr,hint:yr.id})));let he=await P("Checking the billing account has room",()=>au(F.id));if(he&&he.length>=5&&(x(`${F.name} already has ${he.length} projects linked (${he.join(", ")}). New billing accounts are often limited to 5.`),k(A(" If linking fails, unlink a project you don't use (gcloud billing projects unlink <project>), or ask Google")),k(A(" for more: https://support.google.com/code/contact/billing_quota_increase")),!await z(" Try anyway?",!1))){k("Nothing was created.");return}}let ue=await Fy();M("The plan");let Se=(se,he)=>k(` ${A(se.padEnd(10))}${he}`);if(Se("Runs in",`Google Cloud \xB7 ${I?`new project ${_(R)}${q?` in ${q.name}`:""}`:`existing project ${_(R)}`} \xB7 ${ue}`),F&&Se("Billing",`${F.name} ${A(F.id)}`),Se("Sign-in",`Google Workspace \xB7 people at ${_(i)}`),Se("Admins",`kuriko-admins@${i}`),Se("Builders",`kuriko-builders@${i}`),Se("Cost","about $10\u201315 a month, almost all of it the database; the rest scales to zero when idle"),k(""),!await z("Start?",!0)){k("Nothing was created.");return}if(I){for(;;)try{await P(`Creating project ${R}`,()=>ru(R,q.id));break}catch(se){if(!(se instanceof ee&&/already (in use|exists)/i.test(se.stderr)))throw se;k(` ${R} is taken (project IDs are unique across all of Google Cloud).`),R=await gr("Another project ID:",void 0,eo,"6\u201330 characters, starting with a letter: lowercase letters, digits and hyphens.")}N(`Created project ${R}`)}if(F){try{await P("Linking billing",()=>ou(R,F.id))}catch(se){throw cu(se)?new Error(`${F.name} is at Google's limit of linked projects, so billing couldn't be linked to ${R}.
467
452
  Free a slot (gcloud billing projects unlink <a project you don't use>) or ask Google for more:
468
453
  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.")}
454
+ Then run kuriko install again and choose "Use an existing, empty project": ${R}${I?" (already created, so no new project is made)":""}.`):se}N("Billing linked")}o=(await Ge(R)).number,s={host:"gcp",sso:"google-workspace",project:R,region:ue,domain:i,adminEmail:r,adminsGroup:`kuriko-admins@${i}`,buildersGroup:`kuriko-builders@${i}`,dbInstanceName:""},n=Je(e,R),qy(n,{recursive:!0}),pe(n,s)}let a=n,c=st(s,o);M("Turning on the Google Cloud services Kuriko uses"),await P("Enabling APIs",()=>Ys(s.project,Ml)),await sr(s),N("Cloud Run, Cloud SQL, Secret Manager, KMS, Artifact Registry, Cloud Build, Pub/Sub, IAM, Cloud Identity"),M("Somewhere to keep Kuriko's Terraform state");let l=`${s.project}-tfstate`,h=await P("Creating the state bucket",()=>lu(l,s.project,s.region));N(`gs://${l} ${A(`(${h}; versioned, private)`)}`);let u=await uu(s.project);s.dbInstanceName||(s.dbInstanceName=Ul(u.map(I=>I.name)),pe(a,s));let f=await ir(t.allowDirty);W&&(M(`Kuriko ${f}`),Tn(await ur(s,f)),pe(a,s)),rr(a,s),await P("Preparing Terraform",()=>L("terraform",["init","-input=false"],{cwd:a}));let d={},m=()=>My(Je(a,"imports.tf"),Jl(s,d));await at(a,"module.kuriko.google_kms_key_ring.kuriko")||(Object.assign(d,await fu(s.project,s.region,wn.ring,wn.key)),d.ring&&N("Found a KMS key from an earlier install; this one will reuse it"));let g=(await L("terraform",["state","list"],{cwd:a}).catch(()=>"")).split(`
455
+ `),y=Object.keys(kn).filter(I=>!g.includes(`module.kuriko.google_service_account.${I}`));if(y.length){let I=await P("Looking for service accounts from an earlier install",()=>du(s.project,y.map(R=>kn[R])));d.accounts=y.filter(R=>I.includes(kn[R])),d.accounts.length&&N(`Found ${I.join(", ")} from an earlier install; this one takes ${I.length===1?"it":"them"} over`)}m(),N(`Install config in ${a}`),M("Kuriko's service accounts and image registry"),Pt(a,s,f),await P("Creating service accounts and the image registry",()=>ar(a,"bootstrap",Kl)),N("kuriko-web, kuriko-gateway and kuriko-tools service accounts; image registry"),M("Kuriko's database");let S={started:Date.now(),state:"creating",note:""},C=Promise.resolve();if(await at(a,qs))S.state="ready",N(`Database ${s.dbInstanceName} ${A("(already created)")}`);else{let I=u.find(R=>R.name===s.dbInstanceName&&R.kuriko);if(I)d.sqlInstance=I.name,m(),N(`Found database ${I.name} from an earlier run; picking it up`);else if(k(" Cloud SQL takes 10\u201315 minutes to create, so it starts now and carries on while you do the next steps."),k(" It's most of Kuriko's cost: about $10\u201315 a month. The rest scales to zero when nobody's using it."),!await z(" Start creating it?",!0))throw new Error("Stopped before creating the database. Run install again to continue.");C=Uy(a,s,f,S).then(()=>S.state="ready",R=>(S.state="failed",R)),ao(()=>S.state==="creating"?`database: ${S.note||"creating"} (${Ds(S.started)})`:S.state==="ready"?"database: ready":"database: failed"),N("Started; it'll be ready in about 10\u201315 minutes")}for(W||(M(`Kuriko's images (version ${f})`),k(A(" Built from this checkout (development). Released versions pull Kuriko's published images instead.")),await lr(s.region,c.registry,f)),Ee("Let people sign in with Google (an OAuth app, in Google Cloud)",["Kuriko signs people in with their Google accounts. Google needs an OAuth app in this project for that.","",`1. Open ${_(c.newClient)}`,` If Google first asks you to set up the app (${_("Get started")}): App name ${_("Kuriko")}, support email: you,`,` Audience: ${_("Internal")} (only people in ${s.domain} can sign in), contact email: you. Agree, ${_("Create")},`," then open the link again. If it goes straight to a form for a new client, skip this.","",`2. Application type: ${_("Web application")}. Name: ${_("Kuriko")}.`,` Under Authorized redirect URIs, ${_("Add URI")} and paste exactly:`,` ${_(c.redirect)}`,` Then ${_("Create")}. A dialog shows the Client ID and Client secret: keep it open.`]);;){let I=await gr(`
456
+ Client ID:`,s.idpClientId,Bl,"It looks like 1234567890-abc123.apps.googleusercontent.com."),R=I!==s.idpClientId;if(s.idpClientId=I,pe(a,s),await vn(s.project,bn)&&!R&&!await z(` A client secret is already in Secret Manager (${bn}). Replace it?`)){N("Keeping the stored client secret");break}k(A(` The secret goes straight into Secret Manager as ${bn}. It isn't shown or saved anywhere else.`));let F=await Gs(" Client secret (hidden as you type or paste):");if(!F)continue;let ue=await P("Checking them with Google",()=>hu(I,F,c.redirect));if(ue===!1){x("Google doesn't accept that client ID and secret together. Copy both again from the same client.");continue}await P("Storing the secret",()=>Ct(s.project,bn,F)),N(`Client secret stored in Secret Manager${ue?", and Google accepts it":""}`);break}s.groupsChosen||((await Promise.all([s.adminsGroup,s.buildersGroup].map(R=>Js(s.project,R,s.adminEmail).catch(()=>null)))).every(R=>R?.exists)||await Yy(s),s.groupsChosen=!0,pe(a,s)),s.clients||(s.clients=await Dy(a),pe(a,s)),!s.warehouse&&!In(Je(a,U))&&(s.warehouse=await zu(s),pe(a,s)),Ee("Decide who runs Kuriko (Google Groups)",["Kuriko gives roles by Google Group, so access is managed where you already manage people:",` ${_(s.adminsGroup)} Admin: manages who can use which data, sees the audit log.`,` ${_(s.buildersGroup)} Builder: builds tools.`,` Everyone else in ${s.domain} can sign in and use tools shared with them. Groups inside these groups count too.`]);let O=()=>P("Looking for the groups",()=>Promise.all([Js(s.project,s.adminsGroup,s.adminEmail),Js(s.project,s.buildersGroup,s.adminEmail)])),[$,T]=await O(),j=[!$.exists&&s.adminsGroup,!T.exists&&s.buildersGroup].filter(I=>!!I),b=!1;if(j.length&&await z(`
457
+ Create ${j.join(" and ")} now${$.exists?"":`, with you in ${s.adminsGroup}`}?`,!0)){let I=await _t(),R=(I.find(q=>q.name===s.domain)??I[0])?.customerId;if(!R)throw new Error("Couldn't find your Workspace's customer ID to create the groups. Create them in the Admin console instead.");for(let[q,F,ue,Se]of[[s.adminsGroup,"Kuriko admins","Kuriko Admin role: manages who can use which data, sees the audit log.",!0],[s.buildersGroup,"Kuriko builders","Kuriko Builder role: builds tools on Kuriko.",!1]])j.includes(q)&&(await P(`Creating ${q}`,()=>mu(s.project,{customerId:R,email:q,name:F,description:ue,owner:Se})),N(`Created ${q}${Se?" (you're its owner)":""}`));if(b=!0,!T.exists){let q=(await V(` Who should build? Their ${s.domain} emails, comma-separated (Enter to add people later):`)).split(/[\s,]+/).filter(Boolean);for(let F of q){if(!xs(F)){x(`Skipped ${F}: not an email address.`);continue}try{await P(`Adding ${F}`,()=>lo(s.project,s.buildersGroup,F)),N(`Added ${F} to ${s.buildersGroup}`)}catch(ue){x(`Couldn't add ${F}: ${ue instanceof Error?ue.message:String(ue)}`)}}}}else j.length&&Ee("Create the groups in the Google Admin console",[`${_("https://admin.google.com/ac/groups")} \u2192 ${_("Create group")}, once for each group email above.`,`Under access settings choose ${_("Restricted")} (only members see the member list) and no external members.`,`Add yourself to ${s.adminsGroup}, and the people who'll build to ${s.buildersGroup}.`]);for(let I=0;;I++){if(I&&([$,T]=await O()),$.exists&&T.exists&&$.isMember){N(`${s.adminsGroup} (you're in it) and ${s.buildersGroup} are ready`);break}if(b&&I<6){await new Promise(q=>setTimeout(q,3e3));continue}if($.exists&&!$.isMember&&await z(` You're not in ${s.adminsGroup}, so you wouldn't be a Kuriko admin. Add you?`,!0)){await P("Adding you",()=>lo(s.project,s.adminsGroup,s.adminEmail)),b=!0,I=0;continue}let R=[!$.exists&&s.adminsGroup,!T.exists&&s.buildersGroup].filter(Boolean);R.length?x(`Not found yet: ${R.join(", ")} (or ${s.adminEmail} can't see ${R.length>1?"them":"it"}).`):x(`${s.adminEmail} isn't in ${s.adminsGroup}. Add yourself, or you won't be an admin.`),await V(" Press Enter to check again.")}Ee("Let Kuriko see group membership (Groups Reader role, in the Google Admin console)",["Google doesn't tell apps which groups someone is in when they sign in, so Kuriko asks Google","directly. It needs the Groups Reader admin role for that: it can read group membership and nothing else.","",`1. Open ${_("https://admin.google.com/ac/roles")} and click ${_("Groups Reader")}.`,`2. Open ${_("Admins")} (or "Assign role"), then ${_("Assign service accounts")}.`,`3. Paste ${_(c.webServiceAccount)}, click ${_("Add")}, then ${_("Assign role")}.`,"","It can take a few minutes to take effect. Kuriko checks it at the end."]),await V(" Press Enter when you've assigned it."),M("Creating Kuriko");let v=await P("Waiting for the database",()=>C);if(ao(null),S.state==="failed")throw v;N(`Database ${s.dbInstanceName} ${A(`(${Ds(S.started)} in all)`)}`),Pt(a,s,f),await P("Creating Kuriko's secrets, key and services",()=>ar(a,"install",null));for(let I of Object.keys(d))delete d[I];m(),N("Kuriko's secrets, key and services"),M("Setting up Kuriko's database"),await cr(s,"kuriko-migrate",void 0,"Database schema");let K="";if(!In(Je(a,U))){let I=await P("Reading your Workspace's groups for policy.yaml",()=>To(s));I&&(K=cf(I,s))}for(await of(s,a,K),M("Checking Kuriko can see group membership");;){let I=await P("Checking as kuriko-web, in the cloud",()=>Nt(s.project,s.region,"kuriko-migrate",["scripts/admin.ts","check-groups",s.adminEmail,s.adminsGroup]));if(I.code===0){N(`Kuriko sees you in ${s.adminsGroup}`);break}for(let R of I.logs.slice(-3))k(A(` ${R.trim()}`));I.code===3?x(`Kuriko can read groups, but doesn't see ${s.adminEmail} in ${s.adminsGroup}.`):x(`Kuriko can't read group membership yet. Check ${c.webServiceAccount} has Groups Reader (above); it can take a few minutes.`),await V(" Press Enter to check again.")}k(`
458
+ ${_("Kuriko is installed.")}
474
459
 
475
- Sign in: ${C(c.web)}
476
- MCP server: ${C(c.mcp)}
477
- ${xy(n.clients??Ie,c.mcp)}
460
+ Sign in: ${_(c.web)}
461
+ MCP server: ${_(c.mcp)}
462
+ ${By(s.clients??Ie,c.mcp)}
478
463
 
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};
464
+ To let someone build: add them to ${s.buildersGroup} and send them the MCP server address.
465
+ ${s.warehouse&&s.warehouse.kind!=="none"?`Your ${s.warehouse.kind==="bigquery"?"BigQuery datasets are":"Snowflake database is"} connected; nobody can read ${s.warehouse.kind==="bigquery"&&s.warehouse.datasets.length>1?"them":"it"} until you grant a group
466
+ access in ${s.project}/${U} (there's an example in it).
467
+ `:""}Data sources, who may use them, and which AI apps can connect go in ${s.project}/${U};
483
468
  apply with kuriko policy apply.
484
469
  Their first sign-in is their setup; they never need Google Cloud access.
485
470
 
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"?`
471
+ Install config: ${D(a)} ${A("(no secrets in it; state is in gs://"+l+")")}`),await We([a],`Install ${s.project} (Kuriko ${f})`)}async function Dy(t){M("Choosing which AI apps can connect");let e=Je(t,U);if(In(e)){let{clients:s}=Ne(mf(e,"utf8"),Ky(t));return N(`From ${U}: ${s.length?s.join(", "):"none"}`),s}k(A(" People connect Kuriko to the AI app they build in. Data access is the same whichever app they use;")),k(A(` this only decides which apps may act for them. Change it any time in ${U}.`));let n=await Fs(`
472
+ Which AI apps can people connect with?`,me.map(s=>({label:s.name,value:s.id,hint:s.notYet?"not yet":s.where,disabled:!!s.notYet})),s=>Ie.includes(s));return n.length?N(`AI apps: ${n.map(s=>me.find(r=>r.id===s).name).join(", ")}`):x(`Nobody will be able to connect from an AI app until you allow one in ${U}.`),n}function By(t,e){let n={"claude-code":`claude mcp add --transport http kuriko ${e} (then /mcp to sign in)`,claude:"Settings \u2192 Connectors \u2192 Add custom connector, with the MCP server address",codex:`codex mcp add kuriko --url ${e} (then codex mcp login kuriko)`,vscode:"Command Palette \u2192 MCP: Add Server \u2192 HTTP, with the MCP server address",cursor:"Settings \u2192 MCP \u2192 Add new MCP server, with the MCP server address",lovable:"Connectors \u2192 Add custom, with the MCP server address"},s=t.map(r=>` ${`${me.find(o=>o.id===r)?.name??r}:`.padEnd(14)}${n[r]??"add the MCP server address as a remote MCP server"}`);return s.length?s.join(`
473
+ `):` ${A(`No AI apps can connect yet: allow one in ${U}.`)}`}async function Uy(t,e,n,s){for(;;)try{await ar(t,"database",[qs]);return}catch(r){if(!(r instanceof ee&&Fl(r.stderr)))throw r;let i=Gl(e.dbInstanceName);s.note=`${e.dbInstanceName} was taken, creating ${i}`,e.dbInstanceName=i,pe(t,e),Pt(t,e,n)}}var Gy=[["europe-west2","London"],["europe-west1","Belgium"],["europe-west3","Frankfurt"],["us-central1","Iowa"],["us-east1","South Carolina"],["us-west1","Oregon"],["asia-southeast1","Singapore"],["australia-southeast1","Sydney"]];async function Fy(){return await oe("Region (where Kuriko and its data live):",[...Gy.map(([e,n])=>({label:e,value:e,hint:n})),{label:"Another region\u2026",value:""}])||gr("Region:",void 0,Dl,"Like europe-west2 or us-central1: https://cloud.google.com/run/docs/locations")}async function Wy(){let t=it().filter(n=>In(Je(n,Ve)));if(!t.length)return null;await te({terraformOnly:!0});let e=await Nn(t);return oe("Continue an install, or start a new one?",[{label:"Start a new install",value:null},...e.map(n=>{let s=Xs[n.status],r=n.status==="gone";return{label:`Continue ${n.project}`,value:n.dir,disabled:r,hint:`${n.region} ${s.mark} ${s.text}`}})])}async function gr(t,e,n,s){for(;;){let r=await V(t,e);if(n(r))return r;k(` ${s}`)}}async function Yy(t){M("Choosing who runs Kuriko");let e=await _t().catch(()=>[]),n=(e.find(r=>r.name===t.domain)??e[0])?.customerId,s=n?await P("Reading your Workspace's groups",()=>Vs(t.project,n)).catch(()=>null):null;s?N(`${s.length} group${s.length===1?"":"s"} in ${t.domain}`):x("Couldn't list your Workspace's groups (your account may not be allowed to). Type the group emails instead."),k(A(" Admins manage who can use which data and see the audit log. Builders make tools and deploy them into this project.")),k(A(" Everyone else who can sign in uses the tools shared with them. More groups can be given roles later, in policy.yaml.")),t.adminsGroup=await gf("admins",s,`kuriko-admins@${t.domain}`),t.buildersGroup=await gf("builders",s?.filter(r=>r.email!==t.adminsGroup)??null,`kuriko-builders@${t.domain}`),t.groupsChosen=!0,N(`Admins: ${_(t.adminsGroup)} Builders: ${_(t.buildersGroup)}`)}async function gf(t,e,n){let s=t==="admins"?`
489
474
  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}`)}
475
+ Which group can build tools?`,r=async()=>{for(;;){let l=(await V(e?" Group email, or part of its name:":" Group email:",e?void 0:n)).toLowerCase();if(!e){if(xs(l))return l;x(`${l} isn't an email address.`);continue}let h=e.find(f=>f.email===l);if(h)return h.email;let u=Ql(e,l);if(u.length===1&&await z(` ${u[0].email}${u[0].name?` (${u[0].name})`:""}?`,!0))return u[0].email;if(u.length>1&&u.length<=9){let f=await oe(" Which one?",[...u.map(d=>({label:d.email,value:d.email,hint:d.name})),{label:"None of these",value:""}]);if(f)return f}else if(u.length>9)x(`${u.length} groups match "${l}"; type more of it.`);else if(!u.length){if(xs(l)&&await z(` No group ${l} yet. Create it?`,!1))return l;x(`No group matches "${l}".`)}}};if(!e?.length)return r();let i=Hl(e,t),o={label:`Create ${n}`,value:n,hint:"(a new, empty group)"},a=[...i.length?[]:[o],...i.map(l=>({label:l.email,value:l.email,hint:l.name&&l.name.toLowerCase()!==l.email.split("@")[0]?l.name:void 0})),{label:"Another existing group\u2026",value:"?",hint:`(search all ${e.length})`},...i.length?[o]:[]],c=await oe(s,a);return c==="?"?r():c}p();async function wf(){if(!ne()){k(Zs);return}let t=it();if(!t.length){k(`No Kuriko installs yet. Start one with: ${_("kuriko install")}`);return}await te({terraformOnly:!0});let e=await Nn(t),n={installed:Ue("\u25CF installed"),partial:rt("\u25D0 partly installed: run install to continue, or destroy"),empty:A("\u25CB not installed (or destroyed)"),gone:A("\u25CB project deleted"),unknown:rt("? unknown")};for(let s of e)k(`
476
+ ${_(s.project)} ${A(s.region)} ${n[s.status]}`),s.web&&k(` web ${s.web}`),s.mcp&&k(` mcp ${s.mcp}`),s.detail&&k(s.status==="gone"?A(` ${s.detail}`):` ${rt("!")} ${s.detail}`),k(A(` dir ${D(s.dir)}`))}p();import{existsSync as Vy}from"node:fs";import{join as Jy}from"node:path";var zy="module.kuriko.google_cloud_run_v2_job.migrate",Hy={create:"+",update:"~",replace:"\xB1",delete:"-"};async function Qy(t,e){if(t==="unknown")return"forward";if(ot(t)&&ot(e)){let n=qu(t,e);return n===0?"same":n<0?"forward":"backward"}return!ot(t)&&!ot(e)?Ru(H,t,e):"switch"}async function bf(t){M("Checking this machine"),await ke(Fe(process.cwd(),t.dir));for(let m of["gcloud","terraform",...W?[]:["git"]])if(!await He(m,m==="terraform"?"-version":"--version"))throw new Error(`${m} isn't installed.`);if(await te(),!W&&!t.dryRun)try{await L("docker",["info","--format","{{.ServerVersion}}"])}catch{throw new Error("Docker isn't running. Start Docker Desktop (it builds Kuriko's images), then run this again.")}let e=await Ye(t.dir,"Which install should be upgraded?",["installed"],{partial:"finish it with kuriko install",empty:"nothing to upgrade",unknown:"can't read its state"}),n=It(e),s=await Ge(n.project);if(!s||s.state!=="ACTIVE")throw new Error(`Project ${n.project} isn't available (deleted, or your account can't see it).`);if(!await at(e,"module.kuriko.google_cloud_run_v2_service.web"))throw new Error(`${n.project} isn't fully installed yet. Finish it with kuriko install`);let r=st(n,s.number);N(`Install ${_(n.project)} ${A(`(${D(e)})`)}`),M("What changes");let i=Uu(e)??"unknown",o=await ir(t.allowDirty),a=await Qy(i,o);if(a==="backward")throw new Error(W?`${n.project} is on ${i}, newer than this CLI (${o}). Update the CLI first: npm i -g kuriko`:`${n.project} is on ${i}, which is newer than this Kuriko checkout (${o}). Pull the Kuriko repo first: git -C ${D(H)} pull`);if(a==="unknown")throw new Error(`${n.project} is on ${i}, which this Kuriko checkout doesn't have. Pull the Kuriko repo first: git -C ${D(H)} pull`);let c=Fu(e);W?(Tn(await ur(n,o)),pe(e,n)):Tn(Bu(e,n)),rr(e,n),Pt(e,n,o),await P("Preparing Terraform",()=>L("terraform",["init","-input=false"],{cwd:e}));let{plan:l}=await P("Working out the changes",()=>ko(e,"upgrade",null)),h=Ms(l);if(i===o&&!h.length){c(),N(`Already on ${o}. Nothing to do.`);return}k(` Version ${i===o?o:`${A(i)} \u2192 ${_(o)}`}`),a==="switch"&&x(ot(o)?`Moves from a development build to release ${o}.`:`Moves from release ${i} to a development build. Use this only for testing.`);let u=!W&&!ot(i)?await mo(H,i,o)??i:i,f=a==="forward"&&!W?await Gu(u,o):[];if(f.length){k(` ${f.length} commit${f.length===1?"":"s"}:`);for(let m of f.slice(0,12))k(A(` ${m}`));f.length>12&&k(A(` \u2026 and ${f.length-12} more`))}k(h.length?" Cloud":" Cloud no resource changes");for(let m of h)k(A(` ${Hy[m.action]} ${m.address}${Ks.has(`module.kuriko.${m.address}`)?" (old project-wide secret access; policy.yaml grants each secret instead)":""}`));if(k(A(" No data or service is deleted. The database is migrated first; the web app and gateway switch over after.")),t.dryRun){c(),k(`
477
+ ${A("Dry run: nothing was changed.")}`);return}if(!await z(`
478
+ Upgrade?`,!0).catch(m=>{throw c(),m})){c(),k("Nothing was changed.");return}if(W||(M(`Kuriko's images (version ${o})`),await lr(n.region,r.registry,o)),await sr(n),M("Migrating the database"),await P("Updating the migrate job",()=>or(e,"upgrade-migrate",[zy,...W?["module.kuriko.google_artifact_registry_repository.releases"]:[]])),await cr(n,"kuriko-migrate",void 0,"Database schema"),h.some(m=>Ks.has(`module.kuriko.${m.address}`))){Vy(Jy(e,U))||x(`No ${U}: the gateway won't be able to read data source secrets until one names them (kuriko policy apply).`);let m=await P("Giving the gateway the secrets policy.yaml names, one by one",()=>rf(n,e));N(m.length?`The gateway can read ${m.map(g=>g.split("/").pop()).join(", ")}`:"The gateway already reads the secrets policy.yaml names")}M("Switching to the new version"),await P("Updating the web app and gateway",()=>or(e,"upgrade",null)),N(`${n.project} is on ${_(o)}`),k(`
479
+ ${r.web}`),await We([e],`Upgrade ${n.project} to Kuriko ${o}${i!=="unknown"&&i!==o?` (from ${i})`:""}`)}var Pn={install:{usage:"install [--dir <install>] [--allow-dirty]",summary:"Put Kuriko in a Google Cloud project, for a company on Google Workspace",details:["Walks through every step, including the three done in Google's admin pages (an OAuth app,","two Google Groups, and the Groups Reader role), explaining each and checking it before moving on.","Takes about 30 minutes, mostly waiting for the database. Safe to re-run: it continues where it stopped.",""," --dir <install> Continue a specific install, by project ID (default: asks, if there are any)"," --allow-dirty Install from a checkout with uncommitted changes (images get a -dirty tag)"],run:t=>yf({dir:t.dir,allowDirty:t["allow-dirty"]})},list:{usage:"list",summary:"Show your installs, how far each got, and their URLs",details:["Reads each install's Terraform state, so it shows what's actually in the cloud."],run:()=>wf()},upgrade:{usage:"upgrade [--dir <install>] [--dry-run] [--allow-dirty]",summary:"Move an install to the version in this checkout",details:["Shows the version change, the commits in it and what changes in the cloud, then asks.","Builds and pushes the new images, migrates the database with the new version, and only then","switches the web app and gateway over. Never deletes anything; a plan that would is refused.",""," --dir <install> Which install, by project ID (default: asks, if there's more than one)"," --dry-run Show what would change, change nothing (no images built)"," --allow-dirty Upgrade to a checkout with uncommitted changes (images get a -dirty tag)"],run:t=>bf({dir:t.dir,allowDirty:t["allow-dirty"],dryRun:t["dry-run"]})},policy:{usage:"policy plan|apply [--dir <install>] [--yes]",summary:"Change who can do what: roles, data sources and access, from the install's policy.yaml",details:["Each install's access lives in policy.yaml next to its Terraform: which Google groups are admins and","builders, which data sources exist (naming their secrets, never holding them), and who may use what.","plan shows what applying the file would change; apply shows the same, asks, and makes the install match.","Runs inside the cloud; every change is in the audit log. Commit the file so the repo is the record.",""," --dir <install> Which install, by project ID (default: asks, if there's more than one)"," --yes Apply without asking (for CI)"],run:(t,e)=>{if(e[0]!=="plan"&&e[0]!=="apply")throw new Rt('Say "kuriko policy plan" or "kuriko policy apply".');return Xu(e[0],{dir:t.dir,yes:t.yes})}},groups:{usage:"groups [search] [--dir <install>]",summary:"List your Google Groups, to name in policy.yaml, and which ones it already uses",details:["Shows every group in the install's Google Workspace with its name, marks the ones policy.yaml gives a","role or access to, and warns about groups policy.yaml names that don't exist. Membership is never","copied into Kuriko: people's groups are read from Workspace each time they sign in.",""," search Only groups whose email, name or description contains this"," --dir <install> Which install, by project ID (default: asks, if there's more than one)"],run:(t,e)=>lf({dir:t.dir,search:e.join(" ")||void 0})},destroy:{usage:"destroy [--dir <install>] [--dry-run] [--confirm <project-id>]",summary:"Remove an install from its cloud project",details:["Shows what will be deleted (the database and everything in it, services, accounts) and what stays","(the KMS key, your own secrets, the state bucket, the project), then asks for the project ID.",""," --dir <install> Which install, by project ID (default: asks, if there's more than one)"," --dry-run Show what would happen, change nothing"," --confirm <project-id> Give the project ID up front instead of typing it"],run:t=>af({dir:t.dir,dryRun:t["dry-run"],confirm:t.confirm})},init:{usage:"init [folder]",summary:"Make a folder the installs repo you share with whoever runs Kuriko",details:["Installs (answers and Terraform config, no secrets) live in a git repo. Whoever can clone it sees","the installs; changing one also needs permissions on its cloud project. Commands find the repo","from inside it, from $KURIKO_INSTALLS, or as a kuriko-installs checkout next to the Kuriko one."],run:(t,e)=>uf(e[0])},help:{usage:"help [command]",summary:"Show this, or the details of one command",details:[],run:async(t,e)=>mr(e[0])}};function mr(t){if(t){let n=Pn[t];if(!n)throw new Rt(`No command "${t}".`);console.log(`${_(`kuriko ${n.usage}`)}
495
480
 
496
- ${s.summary}.${s.details.length?`
481
+ ${n.summary}.${n.details.length?`
497
482
 
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")}
483
+ ${n.details.join(`
484
+ `)}`:""}`);return}let e=Math.max(...Object.keys(Pn).map(n=>n.length));console.log(`${_("kuriko")} ${A("\xB7 runs Kuriko in your own cloud")}
500
485
 
501
- Usage: kuriko <command> [options] ${v(W?`version ${W.version}`:"development build, from a Kuriko checkout")}
486
+ Usage: kuriko <command> [options] ${A(W?`version ${W.version}`:"development build, from a Kuriko checkout")}
502
487
 
503
488
  Commands:
504
- ${Object.entries(Is).map(([s,n])=>` ${s.padEnd(e)} ${n.summary}`).join(`
489
+ ${Object.entries(Pn).map(([n,s])=>` ${n.padEnd(e)} ${s.summary}`).join(`
505
490
  `)}
506
491
 
507
- Run ${C("kuriko help <command>")} for a command's options.
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)}
492
+ Run ${_("kuriko help <command>")} for a command's options.
493
+ ${Xy()}`)}function Xy(){let t=ne();return t?`Installs repo: ${D(t)}`:"No installs repo yet: clone yours next to the Kuriko checkout, or run kuriko init <folder>."}var Rt=class extends Error{};try{let{positionals:t,values:e}=Zy({allowPositionals:!0,options:{dir:{type:"string"},"allow-dirty":{type:"boolean"},confirm:{type:"string"},"dry-run":{type:"boolean"},yes:{type:"boolean"},help:{type:"boolean",short:"h"},version:{type:"boolean",short:"v"}}}),[n,...s]=t;if(e.version)console.log(W?W.version:"development build");else if(!n)mr();else if(Pn[n])e.help?mr(n):await Pn[n].run(e,s);else throw new Rt(`No command "${n}".`)}catch(t){let e=t instanceof Error?t.message:String(t),n=/Unknown option '([^']+)'/.exec(e)?.[1],s=n?`No option ${n}.`:e,r=t.code;t instanceof Rt||typeof r=="string"&&r.startsWith("ERR_PARSE_ARGS")?(console.error(`${be("\u2717")} ${s}
494
+ `),mr(),process.exitCode=2):(console.error(`
495
+ ${be("\u2717")} ${s}`),process.exitCode=1)}